Java Code Examples for com.intellij.openapi.progress.ProgressIndicator

The following are top voted examples for showing how to use com.intellij.openapi.progress.ProgressIndicator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: DataWriter.java   Source Code and License 6 votes vote down vote up
public void execute(ClassEntity targetClass) {
        this.targetClass = targetClass;
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setIndeterminate(true);
                long currentTimeMillis = System.currentTimeMillis();
                execute();
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(1.0);
                StringBuffer sb = new StringBuffer();
                sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n");
//                sb.append("generate class : ( "+generateClassList.size()+" )\n");
//                for (String item: generateClassList) {
//                    sb.append("    at "+item+"\n");
//                }
//                sb.append("  \n");
//                NotificationCenter.info(sb.toString());
                Toast.make(project, MessageType.INFO, sb.toString());
            }
        });
    }
 
Example 2
Project: CodeGenerate   File: DataWriter.java   Source Code and License 6 votes vote down vote up
public void execute(ClassEntity targetClass) {
        this.targetClass = targetClass;
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setIndeterminate(true);
                long currentTimeMillis = System.currentTimeMillis();
                execute();
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(1.0);
                StringBuffer sb = new StringBuffer();
                sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n");
//                sb.append("generate class : ( "+generateClassList.size()+" )\n");
//                for (String item: generateClassList) {
//                    sb.append("    at "+item+"\n");
//                }
//                sb.append("  \n");
//                NotificationCenter.info(sb.toString());
                Toast.make(project, MessageType.INFO, sb.toString());
            }
        });
    }
 
Example 3
Project: logviewer   File: LogView.java   Source Code and License 6 votes vote down vote up
/**
 * Refreshes the log console in background
 */
void refresh(final String task) {
    SingleTaskBackgroundExecutor.executeIfPossible(myProject, new SingleTaskBackgroundExecutor.BackgroundTask() {
        @Override
        public void run(ProgressIndicator progressIndicator) {
            try {
                UIUtil.invokeAndWaitIfNeeded((Runnable) () -> {
                    progressIndicator.setFraction(0);
                    doFilter(progressIndicator);
                });
            } catch (Throwable ex) {
                debug("Exception " + ex.getMessage());
            }
        }

        @Override
        public String getTaskName() {
            return task;
        }
    });
}
 
Example 4
Project: logviewer   File: LogView.java   Source Code and License 6 votes vote down vote up
/**
 * Filters the console
 */
private synchronized void doFilter(ProgressIndicator progressIndicator) {
    final ConsoleView console = getConsole();
    String allLInes = getOriginalDocument().toString();
    final String[] lines = allLInes.split("\n");
    if (console != null) {
        console.clear();
    }
    myLogFilterModel.processingStarted();
    int size = lines.length;
    float current = 0;
    for (String line : lines) {
        printMessageToConsole(line);
        current++;
        progressIndicator.setFraction(current / size);
    }
    if (console != null) {
        ((ConsoleViewImpl) console).requestScrollingToEnd();
    }
}
 
Example 5
Project: StAnalysisRunner   File: AnalysisTask.java   Source Code and License 6 votes vote down vote up
private void runAnalysis(@NotNull final ProgressIndicator progressIndicator) throws Exception {
    String analysisOutput = getAnalysisOutput(progressIndicator);
    if (!analysisOutput.startsWith("Error") && !analysisOutput.startsWith("FAILURE")) {
        if (Pattern.compile("Overall: PASSED").matcher(analysisOutput).find()) {
            showInfoNotification("Overall: PASSED!");
            requestIdeFocus();
        } else if (!Pattern.compile("Overall: FAILED").matcher(analysisOutput).find()) {
            showErrorNotification("Can't detect analysis result. Try to run it manually.");
        } else {
            Pattern errorsCountPattern = Pattern.compile("Overall: FAILED \\((.+)\\)\u001b");
            Pattern urlPattern = Pattern.compile("file:.+full_report.html");
            Matcher errorsCountMatcher = errorsCountPattern.matcher(analysisOutput);
            Matcher urlMatcher = urlPattern.matcher(analysisOutput);
            if (errorsCountMatcher.find() && urlMatcher.find()) {
                showErrorNotification(String.format("Analysis failed: %s", errorsCountMatcher.group(1)));
                (new OpenUrlHyperlinkInfo(urlMatcher.group())).navigate(project);
            } else {
                showErrorNotification("Can't detect analysis result. Try to run it manually.");
            }
        }
    } else {
        showErrorNotification(analysisOutput);
    }
}
 
