com.intellij.openapi.application.ModalityState Java Examples

The following examples show how to use com.intellij.openapi.application.ModalityState. 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: SafeDialogUtils.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Synchronously shows a yes/no dialog. This method must not be called from a write safe context
 * as it needs to be executed synchronously and AWT actions are not allowed from a write safe
 * context.
 *
 * @param project the project used as a reference to generate and position the dialog
 * @param message the text displayed as the message of the dialog
 * @param title the text displayed as the title of the dialog
 * @return <code>true</code> if {@link Messages#YES} is chosen or <code>false</code> if {@link
 *     Messages#NO} is chosen or the dialog is closed
 * @throws IllegalAWTContextException if the calling thread is currently inside a write safe
 *     context
 * @throws IllegalStateException if no response value was received from the dialog or the response
 *     was not {@link Messages#YES} or {@link Messages#NO}.
 */
public static boolean showYesNoDialog(Project project, final String message, final String title)
    throws IllegalAWTContextException {

  if (application.isWriteAccessAllowed()) {
    throw new IllegalAWTContextException("AWT events are not allowed inside write actions.");
  }

  log.info("Showing yes/no dialog: " + title + " - " + message);

  Integer result =
      EDTExecutor.invokeAndWait(
          (Computable<Integer>)
              () -> Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()),
          ModalityState.defaultModalityState());

  switch (result) {
    case Messages.YES:
      return true;
    case Messages.NO:
      return false;
    default:
      throw new IllegalStateException("Encountered unknown dialog answer " + result);
  }
}
 
Example #2
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
void execute(@Nonnull BrowseMode browseMode) {
  myBrowseMode = browseMode;

  if (PsiDocumentManager.getInstance(myProject).getPsiFile(myHostEditor.getDocument()) == null) return;

  int selStart = myHostEditor.getSelectionModel().getSelectionStart();
  int selEnd = myHostEditor.getSelectionModel().getSelectionEnd();

  if (myHostOffset >= selStart && myHostOffset < selEnd) {
    disposeHighlighter();
    return;
  }

  myExecutionProgress = ReadAction.nonBlocking(() -> doExecute()).withDocumentsCommitted(myProject).expireWhen(() -> isTaskOutdated(myHostEditor))
          .finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).submit(AppExecutorUtil.getAppExecutorService());
}
 
Example #3
Source File: UiNotifyConnector.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void hierarchyChanged(@Nonnull HierarchyEvent e) {
  if (isDisposed()) return;

  if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) > 0) {
    final Runnable runnable = () -> {
      final Component c = myComponent.get();
      if (isDisposed() || c == null) return;

      if (c.isShowing()) {
        showNotify();
      }
      else {
        hideNotify();
      }
    };
    final Application app = ApplicationManager.getApplication();
    if (app != null && app.isDispatchThread()) {
      app.invokeLater(runnable, ModalityState.current());
    }
    else {
      //noinspection SSBasedInspection
      SwingUtilities.invokeLater(runnable);
    }
  }
}
 
Example #4
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateGutterSize() {
  assertIsDispatchThread();
  if (!updatingSize) {
    updatingSize = true;
    ApplicationManager.getApplication().invokeLater(() -> {
      try {
        if (!isDisposed()) {
          myGutterComponent.updateSize();
        }
      }
      finally {
        updatingSize = false;
      }
    }, ModalityState.any(), __ -> isDisposed());
  }
}
 
Example #5
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 #6
Source File: ErrorDiffTool.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Nonnull
@Override
public ToolbarComponents init() {
  if (myRequest instanceof UnknownFileTypeDiffRequest) {
    String fileName = ((UnknownFileTypeDiffRequest)myRequest).getFileName();
    if (fileName != null && FileTypeManager.getInstance().getFileTypeByFileName(fileName) != UnknownFileType.INSTANCE) {
      // FileType was assigned elsewhere (ex: by other UnknownFileTypeDiffRequest). We should reload request.
      if (myContext instanceof DiffContextEx) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            ((DiffContextEx)myContext).reloadDiffRequest();
          }
        }, ModalityState.current());
      }
    }
  }

  return new ToolbarComponents();
}
 
