Java Code Examples for com.intellij.openapi.roots.ProjectRootManager

The following are top voted examples for showing how to use com.intellij.openapi.roots.ProjectRootManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: json2java4idea   File: NewClassAction.java   Source Code and License 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 2
Project: hybris-integration-intellij-idea-plugin   File: ImportProjectProgressModalWindow.java   Source Code and License 6 votes vote down vote up
private void selectSdk(@NotNull final Project project) {
    Validate.notNull(project);

    final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);

    final Sdk projectSdk = projectRootManager.getProjectSdk();

    if (null == projectSdk) {
        return;
    }

    if (StringUtils.isNotBlank(projectSdk.getVersionString())) {
        final JavaSdkVersion sdkVersion = JdkVersionUtil.getVersion(projectSdk.getVersionString());
        final LanguageLevelProjectExtension languageLevelExt = LanguageLevelProjectExtension.getInstance(project);

        if (sdkVersion.getMaxLanguageLevel() != languageLevelExt.getLanguageLevel()) {
            languageLevelExt.setLanguageLevel(sdkVersion.getMaxLanguageLevel());
        }
    }
}
 
Example 3
Project: hybris-integration-intellij-idea-plugin   File: ProjectRefreshAction.java   Source Code and License 6 votes vote down vote up
private AddModuleWizard getWizard(final Project project) throws ConfigurationException {
    final HybrisProjectImportProvider provider = getHybrisProjectImportProvider();
    final String basePath = project.getBasePath();
    final String projectName = project.getName();
    final Sdk jdk = ProjectRootManager.getInstance(project).getProjectSdk();
    final String compilerOutputUrl = CompilerProjectExtension.getInstance(project).getCompilerOutputUrl();
    final HybrisProjectSettings settings = HybrisProjectSettingsComponent.getInstance(project).getState();

    final AddModuleWizard wizard = new AddModuleWizard(null, basePath, provider) {

        protected void init() {
            // non GUI mode
        }
    };
    final WizardContext wizardContext = wizard.getWizardContext();
    wizardContext.setProjectJdk(jdk);
    wizardContext.setProjectName(projectName);
    wizardContext.setCompilerOutputDirectory(compilerOutputUrl);
    final StepSequence stepSequence = wizard.getSequence();
    for (ModuleWizardStep step : stepSequence.getAllSteps()) {
        if (step instanceof NonGuiSupport) {
            ((NonGuiSupport) step).nonGuiModeImport(settings);
        }
    }
    return wizard;
}
 
Example 4
Project: educational-plugin   File: EduIntellijCourseProjectGeneratorBase.java   Source Code and License 6 votes vote down vote up
protected void setJdk(@NotNull Project project) {
  JdkComboBox.JdkComboBoxItem selectedItem = myJdkComboBox.getSelectedItem();
  if (selectedItem instanceof JdkComboBox.SuggestedJdkItem) {
    SdkType type = ((JdkComboBox.SuggestedJdkItem)selectedItem).getSdkType();
    String path = ((JdkComboBox.SuggestedJdkItem)selectedItem).getPath();
    myModel.addSdk(type, path, sdk -> {
      myJdkComboBox.reloadModel(new JdkComboBox.ActualJdkComboBoxItem(sdk), project);
      myJdkComboBox.setSelectedJdk(sdk);
    });
  }
  try {
    myModel.apply();
  } catch (ConfigurationException e) {
    LOG.error(e);
  }
  ApplicationManager.getApplication().runWriteAction(() -> {
    ProjectRootManager.getInstance(project).setProjectSdk(myJdkComboBox.getSelectedJdk());
  });
}
 
Example 5
Project: RIBs   File: GenerateAction.java   Source Code and License 6 votes vote down vote up
/**
 * Checked whether or not this action can be enabled.
 *
 * <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 6
Project: processing-idea   File: SketchClassFilter.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isAccepted(PsiClass klass) {
    return ApplicationManager.getApplication().runReadAction((Computable<Boolean>) () -> {
        if (isSketchClass(klass)) {
            final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project);
            final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(klass);

            if (virtualFile == null) {
                return false;
            }

            return ! compilerConfiguration.isExcludedFromCompilation(virtualFile) &&
                    ! ProjectRootManager.getInstance(project)
                            .getFileIndex()
                            .isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.RESOURCES);
        }

        return false;
    });
}
 
Example 7
Project: branch-window-title   File: BranchNameFrameTitleBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Look through all open projects and see if git head symlink file is contained in it.
 */
