protected HighlightSeverity getSeverity(@NotNull RefElement element) {
    final PsiElement psiElement = element.getPointer().getContainingFile();
    if (psiElement != null) {
      final GlobalInspectionContextImpl context = getContext();
      final String shortName = getSeverityDelegateName();
      final Tools tools = context.getTools().get(shortName);
      if (tools != null) {
        for (ScopeToolState state : tools.getTools()) {
          InspectionToolWrapper toolWrapper = state.getTool();
          if (toolWrapper == getToolWrapper()) {
            return context
                .getCurrentProfile()
                .getErrorLevel(HighlightDisplayKey.find(shortName), psiElement)
                .getSeverity();
          }
        }
      }

      final InspectionProfile profile =
          InspectionProjectProfileManager.getInstance(context.getProject()).getInspectionProfile();
      final HighlightDisplayLevel level =
          profile.getErrorLevel(HighlightDisplayKey.find(shortName), psiElement);
      return level.getSeverity();
    }
    return null;
  }
  @Override
  public void computeUsages(List<PsiLiteralExpression> targets) {
    final Project project = myTarget.getProject();
    final PsiElement parent = myTarget.getParent().getParent();
    final LocalInspectionsPass pass =
        new LocalInspectionsPass(
            myFile,
            myFile.getViewProvider().getDocument(),
            parent.getTextRange().getStartOffset(),
            parent.getTextRange().getEndOffset(),
            LocalInspectionsPass.EMPTY_PRIORITY_RANGE,
            false,
            HighlightInfoProcessor.getEmpty());
    final InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    for (PsiLiteralExpression target : targets) {
      final Object value = target.getValue();
      if (!(value instanceof String)) {
        continue;
      }
      InspectionToolWrapper toolWrapperById =
          ((InspectionProfileImpl) inspectionProfile).getToolById((String) value, target);
      if (!(toolWrapperById instanceof LocalInspectionToolWrapper)) {
        continue;
      }
      final LocalInspectionToolWrapper toolWrapper =
          ((LocalInspectionToolWrapper) toolWrapperById).createCopy();
      final InspectionManagerEx managerEx =
          (InspectionManagerEx) InspectionManager.getInstance(project);
      final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
      toolWrapper.initialize(context);
      ((RefManagerImpl) context.getRefManager()).inspectionReadActionStarted();
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      Runnable inspect =
          new Runnable() {
            @Override
            public void run() {
              pass.doInspectInBatch(
                  context,
                  managerEx,
                  Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper));
            }
          };
      if (indicator == null) {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(inspect, new ProgressIndicatorBase());
      } else {
        inspect.run();
      }

      for (HighlightInfo info : pass.getInfos()) {
        final PsiElement element =
            CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset);
        if (element != null) {
          addOccurrence(element);
        }
      }
    }
  }
 @NotNull
 @Override
 public FileStatus getElementStatus(final RefEntity element) {
   final GlobalInspectionContextImpl context = getContext();
   if (!isDisposed() && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN) {
     if (myOldProblemElements != null) {
       final boolean old = RefUtil.contains(element, myOldProblemElements.keySet());
       final boolean current = RefUtil.contains(element, getProblemElements().keySet());
       return calcStatus(old, current);
     }
   }
   return FileStatus.NOT_CHANGED;
 }
コード例 #4
0
 private InspectionTool getTool(final RefEntity refEntity) {
   InspectionTool tool = getTool();
   assert tool != null;
   final GlobalInspectionContextImpl manager = tool.getContext();
   if (manager == null) return tool;
   if (refEntity instanceof RefElement) {
     PsiElement element = ((RefElement) refEntity).getElement();
     if (element == null) return tool;
     final InspectionProfileWrapper profileWrapper =
         InspectionProjectProfileManagerImpl.getInstanceImpl(manager.getProject())
             .getProfileWrapper();
     if (profileWrapper == null) return tool;
     tool = profileWrapper.getInspectionTool(tool.getShortName(), element);
   }
   return tool;
 }
