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

The following examples show how to use com.intellij.openapi.progress.ProgressIndicator#checkCanceled() . 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: ByLine.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static FairDiffIterable doCompare(@Nonnull List<Line> lines1,
                                  @Nonnull List<Line> lines2,
                                  @Nonnull ComparisonPolicy policy,
                                  @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();

  if (policy == IGNORE_WHITESPACES) {
    FairDiffIterable changes = compareSmart(lines1, lines2, indicator);
    changes = optimizeLineChunks(lines1, lines2, changes, indicator);
    return expandRanges(lines1, lines2, changes);
  }
  else {
    List<Line> iwLines1 = convertMode(lines1, IGNORE_WHITESPACES);
    List<Line> iwLines2 = convertMode(lines2, IGNORE_WHITESPACES);

    FairDiffIterable iwChanges = compareSmart(iwLines1, iwLines2, indicator);
    iwChanges = optimizeLineChunks(lines1, lines2, iwChanges, indicator);
    return correctChangesSecondStep(lines1, lines2, iwChanges);
  }
}
 
Example 2
Source File: RepositoryHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static List<PluginDescriptor> readPluginsStream(InputStream is, ProgressIndicator indicator) throws Exception {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try {
    byte[] buffer = new byte[1024];
    int size;
    while ((size = is.read(buffer)) > 0) {
      os.write(buffer, 0, size);
      if (indicator != null) {
        indicator.checkCanceled();
      }
    }
  }
  finally {
    os.close();
  }

  PluginJsonNode[] nodes =
          new Gson().fromJson(new InputStreamReader(new ByteArrayInputStream(os.toByteArray()), StandardCharsets.UTF_8), PluginJsonNode[].class);

  List<PluginDescriptor> pluginDescriptors = new ArrayList<>(nodes.length);
  for (PluginJsonNode jsonPlugin : nodes) {
    pluginDescriptors.add(new PluginNode(jsonPlugin));
  }
  return pluginDescriptors;
}
 
Example 3
Source File: CompileDriver.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean doPrune(ProgressIndicator progress, final File directory, final Set<File> outPutDirectories) {
  progress.checkCanceled();
  final File[] files = directory.listFiles();
  boolean isEmpty = true;
  if (files != null) {
    for (File file : files) {
      if (!outPutDirectories.contains(file)) {
        if (doPrune(progress, file, outPutDirectories)) {
          deleteFile(file);
        }
        else {
          isEmpty = false;
        }
      }
      else {
        isEmpty = false;
      }
    }
  }
  else {
    isEmpty = false;
  }

  return isEmpty;
}
 
Example 4
Source File: ByLine.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static List<MergeRange> doCompare(@Nonnull List<Line> lines1,
                                  @Nonnull List<Line> lines2,
                                  @Nonnull List<Line> lines3,
                                  @Nonnull ComparisonPolicy policy,
                                  @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();

  List<Line> iwLines1 = convertMode(lines1, IGNORE_WHITESPACES);
  List<Line> iwLines2 = convertMode(lines2, IGNORE_WHITESPACES);
  List<Line> iwLines3 = convertMode(lines3, IGNORE_WHITESPACES);

  FairDiffIterable iwChanges1 = compareSmart(iwLines2, iwLines1, indicator);
  iwChanges1 = optimizeLineChunks(lines2, lines1, iwChanges1, indicator);
  FairDiffIterable iterable1 = correctChangesSecondStep(lines2, lines1, iwChanges1);

  FairDiffIterable iwChanges2 = compareSmart(iwLines2, iwLines3, indicator);
  iwChanges2 = optimizeLineChunks(lines2, lines3, iwChanges2, indicator);
  FairDiffIterable iterable2 = correctChangesSecondStep(lines2, lines3, iwChanges2);

  return ComparisonMergeUtil.buildFair(iterable1, iterable2, indicator);
}
 
