com.intellij.psi.PsiInvalidElementAccessException#com.intellij.openapi.progress.ProcessCanceledException源码实例Demo

下面列出了com.intellij.psi.PsiInvalidElementAccessException#com.intellij.openapi.progress.ProcessCanceledException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: consulo   文件: LocalInspectionsPass.java
void inspectInjectedPsi(@Nonnull final List<PsiElement> elements,
                        final boolean onTheFly,
                        @Nonnull final ProgressIndicator indicator,
                        @Nonnull final InspectionManager iManager,
                        final boolean inVisibleRange,
                        @Nonnull final List<LocalInspectionToolWrapper> wrappers) {
  final Set<PsiFile> injected = new THashSet<>();
  for (PsiElement element : elements) {
    InjectedLanguageUtil.enumerate(element, getFile(), false, (injectedPsi, places) -> injected.add(injectedPsi));
  }
  if (injected.isEmpty()) return;
  Processor<PsiFile> processor = injectedPsi -> {
    doInspectInjectedPsi(injectedPsi, onTheFly, indicator, iManager, inVisibleRange, wrappers);
    return true;
  };
  if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(injected), indicator, myFailFastOnAcquireReadAction, processor)) {
    throw new ProcessCanceledException();
  }
}
 
@NotNull
List<VirtualFile> suggestOCamlRoots(@NotNull VirtualFile dir, @NotNull final ProgressIndicator progressIndicator) {
    if (!dir.isDirectory()) {
        return ContainerUtil.emptyList();
    }

    final FileTypeManager typeManager = FileTypeManager.getInstance();
    final ArrayList<VirtualFile> foundDirectories = new ArrayList<>();
    try {
        VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor() {
            @NotNull
            @Override
            public Result visitFileEx(@NotNull VirtualFile file) {
                progressIndicator.checkCanceled();

                if (!file.isDirectory()) {
                    FileType type = typeManager.getFileTypeByFileName(file.getName());

                    if (type.getDefaultExtension().equals("ml")) {
                        VirtualFile root = file.getParent();
                        if (root != null) {
                            foundDirectories.add(root);
                            return skipTo(root);
                        }
                    }
                }

                return CONTINUE;
            }
        });
    } catch (ProcessCanceledException ignore) {
    }

    return foundDirectories;
}
 
源代码3 项目: consulo   文件: FindInProjectUtil.java
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;
}
 
/**
 * Looks for the schema file to handle the given namespace (url) within the schemas supported by this provider.
 * These schemas are read from spring.schemas file and searched in project files and dependencies. If a schema
 * declared in spring.schemas is not present within project files and project dependencies it will not be resolved.
 *
 * @param url      the url of the namespace
 * @param module   the module where the baseFile is
 * @param baseFile the file where the namespace is declared
 * @return the schema file for the given url if it is supported by this provider (declared in spring.schemas), otherwise null
 */
@Override
public XmlFile getSchema(@NotNull @NonNls String url, @Nullable final Module module, @NotNull PsiFile baseFile) throws ProcessCanceledException {
    if (module == null) {
        return null;
    }
    try {
        Map<String, XmlFile> schemas = getSchemas(module);
        if (schemas != null) {
            XmlFile schemaFile = schemas.get(url);
            return schemaFile;
        }
    } catch (Exception e) {
        //e.printStackTrace();
    }

    return null;
}
 
@NotNull
public Map<String, XmlFile> getSchemas(@NotNull final Module module) throws ProcessCanceledException {
    final Project project = module.getProject();
    final CachedValuesManager manager = CachedValuesManager.getManager(project);
    final Map<String, XmlFile> bundle = manager.getCachedValue(module, SCHEMAS_BUNDLE_KEY, new CachedValueProvider<Map<String, XmlFile>>() {
        public Result<Map<String, XmlFile>> compute() {
            try {
                return computeSchemas(module);
            } catch (ProcessCanceledException pce) {
                throw pce;
            } catch (Exception e) {
                //e.printStackTrace();
                return null;
            }
        }
    }, false);
    return bundle == null ? Collections.<String, XmlFile>emptyMap() : bundle;
}
 
