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

The following examples show how to use com.intellij.openapi.progress.ProgressIndicator#setFraction() . 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: FormattingProgressTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Updates current progress state if necessary.
 *
 * @param state          current state
 * @param completionRate completion rate of the given state. Is assumed to belong to <code>[0; 1]</code> interval
 */
private void update(@Nonnull FormattingStateId state, double completionRate) {
  ProgressIndicator indicator = getIndicator();
  if (indicator == null) {
    return;
  }

  updateTextIfNecessary(state);

  myLastState = state;
  double newFraction = 0;
  for (FormattingStateId prevState : state.getPreviousStates()) {
    newFraction += MAX_PROGRESS_VALUE * prevState.getProgressWeight() / TOTAL_WEIGHT;
  }
  newFraction += completionRate * state.getProgressWeight() / TOTAL_WEIGHT;

  // We don't bother about imprecise floating point arithmetic here because that is enough for progress representation.
  double currentFraction = indicator.getFraction();
  if (newFraction - currentFraction < MAX_PROGRESS_VALUE / 100) {
    return;
  }

  indicator.setFraction(newFraction);
}
 
Example 2
Source File: ActionHandlerAdapter.java    From markdown-image-kit with MIT License 6 votes vote down vote up
@Override
public boolean execute(EventData data) {
    ProgressIndicator indicator = data.getIndicator();
    int size = data.getSize();
    int totalProcessed = 0;

    for (Map.Entry<Document, List<MarkdownImage>> imageEntry : data.getWaitingProcessMap().entrySet()) {
        int totalCount = imageEntry.getValue().size();
        Iterator<MarkdownImage> imageIterator = imageEntry.getValue().iterator();
        while (imageIterator.hasNext()) {
            MarkdownImage markdownImage = imageIterator.next();

            indicator.setText2("Processing " + markdownImage.getImageName());
            indicator.setFraction(((++totalProcessed * 1.0) + data.getIndex() * size) / totalCount * size);

            invoke(data, imageIterator, markdownImage);
        }
    }
    return true;
}
 
Example 3
Source File: InsertToClipboardHandler.java    From markdown-image-kit with MIT License 6 votes vote down vote up
@Override
public boolean execute(EventData data) {
    ProgressIndicator indicator = data.getIndicator();
    int size = data.getSize();
    int totalProcessed = 0;
    StringBuilder marks = new StringBuilder();
    for (Map.Entry<Document, List<MarkdownImage>> imageEntry : data.getWaitingProcessMap().entrySet()) {
        int totalCount = imageEntry.getValue().size();
        for (MarkdownImage markdownImage : imageEntry.getValue()) {
            String imageName = markdownImage.getImageName();
            indicator.setText2("Processing " + imageName);

            marks.append(markdownImage.getFinalMark()).append(ImageContents.LINE_BREAK);

            indicator.setFraction(((++totalProcessed * 1.0) + data.getIndex() * size) / totalCount * size);
        }
    }
    ImageUtils.setStringToClipboard(marks.toString());
    return true;
}
 
Example 4
Source File: RoutesManager.java    From railways with MIT License 6 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
    indicator.setText("Updating route list for module "  +
            getModule().getName() + "...");
    indicator.setFraction(0.0);
    indicator.setIndeterminate(false);

    // Save indicator to be able to cancel task execution.
    routesUpdateIndicator = indicator;

    output = RailwaysUtils.queryRakeRoutes(getModule(),
            myModuleSettings.routesTaskName,
            myModuleSettings.environment);

    if (output == null)
        setState(UPDATED);

    indicator.setFraction(1.0);
}
 
Example 5
Source File: JarHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private File copyToMirror(@Nonnull File original, @Nonnull File mirror) {
  ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
  if (progress != null) {
    progress.pushState();
    progress.setText(VfsBundle.message("jar.copy.progress", original.getPath()));
    progress.setFraction(0);
  }

  try {
    FileUtil.copy(original, mirror);
  }
  catch (final IOException e) {
    reportIOErrorWithJars(original, mirror, e);
    return original;
  }
  finally {
    if (progress != null) {
      progress.popState();
    }
  }


  return mirror;
}
 
