com.intellij.util.containers.JBIterable Java Examples

The following examples show how to use com.intellij.util.containers.JBIterable. 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: DbReference.java    From Thinkphp5-Plugin with MIT License 7 votes vote down vote up
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
    final Collection<LookupElement> lookupElements = new ArrayList<>();
    JBIterable<? extends DasTable> tables = DbTableUtil.getTables(getElement().getProject());
    if(tables==null) return lookupElements;
    for (DasTable table : tables) {
        String comment = "";
        if (table.getComment() != null)
            comment = table.getComment();
        String tableStr = table.getName();
        lookupElements.add(LookupElementBuilder.create(tableStr).withTailText("   " + comment).withIcon(DatabaseIcons.Table));
        if (this.type == 2) {
            int index = tableStr.indexOf("_");
            if (index != -1) {
                tableStr = tableStr.substring(index+1);
                lookupElements.add(LookupElementBuilder.create(tableStr).withTailText("   " + comment).withIcon(DatabaseIcons.Table));
            }
        }
    }
    return lookupElements;
}
 
Example #2
Source File: ScratchTreeStructureProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void registerUpdaters(@Nonnull Project project, @Nonnull consulo.disposer.Disposable disposable, @Nonnull Runnable onUpdate) {
  String scratchPath = FileUtil.toSystemIndependentName(FileUtil.toCanonicalPath(ContainerPathManager.get().getScratchPath()));
  VirtualFileManager.getInstance().addAsyncFileListener(events -> {
    boolean update = JBIterable.from(events).find(e -> {
      ProgressManager.checkCanceled();

      final boolean isDirectory = isDirectory(e);
      final VirtualFile parent = getNewParent(e);
      return parent != null && (ScratchUtil.isScratch(parent) || isDirectory && parent.getPath().startsWith(scratchPath));
    }) != null;

    return !update ? null : new AsyncFileListener.ChangeApplier() {
      @Override
      public void afterVfsChange() {
        onUpdate.run();
      }
    };
  }, disposable);
  ConcurrentMap<RootType, Disposable> disposables = ConcurrentFactoryMap.createMap(o -> Disposable.newDisposable(o.getDisplayName()));
  for (RootType rootType : RootType.getAllRootTypes()) {
    registerRootTypeUpdater(project, rootType, onUpdate, disposable, disposables);
  }
}
 
Example #3
Source File: TreeSpeedSearch.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected Object[] getAllElements() {
  JBIterable<TreePath> paths;
  if (myCanExpand) {
    paths = TreeUtil.treePathTraverser(myComponent).traverse();
  }
  else {
    TreePath[] arr = new TreePath[myComponent.getRowCount()];
    for (int i = 0; i < arr.length; i++) {
      arr[i] = myComponent.getPathForRow(i);
    }
    paths = JBIterable.of(arr);
  }
  List<TreePath> result = paths.filter(o -> !(o.getLastPathComponent() instanceof LoadingNode)).toList();
  return result.toArray(new TreePath[0]);
}
 
Example #4
Source File: NavBarIdeView.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public PsiDirectory[] getDirectories() {
  NavBarPopup nodePopup = myPanel.getNodePopup();
  JBIterable<?> selection = nodePopup != null && nodePopup.isVisible() ? JBIterable.from(nodePopup.getList().getSelectedValuesList()) : myPanel.getSelection();
  List<PsiDirectory> dirs = selection.flatMap(o -> {
    if (o instanceof PsiElement && !((PsiElement)o).isValid()) return JBIterable.empty();
    if (o instanceof PsiDirectory) return JBIterable.of((PsiDirectory)o);
    if (o instanceof PsiDirectoryContainer) {
      return JBIterable.of(((PsiDirectoryContainer)o).getDirectories());
    }
    if (o instanceof PsiElement) {
      PsiFile file = ((PsiElement)o).getContainingFile();
      return JBIterable.of(file != null ? file.getContainingDirectory() : null);
    }
    if (o instanceof Module && !((Module)o).isDisposed()) {
      PsiManager psiManager = PsiManager.getInstance(myPanel.getProject());
      return JBIterable.of(ModuleRootManager.getInstance((Module)o).getSourceRoots()).filterMap(file -> psiManager.findDirectory(file));
    }
    return JBIterable.empty();
  }).filter(o -> o.isValid()).toList();
  return dirs.isEmpty() ? PsiDirectory.EMPTY_ARRAY : dirs.toArray(PsiDirectory.EMPTY_ARRAY);
}
 