private Project getProjectForFile(VirtualFile gitHeadFile) {
  //
  for (Project project : ProjectManager.getInstance().getOpenProjects()) {
    try {
      VirtualFile[] contentRootArray = ProjectRootManager.getInstance(project).getContentRoots();
      for (VirtualFile virtualFile : contentRootArray) {
        String expectedLoc = virtualFile.getCanonicalPath() + "/.git/HEAD";
        if (expectedLoc.equals(gitHeadFile.getCanonicalPath())) {
          return project;
        }
      }
    } catch (Exception e) {
      // ignore
    }
  }
  return null;
}
 
Example 8
Project: intellij-ce-playground   File: ThumbnailViewUI.java   Source Code and License 6 votes vote down vote up
private Set<VirtualFile> findFiles(VirtualFile file) {
    Set<VirtualFile> files = new HashSet<VirtualFile>(0);
    Project project = thumbnailView.getProject();
    if (!project.isDisposed()) {
        ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
        boolean projectIgnored = rootManager.getFileIndex().isExcluded(file);

        if (!projectIgnored && !FileTypeManager.getInstance().isFileIgnored(file)) {
            ImageFileTypeManager typeManager = ImageFileTypeManager.getInstance();
            if (file.isDirectory()) {
                if (thumbnailView.isRecursive()) {
                    files.addAll(findFiles(file.getChildren()));
                } else if (isImagesInDirectory(file)) {
                    files.add(file);
                }
            } else if (typeManager.isImage(file)) {
                files.add(file);
            }
        }
    }
    return files;
}
 
Example 9
Project: intellij-ce-playground   File: ProjectCompileScope.java   Source Code and License 6 votes vote down vote up
public boolean belongs(String url) {
  final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
  if (file != null) {
    for (FileIndex index : getFileIndices()) {
      if (index.isInSourceContent(file)) {
        return true;
      }
    }
  }
  else {
    // the file might be deleted
    for (VirtualFile root : ProjectRootManager.getInstance(myProject).getContentSourceRoots()) {
      final String rootUrl = root.getUrl();
      if (FileUtil.startsWith(url, rootUrl.endsWith("/")? rootUrl : rootUrl + "/")) {
        return true;
      }
    }
  }
  return false;
  //return !FileUtil.startsWith(url, myTempDirUrl);
}
 
