public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (myProgress.isCanceled()) {
      return Printable.NO_SUCH_PAGE;
    }
    while (myFileIndex < myFilesList.size()) {
      if (myTextPainter == null) {
        myTextPainter =
            PrintManager.initTextPainter((PsiFile) myFilesList.get(myFileIndex), myProject);
      }
      if (myTextPainter != null) {
        ((TextPainter) myTextPainter).setProgress(myProgress);
        int ret = 0;
        try {
          ret = myTextPainter.print(g, pageFormat, pageIndex - myStartPageIndex);
        } catch (ProcessCanceledException e) {
        }

        if (myProgress.isCanceled()) {
          return Printable.NO_SUCH_PAGE;
        }
        if (ret == Printable.PAGE_EXISTS) {
          return Printable.PAGE_EXISTS;
        }
        myTextPainter = null;
        myStartPageIndex = pageIndex;
      }
      myFileIndex++;
    }
    return Printable.NO_SUCH_PAGE;
  }
 static void log(
     ProgressIndicator progressIndicator,
     TextEditorHighlightingPass pass,
     @NonNls @NotNull 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);
     }
   }
 }
 private void updateProgress(final ProgressIndicator indicator, final String text) {
   LOG.info("PAX output: " + text.replace("\n", ""));
   Matcher matcher = errorMessagePattern.matcher(text.trim());
   // save error message for later..
   if (matcher.matches()) {
     String message = matcher.group(1).trim();
     if (!StringUtil.isEmpty(message)
         && !message.contains("--log=debug")
         && !message.contains("Oops")) {
       myErrorMessage = (myErrorMessage != null ? myErrorMessage : "") + message + "\n";
     }
   }
   if (indicator != null) {
     if (indicator.isCanceled()) {
       if (!myIsCancelled) {
         ApplicationManager.getApplication()
             .invokeLater(
                 new Runnable() {
                   public void run() {
                     cancel();
                   }
                 });
       }
     }
     indicator.setText2(text);
   }
 }
  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 =
        () -> {
          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,
                      () ->
                          PostprocessReformattingAspect.getInstance(project)
                              .postponeFormattingInside(
                                  () -> {
                                    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);
  }
  public void findUsages(
      @NotNull final Processor<UsageInfo> consumer,
      @NotNull FindUsagesProcessPresentation processPresentation) {
    try {
      myProgress.setIndeterminate(true);
      myProgress.setText("Scanning indexed files...");
      final Set<PsiFile> filesForFastWordSearch =
          ApplicationManager.getApplication()
              .runReadAction(
                  new Computable<Set<PsiFile>>() {
                    @Override
                    public Set<PsiFile> compute() {
                      return getFilesForFastWordSearch();
                    }
                  });
      myProgress.setIndeterminate(false);

      searchInFiles(filesForFastWordSearch, processPresentation, consumer);

      myProgress.setIndeterminate(true);
      myProgress.setText("Scanning non-indexed files...");
      boolean skipIndexed = canRelyOnIndices();
      final Collection<PsiFile> otherFiles =
          collectFilesInScope(filesForFastWordSearch, skipIndexed);
      myProgress.setIndeterminate(false);

      long start = System.currentTimeMillis();
      searchInFiles(otherFiles, processPresentation, consumer);
      if (skipIndexed && otherFiles.size() > 1000) {
        logStats(otherFiles, start);
      }
    } catch (ProcessCanceledException e) {
      // fine
    }

    if (!myLargeFiles.isEmpty()) {
      processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
    }

    if (!myProgress.isCanceled()) {
      myProgress.setText(FindBundle.message("find.progress.search.completed"));
    }
  }
  @Override
  public void run(@NotNull final ProgressIndicator indicator) {
    myIndicator = indicator;

    final ProjectManager projectManager = ProjectManager.getInstance();
    projectManager.addProjectManagerListener(myProject, myCloseListener = new CloseListener());

    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();
        projectManager.removeProjectManagerListener(myProject, myCloseListener);
      } finally {
        if (acquired) {
          semaphore.release();
        }
      }
    }
  }
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      indicator.setIndeterminate(true);
      synchronized (myLock) {
        final long startTime = System.currentTimeMillis();

        final long timeout = 10000;

        while (!myFinished && !myCanceled && !indicator.isCanceled()) {
          long wastedTime = System.currentTimeMillis() - startTime;
          if (wastedTime >= timeout) {
            break;
          }
          try {
            myLock.wait(Math.min(timeout - wastedTime, 500));
          } catch (InterruptedException e) {
            break;
          }
        }
      }
    }
  // error tree view initialization must be invoked from event dispatch thread
  private void openMessageView() {
    if (isHeadlessMode()) {
      return;
    }
    if (myIndicator.isCanceled()) {
      return;
    }

    final JComponent component;
    synchronized (myMessageViewLock) {
      if (myErrorTreeView != null) {
        return;
      }
      myErrorTreeView = new CompilerErrorTreeView(myProject, myRestartWork);

      myErrorTreeView.setProcessController(
          new NewErrorTreeViewPanel.ProcessController() {
            @Override
            public void stopProcess() {
              cancel();
            }

            @Override
            public boolean isProcessStopped() {
              return !myIndicator.isRunning();
            }
          });
      component = myErrorTreeView.getComponent();
    }

    final MessageView messageView = MessageView.SERVICE.getInstance(myProject);
    final Content content =
        ContentFactory.SERVICE.getInstance().createContent(component, myContentName, true);
    CONTENT_ID_KEY.set(content, myContentId);
    SESSION_ID_KEY.set(content, mySessionId);
    messageView.getContentManager().addContent(content);
    myCloseListener.setContent(content, messageView.getContentManager());
    removeAllContents(myProject, content);
    messageView.getContentManager().setSelectedContent(content);
  }
            @Override
            public boolean process(Pair<HighlightInfo, ProgressIndicator> pair) {
              ApplicationManager.getApplication().assertIsDispatchThread();
              ProgressIndicator indicator = pair.getSecond();
              if (indicator.isCanceled()) {
                return false;
              }
              HighlightInfo info = pair.getFirst();
              final EditorColorsScheme colorsScheme = getColorsScheme();
              UpdateHighlightersUtil.addHighlighterToEditorIncrementally(
                  myProject,
                  myDocument,
                  myFile,
                  myStartOffset,
                  myEndOffset,
                  info,
                  colorsScheme,
                  Pass.UPDATE_ALL,
                  ranges2markersCache);

              return true;
            }
