@NotNull
  public Change[] getSelectedChanges() {
    Set<Change> changes = new LinkedHashSet<Change>();

    final TreePath[] paths = getSelectionPaths();
    if (paths == null) {
      return new Change[0];
    }

    for (TreePath path : paths) {
      ChangesBrowserNode<?> node = (ChangesBrowserNode) path.getLastPathComponent();
      changes.addAll(node.getAllChangesUnder());
    }

    if (changes.isEmpty()) {
      final List<VirtualFile> selectedModifiedWithoutEditing = getSelectedModifiedWithoutEditing();
      if (selectedModifiedWithoutEditing != null && !selectedModifiedWithoutEditing.isEmpty()) {
        for (VirtualFile file : selectedModifiedWithoutEditing) {
          AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(file);
          if (vcs == null) continue;
          final VcsCurrentRevisionProxy before =
              VcsCurrentRevisionProxy.create(file, myProject, vcs.getKeyInstanceMethod());
          if (before != null) {
            ContentRevision afterRevision = new CurrentContentRevision(new FilePathImpl(file));
            changes.add(new Change(before, afterRevision, FileStatus.HIJACKED));
          }
        }
      }
    }

    return changes.toArray(new Change[changes.size()]);
  }
 @NotNull
 private static GlobalSearchScope forDirectory(
     @NotNull Project project, boolean withSubdirectories, @NotNull VirtualFile directory) {
   Set<VirtualFile> result = new LinkedHashSet<>();
   result.add(directory);
   addSourceDirectoriesFromLibraries(project, directory, result);
   VirtualFile[] array = result.toArray(new VirtualFile[result.size()]);
   return GlobalSearchScopesCore.directoriesScope(project, withSubdirectories, array);
 }
    @Override
    public void calcData(final DataKey key, final DataSink sink) {
      Node node = getSelectedNode();

      if (key == PlatformDataKeys.PROJECT) {
        sink.put(PlatformDataKeys.PROJECT, myProject);
      } else if (key == USAGE_VIEW_KEY) {
        sink.put(USAGE_VIEW_KEY, UsageViewImpl.this);
      } else if (key == PlatformDataKeys.NAVIGATABLE_ARRAY) {
        sink.put(PlatformDataKeys.NAVIGATABLE_ARRAY, getNavigatablesForNodes(getSelectedNodes()));
      } else if (key == PlatformDataKeys.EXPORTER_TO_TEXT_FILE) {
        sink.put(PlatformDataKeys.EXPORTER_TO_TEXT_FILE, myTextFileExporter);
      } else if (key == USAGES_KEY) {
        final Set<Usage> selectedUsages = getSelectedUsages();
        sink.put(
            USAGES_KEY,
            selectedUsages != null
                ? selectedUsages.toArray(new Usage[selectedUsages.size()])
                : null);
      } else if (key == USAGE_TARGETS_KEY) {
        sink.put(USAGE_TARGETS_KEY, getSelectedUsageTargets());
      } else if (key == PlatformDataKeys.VIRTUAL_FILE_ARRAY) {
        final Set<Usage> usages = getSelectedUsages();
        Usage[] ua = usages != null ? usages.toArray(new Usage[usages.size()]) : null;
        VirtualFile[] data = UsageDataUtil.provideVirtualFileArray(ua, getSelectedUsageTargets());
        sink.put(PlatformDataKeys.VIRTUAL_FILE_ARRAY, data);
      } else if (key == PlatformDataKeys.HELP_ID) {
        sink.put(PlatformDataKeys.HELP_ID, HELP_ID);
      } else if (key == PlatformDataKeys.COPY_PROVIDER) {
        sink.put(PlatformDataKeys.COPY_PROVIDER, this);
      } else if (node != null) {
        Object userObject = node.getUserObject();
        if (userObject instanceof TypeSafeDataProvider) {
          ((TypeSafeDataProvider) userObject).calcData(key, sink);
        } else if (userObject instanceof DataProvider) {
          DataProvider dataProvider = (DataProvider) userObject;
          Object data = dataProvider.getData(key.getName());
          if (data != null) {
            sink.put(key, data);
          }
        }
      }
    }
    public void actionPerformed(AnActionEvent e) {
      final TreePath[] paths = myTree.getSelectionPaths();
      if (paths == null) return;

      final Set<TreePath> pathsToRemove = new HashSet<TreePath>();
      for (TreePath path : paths) {
        if (removeFromModel(path)) {
          pathsToRemove.add(path);
        }
      }
      removePaths(pathsToRemove.toArray(new TreePath[pathsToRemove.size()]));
    }
    @Nullable
    private Object findClosestTo(PsiElement path, ArrayList<ObjectWithWeight> paths) {
      if (path == null || myInitialPsiElement == null) {
        return paths.get(0).node;
      }
      final Set<PsiElement> parents = getAllParents(myInitialPsiElement);
      ArrayList<ObjectWithWeight> cur = new ArrayList<ObjectWithWeight>();
      int max = -1;
      for (ObjectWithWeight p : paths) {
        final Object last = ((TreePath) p.node).getLastPathComponent();
        final List<PsiElement> elements = new ArrayList<PsiElement>();
        final Object object = ((DefaultMutableTreeNode) last).getUserObject();
        if (object instanceof FilteringTreeStructure.FilteringNode) {
          FilteringTreeStructure.FilteringNode node = (FilteringTreeStructure.FilteringNode) object;
          FilteringTreeStructure.FilteringNode candidate = node;

          while (node != null) {
            elements.add(getPsi(node));
            node = node.getParentNode();
          }
          final int size = ContainerUtil.intersection(parents, elements).size();
          if (size == elements.size() - 1
              && size == parents.size() - (myInitialNodeIsLeaf ? 1 : 0)
              && candidate.children().isEmpty()) {
            return p.node;
          }
          if (size > max) {
            max = size;
            cur.clear();
            cur.add(p);
          } else if (size == max) {
            cur.add(p);
          }
        }
      }

      Collections.sort(
          cur,
          new Comparator<ObjectWithWeight>() {
            @Override
            public int compare(ObjectWithWeight o1, ObjectWithWeight o2) {
              final int i = o1.compareWith(o2);
              return i != 0
                  ? i
                  : ((TreePath) o2.node).getPathCount() - ((TreePath) o1.node).getPathCount();
            }
          });
      return cur.isEmpty() ? null : cur.get(0).node;
    }
  private Change[] getLeadSelection() {
    final Set<Change> changes = new LinkedHashSet<Change>();

    final TreePath[] paths = getSelectionPaths();
    if (paths == null) return new Change[0];

    for (TreePath path : paths) {
      ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
      if (node instanceof ChangesBrowserChangeNode) {
        changes.add(((ChangesBrowserChangeNode) node).getUserObject());
      }
    }

    return changes.toArray(new Change[changes.size()]);
  }
  @NotNull
  private ChangeList[] getSelectedChangeLists() {
    Set<ChangeList> lists = new HashSet<ChangeList>();

    final TreePath[] paths = getSelectionPaths();
    if (paths == null) return new ChangeList[0];

    for (TreePath path : paths) {
      ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
      final Object userObject = node.getUserObject();
      if (userObject instanceof ChangeList) {
        lists.add((ChangeList) userObject);
      }
    }

    return lists.toArray(new ChangeList[lists.size()]);
  }
  @Nullable
  private UsageTarget[] getSelectedUsageTargets() {
    TreePath[] selectionPaths = myTree.getSelectionPaths();
    if (selectionPaths == null) return null;

    Set<UsageTarget> targets = new THashSet<UsageTarget>();
    for (TreePath selectionPath : selectionPaths) {
      Object lastPathComponent = selectionPath.getLastPathComponent();
      if (lastPathComponent instanceof UsageTargetNode) {
        UsageTargetNode usageTargetNode = (UsageTargetNode) lastPathComponent;
        UsageTarget target = usageTargetNode.getTarget();
        if (target != null && target.isValid()) {
          targets.add(target);
        }
      }
    }

    return targets.isEmpty() ? null : targets.toArray(new UsageTarget[targets.size()]);
  }
 private void rulesChanged() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   final ArrayList<UsageState> states = new ArrayList<UsageState>();
   captureUsagesExpandState(new TreePath(myTree.getModel().getRoot()), states);
   final List<Usage> allUsages = new ArrayList<Usage>(myUsageNodes.keySet());
   Collections.sort(allUsages, USAGE_COMPARATOR);
   final Set<Usage> excludedUsages = getExcludedUsages();
   reset();
   myBuilder.setGroupingRules(getActiveGroupingRules(myProject));
   myBuilder.setFilteringRules(getActiveFilteringRules(myProject));
   ApplicationManager.getApplication()
       .runReadAction(
           new Runnable() {
             @Override
             public void run() {
               for (Usage usage : allUsages) {
                 if (!usage.isValid()) {
                   continue;
                 }
                 if (usage instanceof MergeableUsage) {
                   ((MergeableUsage) usage).reset();
                 }
                 appendUsage(usage);
               }
             }
           });
   excludeUsages(excludedUsages.toArray(new Usage[excludedUsages.size()]));
   if (myCentralPanel != null) {
     setupCentralPanel();
   }
   SwingUtilities.invokeLater(
       new Runnable() {
         @Override
         public void run() {
           if (isDisposed) return;
           restoreUsageExpandState(states);
           updateImmediately();
         }
       });
 }
  @NotNull
  private JBPopup createUsagePopup(
      @NotNull final List<Usage> usages,
      @NotNull final UsageInfoToUsageConverter.TargetElementsDescriptor descriptor,
      @NotNull Set<UsageNode> visibleNodes,
      @NotNull final FindUsagesHandler handler,
      final Editor editor,
      @NotNull final RelativePoint popupPosition,
      final int maxUsages,
      @NotNull final UsageViewImpl usageView,
      @NotNull final FindUsagesOptions options,
      @NotNull final JTable table,
      @NotNull final UsageViewPresentation presentation,
      @NotNull final AsyncProcessIcon processIcon,
      boolean hadMoreSeparator) {
    table.setRowHeight(PlatformIcons.CLASS_ICON.getIconHeight() + 2);
    table.setShowGrid(false);
    table.setShowVerticalLines(false);
    table.setShowHorizontalLines(false);
    table.setTableHeader(null);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setIntercellSpacing(new Dimension(0, 0));

    PopupChooserBuilder builder = new PopupChooserBuilder(table);
    final String title = presentation.getTabText();
    if (title != null) {
      String result = getFullTitle(usages, title, hadMoreSeparator, visibleNodes.size() - 1, true);
      builder.setTitle(result);
      builder.setAdText(getSecondInvocationTitle(options, handler));
    }

    builder.setMovable(true).setResizable(true);
    builder.setItemChoosenCallback(
        new Runnable() {
          @Override
          public void run() {
            int[] selected = table.getSelectedRows();
            for (int i : selected) {
              Object value = table.getValueAt(i, 0);
              if (value instanceof UsageNode) {
                Usage usage = ((UsageNode) value).getUsage();
                if (usage == MORE_USAGES_SEPARATOR) {
                  appendMoreUsages(editor, popupPosition, handler, maxUsages);
                  return;
                }
                navigateAndHint(usage, null, handler, popupPosition, maxUsages, options);
              }
            }
          }
        });
    final JBPopup[] popup = new JBPopup[1];

    KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          showDialogAndFindUsages(handler, popupPosition, editor, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }
    shortcut = getShowUsagesShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          searchEverywhere(options, handler, editor, popupPosition, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }

    InplaceButton settingsButton =
        createSettingsButton(
            handler,
            popupPosition,
            editor,
            maxUsages,
            new Runnable() {
              @Override
              public void run() {
                popup[0].cancel();
              }
            });

    ActiveComponent spinningProgress =
        new ActiveComponent() {
          @Override
          public void setActive(boolean active) {}

          @Override
          public JComponent getComponent() {
            return processIcon;
          }
        };
    builder.setCommandButton(new CompositeActiveComponent(spinningProgress, settingsButton));

    DefaultActionGroup toolbar = new DefaultActionGroup();
    usageView.addFilteringActions(toolbar);

    toolbar.add(UsageGroupingRuleProviderImpl.createGroupByFileStructureAction(usageView));
    toolbar.add(
        new AnAction(
            "Open Find Usages Toolwindow",
            "Show all usages in a separate toolwindow",
            AllIcons.Toolwindows.ToolWindowFind) {
          {
            AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_USAGES);
            setShortcutSet(action.getShortcutSet());
          }

          @Override
          public void actionPerformed(AnActionEvent e) {
            hideHints();
            popup[0].cancel();
            FindUsagesManager findUsagesManager =
                ((FindManagerImpl) FindManager.getInstance(usageView.getProject()))
                    .getFindUsagesManager();

            findUsagesManager.findUsages(
                handler.getPrimaryElements(),
                handler.getSecondaryElements(),
                handler,
                options,
                FindSettings.getInstance().isSkipResultsWithOneUsage());
          }
        });

    ActionToolbar actionToolbar =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, toolbar, true);
    actionToolbar.setReservePlaceAutoPopupIcon(false);
    final JComponent toolBar = actionToolbar.getComponent();
    toolBar.setOpaque(false);
    builder.setSettingButton(toolBar);

    popup[0] = builder.createPopup();
    JComponent content = popup[0].getContent();

    myWidth =
        (int)
            (toolBar.getPreferredSize().getWidth()
                + new JLabel(
                        getFullTitle(
                            usages, title, hadMoreSeparator, visibleNodes.size() - 1, true))
                    .getPreferredSize()
                    .getWidth()
                + settingsButton.getPreferredSize().getWidth());
    myWidth = -1;
    for (AnAction action : toolbar.getChildren(null)) {
      action.unregisterCustomShortcutSet(usageView.getComponent());
      action.registerCustomShortcutSet(action.getShortcutSet(), content);
    }

    return popup[0];
  }
  public DependenciesPanel(
      Project project, final List<DependenciesBuilder> builders, final Set<PsiFile> excluded) {
    super(new BorderLayout());
    myBuilders = builders;
    myExcluded = excluded;
    final DependenciesBuilder main = myBuilders.get(0);
    myForward = !main.isBackward();
    myScopeOfInterest = main.getScopeOfInterest();
    myTransitiveBorder = main.getTransitiveBorder();
    myDependencies = new HashMap<PsiFile, Set<PsiFile>>();
    myIllegalDependencies = new HashMap<PsiFile, Map<DependencyRule, Set<PsiFile>>>();
    for (DependenciesBuilder builder : builders) {
      myDependencies.putAll(builder.getDependencies());
      myIllegalDependencies.putAll(builder.getIllegalDependencies());
    }
    exclude(excluded);
    myProject = project;
    myUsagesPanel = new DependenciesUsagesPanel(myProject, myBuilders);
    Disposer.register(this, myUsagesPanel);

    final Splitter treeSplitter = new Splitter();
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            treeSplitter.dispose();
          }
        });
    treeSplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myLeftTree));
    treeSplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myRightTree));

    final Splitter splitter = new Splitter(true);
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            splitter.dispose();
          }
        });
    splitter.setFirstComponent(treeSplitter);
    splitter.setSecondComponent(myUsagesPanel);
    add(splitter, BorderLayout.CENTER);
    add(createToolbar(), BorderLayout.NORTH);

    myRightTreeExpansionMonitor = PackageTreeExpansionMonitor.install(myRightTree, myProject);
    myLeftTreeExpansionMonitor = PackageTreeExpansionMonitor.install(myLeftTree, myProject);

    myRightTreeMarker =
        new Marker() {
          public boolean isMarked(VirtualFile file) {
            return myIllegalsInRightTree.contains(file);
          }
        };

    myLeftTreeMarker =
        new Marker() {
          public boolean isMarked(VirtualFile file) {
            return myIllegalDependencies.containsKey(file);
          }
        };

    updateLeftTreeModel();
    updateRightTreeModel();

    myLeftTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                updateRightTreeModel();
                final StringBuffer denyRules = new StringBuffer();
                final StringBuffer allowRules = new StringBuffer();
                final TreePath[] paths = myLeftTree.getSelectionPaths();
                if (paths == null) {
                  return;
                }
                for (TreePath path : paths) {
                  PackageDependenciesNode selectedNode =
                      (PackageDependenciesNode) path.getLastPathComponent();
                  traverseToLeaves(selectedNode, denyRules, allowRules);
                }
                if (denyRules.length() + allowRules.length() > 0) {
                  StatusBar.Info.set(
                      AnalysisScopeBundle.message(
                          "status.bar.rule.violation.message",
                          ((denyRules.length() == 0 || allowRules.length() == 0) ? 1 : 2),
                          (denyRules.length() > 0
                                  ? denyRules.toString() + (allowRules.length() > 0 ? "; " : "")
                                  : " ")
                              + (allowRules.length() > 0 ? allowRules.toString() : " ")),
                      myProject);
                } else {
                  StatusBar.Info.set(
                      AnalysisScopeBundle.message("status.bar.no.rule.violation.message"),
                      myProject);
                }
              }
            });

    myRightTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                SwingUtilities.invokeLater(
                    new Runnable() {
                      public void run() {
                        final Set<PsiFile> searchIn = getSelectedScope(myLeftTree);
                        final Set<PsiFile> searchFor = getSelectedScope(myRightTree);
                        if (searchIn.isEmpty() || searchFor.isEmpty()) {
                          myUsagesPanel.setToInitialPosition();
                          processDependencies(
                              searchIn,
                              searchFor,
                              new Processor<List<PsiFile>>() { // todo do not show too many usages
                                public boolean process(final List<PsiFile> path) {
                                  searchFor.add(path.get(1));
                                  return true;
                                }
                              });
                        } else {
                          myUsagesPanel.findUsages(searchIn, searchFor);
                        }
                      }
                    });
              }
            });

    initTree(myLeftTree, false);
    initTree(myRightTree, true);

    if (builders.size() == 1) {
      AnalysisScope scope = builders.get(0).getScope();
      if (scope.getScopeType() == AnalysisScope.FILE) {
        Set<PsiFile> oneFileSet = myDependencies.keySet();
        if (oneFileSet.size() == 1) {
          selectElementInLeftTree(oneFileSet.iterator().next());
          return;
        }
      }
    }
    TreeUtil.selectFirstNode(myLeftTree);
  }