Search in sources :

Example 31 with EditorColorsManager

use of com.intellij.openapi.editor.colors.EditorColorsManager in project intellij-community by JetBrains.

the class InlineLocalHandler method invoke.

/**
   * should be called in AtomicAction
   */
public static void invoke(@NotNull final Project project, final Editor editor, final PsiLocalVariable local, PsiReferenceExpression refExpr) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, local))
        return;
    final HighlightManager highlightManager = HighlightManager.getInstance(project);
    final String localName = local.getName();
    final List<PsiElement> innerClassesWithUsages = Collections.synchronizedList(new ArrayList<PsiElement>());
    final List<PsiElement> innerClassUsages = Collections.synchronizedList(new ArrayList<PsiElement>());
    final PsiClass containingClass = PsiTreeUtil.getParentOfType(local, PsiClass.class);
    final Query<PsiReference> query = ReferencesSearch.search(local);
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
        if (query.findFirst() == null) {
            LOG.assertTrue(refExpr == null);
            ApplicationManager.getApplication().invokeLater(() -> {
                String message = RefactoringBundle.message("variable.is.never.used", localName);
                CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
            }, ModalityState.NON_MODAL);
            return;
        }
        query.forEach(psiReference -> {
            final PsiElement element = psiReference.getElement();
            PsiElement innerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class, PsiLambdaExpression.class);
            while (innerClass != containingClass && innerClass != null) {
                final PsiElement parentPsiClass = PsiTreeUtil.getParentOfType(innerClass.getParent(), PsiClass.class, PsiLambdaExpression.class);
                if (parentPsiClass == containingClass) {
                    if (innerClass instanceof PsiLambdaExpression) {
                        if (PsiTreeUtil.isAncestor(innerClass, local, false)) {
                            innerClassesWithUsages.add(element);
                            innerClass = parentPsiClass;
                            continue;
                        }
                    }
                    innerClassesWithUsages.add(innerClass);
                    innerClassUsages.add(element);
                }
                innerClass = parentPsiClass;
            }
            return true;
        });
    }, "Find Usages", true, project)) {
        return;
    }
    final PsiCodeBlock containerBlock = PsiTreeUtil.getParentOfType(local, PsiCodeBlock.class);
    if (containerBlock == null) {
        final String message = RefactoringBundle.getCannotRefactorMessage("Variable is declared outside a code block");
        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
        return;
    }
    final PsiExpression defToInline = getDefToInline(local, innerClassesWithUsages.isEmpty() ? refExpr : innerClassesWithUsages.get(0), containerBlock);
    if (defToInline == null) {
        final String key = refExpr == null ? "variable.has.no.initializer" : "variable.has.no.dominating.definition";
        String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message(key, localName));
        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
        return;
    }
    List<PsiElement> refsToInlineList = new ArrayList<>();
    Collections.addAll(refsToInlineList, DefUseUtil.getRefs(containerBlock, local, defToInline));
    for (PsiElement innerClassUsage : innerClassUsages) {
        if (!refsToInlineList.contains(innerClassUsage)) {
            refsToInlineList.add(innerClassUsage);
        }
    }
    if (refsToInlineList.size() == 0) {
        String message = RefactoringBundle.message("variable.is.never.used.before.modification", localName);
        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
        return;
    }
    final Ref<Boolean> inlineAll = new Ref<>(true);
    if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) {
        int occurrencesCount = refsToInlineList.size();
        if (refExpr != null && occurrencesCount > 1 || EditorSettingsExternalizable.getInstance().isShowInlineLocalDialog()) {
            final InlineLocalDialog inlineLocalDialog = new InlineLocalDialog(project, local, refExpr, occurrencesCount);
            if (!inlineLocalDialog.showAndGet()) {
                WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
                return;
            }
            if (refExpr != null && inlineLocalDialog.isInlineThis()) {
                refsToInlineList = Collections.singletonList(refExpr);
                inlineAll.set(false);
            }
        }
    }
    final PsiElement[] refsToInline = PsiUtilCore.toPsiElementArray(refsToInlineList);
    final EditorColorsManager manager = EditorColorsManager.getInstance();
    final TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
    if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) {
        // TODO : check if initializer uses fieldNames that possibly will be hidden by other
        // locals with the same names after inlining
        highlightManager.addOccurrenceHighlights(editor, refsToInline, attributes, true, null);
    }
    if (refExpr != null && PsiUtil.isAccessedForReading(refExpr) && ArrayUtil.find(refsToInline, refExpr) < 0) {
        final PsiElement[] defs = DefUseUtil.getDefs(containerBlock, local, refExpr);
        LOG.assertTrue(defs.length > 0);
        highlightManager.addOccurrenceHighlights(editor, defs, attributes, true, null);
        String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName));
        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
        WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
        return;
    }
    PsiTryStatement tryStatement = PsiTreeUtil.getParentOfType(defToInline, PsiTryStatement.class);
    if (tryStatement != null) {
        if (ExceptionUtil.getThrownExceptions(defToInline).isEmpty()) {
            tryStatement = null;
        }
    }
    PsiFile workingFile = local.getContainingFile();
    for (PsiElement ref : refsToInline) {
        final PsiFile otherFile = ref.getContainingFile();
        if (!otherFile.equals(workingFile)) {
            String message = RefactoringBundle.message("variable.is.referenced.in.multiple.files", localName);
            CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
            return;
        }
        if (tryStatement != null && !PsiTreeUtil.isAncestor(tryStatement, ref, false)) {
            CommonRefactoringUtil.showErrorHint(project, editor, "Unable to inline outside try/catch statement", REFACTORING_NAME, HelpID.INLINE_VARIABLE);
            return;
        }
    }
    for (final PsiElement ref : refsToInline) {
        final PsiElement[] defs = DefUseUtil.getDefs(containerBlock, local, ref);
        boolean isSameDefinition = true;
        for (PsiElement def : defs) {
            isSameDefinition &= isSameDefinition(def, defToInline);
        }
        if (!isSameDefinition) {
            highlightManager.addOccurrenceHighlights(editor, defs, writeAttributes, true, null);
            highlightManager.addOccurrenceHighlights(editor, new PsiElement[] { ref }, attributes, true, null);
            String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing.and.used.with.inlined", localName));
            CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
            WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
            return;
        }
    }
    final PsiElement writeAccess = checkRefsInAugmentedAssignmentOrUnaryModified(refsToInline, defToInline);
    if (writeAccess != null) {
        HighlightManager.getInstance(project).addOccurrenceHighlights(editor, new PsiElement[] { writeAccess }, writeAttributes, true, null);
        String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName));
        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_VARIABLE);
        WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
        return;
    }
    final Runnable runnable = () -> {
        final String refactoringId = "refactoring.inline.local.variable";
        try {
            SmartPsiElementPointer<PsiExpression>[] exprs = new SmartPsiElementPointer[refsToInline.length];
            RefactoringEventData beforeData = new RefactoringEventData();
            beforeData.addElements(refsToInline);
            project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData);
            WriteAction.run(() -> {
                final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project);
                for (int idx = 0; idx < refsToInline.length; idx++) {
                    PsiJavaCodeReferenceElement refElement = (PsiJavaCodeReferenceElement) refsToInline[idx];
                    exprs[idx] = pointerManager.createSmartPsiElementPointer(InlineUtil.inlineVariable(local, defToInline, refElement));
                }
                if (inlineAll.get()) {
                    if (!isInliningVariableInitializer(defToInline)) {
                        defToInline.getParent().delete();
                    } else {
                        defToInline.delete();
                    }
                }
            });
            if (inlineAll.get() && ReferencesSearch.search(local).findFirst() == null && editor != null) {
                QuickFixFactory.getInstance().createRemoveUnusedVariableFix(local).invoke(project, editor, local.getContainingFile());
            }
            if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) {
                highlightManager.addOccurrenceHighlights(editor, ContainerUtil.convert(exprs, new PsiExpression[refsToInline.length], pointer -> pointer.getElement()), attributes, true, null);
                WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
            }
            WriteAction.run(() -> {
                for (SmartPsiElementPointer<PsiExpression> expr : exprs) {
                    InlineUtil.tryToInlineArrayCreationForVarargs(expr.getElement());
                }
            });
        } finally {
            final RefactoringEventData afterData = new RefactoringEventData();
            afterData.addElement(containingClass);
            project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData);
        }
    };
    CommandProcessor.getInstance().executeCommand(project, () -> PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(runnable), RefactoringBundle.message("inline.command", localName), null);
}
Also used : DefUseUtil(com.intellij.psi.controlFlow.DefUseUtil) WriteAction(com.intellij.openapi.application.WriteAction) ArrayUtil(com.intellij.util.ArrayUtil) ModalityState(com.intellij.openapi.application.ModalityState) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager) RefactoringBundle(com.intellij.refactoring.RefactoringBundle) RefactoringEventListener(com.intellij.refactoring.listeners.RefactoringEventListener) ContainerUtil(com.intellij.util.containers.ContainerUtil) ArrayList(java.util.ArrayList) Query(com.intellij.util.Query) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) EditorSettingsExternalizable(com.intellij.openapi.editor.ex.EditorSettingsExternalizable) Project(com.intellij.openapi.project.Project) PsiUtil(com.intellij.psi.util.PsiUtil) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) Logger(com.intellij.openapi.diagnostic.Logger) HelpID(com.intellij.refactoring.HelpID) ProgressManager(com.intellij.openapi.progress.ProgressManager) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) WindowManager(com.intellij.openapi.wm.WindowManager) QuickFixFactory(com.intellij.codeInsight.intention.QuickFixFactory) InlineUtil(com.intellij.refactoring.util.InlineUtil) Editor(com.intellij.openapi.editor.Editor) CommandProcessor(com.intellij.openapi.command.CommandProcessor) CommonRefactoringUtil(com.intellij.refactoring.util.CommonRefactoringUtil) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) EditorColors(com.intellij.openapi.editor.colors.EditorColors) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) RefactoringUtil(com.intellij.refactoring.util.RefactoringUtil) TargetElementUtil(com.intellij.codeInsight.TargetElementUtil) ApplicationManager(com.intellij.openapi.application.ApplicationManager) com.intellij.psi(com.intellij.psi) ExceptionUtil(com.intellij.codeInsight.ExceptionUtil) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) PostprocessReformattingAspect(com.intellij.psi.impl.source.PostprocessReformattingAspect) Collections(java.util.Collections) ArrayList(java.util.ArrayList) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) Ref(com.intellij.openapi.util.Ref)

