com.intellij.openapi.roots.ProjectFileIndex Java Examples

The following examples show how to use com.intellij.openapi.roots.ProjectFileIndex. 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: MakeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static VirtualFile getSourceRoot(CompileContext context, Module module, VirtualFile file) {
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final VirtualFile root = fileIndex.getSourceRootForFile(file);
  if (root != null) {
    return root;
  }
  // try to find among roots of generated files.
  final VirtualFile[] sourceRoots = context.getSourceRoots(module);
  for (final VirtualFile sourceRoot : sourceRoots) {
    if (fileIndex.isInSourceContent(sourceRoot)) {
      continue; // skip content source roots, need only roots for generated files
    }
    if (VfsUtil.isAncestor(sourceRoot, file, false)) {
      return sourceRoot;
    }
  }
  return null;
}
 
Example #2
Source File: GenerateAction.java    From RIBs with Apache License 2.0 6 votes vote down vote up
/**
 * Checked whether or not this action can be enabled.
 * <p>
 * <p>Requirements to be enabled: * User must be in a Java source folder.
 *
 * @param dataContext to figure out where the user is.
 * @return {@code true} when the action is available, {@code false} when the action is not
 * available.
 */
private boolean isAvailable(DataContext dataContext) {
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return false;
  }

  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null || view.getDirectories().length == 0) {
    return false;
  }

  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  for (PsiDirectory dir : view.getDirectories()) {
    if (projectFileIndex.isUnderSourceRootOfType(
        dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES)
        && checkPackageExists(dir)) {
      return true;
    }
  }

  return false;
}
 
Example #3
Source File: CamelPropertyPlaceholderSmartCompletionExtension.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet resultSet, @NotNull String[] query) {
    Project project = parameters.getOriginalFile().getManager().getProject();

    List<VirtualFile> resourceRoots = ProjectRootManager.getInstance(project).getModuleSourceRoots(JavaModuleSourceRootTypes.PRODUCTION);
    resourceRoots.addAll(ProjectRootManager.getInstance(project).getModuleSourceRoots(JavaModuleSourceRootTypes.TESTS));
    ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    for (final VirtualFile sourceRoot : resourceRoots) {
        if (sourceRoot.isValid() && sourceRoot.getCanonicalFile() != null) {
            VfsUtil.processFilesRecursively(sourceRoot.getCanonicalFile(), virtualFile -> {
                propertyCompletionProviders.stream()
                    .filter(p -> p.isValidExtension(virtualFile.getCanonicalPath()) && !projectFileIndex.isExcluded(sourceRoot))
                    .forEach(p -> p.buildResultSet(resultSet, virtualFile));
                return true;
            });
        }
    }
}
 
Example #4
Source File: HighlightLevelUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean shouldInspect(@Nonnull PsiElement psiRoot) {
  if (ApplicationManager.getApplication().isUnitTestMode()) return true;

  if (!shouldHighlight(psiRoot)) return false;
  final Project project = psiRoot.getProject();
  final VirtualFile virtualFile = psiRoot.getContainingFile().getVirtualFile();
  if (virtualFile == null || !virtualFile.isValid()) return false;

  if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false;

  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  if (ProjectScope.getLibrariesScope(project).contains(virtualFile) && !fileIndex.isInContent(virtualFile)) return false;

  if (SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile)) return false;

  final HighlightingSettingsPerFile component = HighlightingSettingsPerFile.getInstance(project);
  if (component == null) return true;

  final FileHighlightingSetting settingForRoot = component.getHighlightingSettingForRoot(psiRoot);
  return settingForRoot != FileHighlightingSetting.SKIP_INSPECTION;
}
 
Example #5
Source File: BaseIconProvider.java    From intellij-extra-icons-plugin with MIT License 6 votes vote down vote up
/**
 * Indicates if given file/folder should be ignored.
 * @param project project.
 * @param file current file or folder.
 */
