Search in sources :

Example 71 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class RepositoryAttachHandler method doResolveInner.

public static void doResolveInner(Project project, final MavenId mavenId, List<MavenExtraArtifactType> extraTypes, Collection<MavenRepositoryInfo> repositories, @Nullable final Processor<List<MavenArtifact>> resultProcessor, ProgressIndicator indicator) {
    boolean cancelled = false;
    final Collection<MavenArtifact> result = new LinkedHashSet<>();
    MavenEmbeddersManager manager = MavenProjectsManager.getInstance(project).getEmbeddersManager();
    MavenEmbedderWrapper embedder = manager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD, null, null);
    try {
        final MavenGeneralSettings mavenGeneralSettings = MavenProjectsManager.getInstance(project).getGeneralSettings();
        embedder.customizeForResolve(new SoutMavenConsole(mavenGeneralSettings.getOutputLevel(), mavenGeneralSettings.isPrintErrorStackTraces()), new MavenProgressIndicator(indicator));
        List<MavenRemoteRepository> remoteRepositories = convertRepositories(repositories);
        List<MavenArtifactInfo> artifacts = Collections.singletonList(new MavenArtifactInfo(mavenId, "jar", null));
        List<MavenArtifact> firstResult = embedder.resolveTransitively(artifacts, remoteRepositories);
        for (MavenArtifact artifact : firstResult) {
            if (!artifact.isResolved() || MavenConstants.SCOPE_TEST.equals(artifact.getScope())) {
                continue;
            }
            result.add(artifact);
        }
        // download docs & sources
        if (!extraTypes.isEmpty()) {
            Set<String> allowedClassifiers = JBIterable.from(extraTypes).transform(extraType -> extraType.getDefaultClassifier()).toSet();
            List<MavenArtifactInfo> resolve = JBIterable.from(extraTypes).transform(extraType -> new MavenArtifactInfo(mavenId, extraType.getDefaultExtension(), extraType.getDefaultClassifier())).toList();
            // skip sources/javadoc for dependencies
            for (MavenArtifact artifact : embedder.resolveTransitively(new ArrayList<>(resolve), remoteRepositories)) {
                if (!artifact.isResolved() || MavenConstants.SCOPE_TEST.equals(artifact.getScope()) || !allowedClassifiers.contains(artifact.getClassifier())) {
                    continue;
                }
                result.add(artifact);
            }
        }
    } catch (MavenProcessCanceledException e) {
        cancelled = true;
    } finally {
        manager.release(embedder);
        if (!cancelled && resultProcessor != null) {
            ApplicationManager.getApplication().invokeAndWait(() -> resultProcessor.process(new ArrayList<>(result)));
        }
    }
}
Also used : MavenRepositoryServicesManager(org.jetbrains.idea.maven.services.MavenRepositoryServicesManager) MavenProgressIndicator(org.jetbrains.idea.maven.utils.MavenProgressIndicator) JBIterable(com.intellij.util.containers.JBIterable) VirtualFile(com.intellij.openapi.vfs.VirtualFile) THashMap(gnu.trove.THashMap) MavenGeneralSettings(org.jetbrains.idea.maven.project.MavenGeneralSettings) VirtualFileManager(com.intellij.openapi.vfs.VirtualFileManager) PairProcessor(com.intellij.util.PairProcessor) MavenEmbeddersManager(org.jetbrains.idea.maven.project.MavenEmbeddersManager) Task(com.intellij.openapi.progress.Task) SmartList(com.intellij.util.SmartList) SoutMavenConsole(org.jetbrains.idea.maven.execution.SoutMavenConsole) ProjectBundle(org.jetbrains.idea.maven.project.ProjectBundle) RepositoryAttachDialog(org.jetbrains.idea.maven.utils.RepositoryAttachDialog) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Notifications(com.intellij.notification.Notifications) ProgressManager(com.intellij.openapi.progress.ProgressManager) OrderRootType(com.intellij.openapi.roots.OrderRootType) LibraryEditor(com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditor) NotificationType(com.intellij.notification.NotificationType) MavenProjectsManager(org.jetbrains.idea.maven.project.MavenProjectsManager) Notification(com.intellij.notification.Notification) Nullable(org.jetbrains.annotations.Nullable) MavenEmbedderWrapper(org.jetbrains.idea.maven.server.MavenEmbedderWrapper) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) NewLibraryConfiguration(com.intellij.openapi.roots.libraries.NewLibraryConfiguration) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) java.util(java.util) WriteAction(com.intellij.openapi.application.WriteAction) MavenLog(org.jetbrains.idea.maven.utils.MavenLog) MavenExtraArtifactType(org.jetbrains.idea.maven.importing.MavenExtraArtifactType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) JavadocOrderRootType(com.intellij.openapi.roots.JavadocOrderRootType) OrderRoot(com.intellij.openapi.roots.libraries.ui.OrderRoot) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) CommonBundle(com.intellij.CommonBundle) Project(com.intellij.openapi.project.Project) org.jetbrains.idea.maven.model(org.jetbrains.idea.maven.model) VfsUtilCore(com.intellij.openapi.vfs.VfsUtilCore) MavenProcessCanceledException(org.jetbrains.idea.maven.utils.MavenProcessCanceledException) IOException(java.io.IOException) File(java.io.File) Pair(com.intellij.openapi.util.Pair) MavenDependenciesRemoteManager(org.jetbrains.idea.maven.utils.library.remote.MavenDependenciesRemoteManager) VfsUtil(com.intellij.openapi.vfs.VfsUtil) javax.swing(javax.swing) MavenProcessCanceledException(org.jetbrains.idea.maven.utils.MavenProcessCanceledException) MavenEmbeddersManager(org.jetbrains.idea.maven.project.MavenEmbeddersManager) MavenEmbedderWrapper(org.jetbrains.idea.maven.server.MavenEmbedderWrapper) SoutMavenConsole(org.jetbrains.idea.maven.execution.SoutMavenConsole) MavenGeneralSettings(org.jetbrains.idea.maven.project.MavenGeneralSettings) MavenProgressIndicator(org.jetbrains.idea.maven.utils.MavenProgressIndicator)