Example 6
Project: StAnalysisRunner   File: AnalysisTask.java   Source Code and License 6 votes vote down vote up
@NotNull
private String getAnalysisOutput(@NotNull final ProgressIndicator progressIndicator) throws Exception {
    final List<String> gradlewCommand = System.getProperty("os.name").startsWith("Windows")
            ? Arrays.asList("cmd", "/c", "gradlew.bat", "staticAnalys")
            : Arrays.asList("./gradlew", "staticAnalys");
    gradlewProcess = new ProcessBuilder(gradlewCommand)
            .directory(new File(project.getBasePath()))
            .redirectErrorStream(true)
            .start();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gradlewProcess.getInputStream()));
    StringBuilder analysisOutputBuilder = new StringBuilder();

    String outputLine;
    while ((outputLine = bufferedReader.readLine()) != null) {
        progressIndicator.setText2(outputLine);
        progressIndicator.checkCanceled();
        analysisOutputBuilder.append(outputLine);
        analysisOutputBuilder.append('\n');
    }

    return analysisOutputBuilder.toString();
}
 
Example 7
Project: jfrog-idea-plugin   File: ScanManager.java   Source Code and License 6 votes vote down vote up
/**
 * Scan and update dependency components.
 */
private void scanAndUpdate(boolean quickScan, ProgressIndicator indicator, @Nullable Collection<DataNode<LibraryDependencyData>> libraryDependencies) {
    // Don't scan if Xray is not configured
    if (!GlobalSettings.getInstance().isCredentialsSet()) {
        Utils.notify(logger, "JFrog Xray scan failed", "Xray server is not configured.", NotificationType.ERROR);
        return;
    }
    // Prevent multiple simultaneous scans
    if (!scanInProgress.compareAndSet(false, true)) {
        if (!quickScan) {
            Utils.notify(logger, "JFrog Xray", "Scan already in progress.", NotificationType.INFORMATION);
        }
        return;
    }
    try {
        // Refresh dependencies -> Collect -> Scan and store to cache -> Update view
        refreshDependencies(getRefreshDependenciesCbk(quickScan, indicator), libraryDependencies);
    } finally {
        scanInProgress.set(false);
    }
}
 
Example 8
Project: jfrog-idea-plugin   File: ScanManager.java   Source Code and License 6 votes vote down vote up
/**
 * Launch async dependency scan.
 */
public void asyncScanAndUpdateResults(boolean quickScan, @Nullable Collection<DataNode<LibraryDependencyData>> libraryDependencies) {
    Task.Backgroundable scanAndUpdateTask = new Task.Backgroundable(project, "Xray: Scanning for Vulnerabilities...") {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            scanAndUpdate(quickScan, indicator, libraryDependencies);
            indicator.finishNonCancelableSection();
        }
    };
    // The progress manager is only good for foreground threads.
    if (SwingUtilities.isEventDispatchThread()) {
        ProgressManager.getInstance().run(scanAndUpdateTask);
    } else {
        // Run the scan task when the thread is in the foreground.
        SwingUtilities.invokeLater(() -> ProgressManager.getInstance().run(scanAndUpdateTask));
    }
}
 
