Java Code Examples for com.intellij.openapi.progress.ProgressIndicator.isCanceled()

The following are Jave code examples for showing how to use isCanceled() of the com.intellij.openapi.progress.ProgressIndicator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: intellij-ce-playground   File: TreeUiTest.java   Source Code and License Vote up 6 votes
private void expandNext(final NodeElement[] elements, final int index, final ProgressIndicator indicator, final ActionCallback callback) {
  if (indicator.isCanceled()) {
    callback.setRejected();
    return;
  }

  if (index >= elements.length) {
    callback.setDone();
    return;
  }

  getBuilder().expand(elements[index], new Runnable() {
    @Override
    public void run() {
      expandNext(elements, index + 1, indicator, callback);
    }
  });
}
 
Example 2
Project: intellij-ce-playground   File: AbstractProgressIndicatorBase.java   Source Code and License Vote up 6 votes
@Override
public synchronized void initStateFrom(@NotNull final ProgressIndicator indicator) {
  myRunning = indicator.isRunning();
  myCanceled = indicator.isCanceled();
  myFraction = indicator.getFraction();
  myIndeterminate = indicator.isIndeterminate();
  myText = indicator.getText();

  myText2 = indicator.getText2();

  myFraction = indicator.getFraction();

  if (indicator instanceof ProgressIndicatorStacked) {
    ProgressIndicatorStacked stacked = (ProgressIndicatorStacked)indicator;

    myNonCancelableCount = stacked.getNonCancelableCount();

    myTextStack = new Stack<String>(stacked.getTextStack());

    myText2Stack = new Stack<String>(stacked.getText2Stack());

    myFractionStack = new DoubleArrayList(stacked.getFractionStack());
  }
  myShouldStartActivity = false;
}
 
Example 3
Project: intellij-ce-playground   File: ApplicationLevelNumberConnectionsGuardImpl.java   Source Code and License Vote up 6 votes
private void waitForFreeConnections() throws SVNException {
  synchronized (myLock) {
    while (myCurrentlyActiveConnections >= CachingSvnRepositoryPool.ourMaxTotal && ! myDisposed) {
      try {
        myLock.wait(500);
      }
      catch (InterruptedException e) {
        //
      }
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null && indicator.isCanceled()) {
        throw new SVNException(SVNErrorMessage.create(SVNErrorCode.CANCELLED));
      }
    }
  }
}
 
Example 4
Project: intellij-ce-playground   File: AndroidSdkUtils.java   Source Code and License Vote up 6 votes
@Override
public void run(@NotNull ProgressIndicator indicator) {
  indicator.setIndeterminate(true);
  while (!myFuture.isDone()) {
    try {
      myFuture.get(200, TimeUnit.MILLISECONDS);
    }
    catch (Exception ignored) {
      // all we need to know is whether the future completed or not..
    }

    if (indicator.isCanceled()) {
      return;
    }
  }
}
 
Example 5
Project: intellij-ce-playground   File: CvsListenerWithProgress.java   Source Code and License Vote up 5 votes
public boolean isAborted() {
  myPing = true;
  if (myLastError != null) throw new CvsProcessException(myLastError);
  if (myIndirectCancel) return true;
  final ProgressIndicator progressIndicator = getProgressIndicator();
  if (progressIndicator == null) return false;
  return progressIndicator.isCanceled();
}
 
Example 6
Project: intellij-ce-playground   File: PostHighlightingVisitor.java   Source Code and License Vote up 5 votes
private void optimizeImportsOnTheFlyLater(@NotNull final ProgressIndicator progress) {
  if ((myHasRedundantImports || myHasMissortedImports) && !progress.isCanceled()) {
    // schedule optimise action at the time of session disposal, which is after all applyInformation() calls
    Disposable invokeFixLater = new Disposable() {
      @Override
      public void dispose() {
        // later because should invoke when highlighting is finished
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            if (myProject.isDisposed() || !myFile.isValid() || !myFile.isWritable()) return;
            IntentionAction optimizeImportsFix = QuickFixFactory.getInstance().createOptimizeImportsFix(true);
            if (optimizeImportsFix.isAvailable(myProject, null, myFile)) {
              optimizeImportsFix.invoke(myProject, null, myFile);
            }
          }
        });
      }
    };
    Disposer.register((DaemonProgressIndicator)progress, invokeFixLater);
    if (progress.isCanceled()) {
      Disposer.dispose(invokeFixLater);
      Disposer.dispose((DaemonProgressIndicator)progress);
      progress.checkCanceled();
    }
  }
}
 