Example 10
Project: intellij-ce-playground   File: IdeaGateway.java   Source Code and License 6 votes vote down vote up
public boolean isVersioned(@NotNull VirtualFile f, boolean shouldBeInContent) {
  if (!f.isInLocalFileSystem()) return false;

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

  Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
  boolean isInContent = false;
  for (Project each : openProjects) {
    if (each.isDefault()) continue;
    if (!each.isInitialized()) continue;
    if (Comparing.equal(each.getWorkspaceFile(), f)) return false;
    ProjectFileIndex index = ProjectRootManager.getInstance(each).getFileIndex();
    
    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 openProjects.length != 0 || !FileTypeManager.getInstance().isFileIgnored(f);
}
 
Example 11
Project: intellij-ce-playground   File: UsageScopeGroupingRule.java   Source Code and License 6 votes vote down vote up
@Override
public UsageGroup groupUsage(@NotNull 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 = fileIndex.isInTestSourceContent(virtualFile);
  return isInTest ? TEST : PRODUCTION;
}
 
Example 12
Project: intellij-ce-playground   File: DependenciesPanel.java   Source Code and License 6 votes vote down vote up
@Nullable
private AnalysisScope getScope() {
  final Set<PsiFile> selectedScope = getSelectedScope(myRightTree);
  Set<PsiFile> result = new HashSet<PsiFile>();
  ((PackageDependenciesNode)myLeftTree.getModel().getRoot()).fillFiles(result, !mySettings.UI_FLATTEN_PACKAGES);
  selectedScope.removeAll(result);
  if (selectedScope.isEmpty()) return null;
  List<VirtualFile> files = new ArrayList<VirtualFile>();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
  for (PsiFile psiFile : selectedScope) {
    final VirtualFile file = psiFile.getVirtualFile();
    LOG.assertTrue(file != null);
    if (fileIndex.isInContent(file)) {
      files.add(file);
    }
  }
  if (!files.isEmpty()) {
    return new AnalysisScope(myProject, files);
  }
  return null;
}
 
Example 13
Project: camel-idea-plugin   File: CamelPropertyPlaceholderSmartCompletionExtension.java   Source Code and License 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 14
Project: intellij-ce-playground   File: AlternativeSourceNotificationProvider.java   Source Code and License 6 votes vote down vote up
@Override
public String toString() {
  if (myText == null) {
    Module module = ModuleUtilCore.findModuleForPsiElement(myClass);
    if (module != null) {
      myText = module.getName();
    }
    else {
      VirtualFile virtualFile = myClass.getContainingFile().getVirtualFile();
      final ProjectFileIndex index = ProjectRootManager.getInstance(myClass.getProject()).getFileIndex();
      VirtualFile root = index.getSourceRootForFile(virtualFile);
      if (root == null) {
        root = index.getClassRootForFile(virtualFile);
      }
      if (root != null) {
        myText = root.getName();
      }
      else {
        myText = virtualFile.getPath();
      }
    }
  }
  return myText;
}
 
Example 15
Project: intellij-ce-playground   File: SimpleCoverageAnnotator.java   Source Code and License 6 votes vote down vote up
@Nullable
protected DirCoverageInfo getDirCoverageInfo(@NotNull final PsiDirectory directory,
                                             @NotNull 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 16
Project: intellij   File: BlazePythonSyncPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public void updateProjectSdk(
    Project project,
    BlazeContext context,
    ProjectViewSet projectViewSet,
    BlazeVersionData blazeVersionData,
    BlazeProjectData blazeProjectData) {
  if (!blazeProjectData.workspaceLanguageSettings.isWorkspaceType(WorkspaceType.PYTHON)) {
    return;
  }
  Sdk currentSdk = ProjectRootManager.getInstance(project).getProjectSdk();
  if (currentSdk != null && currentSdk.getSdkType() instanceof PythonSdkType) {
    return;
  }
  Sdk sdk = getOrCreatePythonSdk();
  if (sdk != null) {
    setProjectSdk(project, sdk);
  }
}
 
Example 17
Project: intellij-ce-playground   File: RefactoringScopeElementListenerProvider.java   Source Code and License 6 votes vote down vote up
private static String getQualifiedName(PsiElement element, boolean acceptQNames) {
  if (element instanceof PsiQualifiedNamedElement && acceptQNames) {
    return ((PsiQualifiedNamedElement)element).getQualifiedName();
  }
  else {
    final Project project = element.getProject();
    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
    if (virtualFile == null) {
      return null;
    }
    return FilePatternPackageSet.getRelativePath(virtualFile,
                                                 ProjectRootManager.getInstance(project).getFileIndex(),
                                                 true,
                                                 project.getBaseDir());
  }
}
 
Example 18
Project: intellij-ce-playground   File: GroovyOptimizeImportsFix.java   Source Code and License 6 votes vote down vote up
private boolean timeToOptimizeImports(GroovyFile myFile, Editor editor) {
  if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false;
  if (onTheFly && editor != null) {
    // if we stand inside import statements, do not optimize
    final VirtualFile vfile = myFile.getVirtualFile();
    if (vfile != null && ProjectRootManager.getInstance(myFile.getProject()).getFileIndex().isInSource(vfile)) {
      final GrImportStatement[] imports = myFile.getImportStatements();
      if (imports.length > 0) {
        final int offset = editor.getCaretModel().getOffset();
        if (imports[0].getTextRange().getStartOffset() <= offset && offset <= imports[imports.length - 1].getTextRange().getEndOffset()) {
          return false;
        }
      }
    }
  }

  DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(myFile.getProject());
  if (!codeAnalyzer.isHighlightingAvailable(myFile)) return false;

  if (!codeAnalyzer.isErrorAnalyzingFinished(myFile)) return false;
  Document myDocument = PsiDocumentManager.getInstance(myFile.getProject()).getDocument(myFile);
  boolean errors = containsErrorsPreventingOptimize(myFile, myDocument);

  return !errors && DaemonListeners.canChangeFileSilently(myFile);
}
 
Example 19
Project: intellij-ce-playground   File: FileDirRelativeToSourcepathMacro.java   Source Code and License 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return null;
  }
  VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
  if (file == null) {
    return null;
  }
  if (!file.isDirectory()) {
    file = file.getParent();
    if (file == null) {
      return null;
    }
  }
  final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
  if (sourceRoot == null) return null;
  return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
 
Example 20
Project: intellij-ce-playground   File: TodoTreeBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * @return read-only iterator of all valid PSI files that can have T.O.D.O items
 *         and which in specified <code>module</code>.
 * @see FileTree#getFiles(VirtualFile)
 */
public Iterator<PsiFile> getFiles(Module module) {
 if (module.isDisposed()) return Collections.<PsiFile>emptyList().iterator();
 ArrayList<PsiFile> psiFileList = new ArrayList<PsiFile>();
 final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
 final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
 for (VirtualFile virtualFile : contentRoots) {
   List<VirtualFile> files = myFileTree.getFiles(virtualFile);
   PsiManager psiManager = PsiManager.getInstance(myProject);
   for (VirtualFile file : files) {
     if (fileIndex.getModuleForFile(file) != module) continue;
     if (file.isValid()) {
       PsiFile psiFile = psiManager.findFile(file);
       if (psiFile != null) {
         psiFileList.add(psiFile);
       }
     }
   }
 }
 return psiFileList.iterator();
}
 
Example 21
Project: intellij-ce-playground   File: IncludeModuleForFileAction.java   Source Code and License 6 votes vote down vote up
@Nullable
private static VirtualFile findTarget(@NotNull AnActionEvent e, @NotNull Project project) {
  VirtualFile[] virtualFiles = VIRTUAL_FILE_ARRAY.getData(e.getDataContext());
  if (virtualFiles != null && virtualFiles.length == 1) {
    VirtualFile target = virtualFiles[0];
    if (isModuleSourceRoot(target, project) || project.getBaseDir().equals(target)) {
      // Module folders and project folder are ignored.
      return null;
    }
    ProjectFileIndex projectIndex = ProjectRootManager.getInstance(project).getFileIndex();
    if (projectIndex.isExcluded(target)) {
      // Excluded folders are ignored.
      return null;
    }
    return target;
  }
  return null;
}
 
Example 22
Project: intellij-ce-playground   File: AntTasksProvider.java   Source Code and License 6 votes vote down vote up
public static Set<LightMethodBuilder> getAntTasks(PsiElement place) {
  final PsiFile file = place.getContainingFile();
  if (!(file instanceof GroovyFile)) {
    return Collections.emptySet();
  }

  return CachedValuesManager.getManager(file.getProject()).getCachedValue(file, GANT_METHODS, new CachedValueProvider<Set<LightMethodBuilder>>() {
    @Override
    public Result<Set<LightMethodBuilder>> compute() {
      Map<String, Class> antObjects = getAntObjects((GroovyFile)file);

      final Set<LightMethodBuilder> methods = new HashSet<LightMethodBuilder>();

      final Project project = file.getProject();
      final PsiType closureType = TypesUtil.createType(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, file);
      final PsiClassType stringType = TypesUtil.createType(CommonClassNames.JAVA_LANG_STRING, file);

      for (String name : antObjects.keySet()) {
        methods.add(new AntBuilderMethod(file, name, closureType, antObjects.get(name), stringType));
      }
      return Result.create(methods, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT, ProjectRootManager.getInstance(project));
    }
  }, false);
}
 
Example 23
Project: intellij-ce-playground   File: PlatformPackageUtil.java   Source Code and License 6 votes vote down vote up
public static GlobalSearchScope adjustScope(PsiDirectory baseDir,
                                            GlobalSearchScope scope,
                                            boolean skipSourceDirsForBaseTestDirectory,
                                            boolean skipTestDirsForBaseSourceDirectory) {
  if (baseDir != null) {
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(baseDir.getProject()).getFileIndex();
    if (fileIndex.isInTestSourceContent(baseDir.getVirtualFile())) {
      if (skipSourceDirsForBaseTestDirectory) {
        return scope.intersectWith(GlobalSearchScopes.projectTestScope(baseDir.getProject()));
      }
    }
    else {
      if (skipTestDirsForBaseSourceDirectory) {
        return scope.intersectWith(GlobalSearchScopes.projectProductionScope(baseDir.getProject()));
      }
    }
  }
  return scope;
}
 
Example 24
Project: intellij-ce-playground   File: AntDomProject.java   Source Code and License 6 votes vote down vote up
@Nullable
public final Sdk getTargetJdk() {
  final XmlTag tag = getXmlTag();
  final PsiFile containingFile = tag.getContainingFile();
  final AntBuildFileImpl buildFile = (AntBuildFileImpl)AntConfigurationBase.getInstance(containingFile.getProject()).getAntBuildFile(containingFile);
  if (buildFile != null) {
    String jdkName = AntBuildFileImpl.CUSTOM_JDK_NAME.get(buildFile.getAllOptions());
    if (jdkName == null || jdkName.length() == 0) {
      jdkName = AntConfigurationImpl.DEFAULT_JDK_NAME.get(buildFile.getAllOptions());
    }
    if (jdkName != null && jdkName.length() > 0) {
      return ProjectJdkTable.getInstance().findJdk(jdkName);
    }
  }
  return ProjectRootManager.getInstance(tag.getProject()).getProjectSdk();
}
 
Example 25
Project: intellij-ce-playground   File: ProjectLocatorImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public Project guessProjectForFile(final VirtualFile file) {
  ProjectManager projectManager = ProjectManager.getInstance();
  if (projectManager == null) return null;
  final Project[] projects = projectManager.getOpenProjects();
  if (projects.length == 0) return null;
  if (projects.length == 1 && !projects[0].isDisposed()) return projects[0];

  if (file != null) {
    for (Project project : projects) {
      if (project.isInitialized() && !project.isDisposed() && ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) {
        return project;
      }
    }
  }

  return !projects[0].isDisposed() ? projects[0] : null;
}
 
Example 26
Project: intellij-ce-playground   File: NewGroovyClassAction.java   Source Code and License 6 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  super.update(e);
  Presentation presentation = e.getPresentation();
  if (!presentation.isVisible()) return;

  IdeView view = LangDataKeys.IDE_VIEW.getData(e.getDataContext());
  if (view == null) return;
  Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
  if (project == null) return;

  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  for (PsiDirectory dir : view.getDirectories()) {
    if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && checkPackageExists(dir)) {
      for (GroovySourceFolderDetector detector : GroovySourceFolderDetector.EP_NAME.getExtensions()) {
        if (detector.isGroovySourceFolder(dir)) {
          presentation.setWeight(Presentation.HIGHER_WEIGHT);
          break;
        }
      }
      return;
    }
  }
}
 