源代码6 项目: consulo   文件: RemoteRevisionsNumbersCache.java
public boolean updateStep() {
  mySomethingChanged = false;
  // copy under lock
  final HashMap<VcsRoot, LazyRefreshingSelfQueue> copyMap;
  synchronized (myLock) {
    copyMap = new HashMap<>(myRefreshingQueues);
  }

  // filter only items for vcs roots that support background operations
  for (Iterator<Map.Entry<VcsRoot, LazyRefreshingSelfQueue>> iterator = copyMap.entrySet().iterator(); iterator.hasNext();) {
    final Map.Entry<VcsRoot, LazyRefreshingSelfQueue> entry = iterator.next();
    final VcsRoot key = entry.getKey();
    final boolean backgroundOperationsAllowed = key.getVcs().isVcsBackgroundOperationsAllowed(key.getPath());
    LOG.debug("backgroundOperationsAllowed: " + backgroundOperationsAllowed + " for " + key.getVcs().getName() + ", " + key.getPath().getPath());
    if (! backgroundOperationsAllowed) {
      iterator.remove();
    }
  }
  LOG.debug("queues refresh started, queues: " + copyMap.size());
  // refresh "up to date" info
  for (LazyRefreshingSelfQueue queue : copyMap.values()) {
    if (myProject.isDisposed()) throw new ProcessCanceledException();
    queue.updateStep();
  }
  return mySomethingChanged;
}
 