コード例 #5
0
 public FileStatus getProblemStatus(final CommonProblemDescriptor descriptor) {
   final GlobalInspectionContextImpl context = getContext();
   if (context != null && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN) {
     if (myOldProblemElements != null) {
       final Set<CommonProblemDescriptor> allAvailable = new HashSet<CommonProblemDescriptor>();
       for (CommonProblemDescriptor[] descriptors : myOldProblemElements.values()) {
         if (descriptors != null) {
           ContainerUtil.addAll(allAvailable, descriptors);
         }
       }
       final boolean old = contains(descriptor, allAvailable);
       final boolean current = contains(descriptor, getProblemToElements().keySet());
       return calcStatus(old, current);
     }
   }
   return FileStatus.NOT_CHANGED;
 }
コード例 #6
0
 public boolean updateView(boolean strict) {
   if (!strict && !myGlobalInspectionContext.getUIOptions().FILTER_RESOLVED_ITEMS) {
     myTree.repaint();
     return false;
   }
   clearTree();
   boolean resultsFound = buildTree();
   myTree.restoreExpansionAndSelection();
   return resultsFound;
 }
コード例 #7
0
 protected void appendDescriptor(
     final InspectionTool tool,
     final UserObjectContainer container,
     final InspectionPackageNode pNode,
     final boolean canPackageRepeat) {
   final GlobalInspectionContextImpl context = tool.getContext();
   final RefElementContainer refElementDescriptor = ((RefElementContainer) container);
   final RefEntity refElement = refElementDescriptor.getUserObject();
   if (context.getUIOptions().SHOW_ONLY_DIFF
       && tool.getElementStatus(refElement) == FileStatus.NOT_CHANGED) return;
   if (tool instanceof DescriptorProviderInspection) {
     final DescriptorProviderInspection descriptorProviderInspection =
         (DescriptorProviderInspection) tool;
     final CommonProblemDescriptor[] problems = refElementDescriptor.getProblemDescriptors();
     if (problems != null) {
       final RefElementNode elemNode = addNodeToParent(container, tool, pNode);
       for (CommonProblemDescriptor problem : problems) {
         if (context.getUIOptions().SHOW_ONLY_DIFF
             && descriptorProviderInspection.getProblemStatus(problem) == FileStatus.NOT_CHANGED) {
           continue;
         }
         elemNode.add(
             new ProblemDescriptionNode(refElement, problem, descriptorProviderInspection));
         if (problems.length == 1) {
           elemNode.setProblem(problems[0]);
         }
       }
     }
   } else {
     if (canPackageRepeat) {
       final Set<RefEntity> currentElements = tool.getContent().get(pNode.getPackageName());
       if (currentElements != null) {
         final Set<RefEntity> currentEntities = new HashSet<RefEntity>(currentElements);
         if (InspectionTool.contains(refElement, currentEntities)) return;
       }
     }
     addNodeToParent(container, tool, pNode);
   }
 }
コード例 #8
0
 private boolean buildTree() {
   InspectionProfile profile = myInspectionProfile;
   boolean isGroupedBySeverity = myGlobalInspectionContext.getUIOptions().GROUP_BY_SEVERITY;
   myGroups.clear();
   final Map<String, Tools> tools = myGlobalInspectionContext.getTools();
   boolean resultsFound = false;
   for (Tools currentTools : tools.values()) {
     InspectionToolWrapper defaultToolWrapper = currentTools.getDefaultState().getTool();
     final HighlightDisplayKey key = HighlightDisplayKey.find(defaultToolWrapper.getShortName());
     for (ScopeToolState state : myProvider.getTools(currentTools)) {
       InspectionToolWrapper toolWrapper = state.getTool();
       if (myProvider.checkReportedProblems(myGlobalInspectionContext, toolWrapper)) {
         addTool(
             toolWrapper,
             ((InspectionProfileImpl) profile)
                 .getErrorLevel(key, state.getScope(myProject), myProject),
             isGroupedBySeverity);
         resultsFound = true;
       }
     }
   }
   return resultsFound;
 }