Example 6
Source File: QuickFixAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean iteration() {
  final CommonProblemDescriptor descriptor = myDescriptors[myCount++];
  ProgressIndicator indicator = myTask.getIndicator();
  if (indicator != null) {
    indicator.setFraction((double)myCount / myDescriptors.length);
    if (descriptor instanceof ProblemDescriptor) {
      final PsiElement psiElement = ((ProblemDescriptor)descriptor).getPsiElement();
      if (psiElement != null) {
        indicator.setText("Processing " + SymbolPresentationUtil.getSymbolPresentableText(psiElement));
      }
    }
  }
  applyFix(myProject, myContext, new CommonProblemDescriptor[]{descriptor}, myIgnoredElements);
  return isDone();
}
 
Example 7
Source File: LogView.java    From logviewer with Apache License 2.0 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 8
Source File: Generator.java    From r2m-plugin-android with Apache License 2.0 5 votes vote down vote up
private static void displayIndicatorMessage(ProgressIndicator progressIndicator,
                                            String message,
                                            int value)
        throws InterruptedException {
    if (null == progressIndicator) {
        return;
    }
    progressIndicator.setFraction((((double) value) / 100));
    progressIndicator.setText(message);
    Thread.sleep(1000);
}
 
Example 9
Source File: ReplaceToDocument.java    From markdown-image-kit with MIT License 5 votes vote down vote up
@Override
public boolean execute(EventData data) {
    ProgressIndicator indicator = data.getIndicator();
    int size = data.getSize();
    int totalProcessed = 0;

    for (Map.Entry<Document, List<MarkdownImage>> imageEntry : data.getWaitingProcessMap().entrySet()) {
        Document document = imageEntry.getKey();
        int totalCount = imageEntry.getValue().size();
        for (MarkdownImage markdownImage : imageEntry.getValue()) {
            String imageName = markdownImage.getImageName();
            indicator.setFraction(((++totalProcessed * 1.0) + data.getIndex() * size) / totalCount * size);
            indicator.setText2("Processing " + imageName);

            String finalMark = markdownImage.getFinalMark();
            if(StringUtils.isBlank(finalMark)){
                continue;
            }
            String newLineText = markdownImage.getOriginalLineText().replace(markdownImage.getOriginalMark(), finalMark);

            WriteCommandAction.runWriteCommandAction(data.getProject(), () -> document
                .replaceString(document.getLineStartOffset(markdownImage.getLineNumber()),
                               document.getLineEndOffset(markdownImage.getLineNumber()),
                               newLineText));



        }
    }
    return true;
}
 
Example 10
Source File: AsposeJavaAPI.java    From Aspose.OCR-for-Java with MIT License 5 votes vote down vote up
public void syncRepository(ProgressIndicator p)
{   try {

        GitHelper.syncRepository(getLocalRepositoryPath(), get_remoteExamplesRepository());
        p.setFraction(1);

    } catch (Exception e) {
    }
}
 
Example 11
Source File: NetUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @param indicator           Progress indicator.
 * @param inputStream         source stream
 * @param outputStream        destination stream
 * @param expectedContentSize expected content size, used in progress indicator. can be -1.
 * @return bytes copied
 * @throws IOException                                            if IO error occur
 * @throws com.intellij.openapi.progress.ProcessCanceledException if process was canceled.
 */

// TODO [VISTALL] move to another util
public static int copyStreamContent(@Nullable ProgressIndicator indicator,
                                    @Nonnull InputStream inputStream,
                                    @Nonnull OutputStream outputStream,
                                    int expectedContentSize) throws IOException, ProcessCanceledException {
  if (indicator != null) {
    indicator.checkCanceled();
    if (expectedContentSize < 0) {
      indicator.setIndeterminate(true);
    }
  }

  final byte[] buffer = new byte[8 * 1024];
  int count;
  int total = 0;
  while ((count = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, count);
    total += count;

    if (indicator != null) {
      indicator.checkCanceled();

      if (expectedContentSize > 0) {
        indicator.setFraction((double)total / expectedContentSize);
      }
    }
  }

  if (indicator != null) {
    indicator.checkCanceled();
  }

  return total;
}
 