Example 9
Project: AndroidSourceViewer   File: GlobalSearchAction.java   Source Code and License 6 votes vote down vote up
@Override
public void OnResult(String result) {
    int extPos = result.lastIndexOf('/');
    if (extPos < 0 && extPos != result.length() - 1) {
        return;
    }
    String fileName = result.substring(extPos + 1);
    String title = "Download:" + fileName;
    File downloadFile = new File(Constant.CACHE_PATH + "search/" + fileName);
    ProgressManager.getInstance().run(new Task.Backgroundable(project, title) {
        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {
            try {
                DownloadUtil.downloadAtomically(null, result, downloadFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (downloadFile.exists()) {
                Utils.openFileInPanel(downloadFile.getPath(), project);
            }
        }
    });

}
 
Example 10
Project: SearchResourcePlugin   File: SearchResultItemProvider.java   Source Code and License 6 votes vote down vote up
@Override
public boolean filterElements(@NotNull ChooseByNameBase base, @NotNull String pattern, boolean everywhere, @NotNull ProgressIndicator indicator, @NotNull Processor<Object> consumer) {
    Collection<SearchResultElement> elements = getAllFilterItems();

    if (elements != null) {
        for (SearchResultElement element : elements) {
            String value = element.getValue();

            if (value == null) {
                return false;
            }

            if (value.toLowerCase().contains(pattern.toLowerCase()) && !consumer.process(element)) {
                return false;
            }
        }
    }

    return false;
}
 
Example 11
Project: educational-plugin   File: EduNextRecommendationCheckListener.java   Source Code and License 6 votes vote down vote up
@Override
public void afterCheck(@NotNull Project project, @NotNull Task task) {
  Course course = task.getLesson().getCourse();
  if (!(course instanceof RemoteCourse && course.isAdaptive())) {
    return;
  }
  if (myStatusBeforeCheck == StudyStatus.Solved) {
    return;
  }
  StudyStatus statusAfterCheck = task.getStatus();
  if (statusAfterCheck != StudyStatus.Solved) {
    return;
  }
  ProgressManager.getInstance().run(new com.intellij.openapi.progress.Task.Backgroundable(project, EduAdaptiveStepicConnector.LOADING_NEXT_RECOMMENDATION, false,
                                                                                          PerformInBackgroundOption.DEAF) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      indicator.setIndeterminate(true);
      EduAdaptiveStepicConnector.addNextRecommendedTask(project, task.getLesson(), indicator, EduAdaptiveStepicConnector.NEXT_RECOMMENDATION_REACTION);
    }
  });
}
 
Example 12
Project: educational-plugin   File: StepicAdaptiveReactionsPanel.java   Source Code and License 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
  if (e.getClickCount() == 1 && isEnabled()) {
    final com.jetbrains.edu.learning.courseFormat.tasks.Task task = StudyUtils.getCurrentTask(myProject);
    if (task != null && task.getStatus() != StudyStatus.Solved) {
      final ProgressIndicatorBase progress = new ProgressIndicatorBase();
      progress.setText(EduAdaptiveStepicConnector.LOADING_NEXT_RECOMMENDATION);
      ProgressManager.getInstance().run(new Task.Backgroundable(myProject,
                                                                EduAdaptiveStepicConnector.LOADING_NEXT_RECOMMENDATION) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          StepicAdaptiveReactionsPanel.this.setEnabledRecursive(false);
          ApplicationManager.getApplication().invokeLater(()->setBackground(UIUtil.getLabelBackground()));
          EduAdaptiveStepicConnector.addNextRecommendedTask(StepicAdaptiveReactionsPanel.this.myProject, task.getLesson(), indicator,
                                                            myReaction);
          StepicAdaptiveReactionsPanel.this.setEnabledRecursive(true);
        }
      });
    }
  }
}
 
Example 13
Project: educational-plugin   File: RemoteCourse.java   Source Code and License 6 votes vote down vote up
public boolean isUpToDate() {
  if (id == 0) return true;
  if (!EduNames.STUDY.equals(courseMode)) return true;

  ProgressManager.getInstance().runProcessWithProgressAsynchronously(new Backgroundable(null, "Updating Course") {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      final Date date = EduStepicConnector.getCourseUpdateDate(id);
      if (date == null) return;
      if (date.after(myUpdateDate)) {
        isUpToDate = false;
      }
      for (Lesson lesson : lessons) {
        if (!lesson.isUpToDate()) {
          isUpToDate = false;
        }
      }
    }
  }, new EmptyProgressIndicator());

  return isUpToDate;
}
 
Example 14
Project: educational-plugin   File: CCGetCourseFromStepic.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (view == null || project == null) {
    return;
  }
  final String courseId = Messages.showInputDialog("Please, enter course id", "Get Course From Stepik", null);
  if (StringUtil.isNotEmpty(courseId)) {
    ProgressManager.getInstance().run(new Task.Modal(project, "Creating Course", true) {
      @Override
      public void run(@NotNull final ProgressIndicator indicator) {
        createCourse(project, courseId);
      }
    });
  }
}
 
Example 15
Project: Android-Resource-Usage-Count   File: FindUsageUtils.java   Source Code and License 6 votes vote down vote up
private static void dropResolveCacheRegularly(ProgressIndicator indicator, final Project project) {
    if (indicator instanceof ProgressIndicatorEx) {
        ((ProgressIndicatorEx)indicator).addStateDelegate(new ProgressIndicatorBase() {
            volatile long lastCleared = System.currentTimeMillis();

            public void setFraction(double fraction) {
                super.setFraction(fraction);
                long current = System.currentTimeMillis();
                if (current - this.lastCleared >= 500L) {
                    this.lastCleared = current;
                    PsiManager.getInstance(project).dropResolveCaches();
                }

            }
        });
    }

}
 
