@NotNull
  EditorWindow[] getOrderedWindows() {
    final List<EditorWindow> res = new ArrayList<EditorWindow>();

    // Collector for windows in tree ordering:
    class Inner {
      private void collect(final JPanel panel) {
        final Component comp = panel.getComponent(0);
        if (comp instanceof Splitter) {
          final Splitter splitter = (Splitter) comp;
          collect((JPanel) splitter.getFirstComponent());
          collect((JPanel) splitter.getSecondComponent());
        } else if (comp instanceof JPanel || comp instanceof JBTabs) {
          final EditorWindow window = findWindowWith(comp);
          if (window != null) {
            res.add(window);
          }
        }
      }
    }

    // get root component and traverse splitters tree:
    if (getComponentCount() != 0) {
      final Component comp = getComponent(0);
      LOG.assertTrue(comp instanceof JPanel);
      final JPanel panel = (JPanel) comp;
      if (panel.getComponentCount() != 0) {
        new Inner().collect(panel);
      }
    }

    LOG.assertTrue(res.size() == myWindows.size());
    return res.toArray(new EditorWindow[res.size()]);
  }
  private ActionCallback processHangByParent(Set<Object> elements) {
    if (elements.size() == 0) return new ActionCallback.Done();

    ActionCallback result = new ActionCallback(elements.size());
    for (Iterator<Object> iterator = elements.iterator(); iterator.hasNext(); ) {
      Object hangElement = iterator.next();
      if (!myAdjustmentCause2Adjustment.containsKey(hangElement)) {
        processHangByParent(hangElement).notify(result);
      } else {
        result.setDone();
      }
    }
    return result;
  }
 private void secondPass(IExtensionHelpers helpers) {
   publish("Second Pass...");
   publish(0);
   Set<Map<String, CorrelatedParam>> allStats = new HashSet<>();
   allStats.add(urlParameters);
   allStats.add(bodyParameters);
   allStats.add(cookieParameters);
   int x = 0;
   for (IHttpRequestResponse message : inScopeMessagesWithResponses) {
     publish(100 * x / inScopeMessagesWithResponses.size());
     x += 1;
     String responseString = helpers.bytesToString(message.getResponse());
     for (Map<String, CorrelatedParam> paramMap : allStats) {
       for (String paramName : paramMap.keySet()) {
         publish("Analyzing " + paramName + "...");
         for (CorrelatedParam param : paramMap.values()) {
           for (String value : param.getUniqueValues()) {
             if (responseString.contains(value)) {
               param.putSeenParam(value, message);
             }
           }
         }
       }
     }
   }
 }
    public GotoData(
        PsiElement source, PsiElement[] targets, List<AdditionalAction> additionalActions) {
      this.source = source;
      this.targets = targets;
      this.additionalActions = additionalActions;

      myNames = new HashSet<String>();
      for (PsiElement target : targets) {
        if (target instanceof PsiNamedElement) {
          myNames.add(((PsiNamedElement) target).getName());
          if (myNames.size() > 1) break;
        }
      }

      hasDifferentNames = myNames.size() > 1;
    }
  @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()]);
  }
  public boolean checkCanRemove(final List<? extends PackagingElementNode<?>> nodes) {
    Set<PackagingNodeSource> rootSources = new HashSet<PackagingNodeSource>();
    for (PackagingElementNode<?> node : nodes) {
      rootSources.addAll(getRootNodeSources(node.getNodeSources()));
    }

    if (!rootSources.isEmpty()) {
      final String message;
      if (rootSources.size() == 1) {
        final String name = rootSources.iterator().next().getPresentableName();
        message =
            "The selected node belongs to '"
                + name
                + "' element. Do you want to remove the whole '"
                + name
                + "' element from the artifact?";
      } else {
        message =
            "The selected node belongs to "
                + nodes.size()
                + " elements. Do you want to remove all these elements from the artifact?";
      }
      final int answer =
          Messages.showYesNoDialog(
              myArtifactsEditor.getMainComponent(), message, "Remove Elements", null);
      if (answer != Messages.YES) return false;
    }
    return true;
  }
 @Override
 @NotNull
 public Document[] getUncommittedDocuments() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   Document[] documents =
       myUncommittedDocuments.toArray(new Document[myUncommittedDocuments.size()]);
   return ArrayUtil.stripTrailingNulls(documents);
 }
 @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);
          }
        }
      }
    }