private boolean isPatternIgnored(Project project, VirtualFile file) {
    SettingsService service = getSettingsService(project);
    if (service.getIgnoredPatternObj() == null || service.getIgnoredPattern() == null || service.getIgnoredPattern().isEmpty()) {
        return false;
    }
    VirtualFile contentRoot = ProjectFileIndex.SERVICE.getInstance(project).getContentRootForFile(file);
    if (contentRoot == null) {
        return false;
    }
    String relativePath = VfsUtilCore.getRelativePath(file, contentRoot);
    if (relativePath == null) {
        return false;
    }
    return service.getIgnoredPatternObj().matcher(relativePath).matches();
}
 
Example #6
Source File: PsiTypeUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static String getLocation(Project project, VirtualFile directory) {
    String location = null;
    Module module = ProjectFileIndex.getInstance(project).getModuleForFile(directory);
    if (module != null) {
        VirtualFile moduleRoot = LocalFileSystem.getInstance().findFileByIoFile(new File(module.getModuleFilePath()).getParentFile());
        String path = VfsUtilCore.getRelativePath(directory, moduleRoot);
        if (path != null) {
            location = '/' + module.getName() + '/' + path;
        }
    }
    if (location == null) {
        location = directory.getPath();
    }
    if (location.endsWith("!/")) {
        location = location.substring(0, location.length() - 2);
    }
    return location;
}
 
Example #7
Source File: ResourceFileUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static VirtualFile findResourceFile(final String name, final Module inModule) {
  final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(inModule).getContentFolderFiles(ContentFolderScopes.productionAndTest());
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(inModule.getProject()).getFileIndex();
  for (final VirtualFile sourceRoot : sourceRoots) {
    final String packagePrefix = fileIndex.getPackageNameByDirectory(sourceRoot);
    final String prefix = packagePrefix == null || packagePrefix.isEmpty() ? null : packagePrefix.replace('.', '/') + "/";
    final String relPath = prefix != null && name.startsWith(prefix) && name.length() > prefix.length() ? name.substring(prefix.length()) : name;
    final String fullPath = sourceRoot.getPath() + "/" + relPath;
    final VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(fullPath);
    if (fileByPath != null) {
      return fileByPath;
    }
  }
  return null;
}
 
Example #8
Source File: IndexTodoCacheManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public PsiFile[] getFilesWithTodoItems() {
  if (myProject.isDefault()) {
    return PsiFile.EMPTY_ARRAY;
  }
  final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
  final Set<PsiFile> allFiles = new HashSet<>();
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
  for (IndexPattern indexPattern : IndexPatternUtil.getIndexPatterns()) {
    final Collection<VirtualFile> files = fileBasedIndex.getContainingFiles(
            TodoIndex.NAME,
            new TodoIndexEntry(indexPattern.getPatternString(), indexPattern.isCaseSensitive()), GlobalSearchScope.allScope(myProject));
    ApplicationManager.getApplication().runReadAction(() -> {
      for (VirtualFile file : files) {
        if (projectFileIndex.isInContent(file)) {
          final PsiFile psiFile = myPsiManager.findFile(file);
          if (psiFile != null) {
            allFiles.add(psiFile);
          }
        }
      }
    });
  }
  return allFiles.isEmpty() ? PsiFile.EMPTY_ARRAY : PsiUtilCore.toPsiFileArray(allFiles);
}
 
Example #9
Source File: ForwardDependenciesBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void analyze() {
  final PsiManager psiManager = PsiManager.getInstance(getProject());
  psiManager.startBatchFilesProcessingMode();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex();
  try {
    getScope().accept(new PsiRecursiveElementVisitor() {
      @Override public void visitFile(final PsiFile file) {
        visit(file, fileIndex, psiManager, 0);
      }
    });
  }
  finally {
    psiManager.finishBatchFilesProcessingMode();
  }
}
 
