private boolean fileInRoots(VirtualFile file) {
   final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
   return file != null
       && (index.isInSourceContent(file)
           || index.isInLibraryClasses(file)
           || index.isInLibrarySource(file));
 }
  @Nullable
  @Override
  public PsiPackage resolvePackage(
      @NotNull PsiPackageManager packageManager,
      @NotNull VirtualFile virtualFile,
      @NotNull Class<? extends ModuleExtension> extensionClass,
      String qualifiedName) {
    ProjectFileIndex fileIndexFacade =
        ProjectFileIndex.SERVICE.getInstance(packageManager.getProject());
    PsiManager psiManager = PsiManager.getInstance(packageManager.getProject());
    if (fileIndexFacade.isInLibraryClasses(virtualFile)) {

      List<OrderEntry> orderEntriesForFile = fileIndexFacade.getOrderEntriesForFile(virtualFile);
      for (OrderEntry orderEntry : orderEntriesForFile) {
        Module ownerModule = orderEntry.getOwnerModule();
        ModuleExtension extension = ModuleUtilCore.getExtension(ownerModule, extensionClass);
        if (extension != null) {
          for (PsiPackageSupportProvider p : PsiPackageSupportProvider.EP_NAME.getExtensions()) {
            if (p.isSupported(extension)) {
              return p.createPackage(psiManager, packageManager, extensionClass, qualifiedName);
            }
          }
        }
      }
    }
    return null;
  }
  @Override
  public boolean contains(@NotNull VirtualFile file) {
    final ProjectFileIndex index = ProjectRootManager.getInstance(getProject()).getFileIndex();
    if (!index.isInLibrarySource(file) && !index.isInLibraryClasses(file)) {
      return false;
    }

    return someChildContainsFile(file, false);
  }
 @Nullable
 private VirtualFile getFileRoot(VirtualFile file) {
   if (myIndex.isLibraryClassFile(file)) {
     return myIndex.getClassRootForFile(file);
   }
   if (myIndex.isInContent(file)) {
     return myIndex.getSourceRootForFile(file);
   }
   if (myIndex.isInLibraryClasses(file)) {
     return myIndex.getClassRootForFile(file);
   }
   return null;
 }
  public static boolean isInDartSdkOrDartPackagesFolder(
      final Project project, final VirtualFile file) {
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    if (fileIndex.isInLibraryClasses(file)) {
      return true; // file in SDK or in custom package root
    }

    if (fileIndex.isInContent(file) && isInDartPackagesFolder(fileIndex, file)) {
      return true; // symlinked child of 'packages' folder. Real location is in user cache folder
      // for Dart packages, not in project
    }

    return false;
  }
 @Override
 public boolean process(IndexTree.Unit unit) {
   VirtualFile file = PersistentFS.getInstance().findFileById(unit.myFileId);
   if (file == null) {
     return true;
   }
   boolean process =
       isInSourceMode
           ? myProjectIndex.isInSourceContent(file)
           : myProjectIndex.isInLibraryClasses(file);
   if (process) {
     myHierarchyService.processUnit(unit);
     myProcessedSet.set(unit.myFileId);
   }
   return true;
 }
  @Override
  public boolean contains(VirtualFile file) {
    if (!super.contains(file)) {
      return false;
    }

    if (includeLibraries && StdFileTypes.CLASS == file.getFileType()) {
      return index.isInLibraryClasses(file);
    }

    if (JetPluginUtil.isKtFileInGradleProjectInWrongFolder(file, getProject())) {
      return false;
    }

    return file.getFileType().equals(JetFileType.INSTANCE)
        && (index.isInSourceContent(file) || includeLibraries && index.isInLibrarySource(file));
  }
 private boolean isInRootModel(@NotNull VirtualFile file) {
   ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(myProject);
   return index.isInContent(file)
       || index.isInLibraryClasses(file)
       || index.isInLibrarySource(file);
 }
  @Nullable
  protected DirCoverageInfo collectFolderCoverage(
      @NotNull final VirtualFile dir,
      final @NotNull CoverageDataManager dataManager,
      final Annotator annotator,
      final ProjectData projectInfo,
      boolean trackTestFolders,
      @NotNull final ProjectFileIndex index,
      @NotNull final CoverageEngine coverageEngine,
      Set<VirtualFile> visitedDirs,
      @NotNull final Map<String, String> normalizedFiles2Files) {
    if (!index.isInContent(dir)) {
      return null;
    }

    if (visitedDirs.contains(dir)) {
      return null;
    }

    if (!shouldCollectCoverageInsideLibraryDirs()) {
      if (index.isInLibrarySource(dir) || index.isInLibraryClasses(dir)) {
        return null;
      }
    }
    visitedDirs.add(dir);

    final boolean isInTestSrcContent = TestSourcesFilter.isTestSources(dir, getProject());

    // Don't count coverage for tests folders if track test folders is switched off
    if (!trackTestFolders && isInTestSrcContent) {
      return null;
    }

    final VirtualFile[] children = dataManager.doInReadActionIfProjectOpen(dir::getChildren);
    if (children == null) {
      return null;
    }

    final DirCoverageInfo dirCoverageInfo = new DirCoverageInfo();

    for (VirtualFile fileOrDir : children) {
      if (fileOrDir.isDirectory()) {
        final DirCoverageInfo childCoverageInfo =
            collectFolderCoverage(
                fileOrDir,
                dataManager,
                annotator,
                projectInfo,
                trackTestFolders,
                index,
                coverageEngine,
                visitedDirs,
                normalizedFiles2Files);

        if (childCoverageInfo != null) {
          dirCoverageInfo.totalFilesCount += childCoverageInfo.totalFilesCount;
          dirCoverageInfo.coveredFilesCount += childCoverageInfo.coveredFilesCount;
          dirCoverageInfo.totalLineCount += childCoverageInfo.totalLineCount;
          dirCoverageInfo.coveredLineCount += childCoverageInfo.coveredLineCount;
        }
      } else if (coverageEngine.coverageProjectViewStatisticsApplicableTo(fileOrDir)) {
        // let's count statistics only for ruby-based files

        final FileCoverageInfo fileInfo =
            collectBaseFileCoverage(fileOrDir, annotator, projectInfo, normalizedFiles2Files);

        if (fileInfo != null) {
          dirCoverageInfo.totalLineCount += fileInfo.totalLineCount;
          dirCoverageInfo.totalFilesCount++;

          if (fileInfo.coveredLineCount > 0) {
            dirCoverageInfo.coveredFilesCount++;
            dirCoverageInfo.coveredLineCount += fileInfo.coveredLineCount;
          }
        }
      }
    }

    // TODO - toplevelFilesCoverage - is unused variable!

    // no sense to include directories without ruby files
    if (dirCoverageInfo.totalFilesCount == 0) {
      return null;
    }

    final String dirPath = normalizeFilePath(dir.getPath());
    if (isInTestSrcContent) {
      annotator.annotateTestDirectory(dirPath, dirCoverageInfo);
    } else {
      annotator.annotateSourceDirectory(dirPath, dirCoverageInfo);
    }

    return dirCoverageInfo;
  }
  public HectorComponent(@NotNull PsiFile file) {
    super(new GridBagLayout());
    setBorder(BorderFactory.createEmptyBorder(0, 0, 7, 0));
    myFile = file;
    mySliders = new HashMap<Language, JSlider>();

    final Project project = myFile.getProject();
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final VirtualFile virtualFile = myFile.getContainingFile().getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final boolean notInLibrary =
        !fileIndex.isInLibrarySource(virtualFile) && !fileIndex.isInLibraryClasses(virtualFile)
            || fileIndex.isInContent(virtualFile);
    final FileViewProvider viewProvider = myFile.getViewProvider();
    List<Language> languages = new ArrayList<Language>(viewProvider.getLanguages());
    Collections.sort(languages, PsiUtilBase.LANGUAGE_COMPARATOR);
    for (Language language : languages) {
      @SuppressWarnings("UseOfObsoleteCollectionType")
      final Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>();
      sliderLabels.put(1, new JLabel(EditorBundle.message("hector.none.slider.label")));
      sliderLabels.put(2, new JLabel(EditorBundle.message("hector.syntax.slider.label")));
      if (notInLibrary) {
        sliderLabels.put(3, new JLabel(EditorBundle.message("hector.inspections.slider.label")));
      }

      final JSlider slider = new JSlider(SwingConstants.VERTICAL, 1, notInLibrary ? 3 : 2, 1);
      if (UIUtil.isUnderGTKLookAndFeel()) {
        // default GTK+ slider UI is way too ugly
        slider.putClientProperty("Slider.paintThumbArrowShape", true);
        slider.setUI(new BasicSliderUI(slider));
      }
      slider.setLabelTable(sliderLabels);
      UIUtil.setSliderIsFilled(slider, true);
      slider.setPaintLabels(true);
      slider.setSnapToTicks(true);
      slider.addChangeListener(
          new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
              int value = slider.getValue();
              for (Enumeration<Integer> enumeration = sliderLabels.keys();
                  enumeration.hasMoreElements(); ) {
                Integer key = enumeration.nextElement();
                sliderLabels
                    .get(key)
                    .setForeground(
                        key.intValue() <= value
                            ? UIUtil.getLabelForeground()
                            : UIUtil.getLabelDisabledForeground());
              }
            }
          });

      final PsiFile psiRoot = viewProvider.getPsi(language);
      assert psiRoot != null : "No root in " + viewProvider + " for " + language;
      slider.setValue(
          getValue(
              HighlightLevelUtil.shouldHighlight(psiRoot),
              HighlightLevelUtil.shouldInspect(psiRoot)));
      mySliders.put(language, slider);
    }

    GridBagConstraints gc =
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0,
            0,
            GridBagConstraints.NORTHWEST,
            GridBagConstraints.NONE,
            new Insets(0, 5, 0, 0),
            0,
            0);

    JPanel panel = new JPanel(new GridBagLayout());
    panel.setBorder(IdeBorderFactory.createTitledBorder(myTitle, false));
    final boolean addLabel = mySliders.size() > 1;
    if (addLabel) {
      layoutVertical(panel);
    } else {
      layoutHorizontal(panel);
    }
    gc.gridx = 0;
    gc.gridy = 0;
    gc.weighty = 1.0;
    gc.fill = GridBagConstraints.BOTH;
    add(panel, gc);

    gc.gridy = GridBagConstraints.RELATIVE;
    gc.weighty = 0;

    final HyperlinkLabel configurator = new HyperlinkLabel("Configure inspections");
    gc.insets.right = 5;
    gc.insets.bottom = 10;
    gc.weightx = 0;
    gc.fill = GridBagConstraints.NONE;
    gc.anchor = GridBagConstraints.EAST;
    add(configurator, gc);
    configurator.addHyperlinkListener(
        new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            final JBPopup hector = getOldHector();
            if (hector != null) {
              hector.cancel();
            }
            if (!DaemonCodeAnalyzer.getInstance(myFile.getProject())
                .isHighlightingAvailable(myFile)) return;
            final Project project = myFile.getProject();
            final ErrorsConfigurable errorsConfigurable =
                ErrorsConfigurable.SERVICE.createConfigurable(project);
            assert errorsConfigurable != null;
            ShowSettingsUtil.getInstance().editConfigurable(project, errorsConfigurable);
          }
        });

    gc.anchor = GridBagConstraints.WEST;
    gc.weightx = 1.0;
    gc.insets.right = 0;
    gc.fill = GridBagConstraints.HORIZONTAL;
    myAdditionalPanels = new ArrayList<HectorComponentPanel>();
    for (HectorComponentPanelsProvider provider :
        Extensions.getExtensions(HectorComponentPanelsProvider.EP_NAME, project)) {
      final HectorComponentPanel componentPanel = provider.createConfigurable(file);
      if (componentPanel != null) {
        myAdditionalPanels.add(componentPanel);
        add(componentPanel.createComponent(), gc);
        componentPanel.reset();
      }
    }
  }
 public boolean contains(@NotNull VirtualFile file) {
   return myProjectFileIndex.isInContent(file)
       || myProjectFileIndex.isInLibraryClasses(file)
       || myProjectFileIndex.isInLibrarySource(file);
 }