/**
 * 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();
  }
}
 
源代码8 项目: consulo   文件: CompletionThreading.java
@Override
public Future<?> startThread(final ProgressIndicator progressIndicator, final Runnable runnable) {
  final Semaphore startSemaphore = new Semaphore();
  startSemaphore.down();
  Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> {
    try {
      startSemaphore.up();
      ProgressManager.checkCanceled();
      runnable.run();
    }
    catch (ProcessCanceledException ignored) {
    }
  }, progressIndicator));
  startSemaphore.waitFor();
  return future;
}
 
源代码9 项目: nosql4idea   文件: NoSqlConfigurable.java
private void testPath(final DatabaseVendor databaseVendor) {
    ProcessOutput processOutput;
    try {
        processOutput = ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<ProcessOutput, Exception>() {
            @Override
            public ProcessOutput compute() throws Exception {
                return checkShellPath(databaseVendor, getShellPath());
            }
        }, "Testing " + databaseVendor.name + " CLI Executable...", true, NoSqlConfigurable.this.project);
    } catch (ProcessCanceledException pce) {
        return;
    } catch (Exception e) {
        Messages.showErrorDialog(mainPanel, e.getMessage(), "Something wrong happened");
        return;
    }
    if (processOutput != null && processOutput.getExitCode() == 0) {
        Messages.showInfoMessage(mainPanel, processOutput.getStdout(), databaseVendor.name + " CLI Path Checked");
    }
}
 
源代码10 项目: consulo   文件: ExternalMergeTool.java
public static void show(@javax.annotation.Nullable final Project project,
                        @Nonnull final MergeRequest request) {
  try {
    if (canShow(request)) {
      showRequest(project, request);
    }
    else {
      DiffManagerEx.getInstance().showMergeBuiltin(project, request);
    }
  }
  catch (ProcessCanceledException ignore) {
  }
  catch (Throwable e) {
    LOG.error(e);
    Messages.showErrorDialog(project, e.getMessage(), "Can't Show Merge In External Tool");
  }
}
 
源代码11 项目: consulo   文件: RemoteRevisionsCache.java
public void directoryMappingChanged() {
  if (! VcsConfiguration.getInstance(myProject).isChangedOnServerEnabled()) {
    manageAlarm();
  } else {
    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
      @Override
      public void run() {
        try {
          updateRoots();
          myRemoteRevisionsNumbersCache.directoryMappingChanged();
          myRemoteRevisionsStateCache.directoryMappingChanged();
          manageAlarm();
        } catch (ProcessCanceledException ignore) {
        }
      }
    });
  }
}
 
源代码12 项目: consulo   文件: AsyncTreeModel.java
@Override
Node getNode(Object object) {
  Node loaded = new Node(object, model.isLeaf(object));
  if (loaded.leaf || isObsolete()) return loaded;

  if (model instanceof ChildrenProvider) {
    //noinspection unchecked
    ChildrenProvider<Object> provider = (ChildrenProvider)model;
    List<?> children = provider.getChildren(object);
    if (children == null) throw new ProcessCanceledException(); // cancel this command
    loaded.children = load(children.size(), index -> children.get(index));
  }
  else {
    loaded.children = load(model.getChildCount(object), index -> model.getChild(object, index));
  }
  return loaded;
}
 
源代码13 项目: consulo   文件: ProgressIndicatorUtils.java
public static boolean runWithWriteActionPriority(@Nonnull Runnable action, @Nonnull ProgressIndicator progressIndicator) {
  ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    throw new IllegalStateException("Must not call from EDT");
  }
  Runnable cancellation = indicatorCancellation(progressIndicator);
  if (isWriting(application)) {
    cancellation.run();
    return false;
  }
  return ProgressManager.getInstance().runProcess(() -> {
    try {
      // add listener inside runProcess to avoid cancelling indicator before even starting the progress
      return runActionAndCancelBeforeWrite(application, cancellation, action);
    }
    catch (ProcessCanceledException ignore) {
      return false;
    }
  }, progressIndicator);
}
 
源代码14 项目: consulo   文件: VcsDirtyScopeManagerImpl.java
@Override
public void filePathsDirty(@Nullable final Collection<FilePath> filesDirty, @Nullable final Collection<FilePath> dirsRecursivelyDirty) {
  try {
    final MultiMap<AbstractVcs, FilePath> filesConverted = groupByVcs(filesDirty);
    final MultiMap<AbstractVcs, FilePath> dirsConverted = groupByVcs(dirsRecursivelyDirty);
    if (filesConverted.isEmpty() && dirsConverted.isEmpty()) return;

    if (LOG.isDebugEnabled()) {
      LOG.debug("dirty files: " + toString(filesConverted) + "; dirty dirs: " + toString(dirsConverted) + "; " + findFirstInterestingCallerClass());
    }

    boolean hasSomethingDirty;
    synchronized (LOCK) {
      if (!myReady) return;
      markDirty(myDirtBuilder, filesConverted, false);
      markDirty(myDirtBuilder, dirsConverted, true);
      hasSomethingDirty = !myDirtBuilder.isEmpty();
    }

    if (hasSomethingDirty) {
      myChangeListManager.scheduleUpdate();
    }
  }
  catch (ProcessCanceledException ignore) {
  }
}
 
源代码15 项目: consulo   文件: Alarm.java
@Override
public void run() {
  try {
    if (myDisposed) {
      return;
    }
    final Runnable task;
    synchronized (LOCK) {
      task = myTask;
      myTask = null;
    }
    if (task != null) {
      runSafely(task);
    }
  }
  catch (ProcessCanceledException ignored) {
  }
  catch (Throwable e) {
    LOG.error(e);
  }
}
 
源代码16 项目: consulo   文件: CompileDriver.java
public void executeCompileTask(final CompileTask compileTask, final CompileScope scope, final String contentName, final Runnable onTaskFinished) {
  final CompilerTask task = new CompilerTask(myProject, contentName, true, isCompilationStartedAutomatically(scope));
  final CompileContextImpl compileContext = new CompileContextImpl(myProject, task, scope, null, false, false);

  FileDocumentManager.getInstance().saveAllDocuments();

  task.start(() -> {
    try {
      compileTask.execute(compileContext);
    }
    catch (ProcessCanceledException ex) {
      // suppressed
    }
    finally {
      if (onTaskFinished != null) {
        onTaskFinished.run();
      }
    }
  });
}
 
源代码17 项目: consulo   文件: DumbService.java
/**
 * 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;
  }
}
 
源代码18 项目: consulo   文件: WriteCommandAction.java
@Nonnull
@Override
public RunResult<T> execute() {
  Application application = ApplicationManager.getApplication();
  boolean dispatchThread = application.isDispatchThread();

  if (!dispatchThread && application.isReadAccessAllowed()) {
    LOG.error("Must not start write action from within read action in the other thread - deadlock is coming");
    throw new IllegalStateException();
  }

  final RunResult<T> result = new RunResult<>(this);
  if (dispatchThread) {
    performWriteCommandAction(result);
  }
  else {
    try {
      TransactionGuard.getInstance().submitTransactionAndWait(() -> performWriteCommandAction(result));
    }
    catch (ProcessCanceledException ignored) { }
  }
  return result;
}
 
源代码19 项目: consulo   文件: LocalInspectionsPass.java
@Nonnull
private List<InspectionContext> visitPriorityElementsAndInit(@Nonnull Map<LocalInspectionToolWrapper, Set<String>> toolToSpecifiedLanguageIds,
                                                             @Nonnull final InspectionManager iManager,
                                                             final boolean isOnTheFly,
                                                             @Nonnull final ProgressIndicator indicator,
                                                             @Nonnull final List<PsiElement> elements,
                                                             @Nonnull final LocalInspectionToolSession session,
                                                             @Nonnull List<LocalInspectionToolWrapper> wrappers,
                                                             @Nonnull final Set<String> elementDialectIds) {
  final List<InspectionContext> init = new ArrayList<>();
  List<Map.Entry<LocalInspectionToolWrapper, Set<String>>> entries = new ArrayList<>(toolToSpecifiedLanguageIds.entrySet());

  Processor<Map.Entry<LocalInspectionToolWrapper, Set<String>>> processor = pair -> {
    LocalInspectionToolWrapper toolWrapper = pair.getKey();
    Set<String> dialectIdsSpecifiedForTool = pair.getValue();
    ((ApplicationEx2)ApplicationManager.getApplication()).executeByImpatientReader(
            () -> runToolOnElements(toolWrapper, dialectIdsSpecifiedForTool, iManager, isOnTheFly, indicator, elements, session, init, elementDialectIds));
    return true;
  };
  boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(entries, indicator, myFailFastOnAcquireReadAction, processor);
  if (!result) throw new ProcessCanceledException();
  return init;
}
 
源代码20 项目: consulo   文件: ToolWindowManagerBase.java
protected void registerToolWindowsFromBeans(List<FinalizableCommand> list) {
  final List<ToolWindowEP> beans = ToolWindowEP.EP_NAME.getExtensionList();
  for (final ToolWindowEP bean : beans) {
    if (checkCondition(myProject, bean)) {
      list.add(new FinalizableCommand(EmptyRunnable.INSTANCE) {
        @Override
        public void run() {
          try {
            initToolWindow(bean);
          }
          catch (ProcessCanceledException e) {
            throw e;
          }
          catch (Throwable t) {
            LOG.error("failed to init toolwindow " + bean.factoryClass, t);
          }
        }
      });
    }
  }
}
 
源代码21 项目: consulo   文件: ProgressIndicatorUtils.java
/**
 * Run the given computation with its execution time restricted to the given amount of time in milliseconds.<p></p>
 * <p>
 * Internally, it creates a new {@link ProgressIndicator}, runs the computation with that indicator and cancels it after the the timeout.
 * The computation should call {@link ProgressManager#checkCanceled()} frequently enough, so that after the timeout has been exceeded
 * it can stop the execution by throwing {@link ProcessCanceledException}, which will be caught by this {@code withTimeout}.<p></p>
 * <p>
 * If a {@link ProcessCanceledException} happens due to any other reason (e.g. a thread's progress indicator got canceled),
 * it'll be thrown out of this method.
 *
 * @return the computation result or {@code null} if timeout has been exceeded.
 */