Example 32 with EditorColorsManager

use of com.intellij.openapi.editor.colors.EditorColorsManager in project intellij-community by JetBrains.

the class ExternalAnnotationsManagerImpl method chooseAnnotationsPlace.

@Override
@NotNull
public AnnotationPlace chooseAnnotationsPlace(@NotNull final PsiElement element) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    //element just created
    if (!element.isPhysical())
        return AnnotationPlace.IN_CODE;
    if (!element.getManager().isInProject(element))
        return AnnotationPlace.EXTERNAL;
    final Project project = myPsiManager.getProject();
    //otherwise external annotations should be read-only
    if (CodeStyleSettingsManager.getSettings(project).USE_EXTERNAL_ANNOTATIONS) {
        final PsiFile containingFile = element.getContainingFile();
        final VirtualFile virtualFile = containingFile.getVirtualFile();
        LOG.assertTrue(virtualFile != null);
        final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
        if (!entries.isEmpty()) {
            for (OrderEntry entry : entries) {
                if (!(entry instanceof ModuleOrderEntry)) {
                    if (AnnotationOrderRootType.getUrls(entry).length > 0) {
                        return AnnotationPlace.EXTERNAL;
                    }
                    break;
                }
            }
        }
        final MyExternalPromptDialog dialog = ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment() ? null : new MyExternalPromptDialog(project);
        if (dialog != null && dialog.isToBeShown()) {
            final PsiElement highlightElement = element instanceof PsiNameIdentifierOwner ? ((PsiNameIdentifierOwner) element).getNameIdentifier() : element.getNavigationElement();
            LOG.assertTrue(highlightElement != null);
            final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
            final List<RangeHighlighter> highlighters = new ArrayList<>();
            final boolean highlight = editor != null && editor.getDocument() == PsiDocumentManager.getInstance(project).getDocument(containingFile);
            try {
                if (highlight) {
                    //do not highlight for batch inspections
                    final EditorColorsManager colorsManager = EditorColorsManager.getInstance();
                    final TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
                    final TextRange textRange = highlightElement.getTextRange();
                    HighlightManager.getInstance(project).addRangeHighlight(editor, textRange.getStartOffset(), textRange.getEndOffset(), attributes, true, highlighters);
                    final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(textRange.getStartOffset());
                    editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.CENTER);
                }
                dialog.show();
                if (dialog.getExitCode() == 2) {
                    return AnnotationPlace.EXTERNAL;
                } else if (dialog.getExitCode() == 1) {
                    return AnnotationPlace.NOWHERE;
                }
            } finally {
                if (highlight) {
                    HighlightManager.getInstance(project).removeSegmentHighlighter(editor, highlighters.get(0));
                }
            }
        } else if (dialog != null) {
            dialog.close(DialogWrapper.OK_EXIT_CODE);
        }
    }
    return AnnotationPlace.IN_CODE;
}
Also used : LogicalPosition(com.intellij.openapi.editor.LogicalPosition) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager) Project(com.intellij.openapi.project.Project) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) Editor(com.intellij.openapi.editor.Editor) NotNull(org.jetbrains.annotations.NotNull)