Example 72 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class UsedIconsListingAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = LangDataKeys.PROJECT.getData(e.getDataContext());
    final MultiMap<String, PsiExpression> calls = new MultiMap<>();
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    Processor<PsiReference> consumer = new Processor<PsiReference>() {

        @Override
        public boolean process(PsiReference reference) {
            PsiCallExpression call = PsiTreeUtil.getParentOfType(reference.getElement(), PsiCallExpression.class, false);
            if (call == null)
                return true;
            if (call.getArgumentList() == null)
                return true;
            if (call.getArgumentList().getExpressions() == null)
                return true;
            PsiFile file = reference.getElement().getContainingFile();
            if ("AllIcons.java".equals(file.getName()))
                return true;
            PsiClass container = PsiUtil.getTopLevelClass(reference.getElement());
            if (container != null && container.getQualifiedName().startsWith("icons."))
                return true;
            for (PsiExpression arg : call.getArgumentList().getExpressions()) {
                if (arg instanceof PsiLiteralExpression) {
                    Object value = ((PsiLiteralExpression) arg).getValue();
                    processValue(value, call, file);
                } else {
                    Object value = psiFacade.getConstantEvaluationHelper().computeConstantExpression(arg, false);
                    processValue(value, call, file);
                }
            }
            return true;
        }

        private void processValue(Object value, PsiCallExpression call, PsiFile file) {
            if (value instanceof String) {
                String str = StringUtil.unquoteString((String) value, '\"');
                if (!str.startsWith("/")) {
                    if (file instanceof PsiClassOwner) {
                        str = "/" + ((PsiClassOwner) file).getPackageName().replace('.', '/') + "/" + str;
                    }
                }
                calls.putValue(str, call);
            }
        }
    };
    GlobalSearchScope allScope = GlobalSearchScope.allScope(project);
    PsiClass iconLoader = psiFacade.findClass("com.intellij.openapi.util.IconLoader", allScope);
    PsiMethod getIconMethod = iconLoader.findMethodsByName("getIcon", false)[0];
    PsiMethod findIconMethod = iconLoader.findMethodsByName("findIcon", false)[0];
    if (true) {
        MethodReferencesSearch.search(getIconMethod, false).forEach(consumer);
        MethodReferencesSearch.search(findIconMethod, false).forEach(consumer);
    }
    final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
    if (true) {
        PsiClass javaeeIcons = psiFacade.findClass("com.intellij.javaee.oss.JavaeeIcons", allScope);
        MethodReferencesSearch.search(javaeeIcons.findMethodsByName("getIcon", false)[0], false).forEach(consumer);
        MethodReferencesSearch.search(findIconMethod, false).forEach(consumer);
    }
    final List<XmlAttribute> xmlAttributes = new ArrayList<>();
    PsiSearchHelper.SERVICE.getInstance(project).processAllFilesWithWordInText("icon", new DelegatingGlobalSearchScope(GlobalSearchScope.projectScope(project)) {

        @Override
        public boolean contains(@NotNull VirtualFile file) {
            return super.contains(file) && file.getFileType() == XmlFileType.INSTANCE && index.isInSource(file);
        }
    }, new Processor<PsiFile>() {

        @Override
        public boolean process(PsiFile file) {
            file.accept(new XmlRecursiveElementVisitor() {

                @Override
                public void visitXmlTag(XmlTag tag) {
                    super.visitXmlTag(tag);
                    String icon = tag.getAttributeValue("icon");
                    if (icon != null) {
                        xmlAttributes.add(tag.getAttribute("icon"));
                    }
                }
            });
            return true;
        }
    }, true);
    PsiClass presentation = psiFacade.findClass("com.intellij.ide.presentation.Presentation", allScope);
    final MultiMap<String, PsiAnnotation> annotations = new MultiMap<>();
    AnnotationTargetsSearch.search(presentation).forEach(owner -> {
        PsiAnnotation annotation = owner.getModifierList().findAnnotation("com.intellij.ide.presentation.Presentation");
        PsiAnnotationMemberValue icon = annotation.findAttributeValue("icon");
        if (icon instanceof PsiLiteralExpression) {
            Object value = ((PsiLiteralExpression) icon).getValue();
            if (value instanceof String) {
                annotations.putValue((String) value, annotation);
            }
        }
        return true;
    });
    doReplacements(project, calls, xmlAttributes, annotations, psiFacade.findClass("com.intellij.icons.AllIcons", allScope));
    for (PsiClass iconClass : psiFacade.findPackage("icons").getClasses(allScope)) {
        if (iconClass.getName().endsWith("Icons")) {
            doReplacements(project, calls, xmlAttributes, annotations, iconClass);
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Processor(com.intellij.util.Processor) XmlAttribute(com.intellij.psi.xml.XmlAttribute) MultiMap(com.intellij.util.containers.MultiMap) DelegatingGlobalSearchScope(com.intellij.psi.search.DelegatingGlobalSearchScope) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Project(com.intellij.openapi.project.Project) ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex) DelegatingGlobalSearchScope(com.intellij.psi.search.DelegatingGlobalSearchScope) XmlTag(com.intellij.psi.xml.XmlTag)

Example 73 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class InjectedGeneralHighlightingPass method getInjectedPsiFiles.

@NotNull
private Set<PsiFile> getInjectedPsiFiles(@NotNull final List<PsiElement> elements1, @NotNull final List<PsiElement> elements2, @NotNull final ProgressIndicator progress) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    List<DocumentWindow> injected = InjectedLanguageUtil.getCachedInjectedDocuments(myFile);
    final Collection<PsiElement> hosts = new THashSet<>(elements1.size() + elements2.size() + injected.size());
    //since change in one place can lead to invalidation of injected PSI in (completely) other place.
    for (DocumentWindow documentRange : injected) {
        progress.checkCanceled();
        if (!documentRange.isValid())
            continue;
        PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(documentRange);
        if (file == null)
            continue;
        PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file);
        if (context != null && context.isValid() && !file.getProject().isDisposed() && (myUpdateAll || myRestrictRange.intersects(context.getTextRange()))) {
            hosts.add(context);
        }
    }
    InjectedLanguageManagerImpl injectedLanguageManager = InjectedLanguageManagerImpl.getInstanceImpl(myProject);
    Processor<PsiElement> collectInjectableProcessor = Processors.cancelableCollectProcessor(hosts);
    injectedLanguageManager.processInjectableElements(elements1, collectInjectableProcessor);
    injectedLanguageManager.processInjectableElements(elements2, collectInjectableProcessor);
    final Set<PsiFile> outInjected = new THashSet<>();
    final PsiLanguageInjectionHost.InjectedPsiVisitor visitor = new PsiLanguageInjectionHost.InjectedPsiVisitor() {

        @Override
        public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
            synchronized (outInjected) {
                outInjected.add(injectedPsi);
            }
        }
    };
    if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(hosts), progress, true, element -> {
        ApplicationManager.getApplication().assertReadAccessAllowed();
        progress.checkCanceled();
        InjectedLanguageUtil.enumerate(element, myFile, false, visitor);
        return true;
    })) {
        throw new ProcessCanceledException();
    }
    synchronized (outInjected) {
        return outInjected;
    }
}
Also used : Language(com.intellij.lang.Language) InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) com.intellij.openapi.util(com.intellij.openapi.util) java.util(java.util) IElementType(com.intellij.psi.tree.IElementType) JobLauncher(com.intellij.concurrency.JobLauncher) InjectedLanguageManagerImpl(com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) ContainerUtil(com.intellij.util.containers.ContainerUtil) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SyntaxHighlighter(com.intellij.openapi.fileTypes.SyntaxHighlighter) Place(com.intellij.psi.impl.source.tree.injected.Place) Project(com.intellij.openapi.project.Project) HighlightInfoHolder(com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder) DumbAware(com.intellij.openapi.project.DumbAware) SyntaxHighlighterFactory(com.intellij.openapi.fileTypes.SyntaxHighlighterFactory) InjectedLanguageUtil(com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil) CommonProcessors(com.intellij.util.CommonProcessors) ProgressManager(com.intellij.openapi.progress.ProgressManager) DocumentWindow(com.intellij.injected.editor.DocumentWindow) Processors(com.intellij.util.Processors) HighlighterColors(com.intellij.openapi.editor.HighlighterColors) Editor(com.intellij.openapi.editor.Editor) Nullable(org.jetbrains.annotations.Nullable) TextAttributesKey(com.intellij.openapi.editor.colors.TextAttributesKey) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) EditorColors(com.intellij.openapi.editor.colors.EditorColors) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Registry(com.intellij.openapi.util.registry.Registry) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) NotNull(org.jetbrains.annotations.NotNull) THashSet(gnu.trove.THashSet) DocumentWindow(com.intellij.injected.editor.DocumentWindow) InjectedLanguageManagerImpl(com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NotNull(org.jetbrains.annotations.NotNull)

Example 74 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class DocumentationManager method showInPopup.

private void showInPopup(@NotNull final PsiElement element, boolean requestFocus, PopupUpdateProcessor updateProcessor, final PsiElement originalElement, @Nullable final Runnable closeCallback) {
    final DocumentationComponent component = myTestDocumentationComponent == null ? new DocumentationComponent(this) : myTestDocumentationComponent;
    component.setNavigateCallback(psiElement -> {
        final AbstractPopup jbPopup = (AbstractPopup) getDocInfoHint();
        if (jbPopup != null) {
            final String title = getTitle(psiElement, false);
            jbPopup.setCaption(title);
            AccessibleContextUtil.setName(component, title);
        }
    });
    Processor<JBPopup> pinCallback = popup -> {
        createToolWindow(element, originalElement);
        myToolWindow.setAutoHide(false);
        popup.cancel();
        return false;
    };
    ActionListener actionListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            createToolWindow(element, originalElement);
            final JBPopup hint = getDocInfoHint();
            if (hint != null && hint.isVisible())
                hint.cancel();
        }
    };
    List<Pair<ActionListener, KeyStroke>> actions = ContainerUtil.newSmartList();
    AnAction quickDocAction = ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_JAVADOC);
    for (Shortcut shortcut : quickDocAction.getShortcutSet().getShortcuts()) {
        if (!(shortcut instanceof KeyboardShortcut))
            continue;
        actions.add(Pair.create(actionListener, ((KeyboardShortcut) shortcut).getFirstKeyStroke()));
    }
    boolean hasLookup = LookupManager.getActiveLookup(myEditor) != null;
    final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component).setProject(element.getProject()).addListener(updateProcessor).addUserData(updateProcessor).setKeyboardActions(actions).setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false).setResizable(true).setMovable(true).setRequestFocus(requestFocus).setCancelOnClickOutside(// otherwise selecting lookup items by mouse would close the doc
    !hasLookup).setTitle(getTitle(element, false)).setCouldPin(pinCallback).setModalContext(false).setCancelCallback(() -> {
        myCloseOnSneeze = false;
        if (closeCallback != null) {
            closeCallback.run();
        }
        if (fromQuickSearch()) {
            ((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).unregisterHint();
        }
        Disposer.dispose(component);
        myEditor = null;
        myPreviouslyFocused = null;
        return Boolean.TRUE;
    }).setKeyEventHandler(e -> {
        if (myCloseOnSneeze) {
            closeDocHint();
        }
        if (AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null) {
            closeDocHint();
            return true;
        }
        return false;
    }).createPopup();
    component.setHint(hint);
    if (myEditor == null) {
        // subsequent invocation of javadoc popup from completion will have myEditor == null because of cancel invoked, 
        // so reevaluate the editor for proper popup placement
        Lookup lookup = LookupManager.getInstance(myProject).getActiveLookup();
        myEditor = lookup != null ? lookup.getEditor() : null;
    }
    fetchDocInfo(getDefaultCollector(element, originalElement), component);
    myDocInfoHintRef = new WeakReference<>(hint);
    if (fromQuickSearch() && myPreviouslyFocused != null) {
        ((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).registerHint(hint);
    }
}
Also used : Language(com.intellij.lang.Language) com.intellij.openapi.util(com.intellij.openapi.util) AccessibleContextUtil(com.intellij.util.ui.accessibility.AccessibleContextUtil) BaseNavigateToSourceAction(com.intellij.ide.actions.BaseNavigateToSourceAction) Lookup(com.intellij.codeInsight.lookup.Lookup) VirtualFile(com.intellij.openapi.vfs.VirtualFile) com.intellij.lang.documentation(com.intellij.lang.documentation) ModalityState(com.intellij.openapi.application.ModalityState) ProjectSettingsService(com.intellij.openapi.roots.ui.configuration.ProjectSettingsService) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) ShowQuickDocInfoAction(com.intellij.codeInsight.documentation.actions.ShowQuickDocInfoAction) Logger(com.intellij.openapi.diagnostic.Logger) Extensions(com.intellij.openapi.extensions.Extensions) PropertiesComponent(com.intellij.ide.util.PropertiesComponent) ScrollingUtil(com.intellij.ui.ScrollingUtil) ParameterInfoController(com.intellij.codeInsight.hint.ParameterInfoController) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) LookupManager(com.intellij.codeInsight.lookup.LookupManager) PreviewManager(com.intellij.openapi.preview.PreviewManager) OrderEntry(com.intellij.openapi.roots.OrderEntry) Content(com.intellij.ui.content.Content) AbstractPopup(com.intellij.ui.popup.AbstractPopup) LookupEx(com.intellij.codeInsight.lookup.LookupEx) BrowserUtil(com.intellij.ide.BrowserUtil) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) IdeFocusManager(com.intellij.openapi.wm.IdeFocusManager) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) IdeFocusManager.getGlobalInstance(com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance) com.intellij.psi(com.intellij.psi) WindowManagerEx(com.intellij.openapi.wm.ex.WindowManagerEx) NotNull(org.jetbrains.annotations.NotNull) java.util(java.util) ActionListener(java.awt.event.ActionListener) NonNls(org.jetbrains.annotations.NonNls) ContainerUtil(com.intellij.util.containers.ContainerUtil) CodeInsightBundle(com.intellij.codeInsight.CodeInsightBundle) PopupUpdateProcessor(com.intellij.ui.popup.PopupUpdateProcessor) AnActionListener(com.intellij.openapi.actionSystem.ex.AnActionListener) ToolWindowId(com.intellij.openapi.wm.ToolWindowId) Project(com.intellij.openapi.project.Project) PopupPositionManager(com.intellij.ui.popup.PopupPositionManager) WeakReference(java.lang.ref.WeakReference) DataManager(com.intellij.ide.DataManager) LibraryUtil(com.intellij.openapi.roots.libraries.LibraryUtil) LookupElement(com.intellij.codeInsight.lookup.LookupElement) ChooseByNameBase(com.intellij.ide.util.gotoByName.ChooseByNameBase) Editor(com.intellij.openapi.editor.Editor) ActionEvent(java.awt.event.ActionEvent) JBPopup(com.intellij.openapi.ui.popup.JBPopup) TestOnly(org.jetbrains.annotations.TestOnly) java.awt(java.awt) LanguageDocumentation(com.intellij.lang.LanguageDocumentation) com.intellij.openapi.actionSystem(com.intellij.openapi.actionSystem) CommandProcessor(com.intellij.openapi.command.CommandProcessor) SymbolPresentationUtil(com.intellij.psi.presentation.java.SymbolPresentationUtil) HintManagerImpl(com.intellij.codeInsight.hint.HintManagerImpl) JBPopupFactory(com.intellij.openapi.ui.popup.JBPopupFactory) TargetElementUtil(com.intellij.codeInsight.TargetElementUtil) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) AbstractPopup(com.intellij.ui.popup.AbstractPopup) ActionEvent(java.awt.event.ActionEvent) ActionListener(java.awt.event.ActionListener) AnActionListener(com.intellij.openapi.actionSystem.ex.AnActionListener) Lookup(com.intellij.codeInsight.lookup.Lookup) JBPopup(com.intellij.openapi.ui.popup.JBPopup)