コード例 #9
0
  @NotNull
  public InspectionNode addTool(
      @NotNull final InspectionToolWrapper toolWrapper,
      HighlightDisplayLevel errorLevel,
      boolean groupedBySeverity) {
    String groupName =
        toolWrapper.getGroupDisplayName().isEmpty()
            ? InspectionProfileEntry.GENERAL_GROUP_NAME
            : toolWrapper.getGroupDisplayName();
    InspectionTreeNode parentNode = getToolParentNode(groupName, errorLevel, groupedBySeverity);
    InspectionNode toolNode = new InspectionNode(toolWrapper);
    boolean showStructure = myGlobalInspectionContext.getUIOptions().SHOW_STRUCTURE;
    myProvider.appendToolNodeContent(
        myGlobalInspectionContext, toolNode, parentNode, showStructure);
    InspectionToolPresentation presentation =
        myGlobalInspectionContext.getPresentation(toolWrapper);
    toolNode =
        presentation.createToolNode(
            myGlobalInspectionContext, toolNode, myProvider, parentNode, showStructure);
    ((DefaultInspectionToolPresentation) presentation).setToolNode(toolNode);

    registerActionShortcuts(presentation);
    return toolNode;
  }
 @Override
 public boolean hasReportedProblems() {
   final GlobalInspectionContextImpl context = getContext();
   if (!isDisposed() && context.getUIOptions().SHOW_ONLY_DIFF) {
     for (CommonProblemDescriptor descriptor : getProblemToElements().keySet()) {
       if (getProblemStatus(descriptor) != FileStatus.NOT_CHANGED) {
         return true;
       }
     }
     if (myOldProblemElements != null) {
       for (RefEntity entity : myOldProblemElements.keySet()) {
         if (getElementStatus(entity) != FileStatus.NOT_CHANGED) {
           return true;
         }
       }
     }
     return false;
   }
   if (!getProblemElements().isEmpty()) return true;
   return !isDisposed()
       && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN
       && myOldProblemElements != null
       && !myOldProblemElements.isEmpty();
 }
コード例 #11
0
  private JComponent createLeftActionsToolbar() {
    final CommonActionsManager actionsManager = CommonActionsManager.getInstance();
    DefaultActionGroup group = new DefaultActionGroup();
    group.add(new RerunAction(this));
    group.add(new CloseAction());
    final TreeExpander treeExpander =
        new TreeExpander() {
          @Override
          public void expandAll() {
            TreeUtil.expandAll(myTree);
          }

          @Override
          public boolean canExpand() {
            return true;
          }

          @Override
          public void collapseAll() {
            TreeUtil.collapseAll(myTree, 0);
          }

          @Override
          public boolean canCollapse() {
            return true;
          }
        };
    group.add(actionsManager.createExpandAllAction(treeExpander, myTree));
    group.add(actionsManager.createCollapseAllAction(treeExpander, myTree));
    group.add(actionsManager.createPrevOccurenceAction(getOccurenceNavigator()));
    group.add(actionsManager.createNextOccurenceAction(getOccurenceNavigator()));
    group.add(myGlobalInspectionContext.createToggleAutoscrollAction());
    group.add(new ExportHTMLAction(this));
    group.add(new ContextHelpAction(HELP_ID));

    return createToolbar(group);
  }
コード例 #12
0
 private boolean isAutoScrollMode() {
   String activeToolWindowId = ToolWindowManager.getInstance(myProject).getActiveToolWindowId();
   return myGlobalInspectionContext.getUIOptions().AUTOSCROLL_TO_SOURCE
       && (activeToolWindowId == null || activeToolWindowId.equals(ToolWindowId.INSPECTION));
 }
