Java Code Examples for com.intellij.openapi.application.ModalityState

The following examples show how to use com.intellij.openapi.application.ModalityState. These examples are extracted from open source projects. 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 Project: consulo   Source File: FileRefresher.java    License: 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 2
Source Project: floobits-intellij   Source File: FloobitsWindowManager.java    License: 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 3
Source Project: consulo   Source File: LiveTemplateSettingsEditor.java    License: 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 4
Source Project: consulo   Source File: HTMLExportUtil.java    License: 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 5
Source Project: consulo   Source File: CtrlMouseHandler.java    License: 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 6
Source Project: CppTools   Source File: ServerExecutableState.java    License: 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 7
Source Project: consulo   Source File: UiNotifyConnector.java    License: 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 8
Source Project: protobuf-jetbrains-plugin   Source File: GoToClassTest.java    License: 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 Project: saros   Source File: SafeDialogUtils.java    License: 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 10
Source Project: consulo   Source File: DirDiffTableModel.java    License: 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 11
Source Project: aem-ide-tooling-4-intellij   Source File: ExecutionUtil.java    License: 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 12
Source Project: consulo   Source File: DesktopEditorImpl.java    License: 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 13
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 14
Source Project: consulo   Source File: InstalledPackagesPanel.java    License: 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 15
Source Project: consulo   Source File: ErrorDiffTool.java    License: 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 16
Source Project: consulo   Source File: PlatformTestCase.java    License: 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 17
Source Project: consulo   Source File: CommitChangeListDialog.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void refresh() {
  ChangeListManager.getInstance(myProject).invokeAfterUpdate(new Runnable() {
    @Override
    public void run() {
      myBrowser.rebuildList();
      for (RefreshableOnComponent component : myAdditionalComponents) {
        component.refresh();
      }
    }
  }, InvokeAfterUpdateMode.SILENT, "commit dialog", ModalityState.current());   // title not shown for silently
}
 
Example 18
Source Project: consulo   Source File: LineStatusTrackerManager.java    License: Apache License 2.0 5 votes vote down vote up
private void nonModalAliveInvokeLater(@Nonnull Runnable runnable) {
  myApplication.invokeLater(runnable, ModalityState.NON_MODAL, new Condition() {
    @Override
    public boolean value(final Object ignore) {
      return isDisabled();
    }
  });
}
 
Example 19
Source Project: CppTools   Source File: BuildState.java    License: Apache License 2.0 5 votes vote down vote up
public static void invokeOnEDTSynchroneously(Runnable saveRunnable) {
  if (ApplicationManager.getApplication().isDispatchThread()) {
    saveRunnable.run();
  }
  else {
    ApplicationManager.getApplication().invokeAndWait(saveRunnable, ModalityState.defaultModalityState());
  }
}
 
Example 20
Source Project: consulo   Source File: DirectoryChooser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected JComponent createCenterPanel(){
  final JPanel panel = new JPanel(new BorderLayout());

  final DefaultActionGroup actionGroup = new DefaultActionGroup();
  actionGroup.add(new FilterExistentAction());
  final JComponent toolbarComponent = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actionGroup, true).getComponent();
  toolbarComponent.setBorder(null);
  panel.add(toolbarComponent, BorderLayout.NORTH);

  final Runnable runnable = new Runnable() {
    @Override
    public void run() {
      enableButtons();
    }
  };
  myView.onSelectionChange(runnable);
  final JComponent component = myView.getComponent();
  final JScrollPane jScrollPane = ScrollPaneFactory.createScrollPane(component);
  //noinspection HardCodedStringLiteral
  int prototypeWidth = component.getFontMetrics(component.getFont()).stringWidth("X:\\1234567890\\1234567890\\com\\company\\system\\subsystem");
  jScrollPane.setPreferredSize(new Dimension(Math.max(300, prototypeWidth),300));

  installEnterAction(component);
  panel.add(jScrollPane, BorderLayout.CENTER);
  myTabbedPaneWrapper.addTab("Directory Structure", panel);

  myChooseByNamePanel.invoke(new ChooseByNamePopupComponent.Callback() {
    @Override
    public void elementChosen(Object element) {
      setSelection(element);
    }
  }, ModalityState.stateForComponent(getRootPane()), false);
  myTabbedPaneWrapper.addTab("Choose By Neighbor Class", myChooseByNamePanel.getPanel());

  return myTabbedPaneWrapper.getComponent();
}
 