Example 16
Project: intellij-ce-playground   File: DefaultChooseByNameItemProvider.java   Source Code and License 6 votes vote down vote up
private static void processNamesByPattern(@NotNull final ChooseByNameBase base,
                                          @NotNull final String[] names,
                                          @NotNull final String pattern,
                                          final ProgressIndicator indicator,
                                          @NotNull final Consumer<MatchResult> consumer) {
  final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE);
  Processor<String> processor = new Processor<String>() {
    @Override
    public boolean process(String name) {
      ProgressManager.checkCanceled();
      MatchResult result = matches(base, pattern, matcher, name);
      if (result != null) {
        consumer.consume(result);
      }
      return true;
    }
  };
  if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) {
    throw new ProcessCanceledException();
  }
}
 
Example 17
Project: intellij   File: DelegatingSwitchToHeaderOrSourceProvider.java   Source Code and License 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 18
Project: intellij-ce-playground   File: GitHandlerUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Run handler in the current thread
 *
 * @param handler              a handler to run
 * @param indicator            a progress manager
 * @param setIndeterminateFlag if true handler is configured as indeterminate
 * @param operationName
 */
public static void runInCurrentThread(final GitHandler handler,
                                      final ProgressIndicator indicator,
                                      final boolean setIndeterminateFlag,
                                      @Nullable final String operationName) {
  runInCurrentThread(handler, new Runnable() {
    public void run() {
      if (indicator != null) {
        indicator.setText(operationName == null ? GitBundle.message("git.running", handler.printableCommandLine()) : operationName);
        indicator.setText2("");
        if (setIndeterminateFlag) {
          indicator.setIndeterminate(true);
        }
      }
    }
  });
}
 
Example 19
Project: intellij-ce-playground   File: VcsLogRefresherImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
  LOG.debug("Refresh task started");
  indicator.setIndeterminate(true);
  DataPack dataPack = myCurrentDataPack;
  while (true) {
    List<RefreshRequest> requests = mySingleTaskController.popRequests();
    Collection<VirtualFile> rootsToRefresh = getRootsToRefresh(requests);
    LOG.debug("Requests: " + requests + ". roots to refresh: " + rootsToRefresh);
    if (rootsToRefresh.isEmpty()) {
      mySingleTaskController.taskCompleted(dataPack);
      break;
    }
    dataPack = doRefresh(rootsToRefresh);
  }
}
 
Example 20
Project: intellij-ce-playground   File: TreeUiTest.java   Source Code and License 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 21
Project: intellij-ce-playground   File: GroovyMarkerTypes.java   Source Code and License 6 votes vote down vote up
@Override
public void run(@NotNull final ProgressIndicator indicator) {
  super.run(indicator);
  for (PsiMethod method : PsiImplUtil.getMethodOrReflectedMethods(myMethod)) {
    OverridingMethodsSearch.search(method, true).forEach(
      new CommonProcessors.CollectProcessor<PsiMethod>() {
        @Override
        public boolean process(PsiMethod psiMethod) {
          if (!updateComponent(com.intellij.psi.impl.PsiImplUtil.handleMirror(psiMethod), myRenderer.getComparator())) {
            indicator.cancel();
          }
          indicator.checkCanceled();
          return true;
        }
      });
  }
}
 
Example 22
Project: intellij-ce-playground   File: SvnLogUtil.java   Source Code and License 6 votes vote down vote up
@NotNull
private LogEntryConsumer createLogHandler(final SVNRevision fromIncluding,
                                             final SVNRevision toIncluding,
                                             final boolean includingYoungest,
                                             final boolean includeOldest, final List<CommittedChangeList> result) {
  return new LogEntryConsumer() {
    @Override
    public void consume(LogEntry logEntry) {
      if (myProject.isDisposed()) throw new ProcessCanceledException();
      final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
      if (progress != null) {
        progress.setText2(SvnBundle.message("progress.text2.processing.revision", logEntry.getRevision()));
        progress.checkCanceled();
      }
      if ((!includingYoungest) && (logEntry.getRevision() == fromIncluding.getNumber())) {
        return;
      }
      if ((!includeOldest) && (logEntry.getRevision() == toIncluding.getNumber())) {
        return;
      }
      result.add(new SvnChangeList(myVcs, myLocation, logEntry, myRepositoryRoot.toString()));
    }
  };
}
 
