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

The following examples show how to use com.intellij.openapi.progress.ProgressIndicator#isCanceled() . 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: TranslateTask.java    From AndroidLocalizePlugin with Apache License 2.0 6 votes vote down vote up
private void writeResultData(ProgressIndicator progressIndicator) {
    if (progressIndicator.isCanceled()) return;

    if (mWriteData == null) {
        translateError(new IllegalArgumentException("No translate data."));
        return;
    }

    Set<String> keySet = mWriteData.keySet();
    for (String key : keySet) {
        if (progressIndicator.isCanceled()) break;

        File writeFile = getWriteFileForCode(key);
        progressIndicator.setText("Write to " + writeFile.getParentFile().getName() + " data...");
        write(writeFile, mWriteData.get(key));
        refreshAndOpenFile(writeFile);
    }
}
 
Example 2
Source File: MuleSdkSelectionDialog.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
private boolean download(ProgressIndicator progressIndicator, URL url, File outputFile, String version) {
    try {
        HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
        long completeFileSize = httpConnection.getContentLength();
        java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
        java.io.FileOutputStream fos = new java.io.FileOutputStream(outputFile);
        java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, BUFFER_SIZE);
        byte[] data = new byte[BUFFER_SIZE];
        long downloadedFileSize = 0;
        int x;
        while (!progressIndicator.isCanceled() && (x = in.read(data, 0, BUFFER_SIZE)) >= 0) {
            downloadedFileSize += x;
            // calculate progress
            final double currentProgress = ((double) downloadedFileSize) / ((double) completeFileSize);
            progressIndicator.setFraction(currentProgress);
            progressIndicator.setText2(Math.ceil(downloadedFileSize / (1024 * 1024)) + "/" + (Math.ceil(completeFileSize / (1024 * 1024)) + " MB"));
            bout.write(data, 0, x);
        }
        bout.close();
        in.close();
    } catch (IOException e) {
        Messages.showErrorDialog("An error occurred while trying to download " + version + ".\n" + e.getMessage(), "Mule SDK Download Error");
        return false;
    }
    return !progressIndicator.isCanceled();
}
 
Example 3
Source File: TranslatingCompilerFilesMonitorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void ensureInitializationCompleted(Project project, ProgressIndicator indicator) {
  final int id = getProjectId(project);
  synchronized (myAsyncScanLock) {
    while (myInitInProgress.containsKey(id)) {
      if (!project.isOpen() || project.isDisposed() || (indicator != null && indicator.isCanceled())) {
        // makes no sense to continue waiting
        break;
      }
      try {
        myAsyncScanLock.wait(500);
      }
      catch (InterruptedException ignored) {
        break;
      }
    }
  }
}
 
Example 4
Source File: AbstractProgressIndicatorBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void initStateFrom(@Nonnull final ProgressIndicator indicator) {
  synchronized (getLock()) {
    myRunning = indicator.isRunning();
    myCanceled = indicator.isCanceled();
    myFraction = indicator.getFraction();
    myIndeterminate = indicator.isIndeterminate();
    myText = indicator.getText();

    myText2 = indicator.getText2();

    myFraction = indicator.getFraction();

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

      myTextStack = stacked.myTextStack == null ? null : new Stack<>(stacked.getTextStack());

      myText2Stack = stacked.myText2Stack == null ? null : new Stack<>(stacked.getText2Stack());

      myFractionStack = stacked.myFractionStack == null ? null : new TDoubleArrayList(stacked.getFractionStack().toNativeArray());
    }
    dontStartActivity();
  }
}
 
Example 5
Source File: PassExecutorService.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void log(ProgressIndicator progressIndicator, TextEditorHighlightingPass pass, @NonNls @Nonnull Object... info) {
  if (LOG.isDebugEnabled()) {
    CharSequence docText = pass == null || pass.getDocument() == null ? "" : ": '" + StringUtil.first(pass.getDocument().getCharsSequence(), 10, true) + "'";
    synchronized (PassExecutorService.class) {
      String infos = StringUtil.join(info, Functions.TO_STRING(), " ");
      String message = StringUtil.repeatSymbol(' ', getThreadNum() * 4) +
                       " " +
                       pass +
                       " " +
                       infos +
                       "; progress=" +
                       (progressIndicator == null ? null : progressIndicator.hashCode()) +
                       " " +
                       (progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V") +
                       docText;
      LOG.debug(message);
      //System.out.println(message);
    }
  }
}
 
Example 6
Source File: GotoActionModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnEdt(Runnable update) {
  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      update.run();
    }
    finally {
      semaphore.up();
    }
  }, myModality, __ -> indicator != null && indicator.isCanceled());

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
}
 
