Search in sources :

Example 6 with HighlightDisplayKey

use of com.intellij.codeInsight.daemon.HighlightDisplayKey in project intellij-community by JetBrains.

the class LightInspectionTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    for (String environmentClass : getEnvironmentClasses()) {
        myFixture.addClass(environmentClass);
    }
    final InspectionProfileEntry inspection = getInspection();
    if (inspection != null) {
        myFixture.enableInspections(inspection);
        final Project project = myFixture.getProject();
        final HighlightDisplayKey displayKey = HighlightDisplayKey.find(inspection.getShortName());
        final InspectionProfileImpl currentProfile = ProjectInspectionProfileManager.getInstance(project).getCurrentProfile();
        final HighlightDisplayLevel errorLevel = currentProfile.getErrorLevel(displayKey, null);
        if (errorLevel == HighlightDisplayLevel.DO_NOT_SHOW) {
            currentProfile.setErrorLevel(displayKey, HighlightDisplayLevel.WARNING, project);
        }
    }
    Sdk sdk = ModuleRootManager.getInstance(ModuleManager.getInstance(getProject()).getModules()[0]).getSdk();
    if (JAVA_1_7.getSdk().getName().equals(sdk == null ? null : sdk.getName())) {
        PsiClass object = JavaPsiFacade.getInstance(getProject()).findClass("java.lang.Object", GlobalSearchScope.allScope(getProject()));
        assertNotNull(object);
        PsiClass component = JavaPsiFacade.getInstance(getProject()).findClass("java.awt.Component", GlobalSearchScope.allScope(getProject()));
        assertNotNull(component);
    }
}
Also used : Project(com.intellij.openapi.project.Project) InspectionProfileImpl(com.intellij.codeInspection.ex.InspectionProfileImpl) HighlightDisplayLevel(com.intellij.codeHighlighting.HighlightDisplayLevel) HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) PsiClass(com.intellij.psi.PsiClass) InspectionProfileEntry(com.intellij.codeInspection.InspectionProfileEntry) Sdk(com.intellij.openapi.projectRoots.Sdk)

Example 7 with HighlightDisplayKey

use of com.intellij.codeInsight.daemon.HighlightDisplayKey in project android by JetBrains.

the class AndroidLintInspectionToolProviderTest method checkAllLintChecksRegistered.