Example 75 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class ShowIntentionsPass method collectIntentionsFromDoNotShowLeveledInspections.

/**
   * Can be invoked in EDT, each inspection should be fast
   */
private static void collectIntentionsFromDoNotShowLeveledInspections(@NotNull final Project project, @NotNull final PsiFile hostFile, PsiElement psiElement, final int offset, @NotNull final IntentionsInfo intentions) {
    if (psiElement != null) {
        if (!psiElement.isPhysical()) {
            VirtualFile virtualFile = hostFile.getVirtualFile();
            String text = hostFile.getText();
            LOG.error("not physical: '" + psiElement.getText() + "' @" + offset + psiElement.getTextRange() + " elem:" + psiElement + " (" + psiElement.getClass().getName() + ")" + " in:" + psiElement.getContainingFile() + " host:" + hostFile + "(" + hostFile.getClass().getName() + ")", new Attachment(virtualFile != null ? virtualFile.getPresentableUrl() : "null", text != null ? text : "null"));
        }
        if (DumbService.isDumb(project)) {
            return;
        }
        final List<LocalInspectionToolWrapper> intentionTools = new ArrayList<>();
        final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
        final InspectionToolWrapper[] tools = profile.getInspectionTools(hostFile);
        for (InspectionToolWrapper toolWrapper : tools) {
            if (toolWrapper instanceof LocalInspectionToolWrapper && !((LocalInspectionToolWrapper) toolWrapper).isUnfair()) {
                final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
                if (profile.isToolEnabled(key, hostFile) && HighlightDisplayLevel.DO_NOT_SHOW.equals(profile.getErrorLevel(key, hostFile))) {
                    intentionTools.add((LocalInspectionToolWrapper) toolWrapper);
                }
            }
        }
        if (!intentionTools.isEmpty()) {
            final List<PsiElement> elements = new ArrayList<>();
            PsiElement el = psiElement;
            while (el != null) {
                elements.add(el);
                if (el instanceof PsiFile)
                    break;
                el = el.getParent();
            }
            final Set<String> dialectIds = InspectionEngine.calcElementDialectIds(elements);
            final LocalInspectionToolSession session = new LocalInspectionToolSession(hostFile, 0, hostFile.getTextLength());
            final Processor<LocalInspectionToolWrapper> processor = toolWrapper -> {
                final LocalInspectionTool localInspectionTool = toolWrapper.getTool();
                final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
                final String displayName = toolWrapper.getDisplayName();
                final ProblemsHolder holder = new ProblemsHolder(InspectionManager.getInstance(project), hostFile, true) {

                    @Override
                    public void registerProblem(@NotNull ProblemDescriptor problemDescriptor) {
                        super.registerProblem(problemDescriptor);
                        if (problemDescriptor instanceof ProblemDescriptorBase) {
                            final TextRange range = ((ProblemDescriptorBase) problemDescriptor).getTextRange();
                            if (range != null && range.contains(offset)) {
                                final QuickFix[] fixes = problemDescriptor.getFixes();
                                if (fixes != null) {
                                    for (int k = 0; k < fixes.length; k++) {
                                        final IntentionAction intentionAction = QuickFixWrapper.wrap(problemDescriptor, k);
                                        final HighlightInfo.IntentionActionDescriptor actionDescriptor = new HighlightInfo.IntentionActionDescriptor(intentionAction, null, displayName, null, key, null, HighlightSeverity.INFORMATION);
                                        intentions.intentionsToShow.add(actionDescriptor);
                                    }
                                }
                            }
                        }
                    }
                };
                InspectionEngine.createVisitorAndAcceptElements(localInspectionTool, holder, true, session, elements, dialectIds, InspectionEngine.getDialectIdsSpecifiedForTool(toolWrapper));
                localInspectionTool.inspectionFinished(session, holder);
                return true;
            };
            JobLauncher.getInstance().invokeConcurrentlyUnderProgress(intentionTools, new DaemonProgressIndicator(), false, processor);
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) HighlightSeverity(com.intellij.lang.annotation.HighlightSeverity) Document(com.intellij.openapi.editor.Document) MarkupModelEx(com.intellij.openapi.editor.ex.MarkupModelEx) DocumentMarkupModel(com.intellij.openapi.editor.impl.DocumentMarkupModel) QuickFixWrapper(com.intellij.codeInspection.ex.QuickFixWrapper) RangeHighlighterEx(com.intellij.openapi.editor.ex.RangeHighlighterEx) EditorEx(com.intellij.openapi.editor.ex.EditorEx) HighlightingLevelManager(com.intellij.codeInsight.daemon.impl.analysis.HighlightingLevelManager) Logger(com.intellij.openapi.diagnostic.Logger) CommonProcessors(com.intellij.util.CommonProcessors) RangeMarker(com.intellij.openapi.editor.RangeMarker) DumbService(com.intellij.openapi.project.DumbService) HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) IntentionHintComponent(com.intellij.codeInsight.intention.impl.IntentionHintComponent) Processors(com.intellij.util.Processors) Set(java.util.Set) TextRange(com.intellij.openapi.util.TextRange) LogicalPosition(com.intellij.openapi.editor.LogicalPosition) CleanupAllIntention(com.intellij.codeInspection.actions.CleanupAllIntention) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) TextEditorHighlightingPass(com.intellij.codeHighlighting.TextEditorHighlightingPass) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) IntentionManagerSettings(com.intellij.codeInsight.intention.impl.config.IntentionManagerSettings) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) NotNull(org.jetbrains.annotations.NotNull) InspectionProjectProfileManager(com.intellij.profile.codeInspection.InspectionProjectProfileManager) TemplateManagerImpl(com.intellij.codeInsight.template.impl.TemplateManagerImpl) JobLauncher(com.intellij.concurrency.JobLauncher) LocalInspectionToolWrapper(com.intellij.codeInspection.ex.LocalInspectionToolWrapper) NonNls(org.jetbrains.annotations.NonNls) DaemonCodeAnalyzer(com.intellij.codeInsight.daemon.DaemonCodeAnalyzer) ContainerUtil(com.intellij.util.containers.ContainerUtil) ArrayList(java.util.ArrayList) PsiElement(com.intellij.psi.PsiElement) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace) IntentionManager(com.intellij.codeInsight.intention.IntentionManager) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) Segment(com.intellij.openapi.util.Segment) InjectedLanguageUtil(com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) Iterator(java.util.Iterator) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) com.intellij.codeInspection(com.intellij.codeInspection) HighlightDisplayLevel(com.intellij.codeHighlighting.HighlightDisplayLevel) Editor(com.intellij.openapi.editor.Editor) java.awt(java.awt) ShowIntentionActionsHandler(com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler) InspectionToolWrapper(com.intellij.codeInspection.ex.InspectionToolWrapper) Pair(com.intellij.openapi.util.Pair) Attachment(com.intellij.openapi.diagnostic.Attachment) HintManager(com.intellij.codeInsight.hint.HintManager) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) HighlightDisplayKey(com.intellij.codeInsight.daemon.HighlightDisplayKey) ArrayList(java.util.ArrayList) Attachment(com.intellij.openapi.diagnostic.Attachment) PsiFile(com.intellij.psi.PsiFile) LocalInspectionToolWrapper(com.intellij.codeInspection.ex.LocalInspectionToolWrapper) PsiElement(com.intellij.psi.PsiElement) TextRange(com.intellij.openapi.util.TextRange) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) LocalInspectionToolWrapper(com.intellij.codeInspection.ex.LocalInspectionToolWrapper) InspectionToolWrapper(com.intellij.codeInspection.ex.InspectionToolWrapper)

Aggregations

Processor (com.intellij.util.Processor)83 NotNull (org.jetbrains.annotations.NotNull)65 Project (com.intellij.openapi.project.Project)49 Nullable (org.jetbrains.annotations.Nullable)49 ContainerUtil (com.intellij.util.containers.ContainerUtil)42 com.intellij.psi (com.intellij.psi)31 List (java.util.List)28 ApplicationManager (com.intellij.openapi.application.ApplicationManager)25 StringUtil (com.intellij.openapi.util.text.StringUtil)25 VirtualFile (com.intellij.openapi.vfs.VirtualFile)25 java.util (java.util)25 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)24 ProgressManager (com.intellij.openapi.progress.ProgressManager)21 Logger (com.intellij.openapi.diagnostic.Logger)20 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)20 NonNls (org.jetbrains.annotations.NonNls)18 Ref (com.intellij.openapi.util.Ref)16 Collection (java.util.Collection)16 SmartList (com.intellij.util.SmartList)14 Document (com.intellij.openapi.editor.Document)13