Java Code Examples for com.intellij.util.containers.ContainerUtil#sorted()

The following examples show how to use com.intellij.util.containers.ContainerUtil#sorted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RectangleReferencePainter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void customizePainter(@Nonnull JComponent component,
                             @Nonnull Collection<VcsRef> references,
                             @Nullable VcsLogRefManager manager,
                             @Nonnull Color background,
                             @Nonnull Color foreground) {
  FontMetrics metrics = component.getFontMetrics(getReferenceFont());
  myHeight = metrics.getHeight() + RectanglePainter.TOP_TEXT_PADDING + RectanglePainter.BOTTOM_TEXT_PADDING;
  myWidth = 2 * PaintParameters.LABEL_PADDING;

  myLabels = ContainerUtil.newArrayList();
  if (manager == null) return;

  List<VcsRef> sorted = ContainerUtil.sorted(references, manager.getLabelsOrderComparator());

  for (Map.Entry<VcsRefType, Collection<VcsRef>> entry : ContainerUtil.groupBy(sorted, VcsRef::getType).entrySet()) {
    VcsRef ref = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(entry.getValue()));
    String text = ref.getName() + (entry.getValue().size() > 1 ? " +" : "");
    myLabels.add(Pair.create(text, entry.getKey().getBackgroundColor()));

    myWidth += myLabelPainter.calculateSize(text, metrics).getWidth() + PaintParameters.LABEL_PADDING;
  }
}
 
Example 2
Source File: ChangesBrowserNodeCopyProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void performCopy(@Nonnull DataContext dataContext) {
  List<TreePath> paths = ContainerUtil.sorted(Arrays.asList(ObjectUtils.assertNotNull(myTree.getSelectionPaths())),
                                              TreeUtil.getDisplayOrderComparator(myTree));
  CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(paths, new Function<TreePath, String>() {
    @Override
    public String fun(TreePath path) {
      Object node = path.getLastPathComponent();
      if (node instanceof ChangesBrowserNode) {
        return ((ChangesBrowserNode)node).getTextPresentation();
      }
      else {
        return node.toString();
      }
    }
  }, "\n")));
}
 
Example 3
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public TreeModelBuilder setSwitchedFiles(@Nonnull MultiMap<String, VirtualFile> switchedFiles) {
  if (switchedFiles.isEmpty()) return this;
  ChangesBrowserNode subtreeRoot = createTagNode(ChangesBrowserNode.SWITCHED_FILES_TAG);
  for (String branchName : switchedFiles.keySet()) {
    List<VirtualFile> switchedFileList = ContainerUtil.sorted(switchedFiles.get(branchName), VirtualFileHierarchicalComparator.getInstance());
    if (switchedFileList.size() > 0) {
      ChangesBrowserNode branchNode = ChangesBrowserNode.create(myProject, branchName);
      myModel.insertNodeInto(branchNode, subtreeRoot, subtreeRoot.getChildCount());

      for (VirtualFile file : switchedFileList) {
        insertChangeNode(file, branchNode, ChangesBrowserNode.create(myProject, file));
      }
    }
  }
  return this;
}
 
Example 4
Source File: StructureFilterPopupComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected ActionGroup createActionGroup() {
  Set<VirtualFile> roots = getAllRoots();

  List<AnAction> rootActions = new ArrayList<>();
  if (myColorManager.isMultipleRoots()) {
    for (VirtualFile root : ContainerUtil.sorted(roots, FILE_BY_NAME_COMPARATOR)) {
      rootActions.add(new SelectVisibleRootAction(root));
    }
  }
  List<AnAction> structureActions = new ArrayList<>();
  for (VcsLogStructureFilter filter : myHistory) {
    structureActions.add(new SelectFromHistoryAction(filter));
  }

  if (roots.size() > 15) {
    return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(),
                                  new AnSeparator("Recent"), new DefaultActionGroup(structureActions),
                                  new AnSeparator("Roots"), new DefaultActionGroup(rootActions));
  }
  else {
    return new DefaultActionGroup(createAllAction(), new SelectFoldersAction(),
                                  new AnSeparator("Roots"), new DefaultActionGroup(rootActions),
                                  new AnSeparator("Recent"), new DefaultActionGroup(structureActions));
  }
}
 