@SuppressWarnings("deprecation")
public static boolean checkAllLintChecksRegistered(Project project) throws Exception {
    if (ourDone) {
        return true;
    }
    ourDone = true;
    // For some reason, I can't just use
    //   AndroidLintInspectionBase.getInspectionShortNameByIssue
    // to iterate the available inspections from unit tests; at runtime this will enumerate all
    // the available inspections, but from unit tests (even when extending IdeaTestCase) it's empty.
    // So instead we take advantage of the knowledge that all our inspections are named in a particular
    // way from the lint issue id's, so we can use reflection to find the classes.
    // This won't catch cases if we declare a class there and forget to register in the plugin, but
    // it's better than nothing.
    Set<String> registered = Sets.newHashSetWithExpectedSize(200);
    Set<Issue> quickfixes = Sets.newLinkedHashSetWithExpectedSize(200);
    final LintIdeIssueRegistry fullRegistry = new LintIdeIssueRegistry();
    List<Issue> allIssues = fullRegistry.getIssues();
    for (Issue issue : allIssues) {
        if (!isRelevant(issue)) {
            continue;
        }
        String className = "com.android.tools.idea.lint.AndroidLint" + issue.getId() + "Inspection";
        try {
            Class<?> c = Class.forName(className);
            if (AndroidLintInspectionBase.class.isAssignableFrom(c) && ((c.getModifiers() & Modifier.ABSTRACT) == 0)) {
                AndroidLintInspectionBase provider = (AndroidLintInspectionBase) c.newInstance();
                registered.add(provider.getIssue().getId());
                boolean hasQuickFix = true;
                try {
                    provider.getClass().getDeclaredMethod("getQuickFixes", String.class);
                } catch (NoSuchMethodException e1) {
                    try {
                        provider.getClass().getDeclaredMethod("getQuickFixes", PsiElement.class, PsiElement.class, String.class);
                    } catch (NoSuchMethodException e2) {
                        hasQuickFix = false;
                    }
                }
                if (hasQuickFix) {
                    quickfixes.add(provider.getIssue());
                }
            }
        } catch (ClassNotFoundException ignore) {
        }
    }
    final List<Issue> missing = new ArrayList<>();
    for (Issue issue : allIssues) {
        if (!isRelevant(issue) || registered.contains(issue.getId())) {
            continue;
        }
        // When enabled, adjust this to register class based registrations
        assertFalse(LintIdeProject.SUPPORT_CLASS_FILES);
        Implementation implementation = issue.getImplementation();
        if (implementation.getScope().contains(Scope.CLASS_FILE) || implementation.getScope().contains(Scope.ALL_CLASS_FILES) || implementation.getScope().contains(Scope.JAVA_LIBRARIES)) {
            boolean isOk = false;
            for (EnumSet<Scope> analysisScope : implementation.getAnalysisScopes()) {
                if (!analysisScope.contains(Scope.CLASS_FILE) && !analysisScope.contains(Scope.ALL_CLASS_FILES) && !analysisScope.contains(Scope.JAVA_LIBRARIES)) {
                    isOk = true;
                    break;
                }
            }
            if (!isOk) {
                System.out.println("Skipping issue " + issue + " because it requires classfile analysis. Consider rewriting in IDEA.");
                continue;
            }
        }
        final String inspectionShortName = AndroidLintInspectionBase.getInspectionShortNameByIssue(project, issue);
        if (inspectionShortName == null) {
            missing.add(issue);
            continue;
        }
        // ELSE: compare severity, enabledByDefault, etc, message, etc
        final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionShortName);
        if (key == null) {
            //fail("No highlight display key for inspection " + inspectionShortName + " for issue " + issue);
            System.out.println("No highlight display key for inspection " + inspectionShortName + " for issue " + issue);
            continue;
        }
        final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
        HighlightDisplayLevel errorLevel = profile.getErrorLevel(key, null);
        Severity s;
        if (errorLevel == HighlightDisplayLevel.WARNING || errorLevel == HighlightDisplayLevel.WEAK_WARNING) {
            s = Severity.WARNING;
        } else if (errorLevel == HighlightDisplayLevel.ERROR || errorLevel == HighlightDisplayLevel.NON_SWITCHABLE_ERROR) {
            s = Severity.ERROR;
        } else if (errorLevel == HighlightDisplayLevel.DO_NOT_SHOW) {
            s = Severity.IGNORE;
        } else if (errorLevel == HighlightDisplayLevel.INFO) {
            s = Severity.INFORMATIONAL;
        } else {
            //fail("Unexpected error level " + errorLevel);
            System.out.println("Unexpected error level " + errorLevel);
            continue;
        }
        Severity expectedSeverity = issue.getDefaultSeverity();
        if (expectedSeverity == Severity.FATAL) {
            expectedSeverity = Severity.ERROR;
        }
        if (expectedSeverity != s) {
            System.out.println("Wrong severity for " + issue + "; expected " + expectedSeverity + ", got " + s);
        }
    }
    // Spit out registration information for the missing elements
    if (!missing.isEmpty()) {
        missing.sort((issue1, issue2) -> String.CASE_INSENSITIVE_ORDER.compare(issue1.getId(), issue2.getId()));
        StringBuilder sb = new StringBuilder(1000);
        sb.append("Missing registration for ").append(missing.size()).append(" issues (out of a total issue count of ").append(allIssues.size()).append(")");
        sb.append("\nAdd to android/src/META-INF/android-plugin.xml (and please try to preserve the case insensitive alphabetical order):\n");
        for (Issue issue : missing) {
            sb.append("    <globalInspection hasStaticDescription=\"true\" shortName=\"");
            sb.append(LINT_INSPECTION_PREFIX);
            String id = issue.getId();
            sb.append(id);
            sb.append("\" displayName=\"");
            sb.append(XmlUtils.toXmlAttributeValue(issue.getBriefDescription(TextFormat.TEXT)));
            sb.append("\" groupKey=\"").append(getCategoryBundleKey(issue.getCategory())).append("\" bundle=\"messages.AndroidBundle\" enabledByDefault=\"");
            sb.append(issue.isEnabledByDefault());
            sb.append("\" level=\"");
            sb.append(issue.getDefaultSeverity() == Severity.ERROR || issue.getDefaultSeverity() == Severity.FATAL ? "ERROR" : issue.getDefaultSeverity() == Severity.WARNING ? "WARNING" : "INFO");
            sb.append("\" implementationClass=\"com.android.tools.idea.lint.AndroidLint");
            sb.append(id);
            sb.append("Inspection\"/>\n");
        }
        sb.append("\nAdd to com.android.tools.idea.lint:\n");
        for (Issue issue : missing) {
            String id = issue.getId();
            String detectorClass = getDetectorClass(issue).getName();
            String detectorName = getDetectorClass(issue).getSimpleName();
            String issueName = getIssueFieldName(issue);
            String messageKey = getMessageKey(issue);
            //noinspection StringConcatenationInsideStringBufferAppend
            sb.append("/*\n" + " * Copyright (C) 2016 The Android Open Source Project\n" + " *\n" + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" + " * you may not use this file except in compliance with the License.\n" + " * You may obtain a copy of the License at\n" + " *\n" + " *      http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */\n" + "package com.android.tools.idea.lint;\n" + "\n" + "import " + detectorClass + ";\n" + "import org.jetbrains.android.inspections.lint.AndroidLintInspectionBase;\n" + "import org.jetbrains.android.util.AndroidBundle;\n" + "\n" + "public class AndroidLint" + id + "Inspection extends AndroidLintInspectionBase {\n" + "  public AndroidLint" + id + "Inspection() {\n" + "    super(AndroidBundle.message(\"android.lint.inspections." + messageKey + "\"), " + detectorName + "." + issueName + ");\n" + "  }\n" + "}\n");
        }
        sb.append("\nAdd to AndroidBundle.properties:\n");
        for (Issue issue : missing) {
            String messageKey = getMessageKey(issue);
            sb.append("android.lint.inspections.").append(messageKey).append("=").append(escapePropertyValue(getBriefDescription(issue))).append("\n");
        }
        sb.append("\nAdded registrations for ").append(missing.size()).append(" issues (out of a total issue count of ").append(allIssues.size()).append(")\n");
        System.out.println("*IF* necessary, add these category descriptors to AndroidBundle.properties:\n");
        Set<Category> categories = Sets.newHashSet();
        for (Issue issue : missing) {
            categories.add(issue.getCategory());
        }
        List<Category> sorted = Lists.newArrayList(categories);
        Collections.sort(sorted);
        for (Category category : sorted) {
            sb.append(getCategoryBundleKey(category)).append('=').append(escapePropertyValue(("Android > Lint > " + category.getFullName()).replace(":", " > "))).append("\n");
        }
        System.out.println(sb.toString());
        return false;
    } else if (LIST_ISSUES_WITH_QUICK_FIXES) {
        System.out.println("The following inspections have quickfixes (used for Reporter.java):\n");
        List<String> fields = Lists.newArrayListWithExpectedSize(quickfixes.size());
        Set<String> imports = Sets.newHashSetWithExpectedSize(quickfixes.size());
        // These two are handled by the ResourceTypeInspection's quickfixes; they're
        // not handled by lint per se, but on the command line (in HTML reports) they're
        // flagged by lint, so include them in the list
        quickfixes.add(SupportAnnotationDetector.CHECK_PERMISSION);
        quickfixes.add(SupportAnnotationDetector.MISSING_PERMISSION);
        quickfixes.add(SupportAnnotationDetector.CHECK_RESULT);
        for (Issue issue : quickfixes) {
            String detectorName = getDetectorClass(issue).getName();
            imports.add(detectorName);
            int index = detectorName.lastIndexOf('.');
            if (index != -1) {
                detectorName = detectorName.substring(index + 1);
            }
            String issueName = getIssueFieldName(issue);
            fields.add(detectorName + "." + issueName);
        }
        Collections.sort(fields);
        List<String> sortedImports = Lists.newArrayList(imports);
        Collections.sort(sortedImports);
        for (String cls : sortedImports) {
            System.out.println("import " + cls + ";");
        }
        System.out.println();
        System.out.println("sStudioFixes = Sets.newHashSet(\n    " + Joiner.on(",\n    ").join(fields) + "\n);\n");
    }
    return true;
}
Also used : HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) PsiElement(com.intellij.psi.PsiElement) HighlightDisplayLevel(com.intellij.codeHighlighting.HighlightDisplayLevel) InspectionProfile(com.intellij.codeInspection.InspectionProfile)

Example 8 with HighlightDisplayKey

use of com.intellij.codeInsight.daemon.HighlightDisplayKey in project intellij-community by JetBrains.

the class LocalInspectionsPass method registerQuickFixes.

private static void registerQuickFixes(@NotNull LocalInspectionToolWrapper tool, @NotNull ProblemDescriptor descriptor, @NotNull HighlightInfo highlightInfo, @NotNull Set<Pair<TextRange, String>> emptyActionRegistered) {
    final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
    boolean needEmptyAction = true;
    final QuickFix[] fixes = descriptor.getFixes();
    if (fixes != null && fixes.length > 0) {
        for (int k = 0; k < fixes.length; k++) {
            if (fixes[k] != null) {
                // prevent null fixes from var args
                QuickFixAction.registerQuickFixAction(highlightInfo, QuickFixWrapper.wrap(descriptor, k), key);
                needEmptyAction = false;
            }
        }
    }
    HintAction hintAction = descriptor instanceof ProblemDescriptorImpl ? ((ProblemDescriptorImpl) descriptor).getHintAction() : null;
    if (hintAction != null) {
        QuickFixAction.registerQuickFixAction(highlightInfo, hintAction, key);
        needEmptyAction = false;
    }
    if (((ProblemDescriptorBase) descriptor).getEnforcedTextAttributes() != null) {
        needEmptyAction = false;
    }
    if (needEmptyAction && emptyActionRegistered.add(Pair.create(highlightInfo.getFixTextRange(), tool.getShortName()))) {
        IntentionAction emptyIntentionAction = new EmptyIntentionAction(tool.getDisplayName());
        QuickFixAction.registerQuickFixAction(highlightInfo, emptyIntentionAction, key);
    }
}
Also used : HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) EmptyIntentionAction(com.intellij.codeInsight.intention.EmptyIntentionAction) EmptyIntentionAction(com.intellij.codeInsight.intention.EmptyIntentionAction)

Example 9 with HighlightDisplayKey

use of com.intellij.codeInsight.daemon.HighlightDisplayKey in project intellij-community by JetBrains.

the class EditSettingsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final InspectionResultsView view = getView(e);
    InspectionProfileImpl inspectionProfile = view.getCurrentProfile();
    if (view.isSingleInspectionRun()) {
        InspectionToolWrapper tool = ObjectUtils.notNull(inspectionProfile.getInspectionTool(ObjectUtils.notNull(inspectionProfile.getSingleTool()), view.getProject()));
        JComponent panel = tool.getTool().createOptionsPanel();
        if (panel != null) {
            final DialogBuilder builder = new DialogBuilder().title(InspectionsBundle.message("inspection.tool.window.inspection.dialog.title", tool.getDisplayName())).centerPanel(panel);
            builder.removeAllActions();
            builder.addOkAction();
            if (view.isRerunAvailable()) {
                builder.addActionDescriptor(new DialogBuilder.DialogActionDescriptor(InspectionsBundle.message("inspection.action.rerun"), 'R') {

                    @Override
                    protected Action createAction(DialogWrapper dialogWrapper) {
                        return new AbstractAction() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                view.rerun();
                                dialogWrapper.close(DialogWrapper.OK_EXIT_CODE);
                            }
                        };
                    }
                });
            }
            builder.show();
        } else {
            Messages.showInfoMessage(view.getProject(), InspectionsBundle.message("inspection.tool.window.dialog.no.options", tool.getDisplayName()), InspectionsBundle.message("inspection.tool.window.dialog.title"));
        }
    } else {
        final InspectionToolWrapper toolWrapper = view.getTree().getSelectedToolWrapper(false);
        if (toolWrapper != null) {
            //do not search for dead code entry point tool
            final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
            if (key != null) {
                if (new EditInspectionToolsSettingsAction(key).editToolSettings(view.getProject(), inspectionProfile)) {
                    view.updateCurrentProfile();
                }
                return;
            }
        }
        final String[] path = view.getTree().getSelectedGroupPath();
        if (EditInspectionToolsSettingsAction.editSettings(view.getProject(), inspectionProfile, (c) -> {
            if (path != null) {
                c.selectInspectionGroup(path);
            }
        })) {
            view.updateCurrentProfile();
        }
    }
}
Also used : InspectionProfileImpl(com.intellij.codeInspection.ex.InspectionProfileImpl) EditInspectionToolsSettingsAction(com.intellij.codeInspection.ex.EditInspectionToolsSettingsAction) ActionEvent(java.awt.event.ActionEvent) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) InspectionResultsView(com.intellij.codeInspection.ui.InspectionResultsView) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) EditInspectionToolsSettingsAction(com.intellij.codeInspection.ex.EditInspectionToolsSettingsAction) DialogBuilder(com.intellij.openapi.ui.DialogBuilder) InspectionToolWrapper(com.intellij.codeInspection.ex.InspectionToolWrapper)

