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

The following examples show how to use com.intellij.openapi.application.Application#isDispatchThread() . 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: WaitForProgressToShow.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void runOrInvokeLaterAboveProgress(final Runnable command, @Nullable final ModalityState modalityState, @Nonnull final Project project) {
  final Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    command.run();
  } else {
    final ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
    if (pi != null) {
      execute(pi);
      application.invokeLater(command, pi.getModalityState(), new Condition() {
        @Override
        public boolean value(Object o) {
          return (! project.isOpen()) || project.isDisposed();
        }
      });
    } else {
      final ModalityState notNullModalityState = modalityState == null ? ModalityState.NON_MODAL : modalityState;
      application.invokeLater(command, notNullModalityState, project.getDisposed());
    }
  }
}
 
Example 2
Source File: LocalFileSystemBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void refreshIoFiles(@Nonnull Iterable<? extends File> files, boolean async, boolean recursive, @Nullable Runnable onFinish) {
  VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance();

  Application app = ApplicationManager.getApplication();
  boolean fireCommonRefreshSession = app.isDispatchThread() || app.isWriteAccessAllowed();
  if (fireCommonRefreshSession) manager.fireBeforeRefreshStart(false);

  try {
    List<VirtualFile> filesToRefresh = new ArrayList<>();

    for (File file : files) {
      VirtualFile virtualFile = refreshAndFindFileByIoFile(file);
      if (virtualFile != null) {
        filesToRefresh.add(virtualFile);
      }
    }

    RefreshQueue.getInstance().refresh(async, recursive, onFinish, filesToRefresh);
  }
  finally {
    if (fireCommonRefreshSession) manager.fireAfterRefreshFinish(false);
  }
}
 
Example 3
Source File: ModuleManagerComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void fireModulesAdded() {
  Runnable runnableWithProgress = () -> {
    for (final Module module : myModuleModel.getModules()) {
      final Application app = ApplicationManager.getApplication();
      final Runnable swingRunnable = () -> fireModuleAddedInWriteAction(module);
      if (app.isDispatchThread() || app.isHeadlessEnvironment()) {
        swingRunnable.run();
      }
      else {
        ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
        app.invokeAndWait(swingRunnable, pi.getModalityState());
      }
    }
  };

  ProgressIndicator progressIndicator = myProgressManager.getProgressIndicator();
  if (progressIndicator == null) {
    myProgressManager.runProcessWithProgressSynchronously(runnableWithProgress, "Loading modules", false, myProject);
  }
  else {
    runnableWithProgress.run();
  }
}
 
Example 4
Source File: CompilerTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void addMessage(final CompilerMessage message) {
  final CompilerMessageCategory messageCategory = message.getCategory();
  if (CompilerMessageCategory.WARNING.equals(messageCategory)) {
    myWarningCount += 1;
  }
  else if (CompilerMessageCategory.ERROR.equals(messageCategory)) {
    myErrorCount += 1;
    informWolf(message);
  }

  Application application = Application.get();
  if (application.isDispatchThread()) {
    // implicit ui thread
    //noinspection RequiredXAction
    doAddMessage(message);
  }
  else {
    application.invokeLater(() -> {
      if (!myProject.isDisposed()) {
        doAddMessage(message);
      }
    }, ModalityState.NON_MODAL);
  }
}
 
Example 5
Source File: CompilerPathsImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getModuleOutputPath(final Module module, final ContentFolderTypeProvider contentFolderType) {
  final String outPathUrl;
  final Application application = ApplicationManager.getApplication();
  final ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module);

  if (application.isDispatchThread()) {
    outPathUrl = pathsManager.getCompilerOutputUrl(contentFolderType);
  }
  else {
    outPathUrl = application.runReadAction(new Computable<String>() {
      @Override
      public String compute() {
        return pathsManager.getCompilerOutputUrl(contentFolderType);
      }
    });
  }

  return outPathUrl != null ? VirtualFileManager.extractPath(outPathUrl) : null;
}
 
Example 6
Source File: CompilerPathsImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * The same as {@link #getModuleOutputDirectory} but returns String.
 * The method still returns a non-null value if the output path is specified in Settings but does not exist on disk.
 */
@javax.annotation.Nullable
@Deprecated
public static String getModuleOutputPath(final Module module, final boolean forTestClasses) {
  final String outPathUrl;
  final Application application = ApplicationManager.getApplication();
  final ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module);

  if (application.isDispatchThread()) {
    outPathUrl = pathsManager.getCompilerOutputUrl(
      forTestClasses ? TestContentFolderTypeProvider.getInstance() : ProductionContentFolderTypeProvider.getInstance());
  }
  else {
    outPathUrl = application.runReadAction(new Computable<String>() {
      @Override
      public String compute() {
        return pathsManager.getCompilerOutputUrl(
          forTestClasses ? TestContentFolderTypeProvider.getInstance() : ProductionContentFolderTypeProvider.getInstance());
      }
    });
  }

  return outPathUrl != null ? VirtualFileManager.extractPath(outPathUrl) : null;
}
 