Example 5
Source File: GraphLayoutBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static GraphLayoutImpl build(@Nonnull LinearGraph graph, @Nonnull Comparator<Integer> headNodeIndexComparator) {
  List<Integer> heads = new ArrayList<>();
  for (int i = 0; i < graph.nodesCount(); i++) {
    if (getUpNodes(graph, i).size() == 0) {
      heads.add(i);
    }
  }
  try {
    heads = ContainerUtil.sorted(heads, headNodeIndexComparator);
  }
  catch (ProcessCanceledException pce) {
    throw pce;
  }
  catch (Exception e) {
    // protection against possible comparator flaws
    LOG.error(e);
  }
  GraphLayoutBuilder builder = new GraphLayoutBuilder(graph, heads);
  return builder.build();
}
 
Example 6
Source File: FileHistoryPanelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void executeAction(AnActionEvent e) {
  List<TreeNodeOnVcsRevision> sel = getSelection();

  int selectionSize = sel.size();
  if (selectionSize > 1) {
    List<VcsFileRevision> selectedRevisions =
            ContainerUtil.sorted(ContainerUtil.map(sel, TreeNodeOnVcsRevision::getRevision), myRevisionsInOrderComparator);
    VcsFileRevision olderRevision = selectedRevisions.get(0);
    VcsFileRevision newestRevision = selectedRevisions.get(sel.size() - 1);
    myDiffHandler.showDiffForTwo(e.getRequiredData(CommonDataKeys.PROJECT), myFilePath, olderRevision, newestRevision);
  }
  else if (selectionSize == 1) {
    final TableView<TreeNodeOnVcsRevision> flatView = myDualView.getFlatView();
    final int selectedRow = flatView.getSelectedRow();
    VcsFileRevision revision = getFirstSelectedRevision();

    VcsFileRevision previousRevision;
    if (selectedRow == (flatView.getRowCount() - 1)) {
      // no previous
      previousRevision = myBottomRevisionForShowDiff != null ? myBottomRevisionForShowDiff : VcsFileRevision.NULL;
    }
    else {
      previousRevision = flatView.getRow(selectedRow + 1).getRevision();
    }

    if (revision != null) {
      myDiffHandler.showDiffForOne(e, e.getRequiredData(CommonDataKeys.PROJECT), myFilePath, previousRevision, revision);
    }
  }
}
 
Example 7
Source File: BlazeCWorkspace.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<String> collectCompilerSettingsInParallel(
    OCWorkspaceImpl.ModifiableModel model, CidrToolEnvironment toolEnvironment) {
  CompilerInfoCache compilerInfoCache = new CompilerInfoCache();
  TempFilesPool tempFilesPool = new CachedTempFilesPool();
  Session<Integer> session = compilerInfoCache.createSession(new EmptyProgressIndicator());
  ImmutableList.Builder<String> issues = ImmutableList.builder();
  try {
    int i = 0;
    for (OCResolveConfiguration.ModifiableModel config : model.getConfigurations()) {
      session.schedule(i++, config, toolEnvironment);
    }
    MultiMap<Integer, Message> messages = new MultiMap<>();
    session.waitForAll(messages);
    for (Map.Entry<Integer, Collection<Message>> entry :
        ContainerUtil.sorted(messages.entrySet(), Comparator.comparingInt(Map.Entry::getKey))) {
      entry.getValue().stream()
          .filter(m -> m.getType().equals(Message.Type.ERROR))
          .map(Message::getText)
          .forEachOrdered(issues::add);
    }
  } catch (Error | RuntimeException e) {
    session.dispose(); // This calls tempFilesPool.clean();
    throw e;
  }
  tempFilesPool.clean();
  return issues.build();
}
 
Example 8
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public TreeModelBuilder setLogicallyLockedFiles(@javax.annotation.Nullable Map<VirtualFile, LogicalLock> logicallyLockedFiles) {
  if (ContainerUtil.isEmpty(logicallyLockedFiles)) return this;
  final ChangesBrowserNode subtreeRoot = createTagNode(ChangesBrowserNode.LOGICALLY_LOCKED_TAG);

  List<VirtualFile> keys = ContainerUtil.sorted(logicallyLockedFiles.keySet(), VirtualFileHierarchicalComparator.getInstance());

  for (VirtualFile file : keys) {
    final LogicalLock lock = logicallyLockedFiles.get(file);
    final ChangesBrowserLogicallyLockedFile obj = new ChangesBrowserLogicallyLockedFile(myProject, file, lock);
    insertChangeNode(obj, subtreeRoot, ChangesBrowserNode.create(myProject, obj));
  }
  return this;
}
 