Example 5
Source File: DefaultChooseByNameItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean filterElements(@Nonnull ChooseByNameViewModel base,
                                      @Nonnull ProgressIndicator indicator,
                                      @Nullable PsiElement context,
                                      @Nullable Supplier<String[]> allNamesProducer,
                                      @Nonnull Processor<FoundItemDescriptor<?>> consumer,
                                      @Nonnull FindSymbolParameters parameters) {
  boolean everywhere = parameters.isSearchInLibraries();
  String pattern = parameters.getCompletePattern();
  if (base.getProject() != null) {
    base.getProject().putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern);
  }

  String namePattern = getNamePattern(base, pattern);
  boolean preferStartMatches = !pattern.startsWith("*");

  List<MatchResult> namesList = getSortedNamesForAllWildcards(base, parameters, indicator, allNamesProducer, namePattern, preferStartMatches);

  indicator.checkCanceled();

  return processByNames(base, everywhere, indicator, context, consumer, preferStartMatches, namesList, parameters);
}
 
Example 6
Source File: ActionManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void preloadActions(@Nonnull ProgressIndicator indicator) {
  Application application = ApplicationManager.getApplication();

  for (String id : getActionIds()) {
    indicator.checkCanceled();
    if (application.isDisposeInProgress() || application.isDisposed()) return;

    AnAction action = getAction(id);
    if (action instanceof PreloadableAction) {
      ((PreloadableAction)action).preload();
    }
    // don't preload ActionGroup.getChildren() because that would un-stub child actions
    // and make it impossible to replace the corresponding actions later
    // (via unregisterAction+registerAction, as some app components do)
  }
  myPreloadComplete = true;
}
 
Example 7
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void visitRestElementsAndCleanup(@Nonnull final ProgressIndicator indicator,
                                         @Nonnull final List<PsiElement> elements,
                                         @Nonnull final LocalInspectionToolSession session,
                                         @Nonnull List<InspectionContext> init,
                                         @Nonnull final Set<String> elementDialectIds) {
  Processor<InspectionContext> processor = context -> {
    indicator.checkCanceled();
    ApplicationManager.getApplication().assertReadAccessAllowed();
    InspectionEngine.acceptElements(elements, context.visitor, elementDialectIds, context.dialectIdsSpecifiedForTool);
    advanceProgress(1);
    context.tool.getTool().inspectionFinished(session, context.holder);

    if (context.holder.hasResults()) {
      List<ProblemDescriptor> allProblems = context.holder.getResults();
      List<ProblemDescriptor> restProblems = allProblems.subList(context.problemsSize, allProblems.size());
      appendDescriptors(getFile(), restProblems, context.tool);
    }
    return true;
  };
  boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(init, indicator, myFailFastOnAcquireReadAction, processor);
  if (!result) {
    throw new ProcessCanceledException();
  }
}
 
Example 8
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void runToolOnElements(@Nonnull final LocalInspectionToolWrapper toolWrapper,
                               Set<String> dialectIdsSpecifiedForTool,
                               @Nonnull final InspectionManager iManager,
                               final boolean isOnTheFly,
                               @Nonnull final ProgressIndicator indicator,
                               @Nonnull final List<PsiElement> elements,
                               @Nonnull final LocalInspectionToolSession session,
                               @Nonnull List<InspectionContext> init,
                               @Nonnull Set<String> elementDialectIds) {
  indicator.checkCanceled();

  ApplicationManager.getApplication().assertReadAccessAllowed();
  final LocalInspectionTool tool = toolWrapper.getTool();
  final boolean[] applyIncrementally = {isOnTheFly};
  ProblemsHolder holder = new ProblemsHolder(iManager, getFile(), isOnTheFly) {
    @Override
    public void registerProblem(@Nonnull ProblemDescriptor descriptor) {
      super.registerProblem(descriptor);
      if (applyIncrementally[0]) {
        addDescriptorIncrementally(descriptor, toolWrapper, indicator);
      }
    }
  };

  PsiElementVisitor visitor =
          InspectionEngine.createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, elementDialectIds, dialectIdsSpecifiedForTool);

  synchronized (init) {
    init.add(new InspectionContext(toolWrapper, holder, holder.getResultCount(), visitor, dialectIdsSpecifiedForTool));
  }
  advanceProgress(1);

  if (holder.hasResults()) {
    appendDescriptors(getFile(), holder.getResults(), toolWrapper);
  }
  applyIncrementally[0] = false; // do not apply incrementally outside visible range
}
 