Example #5
Source File: ScratchFileActions.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void update(@Nonnull AnActionEvent e) {
  Project project = e.getProject();
  JBIterable<VirtualFile> files = JBIterable.of(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY));
  if (project == null || files.isEmpty()) {
    e.getPresentation().setEnabledAndVisible(false);
    return;
  }

  Condition<VirtualFile> isScratch = fileFilter(project);
  if (!files.filter(not(isScratch)).isEmpty()) {
    e.getPresentation().setEnabledAndVisible(false);
    return;
  }
  Set<Language> languages = files.filter(isScratch).map(fileLanguage(project)).filter(notNull()).addAllTo(new LinkedHashSet<>());
  String langName = languages.size() == 1 ? languages.iterator().next().getDisplayName() : languages.size() + " different";
  e.getPresentation().setText(String.format("Change %s (%s)...", getLanguageTerm(), langName));
  e.getPresentation().setEnabledAndVisible(true);
}
 
Example #6
Source File: GotoActionItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean processTopHits(String pattern, Processor<? super MatchedValue> consumer, DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  final CollectConsumer<Object> collector = new CollectConsumer<Object>();
  for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensionList()) {
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider.CoveredByToggleActions) continue;
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider && !((com.intellij.ide.ui.OptionsTopHitProvider)provider).isEnabled(project)) continue;
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider && !StringUtil.startsWith(pattern, "#")) {
      String prefix = "#" + ((com.intellij.ide.ui.OptionsTopHitProvider)provider).getId() + " ";
      provider.consumeTopHits(prefix + pattern, collector, project);
    }
    provider.consumeTopHits(pattern, collector, project);
  }
  final Collection<Object> result = collector.getResult();
  final List<Comparable> c = new ArrayList<Comparable>();
  for (Object o : result) {
    if (o instanceof Comparable) {
      c.add((Comparable)o);
    }
  }
  return processItems(pattern, JBIterable.from(c), consumer);
}
 
Example #7
Source File: GotoActionItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean processActions(String pattern, Processor<? super MatchedValue> consumer, DataContext dataContext) {
  Set<String> ids = ((ActionManagerImpl)myActionManager).getActionIds();
  JBIterable<AnAction> actions = JBIterable.from(ids).filterMap(myActionManager::getAction);
  Matcher matcher = buildMatcher(pattern);

  QuickActionProvider provider = dataContext.getData(QuickActionProvider.KEY);
  if (provider != null) {
    actions = actions.append(provider.getActions(true));
  }

  JBIterable<ActionWrapper> actionWrappers = actions.unique().filterMap(action -> {
    MatchMode mode = myModel.actionMatches(pattern, matcher, action);
    if (mode == MatchMode.NONE) return null;
    return new ActionWrapper(action, myModel.getGroupMapping(action), mode, dataContext, myModel);
  });
  return processItems(pattern, actionWrappers, consumer);
}
 
Example #8
Source File: TableInfo.java    From idea-sql-generator-tool with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TableInfo(DbTable tableElement) {
    this.tableElement = tableElement;
    List<DasColumn> columns = new ArrayList<DasColumn>();

    JBIterable<? extends DasColumn> columnsIter = DasUtil.getColumns(tableElement);
    List<? extends DasColumn> dasColumns = columnsIter.toList();
    for (DasColumn dasColumn : dasColumns) {
        columns.add(dasColumn);

        if (DasUtil.isPrimary(dasColumn)) {
            primaryKeys.add(dasColumn.getName());
        }

    }

    this.columns = columns;
}
 
Example #9
Source File: TableInfoServiceImpl.java    From EasyCode with MIT License 6 votes vote down vote up
/**
 * 类型校验,如果存在未知类型则引导用于去条件类型
 *
 * @param dbTable 原始表对象
 * @return 是否验证通过
 */