Example 27
Project: intellij-ce-playground   File: FxmlDataIndexer.java   Source Code and License 6 votes vote down vote up
@Nullable
protected Map<String, Set<String>> getIds(String content, final VirtualFile file, Project project) {
  if (!content.contains(JavaFXNamespaceProvider.JAVAFX_NAMESPACE)) {
    return null;
  }

  final Map<String, Set<String>> map = new HashMap<String, Set<String>>();
  final String path = file.getPath();
  final IXMLBuilder handler = createParseHandler(path, map);
  try {
    NanoXmlUtil.parse(new StringReader(content), handler);
  }
  catch (StopException ignore) {}
  final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
  endDocument(path, sourceRoot, map, handler);
  return map;
}
 
Example 28
Project: intellij-ce-playground   File: LegacyNewAndroidComponentAction.java   Source Code and License 6 votes vote down vote up
private static boolean isAvailable(DataContext dataContext) {
  final Module module = LangDataKeys.MODULE.getData(dataContext);
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);

  if (module == null ||
      view == null ||
      view.getDirectories().length == 0) {
    return false;
  }
  final AndroidFacet facet = AndroidFacet.getInstance(module);

  if (facet == null || facet.isGradleProject()) {
    return false;
  }
  final ProjectFileIndex projectIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final JavaDirectoryService dirService = JavaDirectoryService.getInstance();

  for (PsiDirectory dir : view.getDirectories()) {
    if (projectIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) &&
        dirService.getPackage(dir) != null) {
      return true;
    }
  }
  return false;
}
 
