Search in sources :

Example 56 with Processor

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

the class UpdateHighlightersUtil method addHighlighterToEditorIncrementally.

static void addHighlighterToEditorIncrementally(@NotNull Project project, @NotNull Document document, @NotNull PsiFile file, int startOffset, int endOffset, @NotNull final HighlightInfo info, // if null global scheme will be used
@Nullable final EditorColorsScheme colorsScheme, final int group, @NotNull Map<TextRange, RangeMarker> ranges2markersCache) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (isFileLevelOrGutterAnnotation(info))
        return;
    if (info.getStartOffset() < startOffset || info.getEndOffset() > endOffset)
        return;
    MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);
    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
    final boolean myInfoIsError = isSevere(info, severityRegistrar);
    Processor<HighlightInfo> otherHighlightInTheWayProcessor = oldInfo -> {
        if (!myInfoIsError && isCovered(info, severityRegistrar, oldInfo)) {
            return false;
        }
        return oldInfo.getGroup() != group || !oldInfo.equalsByActualOffset(info);
    };
    boolean allIsClear = DaemonCodeAnalyzerEx.processHighlights(document, project, null, info.getActualStartOffset(), info.getActualEndOffset(), otherHighlightInTheWayProcessor);
    if (allIsClear) {
        createOrReuseHighlighterFor(info, colorsScheme, document, group, file, (MarkupModelEx) markup, null, ranges2markersCache, severityRegistrar);
        clearWhiteSpaceOptimizationFlag(document);
        assertMarkupConsistent(markup, project);
    }
}
Also used : com.intellij.openapi.util(com.intellij.openapi.util) java.util(java.util) GutterMark(com.intellij.codeInsight.daemon.GutterMark) HighlightSeverity(com.intellij.lang.annotation.HighlightSeverity) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) DocumentEvent(com.intellij.openapi.editor.event.DocumentEvent) MarkupModelEx(com.intellij.openapi.editor.ex.MarkupModelEx) DocumentMarkupModel(com.intellij.openapi.editor.impl.DocumentMarkupModel) ContainerUtil(com.intellij.util.containers.ContainerUtil) THashMap(gnu.trove.THashMap) RangeHighlighterEx(com.intellij.openapi.editor.ex.RangeHighlighterEx) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) DocumentEx(com.intellij.openapi.editor.ex.DocumentEx) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) RangeMarker(com.intellij.openapi.editor.RangeMarker) RedBlackTree(com.intellij.openapi.editor.impl.RedBlackTree) com.intellij.openapi.editor.markup(com.intellij.openapi.editor.markup) EditorColorsScheme(com.intellij.openapi.editor.colors.EditorColorsScheme) java.awt(java.awt) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) RangeMarkerTree(com.intellij.openapi.editor.impl.RangeMarkerTree) DocumentMarkupModel(com.intellij.openapi.editor.impl.DocumentMarkupModel)

Example 57 with Processor

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

the class GlobalInspectionContextImpl method runTools.