Example 23
Project: intellij-ce-playground   File: InjectedGeneralHighlightingPass.java   Source Code and License 6 votes vote down vote up
private void runHighlightVisitorsForInjected(@NotNull PsiFile injectedPsi,
                                             @NotNull final HighlightInfoHolder holder,
                                             @NotNull final ProgressIndicator progress) {
  HighlightVisitor[] filtered = getHighlightVisitors(injectedPsi);
  try {
    final List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(injectedPsi, 0, injectedPsi.getTextLength());
    for (final HighlightVisitor visitor : filtered) {
      visitor.analyze(injectedPsi, true, holder, new Runnable() {
        @Override
        public void run() {
          for (PsiElement element : elements) {
            progress.checkCanceled();
            visitor.visit(element);
          }
        }
      });
    }
  }
  finally {
    incVisitorUsageCount(-1);
  }
}
 
Example 24
Project: intellij-ce-playground   File: FileHistoryPanelImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
  final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider();
  if (provider == null) return;
  final RepositoryLocation changedRepositoryPath = myRevision.getChangedRepositoryPath();
  if (changedRepositoryPath == null) return;
  final VcsVirtualFile vf =
    new VcsVirtualFile(changedRepositoryPath.toPresentableString(), myRevision.getRevision(), VcsFileSystem.getInstance());
  try {
    myList = AbstractVcsHelperImpl.getRemoteList(myVcs, myRevision.getRevisionNumber(), vf);
    //myList = provider.getOneList(vf, myRevision.getRevisionNumber());
  }
  catch (VcsException e1) {
    myException = e1;
  }
}
 
Example 25
Project: intellij-ce-playground   File: TreeState.java   Source Code and License 6 votes vote down vote up
public void applyTo(final JTree tree, final DefaultMutableTreeNode node) {
  final TreeFacade facade = getFacade(tree);
  ActionCallback callback = facade.getInitialized().doWhenDone(new TreeRunnable("TreeState.applyTo: on done facade init") {
    @Override
    public void perform() {
      facade.batch(new Progressive() {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          applyExpanded(facade, node, indicator);
        }
      });
    }
  });
  if (tree.getSelectionCount() == 0) {
    callback.doWhenDone(new TreeRunnable("TreeState.applyTo: on done") {
      @Override
      public void perform() {
        applySelected(tree, node);
      }
    });
  }
}
 
Example 26
Project: intellij-ce-playground   File: AbstractTreeClassChooserDialog.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getElementsByName(String name, FindSymbolParameters parameters, @NotNull ProgressIndicator canceled) {
  String patternName = parameters.getLocalPatternName();
  List<T> classes = myTreeClassChooserDialog.getClassesByName(
    name, parameters.isSearchInLibraries(), patternName, myTreeClassChooserDialog.getScope()
  );
  if (classes.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY;
  if (classes.size() == 1) {
    return isAccepted(classes.get(0)) ? ArrayUtil.toObjectArray(classes) : ArrayUtil.EMPTY_OBJECT_ARRAY;
  }
  Set<String> qNames = ContainerUtil.newHashSet();
  List<T> list = new ArrayList<T>(classes.size());
  for (T aClass : classes) {
    if (qNames.add(getFullName(aClass)) && isAccepted(aClass)) {
      list.add(aClass);
    }
  }
  return ArrayUtil.toObjectArray(list);
}
 
Example 27
Project: intellij-ce-playground   File: TaskItemProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Download next page of tasks from server(s). If filtering settings changed, download them all over again, but always increment
 * upper limit to make progress. If server supports search on its side, it should not affect access time much, because only a few
 * tasks will be returned anyway.
 */
private List<Task> fetchFromServer(String pattern, boolean everywhere, ProgressIndicator cancelled) {
  int offset, limit;
  // pattern changed -> reset pagination
  if (!myOldPattern.equals(pattern)) {
    myCurrentOffset = offset = 0;
    limit = GotoTaskAction.PAGE_SIZE;
  }
  // include closed tasks -> download all previous + closed, so no one is missing
  else if (myOldEverywhere != everywhere) {
    offset = 0;
    myCurrentOffset = limit = myCurrentOffset + GotoTaskAction.PAGE_SIZE;
  }
  // normal pagination step
  else {
    offset = myCurrentOffset;
    limit = GotoTaskAction.PAGE_SIZE;
    myCurrentOffset += GotoTaskAction.PAGE_SIZE;
  }
  List<Task> tasks = TaskSearchSupport.getRepositoriesTasks(TaskManager.getManager(myProject),
                                                            pattern, offset, limit, true, everywhere, cancelled);
  myOldEverywhere = everywhere;
  myOldPattern = pattern;
  return tasks;
}
 
Example 28
Project: intellij-ce-playground   File: HgAddCommand.java   Source Code and License 6 votes vote down vote up
public void addWithProgress(final Collection<VirtualFile> files) {
  if (files.size() >= HgUtil.MANY_FILES) {
    new Task.Backgroundable(myProject, "Adding files to Mercurial", true) {
      @Override public void run(@NotNull ProgressIndicator indicator) {
        indicator.setIndeterminate(false);
        execute(files, indicator);
      }
    }.queue();
  } else {
    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
      @Override public void run() {
        execute(files);
      }
    });
  }
}
 
