Java 类com.intellij.openapi.application.ReadAction 实例源码

项目:intellij-ce-playground    文件:ProjectStructureDaemonAnalyzer.java   
private void doCollectUsages(final ProjectStructureElement element) {
  final List<ProjectStructureElementUsage> usages = new ReadAction<List<ProjectStructureElementUsage>>() {
    @Override
    protected void run(@NotNull final Result<List<ProjectStructureElementUsage>> result) {
      if (myStopped.get()) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("collecting usages in " + element);
      }
      result.setResult(getUsagesInElement(element));
    }
  }.execute().getResultObject();
  if (usages != null) {
    myResultsUpdateQueue.queue(new UsagesCollectedUpdate(element, usages));
  }
}
项目:intellij-ce-playground    文件:ArtifactCompilerUtil.java   
public static MultiMap<String, Artifact> createOutputToArtifactMap(final Project project) {
  final MultiMap<String, Artifact> result = MultiMap.create(FileUtil.PATH_HASHING_STRATEGY);
  new ReadAction() {
    protected void run(@NotNull final Result r) {
      for (Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) {
        String outputPath = artifact.getOutputFilePath();
        if (!StringUtil.isEmpty(outputPath)) {
          result.putValue(outputPath, artifact);
        }
      }
    }
  }.execute();


  return result;
}
项目:intellij-ce-playground    文件:PsiVisitors.java   
/**
 * Read action will be taken automatically
 */
public static <RESULT> RESULT visit(@NotNull XSourcePosition position, @NotNull Project project, @NotNull Visitor<RESULT> visitor, RESULT defaultResult) {
  AccessToken token = ReadAction.start();
  try {
    Document document = FileDocumentManager.getInstance().getDocument(position.getFile());
    PsiFile file = document == null || document.getTextLength() == 0 ? null : PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
      return defaultResult;
    }

    int positionOffset;
    int column = position instanceof SourceInfo ? Math.max(((SourceInfo)position).getColumn(), 0) : 0;
    try {
      positionOffset = column == 0 ? DocumentUtil.getFirstNonSpaceCharOffset(document, position.getLine()) : document.getLineStartOffset(position.getLine()) + column;
    }
    catch (IndexOutOfBoundsException ignored) {
      return defaultResult;
    }

    PsiElement element = file.findElementAt(positionOffset);
    return element == null ? defaultResult : visitor.visit(element, positionOffset, document);
  }
  finally {
    token.finish();
  }
}
项目:intellij-ce-playground    文件:SourceInfo.java   
@Override
public int getOffset() {
  if (offset == -1) {
    Document document;
    AccessToken token = ReadAction.start();
    try {
      document = file.isValid() ? FileDocumentManager.getInstance().getDocument(file) : null;
    }
    finally {
      token.finish();
    }

    if (document == null) {
      return -1;
    }

    offset = line < document.getLineCount() ? document.getLineStartOffset(line) : -1;
  }
  return offset;
}
项目:intellij-ce-playground    文件:FormatChangedTextUtil.java   
/**
 * Allows to answer if any file that belongs to the given project has changes in comparison with VCS.
 * 
 * @param project  target project to check
 * @return         <code>true</code> if any file that belongs to the given project has changes in comparison with VCS
 *                 <code>false</code> otherwise
 */