Example 12
Source File: AsposeExampleCallback.java    From Aspose.OCR-for-Java with MIT License 5 votes vote down vote up
@Override
 public boolean executeTask(@NotNull ProgressIndicator progressIndicator) {
   // progressIndicator.setIndeterminate(true);
     // Set the progress bar percentage and text
     progressIndicator.setFraction(0.10);

     progressIndicator.setText("Preparing to refresh examples");

    final String item = (String) page.getComponentSelection().getSelectedItem();

            if (item != null && !item.equals("Select Java API")) {
                ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        page.diplayMessage("Please wait. Preparing to refresh examples", true);
                    }
                }, ModalityState.defaultModalityState());

                progressIndicator.setFraction(0.20);
                AsposeJavaAPI component = AsposeOCRJavaAPI.getInstance();
                component.checkAndUpdateRepo(progressIndicator);
                if (component.isExamplesDefinitionAvailable()) {
                    progressIndicator.setFraction(0.60);
                    page.populateExamplesTree(component, top,progressIndicator);
                }
            }

     progressIndicator.setFraction(1);
 return true;
}
 
Example 13
Source File: FileTreeModelBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void update(ProgressIndicator indicator, boolean indeterminate, double fraction) {
  if (indicator instanceof PanelProgressIndicator) {
    ((PanelProgressIndicator)indicator).update(SCANNING_PACKAGES_MESSAGE, indeterminate, fraction);
  } else {
    if (fraction != -1) {
      indicator.setFraction(fraction);
    }
  }
}
 
Example 14
Source File: ShowImageDuplicatesAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void collectAndShowDuplicates(final Project project) {
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && !indicator.isCanceled()) {
    indicator.setText("Collecting project images...");
    indicator.setIndeterminate(false);
    final List<VirtualFile> images = new ArrayList<VirtualFile>();
    for (String ext : IMAGE_EXTENSIONS) {
      images.addAll(FilenameIndex.getAllFilesByExt(project, ext));
    }

    final Map<Long, Set<VirtualFile>> duplicates = new HashMap<Long, Set<VirtualFile>>();
    final Map<Long, VirtualFile> all = new HashMap<Long, VirtualFile>();
    for (int i = 0; i < images.size(); i++) {
      indicator.setFraction((double)(i + 1) / (double)images.size());
      final VirtualFile file = images.get(i);
      if (!(file.getFileSystem() instanceof LocalFileSystem)) continue;
      final long length = file.getLength();
      if (all.containsKey(length)) {
        if (!duplicates.containsKey(length)) {
          final HashSet<VirtualFile> files = new HashSet<VirtualFile>();
          files.add(all.get(length));
          duplicates.put(length, files);
        }
        duplicates.get(length).add(file);
      } else {
        all.put(length, file);
      }
      indicator.checkCanceled();
    }
    showResults(project, images, duplicates, all);
  }
}
 
Example 15
Source File: AsposeJavaAPI.java    From Aspose.OCR-for-Java with MIT License 5 votes vote down vote up
public void checkAndUpdateRepo(ProgressIndicator p) {

        if (null == get_remoteExamplesRepository()) {
            AsposeMavenProjectManager.showMessage(AsposeConstants.EXAMPLES_NOT_AVAILABLE_TITLE, get_name() + " - " + AsposeConstants.EXAMPLES_NOT_AVAILABLE_MESSAGE, JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE);
            examplesNotAvailable = true;
            examplesDefinitionAvailable = false;
            return;
        } else {
            examplesNotAvailable = false;
        }

        if (isExamplesDefinitionsPresent()) {
            try {
                examplesDefinitionAvailable = true;
                syncRepository(p);
                p.setFraction(0.30);
            } catch (Exception e) {
            }
        } else {
            updateRepository(p);
            if (isExamplesDefinitionsPresent()) {
                examplesDefinitionAvailable = true;

            }


        }
        p.setFraction(0.50);
    }
 
