@Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
  public static void openAttachment(
      final Project project, String name, EntityRef parent, int size) {
    try {
      final File file;
      boolean agmLink = name.endsWith(".agmlink");
      if (agmLink) {
        // for the file to open correctly, there must be no trailing extension
        file = File.createTempFile("tmp", "_" + name.replaceFirst("\\.agmlink$", ""));
      } else {
        file = File.createTempFile("tmp", "_" + name);
      }
      final Runnable openFile =
          new Runnable() {
            @Override
            public void run() {
              String url =
                  VirtualFileManager.constructUrl(
                      LocalFileSystem.PROTOCOL,
                      FileUtil.toSystemIndependentName(file.getAbsolutePath()));
              final VirtualFile virtualFile =
                  VirtualFileManager.getInstance().refreshAndFindFileByUrl(url);
              UIUtil.invokeLaterIfNeeded(
                  new Runnable() {
                    public void run() {
                      if (virtualFile != null) {
                        FileEditor[] editors =
                            project
                                .getComponent(FileEditorManager.class)
                                .openFile(virtualFile, true);
                        if (editors.length > 0) {
                          return;
                        }

                        FileType type =
                            FileTypeManager.getInstance()
                                .getKnownFileTypeOrAssociate(virtualFile, project);
                        if (type instanceof INativeFileType
                            && ((INativeFileType) type)
                                .openFileInAssociatedApplication(project, virtualFile)) {
                          return;
                        }
                      }
                      Messages.showWarningDialog(
                          "No editor seems to be associated with this file type. Try to download and open the file manually.",
                          "Not Supported");
                    }
                  });
            }
          };
      if (agmLink) {
        ProgressManager.getInstance()
            .run(new AttachmentAgmLinkDownloadTask(project, file, name, size, parent, openFile));
      } else {
        ProgressManager.getInstance()
            .run(new AttachmentDownloadTask(project, file, name, size, parent, openFile));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  public void computeUsages(List<PsiLiteralExpression> targets) {
    final Project project = myTarget.getProject();
    final PsiElement parent = myTarget.getParent().getParent();
    final LocalInspectionsPass pass =
        new LocalInspectionsPass(
            myFile,
            myFile.getViewProvider().getDocument(),
            parent.getTextRange().getStartOffset(),
            parent.getTextRange().getEndOffset(),
            LocalInspectionsPass.EMPTY_PRIORITY_RANGE,
            false,
            HighlightInfoProcessor.getEmpty());
    final InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    for (PsiLiteralExpression target : targets) {
      final Object value = target.getValue();
      if (!(value instanceof String)) {
        continue;
      }
      InspectionToolWrapper toolWrapperById =
          ((InspectionProfileImpl) inspectionProfile).getToolById((String) value, target);
      if (!(toolWrapperById instanceof LocalInspectionToolWrapper)) {
        continue;
      }
      final LocalInspectionToolWrapper toolWrapper =
          ((LocalInspectionToolWrapper) toolWrapperById).createCopy();
      final InspectionManagerEx managerEx =
          (InspectionManagerEx) InspectionManager.getInstance(project);
      final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
      toolWrapper.initialize(context);
      ((RefManagerImpl) context.getRefManager()).inspectionReadActionStarted();
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      Runnable inspect =
          new Runnable() {
            @Override
            public void run() {
              pass.doInspectInBatch(
                  context,
                  managerEx,
                  Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper));
            }
          };
      if (indicator == null) {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(inspect, new ProgressIndicatorBase());
      } else {
        inspect.run();
      }

      for (HighlightInfo info : pass.getInfos()) {
        final PsiElement element =
            CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset);
        if (element != null) {
          addOccurrence(element);
        }
      }
    }
  }
  private void loadCommitsData(
      @NotNull final TIntIntHashMap commits,
      @NotNull final Consumer<List<T>> consumer,
      @Nullable ProgressIndicator indicator) {
    final List<T> result = ContainerUtil.newArrayList();
    final TIntHashSet toLoad = new TIntHashSet();

    long taskNumber = myCurrentTaskIndex++;

    for (int id : commits.keys()) {
      T details = getFromCache(id);
      if (details == null || details instanceof LoadingDetails) {
        toLoad.add(id);
        cacheCommit(id, taskNumber);
      } else {
        result.add(details);
      }
    }

    if (toLoad.isEmpty()) {
      sortCommitsByRow(result, commits);
      consumer.consume(result);
    } else {
      Task.Backgroundable task =
          new Task.Backgroundable(
              null, "Loading Selected Details", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
              indicator.checkCanceled();
              try {
                TIntObjectHashMap<T> map = preLoadCommitData(toLoad);
                map.forEachValue(
                    value -> {
                      result.add(value);
                      return true;
                    });
                sortCommitsByRow(result, commits);
                notifyLoaded();
              } catch (VcsException e) {
                LOG.error(e);
              }
            }

            @Override
            public void onSuccess() {
              consumer.consume(result);
            }
          };
      if (indicator != null) {
        ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator);
      } else {
        ProgressManager.getInstance().run(task);
      }
    }
  }