public static boolean hasChanges(@NotNull final Project project) {
  final ModifiableModuleModel moduleModel = new ReadAction<ModifiableModuleModel>() {
    @Override
    protected void run(@NotNull Result<ModifiableModuleModel> result) throws Throwable {
      result.setResult(ModuleManager.getInstance(project).getModifiableModel());
    }
  }.execute().getResultObject();
  try {
    for (Module module : moduleModel.getModules()) {
      if (hasChanges(module)) {
        return true;
      }
    }
    return false;
  }
  finally {
    moduleModel.dispose();
  }
}
项目:intellij-ce-playground    文件:GeneratedSourceFileChangeTrackerImpl.java   
private void checkFiles() {
  final VirtualFile[] files;
  synchronized (myFilesToCheck) {
    files = myFilesToCheck.toArray(new VirtualFile[myFilesToCheck.size()]);
    myFilesToCheck.clear();
  }
  final List<VirtualFile> newEditedGeneratedFiles = new ArrayList<VirtualFile>();
  new ReadAction() {
    protected void run(final @NotNull Result result) {
      if (myProject.isDisposed()) return;
      for (VirtualFile file : files) {
        if (isGenerated(file)) {
          newEditedGeneratedFiles.add(file);
        }
      }
    }
  }.execute();

  if (!newEditedGeneratedFiles.isEmpty()) {
    myEditedGeneratedFiles.addAll(newEditedGeneratedFiles);
    myEditorNotifications.updateAllNotifications();
  }
}
项目:intellij-ce-playground    文件:PyMagicLiteralReferenceSearcher.java   
@Override
public void processQuery(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final Processor<PsiReference> consumer) {
  new ReadAction() {
    @Override
    protected void run(@NotNull final Result result) throws Throwable {
      final PsiElement refElement = queryParameters.getElementToSearch();
      if (PyMagicLiteralTools.isMagicLiteral(refElement)) {
        final String refText = ((StringLiteralExpression)refElement).getStringValue();
        if (!StringUtil.isEmpty(refText)) {
          final SearchScope searchScope = queryParameters.getEffectiveSearchScope();
          queryParameters.getOptimizer().searchWord(refText, searchScope, true, refElement);
        }
      }
    }
  }.execute();
}
项目:intellij-ce-playground    文件:PyIronPythonTest.java   
/**
 * Tests skeletons for built-in classes. We can't compare files (CLR class may be changed from version to version),
 * but we are sure there should be class System.Web.AspNetHostingPermissionLevel which is part of public API
 */