@Override
protected void runTools(@NotNull final AnalysisScope scope, boolean runGlobalToolsOnly, boolean isOfflineInspections) {
    final ProgressIndicator progressIndicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
    if (progressIndicator == null) {
        throw new IncorrectOperationException("Must be run under progress");
    }
    if (!isOfflineInspections && ApplicationManager.getApplication().isDispatchThread()) {
        throw new IncorrectOperationException("Must not start inspections from within EDT");
    }
    if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
        throw new IncorrectOperationException("Must not start inspections from within write action");
    }
    // in offline inspection application we don't care about global read action
    if (!isOfflineInspections && ApplicationManager.getApplication().isReadAccessAllowed()) {
        throw new IncorrectOperationException("Must not start inspections from within global read action");
    }
    final InspectionManager inspectionManager = InspectionManager.getInstance(getProject());
    ((RefManagerImpl) getRefManager()).initializeAnnotators();
    final List<Tools> globalTools = new ArrayList<>();
    final List<Tools> localTools = new ArrayList<>();
    final List<Tools> globalSimpleTools = new ArrayList<>();
    initializeTools(globalTools, localTools, globalSimpleTools);
    appendPairedInspectionsForUnfairTools(globalTools, globalSimpleTools, localTools);
    runGlobalTools(scope, inspectionManager, globalTools, isOfflineInspections);
    if (runGlobalToolsOnly || localTools.isEmpty() && globalSimpleTools.isEmpty())
        return;
    SearchScope searchScope = ReadAction.compute(scope::toSearchScope);
    final Set<VirtualFile> localScopeFiles = searchScope instanceof LocalSearchScope ? new THashSet<>() : null;
    for (Tools tools : globalSimpleTools) {
        GlobalInspectionToolWrapper toolWrapper = (GlobalInspectionToolWrapper) tools.getTool();
        GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool) toolWrapper.getTool();
        tool.inspectionStarted(inspectionManager, this, getPresentation(toolWrapper));
    }
    final boolean headlessEnvironment = ApplicationManager.getApplication().isHeadlessEnvironment();
    final Map<String, InspectionToolWrapper> map = getInspectionWrappersMap(localTools);
    final BlockingQueue<PsiFile> filesToInspect = new ArrayBlockingQueue<>(1000);
    // use original progress indicator here since we don't want it to cancel on write action start
    ProgressIndicator iteratingIndicator = new SensitiveProgressWrapper(progressIndicator);
    Future<?> future = startIterateScopeInBackground(scope, localScopeFiles, headlessEnvironment, filesToInspect, iteratingIndicator);
    Processor<PsiFile> processor = file -> {
        ProgressManager.checkCanceled();
        if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(() -> {
            if (!file.isValid()) {
                return;
            }
            LOG.assertTrue(scope.contains(file.getVirtualFile()), file.getName());
            inspectFile(file, inspectionManager, localTools, globalSimpleTools, map);
        })) {
            throw new ProcessCanceledException();
        }
        boolean includeDoNotShow = includeDoNotShow(getCurrentProfile());
        Stream.concat(getWrappersFromTools(localTools, file, includeDoNotShow).stream(), getWrappersFromTools(globalSimpleTools, file, includeDoNotShow).stream()).filter(wrapper -> wrapper.getTool() instanceof ExternalAnnotatorBatchInspection).forEach(wrapper -> {
            ProblemDescriptor[] descriptors = ((ExternalAnnotatorBatchInspection) wrapper.getTool()).checkFile(file, this, inspectionManager);
            InspectionToolPresentation toolPresentation = getPresentation(wrapper);
            ReadAction.run(() -> LocalDescriptorsUtil.addProblemDescriptors(Arrays.asList(descriptors), false, this, null, CONVERT, toolPresentation));
        });
        return true;
    };
    try {
        final Queue<PsiFile> filesFailedToInspect = new LinkedBlockingQueue<>();
        while (true) {
            Disposable disposable = Disposer.newDisposable();
            ProgressIndicator wrapper = new SensitiveProgressWrapper(progressIndicator);
            wrapper.start();
            ProgressIndicatorUtils.forceWriteActionPriority(wrapper, disposable);
            try {
                // use wrapper here to cancel early when write action start but do not affect the original indicator
                ((JobLauncherImpl) JobLauncher.getInstance()).processQueue(filesToInspect, filesFailedToInspect, wrapper, TOMBSTONE, processor);
                break;
            } catch (ProcessCanceledException ignored) {
                progressIndicator.checkCanceled();
                // go on with the write and then resume processing the rest of the queue
                assert !ApplicationManager.getApplication().isReadAccessAllowed();
                assert !ApplicationManager.getApplication().isDispatchThread();
                // wait for write action to complete
                ApplicationManager.getApplication().runReadAction(EmptyRunnable.getInstance());
            } finally {
                Disposer.dispose(disposable);
            }
        }
    } finally {
        // tell file scanning thread to stop
        iteratingIndicator.cancel();
        // let file scanning thread a chance to put TOMBSTONE and complete
        filesToInspect.clear();
        try {
            future.get(30, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error("Thread dump: \n" + ThreadDumper.dumpThreadsToString(), e);
        }
    }
    progressIndicator.checkCanceled();
    for (Tools tools : globalSimpleTools) {
        GlobalInspectionToolWrapper toolWrapper = (GlobalInspectionToolWrapper) tools.getTool();
        GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool) toolWrapper.getTool();
        ProblemDescriptionsProcessor problemDescriptionProcessor = getProblemDescriptionProcessor(toolWrapper, map);
        tool.inspectionFinished(inspectionManager, this, problemDescriptionProcessor);
    }
    addProblemsToView(globalSimpleTools);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) com.intellij.openapi.util(com.intellij.openapi.util) UIUtil(com.intellij.util.ui.UIUtil) ToolWindowManager(com.intellij.openapi.wm.ToolWindowManager) MessageType(com.intellij.openapi.ui.MessageType) ToggleAction(com.intellij.openapi.actionSystem.ToggleAction) VirtualFile(com.intellij.openapi.vfs.VirtualFile) HashMap(com.intellij.util.containers.HashMap) Document(com.intellij.openapi.editor.Document) HashSet(com.intellij.util.containers.HashSet) DefaultInspectionToolPresentation(com.intellij.codeInspection.ui.DefaultInspectionToolPresentation) THashSet(gnu.trove.THashSet) TripleFunction(com.intellij.util.TripleFunction) com.intellij.openapi.application(com.intellij.openapi.application) ProjectUtilCore(com.intellij.openapi.project.ProjectUtilCore) ProblemHighlightFilter(com.intellij.codeInsight.daemon.ProblemHighlightFilter) FileIndex(com.intellij.openapi.roots.FileIndex) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) ProjectRootManager(com.intellij.openapi.roots.ProjectRootManager) InspectionToolPresentation(com.intellij.codeInspection.ui.InspectionToolPresentation) FileModificationService(com.intellij.codeInsight.FileModificationService) com.intellij.openapi.progress(com.intellij.openapi.progress) RefElement(com.intellij.codeInspection.reference.RefElement) IncorrectOperationException(com.intellij.util.IncorrectOperationException) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) PathMacroManager(com.intellij.openapi.components.PathMacroManager) java.util.concurrent(java.util.concurrent) InspectionResultsView(com.intellij.codeInspection.ui.InspectionResultsView) ProjectUtil(com.intellij.openapi.project.ProjectUtil) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) Stream(java.util.stream.Stream) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) Processor(com.intellij.util.Processor) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) JobLauncherImpl(com.intellij.concurrency.JobLauncherImpl) com.intellij.ui.content(com.intellij.ui.content) java.util(java.util) LocalInspectionsPass(com.intellij.codeInsight.daemon.impl.LocalInspectionsPass) CharsetToolkit(com.intellij.openapi.vfs.CharsetToolkit) CleanupInspectionIntention(com.intellij.codeInspection.actions.CleanupInspectionIntention) PerformAnalysisInBackgroundOption(com.intellij.analysis.PerformAnalysisInBackgroundOption) JobLauncher(com.intellij.concurrency.JobLauncher) GlobalInspectionContextExtension(com.intellij.codeInspection.lang.GlobalInspectionContextExtension) SensitiveProgressWrapper(com.intellij.concurrency.SensitiveProgressWrapper) NonNls(org.jetbrains.annotations.NonNls) ProgressIndicatorUtils(com.intellij.openapi.progress.util.ProgressIndicatorUtils) SearchScope(com.intellij.psi.search.SearchScope) ContainerUtil(com.intellij.util.containers.ContainerUtil) Constructor(java.lang.reflect.Constructor) ThreadDumper(com.intellij.diagnostic.ThreadDumper) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) NamedScope(com.intellij.psi.search.scope.packageSet.NamedScope) CoreProgressManager(com.intellij.openapi.progress.impl.CoreProgressManager) ProblemGroup(com.intellij.lang.annotation.ProblemGroup) NotificationGroup(com.intellij.notification.NotificationGroup) ToolWindowId(com.intellij.openapi.wm.ToolWindowId) Project(com.intellij.openapi.project.Project) OutputStreamWriter(java.io.OutputStreamWriter) RefVisitor(com.intellij.codeInspection.reference.RefVisitor) RefManagerImpl(com.intellij.codeInspection.reference.RefManagerImpl) StringUtil(com.intellij.openapi.util.text.StringUtil) HighlightInfoProcessor(com.intellij.codeInsight.daemon.impl.HighlightInfoProcessor) AnalysisScope(com.intellij.analysis.AnalysisScope) FileOutputStream(java.io.FileOutputStream) ConcurrencyUtil(com.intellij.util.ConcurrencyUtil) IOException(java.io.IOException) com.intellij.codeInspection(com.intellij.codeInspection) AnalysisUIOptions(com.intellij.analysis.AnalysisUIOptions) GuiUtils(com.intellij.ui.GuiUtils) InspectionTreeState(com.intellij.codeInspection.ui.InspectionTreeState) Disposable(com.intellij.openapi.Disposable) File(java.io.File) ApplicationManagerEx(com.intellij.openapi.application.ex.ApplicationManagerEx) Element(org.jdom.Element) RefEntity(com.intellij.codeInspection.reference.RefEntity) DefaultInspectionToolPresentation(com.intellij.codeInspection.ui.DefaultInspectionToolPresentation) InspectionToolPresentation(com.intellij.codeInspection.ui.InspectionToolPresentation) RefManagerImpl(com.intellij.codeInspection.reference.RefManagerImpl) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Disposable(com.intellij.openapi.Disposable) JobLauncherImpl(com.intellij.concurrency.JobLauncherImpl) IncorrectOperationException(com.intellij.util.IncorrectOperationException) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) IOException(java.io.IOException) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SensitiveProgressWrapper(com.intellij.concurrency.SensitiveProgressWrapper) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 58 with Processor

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