コード例 #13
0
  @SuppressWarnings({"NonStaticInitializer"})
  private JComponent createRightActionsToolbar() {
    myIncludeAction =
        new AnAction(InspectionsBundle.message("inspections.result.view.include.action.text")) {
          {
            registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
          }

          @Override
          public void actionPerformed(AnActionEvent e) {
            final TreePath[] paths = myTree.getSelectionPaths();
            if (paths != null) {
              for (TreePath path : paths) {
                ((InspectionTreeNode) path.getLastPathComponent()).amnesty();
              }
            }
            updateView(false);
          }

          @Override
          public void update(final AnActionEvent e) {
            final TreePath[] paths = myTree.getSelectionPaths();
            e.getPresentation()
                .setEnabled(
                    paths != null
                        && paths.length > 0
                        && !myGlobalInspectionContext.getUIOptions().FILTER_RESOLVED_ITEMS);
          }
        };

    myExcludeAction =
        new AnAction(InspectionsBundle.message("inspections.result.view.exclude.action.text")) {
          {
            registerCustomShortcutSet(CommonShortcuts.getDelete(), myTree);
          }

          @Override
          public void actionPerformed(final AnActionEvent e) {
            final TreePath[] paths = myTree.getSelectionPaths();
            if (paths != null) {
              for (TreePath path : paths) {
                ((InspectionTreeNode) path.getLastPathComponent()).ignoreElement();
              }
            }
            updateView(false);
          }

          @Override
          public void update(final AnActionEvent e) {
            final TreePath[] path = myTree.getSelectionPaths();
            e.getPresentation().setEnabled(path != null && path.length > 0);
          }
        };

    DefaultActionGroup specialGroup = new DefaultActionGroup();
    specialGroup.add(myGlobalInspectionContext.getUIOptions().createGroupBySeverityAction(this));
    specialGroup.add(myGlobalInspectionContext.getUIOptions().createGroupByDirectoryAction(this));
    specialGroup.add(
        myGlobalInspectionContext.getUIOptions().createFilterResolvedItemsAction(this));
    specialGroup.add(
        myGlobalInspectionContext.getUIOptions().createShowOutdatedProblemsAction(this));
    specialGroup.add(myGlobalInspectionContext.getUIOptions().createShowDiffOnlyAction(this));
    specialGroup.add(new EditSettingsAction());
    specialGroup.add(new InvokeQuickFixAction(this));
    specialGroup.add(new InspectionsOptionsToolbarAction(this));
    return createToolbar(specialGroup);
  }
  @Override
  public void addProblemElement(
      final RefEntity refElement,
      boolean filterSuppressed,
      @NotNull final CommonProblemDescriptor... descriptors) {
    if (refElement == null) return;
    if (descriptors.length == 0) return;
    if (filterSuppressed) {
      if (!isOutputPathSet() || !(myToolWrapper instanceof LocalInspectionToolWrapper)) {
        synchronized (lock) {
          Map<RefEntity, CommonProblemDescriptor[]> problemElements = getProblemElements();
          CommonProblemDescriptor[] problems = problemElements.get(refElement);
          problems = problems == null ? descriptors : mergeDescriptors(problems, descriptors);
          problemElements.put(refElement, problems);
        }
        for (CommonProblemDescriptor description : descriptors) {
          getProblemToElements().put(description, refElement);
          collectQuickFixes(description.getFixes(), refElement);
        }
      } else {
        writeOutput(descriptors, refElement);
      }
    } else { // just need to collect problems
      for (CommonProblemDescriptor descriptor : descriptors) {
        getProblemToElements().put(descriptor, refElement);
      }
    }

    final GlobalInspectionContextImpl context = getContext();
    if (myToolWrapper instanceof LocalInspectionToolWrapper) {
      final InspectionResultsView view = context.getView();
      if (view == null || !(refElement instanceof RefElement)) {
        return;
      }
      UIUtil.invokeLaterIfNeeded(
          new Runnable() {
            @Override
            public void run() {
              if (!isDisposed()) {
                final InspectionNode toolNode;
                synchronized (myToolLock) {
                  if (myToolNode == null) {
                    final HighlightSeverity currentSeverity = getSeverity((RefElement) refElement);
                    toolNode =
                        view.addTool(
                            myToolWrapper,
                            HighlightDisplayLevel.find(currentSeverity),
                            context.getUIOptions().GROUP_BY_SEVERITY);
                  } else {
                    toolNode = myToolNode;
                    if (toolNode.isTooBigForOnlineRefresh()) {
                      return;
                    }
                  }
                }
                final Map<RefEntity, CommonProblemDescriptor[]> problems =
                    new HashMap<RefEntity, CommonProblemDescriptor[]>();
                problems.put(refElement, descriptors);
                final Map<String, Set<RefEntity>> contents = new HashMap<String, Set<RefEntity>>();
                final String groupName =
                    refElement.getRefManager().getGroupName((RefElement) refElement);
                Set<RefEntity> content = contents.get(groupName);
                if (content == null) {
                  content = new HashSet<RefEntity>();
                  contents.put(groupName, content);
                }
                content.add(refElement);

                view.getProvider()
                    .appendToolNodeContent(
                        context,
                        toolNode,
                        (InspectionTreeNode) toolNode.getParent(),
                        context.getUIOptions().SHOW_STRUCTURE,
                        contents,
                        problems,
                        (DefaultTreeModel) view.getTree().getModel());
                context.addView(view);
              }
            }
          });
    }
  }
 @Override
 public boolean isOldProblemsIncluded() {
   final GlobalInspectionContextImpl context = getContext();
   return context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN && getOldContent() != null;
 }