Example 29
Project: intellij-ce-playground   File: FilePathRelativeToSourcepathMacro.java   Source Code and License 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return null;
  }
  VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
  if (file == null) {
    return null;
  }
  final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
  if (sourceRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
 
Example 30
Project: intellij-ce-playground   File: I18nUtil.java   Source Code and License 6 votes vote down vote up
public static List<String> defaultSuggestPropertiesFiles(Project project) {
  final List<String> paths = new ArrayList<String>();
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();

  PropertiesReferenceManager.getInstance(project).processAllPropertiesFiles(new PropertiesFileProcessor() {

    @Override
    public boolean process(String baseName, PropertiesFile propertiesFile) {
      if (propertiesFile instanceof XmlPropertiesFile) {
        return true;
      }
      VirtualFile virtualFile = propertiesFile.getVirtualFile();
      if (projectFileIndex.isInContent(virtualFile)) {
        String path = FileUtil.toSystemDependentName(virtualFile.getPath());
        paths.add(path);
      }
      return true;
    }
  });
  return paths;
}
 
Example 31
Project: intellij-ce-playground   File: CreateLibraryFromFilesAction.java   Source Code and License 6 votes vote down vote up
@Override
public void update(@NotNull AnActionEvent e) {
  final Project project = getEventProject(e);
  boolean visible = false;
  if (project != null && ModuleManager.getInstance(project).getModules().length > 0) {
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    for (VirtualFile root : getRoots(e)) {
      if (!root.isInLocalFileSystem() && FileUtilRt.extensionEquals(root.getName(), "jar") && !fileIndex.isInLibraryClasses(root)) {
        visible = true;
        break;
      }
    }
  }

  Presentation presentation = e.getPresentation();
  presentation.setVisible(visible);
  presentation.setEnabled(visible);
}
 
Example 32
Project: intellij-ce-playground   File: MavenServerManager.java   Source Code and License 6 votes vote down vote up
public MavenEmbedderWrapper createEmbedder(final Project project, final boolean alwaysOnline) {
  return new MavenEmbedderWrapper(this) {
    @NotNull
    @Override
    protected MavenServerEmbedder create() throws RemoteException {
      MavenServerSettings settings = convertSettings(MavenProjectsManager.getInstance(project).getGeneralSettings());
      if (alwaysOnline && settings.isOffline()) {
        settings = settings.clone();
        settings.setOffline(false);
      }

      settings.setProjectJdk(MavenUtil.getSdkPath(ProjectRootManager.getInstance(project).getProjectSdk()));

      return MavenServerManager.this.getOrCreateWrappee().createEmbedder(settings);
    }
  };
}
 
Example 33
Project: intellij-ce-playground   File: IntroduceParameterObjectDialog.java   Source Code and License 6 votes vote down vote up
private void enableGenerateAccessors() {
  boolean existingNotALibraryClass = false;
  if (useExistingClassButton.isSelected()) {
    final PsiClass selectedClass =
      JavaPsiFacade.getInstance(myProject).findClass(existingClassField.getText(), GlobalSearchScope.projectScope(myProject));
    if (selectedClass != null) {
      final PsiFile containingFile = selectedClass.getContainingFile();
      if (containingFile != null) {
        final VirtualFile virtualFile = containingFile.getVirtualFile();
        if (virtualFile != null) {
          existingNotALibraryClass = ProjectRootManager.getInstance(myProject).getFileIndex().isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES);
        }
      }
    }
  }
  myGenerateAccessorsCheckBox.setEnabled(existingNotALibraryClass);
  myEscalateVisibilityCheckBox.setEnabled(existingNotALibraryClass);
}
 