the class AllClassesSearchExecutor method processClassNames.

public static Project processClassNames(final Project project, final GlobalSearchScope scope, final Consumer<String> consumer) {
    final ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
    DumbService.getInstance(project).runReadActionInSmartMode(new Computable<Void>() {

        @Override
        public Void compute() {
            PsiShortNamesCache.getInstance(project).processAllClassNames(new Processor<String>() {

                int i;

                @Override
                public boolean process(String s) {
                    if (indicator != null && i++ % 512 == 0) {
                        indicator.checkCanceled();
                    }
                    consumer.consume(s);
                    return true;
                }
            }, scope, IdFilter.getProjectIdFilter(project, true));
            return null;
        }
    });
    if (indicator != null) {
        indicator.checkCanceled();
    }
    return project;
}
Also used : Processor(com.intellij.util.Processor) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator)

Example 59 with Processor

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

the class JavaAllOverridingMethodsSearcher method execute.

@Override
public boolean execute(@NotNull final AllOverridingMethodsSearch.SearchParameters p, @NotNull final Processor<Pair<PsiMethod, PsiMethod>> consumer) {
    final PsiClass psiClass = p.getPsiClass();
    final List<PsiMethod> potentials = ReadAction.compute(() -> ContainerUtil.filter(psiClass.getMethods(), PsiUtil::canBeOverriden));
    final SearchScope scope = p.getScope();
    Processor<PsiClass> inheritorsProcessor = inheritor -> {
        Project project = psiClass.getProject();
        for (PsiMethod superMethod : potentials) {
            ProgressManager.checkCanceled();
            if (superMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && !JavaPsiFacade.getInstance(project).arePackagesTheSame(psiClass, inheritor))
                continue;
            PsiMethod inInheritor = JavaOverridingMethodsSearcher.findOverridingMethod(project, inheritor, superMethod, psiClass);
            if (inInheritor != null && !consumer.process(Pair.create(superMethod, inInheritor)))
                return false;
        }
        return true;
    };
    return ClassInheritorsSearch.search(psiClass, scope, true).forEach(inheritorsProcessor);
}
Also used : ProgressManager(com.intellij.openapi.progress.ProgressManager) PsiMethod(com.intellij.psi.PsiMethod) QueryExecutor(com.intellij.util.QueryExecutor) JavaPsiFacade(com.intellij.psi.JavaPsiFacade) SearchScope(com.intellij.psi.search.SearchScope) AllOverridingMethodsSearch(com.intellij.psi.search.searches.AllOverridingMethodsSearch) ContainerUtil(com.intellij.util.containers.ContainerUtil) ReadAction(com.intellij.openapi.application.ReadAction) PsiModifier(com.intellij.psi.PsiModifier) PsiClass(com.intellij.psi.PsiClass) List(java.util.List) Processor(com.intellij.util.Processor) Pair(com.intellij.openapi.util.Pair) Project(com.intellij.openapi.project.Project) PsiUtil(com.intellij.psi.util.PsiUtil) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) NotNull(org.jetbrains.annotations.NotNull) Project(com.intellij.openapi.project.Project) PsiMethod(com.intellij.psi.PsiMethod) PsiClass(com.intellij.psi.PsiClass) SearchScope(com.intellij.psi.search.SearchScope)