示例#5
0
 public static boolean runVcsProcessWithProgress(
     final VcsRunnable runnable, String progressTitle, boolean canBeCanceled, Project project)
     throws VcsException {
   final Ref<VcsException> ex = new Ref<VcsException>();
   boolean result =
       ProgressManager.getInstance()
           .runProcessWithProgressSynchronously(
               new Runnable() {
                 @Override
                 public void run() {
                   try {
                     runnable.run();
                   } catch (VcsException e) {
                     ex.set(e);
                   }
                 }
               },
               progressTitle,
               canBeCanceled,
               project);
   if (!ex.isNull()) {
     throw ex.get();
   }
   return result;
 }
  public static void writeFileImpl(String folder, @NonNls String fileName, CharSequence buf)
      throws IOException {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    final String fullPath = folder + File.separator + fileName;

    if (indicator != null) {
      ProgressManager.checkCanceled();
      indicator.setText(
          InspectionsBundle.message("inspection.export.generating.html.for", fullPath));
    }

    FileWriter writer = null;
    try {
      File folderFile = new File(folder);
      folderFile.mkdirs();
      new File(fullPath).getParentFile().mkdirs();
      writer = new FileWriter(fullPath);
      writer.write(buf.toString().toCharArray());
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          // Cannot do anything in case of exception
        }
      }
    }
  }