Example 34
Project: intellij-ce-playground   File: XsltRunConfiguration.java   Source Code and License 6 votes vote down vote up
@Nullable
public Sdk getEffectiveJDK() {
    if (!XsltRunSettingsEditor.ALLOW_CHOOSING_SDK) {
        return getDefaultSdk(); 
    }
    if (myJdkChoice == JdkChoice.JDK) {
        return myJdk != null ? ProjectJdkTable.getInstance().findJdk(myJdk) : null;
    }
    Sdk jdk = null;
    final Module module = getEffectiveModule();
    if (module != null) {
        jdk = ModuleRootManager.getInstance(module).getSdk();
    }
    if (jdk == null) {
        jdk = ProjectRootManager.getInstance(getProject()).getProjectSdk();
    }
    // EA-33419
    if (jdk == null || !(jdk.getSdkType() instanceof JavaSdkType)) {
      return getDefaultSdk();
    }
    return jdk;
}
 
Example 35
Project: intellij-ce-playground   File: TestClassFilter.java   Source Code and License 6 votes vote down vote up
public boolean isAccepted(final PsiClass aClass) {
  return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      if (aClass.getQualifiedName() != null && ConfigurationUtil.PUBLIC_INSTANTIATABLE_CLASS.value(aClass) &&
          (aClass.isInheritor(myBase, true) || JUnitUtil.isTestClass(aClass))) {
        final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(getProject());
        final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(aClass);
        if (virtualFile == null) return false;
        return !compilerConfiguration.isExcludedFromCompilation(virtualFile) &&
               !ProjectRootManager.getInstance(myProject).getFileIndex().isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.RESOURCES);
      }
      return false;
    }
  });
}
 
