Java Code Examples for com.intellij.openapi.application.ReadAction#compute()

The following examples show how to use com.intellij.openapi.application.ReadAction#compute() . 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 vote down vote up
/**
 * 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: BlazeNativeAndroidDebugger.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: ExcludeRootsCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
String[] getExcludedUrls() {
  return ReadAction.compute(() -> {
    CachedUrls cache = myCache;
    long actualModCount = Arrays.stream(ProjectManager.getInstance().getOpenProjects()).map(ProjectRootManager::getInstance).mapToLong(ProjectRootManager::getModificationCount).sum();
    String[] urls;
    if (cache != null && actualModCount == cache.myModificationCount) {
      urls = cache.myUrls;
    }
    else {
      Collection<String> excludedUrls = new THashSet<>();
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        for (Module module : ModuleManager.getInstance(project).getModules()) {
          urls = ModuleRootManager.getInstance(module).getExcludeRootUrls();
          ContainerUtil.addAll(excludedUrls, urls);
        }
      }
      urls = ArrayUtilRt.toStringArray(excludedUrls);
      Arrays.sort(urls);
      myCache = new CachedUrls(actualModCount, urls);
    }
    return urls;
  });
}
 
Example 4
Source File: ClassPackagePathHeuristic.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: RefElementImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: TestClassHeuristic.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: PsiTreeAnchorizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Object retrieveElement(@Nonnull final Object pointer) {
  if (pointer instanceof SmartPsiElementPointer) {
    return ReadAction.compute(() -> ((SmartPsiElementPointer)pointer).getElement());
  }

  return super.retrieveElement(pointer);
}
 
Example 8
Source File: LocalFileSystemRefreshWorker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void fullDirRefresh(@Nonnull VirtualDirectoryImpl dir, @Nonnull RefreshContext refreshContext) {
  while (true) {
    // obtaining directory snapshot
    Pair<String[], VirtualFile[]> result = getDirectorySnapshot(refreshContext.persistence, dir);
    if (result == null) return;
    String[] persistedNames = result.getFirst();
    VirtualFile[] children = result.getSecond();

    RefreshingFileVisitor refreshingFileVisitor = new RefreshingFileVisitor(dir, refreshContext, null, Arrays.asList(children));
    refreshingFileVisitor.visit(dir);
    if (myCancelled) {
      addAllEventsFrom(refreshingFileVisitor);
      break;
    }

    // generating events unless a directory was changed in between
    boolean hasEvents = ReadAction.compute(() -> {
      if (ApplicationManager.getApplication().isDisposed()) {
        return true;
      }
      if (!Arrays.equals(persistedNames, refreshContext.persistence.list(dir)) || !Arrays.equals(children, dir.getChildren())) {
        if (LOG.isDebugEnabled()) LOG.debug("retry: " + dir);
        return false;
      }

      addAllEventsFrom(refreshingFileVisitor);
      return true;
    });
    if (hasEvents) {
      break;
    }
  }
}
 
Example 9
Source File: SelfElementInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static PsiFile restoreFileFromVirtual(@Nonnull VirtualFile virtualFile, @Nonnull Project project, @Nonnull Language language) {
  return ReadAction.compute(() -> {
    if (project.isDisposed()) return null;
    VirtualFile child = restoreVFile(virtualFile);
    if (child == null || !child.isValid()) return null;
    PsiFile file = PsiManager.getInstance(project).findFile(child);
    if (file != null) {
      return file.getViewProvider().getPsi(language == Language.ANY ? file.getViewProvider().getBaseLanguage() : language);
    }

    return null;
  });
}
 
Example 10
Source File: PsiTreeAnchorizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: FileTypeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int readSafely(@Nonnull InputStream stream, @Nonnull byte[] buffer, int offset, int length) throws IOException {
  int n = stream.read(buffer, offset, length);
  if (n <= 0) {
    // maybe locked because someone else is writing to it
    // repeat inside read action to guarantee all writes are finished
    if (toLog()) {
      log("F: processFirstBytes(): inputStream.read() returned " + n + "; retrying with read action. stream=" + streamInfo(stream));
    }
    n = ReadAction.compute(() -> stream.read(buffer, offset, length));
    if (toLog()) {
      log("F: processFirstBytes(): under read action inputStream.read() returned " + n + "; stream=" + streamInfo(stream));
    }
  }
  return n;
}
 
Example 12
Source File: CSharpMethodImplementationsSearcher.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
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 14
Source File: XSourcePositionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * 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 15
Source File: ModuleToDoNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getTodoItemCount(final Module val) {
  Iterator<PsiFile> iterator = myBuilder.getFiles(val);
  int count = 0;
  while (iterator.hasNext()) {
    final PsiFile psiFile = iterator.next();
    count += ReadAction.compute(() -> getTreeStructure().getTodoItemCount(psiFile));
  }
  return count;
}
 
Example 16
Source File: BlazeGoSdkUpdater.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Module getWorkspaceModule(Project project) {
  return ReadAction.compute(
      () ->
          ModuleManager.getInstance(project)
              .findModuleByName(BlazeDataStorage.WORKSPACE_MODULE_NAME));
}
 
Example 17
Source File: FindInProjectTask.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void findUsages(@Nonnull FindUsagesProcessPresentation processPresentation, @Nonnull Processor<? super UsageInfo> consumer) {
  try {
    myProgress.setIndeterminate(true);
    myProgress.setText("Scanning indexed files...");
    Set<VirtualFile> filesForFastWordSearch = ReadAction.compute(this::getFilesForFastWordSearch);
    myProgress.setIndeterminate(false);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Searching for " + myFindModel.getStringToFind() + " in " + filesForFastWordSearch.size() + " indexed files");
    }

    searchInFiles(filesForFastWordSearch, processPresentation, consumer);

    myProgress.setIndeterminate(true);
    myProgress.setText("Scanning non-indexed files...");
    boolean canRelyOnIndices = canRelyOnIndices();
    final Collection<VirtualFile> otherFiles = collectFilesInScope(filesForFastWordSearch, canRelyOnIndices);
    myProgress.setIndeterminate(false);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Searching for " + myFindModel.getStringToFind() + " in " + otherFiles.size() + " non-indexed files");
    }
    myProgress.checkCanceled();
    long start = System.currentTimeMillis();
    searchInFiles(otherFiles, processPresentation, consumer);
    if (canRelyOnIndices && otherFiles.size() > 1000) {
      long time = System.currentTimeMillis() - start;
      logStats(otherFiles, time);
    }
  }
  catch (ProcessCanceledException e) {
    processPresentation.setCanceled(true);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Usage search canceled", e);
    }
  }

  if (!myLargeFiles.isEmpty()) {
    processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
  }

  if (!myProgress.isCanceled()) {
    myProgress.setText(FindBundle.message("find.progress.search.completed"));
  }
}
 
Example 18
Source File: GeneratedSourcesFilter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isGeneratedSourceByAnyFilter(@Nonnull VirtualFile file, @Nonnull Project project) {
  return ReadAction.compute(() -> !project.isDisposed() && file.isValid() && EP_NAME.getExtensionList().stream().anyMatch(filter -> filter.isGeneratedSource(file, project)));
}
 
Example 19
Source File: AndroidTestContextProvider.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Nullable
private String getClassName() {
  return ReadAction.compute(() -> psiClass.getQualifiedName());
}
 
Example 20
Source File: PsiBasedClassFileFinder.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public VirtualFile findClassFile(String fqcn) {
  GlobalSearchScope searchScope = module.getModuleRuntimeScope(false);

  PsiClass[] psiClasses =
      ReadAction.compute(
          () ->
              JavaPsiFacade.getInstance(project)
                  .findClasses(getContainingClassName(fqcn), searchScope));
  if (psiClasses.length == 0) {
    return null;
  }

  BlazeProjectData projectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (projectData == null) {
    return null;
  }

  // It's possible that there's more than one source file in the project corresponding to
  // the same fully-qualified class name, with Blaze choosing the appropriate source to use
  // according to some configuration flags. Here we check each of them until we find the one
  // that was chosen during Blaze sync.
  for (PsiClass psiClass : psiClasses) {
    PsiFile psiFile = psiClass.getContainingFile();
    if (psiFile == null) {
      continue;
    }

    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile == null) {
      continue;
    }

    FileType fileType = psiFile.getFileType();
    VirtualFile classFile = null;

    if (fileType == StdFileTypes.JAVA) {
      classFile =
          findClassFileForSourceAndRegisterResourcePackage(projectData, virtualFile, fqcn);
    } else if (fileType == StdFileTypes.CLASS) {
      classFile = findClassFileForIJarClass(projectData, virtualFile, fqcn);
    }

    if (classFile != null) {
      return classFile;
    }
  }

  return null;
}