示例#7
0
  public static void run(Project project, String title, final MavenTask task)
      throws MavenProcessCanceledException {
    final Exception[] canceledEx = new Exception[1];
    final RuntimeException[] runtimeEx = new RuntimeException[1];
    final Error[] errorEx = new Error[1];

    ProgressManager.getInstance()
        .run(
            new Task.Modal(project, title, true) {
              public void run(@NotNull ProgressIndicator i) {
                try {
                  task.run(new MavenProgressIndicator(i));
                } catch (MavenProcessCanceledException e) {
                  canceledEx[0] = e;
                } catch (ProcessCanceledException e) {
                  canceledEx[0] = e;
                } catch (RuntimeException e) {
                  runtimeEx[0] = e;
                } catch (Error e) {
                  errorEx[0] = e;
                }
              }
            });
    if (canceledEx[0] instanceof MavenProcessCanceledException)
      throw (MavenProcessCanceledException) canceledEx[0];
    if (canceledEx[0] instanceof ProcessCanceledException)
      throw new MavenProcessCanceledException();

    if (runtimeEx[0] != null) throw runtimeEx[0];
    if (errorEx[0] != null) throw errorEx[0];
  }
 public void actionPerformed(final AnActionEvent e) {
   final AnalysisScope scope = getScope();
   LOG.assertTrue(scope != null);
   final DependenciesBuilder builder;
   if (!myForward) {
     builder = new BackwardDependenciesBuilder(myProject, scope, myScopeOfInterest);
   } else {
     builder = new ForwardDependenciesBuilder(myProject, scope, myTransitiveBorder);
   }
   ProgressManager.getInstance()
       .runProcessWithProgressAsynchronously(
           myProject,
           AnalysisScopeBundle.message("package.dependencies.progress.title"),
           new Runnable() {
             public void run() {
               builder.analyze();
             }
           },
           new Runnable() {
             public void run() {
               myBuilders.add(builder);
               myDependencies.putAll(builder.getDependencies());
               myIllegalDependencies.putAll(builder.getIllegalDependencies());
               exclude(myExcluded);
               rebuild();
             }
           },
           null,
           new PerformAnalysisInBackgroundOption(myProject));
 }
 public boolean checkConflicts(final ExtractSuperclassDialog dialog) {
   final MemberInfo[] infos =
       ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class);
   final PsiDirectory targetDirectory = dialog.getTargetDirectory();
   final PsiPackage targetPackage;
   if (targetDirectory != null) {
     targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory);
   } else {
     targetPackage = null;
   }
   final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
   if (!ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           new Runnable() {
             public void run() {
               final PsiClass superClass =
                   mySubclass.getExtendsListTypes().length > 0 ? mySubclass.getSuperClass() : null;
               conflicts.putAllValues(
                   PullUpConflictsUtil.checkConflicts(
                       infos,
                       mySubclass,
                       superClass,
                       targetPackage,
                       targetDirectory,
                       dialog.getContainmentVerifier(),
                       false));
             }
           },
           RefactoringBundle.message("detecting.possible.conflicts"),
           true,
           myProject)) return false;
   ExtractSuperClassUtil.checkSuperAccessible(targetDirectory, conflicts, mySubclass);
   return ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject);
 }
  public byte[] loadContent() throws IOException, VcsException {
    ContentLoader loader = new ContentLoader(myURL, myRevision, myPegRevision);
    if (ApplicationManager.getApplication().isDispatchThread() && !myRevision.isLocal()) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              loader,
              SvnBundle.message("progress.title.loading.file.content"),
              false,
              myVCS.getProject());
    } else {
      loader.run();
    }

    VcsException exception = loader.getException();
    if (exception == null) {
      final byte[] contents = loader.getContents();
      ContentRevisionCache.checkContentsSize(myURL, contents.length);
      return contents;
    } else {
      LOG.info(
          "Failed to load file '"
              + myURL
              + "' content at revision: "
              + myRevision
              + "\n"
              + exception.getMessage(),
          exception);
      throw exception;
    }
  }
  public static void deleteFile(Project project, final VirtualFile file) throws ExecutionException {
    final Ref<IOException> error = new Ref<IOException>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          if (file.isValid()) {
                            file.delete(this);
                          }
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };

    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }
    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
  }
 @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 Course course = StudyTaskManager.getInstance(project).getCourse();
   if (course == null) {
     return;
   }
   if (course.getId() > 0) {
     ProgressManager.getInstance()
         .run(
             new Task.Modal(project, "Updating Course", true) {
               @Override
               public void run(@NotNull ProgressIndicator indicator) {
                 for (Lesson lesson : course.getLessons()) {
                   if (lesson.getId() > 0) {
                     CCStepicConnector.updateLesson(project, lesson, indicator);
                   } else {
                     final CourseInfo info = CourseInfo.fromCourse(course);
                     final int lessonId = CCStepicConnector.postLesson(project, lesson, indicator);
                     final List<Integer> sections = info.getSections();
                     final Integer sectionId = sections.get(sections.size() - 1);
                     CCStepicConnector.postUnit(lessonId, lesson.getIndex(), sectionId);
                   }
                 }
               }
             });
   } else {
     CCStepicConnector.postCourseWithProgress(project, course);
   }
   EduUsagesCollector.courseUploaded();
 }