@Override
public boolean typeValidator(DbTable dbTable) {
    // 处理所有列
    JBIterable<? extends DasColumn> columns = DasUtil.getColumns(dbTable);
    List<TypeMapper> typeMapperList = CurrGroupUtils.getCurrTypeMapperGroup().getElementList();

    FLAG:
    for (DasColumn column : columns) {
        String typeName = column.getDataType().getSpecification();
        for (TypeMapper typeMapper : typeMapperList) {
            // 不区分大小写查找类型
            if (Pattern.compile(typeMapper.getColumnType(), Pattern.CASE_INSENSITIVE).matcher(typeName).matches()) {
                continue FLAG;
            }
        }
        // 没找到类型,引导用户去添加类型
        if (MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, String.format("数据库类型%s,没有找到映射关系,是否去添加?", typeName)).isYes()) {
            ShowSettingsUtil.getInstance().showSettingsDialog(project, "Type Mapper");
            return false;
        }
        // 用户取消添加
        return true;
    }
    return true;
}
 
Example #10
Source File: DbTableUtil.java    From Thinkphp5-Plugin with MIT License 6 votes vote down vote up
public static JBIterable<? extends DasTable> getTables(Project project) {

        JBIterable<DbDataSource> dataSources = DbUtil.getDataSources(project);
        if (dataSources.size() < 1) {
            return null;
        } else {
            DbDataSource work = null;
            for (DbDataSource db : dataSources) {
                if (db.getName().contains("work")) {
                    work = db;
                    break;
                }
            }
            if (work != null) {
                return DasUtil.getTables(work.getDelegate());
            } else {
                if (dataSources.get(0) == null) return null;
                DbDataSource dbDataSource = dataSources.get(0);
                if(dbDataSource==null)return null;
                return DasUtil.getTables(dbDataSource.getDelegate());
            }
        }
    }
 
Example #11
Source File: DbTableUtil.java    From Thinkphp5-Plugin with MIT License 6 votes vote down vote up
public static String getTableByName(Project project, String name) {
    if (name.isEmpty()) return null;
    name = name.replace("'", "").replace("\"", "");
    JBIterable<? extends DasTable> tables = getTables(project);
    if (tables == null) return null;
    for (DasTable item : tables) {
        String tableName = item.getName();
        if (tableName.contains(name)) {
            String prefix = tableName.replace(name, "");
            if (prefix.equals(tableName.substring(0, prefix.length()))) {
                if (prefix.indexOf("_") == prefix.length() - 1)
                    return tableName;
            }
        }
    }
    return null;
}
 
Example #12
Source File: ColumnEditorFrame.java    From CodeGen with MIT License 6 votes vote down vote up
public void newColumnEditorByDb(IdeaContext ideaContext, List<DbTable> dbTables) {
    List<Table> tables = new ArrayList<>();
    for (DbTable dbTable: dbTables) {
        Table table = new Table();
        table.setTableName(dbTable.getName());

        List<Field> fields = new ArrayList<>();

        JBIterable<? extends DasColumn> columnsIter = DasUtil.getColumns(dbTable);
        List<? extends DasColumn> dasColumns = columnsIter.toList();
        for (DasColumn dasColumn : dasColumns) {
            Field field = new Field();
            field.setColumn(dasColumn.getName());
            field.setColumnType(dasColumn.getDataType().typeName);
            field.setColumnSize(String.valueOf(dasColumn.getDataType().size));
            field.setComment(dasColumn.getComment());
            fields.add(field);
        }
        table.setFields(fields);
        tables.add(table);
    }
    init(ideaContext, tables);

    // esc
    this.getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
}
 
Example #13
Source File: ScratchFileActions.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getProject();
  JBIterable<VirtualFile> files = JBIterable.of(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)).
          filter(fileFilter(project));
  if (project == null || files.isEmpty()) return;
  actionPerformedImpl(e, project, "Change " + getLanguageTerm(), files);
}
 
