com.intellij.openapi.progress.ProcessCanceledException Java Examples

The following examples show how to use com.intellij.openapi.progress.ProcessCanceledException. 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: WriteCommandAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #3
Source File: MuleSchemaProvider.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: ToolWindowManagerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
          }
        }
      });
    }
  }
}
 
Example #5
Source File: FindInProjectUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: MuleSchemaProvider.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: OCamlSourcesOrderRootTypeUIFactory.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example #8
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #9
Source File: RemoteRevisionsNumbersCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
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 #12
Source File: CompileDriver.java    From consulo with Apache License 2.0 6 votes vote down vote up
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();
      }
    }
  });
}
 
Example #13
Source File: Alarm.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #14
Source File: DelegatingSwitchToHeaderOrSourceProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * 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: VcsDirtyScopeManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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) {
  }
}
 
Example #16
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #17
Source File: AsyncTreeModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #18
Source File: CompletionThreading.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #19
Source File: NoSqlConfigurable.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #20
Source File: RemoteRevisionsCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
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) {
        }
      }
    });
  }
}
 
Example #21
Source File: ExternalMergeTool.java    From consulo with Apache License 2.0 6 votes vote down vote up
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");
  }
}
 
Example #22
Source File: ObjectTree.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void handleExceptions(@Nonnull List<? extends Throwable> exceptions) {
  if (!exceptions.isEmpty()) {
    for (Throwable exception : exceptions) {
      if (!(exception instanceof ProcessCanceledException)) {
        getLogger().error(exception);
      }
    }

    ProcessCanceledException pce = ContainerUtil.findInstance(exceptions, ProcessCanceledException.class);
    if (pce != null) {
      throw pce;
    }
  }
}
 
Example #23
Source File: EmptyMarkupModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RangeHighlighterEx addRangeHighlighterAndChangeAttributes(int startOffset,
                                                                 int endOffset,
                                                                 int layer,
                                                                 TextAttributes textAttributes,
                                                                 @Nonnull HighlighterTargetArea targetArea,
                                                                 boolean isPersistent,
                                                                 Consumer<? super RangeHighlighterEx> changeAttributesAction) {
  throw new ProcessCanceledException();
}
 
Example #24
Source File: UnindexedFilesUpdater.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void performInDumbMode(@Nonnull ProgressIndicator indicator) {
  myIndex.filesUpdateStarted(myProject);
  try {
    updateUnindexedFiles(indicator);
  }
  catch (ProcessCanceledException e) {
    LOG.info("Unindexed files update canceled");
    throw e;
  }
  finally {
    myIndex.filesUpdateFinished(myProject);
  }
}
 
Example #25
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static ReadTask.Continuation runUnderProgress(@Nonnull final ProgressIndicator progressIndicator, @Nonnull final ReadTask task) {
  return ProgressManager.getInstance().runProcess(() -> {
    try {
      return task.runBackgroundProcess(progressIndicator);
    }
    catch (ProcessCanceledException ignore) {
      return null;
    }
  }, progressIndicator);
}
 
Example #26
Source File: BackgroundTaskUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps {@link MessageBus#syncPublisher(Topic)} in a dispose check,
 * and throws a {@link ProcessCanceledException} if the project is disposed,
 * instead of throwing an assertion which would happen otherwise.
 *
 * @see #syncPublisher(Topic)
 */
@Nonnull
public static <L> L syncPublisher(@Nonnull Project project, @Nonnull Topic<L> topic) throws ProcessCanceledException {
  ThrowableComputable<L, RuntimeException> action = () -> {
    if (project.isDisposed()) throw new ProcessCanceledException();
    return project.getMessageBus().syncPublisher(topic);
  };
  return AccessRule.read(action);
}
 
Example #27
Source File: SubstrateRef.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PsiFile reportError(StubElement stub) {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String reason = ((PsiFileStubImpl<?>)stub).getInvalidationReason();
  PsiInvalidElementAccessException exception = new PsiInvalidElementAccessException(myStub.getPsi(), "no psi for file stub " + stub + ", invalidation reason=" + reason, null);
  if (PsiFileImpl.STUB_PSI_MISMATCH.equals(reason)) {
    // we're between finding stub-psi mismatch and the next EDT spot where the file is reparsed and stub rebuilt
    //    see com.intellij.psi.impl.source.PsiFileImpl.rebuildStub()
    // most likely it's just another highlighting thread accessing the same PSI concurrently and not yet canceled, so cancel it
    throw new ProcessCanceledException(exception);
  }
  throw exception;
}
 
Example #28
Source File: CommittedChangesCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean hasEmptyCaches() {
  try {
    return hasCachesWithEmptiness(true);
  }
  catch (ProcessCanceledException e) {
    return false;
  }
}
 
Example #29
Source File: ProcessHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for process execution.
 *
 * @return true if target process has actually ended; false if we stopped watching the process execution and don't know if it has completed.
 */
public boolean waitFor() {
  try {
    myWaitSemaphore.waitFor();
    return true;
  }
  catch (ProcessCanceledException e) {
    return false;
  }
}
 
Example #30
Source File: TreeUiTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void runAndInterrupt(final Runnable action, final String interruptAction, final Object interruptElement, final Interruption interruption) throws Exception {
  myElementUpdate.clear();

  final boolean[] wasInterrupted = new boolean[]{false};
  myElementUpdateHook = new ElementUpdateHook() {
    @Override
    public void onElementAction(String action, Object element) {
      boolean toInterrupt = element.equals(interruptElement) && action.equals(interruptAction);

      if (wasInterrupted[0]) {
        if (myCancelRequest == null) {
          getBuilder().getUi().getStatus();
          final String message =
                  "Not supposed to be update after interruption request: action=" + action + " element=" + element + " interruptAction=" + interruptAction + " interruptElement=" + interruptElement;
          myCancelRequest = new AssertionError(message);
        }
      }
      else if (toInterrupt) {
        wasInterrupted[0] = true;
        switch (interruption) {
          case throwProcessCancelled:
            throw new ProcessCanceledException();
          case invokeCancel:
            getBuilder().cancelUpdate();
            break;
        }
      }
    }
  };

  action.run();

  myCancelRequest = null;
  myElementUpdateHook = null;
}