示例#13
0
  protected Map<
          ModuleDescriptor, Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>
      calculate() {
    myLastRoots = getRoots();

    ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();

    Map<ModuleDescriptor, Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>
        result =
            new HashMap<
                ModuleDescriptor,
                Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>>();
    for (ModuleDescriptor moduleDescriptor : getModuleDescriptors()) {

      Map<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>> root2Facets =
          new HashMap<File, List<FacetDetectionProcessor.DetectedInWizardFacetInfo>>();
      for (File root : moduleDescriptor.getContentRoots()) {
        FacetDetectionProcessor processor =
            new FacetDetectionProcessor(progressIndicator, myModuleType);
        processor.process(root);
        List<FacetDetectionProcessor.DetectedInWizardFacetInfo> facets =
            processor.getDetectedFacetsInfos();
        if (!facets.isEmpty()) {
          root2Facets.put(root, facets);
        }
      }

      if (!root2Facets.isEmpty()) {
        result.put(moduleDescriptor, root2Facets);
      }
    }

    return result;
  }
示例#14
0
 public void updateTargetsView(final DependencyViewerScope sourceScope) {
   myScope = sourceScope;
   final Wrappers._T<SearchResults<SNode>> results =
       new Wrappers._T<SearchResults<SNode>>(new SearchResults<SNode>());
   ProgressManager.getInstance()
       .run(
           new Task.Modal(myProject, "Analyzing dependencies", true) {
             public void run(@NotNull final ProgressIndicator indicator) {
               ModelAccess.instance()
                   .runReadAction(
                       new Runnable() {
                         public void run() {
                           ProgressMonitor monitor = new ProgressMonitorAdapter(indicator);
                           try {
                             monitor.start(null, 100);
                             List<SNode> nodes =
                                 myReferencesFinder.getNodes(sourceScope, monitor.subTask(20));
                             mySourceNodes = nodes;
                             results.value =
                                 (myIsMeta
                                     ? myReferencesFinder.getUsedLanguagesSearchResults(
                                         nodes, sourceScope, monitor.subTask(80))
                                     : myReferencesFinder.getTargetSearchResults(
                                         nodes, sourceScope, monitor.subTask(80)));
                           } finally {
                             monitor.done();
                           }
                         }
                       });
             }
           });
   myTargetsView.setContents(results.value);
   updateReferencesView(null);
 }