Example 36
Project: intellij-ce-playground   File: MavenDomUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
public static Module findContainingMavenizedModule(@NotNull PsiFile psiFile) {
  VirtualFile file = psiFile.getVirtualFile();
  if (file == null) return null;

  Project project = psiFile.getProject();

  MavenProjectsManager manager = MavenProjectsManager.getInstance(project);
  if (!manager.isMavenizedProject()) return null;

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

  Module module = index.getModuleForFile(file);
  if (module == null || !manager.isMavenizedModule(module)) return null;
  return module;
}
 
Example 37
Project: intellij-ce-playground   File: AbstractFolderNode.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean containsImpl(@NotNull final VirtualFile file) {
  final PsiElement psiElement = extractPsiFromValue();
  if (psiElement == null || !psiElement.isValid()) {
    return false;
  }

  final VirtualFile valueFile = ((PsiDirectory)psiElement).getVirtualFile();
  if (!VfsUtil.isAncestor(valueFile, file, false)) {
    return false;
  }

  final Project project = psiElement.getProject();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final Module module = fileIndex.getModuleForFile(valueFile);
  if (module == null) {
    return fileIndex.getModuleForFile(file) == null;
  }

  return ModuleRootManager.getInstance(module).getFileIndex().isInContent(file);
}
 
Example 38
Project: intellij-ce-playground   File: UpdateCacheTest.java   Source Code and License 6 votes vote down vote up
public void testAddExcludeRoot() throws Exception{
  PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to initialize caches

  ProjectRootManagerEx rootManager = (ProjectRootManagerEx)ProjectRootManager.getInstance(myProject);
  final VirtualFile root = rootManager.getContentRoots()[0];

  final VirtualFile dir = root.findChild("aDir");

  new WriteCommandAction.Simple(getProject()) {
    @Override
    protected void run() throws Throwable {
      VirtualFile newFile = dir.createChildData(null, "New.java");
      VfsUtil.saveText(newFile, "class A{ Exception e;} //todo");
    }
  }.execute().throwException();

  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  PsiTestUtil.addExcludedRoot(myModule, dir);

  PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception",GlobalSearchScope.allScope(getProject()));
  assertNotNull(exceptionClass);
  checkUsages(exceptionClass, new String[]{"1.java"});
  checkTodos(new String[]{});
}
 
Example 39
Project: intellij-ce-playground   File: UpdateCacheTest.java   Source Code and License 6 votes vote down vote up
public void testSCR6066() throws Exception{
  ProjectRootManagerEx rootManager = (ProjectRootManagerEx)ProjectRootManager.getInstance(myProject);
  final VirtualFile root = rootManager.getContentRoots()[0];

  PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to initialize caches

  new WriteCommandAction.Simple(getProject()) {
    @Override
    protected void run() throws Throwable {
      VirtualFile newFile = root.createChildData(null, "New.java");
      VfsUtil.saveText(newFile, "class A{ Exception e;} //todo");
    }
  }.execute().throwException();

  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

  PsiTestUtil.addExcludedRoot(myModule, root);

  PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
  assertNotNull(exceptionClass);
  checkUsages(exceptionClass, new String[]{});
  checkTodos(new String[]{});
}
 
Example 40
Project: intellij-ce-playground   File: ProjectPaneSelectInTarget.java   Source Code and License 6 votes vote down vote up
private boolean canSelect(VirtualFile vFile) {
  if (vFile != null && vFile.isValid()) {
    ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
    if (index.getContentRootForFile(vFile, false) != null) {
      return true;
    }

    if (index.isInLibraryClasses(vFile) || index.isInLibrarySource(vFile)) {
      return true;
    }

    return Comparing.equal(vFile.getParent(), myProject.getBaseDir());
  }

  return false;
}