Example 9
Source File: DiffIterableUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static <T> FairDiffIterable diff(@Nonnull T[] data1, @Nonnull T[] data2, @Nonnull ProgressIndicator indicator)
        throws DiffTooBigException {
  indicator.checkCanceled();

  try {
    // TODO: use ProgressIndicator inside
    Diff.Change change = Diff.buildChanges(data1, data2);
    return fair(create(change, data1.length, data2.length));
  }
  catch (FilesTooBigForDiffException e) {
    throw new DiffTooBigException();
  }
}
 
Example 10
Source File: DiffIterableUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static <T> FairDiffIterable diff(@Nonnull List<T> objects1, @Nonnull List<T> objects2, @Nonnull ProgressIndicator indicator)
        throws DiffTooBigException {
  indicator.checkCanceled();

  // TODO: compare lists instead of arrays in Diff
  Object[] data1 = ContainerUtil.toArray((List)objects1, new Object[objects1.size()]);
  Object[] data2 = ContainerUtil.toArray((List)objects2, new Object[objects2.size()]);
  return diff(data1, data2, indicator);
}
 
Example 11
Source File: ApplicationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to interrupt a process which does not performs checkCancelled() calls by itself.
 * Note that the process may continue to run in background indefinitely - so <b>avoid using this method unless absolutely needed</b>.
 */
public static <T> T runWithCheckCanceled(@Nonnull final Callable<T> callable, @Nonnull final ProgressIndicator indicator) throws Exception {
  final Ref<T> result = Ref.create();
  final Ref<Throwable> error = Ref.create();

  Future<?> future = PooledThreadExecutor.INSTANCE.submit(() -> ProgressManager.getInstance().executeProcessUnderProgress(() -> {
    try {
      result.set(callable.call());
    }
    catch (Throwable t) {
      error.set(t);
    }
  }, indicator));

  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      future.cancel(true);
      throw e;
    }

    try {
      future.get(200, TimeUnit.MILLISECONDS);
      ExceptionUtil.rethrowAll(error.get());
      return result.get();
    }
    catch (TimeoutException ignored) {
    }
  }
}
 
Example 12
Source File: ByLine.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<MergeRange> compare(@Nonnull List<? extends CharSequence> lines1,
                                       @Nonnull List<? extends CharSequence> lines2,
                                       @Nonnull List<? extends CharSequence> lines3,
                                       @Nonnull ComparisonPolicy policy,
                                       @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();
  return doCompare(getLines(lines1, policy), getLines(lines2, policy), getLines(lines3, policy), policy, indicator);
}
 
Example 13
Source File: ByChar.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static DiffIterable compareIgnoreWhitespaces(@Nonnull CharSequence text1,
                                                    @Nonnull CharSequence text2,
                                                    @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();

  CharOffsets chars1 = getNonSpaceChars(text1);
  CharOffsets chars2 = getNonSpaceChars(text2);

  FairDiffIterable changes = diff(chars1.characters, chars2.characters, indicator);
  return matchAdjustmentSpacesIW(chars1, chars2, text1, text2, changes);
}
 
Example 14
Source File: ByWord.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<DiffFragment> compare(@Nonnull CharSequence text1,
                                         @Nonnull CharSequence text2,
                                         @Nonnull ComparisonPolicy policy,
                                         @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();

  List<InlineChunk> words1 = getInlineChunks(text1);
  List<InlineChunk> words2 = getInlineChunks(text2);

  return compare(text1, words1, text2, words2, policy, indicator);
}
 