Example 7
Project: intellij-ce-playground   File: MethodDuplicatesHandler.java   Source Code and License Vote up 5 votes
private static void replaceDuplicate(final Project project, final Map<PsiMember, List<Match>> duplicates, final Set<PsiMember> methods) {
  final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
  if (progressIndicator != null && progressIndicator.isCanceled()) return;

  final Runnable replaceRunnable = new Runnable() {
    @Override
    public void run() {
      LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME);
      try {
        for (final PsiMember member : methods) {
          final List<Match> matches = duplicates.get(member);
          if (matches == null) continue;
          final int duplicatesNo = matches.size();
          WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo));
          CommandProcessor.getInstance().executeCommand(project, new Runnable() {
            @Override
            public void run() {
              PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
                @Override
                public void run() {
                  final MatchProvider matchProvider =
                    member instanceof PsiMethod ? new MethodDuplicatesMatchProvider((PsiMethod)member, matches)
                                                : new ConstantMatchProvider(member, project, matches);
                  DuplicatesImpl.invoke(project, matchProvider);
                }
              });
            }
          }, REFACTORING_NAME, REFACTORING_NAME);

          WindowManager.getInstance().getStatusBar(project).setInfo("");
        }
      }
      finally {
        a.finish();
      }
    }
  };
  ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL);
}
 
Example 8
Project: intellij-ce-playground   File: CvsHandler.java   Source Code and License Vote up 5 votes
public void run(Project project, final ModalityContext executor) {
  initializeListeners();
  try {
    internalRun(project, executor, runInReadThread());
  } finally {
    cleanupListeners();
  }
  if (isCanceled())  throw new ProcessCanceledException();
  final ProgressIndicator progress = getProgress();
  if (progress != null) {
    if (progress.isCanceled()) throw new ProcessCanceledException();
  }
}
 
Example 9
Project: intellij-ce-playground   File: MvcConsole.java   Source Code and License Vote up 5 votes
private void doWait(ProgressIndicator progressIndicator) {
  while (!myHandler.waitFor(500)) {
    if (progressIndicator.isCanceled()) {
      myHandler.destroyProcess();
      break;
    }
  }
}
 
Example 10
Project: intellij-ce-playground   File: HgAddCommand.java   Source Code and License Vote up 5 votes
private void addFiles(VirtualFile repo, Collection<VirtualFile> files, @Nullable ProgressIndicator indicator) {
  final List<List<String>> chunks = VcsFileUtil.chunkFiles(repo, files);
  int currentChunk = 0;
  for (List<String> paths : chunks) {
    if (indicator != null) {
      if (indicator.isCanceled()) { return; }
      indicator.setFraction((double)currentChunk / chunks.size());
      currentChunk++;
    }
    new HgCommandExecutor(myProject).executeInCurrentThread(repo, "add", paths);
  }
}
 
Example 11
Project: intellij-ce-playground   File: SvnIdeaRepositoryPoolManager.java   Source Code and License Vote up 5 votes
@Override
public void checkCancelled() throws SVNCancelException {
  final ProgressManager pm = ProgressManager.getInstance();
  final ProgressIndicator pi = pm.getProgressIndicator();
  if (pi != null) {
    if (pi.isCanceled()) throw new SVNCancelException();
  }
  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && indicator.isCanceled()) {
    throw new SVNCancelException();
  }
}
 
Example 12
Project: intellij-ce-playground   File: ShowImageDuplicatesAction.java   Source Code and License Vote up 5 votes
private static void collectAndShowDuplicates(final Project project) {
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && !indicator.isCanceled()) {
    indicator.setText("Collecting project images...");
    indicator.setIndeterminate(false);
    final List<VirtualFile> images = new ArrayList<VirtualFile>();
    for (String ext : IMAGE_EXTENSIONS) {
      images.addAll(FilenameIndex.getAllFilesByExt(project, ext));
    }

    final Map<Long, Set<VirtualFile>> duplicates = new HashMap<Long, Set<VirtualFile>>();
    final Map<Long, VirtualFile> all = new HashMap<Long, VirtualFile>();
    for (int i = 0; i < images.size(); i++) {
      indicator.setFraction((double)(i + 1) / (double)images.size());
      final VirtualFile file = images.get(i);
      if (!(file.getFileSystem() instanceof LocalFileSystem)) continue;
      final long length = file.getLength();
      if (all.containsKey(length)) {
        if (!duplicates.containsKey(length)) {
          final HashSet<VirtualFile> files = new HashSet<VirtualFile>();
          files.add(all.get(length));
          duplicates.put(length, files);
        }
        duplicates.get(length).add(file);
      } else {
        all.put(length, file);
      }
      indicator.checkCanceled();
    }
    showResults(project, images, duplicates, all);
  }
}
 