Example 7
Source File: FormatterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void execute(@Nonnull SequentialTask task) {
  disableFormatting();
  Application application = ApplicationManager.getApplication();
  FormattingProgressTask progressTask = myProgressTask.getAndSet(null);
  if (progressTask == null || !application.isDispatchThread() || application.isUnitTestMode()) {
    try {
      task.prepare();
      while (!task.isDone()) {
        task.iteration();
      }
    }
    finally {
      enableFormatting();
    }
  }
  else {
    progressTask.setTask(task);
    Runnable callback = () -> enableFormatting();
    for (FormattingProgressCallback.EventType eventType : FormattingProgressCallback.EventType.values()) {
      progressTask.addCallback(eventType, callback);
    }
    ProgressManager.getInstance().run(progressTask);
  }
}
 
Example 8
Source File: GenericNotifierImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void clear() {
  final List<MyNotification> notifications;
  synchronized (myLock) {
    notifications = new ArrayList<MyNotification>(myState.values());
    myState.clear();
  }
  final Application application = ApplicationManager.getApplication();
  final Runnable runnable = new Runnable() {
    public void run() {
      for (MyNotification notification : notifications) {
        notification.expire();
      }
    }
  };
  if (application.isDispatchThread()) {
    runnable.run();
  } else {
    application.invokeLater(runnable, ModalityState.NON_MODAL, myProject.getDisposed());
  }
}
 
Example 9
Source File: IdeaHelper.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
public static void runOnUIThread(final Runnable runnable, final boolean wait, final ModalityState modalityState) {
    Application application = ApplicationManager.getApplication();
    if (application != null && !application.isDispatchThread() && !application.isUnitTestMode()) {
        if (wait) {
            application.invokeAndWait(runnable, modalityState);
            // TODO: use this instead after deprecating IDEA 15: TransactionGuard.getInstance().submitTransactionAndWait(runnable);
        } else {
            application.invokeLater(runnable, modalityState);
            // TODO: use this instead after deprecating IDEA 15: TransactionGuard.getInstance().submitTransaction(runnable);
        }
    } else {
        // If we are already on the dispatch thread then we can run it here
        // If we don't have an application or we are testing, just run the runnable here
        runnable.run();
    }
}
 
Example 10
Source File: ToolbarUpdater.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateActions(boolean now, final boolean transparentOnly, final boolean forced) {
  final Runnable updateRunnable = new MyUpdateRunnable(this, transparentOnly, forced);
  final Application app = ApplicationManager.getApplication();

  if (now || (app.isUnitTestMode() && app.isDispatchThread())) {
    updateRunnable.run();
  }
  else {
    final IdeFocusManager fm = IdeFocusManager.getInstance(null);

    if (!app.isHeadlessEnvironment()) {
      if (app.isDispatchThread() && myComponent.isShowing()) {
        fm.doWhenFocusSettlesDown(updateRunnable);
      }
      else {
        UiNotifyConnector.doWhenFirstShown(myComponent, () -> fm.doWhenFocusSettlesDown(updateRunnable));
      }
    }
  }
}
 
Example 11
Source File: CommittedChangesCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void notifyIncomingChangesUpdated(@Nullable final Collection<CommittedChangeList> receivedChanges) {
  final Collection<CommittedChangeList> changes = receivedChanges == null ? myCachedIncomingChangeLists : receivedChanges;
  if (changes == null) {
    final Application application = ApplicationManager.getApplication();
    final Runnable runnable = new Runnable() {
      @Override
      public void run() {
        final List<CommittedChangeList> lists = loadIncomingChanges(true);
        fireIncomingChangesUpdated(lists);
      }
    };
    if (application.isDispatchThread()) {
      myTaskQueue.run(runnable);
    }
    else {
      runnable.run();
    }
    return;
  }
  final ArrayList<CommittedChangeList> listCopy = new ArrayList<CommittedChangeList>(changes);
  fireIncomingChangesUpdated(listCopy);
}
 