Example 29
Project: intellij-ce-playground   File: SpellCheckerDictionaryGenerator.java   Source Code and License 6 votes vote down vote up
public void generate() {
  ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
    @Override
    public void run() {
      ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
      // let's do result a bit more predictable

      // ruby dictionary
      generate(myDefaultDictName, progressIndicator);

      // other gem-related dictionaries in alphabet order
      final List<String> dictionaries = new ArrayList<String>(myDict2FolderMap.keySet());
      Collections.sort(dictionaries);

      for (String dict : dictionaries) {
        if (myDefaultDictName.equals(dict)) {
          continue;
        }
        generate(dict, progressIndicator);
      }
    }
  }, "Generating Dictionaries", false, myProject);
}
 
Example 30
Project: intellij-ce-playground   File: AndroidDbUtil.java   Source Code and License 6 votes vote down vote up
private static boolean recreateRemoteFile(IDevice device,
                                          String packageName,
                                          String remotePath,
                                          AndroidDbErrorReporter errorReporter,
                                          ProgressIndicator progressIndicator) throws Exception {
  MyShellOutputReceiver outputReceiver = new MyShellOutputReceiver(progressIndicator, device);
  device.executeShellCommand("run-as " + packageName + " rm " + remotePath,
                             outputReceiver, DB_COPYING_TIMEOUT_SEC, TimeUnit.SECONDS);
  String output = outputReceiver.getOutput();

  if (!output.isEmpty() && !output.startsWith("rm failed")) {
    errorReporter.reportError(output);
    return false;
  }
  outputReceiver = new MyShellOutputReceiver(progressIndicator, device);
  device.executeShellCommand("run-as " + packageName + " touch " + remotePath,
                             outputReceiver, DB_COPYING_TIMEOUT_SEC, TimeUnit.SECONDS);
  output = outputReceiver.getOutput();

  if (!output.isEmpty()) {
    errorReporter.reportError(output);
    return false;
  }
  return true;
}
 
Example 31
Project: intellij-ce-playground   File: CreateExternalAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final ActionExecuteHelper helper = new ActionExecuteHelper();
  checkState(e, helper);
  if (! helper.isOk()) return;

  final DataContext dc = e.getDataContext();
  final Project project = CommonDataKeys.PROJECT.getData(dc);
  final VirtualFile vf = CommonDataKeys.VIRTUAL_FILE.getData(dc);

  //1 select target
  final SelectCreateExternalTargetDialog dialog = new SelectCreateExternalTargetDialog(project, vf);
  dialog.show();
  if (DialogWrapper.OK_EXIT_CODE != dialog.getExitCode()) return;

  final String url = dialog.getSelectedURL();
  final boolean checkout = dialog.isCheckout();
  final String target = dialog.getLocalTarget().trim();

  ProgressManager.getInstance().run(new Task.Backgroundable(project, "Creating External", true, null) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      doInBackground(project, vf, url, checkout, target);
    }
  });
}
 