Example 9
Source File: ScopeChooserCombo.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean processScopes(@Nonnull Project project,
                                    @Nonnull DataContext dataContext,
                                    @MagicConstant(flagsFromClass = ScopeChooserCombo.class) int options,
                                    @Nonnull Processor<? super ScopeDescriptor> processor) {
  List<SearchScope> predefinedScopes = PredefinedSearchScopeProvider.getInstance()
          .getPredefinedScopes(project, dataContext, BitUtil.isSet(options, OPT_LIBRARIES), BitUtil.isSet(options, OPT_SEARCH_RESULTS), BitUtil.isSet(options, OPT_FROM_SELECTION),
                               BitUtil.isSet(options, OPT_USAGE_VIEW), BitUtil.isSet(options, OPT_EMPTY_SCOPES));
  for (SearchScope searchScope : predefinedScopes) {
    if (!processor.process(new ScopeDescriptor(searchScope))) return false;
  }
  for (ScopeDescriptorProvider provider : ScopeDescriptorProvider.EP_NAME.getExtensionList()) {
    for (ScopeDescriptor descriptor : provider.getScopeDescriptors(project)) {
      if (!processor.process(descriptor)) return false;
    }
  }
  Comparator<SearchScope> comparator = (o1, o2) -> {
    int w1 = o1 instanceof WeighedItem ? ((WeighedItem)o1).getWeight() : Integer.MAX_VALUE;
    int w2 = o2 instanceof WeighedItem ? ((WeighedItem)o2).getWeight() : Integer.MAX_VALUE;
    if (w1 == w2) return StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName());
    return w1 - w2;
  };
  for (SearchScopeProvider each : SearchScopeProvider.EP_NAME.getExtensionList()) {
    if (StringUtil.isEmpty(each.getDisplayName())) continue;
    List<SearchScope> scopes = each.getSearchScopes(project);
    if (scopes.isEmpty()) continue;
    if (!processor.process(new ScopeSeparator(each.getDisplayName()))) return false;
    for (SearchScope scope : ContainerUtil.sorted(scopes, comparator)) {
      if (!processor.process(new ScopeDescriptor(scope))) return false;
    }
  }
  return true;
}
 
Example 10
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public TreeModelBuilder setChanges(@Nonnull Collection<? extends Change> changes, @javax.annotation.Nullable ChangeNodeDecorator changeNodeDecorator) {
  List<? extends Change> sortedChanges = ContainerUtil.sorted(changes, PATH_LENGTH_COMPARATOR);
  for (Change change : sortedChanges) {
    insertChangeNode(change, myRoot, createChangeNode(change, changeNodeDecorator));
  }
  return this;
}
 
Example 11
Source File: LinearBekGraphBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public MergeFragment getFragment(int mergeCommit) {
  List<Integer> downNodes = ContainerUtil.sorted(LinearGraphUtils.getDownNodes(myLinearBekGraph, mergeCommit));
  if (downNodes.size() != 2) return null;

  return getFragment(downNodes.get(1), downNodes.get(0), mergeCommit);
}
 
Example 12
Source File: ValuesCompletionProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void fillCompletionVariants(@Nonnull CompletionParameters parameters,
                                   @Nonnull String prefix,
                                   @Nonnull CompletionResultSet result) {
  Collection<? extends T> values = getValues(prefix, result);
  values = ContainerUtil.sorted(values, myDescriptor);

  for (T completionVariant : values) {
    result.addElement(installInsertHandler(myDescriptor.createLookupBuilder(completionVariant)));
  }
  result.stopHere();
}
 
Example 13
Source File: VcsLogGraphTable.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Selection(@Nonnull VcsLogGraphTable table) {
  myTable = table;
  List<Integer> selectedRows = ContainerUtil.sorted(Ints.asList(myTable.getSelectedRows()));
  Couple<Integer> visibleRows = ScrollingUtil.getVisibleRows(myTable);
  myIsOnTop = visibleRows.first - 1 == 0;

  VisibleGraph<Integer> graph = myTable.getVisibleGraph();

  mySelectedCommits = new TIntHashSet();

  Integer visibleSelectedCommit = null;
  Integer delta = null;
  for (int row : selectedRows) {
    if (row < graph.getVisibleCommitCount()) {
      Integer commit = graph.getRowInfo(row).getCommit();
      mySelectedCommits.add(commit);
      if (visibleRows.first - 1 <= row && row <= visibleRows.second && visibleSelectedCommit == null) {
        visibleSelectedCommit = commit;
        delta = myTable.getCellRect(row, 0, false).y - myTable.getVisibleRect().y;
      }
    }
  }
  if (visibleSelectedCommit == null && visibleRows.first - 1 >= 0) {
    visibleSelectedCommit = graph.getRowInfo(visibleRows.first - 1).getCommit();
    delta = myTable.getCellRect(visibleRows.first - 1, 0, false).y - myTable.getVisibleRect().y;
  }

  myVisibleSelectedCommit = visibleSelectedCommit;
  myDelta = delta;
}
 