Example 13
Project: intellij-ce-playground   File: ScreenRecorderAction.java   Source Code and License Vote up 5 votes
@Override
public void run(@NotNull ProgressIndicator indicator) {
  int elapsedTime = 0; // elapsed time in seconds
  indicator.setIndeterminate(true);
  while (true) {
    try {
      if (myCompletionLatch.await(1, TimeUnit.SECONDS)) {
        break;
      }

      // update elapsed time in seconds
      elapsedTime++;
      indicator.setText(String.format("Recording...%1$d %2$s elapsed", elapsedTime, StringUtil.pluralize("second", elapsedTime)));

      if (indicator.isCanceled()) {
        // explicitly cancel the running task
        myReceiver.cancel();

        indicator.setText("Stopping...");

        // Wait for an additional second to make sure that the command
        // completed and screen recorder finishes writing the output
        myCompletionLatch.await(1, TimeUnit.SECONDS);
        break;
      }
    }
    catch (InterruptedException ignored) {
    }
  }
}
 
Example 14
Project: intellij-ce-playground   File: CyclicDependenciesBuilder.java   Source Code and License Vote up 4 votes
public void analyze() {
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex();
  getScope().accept(new PsiRecursiveElementVisitor() {
    @Override public void visitFile(PsiFile file) {
      if (file instanceof PsiJavaFile) {
        PsiJavaFile psiJavaFile = (PsiJavaFile)file;
        if (getScope().contains(psiJavaFile)) {
          final PsiPackage aPackage = findPackage(psiJavaFile.getPackageName());
          if (aPackage != null) {
            myPackages.put(psiJavaFile.getPackageName(), aPackage);
          }
        }
        final Set<PsiPackage> packs = getPackageHierarhy(psiJavaFile.getPackageName());
        final ForwardDependenciesBuilder builder = new ForwardDependenciesBuilder(getProject(), new AnalysisScope(psiJavaFile));
        builder.setTotalFileCount(getScope().getFileCount());
        builder.setInitialFileCount(++myFileCount);
        builder.analyze();
        final Set<PsiFile> psiFiles = builder.getDependencies().get(psiJavaFile);
        if (psiFiles == null) return;
        for (PsiPackage pack : packs) {
          Set<PsiPackage> pack2Packages = myPackageDependencies.get(pack);
          if (pack2Packages == null) {
            pack2Packages = new HashSet<PsiPackage>();
            myPackageDependencies.put(pack, pack2Packages);
          }
          for (PsiFile psiFile : psiFiles) {
            if (!(psiFile instanceof PsiJavaFile) ||
                !projectFileIndex.isInSourceContent(psiFile.getVirtualFile()) ||
                !getScope().contains(psiFile)) {
              continue;
            }

            // construct dependent packages
            final String packageName = ((PsiJavaFile)psiFile).getPackageName();
            //do not depend on parent packages
            if (packageName.startsWith(pack.getQualifiedName())) {
              continue;
            }
            final PsiPackage depPackage = findPackage(packageName);
            if (depPackage == null) { //not from analyze scope
              continue;
            }
            pack2Packages.add(depPackage);

            constractFilesInDependenciesPackagesMap(pack, depPackage, psiFile, myFilesInDependentPackages);
            constractFilesInDependenciesPackagesMap(depPackage, pack, psiJavaFile, myBackwardFilesInDependentPackages);
            constractWholeDependenciesMap(psiJavaFile, psiFile);
          }
        }
      }
    }
  });
  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null) {
    if (indicator.isCanceled()) {
      throw new ProcessCanceledException();
    }
    indicator.setText(AnalysisScopeBundle.message("cyclic.dependencies.progress.text"));
    indicator.setText2("");
    indicator.setIndeterminate(true);
  }
  myCyclicDependencies = getCycles(myPackages.values());
}
 
Example 15
Project: intellij-ce-playground   File: BackgroundTaskUtil.java   Source Code and License Vote up 4 votes
@CalledInAwt
private static void finish(@NotNull Runnable result, @NotNull ProgressIndicator indicator) {
  if (indicator.isCanceled()) return;
  result.run();
  indicator.stop();
}
 