Example 16
Source File: MikTaskBase.java    From markdown-image-kit with MIT License 5 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
    indicator.pushState();
    indicator.setIndeterminate(false);
    try {
        indicator.setFraction(0.0);
        manager.invoke(indicator);
    } finally {
        indicator.setFraction(1.0);
        indicator.popState();
    }
}
 
Example 17
Source File: WGet.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
public static boolean apply(@NotNull String urlString, @NotNull File targetFile, @NotNull ProgressIndicator indicator, double totalBytes) {
    try {
        // some code
        File partFile = new File(targetFile.getPath() + ".part");

        if (partFile.exists()) {
            //noinspection ResultOfMethodCallIgnored
            partFile.delete();
        }

        //noinspection ResultOfMethodCallIgnored
        partFile.createNewFile();

        FileOutputStream partFileOut = new FileOutputStream(partFile);

        java.net.URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);

        connection.setConnectTimeout(240 * 1000);
        connection.setReadTimeout(240 * 1000);

        InputStream inputStream = connection.getInputStream();

        double totalBytesDownloaded = 0.0;

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = inputStream.read(buffer);
        while (bytesRead >= 0) {
            if (totalBytes > 0.0) {
                indicator.setFraction(totalBytesDownloaded / totalBytes);
            }
            totalBytesDownloaded += bytesRead;

            partFileOut.write(buffer, 0, bytesRead);
            bytesRead = inputStream.read(buffer);
        }

        connection.disconnect();
        partFileOut.close();
        inputStream.close();

        java.nio.file.Files.move(partFile.toPath(), targetFile.toPath(), StandardCopyOption.ATOMIC_MOVE);
        if (!SystemInfo.isWindows) {
            //noinspection ResultOfMethodCallIgnored
            targetFile.setExecutable(true);
        }

        LOG.info(targetFile.getName() + " downloaded to " + targetFile.toPath().getParent());
        Notifications.Bus.notify(new ORNotification("Reason", "Downloaded " + targetFile, NotificationType.INFORMATION));

        return true;
    } catch (IOException e) {
        Notifications.Bus.notify(new ORNotification("Reason", "Can't download " + targetFile + "\n" + e, NotificationType.ERROR));
        return false;
    }
}
 
Example 18
Source File: DistanceMatrix.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public List<ExtractClassCandidateRefactoring> getExtractClassCandidateRefactorings(Set<String> classNamesToBeExamined, ProgressIndicator indicator) {
    List<ExtractClassCandidateRefactoring> candidateList = new ArrayList<>();
    Iterator<MyClass> classIt = system.getClassIterator();
    ArrayList<MyClass> oldClasses = new ArrayList<>();

    while (classIt.hasNext()) {
        MyClass myClass = classIt.next();
        if (classNamesToBeExamined.contains(myClass.getName())) {
            oldClasses.add(myClass);
        }
    }

    indicator.setText(IntelliJDeodorantBundle.message("god.class.identification.indicator"));
    indicator.setFraction(0.0);
    for (MyClass sourceClass : oldClasses) {
        if (!sourceClass.getMethodList().isEmpty() && !sourceClass.getAttributeList().isEmpty()) {
            double[][] distanceMatrix = getJaccardDistanceMatrix(sourceClass);
            Clustering clustering = Clustering.getInstance(distanceMatrix);
            ArrayList<Entity> entities = new ArrayList<>();
            entities.addAll(sourceClass.getAttributeList());
            entities.addAll(sourceClass.getMethodList());
            HashSet<Cluster> clusters = clustering.clustering(entities);
            int processedClusters = 0;

            for (Cluster cluster : clusters) {
                processedClusters += 1;
                indicator.setFraction(((double) processedClusters) / clusters.size());
                ExtractClassCandidateRefactoring candidate = new ExtractClassCandidateRefactoring(system, sourceClass, cluster.getEntities());
                if (candidate.isApplicable()) {
                    int sourceClassDependencies = candidate.getDistinctSourceDependencies();
                    int extractedClassDependencies = candidate.getDistinctTargetDependencies();
                    if (sourceClassDependencies <= maximumNumberOfSourceClassMembersAccessedByExtractClassCandidate &&
                            sourceClassDependencies < extractedClassDependencies) {
                        candidateList.add(candidate);
                    }
                }
            }
        }
    }
    indicator.setFraction(1.0);
    return candidateList;
}
 