public void testImportBuiltInSystem() throws Exception {
  final SkeletonTestTask task = new SkeletonTestTask(
    null,
    "System.Web",
    "import_system.py",
    null
  );
  runPythonTest(task);
  final PyFile skeleton = task.getGeneratedSkeleton();
  new ReadAction() {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      Assert.assertNotNull("System.Web does not contain class AspNetHostingPermissionLevel. Error generating stub? It has classes  " +
                           skeleton.getTopLevelClasses(),
                           skeleton.findTopLevelClass("AspNetHostingPermissionLevel"));
    }
  }.execute();

}
项目:intellij-ce-playground    文件:OpenInBrowserRequest.java   
@Nullable
public static OpenInBrowserRequest create(@NotNull final PsiElement element) {
  PsiFile psiFile;
  AccessToken token = ReadAction.start();
  try {
    psiFile = element.isValid() ? element.getContainingFile() : null;
    if (psiFile == null || psiFile.getVirtualFile() == null) {
      return null;
    }
  }
  finally {
    token.finish();
  }

  return new OpenInBrowserRequest(psiFile) {
    @NotNull
    @Override
    public PsiElement getElement() {
      return element;
    }
  };
}
项目:intellij-ce-playground    文件:GradleCompilingTestCase.java   
@Override
protected void setUpInWriteAction() throws Exception {
  super.setUpInWriteAction();

  final GradleResourceCompilerConfigurationGenerator buildConfigurationGenerator = new GradleResourceCompilerConfigurationGenerator(myProject);
  CompilerManager.getInstance(myProject).addBeforeTask(new CompileTask() {
    @Override
    public boolean execute(CompileContext context) {
      AccessToken token = ReadAction.start();
      try {
        buildConfigurationGenerator.generateBuildConfiguration(context);
      }
      finally {
        token.finish();
      }
      return true;
    }
  });
}
项目:intellij-ce-playground    文件:GradleStartupActivity.java   
@Override
public void runActivity(@NotNull final Project project) {
  configureBuildClasspath(project);
  showNotificationForUnlinkedGradleProject(project);

  final GradleResourceCompilerConfigurationGenerator buildConfigurationGenerator = new GradleResourceCompilerConfigurationGenerator(project);
  CompilerManager.getInstance(project).addBeforeTask(new CompileTask() {
    @Override
    public boolean execute(CompileContext context) {
      AccessToken token = ReadAction.start();
      try {
        buildConfigurationGenerator.generateBuildConfiguration(context);
      }
      finally {
        token.finish();
      }
      return true;
    }
  });
}
项目:intellij-ce-playground    文件:MavenProjectIndicesManager.java   
public void scheduleUpdateIndicesList(@Nullable final Consumer<List<MavenIndex>> consumer) {
  myUpdateQueue.queue(new Update(MavenProjectIndicesManager.this) {
    public void run() {
      Set<Pair<String, String>> remoteRepositoriesIdsAndUrls;
      File localRepository;

      AccessToken accessToken = ReadAction.start();

      try {
        if (myProject.isDisposed()) return;

        remoteRepositoriesIdsAndUrls = collectRemoteRepositoriesIdsAndUrls();
        localRepository = getLocalRepository();
      }
      finally {
        accessToken.finish();
      }

      myProjectIndices = MavenIndicesManager.getInstance().ensureIndicesExist(myProject, localRepository, remoteRepositoriesIdsAndUrls);
      if(consumer != null) {
        consumer.consume(myProjectIndices);
      }
    }
  });
}
项目:intellij-ce-playground    文件:FormReferencesSearcher.java   
private static boolean processReferencesInUIForms(Processor<PsiReference> processor,
                                                  PsiManager psiManager,
                                                  PsiField field,
                                                  GlobalSearchScope scope1,
                                                  LocalSearchScope filterScope) {
  GlobalSearchScope scope = GlobalSearchScope.projectScope(psiManager.getProject()).intersectWith(scope1);
  final AccessToken token = ReadAction.start();
  PsiClass containingClass = field.getContainingClass();
  if (containingClass == null) return true;
  String fieldName;
  try {
    fieldName = field.getName();
  }
  finally {
    token.finish();
  }
  final List<PsiFile> files = FormClassIndex.findFormsBoundToClass(psiManager.getProject(), containingClass, scope);
  return processReferencesInFiles(files, psiManager, fieldName, field, filterScope, processor);
}
项目:intellij-ce-playground    文件:GroovyHotSwapper.java   
private static boolean containsGroovyClasses(final Project project) {
  return CachedValuesManager.getManager(project).getCachedValue(project, new CachedValueProvider<Boolean>() {
    @Nullable
    @Override
    public Result<Boolean> compute() {
      AccessToken accessToken = ReadAction.start();
      try {
        return Result.create(FileTypeIndex.containsFileOfType(GroovyFileType.GROOVY_FILE_TYPE, GlobalSearchScope.projectScope(project)),
                             PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
      }
      finally {
        accessToken.finish();
      }
    }
  });
}
项目:intellij    文件:DelegatingSwitchToHeaderOrSourceProvider.java   
/**
 * 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();
  }
}
项目:tools-idea    文件:ProjectStructureDaemonAnalyzer.java   
private void doCollectUsages(final ProjectStructureElement element) {
  final List<ProjectStructureElementUsage> usages = new ReadAction<List<ProjectStructureElementUsage>>() {
    @Override
    protected void run(final Result<List<ProjectStructureElementUsage>> result) {
      if (myStopped.get()) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("collecting usages in " + element);
      }
      result.setResult(getUsagesInElement(element));
    }
  }.execute().getResultObject();

  invokeLater(new Runnable() {
    @Override
    public void run() {
      if (myStopped.get() || usages == null) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("updating usages for " + element);
      }
      updateUsages(element, usages);
    }
  });
}
项目:tools-idea    文件:InspectionValidatorWrapper.java   
private boolean checkUnderReadAction(PsiFile file, CompileContext context, Computable<Map<ProblemDescriptor, HighlightDisplayLevel>> runnable) {
  AccessToken token = ReadAction.start();
  try {
    if (!file.isValid()) return false;

    final Document document = myPsiDocumentManager.getCachedDocument(file);
    if (document != null && myPsiDocumentManager.isUncommited(document)) {
      final String url = file.getViewProvider().getVirtualFile().getUrl();
      context.addMessage(CompilerMessageCategory.WARNING, CompilerBundle.message("warning.text.file.has.been.changed"), url, -1, -1);
      return false;
    }

    if (reportProblems(context, runnable.compute())) return false;
  }
  finally {
    token.finish();
  }
  return true;
}
项目:tools-idea    文件:ArtifactCompilerUtil.java   
public static MultiMap<String, Artifact> createOutputToArtifactMap(final Project project) {
  final MultiMap<String, Artifact> result = new MultiMap<String, Artifact>() {
    @Override
    protected Map<String, Collection<Artifact>> createMap() {
      return new THashMap<String, Collection<Artifact>>(FileUtil.PATH_HASHING_STRATEGY);
    }
  };
  new ReadAction() {
    protected void run(final Result r) {
      for (Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) {
        String outputPath = artifact.getOutputFilePath();
        if (!StringUtil.isEmpty(outputPath)) {
          result.putValue(outputPath, artifact);
        }
      }
    }
  }.execute();


  return result;
}
项目:tools-idea    文件:ArtifactAdditionalCompileScopeProvider.java   
@Override
public CompileScope getAdditionalScope(@NotNull final CompileScope baseScope, @NotNull CompilerFilter filter, @NotNull final Project project) {
  if (ArtifactCompileScope.getArtifacts(baseScope) != null) {
    return null;
  }
  final ArtifactsCompiler compiler = ArtifactsCompiler.getInstance(project);
  if (compiler == null || !filter.acceptCompiler(compiler)) {
    return null;
  }
  return new ReadAction<CompileScope>() {
    protected void run(final Result<CompileScope> result) {
      final Set<Artifact> artifacts = ArtifactCompileScope.getArtifactsToBuild(project, baseScope, false);
      result.setResult(ArtifactCompileScope.createScopeForModulesInArtifacts(project, artifacts));
    } 
  }.execute().getResultObject();
}
项目:tools-idea    文件:FormatChangedTextUtil.java   
/**
 * Allows to answer if any file that belongs to the given project has changes in comparison with VCS.
 * 
 * @param project  target project to check
 * @return         <code>true</code> if any file that belongs to the given project has changes in comparison with VCS
 *                 <code>false</code> otherwise
 */
public static boolean hasChanges(@NotNull final Project project) {
  final ModifiableModuleModel moduleModel = new ReadAction<ModifiableModuleModel>() {
    @Override
    protected void run(Result<ModifiableModuleModel> result) throws Throwable {
      result.setResult(ModuleManager.getInstance(project).getModifiableModel());
    }
  }.execute().getResultObject();
  try {
    for (Module module : moduleModel.getModules()) {
      if (hasChanges(module)) {
        return true;
      }
    }
    return false;
  }
  finally {
    moduleModel.dispose();
  }
}
项目:consulo-javaee    文件:ApplicationServerUrlMapping.java   
private String getContextForKnownFacet(final @NotNull DeploymentModel deploymentModel, final @NotNull JavaEEModuleExtension javaeeFacet)
{
    String providedContext = getProvidedContext(deploymentModel);
    if(providedContext != null)
    {
        return providedContext;
    }

    return new ReadAction<String>()
    {

        @Override
        protected void run(@NotNull Result<String> result)
        {
            Class facetTypeId = javaeeFacet.getClass();
            for(FacetContextProvider facetContextProvider : getFacetContextProviders())
            {
                if(facetContextProvider.getFacetId().equals(facetTypeId))
                {
                    result.setResult(facetContextProvider.getDeploymentContext(getWebModuleContextProviders(), deploymentModel, javaeeFacet));
                    return;
                }
            }
        }
    }.execute().getResultObject();
}
项目:consulo    文件:TreeStructureWrappenModel.java   
@Override
public void fetchChildren(@Nonnull Function<T, TreeNode<T>> nodeFactory, @javax.annotation.Nullable T parentValue) {
  for (Object o : ReadAction.compute(() -> myStructure.getChildElements(parentValue))) {
    T element = (T)o;
    TreeNode<T> apply = nodeFactory.apply(element);

    apply.setLeaf(o instanceof AbstractTreeNode && !((AbstractTreeNode)o).isAlwaysShowPlus());


    apply.setRender((fileElement, itemPresentation) -> {
      NodeDescriptor descriptor = myStructure.createDescriptor(element, null);

      descriptor.update();

      itemPresentation.append(descriptor.toString());
      try {
        ReadAction.run(() -> itemPresentation.setIcon((consulo.ui.image.Image)descriptor.getIcon()));
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    });
  }
}
项目:consulo    文件:DiffContentFactoryImpl.java   
@javax.annotation.Nullable
private static Document createPsiDocument(@Nonnull Project project,
                                          @Nonnull String content,
                                          @Nonnull FileType fileType,
                                          @Nonnull String fileName,
                                          boolean readOnly) {
  return ReadAction.compute(() -> {
    LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
    file.setWritable(!readOnly);

    file.putUserData(DiffPsiFileSupport.KEY, true);

    Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return null;

    PsiDocumentManager.getInstance(project).getPsiFile(document);

    return document;
  });
}
项目:consulo    文件:ArtifactCompilerUtil.java   
public static MultiMap<String, Artifact> createOutputToArtifactMap(final Project project) {
  final MultiMap<String, Artifact> result = new MultiMap<String, Artifact>() {
    @Nonnull
    @Override
    protected Map<String, Collection<Artifact>> createMap() {
      return new THashMap<String, Collection<Artifact>>(FileUtil.PATH_HASHING_STRATEGY);
    }
  };
  new ReadAction() {
    @Override
    protected void run(final Result r) {
      for (Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) {
        String outputPath = artifact.getOutputFilePath();
        if (!StringUtil.isEmpty(outputPath)) {
          result.putValue(outputPath, artifact);
        }
      }
    }
  }.execute();


  return result;
}
项目:consulo    文件:DumbService.java   
/**
 * Pause the current thread until dumb mode ends, and then run the read action. Index is 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;
  }
}
项目:consulo    文件:SelfElementInfo.java   
@Override
boolean pointsToTheSameElementAs(@Nonnull final SmartPointerElementInfo other) {
  if (other instanceof SelfElementInfo) {
    final SelfElementInfo otherInfo = (SelfElementInfo)other;
    if (!getVirtualFile().equals(other.getVirtualFile()) || myIdentikit != otherInfo.myIdentikit) return false;

    return ReadAction.compute(() -> {
      Segment range1 = getPsiRange();
      Segment range2 = otherInfo.getPsiRange();
      return range1 != null && range2 != null
             && range1.getStartOffset() == range2.getStartOffset()
             && range1.getEndOffset() == range2.getEndOffset();
    });
  }
  return false;
}
项目:consulo    文件:AnchorElementInfo.java   
@Override
public boolean pointsToTheSameElementAs(@Nonnull final SmartPointerElementInfo other) {
  if (other instanceof AnchorElementInfo) {
    if (!getVirtualFile().equals(other.getVirtualFile())) return false;

    long packed1 = myStubElementTypeAndId;
    long packed2 = ((AnchorElementInfo)other).myStubElementTypeAndId;

    if (packed1 != -1 && packed2 != -1) {
      return packed1 == packed2;
    }
    if (packed1 != -1 || packed2 != -1) {
      return ReadAction.compute(() -> Comparing.equal(restoreElement(), other.restoreElement()));
    }
  }
  return super.pointsToTheSameElementAs(other);
}
项目:consulo    文件:ChangesUtil.java   
public static FilePath getLocalPath(@Nonnull Project project, FilePath filePath) {
  // check if the file has just been renamed (IDEADEV-15494)
  Change change = ReadAction.compute(() -> {
    if (project.isDisposed()) throw new ProcessCanceledException();
    return ChangeListManager.getInstance(project).getChange(filePath);
  });
  if (change != null) {
    ContentRevision beforeRevision = change.getBeforeRevision();
    ContentRevision afterRevision = change.getAfterRevision();
    if (beforeRevision != null && afterRevision != null && !beforeRevision.getFile().equals(afterRevision.getFile()) &&
        beforeRevision.getFile().equals(filePath)) {
      return afterRevision.getFile();
    }
  }
  return filePath;
}
项目:consulo    文件:XDebugSessionImpl.java   
private <B extends XBreakpoint<?>> void handleBreakpoint(final XBreakpointHandler<B> handler, final B b, final boolean register,
                                                         final boolean temporary) {
  if (register) {
    boolean active = ReadAction.compute(() -> isBreakpointActive(b));
    if (active) {
      synchronized (myRegisteredBreakpoints) {
        myRegisteredBreakpoints.put(b, new CustomizedBreakpointPresentation());
      }
      handler.registerBreakpoint(b);
    }
  }
  else {
    boolean removed;
    synchronized (myRegisteredBreakpoints) {
      removed = myRegisteredBreakpoints.remove(b) != null;
    }
    if (removed) {
      handler.unregisterBreakpoint(b, temporary);
    }
  }
}
项目:consulo    文件:ShowImplementationsAction.java   
@Nonnull
static PsiElement[] getSelfAndImplementations(Editor editor,
                                              @Nonnull PsiElement element,
                                              @Nonnull ImplementationSearcher handler,
                                              final boolean includeSelfAlways) {
  final PsiElement[] handlerImplementations = handler.searchImplementations(element, editor, includeSelfAlways, true);
  if (handlerImplementations.length > 0) return handlerImplementations;

  return ReadAction.compute(() -> {
    PsiElement psiElement = element;
    PsiFile psiFile = psiElement.getContainingFile();
    if (psiFile == null) {
      // Magically, it's null for ant property declarations.
      psiElement = psiElement.getNavigationElement();
      psiFile = psiElement.getContainingFile();
      if (psiFile == null) {
        return PsiElement.EMPTY_ARRAY;
      }
    }
    if (psiFile.getVirtualFile() != null && (psiElement.getTextRange() != null || psiElement instanceof PsiFile)) {
      return new PsiElement[]{psiElement};
    }
    return PsiElement.EMPTY_ARRAY;
  });
}
项目:consulo    文件:FormatChangedTextUtil.java   
/**
 * Allows to answer if any file that belongs to the given project has changes in comparison with VCS.
 *
 * @param project  target project to check
 * @return         <code>true</code> if any file that belongs to the given project has changes in comparison with VCS
 *                 <code>false</code> otherwise
 */
public static boolean hasChanges(@Nonnull final Project project) {
  final ModifiableModuleModel moduleModel = new ReadAction<ModifiableModuleModel>() {
    @Override
    protected void run(@Nonnull Result<ModifiableModuleModel> result) throws Throwable {
      result.setResult(ModuleManager.getInstance(project).getModifiableModel());
    }
  }.execute().getResultObject();
  try {
    for (Module module : moduleModel.getModules()) {
      if (hasChanges(module)) {
        return true;
      }
    }
    return false;
  }
  finally {
    moduleModel.dispose();
  }
}
项目:consulo    文件:ProjectStructureDaemonAnalyzer.java   
private void doCollectUsages(final ProjectStructureElement element) {
  final List<ProjectStructureElementUsage> usages = new ReadAction<List<ProjectStructureElementUsage>>() {
    @Override
    protected void run(final Result<List<ProjectStructureElementUsage>> result) {
      if (myStopped.get()) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("collecting usages in " + element);
      }
      result.setResult(getUsagesInElement(element));
    }
  }.execute().getResultObject();

  invokeLater(new Runnable() {
    @Override
    public void run() {
      if (myStopped.get() || usages == null) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("updating usages for " + element);
      }
      updateUsages(element, usages);
    }
  });
}
项目:consulo    文件:PsiDocumentManagerImpl.java   
public PsiDocumentManagerImpl(@Nonnull final Project project,
                              @Nonnull PsiManager psiManager,
                              @Nonnull EditorFactory editorFactory,
                              @Nonnull MessageBus bus,
                              @NonNls @Nonnull final DocumentCommitProcessor documentCommitThread) {
  super(project, psiManager, bus, documentCommitThread);
  myDocumentCommitThread = documentCommitThread;
  editorFactory.getEventMulticaster().addDocumentListener(this, project);
  MessageBusConnection connection = bus.connect();
  connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() {
    @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);
    }
  });
  connection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
    @Override
    public void updateFinished(@Nonnull Document doc) {
      documentCommitThread.commitAsynchronously(project, doc, "Bulk update finished", TransactionGuard.getInstance().getContextTransaction());
    }
  });
  Disposer.register(project, () -> ((DocumentCommitThread)myDocumentCommitThread).cancelTasksOnProjectDispose(project));
}
项目:consulo    文件:FindInProjectUtil.java   
static int processUsagesInFile(@Nonnull final PsiFile psiFile, @Nonnull final VirtualFile virtualFile, @Nonnull final FindModel findModel, @Nonnull final Processor<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, consumer, findModel, psiFile, offset, USAGES_PER_READ_ACTION);
    });
    count += found;
  }
  while (found != 0);
  return count;
}
项目:consulo    文件:FindInProjectUtil.java   
@Nonnull
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 " ";
      }
    }, "");
  });
}
项目:consulo    文件:ExtractMethodHelper.java   
/**
 * Finds duplicates of the code fragment specified in the finder in given scopes.
 * Note that in contrast to {@link #processDuplicates} the search is performed synchronously because normally you need the results in
 * order to complete the refactoring. If user cancels it, empty list will be returned.
 *
 * @param finder          finder object to seek for duplicates
 * @param searchScopes    scopes where to look them in
 * @param generatedMethod new method that should be excluded from the search
 * @return list of discovered duplicate code fragments or empty list if user interrupted the search
 * @see #replaceDuplicates(PsiElement, Editor, Consumer, List)
 */