Example 16
Project: intellij-ce-playground   File: SVNStoppableInputStream.java   Source Code and License Vote up 4 votes
private void check() throws IOException {
  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && indicator.isCanceled()) {
    throw new IOException("Read request to canceled by user");
  }
}
 
Example 17
Project: intellij-ce-playground   File: UsageViewImpl.java   Source Code and License Vote up 4 votes
private void doReRun() {
  final AtomicInteger usageCountWithoutDefinition = new AtomicInteger(0);
  final Project project = myProject;
  Task.Backgroundable task = new Task.Backgroundable(project, UsageViewManagerImpl.getProgressTitle(myPresentation)) {
    @Override
    public void run(@NotNull final ProgressIndicator indicator) {
      final TooManyUsagesStatus tooManyUsagesStatus = TooManyUsagesStatus.createFor(indicator);
      setSearchInProgress(true);
      associateProgress(indicator);

      Processor<Usage> processor = new Processor<Usage>() {
        @Override
        public boolean process(final Usage usage) {
          if (searchHasBeenCancelled()) return false;
          TooManyUsagesStatus.getFrom(indicator).pauseProcessingIfTooManyUsages();

          boolean incrementCounter = !com.intellij.usages.UsageViewManager.isSelfUsage(usage, myTargets);

          if (incrementCounter) {
            final int usageCount = usageCountWithoutDefinition.incrementAndGet();
            if (usageCount > UsageLimitUtil.USAGES_LIMIT) {
              if (tooManyUsagesStatus.switchTooManyUsagesStatus()) {
                UsageViewManagerImpl
                  .showTooManyUsagesWarning(project, tooManyUsagesStatus, indicator, getPresentation(), usageCountWithoutDefinition.get(),
                                            UsageViewImpl.this);
              }
            }
            ApplicationManager.getApplication().runReadAction(new Runnable() {
              @Override
              public void run() {
                appendUsage(usage);
              }
            });
          }
          return !indicator.isCanceled();
        }
      };

      myChangesDetected = false;
      PsiManager.getInstance(project).startBatchFilesProcessingMode();
      try {
        myUsageSearcherFactory.create().generate(processor);
        drainQueuedUsageNodes();
      }
      finally {
        PsiManager.getInstance(project).finishBatchFilesProcessingMode();
      }
      setSearchInProgress(false);
    }
  };
  ProgressManager.getInstance().run(task);
}
 
Example 18
Project: intellij-ce-playground   File: SvnProgressCanceller.java   Source Code and License Vote up 4 votes
public void checkCancelled() throws SVNCancelException {
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && indicator.isCanceled()) {
    throw new SVNCancelException();
  }
}
 
Example 19
Project: intellij-ce-playground   File: SvnUtil.java   Source Code and License Vote up 4 votes
private static void checkCanceled(final ProgressIndicator progress) {
  if (progress != null && progress.isCanceled()) {
    throw new ProcessCanceledException();
  }
}
 
Example 20
Project: intellij-ce-playground   File: GradleTasksExecutor.java   Source Code and License Vote up 4 votes
@Override
public void run(@NotNull ProgressIndicator indicator) {
  if (isAndroidStudio()) {
    // See https://code.google.com/p/android/issues/detail?id=169743
    clearStoredGradleJvmArgs(getNotNullProject());
  }

  myIndicator = indicator;

  ProjectManager projectManager = ProjectManager.getInstance();
  Project project = getNotNullProject();
  myCloseListener = new CloseListener();
  projectManager.addProjectManagerListener(project, myCloseListener);

  Semaphore semaphore = ((CompilerManagerImpl)CompilerManager.getInstance(project)).getCompilationSemaphore();
  boolean acquired = false;
  try {
    try {
      while (!acquired) {
        acquired = semaphore.tryAcquire(300, MILLISECONDS);
        if (indicator.isCanceled()) {
          // Give up obtaining the semaphore, let compile work begin in order to stop gracefully on cancel event.
          break;
        }
      }
    }
    catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }

    if (!isHeadless()) {
      addIndicatorDelegate();
    }
    invokeGradleTasks();
  }
  finally {
    try {
      indicator.stop();
      projectManager.removeProjectManagerListener(project, myCloseListener);
    }
    finally {
      if (acquired) {
        semaphore.release();
      }
    }
  }
}