Example 7
Source File: TreeUiTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
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 8
Source File: MultiThreadSearcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  LOG.debug("Search task started for contributor ", myContributor);
  try {
    boolean repeat;
    do {
      ProgressIndicator wrapperIndicator = new SensitiveProgressWrapper(myIndicator);
      try {
        Runnable runnable = (myContributor instanceof WeightedSearchEverywhereContributor)
                            ? () -> ((WeightedSearchEverywhereContributor<Item>)myContributor)
                .fetchWeightedElements(myPattern, wrapperIndicator, descriptor -> processFoundItem(descriptor.getItem(), descriptor.getWeight(), wrapperIndicator))
                            : () -> myContributor.fetchElements(myPattern, wrapperIndicator, element -> {
                              int priority = myContributor.getElementPriority(element, myPattern);
                              return processFoundItem(element, priority, wrapperIndicator);
                            });

        ProgressManager.getInstance().runProcess(runnable, wrapperIndicator);
      }
      catch (ProcessCanceledException ignore) {
      }
      repeat = !myIndicator.isCanceled() && wrapperIndicator.isCanceled();
    }
    while (repeat);

    if (myIndicator.isCanceled()) {
      return;
    }
    myAccumulator.contributorFinished(myContributor);
  }
  finally {
    finishCallback.run();
  }
  LOG.debug("Search task finished for contributor ", myContributor);
}
 
Example 9
Source File: ActionUpdateEdtExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the supplied value on Swing thread, but try to avoid deadlocks by periodically performing {@link ProgressManager#checkCanceled()} in the current thread.
 * Makes sense to be used in background read actions running with a progress indicator that's canceled when a write action is about to occur.
 *
 * @see com.intellij.openapi.application.ReadAction#nonBlocking(Runnable)
 */
public static <T> T computeOnEdt(Supplier<T> supplier) {
  Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    return supplier.get();
  }

  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  Ref<T> result = Ref.create();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      if (indicator == null || !indicator.isCanceled()) {
        result.set(supplier.get());
      }
    }
    finally {
      semaphore.up();
    }
  });

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
  // check cancellation one last time, to ensure the EDT action wasn't no-op due to cancellation
  if (indicator != null && indicator.isCanceled()) {
    throw new ProcessCanceledException();
  }
  return result.get();
}
 
Example 10
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Trinity<ProblemDescriptor, LocalInspectionToolWrapper, ProgressIndicator> trinity) {
  ProgressIndicator indicator = trinity.getThird();
  if (indicator.isCanceled()) {
    return false;
  }

  ProblemDescriptor descriptor = trinity.first;
  LocalInspectionToolWrapper tool = trinity.second;
  PsiElement psiElement = descriptor.getPsiElement();
  if (psiElement == null) return true;
  PsiFile file = psiElement.getContainingFile();
  Document thisDocument = documentManager.getDocument(file);

  HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();

  infos.clear();
  createHighlightsForDescriptor(infos, emptyActionRegistered, ilManager, file, thisDocument, tool, severity, descriptor, psiElement);
  for (HighlightInfo info : infos) {
    final EditorColorsScheme colorsScheme = getColorsScheme();
    UpdateHighlightersUtil
            .addHighlighterToEditorIncrementally(myProject, myDocument, getFile(), myRestrictRange.getStartOffset(), myRestrictRange.getEndOffset(),
                                                 info, colorsScheme, getId(), ranges2markersCache);
  }

  return true;
}
 
Example 11
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static
@Nonnull
Runnable indicatorCancellation(@Nonnull ProgressIndicator progressIndicator) {
  return () -> {
    if (!progressIndicator.isCanceled()) {
      progressIndicator.cancel();
    }
  };
}
 
Example 12
Source File: SequentialModalProgressTask.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void doRun(@Nonnull ProgressIndicator indicator) throws InvocationTargetException, InterruptedException {
  final SequentialTask task = myTask;
  if (task == null) {
    return;
  }
  
  myIndicator = indicator;
  indicator.setIndeterminate(false);
  prepare(task);
  
  // We need to sync background thread and EDT here in order to avoid situation when event queue is full of processing requests.
  while (!task.isDone()) {
    if (indicator.isCanceled()) {
      task.stop();
      break;
    }
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        long start = System.currentTimeMillis();
        try {
          while (!task.isDone() && System.currentTimeMillis() - start < myMinIterationTime) {
            task.iteration();
          }
        }
        catch (RuntimeException e) {
          task.stop();
          throw e;
        }
      }
    });
    //if (ApplicationManager.getApplication().isDispatchThread()) {
    //  runnable.run();
    //}
    //else {
    //  ApplicationManagerEx.getApplicationEx().suspendReadAccessAndRunWriteAction(runnable);
    //}
  }
}
 