Exemple #12
0
 public boolean contains(final VirtualFile file) {
   final FileType fileType = file.getFileType();
   return (myDelegate == null || myDelegate.contains(file))
       && (StdFileTypes.JAVA == fileType && myIndex.isInSourceContent(file)
           || StdFileTypes.CLASS == fileType && myIndex.isInLibraryClasses(file));
 }
  // currently only one level here..
  public boolean contains(@NotNull String name, @NotNull final VirtualFile vFile) {
    final ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(myProject).getFileIndex();
    final Set<Boolean> find = new HashSet<Boolean>();
    final ContentIterator contentIterator =
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir != null && fileOrDir.getPath().equals(vFile.getPath())) {
              find.add(Boolean.TRUE);
            }
            return true;
          }
        };

    Collection<TreeItem<Pair<AbstractUrl, String>>> urls = getFavoritesListRootUrls(name);
    for (TreeItem<Pair<AbstractUrl, String>> pair : urls) {
      AbstractUrl abstractUrl = pair.getData().getFirst();
      if (abstractUrl == null) {
        continue;
      }
      final Object[] path = abstractUrl.createPath(myProject);
      if (path == null || path.length < 1 || path[0] == null) {
        continue;
      }
      Object element = path[path.length - 1];
      if (element instanceof SmartPsiElementPointer) {
        final VirtualFile virtualFile =
            PsiUtilBase.getVirtualFile(((SmartPsiElementPointer) element).getElement());
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }

      if (element instanceof PsiElement) {
        final VirtualFile virtualFile = PsiUtilBase.getVirtualFile((PsiElement) element);
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }
      if (element instanceof Module) {
        ModuleRootManager.getInstance((Module) element)
            .getFileIndex()
            .iterateContent(contentIterator);
      }
      if (element instanceof LibraryGroupElement) {
        final boolean inLibrary =
            ModuleRootManager.getInstance(((LibraryGroupElement) element).getModule())
                    .getFileIndex()
                    .isInContent(vFile)
                && projectFileIndex.isInLibraryClasses(vFile);
        if (inLibrary) {
          return true;
        }
      }
      if (element instanceof NamedLibraryElement) {
        NamedLibraryElement namedLibraryElement = (NamedLibraryElement) element;
        final VirtualFile[] files =
            namedLibraryElement.getOrderEntry().getRootFiles(OrderRootType.CLASSES);
        if (files != null && ArrayUtil.find(files, vFile) > -1) {
          return true;
        }
      }
      if (element instanceof ModuleGroup) {
        ModuleGroup group = (ModuleGroup) element;
        final Collection<Module> modules = group.modulesInGroup(myProject, true);
        for (Module module : modules) {
          ModuleRootManager.getInstance(module).getFileIndex().iterateContent(contentIterator);
        }
      }

      for (FavoriteNodeProvider provider :
          Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, myProject)) {
        if (provider.elementContainsFile(element, vFile)) {
          return true;
        }
      }

      if (!find.isEmpty()) {
        return true;
      }
    }
    return false;
  }
  @Override
  protected JComponent createCenterPanel() {
    myTitledSeparator.setText(myAnalysisNoon);

    // include test option
    myInspectTestSource.setSelected(myAnalysisOptions.ANALYZE_TEST_SOURCES);

    // module scope if applicable
    myModuleButton.setText(
        AnalysisScopeBundle.message("scope.option.module.with.mnemonic", myModuleName));
    boolean useModuleScope = false;
    if (myModuleName != null) {
      useModuleScope = myAnalysisOptions.SCOPE_TYPE == AnalysisScope.MODULE;
      myModuleButton.setSelected(myRememberScope && useModuleScope);
    }

    myModuleButton.setVisible(
        myModuleName != null && ModuleManager.getInstance(myProject).getModules().length > 1);

    boolean useUncommitedFiles = false;
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    final boolean hasVCS = !changeListManager.getAffectedFiles().isEmpty();
    if (hasVCS) {
      useUncommitedFiles = myAnalysisOptions.SCOPE_TYPE == AnalysisScope.UNCOMMITTED_FILES;
      myUncommitedFilesButton.setSelected(myRememberScope && useUncommitedFiles);
    }
    myUncommitedFilesButton.setVisible(hasVCS);

    DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(ALL);
    final List<? extends ChangeList> changeLists = changeListManager.getChangeListsCopy();
    for (ChangeList changeList : changeLists) {
      model.addElement(changeList.getName());
    }
    myChangeLists.setModel(model);
    myChangeLists.setEnabled(myUncommitedFilesButton.isSelected());
    myChangeLists.setVisible(hasVCS);

    // file/package/directory/module scope
    if (myFileName != null) {
      myFileButton.setText(myFileName);
      myFileButton.setMnemonic(myFileName.charAt(getSelectedScopeMnemonic()));
    } else {
      myFileButton.setVisible(false);
    }

    VirtualFile file = PsiUtilBase.getVirtualFile(myContext);
    ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
    boolean searchInLib =
        file != null && (fileIndex.isInLibraryClasses(file) || fileIndex.isInLibrarySource(file));

    String preselect =
        StringUtil.isEmptyOrSpaces(myAnalysisOptions.CUSTOM_SCOPE_NAME)
            ? FindSettings.getInstance().getDefaultScopeName()
            : myAnalysisOptions.CUSTOM_SCOPE_NAME;
    if (searchInLib
        && GlobalSearchScope.projectScope(myProject).getDisplayName().equals(preselect)) {
      preselect = GlobalSearchScope.allScope(myProject).getDisplayName();
    }
    if (GlobalSearchScope.allScope(myProject).getDisplayName().equals(preselect)
        && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.CUSTOM) {
      myAnalysisOptions.CUSTOM_SCOPE_NAME = preselect;
      searchInLib = true;
    }

    // custom scope
    myCustomScopeButton.setSelected(
        myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.CUSTOM);

    myScopeCombo.init(myProject, searchInLib, true, preselect);

    // correct selection
    myProjectButton.setSelected(
        myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.PROJECT
            || myFileName == null);
    myFileButton.setSelected(
        myFileName != null
            && (!myRememberScope
                || myAnalysisOptions.SCOPE_TYPE != AnalysisScope.PROJECT
                    && !useModuleScope
                    && myAnalysisOptions.SCOPE_TYPE != AnalysisScope.CUSTOM
                    && !useUncommitedFiles));

    myScopeCombo.setEnabled(myCustomScopeButton.isSelected());

    final ActionListener radioButtonPressed =
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            onScopeRadioButtonPressed();
          }
        };
    final Enumeration<AbstractButton> enumeration = myGroup.getElements();
    while (enumeration.hasMoreElements()) {
      enumeration.nextElement().addActionListener(radioButtonPressed);
    }

    // additional panel - inspection profile chooser
    JPanel wholePanel = new JPanel(new BorderLayout());
    wholePanel.add(myPanel, BorderLayout.NORTH);
    final JComponent additionalPanel = getAdditionalActionSettings(myProject);
    if (additionalPanel != null) {
      wholePanel.add(additionalPanel, BorderLayout.CENTER);
    }
    new RadioUpDownListener(
        myProjectButton,
        myModuleButton,
        myUncommitedFilesButton,
        myFileButton,
        myCustomScopeButton);
    return wholePanel;
  }