@Nullable
public static <T> T withTimeout(long timeoutMs, @Nonnull Computable<T> computation) {
  ProgressManager.checkCanceled();
  ProgressIndicator outer = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ProgressIndicator inner = outer != null ? new SensitiveProgressWrapper(outer) : new ProgressIndicatorBase(false, false);
  AtomicBoolean canceledByTimeout = new AtomicBoolean();
  ScheduledFuture<?> cancelProgress = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    canceledByTimeout.set(true);
    inner.cancel();
  }, timeoutMs, TimeUnit.MILLISECONDS);
  try {
    return ProgressManager.getInstance().runProcess(computation, inner);
  }
  catch (ProcessCanceledException e) {
    if (canceledByTimeout.get()) {
      return null;
    }
    throw e; // canceled not by timeout
  }
  finally {
    cancelProgress.cancel(false);
  }
}
 
源代码22 项目: consulo   文件: ChangeSignatureDialogBase.java
protected JComponent createOptionsPanel() {
  final JPanel panel = new JPanel(new BorderLayout());
  if (myAllowDelegation) {
    myDelegationPanel = createDelegationPanel();
    panel.add(myDelegationPanel, BorderLayout.WEST);
  }

  myPropagateParamChangesButton =
    new AnActionButton(RefactoringBundle.message("changeSignature.propagate.parameters.title"), null, new LayeredIcon(AllIcons.Nodes.Parameter, AllIcons.Actions.New)) {
      @Override
      public void actionPerformed(AnActionEvent e) {
        final Ref<CallerChooserBase<Method>> chooser = new Ref<CallerChooserBase<Method>>();
        Consumer<Set<Method>> callback = new Consumer<Set<Method>>() {
          @Override
          public void consume(Set<Method> callers) {
            myMethodsToPropagateParameters = callers;
            myParameterPropagationTreeToReuse = chooser.get().getTree();
          }
        };
        try {
          String message = RefactoringBundle.message("changeSignature.parameter.caller.chooser");
          chooser.set(createCallerChooser(message, myParameterPropagationTreeToReuse, callback));
        }
        catch (ProcessCanceledException ex) {
          // user cancelled initial callers search, don't show dialog
          return;
        }
        chooser.get().show();
      }
    };

  final JPanel result = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP));
  result.add(panel);
  return result;
}
 