Example 13
Source File: TranslateTask.java    From AndroidLocalizePlugin with Apache License 2.0 5 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
    boolean isOverwriteExistingString = PropertiesComponent.getInstance(myProject)
            .getBoolean(Constants.KEY_IS_OVERWRITE_EXISTING_STRING);
    Querier<AbstractTranslator> translator = new Querier<>();
    GoogleTranslator googleTranslator = new GoogleTranslator();
    translator.attach(googleTranslator);
    mWriteData.clear();

    for (LANG toLanguage : mLanguages) {
        if (progressIndicator.isCanceled()) break;

        progressIndicator.setText("Translating in the " + toLanguage.getEnglishName() + " language...");

        if (isOverwriteExistingString) {
            translate(progressIndicator, translator, toLanguage, null);
            continue;
        }

        ApplicationManager.getApplication().runReadAction(() -> {
            VirtualFile virtualFile = getVirtualFile(toLanguage);

            if (virtualFile == null) {
                translate(progressIndicator, translator, toLanguage, null);
                return;
            }

            PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
            if (psiFile == null) {
                translate(progressIndicator, translator, toLanguage, null);
                return;
            }

            List<AndroidString> androidStrings = ParseStringXml.parse(progressIndicator, psiFile);
            translate(progressIndicator, translator, toLanguage, androidStrings);
        });
    }
    googleTranslator.close();
    writeResultData(progressIndicator);
}
 
Example 14
Source File: ParseStringXml.java    From AndroidLocalizePlugin with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the strings.xml corresponding to {@link PsiFile}.
 *
 * @param progressIndicator prompt text.
 * @param psiFile           strings.xml psi file.
 * @return parsed android string list.
 */
@NotNull
public static List<AndroidString> parse(@Nullable ProgressIndicator progressIndicator, @NotNull PsiFile psiFile) {
    List<AndroidString> androidStrings = new ArrayList<>();
    XmlFile file = (XmlFile) psiFile;
    XmlDocument document = file.getDocument();
    if (document != null) {
        XmlTag rootTag = document.getRootTag();
        if (rootTag != null) {
            XmlTag[] stringTags = rootTag.findSubTags("string");
            for (XmlTag stringTag : stringTags) {
                if (progressIndicator != null && progressIndicator.isCanceled()) {
                    break;
                }

                String name = stringTag.getAttributeValue("name");
                String translatableStr = stringTag.getAttributeValue("translatable");
                boolean translatable = Boolean.valueOf(translatableStr == null ? "true" : translatableStr);

                List<Content> contents = new ArrayList<>();
                XmlTagChild[] tags = stringTag.getValue().getChildren();
                for (XmlTagChild child : tags) {
                    if (child instanceof XmlText) {
                        XmlText xmlText = (XmlText) child;
                        contents.add(new Content(xmlText.getValue()));
                    } else if (child instanceof XmlTag) {
                        XmlTag xmlTag = (XmlTag) child;
                        if (!xmlTag.getName().equals("xliff:g")) continue;

                        String text = xmlTag.getValue().getText();
                        String id = xmlTag.getAttributeValue("id");
                        String example = xmlTag.getAttributeValue("example");
                        contents.add(new Content(text, id, example, true));
                    }
                }

                androidStrings.add(new AndroidString(name, contents, translatable));

                if (progressIndicator != null) {
                    progressIndicator.setText("Loading " + name + " text from strings.xml...");
                }
            }
        }
    }
    return androidStrings;
}
 