Example 60 with Processor

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

the class JavaOverridingMethodsSearcher method compute.

@NotNull
private static Iterable<PsiMethod> compute(@NotNull PsiMethod method, @NotNull Project project) {
    Application application = ApplicationManager.getApplication();
    final PsiClass containingClass = application.runReadAction((Computable<PsiClass>) method::getContainingClass);
    assert containingClass != null;
    Collection<PsiMethod> result = new LinkedHashSet<>();
    Processor<PsiClass> inheritorsProcessor = inheritor -> {
        PsiMethod found = application.runReadAction((Computable<PsiMethod>) () -> findOverridingMethod(project, inheritor, method, containingClass));
        if (found != null) {
            result.add(found);
        }
        return true;
    };
    // use wider scope to handle public method defined in package-private class which is subclassed by public class in the same package which is subclassed by public class from another package with redefined method
    SearchScope allScope = GlobalSearchScope.allScope(project);
    boolean success = ClassInheritorsSearch.search(containingClass, allScope, true).forEach(inheritorsProcessor);
    assert success;
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ProgressManager(com.intellij.openapi.progress.ProgressManager) TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) Application(com.intellij.openapi.application.Application) MethodSignatureUtil(com.intellij.psi.util.MethodSignatureUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) QueryExecutor(com.intellij.util.QueryExecutor) OverridingMethodsSearch(com.intellij.psi.search.searches.OverridingMethodsSearch) Collection(java.util.Collection) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Computable(com.intellij.openapi.util.Computable) SearchScope(com.intellij.psi.search.SearchScope) ReadAction(com.intellij.openapi.application.ReadAction) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Nullable(org.jetbrains.annotations.Nullable) PsiSearchScopeUtil(com.intellij.psi.search.PsiSearchScopeUtil) MethodSignature(com.intellij.psi.util.MethodSignature) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) com.intellij.psi(com.intellij.psi) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) NotNull(org.jetbrains.annotations.NotNull) LinkedHashSet(java.util.LinkedHashSet) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Application(com.intellij.openapi.application.Application) Computable(com.intellij.openapi.util.Computable) NotNull(org.jetbrains.annotations.NotNull)

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