Java Code Examples for com.intellij.openapi.application.Application#executeOnPooledThread()

The following examples show how to use com.intellij.openapi.application.Application#executeOnPooledThread() . 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: InstalledPackagesPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshLatestVersions(@Nonnull final PackageManagementService packageManagementService) {
  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(() -> {
    if (packageManagementService == myPackageManagementService) {
      try {
        List<RepoPackage> packages = packageManagementService.reloadAllPackages();
        final Map<String, RepoPackage> packageMap = buildNameToPackageMap(packages);
        application.invokeLater(() -> {
          for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) {
            final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0);
            final RepoPackage repoPackage = packageMap.get(pyPackage.getName());
            myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2);
          }
          myPackagesTable.setPaintBusy(false);
        }, ModalityState.stateForComponent(myPackagesTable));
      }
      catch (IOException ignored) {
        myPackagesTable.setPaintBusy(false);
      }
    }
  });
}
 
Example 2
Source File: Log4J2DialogAppender.java    From consulo with Apache License 2.0 6 votes vote down vote up
void appendToLoggers(@Nonnull IdeaLoggingEvent ideaEvent) {
  if (myDialogRunnable != null) {
    return;
  }

  final DefaultIdeaErrorLogger logger = DefaultIdeaErrorLogger.INSTANCE;
  if (!logger.canHandle(ideaEvent)) {
    return;
  }
  myDialogRunnable = () -> {
    try {
      logger.handle(ideaEvent);
    }
    finally {
      myDialogRunnable = null;
    }
  };

  final Application app = ApplicationManager.getApplication();
  if (app == null) {
    new Thread(myDialogRunnable).start();
  }
  else {
    app.executeOnPooledThread(myDialogRunnable);
  }
}
 
Example 3
Source File: ManagePackagesDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void initModel() {
  setDownloadStatus(true);
  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(() -> {
    try {
      myPackagesModel = new PackagesModel(myController.getAllPackages());

      application.invokeLater(() -> {
        myPackages.setModel(myPackagesModel);
        ((MyPackageFilter)myFilter).filter();
        doSelectPackage(mySelectedPackageName);
        setDownloadStatus(false);
      }, ModalityState.any());
    }
    catch (final IOException e) {
      application.invokeLater(() -> {
        if (myMainPanel.isShowing()) {
          Messages.showErrorDialog(myMainPanel, "Error loading package list:" + e.getMessage(), "Packages");
        }
        setDownloadStatus(false);
      }, ModalityState.any());
    }
  });
}
 
Example 4
Source File: InspectionManagerEx.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void buildInspectionSearchIndexIfNecessary() {
  if (!myToolsAreInitialized.getAndSet(true)) {
    final SearchableOptionsRegistrar myOptionsRegistrar = SearchableOptionsRegistrar.getInstance();
    final InspectionToolRegistrar toolRegistrar = InspectionToolRegistrar.getInstance();
    final Application app = ApplicationManager.getApplication();
    if (app.isUnitTestMode() || app.isHeadlessEnvironment()) return;

    app.executeOnPooledThread(new Runnable(){
      @Override
      public void run() {
        List<InspectionToolWrapper> tools = toolRegistrar.createTools();
        for (InspectionToolWrapper toolWrapper : tools) {
          processText(toolWrapper.getDisplayName().toLowerCase(), toolWrapper, myOptionsRegistrar);

          final String description = toolWrapper.loadDescription();
          if (description != null) {
            @NonNls String descriptionText = HTML_PATTERN.matcher(description).replaceAll(" ");
            processText(descriptionText, toolWrapper, myOptionsRegistrar);
          }
        }
      }
    });
  }
}
 
Example 5
Source File: InterruptibleActivity.java    From consulo with Apache License 2.0 6 votes vote down vote up
public final int execute() {
  final Application application = ApplicationManager.getApplication();

  /* TODO: uncomment assertion when problems in Perforce plugin are fixed.
  LOG.assertTrue(!application.isDispatchThread(), "InterruptibleActivity is supposed to be lengthy thus must not block Swing UI thread");
  */

  final Future<?> future = application.executeOnPooledThread(new Runnable() {
    public void run() {
      start();
    }
  });

  final int rc = waitForFuture(future);
  if (rc != 0) {
    application.executeOnPooledThread(new Runnable() {
      public void run() {
        interrupt();
      }
    });
  }

  return rc;
}
 