Example 15
Source File: RoboVmCompileTask.java    From robovm-idea with GNU General Public License v2.0 4 votes vote down vote up
private boolean compileForIpa(CompileContext context, final CreateIpaAction.IpaConfig ipaConfig) {
    try {
        ProgressIndicator progress = context.getProgressIndicator();
        context.getProgressIndicator().pushState();
        RoboVmPlugin.focusToolWindow(context.getProject());
        progress.setText("Creating IPA");

        RoboVmPlugin.logInfo(context.getProject(), "Creating package in " + ipaConfig.getDestinationDir().getAbsolutePath() + " ...");

        Config.Builder builder = new Config.Builder();
        builder.logger(RoboVmPlugin.getLogger(context.getProject()));
        File moduleBaseDir = new File(ModuleRootManager.getInstance(ipaConfig.getModule()).getContentRoots()[0].getPath());

        // load the robovm.xml file
        loadConfig(context.getProject(), builder, moduleBaseDir, false);
        builder.os(OS.ios);
        builder.archs(ipaConfig.getArchs());
        builder.installDir(ipaConfig.getDestinationDir());
        builder.iosSignIdentity(SigningIdentity.find(SigningIdentity.list(), ipaConfig.getSigningIdentity()));
        if (ipaConfig.getProvisioningProfile() != null) {
            builder.iosProvisioningProfile(ProvisioningProfile.find(ProvisioningProfile.list(), ipaConfig.getProvisioningProfile()));
        }
        configureClassAndSourcepaths(context, builder, ipaConfig.getModule());
        builder.home(RoboVmPlugin.getRoboVmHome());
        Config config = builder.build();

        progress.setFraction(0.5);

        AppCompiler compiler = new AppCompiler(config);
        RoboVmCompilerThread thread = new RoboVmCompilerThread(compiler, progress) {
            protected void doCompile() throws Exception {
                compiler.build();
                compiler.archive();
            }
        };
        thread.compile();

        if(progress.isCanceled()) {
            RoboVmPlugin.logInfo(context.getProject(), "Build canceled");
            return false;
        }

        progress.setFraction(1);
        RoboVmPlugin.logInfo(context.getProject(), "Package successfully created in " + ipaConfig.getDestinationDir().getAbsolutePath());
    } catch(Throwable t) {
        RoboVmPlugin.logErrorThrowable(context.getProject(), "Couldn't create IPA", t, false);
        return false;
    } finally {
        context.getProgressIndicator().popState();
    }
    return true;
}
 
Example 16
Source File: CapturingProcessRunner.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public ProcessOutput runProcess(@Nonnull ProgressIndicator indicator, int timeoutInMilliseconds, boolean destroyOnTimeout) {
  // keep in sync with runProcess
  if (timeoutInMilliseconds <= 0) {
    timeoutInMilliseconds = Integer.MAX_VALUE;
  }

  final int WAIT_INTERVAL = 10;
  int waitingTime = 0;
  boolean setExitCode = true;

  myProcessHandler.startNotify();
  while (!myProcessHandler.waitFor(WAIT_INTERVAL)) {
    waitingTime += WAIT_INTERVAL;

    boolean timeout = waitingTime >= timeoutInMilliseconds;
    boolean canceled = indicator.isCanceled();

    if (canceled || timeout) {
      boolean destroying = canceled || destroyOnTimeout;
      setExitCode = destroying;

      if (destroying && !myProcessHandler.isProcessTerminating() && !myProcessHandler.isProcessTerminated()) {
        myProcessHandler.destroyProcess();
      }

      if (canceled) {
        myOutput.setCancelled();
      }
      else {
        myOutput.setTimeout();
      }
      break;
    }
  }
  if (setExitCode) {
    if (myProcessHandler.waitFor()) {
      setErrorCodeIfNotYetSet();
    }
    else {
      LOG.info("runProcess: exit value unavailable");
    }
  }
  return myOutput;
}
 
Example 17
Source File: CompilerTask.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void run(@Nonnull final ProgressIndicator indicator) {
  myIndicator = indicator;

  indicator.setIndeterminate(false);

  final Semaphore semaphore = ((CompilerManagerImpl)CompilerManager.getInstance(myProject)).getCompilationSemaphore();
  boolean acquired = false;
  try {

    try {
      while (!acquired) {
        acquired = semaphore.tryAcquire(300, TimeUnit.MILLISECONDS);
        if (!acquired && !myWaitForPreviousSession) {
          return;
        }
        if (indicator.isCanceled()) {
          // give up obtaining the semaphore,
          // let compile work begin in order to stop gracefuly on cancel event
          break;
        }
      }
    }
    catch (InterruptedException ignored) {
    }

    if (!isHeadless()) {
      addIndicatorDelegate();
    }
    myCompileWork.run();
  }
  finally {
    try {
      indicator.stop();
    }
    finally {
      if (acquired) {
        semaphore.release();
      }
    }
  }
}
 
Example 18
Source File: TFSProgressUtil.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static boolean isCanceled(final @Nullable ProgressIndicator progressIndicator) {
    return progressIndicator != null && progressIndicator.isCanceled();
}
 
Example 19
Source File: BackgroundTaskUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
private static void finish(@Nonnull Runnable result, @Nonnull ProgressIndicator indicator) {
  if (!indicator.isCanceled()) result.run();
}
 
Example 20
Source File: TFSProgressUtil.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static void checkCanceled(final @Nullable ProgressIndicator progressIndicator) throws ProcessCanceledException {
    if (progressIndicator != null && progressIndicator.isCanceled()) {
        throw new ProcessCanceledException();
    }
}