Exemple #10
0
  @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());
    }
  }
 @Override
 public final boolean isCanceled() {
   return super.isCanceled() || myOriginalStarted && myOriginal.isCanceled();
 }
  @Override
  public void startRunInjectors(@NotNull final Document hostDocument, final boolean synchronously) {
    if (myProject.isDisposed()) return;
    if (!synchronously && ApplicationManager.getApplication().isWriteAccessAllowed()) return;
    // use cached to avoid recreate PSI in alien project
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final PsiFile hostPsiFile = documentManager.getCachedPsiFile(hostDocument);
    if (hostPsiFile == null) return;

    final ConcurrentList<DocumentWindow> injected =
        InjectedLanguageUtil.getCachedInjectedDocuments(hostPsiFile);
    if (injected.isEmpty()) return;

    if (myProgress.isCanceled()) {
      myProgress = new DaemonProgressIndicator();
    }
    final Set<DocumentWindow> newDocuments = Collections.synchronizedSet(new THashSet<>());
    final Processor<DocumentWindow> commitProcessor =
        documentWindow -> {
          if (myProject.isDisposed()) return false;
          ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
          if (indicator != null && indicator.isCanceled()) return false;
          if (documentManager.isUncommited(hostDocument) || !hostPsiFile.isValid())
            return false; // will be committed later

          // it is here where the reparse happens and old file contents replaced
          InjectedLanguageUtil.enumerate(
              documentWindow,
              hostPsiFile,
              (injectedPsi, places) -> {
                DocumentWindow newDocument =
                    (DocumentWindow) injectedPsi.getViewProvider().getDocument();
                if (newDocument != null) {
                  PsiDocumentManagerBase.checkConsistency(injectedPsi, newDocument);
                  newDocuments.add(newDocument);
                }
              });
          return true;
        };
    final Runnable commitInjectionsRunnable =
        () -> {
          if (myProgress.isCanceled()) return;
          JobLauncher.getInstance()
              .invokeConcurrentlyUnderProgress(
                  new ArrayList<>(injected), myProgress, true, commitProcessor);

          synchronized (ourInjectionPsiLock) {
            injected.clear();
            injected.addAll(newDocuments);
          }
        };

    if (synchronously) {
      if (Thread.holdsLock(PsiLock.LOCK)) {
        // hack for the case when docCommit was called from within PSI modification, e.g. in
        // formatter.
        // we can't spawn threads to do injections there, otherwise a deadlock is imminent
        ContainerUtil.process(new ArrayList<>(injected), commitProcessor);
      } else {
        commitInjectionsRunnable.run();
      }
    } else {
      JobLauncher.getInstance()
          .submitToJobThread(
              () ->
                  ApplicationManagerEx.getApplicationEx()
                      .tryRunReadAction(commitInjectionsRunnable),
              null);
    }
  }
 public void ensureFinished() {
   if (myProcessIndicator != null && !myProcessIndicator.isCanceled()) {
     finish();
   }
 }
 public boolean isCancelled() {
   return myProgressIndicator != null && myProgressIndicator.isCanceled();
 }
 @CalledInAwt
 private static void finish(@NotNull Runnable result, @NotNull ProgressIndicator indicator) {
   if (indicator.isCanceled()) return;
   result.run();
   indicator.stop();
 }