Esempio n. 10
0
  private ActionCallback processAjusted(
      final Map<Object, Condition> adjusted, final Set<Object> originallySelected) {
    final ActionCallback result = new ActionCallback();

    final Set<Object> allSelected = myUi.getSelectedElements();

    Set<Object> toSelect = new HashSet<Object>();
    for (Object each : adjusted.keySet()) {
      if (adjusted.get(each).value(each)) continue;

      for (final Object eachSelected : allSelected) {
        if (isParentOrSame(each, eachSelected)) continue;
        toSelect.add(each);
      }
      if (allSelected.size() == 0) {
        toSelect.add(each);
      }
    }

    final Object[] newSelection = ArrayUtil.toObjectArray(toSelect);

    if (newSelection.length > 0) {
      myUi._select(
          newSelection,
          new Runnable() {
            public void run() {
              final Set<Object> hangByParent = new HashSet<Object>();
              processUnsuccessfulSelections(
                  newSelection,
                  new Function<Object, Object>() {
                    public Object fun(final Object o) {
                      if (myUi.isInStructure(o) && !adjusted.get(o).value(o)) {
                        hangByParent.add(o);
                      } else {
                        addAdjustedSelection(o, adjusted.get(o), null);
                      }
                      return null;
                    }
                  },
                  originallySelected);

              processHangByParent(hangByParent).notify(result);
            }
          },
          false,
          true,
          true);
    } else {
      result.setDone();
    }

    return result;
  }
    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()]));
    }
  private ActionCallback processHangByParent(Set<Object> elements) {
    if (elements.isEmpty()) return new ActionCallback.Done();

    ActionCallback result = new ActionCallback(elements.size());
    for (Object hangElement : elements) {
      if (!myAdjustmentCause2Adjustment.containsKey(hangElement)) {
        processHangByParent(hangElement).notify(result);
      } else {
        result.setDone();
      }
    }
    return result;
  }