Example 15
Source File: LocalInspectionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void inspect(@Nonnull final List<LocalInspectionToolWrapper> toolWrappers,
                     @Nonnull final InspectionManager iManager,
                     final boolean isOnTheFly,
                     boolean failFastOnAcquireReadAction,
                     @Nonnull final ProgressIndicator progress) {
  myFailFastOnAcquireReadAction = failFastOnAcquireReadAction;
  if (toolWrappers.isEmpty()) return;

  List<Divider.DividedElements> allDivided = new ArrayList<>();
  Divider.divideInsideAndOutsideAllRoots(myFile, myRestrictRange, myPriorityRange, SHOULD_INSPECT_FILTER,
                                         new CommonProcessors.CollectProcessor<>(allDivided));
  List<PsiElement> inside = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> d.inside));
  List<PsiElement> outside = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> ContainerUtil.concat(d.outside, d.parents)));

  Set<String> elementDialectIds = InspectionEngine.calcElementDialectIds(inside, outside);
  Map<LocalInspectionToolWrapper, Set<String>> toolToSpecifiedLanguageIds = InspectionEngine.getToolsToSpecifiedLanguages(toolWrappers);

  setProgressLimit(toolToSpecifiedLanguageIds.size() * 2L);
  final LocalInspectionToolSession session = new LocalInspectionToolSession(getFile(), myRestrictRange.getStartOffset(), myRestrictRange.getEndOffset());

  List<InspectionContext> init =
          visitPriorityElementsAndInit(toolToSpecifiedLanguageIds, iManager, isOnTheFly, progress, inside, session, toolWrappers, elementDialectIds);
  inspectInjectedPsi(inside, isOnTheFly, progress, iManager, true, toolWrappers);
  visitRestElementsAndCleanup(progress, outside, session, init, elementDialectIds);
  inspectInjectedPsi(outside, isOnTheFly, progress, iManager, false, toolWrappers);

  progress.checkCanceled();

  myInfos = new ArrayList<>();
  addHighlightsFromResults(myInfos, progress);
}
 
Example 16
Source File: FileContentQueue.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public FileContent take(@Nonnull ProgressIndicator indicator) throws ProcessCanceledException {
  final FileContent content = doTake(indicator);
  if (content == null) {
    return null;
  }
  final long length = content.getLength();
  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      pushBack(content);
      throw e;
    }

    synchronized (myProceedWithProcessingLock) {
      final boolean requestingLargeSize = length > LARGE_SIZE_REQUEST_THRESHOLD;
      if (requestingLargeSize) {
        myLargeSizeRequested = true;
      }
      try {
        if (myLargeSizeRequested && !requestingLargeSize || myBytesBeingProcessed + length > Math.max(PROCESSED_FILE_BYTES_THRESHOLD, length)) {
          myProceedWithProcessingLock.wait(300);
        }
        else {
          myBytesBeingProcessed += length;
          if (requestingLargeSize) {
            myLargeSizeRequested = false;
          }
          return content;
        }
      }
      catch (InterruptedException ignore) {
      }
    }
  }
}
 
Example 17
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Use when otherwise a deadlock is possible.
 */
public static void checkCancelledEvenWithPCEDisabled(@Nullable ProgressIndicator indicator) {
  if (indicator != null && indicator.isCanceled()) {
    indicator.checkCanceled(); // maybe it'll throw with some useful additional information
    throw new ProcessCanceledException();
  }
}
 
Example 18
Source File: Waiter.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void run(@Nonnull ProgressIndicator indicator) {
  indicator.setIndeterminate(true);
  indicator.setText2(VcsBundle.message("commit.wait.util.synched.text"));

  if (!myStarted.compareAndSet(false, true)) {
    LOG.error("Waiter running under progress being started again.");
  }
  else {
    while (!mySemaphore.waitFor(500)) {
      indicator.checkCanceled();
    }
  }
}
 