Example #14
Source File: GotoActionItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean processAbbreviations(@Nonnull String pattern, Processor<? super MatchedValue> consumer, DataContext context) {
  List<String> actionIds = AbbreviationManager.getInstance().findActions(pattern);
  JBIterable<MatchedValue> wrappers = JBIterable.from(actionIds).filterMap(myActionManager::getAction).transform(action -> {
    ActionWrapper wrapper = wrapAnAction(action, context);
    return new MatchedValue(wrapper, pattern) {
      @Nonnull
      @Override
      public String getValueText() {
        return pattern;
      }
    };
  });
  return processItems(pattern, wrappers, consumer);
}
 
Example #15
Source File: SyntaxTraverser.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public JBIterable<? extends T> children(@Nonnull T node) {
  T first = first(node);
  if (first == null) return JBIterable.empty();
  return siblings(first);
}
 
Example #16
Source File: SyntaxTraverser.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public T getRawDeepestLast() {
  for (T result = JBIterable.from(getRoots()).last(), last; result != null; result = last) {
    JBIterable<T> children = children(result);
    if (children.isEmpty()) return result;
    //noinspection AssignmentToForLoopParameter
    last = children.last();
  }
  return null;
}
 
Example #17
Source File: DbTableUtil.java    From Thinkphp5-Plugin with MIT License 5 votes vote down vote up
public static JBIterable<? extends DasColumn> getColumns(Project project, String table) {
    if (table == null) return null;
    try {
        JBIterable<? extends DasTable> tables = getTables(project);
        for (DasTable item : tables) {
            if (table.equals(item.getName())) {
                return DasUtil.getColumns(item);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}
 
Example #18
Source File: AbstractProjectViewPane.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public List<PsiElement> getElementsFromNode(@Nullable Object node) {
  Object value = getValueFromNode(node);
  JBIterable<?> it = value instanceof PsiElement || value instanceof VirtualFile
                     ? JBIterable.of(value)
                     : value instanceof Object[] ? JBIterable.of((Object[])value) : value instanceof Iterable ? JBIterable.from((Iterable<?>)value) : JBIterable.of(TreeUtil.getUserObject(node));
  return it.flatten(o -> o instanceof RootsProvider ? ((RootsProvider)o).getRoots() : Collections.singleton(o))
          .map(o -> o instanceof VirtualFile ? PsiUtilCore.findFileSystemItem(myProject, (VirtualFile)o) : o).filter(PsiElement.class).filter(PsiElement::isValid).toList();
}
 
Example #19
Source File: NavBarPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
JBIterable<?> getSelection() {
  Object value = myModel.getSelectedValue();
  if (value != null) return JBIterable.of(value);
  int size = myModel.size();
  return JBIterable.of(size > 0 ? myModel.getElement(size - 1) : null);
}
 
Example #20
Source File: ReflectionUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Field processFields(@Nonnull Class clazz, @Nonnull Condition<Field> checker) {
  for (Class c : classTraverser(clazz)) {
    Field field = JBIterable.of(c.getDeclaredFields()).find(checker);
    if (field != null) {
      field.setAccessible(true);
      return field;
    }
  }
  return null;
}
 
Example #21
Source File: TreeChangeEventImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean integrateIntoExistingChanges(CompositeElement nextParent) {
  for (CompositeElement eachParent : JBIterable.generate(nextParent, TreeElement::getTreeParent)) {
    CompositeElement superParent = eachParent.getTreeParent();
    TreeChangeImpl superChange = myChangedElements.get(superParent);
    if (superChange != null) {
      superChange.markChildChanged(eachParent, 0);
      return true;
    }
  }
  return false;
}
 
Example #22
Source File: StatisticsWeigher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Iterable<LookupElement> classify(@Nonnull Iterable<LookupElement> source, @Nonnull final ProcessingContext context) {
  List<LookupElement> initialList = getInitialNoStatElements(source, context);
  Iterable<LookupElement> rest = withoutInitial(source, initialList);
  Collection<List<LookupElement>> byWeight = buildMapByWeight(rest).descendingMap().values();

  return JBIterable.from(initialList).append(JBIterable.from(byWeight).flatten(group -> myNext.classify(group, context)));
}
 
Example #23
Source File: ScratchTreeStructureProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Object getData(@Nonnull Collection<AbstractTreeNode> selected, @Nonnull Key<?> dataId) {
  if (LangDataKeys.PASTE_TARGET_PSI_ELEMENT == dataId) {
    AbstractTreeNode<?> single = JBIterable.from(selected).single();
    if (single instanceof MyRootNode) {
      VirtualFile file = ((MyRootNode)single).getVirtualFile();
      Project project = single.getProject();
      return file == null || project == null ? null : PsiManager.getInstance(project).findDirectory(file);
    }
  }
  return null;
}
 
Example #24
Source File: LRUPopupBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ListPopup forFileLanguages(@Nonnull Project project, @Nonnull String title, @Nonnull Iterable<? extends VirtualFile> files, @Nonnull PerFileMappings<Language> mappings) {
  VirtualFile[] filesCopy = VfsUtilCore.toVirtualFileArray(JBIterable.from(files).toList());
  Arrays.sort(filesCopy, (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), !o1.getFileSystem().isCaseSensitive()));
  return forFileLanguages(project, title, null, t -> {
    try {
      WriteCommandAction.writeCommandAction(project).withName(LangBundle.message("command.name.change.language")).run(() -> changeLanguageWithUndo(project, t, filesCopy, mappings));
    }
    catch (UnexpectedUndoException e) {
      LOG.error(e);
    }
  });
}
 
Example #25
Source File: ScratchTreeStructureProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Collection<AbstractTreeNode> modify(@Nonnull AbstractTreeNode parent, @Nonnull Collection<AbstractTreeNode> children, ViewSettings settings) {
  Project project = parent instanceof ProjectViewProjectNode ? parent.getProject() : null;
  if (project == null) return children;
  if (ApplicationManager.getApplication().isUnitTestMode()) return children;
  if (children.isEmpty() && JBIterable.from(RootType.getAllRootTypes()).filterMap(o -> createRootTypeNode(project, o, settings)).isEmpty()) {
    return children;
  }
  List<AbstractTreeNode> list = new ArrayList<>(children.size() + 1);
  list.addAll(children);
  list.add(new MyProjectNode(project, settings));
  return list;
}
 
Example #26
Source File: StructureViewComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Object getData(@Nonnull Key dataId) {
  if (CommonDataKeys.PSI_ELEMENT == dataId) {
    PsiElement element = getSelectedValues().filter(PsiElement.class).single();
    return element != null && element.isValid() ? element : null;
  }
  if (LangDataKeys.PSI_ELEMENT_ARRAY == dataId) {
    return PsiUtilCore.toPsiElementArray(getSelectedValues().filter(PsiElement.class).toList());
  }
  if (PlatformDataKeys.FILE_EDITOR == dataId) {
    return myFileEditor;
  }
  if (PlatformDataKeys.CUT_PROVIDER == dataId) {
    return myCopyPasteDelegator.getCutProvider();
  }
  if (PlatformDataKeys.COPY_PROVIDER == dataId) {
    return myCopyPasteDelegator.getCopyProvider();
  }
  if (PlatformDataKeys.PASTE_PROVIDER == dataId) {
    return myCopyPasteDelegator.getPasteProvider();
  }
  if (CommonDataKeys.NAVIGATABLE == dataId) {
    List<Object> list = JBIterable.of(getTree().getSelectionPaths()).map(TreePath::getLastPathComponent).map(StructureViewComponent::unwrapNavigatable).toList();
    Object[] selectedElements = list.isEmpty() ? null : ArrayUtil.toObjectArray(list);
    if (selectedElements == null || selectedElements.length == 0) return null;
    if (selectedElements[0] instanceof Navigatable) {
      return selectedElements[0];
    }
  }
  if (PlatformDataKeys.HELP_ID == dataId) {
    return getHelpID();
  }
  if (CommonDataKeys.PROJECT == dataId) {
    return myProject;
  }
  return super.getData(dataId);
}
 
Example #27
Source File: TemplateLanguageStructureViewBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static JBIterable<Language> getLanguages(@Nullable PsiFile psiFile) {
  if (psiFile == null) return JBIterable.empty();
  FileViewProvider provider = psiFile.getViewProvider();

  Language baseLanguage = provider.getBaseLanguage();
  Language dataLanguage = provider instanceof TemplateLanguageFileViewProvider ? ((TemplateLanguageFileViewProvider)provider).getTemplateDataLanguage() : null;
  return JBIterable.of(baseLanguage).append(dataLanguage).append(JBIterable.from(provider.getLanguages()).filter(o -> o != baseLanguage && o != dataLanguage));
}
 
Example #28
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static JBIterable<FoundItemDescriptor<PsiFileSystemItem>> moveDirectoriesToEnd(Iterable<FoundItemDescriptor<PsiFileSystemItem>> iterable) {
  List<FoundItemDescriptor<PsiFileSystemItem>> dirs = new ArrayList<>();
  return JBIterable.from(iterable).filter(res -> {
    if (res.getItem() instanceof PsiDirectory) {
      dirs.add(new FoundItemDescriptor<>(res.getItem(), DIRECTORY_MATCH_DEGREE));
      return false;
    }
    return true;
  }).append(dirs);
}
 
Example #29
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private JBIterable<FoundItemDescriptor<PsiFileSystemItem>> getFilesMatchingPath(@Nonnull FindSymbolParameters parameters,
                                                                                @Nonnull List<MatchResult> fileNames,
                                                                                @Nonnull DirectoryPathMatcher dirMatcher,
                                                                                @Nonnull ProgressIndicator indicator) {
  GlobalSearchScope scope = dirMatcher.narrowDown(parameters.getSearchScope());
  FindSymbolParameters adjusted = parameters.withScope(scope);

  List<List<MatchResult>> sortedNames = sortAndGroup(fileNames, Comparator.comparing(mr -> StringUtil.toLowerCase(FileUtilRt.getNameWithoutExtension(mr.elementName))));
  return JBIterable.from(sortedNames).flatMap(nameGroup -> getItemsForNames(indicator, adjusted, nameGroup));
}
 
Example #30
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
boolean processFiles(@Nonnull FindSymbolParameters parameters,
                     @Nonnull Processor<FoundItemDescriptor<?>> processor,
                     @Nonnull Ref<Boolean> hasSuggestions,
                     @Nonnull DirectoryPathMatcher dirMatcher) {
  MinusculeMatcher qualifierMatcher = getQualifiedNameMatcher(parameters.getLocalPatternName());

  List<MatchResult> matchingNames = this.matchingNames;
  if (patternSuffix.length() <= 3 && !dirMatcher.dirPattern.isEmpty()) {
    // just enumerate over files
    // otherwise there are too many names matching the remaining few letters, and querying index for all of them with a very constrained scope is expensive
    Set<String> existingNames = dirMatcher.findFileNamesMatchingIfCheap(patternSuffix.charAt(0), matcher);
    if (existingNames != null) {
      matchingNames = ContainerUtil.filter(matchingNames, mr -> existingNames.contains(mr.elementName));
    }
  }

  List<List<MatchResult>> groups = groupByMatchingDegree(!parameters.getCompletePattern().startsWith("*"), matchingNames);
  for (List<MatchResult> group : groups) {
    JBIterable<FoundItemDescriptor<PsiFileSystemItem>> filesMatchingPath = getFilesMatchingPath(parameters, group, dirMatcher, indicator);
    Iterable<FoundItemDescriptor<PsiFileSystemItem>> matchedFiles =
            parameters.getLocalPatternName().isEmpty() ? filesMatchingPath : matchQualifiers(qualifierMatcher, filesMatchingPath.map(res -> res.getItem()));

    matchedFiles = moveDirectoriesToEnd(matchedFiles);
    Processor<FoundItemDescriptor<PsiFileSystemItem>> trackingProcessor = res -> {
      hasSuggestions.set(true);
      return processor.process(res);
    };
    if (!ContainerUtil.process(matchedFiles, trackingProcessor)) {
      return false;
    }
  }

  // let the framework switch to searching outside project to display these well-matching suggestions
  // instead of worse-matching ones in project (that are very expensive to calculate)
  return hasSuggestions.get() || parameters.isSearchInLibraries() || !hasSuggestionsOutsideProject(parameters.getCompletePattern(), groups, dirMatcher);
}