Example 14
Source File: FoldingUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void getFoldingsFor(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull List<? super RegionInfo> elementsToFold, boolean quick) {
  final FileViewProvider viewProvider = file.getViewProvider();
  TextRange docRange = TextRange.from(0, document.getTextLength());
  Comparator<Language> preferBaseLanguage = Comparator.comparing((Language l) -> l != viewProvider.getBaseLanguage());
  List<Language> languages = ContainerUtil.sorted(viewProvider.getLanguages(), preferBaseLanguage.thenComparing(Language::getID));

  DocumentEx copyDoc = languages.size() > 1 ? new DocumentImpl(document.getImmutableCharSequence()) : null;
  List<RangeMarker> hardRefToRangeMarkers = new ArrayList<>();

  for (Language language : languages) {
    final PsiFile psi = viewProvider.getPsi(language);
    final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
    if (psi != null && foldingBuilder != null) {
      for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, quick)) {
        PsiElement psiElement = descriptor.getElement().getPsi();
        if (psiElement == null) {
          LOG.error("No PSI for folding descriptor " + descriptor);
          continue;
        }
        TextRange range = descriptor.getRange();
        if (!docRange.contains(range)) {
          diagnoseIncorrectRange(psi, document, language, foldingBuilder, descriptor, psiElement);
          continue;
        }

        if (copyDoc != null && !addNonConflictingRegion(copyDoc, range, hardRefToRangeMarkers)) {
          continue;
        }

        RegionInfo regionInfo = new RegionInfo(descriptor, psiElement, foldingBuilder);
        elementsToFold.add(regionInfo);
      }
    }
  }
}
 
Example 15
Source File: ProjectInfo.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private static <T> List<Map.Entry<String, T>> getSortedEntries(Map<String, T> map) {
  return ContainerUtil.sorted(
    map.entrySet(),
    new Comparator<Map.Entry<String, T>>() {
      @Override
      public int compare(Map.Entry<String, T> o1, Map.Entry<String, T> o2) {
        return StringUtil.naturalCompare(o1.getKey(), o2.getKey());
      }
    }
  );
}
 
Example 16
Source File: TreeChangeEventImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void fireEvents() {
  Collection<TreeChangeImpl> changes = ContainerUtil.sorted(myChangedElements.values());
  for (TreeChangeImpl change : changes) {
    change.fireEvents((PsiFile)myFileElement.getPsi());
  }
}
 
Example 17
Source File: DvcsUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static List<VirtualFile> sortVirtualFilesByPresentation(@Nonnull Collection<VirtualFile> virtualFiles) {
  return ContainerUtil.sorted(virtualFiles, VIRTUAL_FILE_PRESENTATION_COMPARATOR);
}
 
Example 18
Source File: PersistentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int calcLogProvidersHash(@Nonnull final Map<VirtualFile, VcsLogProvider> logProviders) {
  List<VirtualFile> sortedRoots = ContainerUtil.sorted(logProviders.keySet(), Comparator.comparing(VirtualFile::getPath));
  return StringUtil.join(sortedRoots, root -> root.getPath() + "." + logProviders.get(root).getSupportedVcs().getName(), ".").hashCode();
}
 
Example 19
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void insertFilesIntoNode(@Nonnull Collection<VirtualFile> files, @Nonnull ChangesBrowserNode subtreeRoot) {
  List<VirtualFile> sortedFiles = ContainerUtil.sorted(files, VirtualFileHierarchicalComparator.getInstance());
  for (VirtualFile file : sortedFiles) {
    insertChangeNode(file, subtreeRoot, ChangesBrowserNode.create(myProject, file));
  }
}
 
Example 20
Source File: GoToHashOrRefPopup.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private List<VcsRef> filterAndSort(@Nonnull CompletionResultSet result, @Nonnull Stream<VcsRef> stream) {
  return ContainerUtil
    .sorted(stream.filter(ref -> myRoots.contains(ref.getRoot()) && result.getPrefixMatcher().prefixMatches(ref.getName()))
              .collect(Collectors.toList()), myDescriptor);
}