Example #10
Source File: NewClassAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@CheckReturnValue
@VisibleForTesting
@SuppressWarnings("WeakerAccess")
static boolean isAvailable(@Nonnull AnActionEvent event) {
    final Project project = event.getProject();
    if (project == null) {
        return false;
    }

    final IdeView view = event.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
        return false;
    }

    final ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    final ProjectFileIndex fileIndex = rootManager.getFileIndex();
    final Optional<PsiDirectory> sourceDirectory = Stream.of(view.getDirectories())
            .filter(directory -> {
                final VirtualFile virtualFile = directory.getVirtualFile();
                return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES);
            })
            .findFirst();
    return sourceDirectory.isPresent();
}
 
Example #11
Source File: SimpleCoverageAnnotator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void annotate(@Nonnull final VirtualFile contentRoot,
                     @Nonnull final CoverageSuitesBundle suite,
                     final @Nonnull CoverageDataManager dataManager, @Nonnull final ProjectData data,
                     final Project project,
                     final Annotator annotator)
{
  if (!contentRoot.isValid()) {
    return;
  }

  // TODO: check name filter!!!!!

  final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();

  @SuppressWarnings("unchecked") final Set<String> files = data.getClasses().keySet();
  final Map<String, String> normalizedFiles2Files = ContainerUtil.newHashMap();
  for (final String file : files) {
    normalizedFiles2Files.put(normalizeFilePath(file), file);
  }
  collectFolderCoverage(contentRoot, dataManager, annotator, data,
                        suite.isTrackTestFolders(),
                        index,
                        suite.getCoverageEngine(),
                        ContainerUtil.<VirtualFile>newHashSet(),
                        Collections.unmodifiableMap(normalizedFiles2Files));
}
 
Example #12
Source File: SyncStatusContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link SyncStatus} for the given file, or null if it's not relevant (not in the
 * project or otherwise can't be synced).
 */
@Nullable
static SyncStatus getSyncStatus(Project project, BlazeProjectData projectData, VirtualFile vf) {
  if (!vf.isValid() || !vf.isInLocalFileSystem()) {
    return null;
  }
  boolean handledType =
      Arrays.stream(EP_NAME.getExtensions()).anyMatch(c -> c.handlesFile(projectData, vf));
  if (!handledType) {
    return null;
  }
  if (ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(vf) == null) {
    return null;
  }
  return ProjectTargetManager.getInstance(project).getSyncStatus(new File(vf.getPath()));
}
 
Example #13
Source File: MultipleJavaClassesTestContextProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link RunConfigurationContext} future setting up the relevant test target pattern,
 * if one can be found.
 */
@Nullable
private static ListenableFuture<TargetInfo> getTargetContext(PsiDirectory dir) {
  Project project = dir.getProject();
  ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project);
  if (!index.isInTestSourceContent(dir.getVirtualFile())) {
    return null;
  }
  if (BlazePackage.isBlazePackage(dir)) {
    // this case is handled by a separate run config producer
    return null;
  }
  ListenableFuture<Set<PsiClass>> classes = findAllTestClassesBeneathDirectory(dir);
  if (classes == null) {
    return null;
  }
  return Futures.transformAsync(
      classes,
      set -> set == null ? null : ReadAction.compute(() -> getTestTargetIfUnique(project, set)),
      EXECUTOR);
}
 
Example #14
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getRelativePath(@Nonnull VirtualFile virtualFile,
                                     @Nonnull ProjectFileIndex index,
                                     final boolean useFQName,
                                     VirtualFile projectBaseDir) {
  final VirtualFile contentRootForFile = index.getContentRootForFile(virtualFile);
  if (contentRootForFile != null) {
    return VfsUtilCore.getRelativePath(virtualFile, contentRootForFile, '/');
  }
  final Module module = index.getModuleForFile(virtualFile);
  if (module != null) {
    if (projectBaseDir != null) {
      if (VfsUtilCore.isAncestor(projectBaseDir, virtualFile, false)){
        final String projectRelativePath = VfsUtilCore.getRelativePath(virtualFile, projectBaseDir, '/');
        return useFQName ? projectRelativePath : projectRelativePath.substring(projectRelativePath.indexOf('/') + 1);
      }
    }
    return virtualFile.getPath();
  } else {
    return getLibRelativePath(virtualFile, index);
  }
}
 