Example 6
Source File: LightFilePointer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshFile() {
  VirtualFile file = myFile;
  if (file != null && file.isValid()) return;
  VirtualFileManager vfManager = VirtualFileManager.getInstance();
  VirtualFile virtualFile = vfManager.findFileByUrl(myUrl);
  if (virtualFile == null && !myRefreshed) {
    myRefreshed = true;
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread() || !application.isReadAccessAllowed()) {
      virtualFile = vfManager.refreshAndFindFileByUrl(myUrl);
    }
    else {
      application.executeOnPooledThread(() -> vfManager.refreshAndFindFileByUrl(myUrl));
    }
  }

  myFile = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
}
 
Example 7
Source File: InspectionProjectProfileManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void projectClosed() {
  final Application app = ApplicationManager.getApplication();
  Runnable cleanupInspectionProfilesRunnable = new Runnable() {
    @Override
    public void run() {
      for (InspectionProfileWrapper wrapper : myName2Profile.values()) {
        wrapper.cleanup(myProject);
      }
      fireProfilesShutdown();
    }
  };
  if (app.isUnitTestMode() || app.isHeadlessEnvironment()) {
    cleanupInspectionProfilesRunnable.run();
  }
  else {
    app.executeOnPooledThread(cleanupInspectionProfilesRunnable);
  }
}
 
Example 8
Source File: FontComboBox.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Model(boolean withAllStyles, boolean filterNonLatin, boolean noFontItem) {
  myNoFontItem = noFontItem ? new NoFontItem() : null;
  Application application = ApplicationManager.getApplication();
  if (application == null || application.isUnitTestMode()) {
    setFonts(FontInfo.getAll(withAllStyles), filterNonLatin);
  }
  else {
    application.executeOnPooledThread(() -> {
      List<FontInfo> all = FontInfo.getAll(withAllStyles);
      application.invokeLater(() -> {
        setFonts(all, filterNonLatin);
        updateSelectedItem();
      }, application.getAnyModalityState());
    });
  }
}
 
Example 9
Source File: PlatformOrPluginUpdateChecker.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static AsyncResult<Void> updateAndShowResult() {
  final AsyncResult<Void> result = AsyncResult.undefined();
  final Application app = Application.get();
  final UpdateSettings updateSettings = UpdateSettings.getInstance();
  if (!updateSettings.isEnable()) {
    result.setDone();
    return result;
  }
  app.executeOnPooledThread(() -> checkAndNotifyForUpdates(null, false, null).notify(result));
  return result;
}
 
Example 10
Source File: DirectoryAccessChecker.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void refresh() {
  if (IS_ENABLED) {
    Application app = ApplicationManager.getApplication();
    if (app.isDispatchThread()) {
      app.executeOnPooledThread(() -> doRefresh());
    }
    else {
      doRefresh();
    }
  }
}
 
Example 11
Source File: OptionsEditor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private ActionCallback getUiFor(final Configurable configurable) {
  assertIsDispatchThread();

  if (myDisposed) {
    return new ActionCallback.Rejected();
  }

  final ActionCallback result = new ActionCallback();

  if (!myConfigurable2Content.containsKey(configurable)) {

    final ActionCallback readyCallback = myConfigurable2LoadCallback.get(configurable);
    if (readyCallback != null) {
      return readyCallback;
    }

    myConfigurable2LoadCallback.put(configurable, result);
    myLoadingDecorator.startLoading(false);
    final Application app = ApplicationManager.getApplication();
    Runnable action = () -> UIUtil.invokeAndWaitIfNeeded((ProtectedRunnable)() -> {
      if (myProject.isDisposed()) {
        result.setRejected();
      }
      else {
        initConfigurable(configurable).notifyWhenDone(result);
      }
    });
    if (app.isUnitTestMode()) {
      action.run();
    }
    else {
      app.executeOnPooledThread(action);
    }
  }
  else {
    result.setDone();
  }

  return result;
}
 