示例#15
0
  public static boolean prepareToInstall(
      List<PluginNode> pluginsToInstall, List<IdeaPluginDescriptor> allPlugins) {
    ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();

    final List<PluginId> pluginIds = new ArrayList<PluginId>();
    for (PluginNode pluginNode : pluginsToInstall) {
      pluginIds.add(pluginNode.getPluginId());
    }

    boolean result = false;

    for (final PluginNode pluginNode : pluginsToInstall) {
      if (pi != null) pi.setText(pluginNode.getName());

      try {
        result |= prepareToInstall(pluginNode, pluginIds, allPlugins);
      } catch (final IOException e) {
        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                Messages.showErrorDialog(
                    pluginNode.getName() + ": " + e.getMessage(),
                    CommonBundle.message("title.error"));
              }
            });
      }
    }
    return result;
  }
 private static void rollbackUnderProgress(
     @NotNull final Project project,
     @NotNull final VirtualFile virtualFile,
     @NotNull final Label labelToRevert) {
   ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           () -> {
             try {
               labelToRevert.revert(project, virtualFile);
               VcsNotifier.getInstance(project)
                   .notifyImportantWarning(
                       "Apply Patch Aborted",
                       "All files changed during apply patch action were rolled back");
             } catch (LocalHistoryException e) {
               VcsNotifier.getInstance(project)
                   .notifyImportantWarning(
                       "Rollback Failed",
                       String.format(
                           "Try using local history dialog for %s and perform revert manually.",
                           virtualFile.getName()));
             }
           },
           "Rollback Applied Changes...",
           true,
           project);
 }
      @Override
      public Boolean call() throws Exception {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(
                () -> {
                  try {
                    while (true) {
                      progress.checkCanceled();
                      T element = failedToProcess.poll();
                      if (element == null) element = things.take();

                      if (element == tombStone) {
                        things.offer(element);
                        result = true;
                        break;
                      }
                      try {
                        if (!thingProcessor.process(element)) {
                          result = false;
                          break;
                        }
                      } catch (RuntimeException e) {
                        failedToProcess.add(element);
                        throw e;
                      }
                    }
                  } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                  }
                },
                progress);
        return result;
      }
  @Bombed(user = "******", year = 2014, month = Calendar.JANUARY, day = 21)
  public void testAsyncRefresh() throws Throwable {
    final File tempDir = createTempDirectory();

    final Throwable[] ex = {null};
    boolean success =
        JobLauncher.getInstance()
            .invokeConcurrentlyUnderProgress(
                Arrays.asList(new Object[8]),
                ProgressManager.getInstance().getProgressIndicator(),
                true,
                new Processor<Object>() {
                  @Override
                  public boolean process(Object o) {
                    try {
                      doAsyncRefreshTest(tempDir);
                    } catch (Throwable t) {
                      ex[0] = t;
                    }
                    return true;
                  }
                });

    if (ex[0] != null) throw ex[0];
    if (!success) fail("!success");
  }
 private void unzip(String path, boolean moduleMode) {
   try {
     File dir = new File(path);
     ZipInputStream zipInputStream = myTemplate.getStream();
     ZipUtil.unzip(
         ProgressManager.getInstance().getProgressIndicator(),
         dir,
         zipInputStream,
         moduleMode ? PATH_CONVERTOR : null);
     String iml =
         ContainerUtil.find(
             dir.list(),
             new Condition<String>() {
               @Override
               public boolean value(String s) {
                 return s.endsWith(".iml");
               }
             });
     if (moduleMode) {
       File from = new File(path, iml);
       File to = new File(getModuleFilePath());
       if (!from.renameTo(to)) {
         throw new IOException("Can't rename " + from + " to " + to);
       }
     }
     VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir);
     if (virtualFile == null) {
       throw new IOException("Can't find " + dir);
     }
     RefreshQueue.getInstance().refresh(false, true, null, virtualFile);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
示例#20
0
 private static void addToHistory(
     final SMTestProxy.SMRootTestProxy root,
     TestConsoleProperties consoleProperties,
     Disposable parentDisposable) {
   final RunProfile configuration = consoleProperties.getConfiguration();
   if (configuration instanceof RunConfiguration
       && !(consoleProperties instanceof ImportedTestConsoleProperties)) {
     final MySaveHistoryTask backgroundable =
         new MySaveHistoryTask(consoleProperties, root, (RunConfiguration) configuration);
     final BackgroundableProcessIndicator processIndicator =
         new BackgroundableProcessIndicator(backgroundable);
     Disposer.register(
         parentDisposable,
         new Disposable() {
           @Override
           public void dispose() {
             processIndicator.cancel();
             backgroundable.dispose();
           }
         });
     Disposer.register(parentDisposable, processIndicator);
     ProgressManager.getInstance()
         .runProcessWithProgressAsynchronously(backgroundable, processIndicator);
   }
 }
  private void changeFormat(
      @NotNull final WCInfo wcInfo, @NotNull final Collection<WorkingCopyFormat> supportedFormats) {
    ChangeFormatDialog dialog =
        new ChangeFormatDialog(myProject, new File(wcInfo.getPath()), false, !wcInfo.isIsWcRoot());

    dialog.setSupported(supportedFormats);
    dialog.setData(wcInfo.getFormat());
    dialog.show();
    if (!dialog.isOK()) {
      return;
    }
    final WorkingCopyFormat newFormat = dialog.getUpgradeMode();
    if (!wcInfo.getFormat().equals(newFormat)) {
      ApplicationManager.getApplication().saveAll();
      final Task.Backgroundable task =
          new SvnFormatWorker(myProject, newFormat, wcInfo) {
            @Override
            public void onSuccess() {
              super.onSuccess();
              myRefreshLabel.doClick();
            }
          };
      ProgressManager.getInstance().run(task);
    }
  }
 private void runInBackground(final Project project, final String name, final Runnable runnable) {
   if (ApplicationManager.getApplication().isDispatchThread()) {
     ProgressManager.getInstance()
         .runProcessWithProgressSynchronously(runnable, name, false, project);
   } else {
     runnable.run();
   }
 }
示例#23
0
 public boolean isInModalProgressThread() {
   if (myExceptionalThreadWithReadAccessRunnable == null || !isExceptionalThreadWithReadAccess()) {
     return false;
   }
   ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
   return progressIndicator.isModal()
       && ((ProgressIndicatorEx) progressIndicator).isModalityEntered();
 }
 private ProgressMonitor getOrCreateProgressMonitor(ProgressMonitor promon) {
   if (promon != null) {
     return promon;
   }
   ProgressIndicator prind = ProgressManager.getInstance().getProgressIndicator();
   prind = (prind != null ? prind : new EmptyProgressIndicator());
   return new ProgressMonitorAdapter(prind);
 }
  public static void executeExternalProcess(
      @Nullable final Project myProject,
      @NotNull final ProcessHandler processHandler,
      @NotNull final ExecutionMode mode,
      @NotNull final String presentableCmdline) {
    final String title = mode.getTitle() != null ? mode.getTitle() : "Please wait...";
    assert title != null;

    final Runnable process;
    if (mode.cancelable()) {
      process = createCancelableExecutionProcess(processHandler, mode.shouldCancelFun());
    } else {
      if (mode.getTimeout() <= 0) {
        process =
            new Runnable() {
              public void run() {
                processHandler.waitFor();
              }
            };
      } else {
        process =
            createTimelimitedExecutionProcess(
                processHandler, mode.getTimeout(), presentableCmdline);
      }
    }
    if (mode.withModalProgress()) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, title, mode.cancelable(), myProject, mode.getProgressParentComponent());
    } else if (mode.inBackGround()) {
      final Task task =
          new Task.Backgroundable(myProject, title, mode.cancelable()) {
            public void run(@NotNull final ProgressIndicator indicator) {
              process.run();
            }
          };
      ProgressManager.getInstance().run(task);
    } else {
      final String title2 = mode.getTitle2();
      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null && title2 != null) {
        indicator.setText2(title2);
      }
      process.run();
    }
  }
  private void waitForProcess(final RunContentDescriptor descriptor) {
    ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            new Runnable() {
              public void run() {
                final Semaphore semaphore = new Semaphore();
                semaphore.down();

                ApplicationManager.getApplication()
                    .executeOnPooledThread(
                        new Runnable() {
                          public void run() {
                            final ProcessHandler processHandler = descriptor.getProcessHandler();
                            try {
                              if (processHandler != null) {
                                processHandler.waitFor();
                              }
                            } finally {
                              semaphore.up();
                            }
                          }
                        });

                final ProgressIndicator progressIndicator =
                    ProgressManager.getInstance().getProgressIndicator();

                if (progressIndicator != null) {
                  progressIndicator.setText(
                      ExecutionBundle.message("waiting.for.vm.detach.progress.text"));
                  ApplicationManager.getApplication()
                      .executeOnPooledThread(
                          new Runnable() {
                            public void run() {
                              while (true) {
                                if (progressIndicator.isCanceled()
                                    || !progressIndicator.isRunning()) {
                                  semaphore.up();
                                  break;
                                }
                                try {
                                  synchronized (this) {
                                    wait(2000L);
                                  }
                                } catch (InterruptedException ignore) {
                                }
                              }
                            }
                          });
                }

                semaphore.waitFor();
              }
            },
            ExecutionBundle.message(
                "terminating.process.progress.title", descriptor.getDisplayName()),
            true,
            myProject);
  }
  private boolean processFilesConcurrently(
      @NotNull Set<VirtualFile> files,
      @NotNull final ProgressIndicator indicator,
      @NotNull final Processor<VirtualFile> processor) {
    final List<VirtualFile> fileList = new ArrayList<VirtualFile>(files);
    // fine but grabs all CPUs
    // return JobLauncher.getInstance().invokeConcurrentlyUnderProgress(fileList, indicator, false,
    // false, processor);

    int parallelism = CacheUpdateRunner.indexingThreadCount();
    final Callable<Boolean> processFileFromSet =
        () -> {
          final boolean[] result = {true};
          ProgressManager.getInstance()
              .executeProcessUnderProgress(
                  () -> {
                    while (true) {
                      ProgressManager.checkCanceled();
                      VirtualFile file;
                      synchronized (fileList) {
                        file = fileList.isEmpty() ? null : fileList.remove(fileList.size() - 1);
                      }
                      if (file == null) {
                        break;
                      }
                      if (!processor.process(file)) {
                        result[0] = false;
                        break;
                      }
                    }
                  },
                  indicator);
          return result[0];
        };
    List<Future<Boolean>> futures =
        ContainerUtil.map(
            Collections.nCopies(parallelism, ""),
            s -> myApplication.executeOnPooledThread(processFileFromSet));

    List<Boolean> results =
        ContainerUtil.map(
            futures,
            future -> {
              try {
                return future.get();
              } catch (Exception e) {
                LOG.error(e);
              }
              return false;
            });

    return !ContainerUtil.exists(
        results,
        result -> {
          return result != null && !result; // null means PCE
        });
  }
 @Override
 public void applyFix(
     @NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
   final PsiFile file = descriptor.getPsiElement().getContainingFile();
   final Backgroundable backgroundable = getFixTask(file);
   ProgressManager.getInstance()
       .runProcessWithProgressAsynchronously(
           backgroundable, new BackgroundableProcessIndicator(backgroundable));
 }