Esempio n. 13
0
  private void processUnsuccessfulSelections(
      final Object[] toSelect, Function<Object, Object> restore, Set<Object> originallySelected) {
    final Set<Object> selected = myUi.getSelectedElements();

    boolean wasFullyRejected = false;
    if (toSelect.length > 0 && selected.size() > 0 && !originallySelected.containsAll(selected)) {
      final Set<Object> successfulSelections = new HashSet<Object>();
      ContainerUtil.addAll(successfulSelections, toSelect);

      successfulSelections.retainAll(selected);
      wasFullyRejected = successfulSelections.size() == 0;
    } else if (selected.size() == 0 && originallySelected.size() == 0) {
      wasFullyRejected = true;
    }

    if (wasFullyRejected && selected.size() > 0) return;

    for (Object eachToSelect : toSelect) {
      if (!selected.contains(eachToSelect)) {
        restore.fun(eachToSelect);
      }
    }
  }
    @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()]);
  }
 WordListModel(ASDGrammar grammar) {
   Set entrySet = grammar.lexicon().entrySet();
   ArrayList words = new ArrayList(entrySet.size());
   for (Iterator it = entrySet.iterator(); it.hasNext(); ) {
     Map.Entry e = (Map.Entry) it.next();
     String word = (String) e.getKey();
     words.add(word);
   }
   Object[] wordArray = words.toArray();
   if (words.size() > 1)
     //       Arrays.sort(wordArray);
     Arrays.sort(wordArray, new WordComparator());
   for (int j = 0; j < wordArray.length; j++) {
     this.addElement((String) wordArray[j]);
   }
 }
  protected static String getStatusToolTip() {
    StringBuffer result = new StringBuffer("<html>"); // NOI18N
    result.append("<table cellspacing=\"0\" border=\"0\">"); // NOI18N

    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      Set sessions =
          new TreeSet(
              new Comparator() {
                public int compare(Object o1, Object o2) {
                  String s1 = ((CollabSession) o1).getUserPrincipal().getDisplayName();
                  String s2 = ((CollabSession) o2).getUserPrincipal().getDisplayName();

                  return s1.compareTo(s2);
                }
              });

      sessions.addAll(Arrays.asList(manager.getSessions()));

      if (sessions.size() == 0) {
        result.append("<tr><td>"); // NOI18N
        result.append(getStatusDescription(CollabPrincipal.STATUS_OFFLINE));
        result.append("</td></tr>"); // NOI18N
      } else {
        for (Iterator i = sessions.iterator(); i.hasNext(); ) {
          CollabPrincipal principal = ((CollabSession) i.next()).getUserPrincipal();

          result.append("<tr>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append("<b>"); // NOI18N
          result.append(principal.getDisplayName());
          result.append(": "); // NOI18N
          result.append("</b>"); // NOI18N
          result.append("</td>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append(getStatusDescription(principal.getStatus()));
          result.append("</td>"); // NOI18N
          result.append("</tr>"); // NOI18N
        }
      }
    }

    result.append("</table>"); // NOI18N

    return result.toString();
  }
  @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 Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) {
    Ref<PyType> elementType = null;
    final PyBuiltinCache cache = PyBuiltinCache.getInstance(this);
    final PyStatementList statements = getStatementList();
    final Set<PyType> types = new LinkedHashSet<>();
    statements.accept(
        new PyRecursiveElementVisitor() {
          @Override
          public void visitPyYieldExpression(PyYieldExpression node) {
            final PyExpression expr = node.getExpression();
            final PyType type = expr != null ? context.getType(expr) : null;
            if (node.isDelegating() && type instanceof PyCollectionType) {
              final PyCollectionType collectionType = (PyCollectionType) type;
              // TODO: Select the parameter types that matches T in Iterable[T]
              final List<PyType> elementTypes = collectionType.getElementTypes(context);
              types.add(elementTypes.isEmpty() ? null : elementTypes.get(0));
            } else {
              types.add(type);
            }
          }

          @Override
          public void visitPyFunction(PyFunction node) {
            // Ignore nested functions
          }
        });
    final int n = types.size();
    if (n == 1) {
      elementType = Ref.create(types.iterator().next());
    } else if (n > 0) {
      elementType = Ref.create(PyUnionType.union(types));
    }
    if (elementType != null) {
      final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR);
      if (generator != null) {
        final List<PyType> parameters =
            Arrays.asList(elementType.get(), null, getReturnStatementType(context));
        return Ref.create(new PyCollectionTypeImpl(generator, false, parameters));
      }
    }
    if (!types.isEmpty()) {
      return Ref.create(null);
    }
    return null;
  }