Example 33 with EditorColorsManager

use of com.intellij.openapi.editor.colors.EditorColorsManager in project intellij-community by JetBrains.

the class IntroduceVariableBase method highlightReplacedOccurences.

protected static void highlightReplacedOccurences(Project project, Editor editor, PsiElement[] replacedOccurences) {
    if (editor == null)
        return;
    if (ApplicationManager.getApplication().isUnitTestMode())
        return;
    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager colorsManager = EditorColorsManager.getInstance();
    TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    highlightManager.addOccurrenceHighlights(editor, replacedOccurences, attributes, true, null);
    WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
Also used : HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager)

Example 34 with EditorColorsManager

use of com.intellij.openapi.editor.colors.EditorColorsManager in project intellij-community by JetBrains.

the class GrIntroduceHandlerBase method showDialog.

@Nullable
private Settings showDialog(@NotNull GrIntroduceContext context) {
    // Add occurrences highlighting
    ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
    HighlightManager highlightManager = null;
    if (context.getEditor() != null) {
        highlightManager = HighlightManager.getInstance(context.getProject());
        EditorColorsManager colorsManager = EditorColorsManager.getInstance();
        TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
        if (context.getOccurrences().length > 1) {
            highlightManager.addOccurrenceHighlights(context.getEditor(), context.getOccurrences(), attributes, true, highlighters);
        }
    }
    GrIntroduceDialog<Settings> dialog = getDialog(context);
    dialog.show();
    if (dialog.isOK()) {
        if (context.getEditor() != null) {
            for (RangeHighlighter highlighter : highlighters) {
                highlightManager.removeSegmentHighlighter(context.getEditor(), highlighter);
            }
        }
        return dialog.getSettings();
    } else {
        if (context.getOccurrences().length > 1) {
            WindowManager.getInstance().getStatusBar(context.getProject()).setInfo(GroovyRefactoringBundle.message("press.escape.to.remove.the.highlighting"));
        }
    }
    return null;
}
Also used : RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager) Nullable(org.jetbrains.annotations.Nullable)