Example 10 with HighlightDisplayKey

use of com.intellij.codeInsight.daemon.HighlightDisplayKey in project intellij-community by JetBrains.

the class KeyAwareInspectionViewAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final InspectionResultsView view = getView(e);
    final HighlightDisplayKey key = HighlightDisplayKey.find(view.getTree().getSelectedToolWrapper(true).getShortName());
    actionPerformed(view, key);
}
Also used : HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) InspectionResultsView(com.intellij.codeInspection.ui.InspectionResultsView)

Aggregations

HighlightDisplayKey (com.intellij.codeInsight.daemon.HighlightDisplayKey)42 HighlightDisplayLevel (com.intellij.codeHighlighting.HighlightDisplayLevel)15 NotNull (org.jetbrains.annotations.NotNull)12 Project (com.intellij.openapi.project.Project)10 PsiElement (com.intellij.psi.PsiElement)10 InspectionProfileImpl (com.intellij.codeInspection.ex.InspectionProfileImpl)7 Nullable (org.jetbrains.annotations.Nullable)7 InspectionProfile (com.intellij.codeInspection.InspectionProfile)6 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)5 Annotation (com.intellij.lang.annotation.Annotation)4 ArrayList (java.util.ArrayList)4 Issue (com.android.tools.lint.detector.api.Issue)3 HighlightSeverity (com.intellij.lang.annotation.HighlightSeverity)3 PsiFile (com.intellij.psi.PsiFile)3 NamedScope (com.intellij.psi.search.scope.packageSet.NamedScope)3 Element (org.jdom.Element)3 Issue (com.android.tools.klint.detector.api.Issue)2 SeverityRegistrar (com.intellij.codeInsight.daemon.impl.SeverityRegistrar)2 LocalInspectionTool (com.intellij.codeInspection.LocalInspectionTool)2 QuickFix (com.intellij.codeInspection.QuickFix)2