Example 32
Project: intellij-ce-playground   File: SdkComponentSource.java   Source Code and License 6 votes vote down vote up
private Collection<UpdatableExternalComponent> getComponents(ProgressIndicator indicator, UpdateSettings settings, boolean remote) {
  List<UpdatableExternalComponent> result = Lists.newArrayList();
  if (!initIfNecessary()) {
    return result;
  }

  Set<String> ignored = settings != null ? Sets.newHashSet(settings.getIgnoredBuildNumbers()) : ImmutableSet.<String>of();
  mySdkState.loadSynchronously(SdkState.DEFAULT_EXPIRATION_PERIOD_MS, true, null, null, null, false);
  boolean previewChannel = settings != null && PREVIEW_CHANNEL.equals(settings.getExternalUpdateChannels().get(getName()));
  for (UpdatablePkgInfo info : mySdkState.getPackages().getConsolidatedPkgs().values()) {
    if (remote) {
      if (info.hasRemote(previewChannel)) {
        IPkgDesc desc = info.getRemote(previewChannel).getPkgDesc();
        if (!ignored.contains(desc.getInstallId())) {
          result.add(new UpdatablePackage(desc));
        }
      }
    }
    else {
      if (info.hasLocal()) {
        result.add(new UpdatablePackage(info.getLocalInfo().getDesc()));
      }
    }
  }
  return result;
}
 
Example 33
Project: reasonml-idea-plugin   File: RmlDocumentListener.java   Source Code and License 5 votes vote down vote up
public RmlDocumentListener(Project project) {
    this.documentEventStream = PublishSubject.create();

    subscriber = this.documentEventStream.
            debounce(150, TimeUnit.MILLISECONDS).
            subscribe(event -> EventQueue.invokeLater(() -> {
                ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
                if (progressIndicator != null && progressIndicator.isCanceled()) {
                    return; // ? not sure about this one
                }

                InferredTypes.queryForSelectedTextEditor(project);
            }));
}
 
Example 34
Project: json2java4idea   File: NewClassAction.java   Source Code and License 5 votes vote down vote up
@Override
public void onOk(@Nonnull NewClassDialog dialog) {
    final PsiDirectory directory = ideView.getOrChooseDirectory();
    if (directory == null) {
        dialog.cancel();
        return;
    }

    try {
        final CommandActionFactory actionFactory = commandActionFactoryProvider.get();
        final JavaConverterFactory converterFactory = javaConverterFactoryProvider.get();
        final NewClassCommandAction command = actionFactory.create(
                dialog.getClassName(),
                dialog.getJson(),
                directory,
                converterFactory.create(settings)
        );

        final ProgressManager progressManager = ProgressManager.getInstance();
        progressManager.runProcessWithProgressSynchronously(() -> {
            final ProgressIndicator indicator = progressManager.getProgressIndicator();
            if (indicator != null) {
                indicator.setIndeterminate(true);
                indicator.setText(bundle.message("progress.text", dialog.getClassName()));
            }

            final RunResult<PsiFile> result = command.execute();
            return result.getResultObject();
        }, bundle.message("progress.title"), false, project);
        dialog.close();
    } catch (RuntimeException e) {
        LOGGER.warn("Unable to create a class", e);
        onError(dialog, e.getCause());
    }
}
 
Example 35
Project: logviewer   File: FileLogDataProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Load logs from the given file
 */
private void loadLogs(final File file) {
    SingleTaskBackgroundExecutor.executeIfPossible(project, new SingleTaskBackgroundExecutor.BackgroundTask() {
        @Override
        public void run(ProgressIndicator progressIndicator) {
            try {
                UIUtil.invokeAndWaitIfNeeded((Runnable) () -> progressIndicator.setFraction(0.10));
                // start your process
                LogFileReader fileReader = LogFileReaderFactory.getFileReader(file);
                UIUtil.invokeAndWaitIfNeeded((Runnable) () -> progressIndicator.setFraction(0.15));
                logData = fileReader.getFileData(logListener);
                UIUtil.invokeAndWaitIfNeeded((Runnable) () -> progressIndicator.setFraction(0.70));
                processes = fileReader.getProcesses();
                UIUtil.invokeAndWaitIfNeeded((Runnable) () -> progressIndicator.setFraction(0.90));
            } catch (Exception ignored) {
            }

        }

        @Override
        public String getTaskName() {
            return "Loading " + file.getName();
        }

        @Override
        public void onTaskComplete() {
            populateLogs();
        }
    });
}
 
Example 36
Project: StAnalysisRunner   File: AnalysisTask.java   Source Code and License 5 votes vote down vote up
@Override
public void run(@NotNull final ProgressIndicator progressIndicator) {
    isRunning = true;
    progressIndicator.setIndeterminate(true);

    try {
        runAnalysis(progressIndicator);
    } catch (final ProcessCanceledException canceledException) {
        progressIndicator.cancel();
    } catch (final Exception exception) {
        showErrorNotification("Exception: " + exception.getMessage());
    }
}
 