Example 12
Source File: QueueProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean startProcessing() {
  LOG.assertTrue(Thread.holdsLock(myQueue));

  if (isProcessing || !myStarted) {
    return false;
  }
  isProcessing = true;
  final T item = myQueue.removeFirst();
  final Runnable runnable = new Runnable() {
    @Override
    public void run() {
      if (myDeathCondition.value(null)) return;
      runSafely(new Runnable() {
        @Override
        public void run() {
          myProcessor.consume(item, myContinuationContext);
        }
      });
    }
  };
  final Application application = ApplicationManager.getApplication();
  if (myThreadToUse == ThreadToUse.AWT) {
    final ModalityState state = myModalityState.remove(new MyOverrideEquals(item));
    if (state != null) {
      application.invokeLater(runnable, state);
    }
    else {
      application.invokeLater(runnable);
    }
  }
  else {
    application.executeOnPooledThread(runnable);
  }
  return true;
}
 
Example 13
Source File: ProcessCloseUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void close(final Process process) {
  final Semaphore outerSemaphore = new Semaphore();
  outerSemaphore.down();

  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(new Runnable() {
    public void run() {
      try {
        final Semaphore semaphore = new Semaphore();
        semaphore.down();

        final Runnable closeRunnable = new Runnable() {
          public void run() {
            try {
              closeProcessImpl(process);
            }
            finally {
              semaphore.up();
            }
          }
        };

        final Future<?> innerFuture = application.executeOnPooledThread(closeRunnable);
        semaphore.waitFor(ourAsynchronousWaitTimeout);
        if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) {
          innerFuture.cancel(true); // will call interrupt()
        }
      }
      finally {
        outerSemaphore.up();
      }
    }
  });

  // just wait
  outerSemaphore.waitFor(ourSynchronousWaitTimeout);
}
 
Example 14
Source File: ProcessWaiter.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int execute(final InterruptibleProcess worker, final long timeout) throws IOException, ExecutionException, TimeoutException, InterruptedException {
  myErrStreamListener = createStreamListener(worker.getErrorStream());
  myInStreamListener = createStreamListener(worker.getInputStream());

  final Application app = ApplicationManager.getApplication();
  Future<?> errorStreamReadingFuture = null;
  Future<?> outputStreamReadingFuture = null;

  final int rc;
  try {
    errorStreamReadingFuture = app.executeOnPooledThread(myErrStreamListener);
    outputStreamReadingFuture = app.executeOnPooledThread(myInStreamListener);
    rc = worker.execute();
    if (tryReadStreams(rc)) {
      errorStreamReadingFuture.get(timeout, TimeUnit.MILLISECONDS);
      outputStreamReadingFuture.get(timeout, TimeUnit.MILLISECONDS);
    }
  } finally {
    cancelListeners();
    if (errorStreamReadingFuture != null) {
      errorStreamReadingFuture.cancel(true);
    }
    if (outputStreamReadingFuture != null) {
      outputStreamReadingFuture.cancel(true);
    }
  }

  return rc;
}
 
Example 15
Source File: DirDiffTableModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void applySettings() {
  if (! myUpdating.get()) myUpdating.set(true);
  final JBLoadingPanel loadingPanel = getLoadingPanel();
  if (!loadingPanel.isLoading()) {
    loadingPanel.startLoading();
    if (myUpdater == null) {
      myUpdater = new Updater(loadingPanel, 100);
      myUpdater.start();
    }
  }
  final Application app = ApplicationManager.getApplication();
  app.executeOnPooledThread(() -> {
    if (myDisposed) return;
    myTree.updateVisibility(mySettings);
    final ArrayList<DirDiffElementImpl> elements = new ArrayList<>();
    fillElements(myTree, elements);
    final Runnable uiThread = () -> {
      if (myDisposed) return;
      clear();
      myElements.addAll(elements);
      myUpdating.set(false);
      fireTableDataChanged();
      this.text.set("");
      if (loadingPanel.isLoading()) {
        loadingPanel.stopLoading();
      }
      if (mySelectionConfig == null) {
        selectFirstRow();
      } else {
        mySelectionConfig.restore();
      }
      myPanel.update(true);
    };
    if (myProject == null || myProject.isDefault()) {
      SwingUtilities.invokeLater(uiThread);
    } else {
      app.invokeLater(uiThread, ModalityState.any());
    }
  });
}
 