Example #15
Source File: CopyReferenceAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static String getVirtualFileFqn(@Nonnull VirtualFile virtualFile, @Nonnull Project project) {
  final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile);
  VirtualFile logicalRootFile = logicalRoot != null ? logicalRoot.getVirtualFile() : null;
  if (logicalRootFile != null && !virtualFile.equals(logicalRootFile)) {
    return ObjectUtil.assertNotNull(VfsUtilCore.getRelativePath(virtualFile, logicalRootFile, '/'));
  }

  VirtualFile outerMostRoot = null;
  VirtualFile each = virtualFile;
  ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
  while (each != null && (each = index.getContentRootForFile(each, false)) != null) {
    outerMostRoot = each;
    each = each.getParent();
  }

  if (outerMostRoot != null && !outerMostRoot.equals(virtualFile)) {
    return ObjectUtil.assertNotNull(VfsUtilCore.getRelativePath(virtualFile, outerMostRoot, '/'));
  }

  return virtualFile.getPath();
}
 
Example #16
Source File: PackageViewPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Module[] getModulesFor(PsiDirectory dir) {
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
  final VirtualFile vFile = dir.getVirtualFile();
  final Set<Module> modules = new HashSet<Module>();
  final Module module = fileIndex.getModuleForFile(vFile);
  if (module != null) {
    modules.add(module);
  }
  if (fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile)) {
    final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(vFile);
    if (orderEntries.isEmpty()) {
      return Module.EMPTY_ARRAY;
    }
    for (OrderEntry entry : orderEntries) {
      modules.add(entry.getOwnerModule());
    }
  }
  return modules.toArray(new Module[modules.size()]);
}
 
Example #17
Source File: PackageFileAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<VirtualFile> getFilesToPackage(@Nonnull AnActionEvent e, @Nonnull Project project) {
  final VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
  if (files == null) return Collections.emptyList();

  List<VirtualFile> result = new ArrayList<VirtualFile>();
  ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final CompilerManager compilerManager = CompilerManager.getInstance(project);
  for (VirtualFile file : files) {
    if (file == null || file.isDirectory() ||
        fileIndex.isInSourceContent(file) && compilerManager.isCompilableFileType(file.getFileType())) {
      return Collections.emptyList();
    }
    final Collection<? extends Artifact> artifacts = ArtifactBySourceFileFinder.getInstance(project).findArtifacts(file);
    for (Artifact artifact : artifacts) {
      if (!StringUtil.isEmpty(artifact.getOutputPath())) {
        result.add(file);
        break;
      }
    }
  }
  return result;
}
 
Example #18
Source File: ModificationAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  if (project == null) return;
  Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
  if (element instanceof PsiClass) {
    PsiFile file = ((PsiClass) element).getContainingFile();
    if (file == null) return;
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return;
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final Module module = fileIndex.getModuleForFile(virtualFile);
    if (module == null) return;
    if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
      ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
    }
  }

}
 
Example #19
Source File: ProjectFileIndexSampleAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  final Editor editor = event.getData(CommonDataKeys.EDITOR);
  if (project == null || editor == null) return;
  Document document = editor.getDocument();
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile virtualFile = fileDocumentManager.getFile(document);
  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  if (virtualFile != null) {
    Module module = projectFileIndex.getModuleForFile(virtualFile);
    String moduleName;
    moduleName = module != null ? module.getName() : "No module defined for file";

    VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
    boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
    boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
    boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
    Messages.showInfoMessage("Module: " + moduleName + "\n" +
                             "Module content root: " + moduleContentRoot + "\n" +
                             "Is library file: " + isLibraryFile + "\n" +
                             "Is in library classes: " + isInLibraryClasses +
                             ", Is in library source: " + isInLibrarySource,
                             "Main File Info for" + virtualFile.getName());
  }
}
 