Example #7
Source File: HTMLExportUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void runExport(final Project project, @Nonnull ThrowableRunnable<IOException> runnable) {
  try {
    runnable.run();
  }
  catch (IOException e) {
    Runnable showError = new Runnable() {
      @Override
      public void run() {
        Messages.showMessageDialog(
          project,
          InspectionsBundle.message("inspection.export.error.writing.to", "export file"),
          InspectionsBundle.message("inspection.export.results.error.title"),
          Messages.getErrorIcon()
        );
      }
    };
    ApplicationManager.getApplication().invokeLater(showError, ModalityState.NON_MODAL);
    throw new ProcessCanceledException();
  }
}
 
Example #8
Source File: GoToClassTest.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
private List<Object> calcPopupElements(ChooseByNamePopup popup, String text, boolean checkboxState) {
    List<Object> elements = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    //noinspection KotlinInternalInJava
    SwingUtilities.invokeLater(() ->
            popup.scheduleCalcElements(text, checkboxState, ModalityState.NON_MODAL, SelectMostRelevant.INSTANCE,
                    set -> {
                        elements.addAll(set);
                        latch.countDown();
                    }));
    try {
        if (!latch.await(10, TimeUnit.SECONDS)) {
            Assert.fail();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return elements;
}
 
Example #9
Source File: LiveTemplateSettingsEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void focusKey() {
  myKeyField.selectAll();
  //todo[peter,kirillk] without these invokeLaters this requestFocus conflicts with com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.MyDialog.MyWindowListener.windowOpened()
  IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true);
  final ModalityState modalityState = ModalityState.stateForComponent(myKeyField);
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true);
            }
          }, modalityState);
        }
      }, modalityState);
    }
  }, modalityState);
}
 
Example #10
Source File: KnowledgeViewTreeBuilder.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
private void queueUpdate(@Nonnull VirtualFile fileToRefresh) {
  synchronized (myFilesToRefresh) {
    if (myFilesToRefresh.add(fileToRefresh)) {
      myUpdateProblemAlarm.cancelAllRequests();
      myUpdateProblemAlarm.addRequest(new Runnable() {
        @Override
        public void run() {
          if (!myProject.isOpen()) {
            return;
          }
          Set<VirtualFile> filesToRefresh;
          synchronized (myFilesToRefresh) {
            filesToRefresh = new THashSet<VirtualFile>(myFilesToRefresh);
          }
          final DefaultMutableTreeNode rootNode = getRootNode();
          if (rootNode != null) {
            updateNodesContaining(filesToRefresh, rootNode);
          }
          synchronized (myFilesToRefresh) {
            myFilesToRefresh.removeAll(filesToRefresh);
          }
        }
      }, 200, ModalityState.NON_MODAL);
    }
  }
}
 
Example #11
Source File: FloobitsWindowManager.java    From floobits-intellij with Apache License 2.0 6 votes vote down vote up
public void updateUserList() {
    Application app = ApplicationManager.getApplication();
    if (app == null) {
        return;
    }
    app.invokeLater(new Runnable() {
        @Override
        public void run() {
            FlooHandler flooHandler = context.getFlooHandler();
            if (flooHandler == null) {
                return;
            }
            chatForm.updateGravatars();
            chatForm.updateFollowing(flooHandler.state.followedUsers);
            updateTitle();
        }
    }, ModalityState.NON_MODAL);
}
 
Example #12
Source File: ExecutionUtil.java    From aem-ide-tooling-4-intellij with Apache License 2.0 6 votes vote down vote up
public static void queueTaskLater(final Task task) {
    final Application app = ApplicationManager.getApplication();
    if (app.isDispatchThread()) {
        task.queue();
    } else {
        app.invokeLater(
            new Runnable() {
                @Override
                public void run() {
                    task.queue();
                    String test3 = "done";
                }
            },
            ModalityState.any()
        );
        String test4 = "done";
    }
}
 
Example #13
Source File: DirDiffTableModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  if (!myDisposed && myLoadingPanel.isLoading()) {
    TimeoutUtil.sleep(mySleep);
    ApplicationManager.getApplication().invokeLater(() -> {
      final String s = text.get();
      if (s != null && myLoadingPanel.isLoading()) {
        myLoadingPanel.setLoadingText(s);
      }
    }, ModalityState.stateForComponent(myLoadingPanel));
    myUpdater = new Updater(myLoadingPanel, mySleep);
    myUpdater.start();
  } else {
    myUpdater = null;
  }
}
 