@Nonnull
public static List<SimpleMatch> collectDuplicates(@Nonnull SimpleDuplicatesFinder finder,
                                                  @Nonnull List<PsiElement> searchScopes,
                                                  @Nonnull PsiElement generatedMethod) {
  final Project project = generatedMethod.getProject();
  try {
    //noinspection RedundantCast
    return ProgressManager.getInstance().runProcessWithProgressSynchronously(
            (ThrowableComputable<List<SimpleMatch>, RuntimeException>)() -> {
              ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
              return ReadAction.compute(() -> finder.findDuplicates(searchScopes, generatedMethod));
            }, RefactoringBundle.message("searching.for.duplicates"), true, project);
  }
  catch (ProcessCanceledException e) {
    return Collections.emptyList();
  }
}
项目:consulo-java    文件:TestClassCollector.java   
public static ClassLoader createUsersClassLoader(JavaTestConfigurationBase configuration)
{
    Module module = configuration.getConfigurationModule().getModule();
    List<URL> urls = new ArrayList<>();

    PathsList pathsList = ReadAction.compute(() -> (module == null || configuration.getTestSearchScope() == TestSearchScope.WHOLE_PROJECT ? OrderEnumerator.orderEntries(configuration.getProject
            ()) : OrderEnumerator.orderEntries(module)).runtimeOnly().recursively().getPathsList()); //include jdk to avoid NoClassDefFoundError for classes inside tools.jar
    for(VirtualFile file : pathsList.getVirtualFiles())
    {
        try
        {
            urls.add(VfsUtilCore.virtualToIoFile(file).toURI().toURL());
        }
        catch(MalformedURLException ignored)
        {
            LOG.info(ignored);
        }
    }

    return UrlClassLoader.build().allowLock().useCache().urls(urls).get();
}
项目:consulo-java    文件:JavaFindUsagesHelper.java   
private static boolean addAliasingUsages(@NotNull PomTarget pomTarget, @NotNull final FindUsagesOptions options, @NotNull final Processor<UsageInfo> processor)
{
    for(AliasingPsiTargetMapper aliasingPsiTargetMapper : Extensions.getExtensions(AliasingPsiTargetMapper.EP_NAME))
    {
        for(final AliasingPsiTarget psiTarget : aliasingPsiTargetMapper.getTargets(pomTarget))
        {
            boolean success = ReferencesSearch.search(new ReferencesSearch.SearchParameters(ReadAction.compute(() -> PomService.convertToPsi(psiTarget)), options.searchScope, false, options
                    .fastTrack)).forEach(new ReadActionProcessor<PsiReference>()
            {
                @Override
                public boolean processInReadAction(final PsiReference reference)
                {
                    return addResult(reference, options, processor);
                }
            });
            if(!success)
            {
                return false;
            }
        }
    }
    return true;
}
项目:consulo-java    文件:GuavaLineMarkerProvider.java   
@NotNull
private static Query<PsiMember> createQuery(@NotNull PsiClass target, @NotNull PsiClass annClass)
{
    PsiImmediateClassType type = new PsiImmediateClassType(target, PsiSubstitutor.EMPTY);
    return new FilteredQuery<>(AnnotatedMembersSearch.search(annClass), psiMember -> ReadAction.compute(() ->
    {
        if(psiMember instanceof PsiMethod && !psiMember.hasModifierProperty(PsiModifier.STATIC))
        {
            PsiParameterList parameterList = ((PsiMethod) psiMember).getParameterList();
            PsiParameter[] parameters = parameterList.getParameters();
            if(parameters.length == 1 && parameters[0].getType().equals(type))
            {
                return true;
            }
        }
        return false;
    }));
}
项目:consulo-java    文件:LineBreakpoint.java   
@Nullable
private static String findOwnerMethod(final PsiFile file, final int offset)
{
    if(offset < 0 /*|| file instanceof JspFile*/)
    {
        return null;
    }
    if(file instanceof PsiClassOwner)
    {
        return ReadAction.compute(() ->
        {
            PsiMethod method = DebuggerUtilsEx.findPsiMethod(file, offset);
            return method != null ? method.getName() : null;
        });
    }
    return null;
}