Example #20
Source File: FileUtil.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
public static String[] getProjectFiles(Project project)
{
    final List<String> files = new ArrayList<String>();
    final VirtualFile projectDirectory = project.getBaseDir();

    ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(project);

    fileIndex.iterateContentUnderDirectory(projectDirectory, file -> {
        String relativePath = file.getPath().replace(projectDirectory.getPath() + "/", "");

        //files.add(file.getName());
        if(!file.isDirectory() && !relativePath.startsWith(".idea/")) {
            files.add(relativePath);
        }

        return true;
    });

    return files.toArray(new String[files.size()]);
}
 
Example #21
Source File: IdeaGateway.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean isVersioned(@Nonnull VirtualFile f, boolean shouldBeInContent) {
  if (!f.isInLocalFileSystem()) return false;

  if (!f.isDirectory() && StringUtil.endsWith(f.getNameSequence(), ".class")) return false;

  VersionedFilterData versionedFilterData = getVersionedFilterData();

  boolean isInContent = false;
  int numberOfOpenProjects = versionedFilterData.myOpenedProjects.size();
  for (int i = 0; i < numberOfOpenProjects; ++i) {
    if (f.equals(versionedFilterData.myWorkspaceFiles.get(i))) return false;
    ProjectFileIndex index = versionedFilterData.myProjectFileIndices.get(i);

    if (index.isExcluded(f)) return false;
    isInContent |= index.isInContent(f);
  }
  if (shouldBeInContent && !isInContent) return false;

  // optimisation: FileTypeManager.isFileIgnored(f) already checked inside ProjectFileIndex.isIgnored()
  return numberOfOpenProjects != 0 || !FileTypeManager.getInstance().isFileIgnored(f);
}
 
Example #22
Source File: UsageScopeGroupingRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public UsageGroup groupUsage(@Nonnull Usage usage) {
  if (!(usage instanceof PsiElementUsage)) {
    return null;
  }
  PsiElementUsage elementUsage = (PsiElementUsage)usage;

  PsiElement element = elementUsage.getElement();
  VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);

  if (virtualFile == null) {
    return null;
  }
  ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex();
  boolean isInLib = fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile);
  if (isInLib) return LIBRARY;
  boolean isInTest = TestSourcesFilter.isTestSources(virtualFile, element.getProject());
  return isInTest ? TEST : PRODUCTION;
}
 
Example #23
Source File: SimpleCoverageAnnotator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
protected DirCoverageInfo getDirCoverageInfo(@Nonnull final PsiDirectory directory,
                                             @Nonnull final CoverageSuitesBundle currentSuite) {
  final VirtualFile dir = directory.getVirtualFile();

  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(directory.getProject()).getFileIndex();
  //final Module module = projectFileIndex.getModuleForFile(dir);

  final boolean isInTestContent = projectFileIndex.isInTestSourceContent(dir);
  if (!currentSuite.isTrackTestFolders() && isInTestContent) {
    return null;
  }

  final String path = normalizeFilePath(dir.getPath());

  return isInTestContent ? myTestDirCoverageInfos.get(path) : myDirCoverageInfos.get(path);
}
 
Example #24
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public static Module getProject(VirtualFile file) {
    for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        Module module = ProjectFileIndex.getInstance(project).getModuleForFile(file);
        if (module != null) {
            return module;
        }
    }
    return null;
}
 