Example #14
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void runBare() throws Throwable {
  if (!shouldRunTest()) return;

  try {
    runBareImpl();
  }
  finally {
    try {
      ApplicationManager.getApplication().invokeAndWait(new Runnable() {
        @Override
        public void run() {
          cleanupApplicationCaches(getProject());
          resetAllFields();
        }
      }, ModalityState.NON_MODAL);
    }
    catch (Throwable e) {
      // Ignore
    }
  }
}
 
Example #15
Source File: ServerExecutableState.java    From CppTools with Apache License 2.0 6 votes vote down vote up
void restartProcess(Communicator communicator) {
  // will not block here since deadlock can be
  ApplicationManager.getApplication().invokeLater(
    new Runnable() {
      public void run() {
        ApplicationManager.getApplication().runWriteAction(
          new Runnable() {
            public void run() {
              FileDocumentManager.getInstance().saveAllDocuments();
            }
          }
        );
      }
    },
    ModalityState.defaultModalityState()
  );

  doDestroyProcess();
  if (communicator.getProject().isDisposed()) return;
  startProcess(communicator);
}
 
Example #16
Source File: FileRefresher.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void launch() {
  LOG.debug("launch");
  if (disposed.get() || launched.getAndSet(true)) return;
  RefreshSession session;
  synchronized (files) {
    if (this.session != null || files.isEmpty()) return;
    ModalityState state = producer.produce();
    LOG.debug("modality state ", state);
    session = RefreshQueue.getInstance().createSession(true, recursive, this::finish, state);
    session.addAllFiles(files);
    this.session = session;
  }
  scheduled.set(false);
  launched.set(false);
  LOG.debug("launched at ", System.currentTimeMillis());
  session.launch();
}
 
Example #17
Source File: NeovimIntellijComplete.java    From neovim-intellij-complete with MIT License 5 votes vote down vote up
/**
 * Hack to have up to date files when doing quickfix stuff...
 * @param path
 */
@NeovimHandler("IntellijOnWrite")
public void intellijOnWrite(String path) {
    ApplicationManager.getApplication().invokeAndWait(() -> {
        PsiFile f = EmbeditorUtil.findTargetFile(path);
        if (f != null) {
            VirtualFile vf = f.getVirtualFile();
            if (vf != null)
                vf.refresh(false, true);
        }
    }, ModalityState.any());
}
 
Example #18
Source File: LaterInvocator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static void dispatchPendingFlushes() {
  if (!isDispatchThread()) throw new IllegalStateException("Must call from EDT");

  Semaphore semaphore = new Semaphore();
  semaphore.down();
  invokeLaterWithCallback(semaphore::up, ModalityState.any(), Conditions.FALSE, null);
  while (!semaphore.isUp()) {
    UIUtil.dispatchAllInvocationEvents();
  }
}
 
Example #19
Source File: FloobitsWindowManager.java    From floobits-intellij with Apache License 2.0 5 votes vote down vote up
public void clearUsers() {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            chatForm.clearClients();
            updateTitle();
        }
    }, ModalityState.NON_MODAL);
}
 
Example #20
Source File: UiActivityMonitorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void addActivity(@Nonnull UiActivity activity, @Nonnull ModalityState effectiveModalityState) {
  if (!myToWatch.isEmpty() && !myToWatch.contains(activity)) return;

  myActivities.put(activity, new ActivityInfo(effectiveModalityState));
  myQueuedToRemove.remove(activity);

  myContainer.onActivityAdded(activity);
}
 
Example #21
Source File: BackgroundTaskQueue.java    From consulo with Apache License 2.0 5 votes vote down vote up
public BackgroundableTaskData(@Nonnull Task.Backgroundable task,
                              @Nullable ModalityState modalityState,
                              @Nullable ProgressIndicator indicator) {
  myTask = task;
  myModalityState = modalityState;
  myIndicator = indicator;
}
 
Example #22
Source File: GuiUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void invokeLaterIfNeeded(@Nonnull Runnable runnable, @Nonnull ModalityState modalityState, @Nonnull Condition expired) {
  if (ApplicationManager.getApplication().isDispatchThread()) {
    runnable.run();
  } else {
    ApplicationManager.getApplication().invokeLater(runnable, modalityState, expired);
  }
}
 
