@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);
 }
Ejemplo n.º 2
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);
  }
  @NotNull
  private Set<PsiFile> getFilesForFastWordSearch() {
    String stringToFind = myFindModel.getStringToFind();
    if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
      return Collections.emptySet();
    }

    SearchScope customScope = myFindModel.getCustomScope();
    GlobalSearchScope scope =
        myPsiDirectory != null
            ? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true)
            : myModule != null
                ? myModule.getModuleContentScope()
                : customScope instanceof GlobalSearchScope
                    ? (GlobalSearchScope) customScope
                    : toGlobal(customScope);
    if (scope == null) {
      scope = ProjectScope.getContentScope(myProject);
    }

    final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>();

    if (TrigramIndex.ENABLED) {
      final Set<Integer> keys = ContainerUtil.newTroveSet();
      TrigramBuilder.processTrigrams(
          stringToFind,
          new TrigramBuilder.TrigramProcessor() {
            @Override
            public boolean execute(int value) {
              keys.add(value);
              return true;
            }
          });

      if (!keys.isEmpty()) {
        final List<VirtualFile> hits = new ArrayList<VirtualFile>();
        final GlobalSearchScope finalScope = scope;
        ApplicationManager.getApplication()
            .runReadAction(
                new Runnable() {
                  @Override
                  public void run() {
                    FileBasedIndex.getInstance()
                        .getFilesWithKey(
                            TrigramIndex.INDEX_ID,
                            keys,
                            new CommonProcessors.CollectProcessor<VirtualFile>(hits),
                            finalScope);
                  }
                });

        for (VirtualFile hit : hits) {
          if (myFileMask.value(hit)) {
            PsiFile file = findFile(hit);
            if (file != null) {
              resultFiles.add(file);
            }
          }
        }

        return resultFiles;
      }
    }

    PsiSearchHelperImpl helper =
        (PsiSearchHelperImpl) PsiSearchHelper.SERVICE.getInstance(myProject);
    helper.processFilesWithText(
        scope,
        UsageSearchContext.ANY,
        myFindModel.isCaseSensitive(),
        stringToFind,
        new Processor<VirtualFile>() {
          @Override
          public boolean process(VirtualFile file) {
            if (myFileMask.value(file)) {
              ContainerUtil.addIfNotNull(resultFiles, findFile(file));
            }
            return true;
          }
        });

    // in case our word splitting is incorrect
    CacheManager cacheManager = CacheManager.SERVICE.getInstance(myProject);
    PsiFile[] filesWithWord =
        cacheManager.getFilesWithWord(
            stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive());
    for (PsiFile file : filesWithWord) {
      if (myFileMask.value(file.getVirtualFile())) {
        resultFiles.add(file);
      }
    }

    return resultFiles;
  }