コード例 #16
0
  public CommonProblemDescriptor[] checkElement(
      @NotNull final PsiElement psiElement, InspectionManager manager, Project project) {
    final Map<PsiElement, Collection<String>> suppressedScopes =
        new THashMap<PsiElement, Collection<String>>();
    psiElement.accept(
        new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitModifierList(PsiModifierList list) {
            super.visitModifierList(list);
            final PsiElement parent = list.getParent();
            if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) {
              checkElement(parent);
            }
          }

          @Override
          public void visitComment(PsiComment comment) {
            checkElement(comment);
          }

          @Override
          public void visitClass(PsiClass aClass) {
            if (aClass == psiElement) {
              super.visitClass(aClass);
              checkElement(aClass);
            }
          }

          private void checkElement(final PsiElement owner) {
            String idsString = SuppressManager.getInstance().getSuppressedInspectionIdsIn(owner);
            if (idsString != null && idsString.length() != 0) {
              List<String> ids = StringUtil.split(idsString, ",");
              if (IGNORE_ALL
                  && (ids.contains(SuppressionUtil.ALL)
                      || ids.contains(SuppressionUtil.ALL.toLowerCase()))) return;
              Collection<String> suppressed = suppressedScopes.get(owner);
              if (suppressed == null) {
                suppressed = ids;
              } else {
                for (String id : ids) {
                  if (!suppressed.contains(id)) {
                    suppressed.add(id);
                  }
                }
              }
              suppressedScopes.put(owner, suppressed);
            }
          }
        });

    if (suppressedScopes.values().isEmpty()) return null;
    // have to visit all file from scratch since inspections can be written in any perversive way
    // including checkFile() overriding
    Collection<InspectionTool> suppressedTools = new THashSet<InspectionTool>();
    InspectionTool[] tools = getInspectionTools(psiElement, manager);
    for (Collection<String> ids : suppressedScopes.values()) {
      for (Iterator<String> iterator = ids.iterator(); iterator.hasNext(); ) {
        final String shortName = iterator.next().trim();
        for (InspectionTool tool : tools) {
          if (tool instanceof LocalInspectionToolWrapper
              && ((LocalInspectionToolWrapper) tool).getTool().getID().equals(shortName)) {
            if (!((LocalInspectionToolWrapper) tool).isUnfair()) {
              suppressedTools.add(tool);
            } else {
              iterator.remove();
              break;
            }
          } else if (tool.getShortName().equals(shortName)) {
            // ignore global unused as it won't be checked anyway
            if (!(tool instanceof LocalInspectionToolWrapper)
                && !(tool instanceof GlobalInspectionToolWrapper)) {
              iterator.remove();
              break;
            } else {
              suppressedTools.add(tool);
            }
          }
        }
      }
    }

    final AnalysisScope scope = new AnalysisScope(psiElement.getContainingFile());
    final InspectionManagerEx inspectionManagerEx =
        ((InspectionManagerEx) InspectionManager.getInstance(project));
    GlobalInspectionContextImpl globalContext = inspectionManagerEx.createNewGlobalContext(false);
    globalContext.setCurrentScope(scope);
    final RefManagerImpl refManager = ((RefManagerImpl) globalContext.getRefManager());
    refManager.inspectionReadActionStarted();
    final List<ProblemDescriptor> result;
    try {
      result = new ArrayList<ProblemDescriptor>();
      for (InspectionTool tool : suppressedTools) {
        String toolId =
            tool instanceof LocalInspectionToolWrapper
                ? ((LocalInspectionToolWrapper) tool).getTool().getID()
                : tool.getShortName();
        tool.initialize(globalContext);
        Collection<CommonProblemDescriptor> descriptors;
        if (tool instanceof LocalInspectionToolWrapper) {
          LocalInspectionToolWrapper local = (LocalInspectionToolWrapper) tool;
          if (local.isUnfair()) continue; // cant't work with passes other than LocalInspectionPass
          local.processFile(psiElement.getContainingFile(), false, manager);
          descriptors = local.getProblemDescriptors();
        } else if (tool instanceof GlobalInspectionToolWrapper) {
          GlobalInspectionToolWrapper global = (GlobalInspectionToolWrapper) tool;
          if (global.getTool().isGraphNeeded()) {
            refManager.findAllDeclarations();
          }
          global.processFile(scope, manager, globalContext, false);
          descriptors = global.getProblemDescriptors();
        } else {
          continue;
        }
        for (PsiElement suppressedScope : suppressedScopes.keySet()) {
          Collection<String> suppressedIds = suppressedScopes.get(suppressedScope);
          if (!suppressedIds.contains(toolId)) continue;
          for (CommonProblemDescriptor descriptor : descriptors) {
            if (!(descriptor instanceof ProblemDescriptor)) continue;
            PsiElement element = ((ProblemDescriptor) descriptor).getPsiElement();
            if (element == null) continue;
            PsiElement annotation =
                SuppressManager.getInstance().getElementToolSuppressedIn(element, toolId);
            if (annotation != null && PsiTreeUtil.isAncestor(suppressedScope, annotation, false)
                || annotation == null && !PsiTreeUtil.isAncestor(suppressedScope, element, false)) {
              suppressedIds.remove(toolId);
              break;
            }
          }
        }
      }
      for (PsiElement suppressedScope : suppressedScopes.keySet()) {
        Collection<String> suppressedIds = suppressedScopes.get(suppressedScope);
        for (String toolId : suppressedIds) {
          PsiMember psiMember;
          String problemLine = null;
          if (suppressedScope instanceof PsiMember) {
            psiMember = (PsiMember) suppressedScope;
          } else {
            psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class);
            final PsiStatement statement =
                PsiTreeUtil.getNextSiblingOfType(suppressedScope, PsiStatement.class);
            problemLine = statement != null ? statement.getText() : null;
          }
          if (psiMember != null && psiMember.isValid()) {
            String description =
                InspectionsBundle.message("inspection.redundant.suppression.description");
            if (myQuickFixes == null) myQuickFixes = new BidirectionalMap<String, QuickFix>();
            final String key = toolId + (problemLine != null ? ";" + problemLine : "");
            QuickFix fix = myQuickFixes.get(key);
            if (fix == null) {
              fix = new RemoveSuppressWarningAction(toolId, problemLine);
              myQuickFixes.put(key, fix);
            }
            PsiElement identifier = null;
            if (psiMember instanceof PsiMethod) {
              identifier = ((PsiMethod) psiMember).getNameIdentifier();
            } else if (psiMember instanceof PsiField) {
              identifier = ((PsiField) psiMember).getNameIdentifier();
            } else if (psiMember instanceof PsiClass) {
              identifier = ((PsiClass) psiMember).getNameIdentifier();
            }
            if (identifier == null) {
              identifier = psiMember;
            }
            result.add(
                manager.createProblemDescriptor(
                    identifier,
                    description,
                    (LocalQuickFix) fix,
                    ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                    false));
          }
        }
      }
    } finally {
      refManager.inspectionReadActionFinished();
      globalContext.close(true);
    }
    return result.toArray(new ProblemDescriptor[result.size()]);
  }