Example 16
Source File: RincewindDownloader.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator indicator) {
    if (myProject.isDisposed()) {
        LOG.debug("Project is disposed, can't download rincewind");
        return;
    }

    InsightManagerImpl insightManager = (InsightManagerImpl) ServiceManager.getService(myProject, InsightManager.class);
    if (!insightManager.isDownloading.compareAndSet(false, true)) {
        // We are already in the process of downloading
        LOG.debug("Already downloading, abort");
        return;
    }

    try {
        File targetFile = insightManager.getRincewindFile(m_sourceFile);
        if (targetFile == null) {
            LOG.debug("No target file, abort downloading");
            return;
        }

        String rincewindFilename = insightManager.getRincewindFilename(m_sourceFile);
        if (rincewindFilename == null) {
            LOG.debug("No rincewind version found, abort downloading");
            return;
        }

        LOG.info("Downloading " + targetFile.getName() + "...");
        indicator.setIndeterminate(false);
        indicator.setFraction(0.0);

        boolean downloaded = WGet.apply(DOWNLOAD_URL + rincewindFilename, targetFile, indicator, TOTAL_BYTES);
        if (downloaded) {
            Application application = ApplicationManager.getApplication();
            application.executeOnPooledThread(() -> {
                DumbService dumbService = DumbService.getInstance(myProject);
                dumbService.runReadActionInSmartMode(() -> {
                    LOG.info("Rincewind downloaded, query types for opened files");
                    PsiManager psiManager = PsiManager.getInstance(myProject);
                    VirtualFile[] openedFiles = FileEditorManager.getInstance(myProject).getOpenFiles();
                    for (VirtualFile openedFile : openedFiles) {
                        // Query types and update psi cache
                        PsiFile cmtFile = ORFileManager.findCmtFileFromSource(myProject, openedFile.getNameWithoutExtension());
                        if (cmtFile != null) {
                            Path cmtPath = FileSystems.getDefault().getPath(cmtFile.getVirtualFile().getPath());

                            application.invokeLater(() -> application.runReadAction(() -> {
                                PsiFile psiFile = psiManager.findFile(openedFile);
                                if (psiFile instanceof FileBase) {
                                    LOG.debug("Query types for " + openedFile);
                                    insightManager.queryTypes(openedFile, cmtPath, inferredTypes -> InferredTypesService
                                            .annotatePsiFile(myProject, psiFile.getLanguage(), openedFile, inferredTypes));
                                }
                            }));
                        }
                    }
                });
            });
        }

        indicator.setFraction(1.0);
    } finally {
        insightManager.isDownloading.set(false);
    }
}
 
Example 17
Source File: InstalledPackagesPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void doUpdatePackages(@Nonnull final PackageManagementService packageManagementService) {
  onUpdateStarted();
  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(() -> {
    Collection<InstalledPackage> packages = Lists.newArrayList();
    try {
      packages = packageManagementService.getInstalledPackages();
    }
    catch (IOException e) {
      LOG.warn(e.getMessage()); // do nothing, we already have an empty list
    }
    finally {
      final Collection<InstalledPackage> finalPackages = packages;

      final Map<String, RepoPackage> cache = buildNameToPackageMap(packageManagementService.getAllPackagesCached());
      final boolean shouldFetchLatestVersionsForOnlyInstalledPackages = shouldFetchLatestVersionsForOnlyInstalledPackages();
      if (cache.isEmpty()) {
        if (!shouldFetchLatestVersionsForOnlyInstalledPackages) {
          refreshLatestVersions(packageManagementService);
        }
      }
      UIUtil.invokeLaterIfNeeded(() -> {
        if (packageManagementService == myPackageManagementService) {
          myPackagesTableModel.getDataVector().clear();
          for (InstalledPackage pkg : finalPackages) {
            RepoPackage repoPackage = cache.get(pkg.getName());
            final String version = repoPackage != null ? repoPackage.getLatestVersion() : null;
            myPackagesTableModel
                    .addRow(new Object[]{pkg, pkg.getVersion(), version == null ? "" : version});
          }
          if (!cache.isEmpty()) {
            onUpdateFinished();
          }
          if (shouldFetchLatestVersionsForOnlyInstalledPackages) {
            setLatestVersionsForInstalledPackages();
          }
        }
      });
    }
  });
}