Esempio n. 20
0
  private boolean checkReferencedRastersIncluded() {
    final Set<String> notIncludedNames = new TreeSet<String>();
    final List<String> includedNodeNames = Arrays.asList(productSubsetDef.getNodeNames());
    for (final String nodeName : includedNodeNames) {
      final RasterDataNode rasterDataNode = product.getRasterDataNode(nodeName);
      if (rasterDataNode != null) {
        collectNotIncludedReferences(rasterDataNode, notIncludedNames);
      }
    }

    boolean ok = true;
    if (!notIncludedNames.isEmpty()) {
      StringBuilder nameListText = new StringBuilder();
      for (String notIncludedName : notIncludedNames) {
        nameListText.append("  '").append(notIncludedName).append("'\n");
      }

      final String pattern =
          "The following dataset(s) are referenced but not included\n"
              + "in your current subset definition:\n"
              + "{0}\n"
              + "If you do not include these dataset(s) into your selection,\n"
              + "you might get unexpected results while working with the\n"
              + "resulting product.\n\n"
              + "Do you wish to include the referenced dataset(s) into your\n"
              + "subset definition?\n"; /*I18N*/
      final MessageFormat format = new MessageFormat(pattern);
      int status =
          JOptionPane.showConfirmDialog(
              getJDialog(),
              format.format(new Object[] {nameListText.toString()}),
              "Incomplete Subset Definition", /*I18N*/
              JOptionPane.YES_NO_CANCEL_OPTION);
      if (status == JOptionPane.YES_OPTION) {
        final String[] nodenames = notIncludedNames.toArray(new String[notIncludedNames.size()]);
        productSubsetDef.addNodeNames(nodenames);
        ok = true;
      } else if (status == JOptionPane.NO_OPTION) {
        ok = true;
      } else if (status == JOptionPane.CANCEL_OPTION) {
        ok = false;
      }
    }
    return ok;
  }
 public boolean addTarget(final PsiElement element) {
   if (ArrayUtil.find(targets, element) > -1) return false;
   targets = ArrayUtil.append(targets, element);
   renderers.put(element, createRenderer(this, element));
   if (!hasDifferentNames && element instanceof PsiNamedElement) {
     final String name =
         ApplicationManager.getApplication()
             .runReadAction(
                 new Computable<String>() {
                   @Override
                   public String compute() {
                     return ((PsiNamedElement) element).getName();
                   }
                 });
     myNames.add(name);
     hasDifferentNames = myNames.size() > 1;
   }
   return true;
 }
  @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()]);
  }
  @Nullable
  private Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) {
    Ref<PyType> elementType = null;
    final PyBuiltinCache cache = PyBuiltinCache.getInstance(this);
    final PyStatementList statements = getStatementList();
    final Set<PyType> types = new LinkedHashSet<PyType>();
    if (statements != null) {
      statements.accept(
          new PyRecursiveElementVisitor() {
            @Override
            public void visitPyYieldExpression(PyYieldExpression node) {
              final PyType type = context.getType(node);
              if (node.isDelegating() && type instanceof PyCollectionType) {
                final PyCollectionType collectionType = (PyCollectionType) type;
                types.add(collectionType.getElementType(context));
              } else {
                types.add(type);
              }
            }

            @Override
            public void visitPyFunction(PyFunction node) {
              // Ignore nested functions
            }
          });
      final int n = types.size();
      if (n == 1) {
        elementType = Ref.create(types.iterator().next());
      } else if (n > 0) {
        elementType = Ref.create(PyUnionType.union(types));
      }
    }
    if (elementType != null) {
      final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR);
      if (generator != null) {
        return Ref.create(new PyCollectionTypeImpl(generator, false, elementType.get()));
      }
    }
    if (!types.isEmpty()) {
      return Ref.create(null);
    }
    return null;
  }