Example 19
Source File: CrucibleTestConnectionTask.java    From Crucible4IDEA with MIT License 4 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
  indicator.setText("Connecting...");
  indicator.setFraction(0);
  indicator.setIndeterminate(true);

  final CrucibleTestConnector connector = new CrucibleTestConnector(myProject);
  connector.run();

  while (connector.getConnectionState() == CrucibleTestConnector.ConnectionState.NOT_FINISHED) {
    try {
      if (indicator.isCanceled()) {
        connector.setInterrupted();
        break;
      }
      else {
        Thread.sleep(CHECK_CANCEL_INTERVAL);
      }
    }
    catch (InterruptedException e) {
      LOG.info(e.getMessage());
    }
  }

  CrucibleTestConnector.ConnectionState state = connector.getConnectionState();
  switch (state) {
    case FAILED:
      EventQueue.invokeLater(new Runnable() {
        public void run() {
          Messages.showDialog(myProject, "Reason:  " + connector.getErrorMessage(), "Connection Failed", new String[]{"Ok"}, 0, null);
        }
      });
      break;
    case INTERRUPTED:
      LOG.debug("'Test Connection' canceled");
      break;
    case SUCCEEDED:
      EventQueue.invokeLater(new Runnable() {
        public void run() {
          Messages.showDialog(myProject, "Connected successfully", "Connection OK", new String[]{"Ok"}, 0, null);
        }
      });
      break;
    default: //NOT_FINISHED:
      LOG.warn("Unexpected 'Test Connection' state: "
               + connector.getConnectionState().toString());
  }
}
 
Example 20
Source File: Generator.java    From r2m-plugin-android with Apache License 2.0 4 votes vote down vote up
public void makeFilePerformance(ProgressIndicator progressIndicator) {
    progressIndicator.setFraction(0.1);
    try {
        File cachedSourceFolder = cacheManager.getControllerSourceFolder();

        // copy test files
        File generatedTestFiles = new File(cachedSourceFolder, CacheManager.RELATIVE_TEST_DIR);
        File targetTestFolder = ProjectManager.getTestSourceFolderFile(project);
        if(generatedTestFiles.exists()) {
            if(targetTestFolder != null && targetTestFolder.exists()) {
                // if test filename exists, copy the test into a fileName_latest.java test
                List<String> testFiles = FileHelper.getCommonTestFiles(project, controllerName, packageName);
                String fileName = testFiles == null || testFiles.size() == 0 ? null : testFiles.get(0); // assuming one test class
                if (fileName == null || !fileName.endsWith(".java")) {
                    FileUtils.copyDirectory(generatedTestFiles, targetTestFolder);
                } else {
                    String newFileName = fileName + ".latest";
                    String header = R2MMessages.getMessage("LATEST_TEST_CLASS_HEADER", fileName.substring(fileName.lastIndexOf('/') + 1));
                    File newFile = new File(generatedTestFiles, newFileName);
                    File oldFile = new File(generatedTestFiles, fileName);
                    String content = FileUtils.readFileToString(oldFile);
                    FileUtils.write(newFile, header);
                    FileUtils.write(newFile, content, true);
                    FileUtils.forceDelete(oldFile);
                    FileUtils.copyDirectory(generatedTestFiles, targetTestFolder);
                }
            }
            // TODO: the src directory can be confusing, it should be called test,or tests as with ios.
            File rootTestDirectory = new File(cachedSourceFolder, "src");
            FileUtils.deleteDirectory(rootTestDirectory);
        }

        // copy others
        FileUtils.copyDirectory(cachedSourceFolder, ProjectManager.getSourceFolderFile(project));
        ControllerHistoryManager.saveController(project, cacheManager.getControllerFolder().getName());
        File controllerFile = ProjectManager.getControllerFile(project, packageName, controllerName);
        if (null != controllerFile) {
            showControllerFile(controllerFile);
        }
        //displayIndicatorMessage(progressIndicator, "Completed generation", 100);
    } catch (Exception e) {
        e.printStackTrace();
    }
}