Example #23
Source File: WelcomeFrameManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void showIfNoProjectOpened() {
  myApplication.invokeLater((DumbAwareRunnable)() -> {
    WindowManagerEx windowManager = (WindowManagerEx)WindowManager.getInstance();
    windowManager.disposeRootFrame();
    IdeFrame[] frames = windowManager.getAllProjectFrames();
    if (frames.length == 0) {
      showFrame();
    }
  }, ModalityState.NON_MODAL);
}
 
Example #24
Source File: CallbackData.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static CallbackData createInteractive(@Nonnull Project project,
                                              @Nonnull InvokeAfterUpdateMode mode,
                                              @Nonnull Runnable afterUpdate,
                                              String title,
                                              @Nullable ModalityState state) {
  Task task = mode.isSynchronous()
              ? new Waiter(project, afterUpdate, title, mode.isCancellable())
              : new FictiveBackgroundable(project, afterUpdate, title, mode.isCancellable(), state);
  Runnable callback = () -> {
    logUpdateFinished(project, mode);
    setDone(task);
  };
  return new CallbackData(callback, () -> ProgressManager.getInstance().run(task));
}
 
Example #25
Source File: WeakTimerListener.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public ModalityState getModalityState() {
  TimerListener delegate = myRef.get();
  if (delegate != null) {
    return delegate.getModalityState();
  }
  else {
    ActionManagerEx.getInstanceEx().removeTimerListener(this);
    return null;
  }
}
 
Example #26
Source File: UiActivityMonitorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
boolean isOwnReady() {
  Map<UiActivity, ActivityInfo> infoToCheck = new HashMap<>();

  for (Set<UiActivity> eachActivitySet : myContainer.myActivities2Object.keySet()) {
    final BusyImpl eachBusyObject = myContainer.myActivities2Object.get(eachActivitySet);
    if (eachBusyObject == this) continue;

    for (UiActivity eachOtherActivity : eachActivitySet) {
      for (UiActivity eachToWatch : myToWatch) {
        if (eachToWatch.isSameOrGeneralFor(eachOtherActivity) && eachBusyObject.myActivities.containsKey(eachOtherActivity)) {
          infoToCheck.put(eachOtherActivity, eachBusyObject.myActivities.get(eachOtherActivity));
        }
      }
    }
  }

  infoToCheck.putAll(myActivities);

  if (infoToCheck.isEmpty()) return true;

  final ModalityState current = getCurrentState();
  for (Map.Entry<UiActivity, ActivityInfo> entry : infoToCheck.entrySet()) {
    final ActivityInfo info = entry.getValue();
    if (!current.dominates(info.getEffectiveState())) {
      return false;
    }
  }

  return true;
}
 
Example #27
Source File: ToolbarComboBoxAction.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
private Runnable setForcePressed() {
  myForcePressed = true;
  repaint();

  return () -> {
    // give the button a chance to handle action listener
    ApplicationManager.getApplication().invokeLater(() -> {
      myForcePressed = false;
      repaint();
    }, ModalityState.any());
    repaint();
    fireStateChanged();
  };
}
 
Example #28
Source File: TreeFileChooserDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void selectFile(@Nonnull final PsiFile file) {
  // Select element in the tree
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      if (myBuilder != null) {
        myBuilder.select(file, file.getVirtualFile(), true);
      }
    }
  }, ModalityState.stateForComponent(getWindow()));
}
 
Example #29
Source File: WaitForProgressToShow.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void runOrInvokeAndWaitAboveProgress(final Runnable command, @Nullable final ModalityState modalityState) {
  final Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    command.run();
  } else {
    final ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
    if (pi != null) {
      execute(pi);
      application.invokeAndWait(command, pi.getModalityState());
    } else {
      final ModalityState notNullModalityState = modalityState == null ? ModalityState.NON_MODAL : modalityState;
      application.invokeAndWait(command, notNullModalityState);
    }
  }
}
 
Example #30
Source File: EmbeddedLinuxJVMConsoleView.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Clears text on console
 */
public void clear() {
    if (consoleView.isShowing()) {
        consoleView.clear();
    } else {
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
            @Override
            public void run() {
                consoleView.flushDeferredText();
            }
        }, ModalityState.NON_MODAL);
    }
}