Esempio n. 24
0
  @Override
  @NotNull
  public PsiFile[] getPsiRoots() {
    final FileViewProvider viewProvider = getViewProvider();
    final Set<Language> languages = viewProvider.getLanguages();

    final PsiFile[] roots = new PsiFile[languages.size()];
    int i = 0;
    for (Language language : languages) {
      PsiFile psi = viewProvider.getPsi(language);
      if (psi == null) {
        LOG.error("PSI is null for " + language + "; in file: " + this);
      }
      roots[i++] = psi;
    }
    if (roots.length > 1) {
      Arrays.sort(roots, FILE_BY_LANGUAGE_ID);
    }
    return roots;
  }
 @NotNull
 public static List<GotoRelatedItem> collectRelatedItems(
     @NotNull PsiElement contextElement, @Nullable DataContext dataContext) {
   Set<GotoRelatedItem> items = ContainerUtil.newLinkedHashSet();
   for (GotoRelatedProvider provider : Extensions.getExtensions(GotoRelatedProvider.EP_NAME)) {
     items.addAll(provider.getItems(contextElement));
     if (dataContext != null) {
       items.addAll(provider.getItems(dataContext));
     }
   }
   GotoRelatedItem[] result = items.toArray(new GotoRelatedItem[items.size()]);
   Arrays.sort(
       result,
       (i1, i2) -> {
         String o1 = i1.getGroup();
         String o2 = i2.getGroup();
         return StringUtil.isEmpty(o1) ? 1 : StringUtil.isEmpty(o2) ? -1 : o1.compareTo(o2);
       });
   return Arrays.asList(result);
 }
 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
 public EditorWindow[] getWindows() {
   return myWindows.toArray(new EditorWindow[myWindows.size()]);
 }
 @Override
 @NotNull
 public Document[] getUncommittedDocuments() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   return myUncommittedDocuments.toArray(new Document[myUncommittedDocuments.size()]);
 }