Example 19
Source File: ByWord.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static List<LineBlock> compareAndSplit(@Nonnull CharSequence text1,
                                              @Nonnull CharSequence text2,
                                              @Nonnull ComparisonPolicy policy,
                                              @Nonnull ProgressIndicator indicator) {
  indicator.checkCanceled();

  // TODO: figure out, what do we exactly want from 'Split' logic
  // -- it is used for trimming of ignored blocks. So we want whitespace-only leading/trailing lines to be separate block.
  // -- old approach: split by matched '\n's

  // TODO: other approach could lead to better results:
  // * Compare words-only
  // * prefer big chunks
  // -- here we can try to minimize number of matched pairs 'pair[i]' and 'pair[i+1]' such that
  //    containsNewline(pair[i].left .. pair[i+1].left) XOR containsNewline(pair[i].right .. pair[i+1].right) == true
  //    ex: "A X C" - "A Y C \n M C" - do not match with last 'C'
  //    ex: "A \n" - "A B \n \n" - do not match with last '\n'
  //    Try some greedy approach ?
  // * split into blocks
  // -- squash blocks with too small unchanged words count (1 matched word out of 40 - is a bad reason to create new block)
  // * match adjustment punctuation
  // * match adjustment whitespaces ('\n' are matched here)

  List<InlineChunk> words1 = getInlineChunks(text1);
  List<InlineChunk> words2 = getInlineChunks(text2);

  FairDiffIterable wordChanges = diff(words1, words2, indicator);
  wordChanges = optimizeWordChunks(text1, text2, words1, words2, wordChanges, indicator);

  List<WordBlock> wordBlocks = new LineFragmentSplitter(text1, text2, words1, words2, wordChanges, indicator).run();

  List<LineBlock> lineBlocks = new ArrayList<>(wordBlocks.size());
  for (WordBlock block : wordBlocks) {
    Range offsets = block.offsets;
    Range words = block.words;

    CharSequence subtext1 = text1.subSequence(offsets.start1, offsets.end1);
    CharSequence subtext2 = text2.subSequence(offsets.start2, offsets.end2);

    List<InlineChunk> subwords1 = words1.subList(words.start1, words.end1);
    List<InlineChunk> subwords2 = words2.subList(words.start2, words.end2);

    FairDiffIterable subiterable = fair(trim(wordChanges, words.start1, words.end1, words.start2, words.end2));

    FairDiffIterable delimitersIterable = matchAdjustmentDelimiters(subtext1, subtext2, subwords1, subwords2, subiterable,
                                                                    offsets.start1, offsets.start2, indicator);
    DiffIterable iterable = matchAdjustmentWhitespaces(subtext1, subtext2, delimitersIterable, policy, indicator);

    List<DiffFragment> fragments = convertIntoDiffFragments(iterable);

    int newlines1 = countNewlines(subwords1);
    int newlines2 = countNewlines(subwords2);

    lineBlocks.add(new LineBlock(fragments, offsets, newlines1, newlines2));
  }

  return lineBlocks;
}
 
Example 20
Source File: BaseProjectTreeBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void expandChild(@Nonnull final List<? extends AbstractTreeNode> kids,
                         int i,
                         @Nonnull final Condition<AbstractTreeNode> nonStopCondition,
                         final VirtualFile file,
                         final Object element,
                         @Nonnull final AsyncPromise<? super AbstractTreeNode> async,
                         @Nonnull final ProgressIndicator indicator,
                         final Ref<Object> virtualSelectTarget) {
  while (i < kids.size()) {
    final AbstractTreeNode eachKid = kids.get(i);
    final boolean[] nodeWasCollapsed = {true};
    final DefaultMutableTreeNode nodeForElement = getNodeForElement(eachKid);
    if (nodeForElement != null) {
      nodeWasCollapsed[0] = getTree().isCollapsed(new TreePath(nodeForElement.getPath()));
    }

    if (nonStopCondition.value(eachKid)) {
      final Promise<AbstractTreeNode> result = expandPathTo(file, eachKid, element, nonStopCondition, indicator, virtualSelectTarget);
      result.onSuccess(abstractTreeNode -> {
        indicator.checkCanceled();
        async.setResult(abstractTreeNode);
      });

      if (result.getState() == Promise.State.PENDING) {
        final int next = i + 1;
        result.onError(error -> {
          indicator.checkCanceled();

          if (nodeWasCollapsed[0] && virtualSelectTarget == null) {
            collapseChildren(eachKid, null);
          }
          expandChild(kids, next, nonStopCondition, file, element, async, indicator, virtualSelectTarget);
        });
        return;
      }
      else {
        if (result.getState() == Promise.State.REJECTED) {
          indicator.checkCanceled();
          if (nodeWasCollapsed[0] && virtualSelectTarget == null) {
            collapseChildren(eachKid, null);
          }
          i++;
        }
        else {
          return;
        }
      }
    }
    else {
      //filter tells us to stop here (for instance, in case of module nodes)
      break;
    }
  }
  async.cancel();
}