Example 21
Source Project: consulo   Source File: BreadcrumbsWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private void updateCrumbs() {
  if (myEditor == null || myFile == null || myEditor.isDisposed()) return;

  Document document = myEditor.getDocument();
  int offset = myEditor.getCaretModel().getOffset();
  Boolean forcedShown = BreadcrumbsForceShownSettings.getForcedShown(myEditor);
  ReadAction.nonBlocking(() -> myBreadcrumbsCollector.computeCrumbs(myFile, document, offset, forcedShown)).withDocumentsCommitted(myProject).expireWith(this).coalesceBy(this)
          .finishOnUiThread(ModalityState.any(), (_crumbs) -> {
            Iterable<? extends Crumb> crumbs = breadcrumbs.isShowing() || ApplicationManager.getApplication().isHeadlessEnvironment() ? _crumbs : EMPTY_BREADCRUMBS;
            breadcrumbs.setFont(getNewFont(myEditor));
            breadcrumbs.setCrumbs(crumbs);
            notifyListeners(crumbs);
          }).submit(NonUrgentExecutor.getInstance());
}
 
Example 22
Source Project: PackageTemplates   Source File: FileWriter.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean wrapInWriteLater(Computable<Boolean> computable) {
    final boolean[] result = new boolean[1];

    ApplicationManager.getApplication().invokeAndWait(() ->
            result[0] = ApplicationManager.getApplication().runWriteAction(computable),
            ModalityState.defaultModalityState());

    return result[0];
}
 
Example 23
Source Project: consulo   Source File: HttpConfigurable.java    License: Apache License 2.0 5 votes vote down vote up
private static void runAboveAll(@Nonnull final Runnable runnable) {
  ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
  if (progressIndicator != null && progressIndicator.isModal()) {
    WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(runnable);
  }
  else {
    Application app = ApplicationManager.getApplication();
    app.invokeAndWait(runnable, ModalityState.any());
  }
}
 
Example 24
Source Project: PackageTemplates   Source File: InjectTextAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doRun() {
    ApplicationManager.getApplication().invokeAndWait(() -> {
        CommandProcessor.getInstance().executeCommand(project, () -> {
            ApplicationManager.getApplication().runWriteAction(() -> {
                doRunInWriteThread();
            });
        }, getClass().getSimpleName(), getClass().getSimpleName());
    }, ModalityState.defaultModalityState());
}
 
Example 25
Source Project: railways   Source File: RoutesView.java    License: MIT License 5 votes vote down vote up
@Override
public void modificationCountChanged() {
    if (PowerSaveMode.isEnabled() ||
            myToolWindow == null || !myToolWindow.isVisible() ||
            !isLiveHighlightingEnabled())
        return;

    alarm.cancelAllRequests();
    alarm.addRequest(RoutesView.this::refreshRouteActionsStatus, 1000, ModalityState.NON_MODAL);
}
 
Example 26
Source Project: consulo   Source File: ChangeListManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void invokeAfterUpdate(final Runnable afterUpdate,
                              final InvokeAfterUpdateMode mode,
                              final String title,
                              final Consumer<VcsDirtyScopeManager> dirtyScopeManagerFiller,
                              final ModalityState state) {
  myUpdater.invokeAfterUpdate(afterUpdate, mode, title, dirtyScopeManagerFiller, state);
}
 
Example 27
Source Project: consulo   Source File: FileWatcher.java    License: Apache License 2.0 5 votes vote down vote up
public void notifyOnFailure(@Nonnull String cause, @Nullable NotificationListener listener) {
  LOG.warn(cause);

  if (myFailureShown.compareAndSet(false, true)) {
    NotificationGroup group = NOTIFICATION_GROUP.getValue();
    String title = ApplicationBundle.message("watcher.slow.sync");
    ApplicationManager.getApplication().invokeLater(() -> Notifications.Bus.notify(group.createNotification(title, cause, NotificationType.WARNING, listener)), ModalityState.NON_MODAL);
  }
}
 
Example 28
Source Project: intellij-pants-plugin   Source File: PantsMakeBeforeRun.java    License: Apache License 2.0 5 votes vote down vote up
private void prepareIDE(Project project) {
  ApplicationManager.getApplication().invokeAndWait(() -> {
    /* Clear message window. */
    ConsoleView executionConsole = PantsConsoleManager.getConsole(project);
    executionConsole.getComponent().setVisible(true);
    executionConsole.clear();
    ToolWindowManagerEx.getInstance(project).getToolWindow(PantsConstants.PANTS_CONSOLE_NAME).activate(null);
  }, ModalityState.NON_MODAL);
}
 
Example 29
Source Project: consulo   Source File: BackgroundTaskQueue.java    License: 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 30
Source Project: consulo   Source File: TreeFileChooserDialog.java    License: 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()));
}