源代码23 项目: bamboo-soy   文件: TemplateBlockIndex.java
@NotNull
@Override
public Collection<String> getAllKeys(Project project) {
  try {
    return super.getAllKeys(project);
  } catch (ProcessCanceledException e) {
    return new ArrayList<>();
  }
}
 
源代码24 项目: mule-intellij-plugins   文件: MuleSchemaProvider.java
@Override
public Set<String> getLocations(@NotNull @NonNls final String namespace, @NotNull final XmlFile context) throws ProcessCanceledException {
    Set<String> locations = new HashSet<>();
    final Module module = ModuleUtil.findModuleForPsiElement(context);
    if (module == null) {
        return null;
    }
    try {
        final Map<String, XmlFile> schemas = getSchemas(module);
        for (Map.Entry<String, XmlFile> entry : schemas.entrySet()) {
            final String s = getNamespace(entry.getValue(), context.getProject());
            if (s != null && s.equals(namespace)) {
                if (!entry.getKey().contains("mule-httpn.xsd")) {
                    locations.add(entry.getKey()); //Observe the formatting rules
                    XmlFile schemaFile = entry.getValue();
                    try {
                        String url = schemaFile.getVirtualFile().getUrl();
                        if (url != null) {
                            if (url.startsWith("jar://"))
                                url = url.substring(6);
                            ExternalResourceManager.getInstance().addResource(namespace, url);
                        }
                    } catch (Throwable ex) {
                        Notifications.Bus.notify(new Notification("Schema Provider", "Schema Provider", ex.toString(),
                                NotificationType.ERROR));
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return locations;
}
 
public static void generateProject(@NotNull Project project,
                                   @NotNull VirtualFile baseDir,
                                   @NotNull String flutterSdkPath,
                                   @NotNull Module module,
                                   @NotNull FlutterCreateAdditionalSettings settings) {
  final FlutterSdk sdk = FlutterSdk.forPath(flutterSdkPath);
  if (sdk == null) {
    FlutterMessages.showError("Error creating project", flutterSdkPath + " is not a valid Flutter SDK");
    return;
  }

  FlutterUtils.disableGradleProjectMigrationNotification(project);

  // Run "flutter create".
  final OutputListener listener = new OutputListener();
  final PubRoot root = sdk.createFiles(baseDir, module, listener, settings);
  if (root == null) {
    final String stderr = listener.getOutput().getStderr();
    final String msg = stderr.isEmpty() ? "Flutter create command was unsuccessful" : stderr;
    FlutterMessages.showError("Error creating project", msg);
    return;
  }
  final Runnable runnable = () -> applyDartModule(sdk, project, module, root);
  try {
    TransactionGuard.getInstance().submitTransactionAndWait(runnable);
  }
  catch (ProcessCanceledException e) {
    FlutterUtils.warn(LOG, e);
  }
}
 
源代码26 项目: flutter-intellij   文件: AsyncUtils.java
public static void invokeAndWait(Runnable runnable) throws ProcessCanceledException {
  final Application app = ApplicationManager.getApplication();
  if (app == null || app.isUnitTestMode()) {
    try {
      // This case existing to support unit testing.
      SwingUtilities.invokeAndWait(runnable);
    }
    catch (InterruptedException | InvocationTargetException e) {
      throw new ProcessCanceledException(e);
    }
  }
  else {
    app.invokeAndWait(runnable);
  }
}
 
源代码27 项目: consulo   文件: ReadTask.java
/**
 * Is invoked on a background thread. The responsibility of this method is to start a read action and
 * call {@link #computeInReadAction(ProgressIndicator)}. Overriders might also do something else.
 * For example, use {@link com.intellij.openapi.project.DumbService#runReadActionInSmartMode(Runnable)}.
 * @param indicator the progress indicator of the background thread
 */
public Continuation runBackgroundProcess(@Nonnull final ProgressIndicator indicator) throws ProcessCanceledException {
  return ApplicationManager.getApplication().runReadAction(new Computable<Continuation>() {
    @Override
    public Continuation compute() {
      return performInReadAction(indicator);
    }
  });
}
 
源代码28 项目: consulo   文件: ProjectLevelVcsManagerImpl.java
@Override
@Nullable
public AbstractVcs getVcsFor(final FilePath file) {
  final VirtualFile vFile = ChangesUtil.findValidParentAccurately(file);
  ThrowableComputable<AbstractVcs, RuntimeException> action = () -> {
    if (!ApplicationManager.getApplication().isUnitTestMode() && !myProject.isInitialized()) return null;
    if (myProject.isDisposed()) throw new ProcessCanceledException();
    if (vFile != null) {
      return getVcsFor(vFile);
    }
    return null;
  };
  return AccessRule.read(action);
}
 
@NotNull
@Override
public Collection<String> getAllKeys(Project project) {
    try {
        return super.getAllKeys(project);
    } catch (ProcessCanceledException e) {
        return new ArrayList<>();
    }
}
 
源代码30 项目: intellij   文件: SyncPhaseCoordinator.java
private static void logSyncError(BlazeContext context, Throwable e) {
  // ignore ProcessCanceledException
  Throwable cause = e;
  while (cause != null) {
    if (cause instanceof ProcessCanceledException) {
      return;
    }
    cause = cause.getCause();
  }
  logger.error(e);
  IssueOutput.error("Internal error: " + e.getMessage()).submit(context);
}