Example 35 with EditorColorsManager

use of com.intellij.openapi.editor.colors.EditorColorsManager in project intellij-community by JetBrains.

the class GroovyRefactoringUtil method highlightOccurrencesByRanges.

public static void highlightOccurrencesByRanges(Project project, Editor editor, TextRange[] ranges) {
    if (editor == null)
        return;
    ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager colorsManager = EditorColorsManager.getInstance();
    TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    for (TextRange range : ranges) {
        highlightManager.addRangeHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, false, highlighters);
    }
}
Also used : RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) TextRange(com.intellij.openapi.util.TextRange) EditorColorsManager(com.intellij.openapi.editor.colors.EditorColorsManager)

Aggregations

EditorColorsManager (com.intellij.openapi.editor.colors.EditorColorsManager)43 TextAttributes (com.intellij.openapi.editor.markup.TextAttributes)37 HighlightManager (com.intellij.codeInsight.highlighting.HighlightManager)22 EditorColorsScheme (com.intellij.openapi.editor.colors.EditorColorsScheme)14 RangeHighlighter (com.intellij.openapi.editor.markup.RangeHighlighter)9 Editor (com.intellij.openapi.editor.Editor)7 Project (com.intellij.openapi.project.Project)7 TextRange (com.intellij.openapi.util.TextRange)7 TextAttributesKey (com.intellij.openapi.editor.colors.TextAttributesKey)6 ArrayList (java.util.ArrayList)6 LogicalPosition (com.intellij.openapi.editor.LogicalPosition)4 FileEditorManager (com.intellij.openapi.fileEditor.FileEditorManager)3 WindowManager (com.intellij.openapi.wm.WindowManager)3 PsiElement (com.intellij.psi.PsiElement)3 Nullable (org.jetbrains.annotations.Nullable)3 FindManager (com.intellij.find.FindManager)2 FindModel (com.intellij.find.FindModel)2 Application (com.intellij.openapi.application.Application)2 Document (com.intellij.openapi.editor.Document)2 StatusBar (com.intellij.openapi.wm.StatusBar)2