Example 37
Project: jfrog-idea-plugin   File: ScanManager.java   Source Code and License 5 votes vote down vote up
private ExternalProjectRefreshCallback getRefreshDependenciesCbk(boolean quickScan, ProgressIndicator indicator) {
    return new ExternalProjectRefreshCallback() {
        @Override
        public void onSuccess(@Nullable DataNode<ProjectData> externalProject) {
            try {
                Components components = collectComponentsToScan(externalProject);
                scanAndCacheArtifacts(components, quickScan, indicator);
                scanResults = updateResultsTree(scanResults);
                setUiLicenses();
                MessageBus messageBus = project.getMessageBus();
                messageBus.syncPublisher(Events.ON_SCAN_COMPONENTS_CHANGE).update();
            } catch (Exception e) {
                Utils.notify(logger, "JFrog Xray scan failed", e, NotificationType.ERROR);
            }
        }

        @Override
        public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) {
            String details;
            String title = "JFrog Xray scan failed";
            if (errorDetails != null) {
                details = errorDetails;
                title += ": " + errorMessage;
            } else {
                details = errorMessage;
            }
            Utils.notify(logger, title, details, NotificationType.ERROR);
        }
    };
}
 
Example 38
Project: AndroidSourceViewer   File: SourceViewerAction.java   Source Code and License 5 votes vote down vote up
@Override
public void OnItemClick(int position, final String version) {
    String title = "Download:" + version + " - " + packageName;
    ProgressManager.getInstance().run(new Task.Backgroundable(project, title) {
        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {
            final ClassEntity entity = new ClassEntity(packageName, version);
            DownloadManager.getInstance().downloadFile(new ClassEntity[]{entity},
                    new File(Constant.CACHE_PATH + entity.getParentPath()),
                    new DownloadResult<File>() {
                        @Override
                        public void onSuccess(List<File> output) {
                            Log.debug("success: length=" + output.size());
                            if (output.isEmpty()) {
                                NotificationUtils.errorNotification("Error: Download " + entity.getPackageName()
                                + " Failure");
                                return;
                            }
                            Utils.openFileInPanel(output.get(0).getPath(), SourceViewerAction.this.project);
                        }

                        @Override
                        public void onFailure(String msg, Throwable throwable) {
                            NotificationUtils.errorNotification("Error:" + msg);
                        }
                    });
            progressIndicator.setFraction(0.5);
        }
    });
}
 
Example 39
Project: hybris-integration-intellij-idea-plugin   File: SearchHybrisDistributionDirectoryTaskModalWindow.java   Source Code and License 5 votes vote down vote up
@Override
public void run(@NotNull final ProgressIndicator indicator) {
    Validate.notNull(indicator);

    final VirtualFileSystemService virtualFileSystemService = ServiceManager.getService(VirtualFileSystemService.class);

    final File hybrisServerShellScriptFile;
    try {
        hybrisServerShellScriptFile = virtualFileSystemService.findFileByNameInDirectory(
            rootProjectDirectory,
            HybrisConstants.HYBRIS_SERVER_SHELL_SCRIPT_NAME,
            new DirectoriesScannerProgressIndicatorUpdaterProcessor(indicator)
        );
    } catch (InterruptedException e) {
        LOG.warn(e);
        return;
    }

    if (null != hybrisServerShellScriptFile
        && null != hybrisServerShellScriptFile.getParentFile()
        && null != hybrisServerShellScriptFile.getParentFile().getParentFile()) {

        this.resultProcessor.process(
            hybrisServerShellScriptFile.getParentFile().getParentFile().getParentFile().getAbsolutePath()
        );
    }
}
 
Example 40
Project: hybris-integration-intellij-idea-plugin   File: SearchModulesRootsTaskModalWindow.java   Source Code and License 5 votes vote down vote up
@Override
public void run(@NotNull final ProgressIndicator indicator) {
    Validate.notNull(indicator);

    this.projectImportParameters.setRootDirectoryAndScanForModules(
        this.rootProjectDirectory,
        new DirectoriesScannerProgressIndicatorUpdaterProcessor(indicator),
        new DirectoriesScannerErrorsProcessor()
    );
}