示例#29
0
 @NotNull
 public ModalityState getDefaultModalityState() {
   if (EventQueue.isDispatchThread()) {
     return getCurrentModalityState();
   } else {
     ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
     return progress == null ? getNoneModalityState() : progress.getModalityState();
   }
 }
  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null) return;
    final ShelvedChangeList[] changeLists =
        e.getData(ShelvedChangesViewManager.SHELVED_CHANGELIST_KEY);
    List<ShelvedChange> changes = e.getData(ShelvedChangesViewManager.SHELVED_CHANGE_KEY);
    List<ShelvedBinaryFile> binaryFiles =
        e.getData(ShelvedChangesViewManager.SHELVED_BINARY_FILE_KEY);
    if (changes != null && binaryFiles != null && changes.size() == 0 && binaryFiles.size() == 0) {
      changes = null;
      binaryFiles = null;
    }
    LOG.assertTrue(changeLists != null);

    final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
    final List<LocalChangeList> allChangeLists = changeListManager.getChangeListsCopy();
    String defaultName = changeLists[0].DESCRIPTION;
    LocalChangeList list = null;
    if (changeLists.length == 1) {
      final LocalChangeList sameNamedList = changeListManager.findChangeList(defaultName);
      if (sameNamedList != null) {
        list = sameNamedList;
      }
    }
    if (list == null) {
      list = changeListManager.getDefaultChangeList();
    }
    final ChangeListChooser chooser =
        new ChangeListChooser(
            project,
            allChangeLists,
            list,
            VcsBundle.message("unshelve.changelist.chooser.title"),
            defaultName);
    chooser.show();
    if (!chooser.isOK()) {
      return;
    }

    FileDocumentManager.getInstance().saveAllDocuments();

    final List<ShelvedBinaryFile> finalBinaryFiles = binaryFiles;
    final List<ShelvedChange> finalChanges = changes;
    ProgressManager.getInstance()
        .run(
            new Task.Backgroundable(
                project, "Unshelve changes", true, BackgroundFromStartOption.getInstance()) {
              @Override
              public void run(@NotNull ProgressIndicator indicator) {
                for (ShelvedChangeList changeList : changeLists) {
                  ShelveChangesManager.getInstance(project)
                      .unshelveChangeList(
                          changeList, finalChanges, finalBinaryFiles, chooser.getSelectedList());
                }
              }
            });
  }