Example 12
Source File: ModuleCompilerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void sortModules(final Project project, final List<Module> modules) {
  final Application application = ApplicationManager.getApplication();
  Runnable sort = new Runnable() {
    public void run() {
      Comparator<Module> comparator = ModuleManager.getInstance(project).moduleDependencyComparator();
      Collections.sort(modules, comparator);
    }
  };
  if (application.isDispatchThread()) {
    sort.run();
  }
  else {
    application.runReadAction(sort);
  }
}
 
Example 13
Source File: AppUIUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void invokeLaterIfProjectAlive(@Nonnull final Project project, @Nonnull final Runnable runnable) {
  final Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    runnable.run();
  }
  else {
    application.invokeLater(runnable, new Condition() {
      @Override
      public boolean value(Object o) {
        return !project.isOpen() || project.isDisposed();
      }
    });
  }
}
 
Example 14
Source File: MessageBusUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T> void runOnSyncPublisher(final Project project, final Topic<T> topic, final Consumer<T> listener) {
  final Application application = ApplicationManager.getApplication();
  final Runnable runnable = createPublisherRunnable(project, topic, listener);
  if (application.isDispatchThread()) {
    runnable.run();
  } else {
    application.runReadAction(runnable);
  }
}
 
Example 15
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure the current EDT activity finishes in case it requires many write actions, with each being delayed a bit
 * by background thread read action (until its first checkCanceled call). Shouldn't be called from under read action.
 */
public static void yieldToPendingWriteActions() {
  Application application = ApplicationManager.getApplication();
  if (application.isReadAccessAllowed()) {
    throw new IllegalStateException("Mustn't be called from within read action");
  }
  if (application.isDispatchThread()) {
    throw new IllegalStateException("Mustn't be called from EDT");
  }
  Semaphore semaphore = new Semaphore(1);
  application.invokeLater(semaphore::up, ModalityState.any());
  awaitWithCheckCanceled(semaphore, ProgressIndicatorProvider.getGlobalProgressIndicator());
}
 
Example 16
Source File: ActionUpdateEdtExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the supplied value on Swing thread, but try to avoid deadlocks by periodically performing {@link ProgressManager#checkCanceled()} in the current thread.
 * Makes sense to be used in background read actions running with a progress indicator that's canceled when a write action is about to occur.
 *
 * @see com.intellij.openapi.application.ReadAction#nonBlocking(Runnable)
 */
public static <T> T computeOnEdt(Supplier<T> supplier) {
  Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    return supplier.get();
  }

  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  Ref<T> result = Ref.create();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      if (indicator == null || !indicator.isCanceled()) {
        result.set(supplier.get());
      }
    }
    finally {
      semaphore.up();
    }
  });

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
  // check cancellation one last time, to ensure the EDT action wasn't no-op due to cancellation
  if (indicator != null && indicator.isCanceled()) {
    throw new ProcessCanceledException();
  }
  return result.get();
}
 
Example 17
Source File: MessageBusUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T> void invokeLaterIfNeededOnSyncPublisher(final Project project, final Topic<T> topic, final Consumer<T> listener) {
  final Application application = ApplicationManager.getApplication();
  final Runnable runnable = createPublisherRunnable(project, topic, listener);
  if (application.isDispatchThread()) {
    runnable.run();
  } else {
    application.invokeLater(runnable);
  }
}
 
Example 18
Source File: FileStatusManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void fileStatusChanged(final VirtualFile file) {
  final Application application = ApplicationManager.getApplication();
  if (!application.isDispatchThread() && !application.isUnitTestMode()) {
    ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() {
      @Override
      public void run() {
        fileStatusChanged(file);
      }
    });
    return;
  }

  if (file == null || !file.isValid()) return;
  FileStatus cachedStatus = getCachedStatus(file);
  if (cachedStatus == FileStatusNull.INSTANCE) {
    return;
  }
  if (cachedStatus == null) {
    cacheChangedFileStatus(file, FileStatusNull.INSTANCE);
    return;
  }
  FileStatus newStatus = calcStatus(file);
  if (cachedStatus == newStatus) return;
  cacheChangedFileStatus(file, newStatus);

  for (FileStatusListener listener : myListeners) {
    listener.fileStatusChanged(file);
  }
}
 
Example 19
Source File: SystemShortcuts.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static <T> T computeOnEdt(Supplier<T> supplier) {
  final Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    return supplier.get();
  }

  final Ref<T> result = Ref.create();
  ApplicationManager.getApplication().invokeAndWait(() -> {
    result.set(supplier.get());
  });
  return result.get();
}
 
Example 20
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();
    }
  }
}