Exemple #16
0
 public void cancel() {
   if (!myIndicator.isCanceled()) {
     myIndicator.cancel();
   }
 }
  // returns finish commit Runnable (to be invoked later in EDT), or null on failure
  private Runnable commitUnderProgress(
      @NotNull final Document document,
      @NotNull final Project project,
      final PsiFile excludeFile,
      @NotNull final ProgressIndicator indicator,
      final boolean synchronously,
      @NotNull final Object reason) {
    final List<Processor<Document>> finishRunnables = new SmartList<Processor<Document>>();
    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;
            final PsiDocumentManagerImpl documentManager =
                (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project);
            final FileViewProvider viewProvider = documentManager.getCachedViewProvider(document);
            if (viewProvider == null) return;
            final List<PsiFile> psiFiles = viewProvider.getAllFiles();
            for (PsiFile file : psiFiles) {
              if (file.isValid() && file != excludeFile) {
                Processor<Document> finishRunnable =
                    doCommit(document, file, indicator, synchronously, documentManager);
                if (finishRunnable != null) {
                  finishRunnables.add(finishRunnable);
                }
              }
            }
          }
        };
    if (synchronously) {
      ApplicationManager.getApplication().assertWriteAccessAllowed();
      runnable.run();
    } else {
      if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(runnable)) {
        log(
            "Could not start readaction",
            document,
            synchronously,
            ApplicationManager.getApplication().isReadAccessAllowed(),
            Thread.currentThread());
        return null;
      }
    }

    boolean canceled = indicator.isCanceled();
    if (synchronously) {
      assert !canceled;
    }
    if (canceled || !indicator.isRunning()) {
      assert !synchronously;
      return null;
    }
    if (!synchronously
        && !changeCommitStage(
            document,
            CommitStage.QUEUED_TO_COMMIT,
            CommitStage.WAITING_FOR_PSI_APPLY,
            synchronously)) {
      return null;
    }

    Runnable finishRunnable =
        new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;

            PsiDocumentManagerImpl documentManager =
                (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project);

            CommitStage stage = getCommitStage(document);
            log("Finish", document, synchronously, project);
            if (stage
                != (synchronously
                    ? CommitStage.ABOUT_TO_BE_SYNC_COMMITTED
                    : CommitStage.WAITING_FOR_PSI_APPLY)) {
              return; // there must be a synchronous commit sneaked in between queued commit and
                      // finish commit, or just document changed meanwhile
            }

            boolean success = false;
            try {
              success =
                  documentManager.finishCommit(document, finishRunnables, synchronously, reason);
              log(
                  "Finished",
                  document,
                  synchronously,
                  success,
                  Arrays.asList(documentManager.getUncommittedDocuments()));
              if (synchronously) {
                assert success;
              }
            } finally {
              if (success) {
                success =
                    synchronously
                        || changeCommitStage(
                            document,
                            CommitStage.WAITING_FOR_PSI_APPLY,
                            CommitStage.COMMITTED,
                            false);
              }
            }
            List<Document> unc = Arrays.asList(documentManager.getUncommittedDocuments());
            log("after call finish commit", document, synchronously, unc, success);
            if (synchronously || success) {
              assert !unc.contains(document) : unc;
            }
            if (!success) {
              // add document back to the queue
              boolean addedBack = queueCommit(project, document, "Re-added back");
              assert addedBack;
            }
          }
        };
    return finishRunnable;
  }
  @Override
  public void run() {
    threadFinished = false;
    while (!isDisposed) {
      try {
        boolean success = false;
        Document document = null;
        Project project = null;
        ProgressIndicator indicator = null;
        try {
          CommitTask task;
          synchronized (documentsToCommit) {
            if (!myEnabled || documentsToCommit.isEmpty()) {
              documentsToCommit.wait();
              continue;
            }
            task = documentsToCommit.pullFirst();
            document = task.document;
            indicator = task.indicator;
            project = task.project;

            log("Pulled", document, false, indicator);

            CommitStage commitStage = getCommitStage(document);
            Document[] uncommitted = null;
            if (commitStage != CommitStage.QUEUED_TO_COMMIT
                || project.isDisposed()
                || !ArrayUtil.contains(
                    document,
                    uncommitted =
                        PsiDocumentManager.getInstance(project).getUncommittedDocuments())) {
              List<Document> documents = uncommitted == null ? null : Arrays.asList(uncommitted);
              log("Abandon and proceeding to next", document, false, commitStage, documents);
              continue;
            }
            if (indicator.isRunning()) {
              useIndicator(indicator);
              document.putUserData(COMMIT_PROGRESS, indicator);
            } else {
              success = true; // document has been marked as removed, e.g. by synchronous commit
            }
          }

          Runnable finishRunnable = null;
          if (!success && !indicator.isCanceled()) {
            try {
              finishRunnable = commit(document, project, null, indicator, false, task.reason);
              success = finishRunnable != null;
              log("DCT.commit returned", document, false, finishRunnable, indicator);
            } finally {
              document.putUserData(COMMIT_PROGRESS, null);
            }
          }

          synchronized (documentsToCommit) {
            if (indicator.isCanceled()) {
              success = false;
            }
            if (success) {
              assert !ApplicationManager.getApplication().isDispatchThread();
              UIUtil.invokeLaterIfNeeded(finishRunnable);
              log(
                  "Invoked later finishRunnable",
                  document,
                  false,
                  success,
                  finishRunnable,
                  indicator);
            }
          }
        } catch (ProcessCanceledException e) {
          cancel(e); // leave queue unchanged
          log("PCE", document, false, e);
          success = false;
        } catch (InterruptedException e) {
          // app must be closing
          int i = 0;
          log("IE", document, false, e);
          cancel(e);
        } catch (Throwable e) {
          LOG.error(e);
          cancel(e);
        }
        synchronized (documentsToCommit) {
          if (!success && indicator.isRunning()) { // running means sync commit has not intervened
            // reset status for queue back successfully
            changeCommitStage(
                document, CommitStage.WAITING_FOR_PSI_APPLY, CommitStage.QUEUED_TO_COMMIT, false);
            changeCommitStage(document, CommitStage.COMMITTED, CommitStage.QUEUED_TO_COMMIT, false);
            doQueue(document, project, CommitStage.QUEUED_TO_COMMIT, "re-added on failure");
          }
        }
      } catch (Throwable e) {
        e.printStackTrace();
        // LOG.error(e);
      }
    }
    threadFinished = true;
    // ping the thread waiting for close
    wakeUpQueue();
    log("Good bye", null, false);
  }
  public void findUsages(final Set<PsiFile> searchIn, final Set<PsiFile> searchFor) {
    cancelCurrentFindRequest();

    myAlarm.cancelAllRequests();
    myAlarm.addRequest(
        () ->
            ApplicationManager.getApplication()
                .executeOnPooledThread(
                    () -> {
                      final ProgressIndicator progress =
                          new PanelProgressIndicator(component -> setToComponent(component));
                      myCurrentProgress = progress;
                      ProgressManager.getInstance()
                          .runProcess(
                              () -> {
                                ApplicationManager.getApplication()
                                    .runReadAction(
                                        () -> {
                                          UsageInfo[] usages = new UsageInfo[0];
                                          Set<PsiFile> elementsToSearch = null;

                                          try {
                                            if (myBuilders.get(0).isBackward()) {
                                              elementsToSearch = searchIn;
                                              usages =
                                                  FindDependencyUtil.findBackwardDependencies(
                                                      myBuilders, searchFor, searchIn);
                                            } else {
                                              elementsToSearch = searchFor;
                                              usages =
                                                  FindDependencyUtil.findDependencies(
                                                      myBuilders, searchIn, searchFor);
                                            }
                                            assert !new HashSet<PsiFile>(elementsToSearch)
                                                .contains(null);
                                          } catch (ProcessCanceledException e) {
                                          } catch (Exception e) {
                                            LOG.error(e);
                                          }

                                          if (!progress.isCanceled()) {
                                            final UsageInfo[] finalUsages = usages;
                                            final PsiElement[] _elementsToSearch =
                                                elementsToSearch != null
                                                    ? PsiUtilCore.toPsiElementArray(
                                                        elementsToSearch)
                                                    : PsiElement.EMPTY_ARRAY;
                                            ApplicationManager.getApplication()
                                                .invokeLater(
                                                    () ->
                                                        showUsages(_elementsToSearch, finalUsages),
                                                    ModalityState.stateForComponent(
                                                        DependenciesUsagesPanel.this));
                                          }
                                        });
                                myCurrentProgress = null;
                              },
                              progress);
                    }),
        300);
  }
 @Override
 public boolean isCanceled() {
   return myIndicator.isCanceled();
 }
 private void cancel() throws IOException {
   if (indicator != null && indicator.isCanceled()) {
     throw new CanceledException();
   }
 }
Exemple #22
0
 public boolean isCanceled() {
   if (super.isCanceled()) return true;
   if (!myOriginalStarted) return false;
   return myOriginal.isCanceled();
 }