Esempio n. 29
0
  @NotNull
  @Override
  public List<SearchScope> getPredefinedScopes(
      @NotNull final Project project,
      @Nullable final DataContext dataContext,
      boolean suggestSearchInLibs,
      boolean prevSearchFiles,
      boolean currentSelection,
      boolean usageView,
      boolean showEmptyScopes) {
    Collection<SearchScope> result = ContainerUtil.newLinkedHashSet();
    result.add(GlobalSearchScope.projectScope(project));
    if (suggestSearchInLibs) {
      result.add(GlobalSearchScope.allScope(project));
    }

    if (ModuleUtil.isSupportedRootType(project, JavaSourceRootType.TEST_SOURCE)) {
      result.add(GlobalSearchScopesCore.projectProductionScope(project));
      result.add(GlobalSearchScopesCore.projectTestScope(project));
    }

    final GlobalSearchScope openFilesScope = GlobalSearchScopes.openFilesScope(project);
    if (openFilesScope != GlobalSearchScope.EMPTY_SCOPE) {
      result.add(openFilesScope);
    } else if (showEmptyScopes) {
      result.add(
          new LocalSearchScope(PsiElement.EMPTY_ARRAY, IdeBundle.message("scope.open.files")));
    }

    final Editor selectedTextEditor =
        ApplicationManager.getApplication().isDispatchThread()
            ? FileEditorManager.getInstance(project).getSelectedTextEditor()
            : null;
    final PsiFile psiFile =
        (selectedTextEditor != null)
            ? PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument())
            : null;
    PsiFile currentFile = psiFile;

    if (dataContext != null) {
      PsiElement dataContextElement = CommonDataKeys.PSI_FILE.getData(dataContext);
      if (dataContextElement == null) {
        dataContextElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      }

      if (dataContextElement == null && psiFile != null) {
        dataContextElement = psiFile;
      }

      if (dataContextElement != null) {
        if (!PlatformUtils.isCidr()) { // TODO: have an API to disable module scopes.
          Module module = ModuleUtilCore.findModuleForPsiElement(dataContextElement);
          if (module == null) {
            module = LangDataKeys.MODULE.getData(dataContext);
          }
          if (module != null && !(ModuleType.get(module) instanceof InternalModuleType)) {
            result.add(module.getModuleScope());
          }
        }
        if (currentFile == null) {
          currentFile = dataContextElement.getContainingFile();
        }
      }
    }

    if (currentFile != null || showEmptyScopes) {
      PsiElement[] scope =
          currentFile != null ? new PsiElement[] {currentFile} : PsiElement.EMPTY_ARRAY;
      result.add(new LocalSearchScope(scope, IdeBundle.message("scope.current.file")));
    }

    if (currentSelection && selectedTextEditor != null && psiFile != null) {
      SelectionModel selectionModel = selectedTextEditor.getSelectionModel();
      if (selectionModel.hasSelection()) {
        int start = selectionModel.getSelectionStart();
        final PsiElement startElement = psiFile.findElementAt(start);
        if (startElement != null) {
          int end = selectionModel.getSelectionEnd();
          final PsiElement endElement = psiFile.findElementAt(end);
          if (endElement != null) {
            final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
            if (parent != null) {
              final List<PsiElement> elements = new ArrayList<PsiElement>();
              final PsiElement[] children = parent.getChildren();
              TextRange selection = new TextRange(start, end);
              for (PsiElement child : children) {
                if (!(child instanceof PsiWhiteSpace)
                    && child.getContainingFile() != null
                    && selection.contains(child.getTextOffset())) {
                  elements.add(child);
                }
              }
              if (!elements.isEmpty()) {
                SearchScope local =
                    new LocalSearchScope(
                        PsiUtilCore.toPsiElementArray(elements),
                        IdeBundle.message("scope.selection"));
                result.add(local);
              }
            }
          }
        }
      }
    }

    if (usageView) {
      addHierarchyScope(project, result);
      UsageView selectedUsageView = UsageViewManager.getInstance(project).getSelectedUsageView();
      if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
        final Set<Usage> usages = ContainerUtil.newTroveSet(selectedUsageView.getUsages());
        usages.removeAll(selectedUsageView.getExcludedUsages());
        final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());

        if (prevSearchFiles) {
          final Set<VirtualFile> files = collectFiles(usages, true);
          if (!files.isEmpty()) {
            GlobalSearchScope prev =
                new GlobalSearchScope(project) {
                  private Set<VirtualFile> myFiles = null;

                  @NotNull
                  @Override
                  public String getDisplayName() {
                    return IdeBundle.message("scope.files.in.previous.search.result");
                  }

                  @Override
                  public synchronized boolean contains(@NotNull VirtualFile file) {
                    if (myFiles == null) {
                      myFiles = collectFiles(usages, false);
                    }
                    return myFiles.contains(file);
                  }

                  @Override
                  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
                    return 0;
                  }

                  @Override
                  public boolean isSearchInModuleContent(@NotNull Module aModule) {
                    return true;
                  }

                  @Override
                  public boolean isSearchInLibraries() {
                    return true;
                  }
                };
            result.add(prev);
          }
        } else {
          for (Usage usage : usages) {
            if (usage instanceof PsiElementUsage) {
              final PsiElement element = ((PsiElementUsage) usage).getElement();
              if (element != null && element.isValid() && element.getContainingFile() != null) {
                results.add(element);
              }
            }
          }

          if (!results.isEmpty()) {
            result.add(
                new LocalSearchScope(
                    PsiUtilCore.toPsiElementArray(results),
                    IdeBundle.message("scope.previous.search.results")));
          }
        }
      }
    }

    final FavoritesManager favoritesManager = FavoritesManager.getInstance(project);
    if (favoritesManager != null) {
      for (final String favorite : favoritesManager.getAvailableFavoritesListNames()) {
        final Collection<TreeItem<Pair<AbstractUrl, String>>> rootUrls =
            favoritesManager.getFavoritesListRootUrls(favorite);
        if (rootUrls.isEmpty()) continue; // ignore unused root
        result.add(
            new GlobalSearchScope(project) {
              @NotNull
              @Override
              public String getDisplayName() {
                return "Favorite \'" + favorite + "\'";
              }

              @Override
              public boolean contains(@NotNull final VirtualFile file) {
                return ApplicationManager.getApplication()
                    .runReadAction(
                        (Computable<Boolean>) () -> favoritesManager.contains(favorite, file));
              }

              @Override
              public int compare(
                  @NotNull final VirtualFile file1, @NotNull final VirtualFile file2) {
                return 0;
              }

              @Override
              public boolean isSearchInModuleContent(@NotNull final Module aModule) {
                return true;
              }

              @Override
              public boolean isSearchInLibraries() {
                return true;
              }
            });
      }
    }

    ContainerUtil.addIfNotNull(result, getSelectedFilesScope(project, dataContext));

    return ContainerUtil.newArrayList(result);
  }
    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      final Component orig =
          super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      if (myPluginDescriptor != null) {
        myNameLabel.setText(myPluginDescriptor.getName());
        final PluginId pluginId = myPluginDescriptor.getPluginId();
        final String idString = pluginId.getIdString();
        if (myPluginDescriptor.isBundled()) {
          myBundledLabel.setText("Bundled");
        } else {
          final String host = myPlugin2host.get(idString);
          if (host != null) {
            String presentableUrl = VfsUtil.urlToPath(host);
            final int idx = presentableUrl.indexOf('/');
            if (idx > -1) {
              presentableUrl = presentableUrl.substring(0, idx);
            }
            myBundledLabel.setText("From " + presentableUrl);
          } else {
            if (PluginManagerUISettings.getInstance().getInstalledPlugins().contains(idString)) {
              myBundledLabel.setText("From repository");
            } else {
              myBundledLabel.setText("Custom");
            }
          }
        }
        if (myPluginDescriptor instanceof IdeaPluginDescriptorImpl
            && ((IdeaPluginDescriptorImpl) myPluginDescriptor).isDeleted()) {
          myNameLabel.setIcon(AllIcons.Actions.Clean);
        } else if (hasNewerVersion(pluginId)) {
          myNameLabel.setIcon(AllIcons.Nodes.Pluginobsolete);
          myPanel.setToolTipText("Newer version of the plugin is available");
        } else {
          myNameLabel.setIcon(AllIcons.Nodes.Plugin);
        }

        final Color fg = orig.getForeground();
        final Color bg = orig.getBackground();
        final Color grayedFg = isSelected ? fg : Color.GRAY;

        myPanel.setBackground(bg);
        myNameLabel.setBackground(bg);
        myBundledLabel.setBackground(bg);

        myNameLabel.setForeground(fg);
        final boolean wasUpdated = wasUpdated(pluginId);
        if (wasUpdated || PluginManager.getPlugin(pluginId) == null) {
          if (!isSelected) {
            myNameLabel.setForeground(FileStatus.COLOR_ADDED);
          }
          if (wasUpdated) {
            myPanel.setToolTipText(
                "Plugin was updated to the newest version. Changes will be available after restart");
          } else {
            myPanel.setToolTipText("Plugin will be activated after restart.");
          }
        }
        myBundledLabel.setForeground(grayedFg);

        final Set<PluginId> required = myDependentToRequiredListMap.get(pluginId);
        if (required != null && required.size() > 0) {
          myNameLabel.setForeground(Color.RED);

          final StringBuilder s = new StringBuilder();
          if (myEnabled.get(pluginId) == null) {
            s.append("Plugin was not loaded.\n");
          }
          if (required.contains(PluginId.getId("com.intellij.modules.ultimate"))) {
            s.append("The plugin requires IntelliJ IDEA Ultimate");
          } else {
            s.append("Required plugin").append(required.size() == 1 ? " \"" : "s \"");
            s.append(
                StringUtil.join(
                    required,
                    new Function<PluginId, String>() {
                      @Override
                      public String fun(final PluginId id) {
                        final IdeaPluginDescriptor plugin = PluginManager.getPlugin(id);
                        return plugin == null ? id.getIdString() : plugin.getName();
                      }
                    },
                    ","));

            s.append(required.size() == 1 ? "\" is not enabled!" : "\" are not enabled!");
          }
          myPanel.setToolTipText(s.toString());
        }

        if (PluginManager.isIncompatible(myPluginDescriptor)) {
          myPanel.setToolTipText(
              IdeBundle.message(
                  "plugin.manager.incompatible.tooltip.warning",
                  ApplicationNamesInfo.getInstance().getFullProductName()));
          myNameLabel.setForeground(Color.red);
        }
      }

      return myPanel;
    }