Example #25
Source File: FindInProjectUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void addSourceDirectoriesFromLibraries(@Nonnull Project project, @Nonnull VirtualFile directory, @Nonnull Collection<? super VirtualFile> outSourceRoots) {
  ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project);
  // if we already are in the sources, search just in this directory only
  if (!index.isInLibraryClasses(directory)) return;
  VirtualFile classRoot = index.getClassRootForFile(directory);
  if (classRoot == null) return;
  String relativePath = VfsUtilCore.getRelativePath(directory, classRoot);
  if (relativePath == null) return;

  Collection<VirtualFile> otherSourceRoots = new THashSet<>();

  // if we are in the library sources, return (to search in this directory only)
  // otherwise, if we outside sources or in a jar directory, add directories from other source roots
  searchForOtherSourceDirs:
  for (OrderEntry entry : index.getOrderEntriesForFile(directory)) {
    if (entry instanceof LibraryOrderEntry) {
      Library library = ((LibraryOrderEntry)entry).getLibrary();
      if (library == null) continue;
      // note: getUrls() returns jar directories too
      String[] sourceUrls = library.getUrls(OrderRootType.SOURCES);
      for (String sourceUrl : sourceUrls) {
        if (VfsUtilCore.isEqualOrAncestor(sourceUrl, directory.getUrl())) {
          // already in this library sources, no need to look for another source root
          otherSourceRoots.clear();
          break searchForOtherSourceDirs;
        }
        // otherwise we may be inside the jar file in a library which is configured as a jar directory
        // in which case we have no way to know whether this is a source jar or classes jar - so try to locate the source jar
      }
    }
    for (VirtualFile sourceRoot : entry.getFiles(OrderRootType.SOURCES)) {
      VirtualFile sourceFile = sourceRoot.findFileByRelativePath(relativePath);
      if (sourceFile != null) {
        otherSourceRoots.add(sourceFile);
      }
    }
  }
  outSourceRoots.addAll(otherSourceRoots);
}
 
Example #26
Source File: SummaryNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void createModuleTodoNodeForFile(ArrayList<? super AbstractTreeNode> children, ProjectFileIndex projectFileIndex, VirtualFile virtualFile) {
  Module module = projectFileIndex.getModuleForFile(virtualFile);
  if (module != null) {
    ModuleToDoNode moduleToDoNode = new ModuleToDoNode(getProject(), module, myBuilder);
    if (!children.contains(moduleToDoNode)) {
      children.add(moduleToDoNode);
    }
  }
}
 
Example #27
Source File: GotoFileCellRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static VirtualFile getAnyRoot(@Nonnull VirtualFile virtualFile, @Nonnull Project project) {
  ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project);
  VirtualFile root = index.getContentRootForFile(virtualFile);
  if (root == null) root = index.getClassRootForFile(virtualFile);
  if (root == null) root = index.getSourceRootForFile(virtualFile);
  return root;
}
 
Example #28
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String getLibRelativePath(final VirtualFile virtualFile, final ProjectFileIndex index) {
  StringBuilder relativePath = new StringBuilder(100);
  VirtualFile directory = virtualFile;
  while (directory != null && index.isInLibraryClasses(directory)) {
    relativePath.insert(0, '/');
    relativePath.insert(0, directory.getName());
    directory = directory.getParent();
  }
  return relativePath.toString();
}
 
Example #29
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean contains(VirtualFile file, NamedScopesHolder holder) {
  Project project = holder.getProject();
  ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  return file != null && fileMatcher(file, fileIndex, holder.getProjectBaseDir()) &&
         matchesModule(myModuleGroupPattern, myModulePattern, file, fileIndex);
}
 
Example #30
Source File: ProjectRootsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean isOutsideSourceRoot(@Nullable PsiFile psiFile) {
  if (psiFile == null) return false;
  if (psiFile instanceof PsiCodeFragment) return false;
  final VirtualFile file = psiFile.getVirtualFile();
  if (file == null) return false;
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(psiFile.getProject()).getFileIndex();
  return !projectFileIndex.isInSource(file) && !projectFileIndex.isInLibraryClasses(file);
}