com.intellij.openapi.application.ReadAction Java Examples
The following examples show how to use
com.intellij.openapi.application.ReadAction.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DumbService.java From consulo with Apache License 2.0 | 6 votes |
/** * Pause the current thread until dumb mode ends, and then run the read action. Indexes are guaranteed to be available inside that read action, * unless this method is already called with read access allowed. * * @throws ProcessCanceledException if the project is closed during dumb mode */ public void runReadActionInSmartMode(@Nonnull Runnable r) { if (ApplicationManager.getApplication().isReadAccessAllowed()) { // we can't wait for smart mode to begin (it'd result in a deadlock), // so let's just pretend it's already smart and fail with IndexNotReadyException if not r.run(); return; } while (true) { waitForSmartMode(); boolean success = ReadAction.compute(() -> { if (getProject().isDisposed()) { throw new ProcessCanceledException(); } if (isDumb()) { return false; } r.run(); return true; }); if (success) break; } }
Example #2
Source File: ClassPackagePathHeuristic.java From intellij with Apache License 2.0 | 6 votes |
@Override public boolean matchesSource( Project project, TargetInfo target, @Nullable PsiFile sourcePsiFile, File sourceFile, @Nullable TestSize testSize) { if (!(sourcePsiFile instanceof PsiClassOwner)) { return false; } String targetName = target.label.targetName().toString(); if (!targetName.contains("/")) { return false; } return ReadAction.compute(() -> doMatchesSource((PsiClassOwner) sourcePsiFile, targetName)); }
Example #3
Source File: MultipleJavaClassesTestContextProvider.java From intellij with Apache License 2.0 | 6 votes |
/** * Returns a {@link RunConfigurationContext} future setting up the relevant test target pattern, * if one can be found. */ @Nullable private static ListenableFuture<TargetInfo> getTargetContext(PsiDirectory dir) { Project project = dir.getProject(); ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project); if (!index.isInTestSourceContent(dir.getVirtualFile())) { return null; } if (BlazePackage.isBlazePackage(dir)) { // this case is handled by a separate run config producer return null; } ListenableFuture<Set<PsiClass>> classes = findAllTestClassesBeneathDirectory(dir); if (classes == null) { return null; } return Futures.transformAsync( classes, set -> set == null ? null : ReadAction.compute(() -> getTestTargetIfUnique(project, set)), EXECUTOR); }
Example #4
Source File: CtrlMouseHandler.java From consulo with Apache License 2.0 | 6 votes |
void execute(@Nonnull BrowseMode browseMode) { myBrowseMode = browseMode; if (PsiDocumentManager.getInstance(myProject).getPsiFile(myHostEditor.getDocument()) == null) return; int selStart = myHostEditor.getSelectionModel().getSelectionStart(); int selEnd = myHostEditor.getSelectionModel().getSelectionEnd(); if (myHostOffset >= selStart && myHostOffset < selEnd) { disposeHighlighter(); return; } myExecutionProgress = ReadAction.nonBlocking(() -> doExecute()).withDocumentsCommitted(myProject).expireWhen(() -> isTaskOutdated(myHostEditor)) .finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).submit(AppExecutorUtil.getAppExecutorService()); }
Example #5
Source File: FindInProjectUtil.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull public static String buildStringToFindForIndicesFromRegExp(@Nonnull String stringToFind, @Nonnull Project project) { if (!Registry.is("idea.regexp.search.uses.indices")) return ""; return ReadAction.compute(() -> { final List<PsiElement> topLevelRegExpChars = getTopLevelRegExpChars("a", project); if (topLevelRegExpChars.size() != 1) return ""; // leave only top level regExpChars return StringUtil.join(getTopLevelRegExpChars(stringToFind, project), new Function<PsiElement, String>() { final Class regExpCharPsiClass = topLevelRegExpChars.get(0).getClass(); @Override public String fun(PsiElement element) { if (regExpCharPsiClass.isInstance(element)) { String text = element.getText(); if (!text.startsWith("\\")) return text; } return " "; } }, ""); }); }
Example #6
Source File: BlazeNativeAndroidDebugger.java From intellij with Apache License 2.0 | 6 votes |
@VisibleForTesting @Override @Nullable public Module findModuleForProcess(Project project, String packageName) { for (Module module : ModuleManager.getInstance(project).getModules()) { if (AndroidFacet.getInstance(module) == null) { continue; // A module must have an attached AndroidFacet to have a package name. } BlazeModuleSystem moduleSystem = BlazeModuleSystem.getInstance(module); String modulePackageName = ReadAction.compute(() -> moduleSystem.getPackageName()); if (modulePackageName != null && modulePackageName.equals(packageName)) { return module; } } return null; }
Example #7
Source File: UsageViewImpl.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public CompletableFuture<?> appendUsagesInBulk(@Nonnull Collection<? extends Usage> usages) { CompletableFuture<Object> result = new CompletableFuture<>(); addUpdateRequest(() -> ReadAction.run(() -> { try { for (Usage usage : usages) { doAppendUsage(usage); } result.complete(null); } catch (Exception e) { result.completeExceptionally(e); throw e; } })); return result; }
Example #8
Source File: PsiBasedClassFileFinder.java From intellij with Apache License 2.0 | 6 votes |
private void registerResourcePackage(TargetIdeInfo resourceDependencyTarget) { AndroidIdeInfo androidIdeInfo = resourceDependencyTarget.getAndroidIdeInfo(); if (androidIdeInfo == null || Strings.isNullOrEmpty(androidIdeInfo.getResourceJavaPackage())) { return; } ResourceRepositoryManager repositoryManager = ResourceRepositoryManagerCompat.getResourceRepositoryManager(module); ResourceIdManager idManager = ResourceIdManager.get(module); if (repositoryManager == null) { return; } // TODO(namespaces) ResourceNamespace namespace = ReadAction.compute(() -> repositoryManager.getNamespace()); ResourceClassRegistry.get(module.getProject()) .addLibrary( ResourceRepositoryManagerCompat.getAppResources(repositoryManager), idManager, androidIdeInfo.getResourceJavaPackage(), namespace); }
Example #9
Source File: QualifiedClassNameHeuristic.java From intellij with Apache License 2.0 | 6 votes |
@Override public boolean matchesSource( Project project, TargetInfo target, @Nullable PsiFile sourcePsiFile, File sourceFile, @Nullable TestSize testSize) { if (!(sourcePsiFile instanceof PsiClassOwner)) { return false; } String targetName = target.label.targetName().toString(); if (!targetName.contains(".")) { return false; } return ReadAction.compute(() -> doMatchesSource((PsiClassOwner) sourcePsiFile, targetName)); }
Example #10
Source File: TestClassHeuristic.java From intellij with Apache License 2.0 | 6 votes |
@Override public boolean matchesSource( Project project, TargetInfo target, @Nullable PsiFile sourcePsiFile, File sourceFile, @Nullable TestSize testSize) { if (!(sourcePsiFile instanceof PsiClassOwner)) { return false; } if (target.testClass == null) { return false; } return ReadAction.compute( () -> doMatchesSource((PsiClassOwner) sourcePsiFile, target.testClass)); }
Example #11
Source File: RefElementImpl.java From consulo with Apache License 2.0 | 6 votes |
@Override public boolean isValid() { if (myIsDeleted) return false; return ReadAction.compute(() -> { if (getRefManager().getProject().isDisposed()) return false; final PsiFile file = myID.getContainingFile(); //no need to check resolve in offline mode if (ApplicationManager.getApplication().isHeadlessEnvironment()) { return file != null && file.isPhysical(); } final PsiElement element = getPsiElement(); return element != null && element.isPhysical(); }); }
Example #12
Source File: AsyncFilterRunner.java From consulo with Apache License 2.0 | 6 votes |
void highlightHyperlinks(@Nonnull Project project, @Nonnull Filter customFilter, final int startLine, final int endLine) { if (endLine < 0) return; myQueue.offer(new HighlighterJob(project, customFilter, startLine, endLine, myEditor.getDocument())); if (ApplicationManager.getApplication().isWriteAccessAllowed()) { runTasks(); highlightAvailableResults(); return; } Promise<?> promise = ReadAction.nonBlocking(this::runTasks).submit(ourExecutor); if (isQuick(promise)) { highlightAvailableResults(); } else { promise.onSuccess(__ -> { if (hasResults()) { ApplicationManager.getApplication().invokeLater(this::highlightAvailableResults, ModalityState.any()); } }); } }
Example #13
Source File: FindInProjectUtil.java From consulo with Apache License 2.0 | 6 votes |
static int processUsagesInFile(@Nonnull final PsiFile psiFile, @Nonnull final VirtualFile virtualFile, @Nonnull final FindModel findModel, @Nonnull final Processor<? super UsageInfo> consumer) { if (findModel.getStringToFind().isEmpty()) { if (!ReadAction.compute(() -> consumer.process(new UsageInfo(psiFile)))) { throw new ProcessCanceledException(); } return 1; } if (virtualFile.getFileType().isBinary()) return 0; // do not decompile .class files final Document document = ReadAction.compute(() -> virtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(virtualFile) : null); if (document == null) return 0; final int[] offset = {0}; int count = 0; int found; ProgressIndicator indicator = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator()); TooManyUsagesStatus tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator); do { tooManyUsagesStatus.pauseProcessingIfTooManyUsages(); // wait for user out of read action found = ReadAction.compute(() -> { if (!psiFile.isValid()) return 0; return addToUsages(document, findModel, psiFile, offset, USAGES_PER_READ_ACTION, consumer); }); count += found; } while (found != 0); return count; }
Example #14
Source File: DelegatingSwitchToHeaderOrSourceProvider.java From intellij with Apache License 2.0 | 6 votes |
/** * Runs the getter under a progress indicator that cancels itself after a certain timeout (assumes * that the getter will check for cancellation cooperatively). * * @param getter computes the GotoRelatedItems. * @return a list of items computed, or Optional.empty if timed out. */ private Optional<List<? extends GotoRelatedItem>> getItemsWithTimeout( ThrowableComputable<List<? extends GotoRelatedItem>, RuntimeException> getter) { try { ProgressIndicator indicator = new ProgressIndicatorBase(); ProgressIndicator wrappedIndicator = new WatchdogIndicator(indicator, TIMEOUT_MS, TimeUnit.MILLISECONDS); // We don't use "runProcessWithProgressSynchronously" because that pops up a ProgressWindow, // and that will cause the event IDs to bump up and no longer match the event ID stored in // DataContexts which may be used in one of the GotoRelatedProvider#getItems overloads. return Optional.of( ProgressManager.getInstance() .runProcess(() -> ReadAction.compute(getter), wrappedIndicator)); } catch (ProcessCanceledException e) { return Optional.empty(); } }
Example #15
Source File: XSourcePositionImpl.java From consulo with Apache License 2.0 | 5 votes |
/** * do not call this method from plugins, use {@link XDebuggerUtil#createPositionByOffset(VirtualFile, int)} instead */ @Nullable public static XSourcePositionImpl createByOffset(@Nullable VirtualFile file, final int offset) { if (file == null) return null; return new XSourcePositionImpl(file) { private final AtomicNotNullLazyValue<Integer> myLine = new AtomicNotNullLazyValue<Integer>() { @Nonnull @Override protected Integer compute() { return ReadAction.compute(() -> { Document document = FileDocumentManager.getInstance().getDocument(file); if (document == null) { return -1; } return DocumentUtil.isValidOffset(offset, document) ? document.getLineNumber(offset) : -1; }); } }; @Override public int getLine() { return myLine.getValue(); } @Override public int getOffset() { return offset; } }; }
Example #16
Source File: WolfTheProblemSolverImpl.java From consulo with Apache License 2.0 | 5 votes |
@Override public Problem convertToProblem(@Nullable final VirtualFile virtualFile, final int line, final int column, @Nonnull final String[] message) { if (virtualFile == null || virtualFile.isDirectory() || virtualFile.getFileType().isBinary()) return null; HighlightInfo info = ReadAction.compute(() -> { TextRange textRange = getTextRange(virtualFile, line, column); String description = StringUtil.join(message, "\n"); return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(textRange).descriptionAndTooltip(description).create(); }); if (info == null) return null; return new ProblemImpl(virtualFile, info, false); }
Example #17
Source File: CSharpMethodImplementationsSearcher.java From consulo-csharp with Apache License 2.0 | 5 votes |
@Override public boolean execute(@Nonnull DefinitionsScopedSearch.SearchParameters queryParameters, @Nonnull Processor<? super PsiElement> consumer) { PsiElement element = queryParameters.getElement(); if(element instanceof DotNetVirtualImplementOwner) { Collection<DotNetVirtualImplementOwner> members = ReadAction.compute(() -> OverrideUtil.collectOverridenMembers((DotNetVirtualImplementOwner) element)); return ContainerUtil.process(members, consumer); } return true; }
Example #18
Source File: PsiDocumentManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
public PsiDocumentManagerImpl(@Nonnull Project project, @Nonnull DocumentCommitProcessor documentCommitProcessor) { super(project, documentCommitProcessor); EditorFactory.getInstance().getEventMulticaster().addDocumentListener(this, this); ((EditorEventMulticasterImpl)EditorFactory.getInstance().getEventMulticaster()).addPrioritizedDocumentListener(new PriorityEventCollector(), this); MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerListener() { @Override public void fileContentLoaded(@Nonnull final VirtualFile virtualFile, @Nonnull Document document) { PsiFile psiFile = ReadAction.compute(() -> myProject.isDisposed() || !virtualFile.isValid() ? null : getCachedPsiFile(virtualFile)); fireDocumentCreated(document, psiFile); } }); Disposer.register(this, () -> ((DocumentCommitThread)myDocumentCommitProcessor).cancelTasksOnProjectDispose(project)); }
Example #19
Source File: FindInProjectTask.java From consulo with Apache License 2.0 | 5 votes |
FindInProjectTask(@Nonnull final FindModel findModel, @Nonnull final Project project, @Nonnull Set<? extends VirtualFile> filesToScanInitially) { myFindModel = findModel; myProject = project; myFilesToScanInitially = filesToScanInitially; myDirectory = FindInProjectUtil.getDirectory(findModel); myPsiManager = PsiManager.getInstance(project); final String moduleName = findModel.getModuleName(); myModule = moduleName == null ? null : ReadAction.compute(() -> ModuleManager.getInstance(project).findModuleByName(moduleName)); myProjectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); myFileIndex = myModule == null ? myProjectFileIndex : ModuleRootManager.getInstance(myModule).getFileIndex(); Condition<CharSequence> patternCondition = FindInProjectUtil.createFileMaskCondition(findModel.getFileFilter()); myFileMask = file -> file != null && patternCondition.value(file.getNameSequence()); final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); myProgress = progress != null ? progress : new EmptyProgressIndicator(); String stringToFind = myFindModel.getStringToFind(); if (myFindModel.isRegularExpressions()) { stringToFind = FindInProjectUtil.buildStringToFindForIndicesFromRegExp(stringToFind, myProject); } myStringToFindInIndices = stringToFind; TooManyUsagesStatus.createFor(myProgress); }
Example #20
Source File: SelfElementInfo.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public static PsiDirectory restoreDirectoryFromVirtual(@Nonnull VirtualFile virtualFile, @Nonnull final Project project) { return ReadAction.compute(() -> { if (project.isDisposed()) return null; VirtualFile child = restoreVFile(virtualFile); if (child == null || !child.isValid()) return null; PsiDirectory file = PsiManager.getInstance(project).findDirectory(child); if (file == null || !file.isValid()) return null; return file; }); }
Example #21
Source File: DefaultSearchScopeProviders.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public List<SearchScope> getSearchScopes(@Nonnull Project project) { FavoritesManager favoritesManager = FavoritesManager.getInstance(project); if (favoritesManager == null) return Collections.emptyList(); List<SearchScope> result = new ArrayList<>(); for (String favorite : favoritesManager.getAvailableFavoritesListNames()) { Collection<TreeItem<Pair<AbstractUrl, String>>> rootUrls = favoritesManager.getFavoritesListRootUrls(favorite); if (rootUrls.isEmpty()) continue; // ignore unused root result.add(new GlobalSearchScope(project) { @Nonnull @Override public String getDisplayName() { return "Favorite \'" + favorite + "\'"; } @Override public boolean contains(@Nonnull VirtualFile file) { return ReadAction.compute(() -> favoritesManager.contains(favorite, file)); } @Override public boolean isSearchInModuleContent(@Nonnull Module aModule) { return true; } @Override public boolean isSearchInLibraries() { return true; } }); } return result; }
Example #22
Source File: ScratchTreeStructureProvider.java From consulo with Apache License 2.0 | 5 votes |
private static void registerRootTypeUpdater(@Nonnull Project project, @Nonnull RootType rootType, @Nonnull Runnable onUpdate, @Nonnull Disposable parentDisposable, @Nonnull Map<RootType, Disposable> disposables) { if (rootType.isHidden()) return; Disposable rootDisposable = disposables.get(rootType); Disposer.register(parentDisposable, rootDisposable); ReadAction.nonBlocking(() -> rootType.registerTreeUpdater(project, parentDisposable, onUpdate)).expireWith(parentDisposable).submit(NonUrgentExecutor.getInstance()); }
Example #23
Source File: AbstractLayoutCodeProcessor.java From consulo with Apache License 2.0 | 5 votes |
private void performFileProcessing(@Nonnull PsiFile file) { for (AbstractLayoutCodeProcessor processor : myProcessors) { FutureTask<Boolean> writeTask = ReadAction.compute(() -> processor.prepareTask(file, myProcessChangedTextOnly)); ProgressIndicatorProvider.checkCanceled(); ApplicationManager.getApplication().invokeAndWait(() -> WriteCommandAction.runWriteCommandAction(myProject, myCommandName, null, writeTask)); checkStop(writeTask, file); } }
Example #24
Source File: RefManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
private boolean belongsToScope(final PsiElement psiElement, final boolean ignoreScope) { if (psiElement == null || !psiElement.isValid()) return false; if (psiElement instanceof PsiCompiledElement) return false; final PsiFile containingFile = ReadAction.compute(psiElement::getContainingFile); if (containingFile == null) { return false; } for (RefManagerExtension extension : myExtensions.values()) { if (!extension.belongsToScope(psiElement)) return false; } final Boolean inProject = ReadAction.compute(() -> psiElement.getManager().isInProject(psiElement)); return inProject.booleanValue() && (ignoreScope || getScope() == null || getScope().contains(psiElement)); }
Example #25
Source File: RefManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public RefElement getReference(PsiElement elem, final boolean ignoreScope) { if (ReadAction.compute(() -> elem == null || !elem.isValid() || elem instanceof LightElement || !(elem instanceof PsiDirectory) && !belongsToScope(elem, ignoreScope))) { return null; } return getFromRefTableOrCache(elem, () -> ReadAction.compute(() -> { final RefManagerExtension extension = getExtension(elem.getLanguage()); if (extension != null) { final RefElement refElement = extension.createRefElement(elem); if (refElement != null) return (RefElementImpl)refElement; } if (elem instanceof PsiFile) { return new RefFileImpl((PsiFile)elem, this); } if (elem instanceof PsiDirectory) { return new RefDirectoryImpl((PsiDirectory)elem, this); } return null; }), element -> ReadAction.run(() -> { element.initialize(); for (RefManagerExtension each : myExtensions.values()) { each.onEntityInitialized(element, elem); } fireNodeInitialized(element); })); }
Example #26
Source File: PsiElementListCellRenderer.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public Comparable getComparingObject(T element) { return ReadAction.compute(() -> { String elementText = getElementText(element); String containerText = getContainerText(element, elementText); return containerText == null ? elementText : elementText + " " + containerText; }); }
Example #27
Source File: RefManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public List<RefElement> getSortedElements() { List<RefElement> answer = myCachedSortedRefs; if (answer != null) return answer; answer = new ArrayList<>(myRefTable.values()); List<RefElement> list = answer; ReadAction.run(() -> ContainerUtil.quickSort(list, (o1, o2) -> { VirtualFile v1 = ((RefElementImpl)o1).getVirtualFile(); VirtualFile v2 = ((RefElementImpl)o2).getVirtualFile(); return (v1 != null ? v1.hashCode() : 0) - (v2 != null ? v2.hashCode() : 0); })); myCachedSortedRefs = answer = Collections.unmodifiableList(answer); return answer; }
Example #28
Source File: PsiTreeAnchorizer.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public Object createAnchor(@Nonnull Object element) { if (element instanceof PsiElement) { PsiElement psi = (PsiElement)element; return ReadAction.compute(() -> { if (!psi.isValid()) return psi; return SmartPointerManager.getInstance(psi.getProject()).createSmartPsiElementPointer(psi); }); } return super.createAnchor(element); }
Example #29
Source File: HaxeFindUsagesHandler.java From intellij-haxe with Apache License 2.0 | 5 votes |
@NotNull @Override public PsiElement[] getSecondaryElements() { PsiElement[] secondaryElements = ReadAction.compute(() -> { if (getPsiElement() instanceof HaxeMethodDeclaration) { return tryGetProperty((HaxeMethodDeclaration)getPsiElement()); } else if (getPsiElement() instanceof HaxeFieldDeclaration && ((HaxeFieldDeclaration)getPsiElement()).getPropertyDeclaration() != null) { return tryGetPropertyAccessMethods((HaxeFieldDeclaration)getPsiElement()); } return null; }); return secondaryElements == null ? super.getSecondaryElements() : secondaryElements; }
Example #30
Source File: IsExpressionEvaluator.java From consulo-csharp with Apache License 2.0 | 5 votes |
@Override public void evaluate(@Nonnull CSharpEvaluateContext context) { DotNetValueProxy pop = context.popValue(); if(pop == null) { return; } DotNetTypeProxy type = pop.getType(); if(type == null) { return; } DotNetTypeRef typeRef = ReadAction.compute(() -> myExpression.getIsTypeRef()); PsiElement element = ReadAction.compute(() -> typeRef.resolve().getElement()); DotNetTypeProxy typeMirror = ReadAction.compute(() -> findTypeMirror(context, element)); if(typeMirror == null) { return; } DotNetVirtualMachineProxy virtualMachine = context.getDebuggerContext().getVirtualMachine(); context.pull(virtualMachine.createBooleanValue(typeMirror.isAssignableFrom(type)), null); }