Java Code Examples for com.intellij.util.ui.UIUtil#invokeAndWaitIfNeeded()

The following examples show how to use com.intellij.util.ui.UIUtil#invokeAndWaitIfNeeded() . 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: MavenImportingTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private void doImportProjects(final List<VirtualFile> files, boolean failOnReadingError, String... profiles) {
  initProjectsManager(false);

  readProjects(files, profiles);

  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    myProjectsManager.waitForResolvingCompletion();
    myProjectsManager.scheduleImportInTests(files);
    myProjectsManager.importProjects();
  });

  if (failOnReadingError) {
    for (MavenProject each : myProjectsTree.getProjects()) {
      assertFalse("Failed to import Maven project: " + each.getProblems(), each.hasReadingProblems());
    }
  }
}
 
Example 2
Source File: ExternalChangesAndRefreshingTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  if (getName().equals("testRefreshingAsynchronously")) {
    // this methods waits for another thread to finish, that leads
    // to deadlock in swing-thread. Therefore we have to run this test
    // outside of swing-thread
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        try {
          ExternalChangesAndRefreshingTest.super.tearDown();
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  }
  else {
    super.tearDown();
  }
}
 
Example 3
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();

  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      try {
        myProjectFixture.setUp();
        myTempDirFixture.setUp();
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }
      myPsiManager = (PsiManagerImpl)PsiManager.getInstance(getProject());
      configureInspections(myInspections == null ? LocalInspectionTool.EMPTY_ARRAY : myInspections);

      DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject());
      daemonCodeAnalyzer.prepareForTest();

      DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false);
      ensureIndexesUpToDate(getProject());
      ((StartupManagerImpl)StartupManagerEx.getInstanceEx(getProject())).runPostStartupActivities(UIAccess.get());
    }
  });
}
 
Example 4
Source File: AbstractRunConfigurationTypeUsagesCollector.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public final Set<UsageDescriptor> getProjectUsages(@Nonnull final Project project) {
  final Set<String> runConfigurationTypes = new HashSet<String>();
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      if (project.isDisposed()) return;
      final RunManager runManager = RunManager.getInstance(project);
      for (RunConfiguration runConfiguration : runManager.getAllConfigurationsList()) {
        if (runConfiguration != null && isApplicable(runManager, runConfiguration)) {
          final ConfigurationFactory configurationFactory = runConfiguration.getFactory();
          final ConfigurationType configurationType = configurationFactory.getType();
          final StringBuilder keyBuilder = new StringBuilder();
          keyBuilder.append(configurationType.getId());
          if (configurationType.getConfigurationFactories().length > 1) {
            keyBuilder.append(".").append(configurationFactory.getName());
          }
          runConfigurationTypes.add(keyBuilder.toString());
        }
      }
    }
  });
  return ContainerUtil.map2Set(runConfigurationTypes, runConfigurationType -> new UsageDescriptor(runConfigurationType, 1));
}
 
Example 5
Source File: Inspect.java    From neovim-intellij-complete with MIT License 6 votes vote down vote up
/**
 * Invokes action in intentionActionDescriptor on file found in path and writes the file to disk.
 *
 * @param path
 * @param fileContent
 * @param intentionActionDescriptor
 * @return
 */
public static String doFix(String path, @Nullable String fileContent, HighlightInfo.IntentionActionDescriptor intentionActionDescriptor) {
    UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
        PsiFile psiFile = EmbeditorUtil.findTargetFile(path);
        Project project = psiFile.getProject();

        PsiFile fileCopy = fileContent != null
                ? EmbeditorUtil.createDummyPsiFile(project, fileContent, psiFile)
                : EmbeditorUtil.createDummyPsiFile(project, psiFile.getText(), psiFile);

        VirtualFile targetVirtualFile =  psiFile.getVirtualFile();
        Document document = fileCopy.getViewProvider().getDocument();

        Editor editor = EditorFactory.getInstance().createEditor(document, project, targetVirtualFile, false);

        intentionActionDescriptor.getAction().invoke(project, editor, fileCopy);

        FileDocumentManager.getInstance().saveDocument(psiFile.getViewProvider().getDocument());
    });
    return null;
}
 
Example 6
Source File: TreeUiTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void buildSiblings(final Node node, final int start, final int end, @Nullable final Runnable eachRunnable, @javax.annotation.Nullable final Runnable endRunnable)
        throws InvocationTargetException, InterruptedException {
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      for (int i = start; i <= end; i++) {
        Node eachFile = node.addChild("File " + i);
        myAutoExpand.add(eachFile.getElement());
        eachFile.addChild("message 1 for " + i);
        eachFile.addChild("message 2 for " + i);

        if (eachRunnable != null) {
          eachRunnable.run();
        }
      }

      if (endRunnable != null) {
        endRunnable.run();
      }
    }
  });
}
 
Example 7
Source File: VfsTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void deleteFile(VirtualFile virtualFile) {
  Ref<Exception> exceptionRef = Ref.create();
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    try {
      WriteAction.run(() -> virtualFile.delete(null));
    }
    catch (IOException e) {
      exceptionRef.set(e);
    }
  });

  ExceptionUtil.rethrowAllAsUnchecked(exceptionRef.get());
}
 
Example 8
Source File: FormattingProgressTask.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepare(@Nonnull final SequentialTask task) {
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      Document document = myDocument.get();
      if (document != null) {
        myDocumentModificationStampBefore = document.getModificationStamp();
      }
      task.prepare();
    }
  });
}
 
Example 9
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public LookupElement[] complete(final CompletionType type, final int invocationCount) {
  assertInitialized();
  myEmptyLookup = false;
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
          final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(type) {
            @Override
            protected void completionFinished(CompletionProgressIndicator indicator, boolean hasModifiers) {
              myEmptyLookup = indicator.getLookup().getItems().isEmpty();
              super.completionFinished(indicator, hasModifiers);
            }
          };
          Editor editor = getCompletionEditor();
          handler.invokeCompletion(getProject(), editor, invocationCount);
          PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); // to compare with file text
        }
      }, null, null);
    }
  });

  return getLookupElements();
}
 
Example 10
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 11
Source File: VcsIntegrationEnabler.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static void refreshVcsDir(@Nonnull final VirtualFile projectDir, @Nonnull final String vcsDirName) {
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDir.getPath() + "/" + vcsDirName);
        }
      });
    }
  });
}
 
Example 12
Source File: ConsoleViewImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void disposeEditor() {
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    if (!myEditor.isDisposed()) {
      EditorFactory.getInstance().releaseEditor(myEditor);
    }
  });
}
 
Example 13
Source File: VfsUtilTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      try {
        VfsUtilTest.super.tearDown();
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  });
}
 
Example 14
Source File: NameValidatorTest.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void tearDown() throws Throwable {
    UIUtil.invokeAndWaitIfNeeded((ThrowableRunnable) () -> fixture.tearDown());
}
 
Example 15
Source File: DesktopEditorsSplitters.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected JPanel processFiles(@Nonnull List<Element> fileElements, final JPanel context, Element parent, UIAccess uiAccess) {
  final Ref<DesktopEditorWindow> windowRef = new Ref<>();
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    DesktopEditorWindow editorWindow = context == null ? createEditorWindow() : findWindowWith(context);
    windowRef.set(editorWindow);
    if (editorWindow != null) {
      updateTabSizeLimit(editorWindow, parent.getAttributeValue(JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY.toString()));
    }
  });

  final DesktopEditorWindow window = windowRef.get();
  LOG.assertTrue(window != null);
  VirtualFile focusedFile = null;

  for (int i = 0; i < fileElements.size(); i++) {
    final Element file = fileElements.get(i);
    Element historyElement = file.getChild(HistoryEntry.TAG);
    String fileName = historyElement.getAttributeValue(HistoryEntry.FILE_ATTR);
    Activity activity = StartUpMeasurer.startActivity(PathUtil.getFileName(fileName), ActivityCategory.REOPENING_EDITOR);
    VirtualFile virtualFile = null;
    try {
      final FileEditorManagerImpl fileEditorManager = getManager();
      final HistoryEntry entry = HistoryEntry.createLight(fileEditorManager.getProject(), historyElement);
      virtualFile = entry.getFile();
      if (virtualFile == null) throw new InvalidDataException("No file exists: " + entry.getFilePointer().getUrl());
      virtualFile.putUserData(OPENED_IN_BULK, Boolean.TRUE);
      VirtualFile finalVirtualFile = virtualFile;
      Document document = ReadAction.compute(() -> finalVirtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(finalVirtualFile) : null);

      boolean isCurrentTab = Boolean.valueOf(file.getAttributeValue(CURRENT_IN_TAB)).booleanValue();
      FileEditorOpenOptions openOptions = new FileEditorOpenOptions().withPin(Boolean.valueOf(file.getAttributeValue(PINNED))).withIndex(i).withReopeningEditorsOnStartup();

      fileEditorManager.openFileImpl4(uiAccess, window, virtualFile, entry, openOptions);
      if (isCurrentTab) {
        focusedFile = virtualFile;
      }
      if (document != null) {
        // This is just to make sure document reference is kept on stack till this point
        // so that document is available for folding state deserialization in HistoryEntry constructor
        // and that document will be created only once during file opening
        document.putUserData(DUMMY_KEY, null);
      }
      updateProgress();
    }
    catch (InvalidDataException e) {
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        LOG.error(e);
      }
    }
    finally {
      if (virtualFile != null) virtualFile.putUserData(OPENED_IN_BULK, null);
    }
    activity.end();
  }
  if (focusedFile != null) {
    getManager().addSelectionRecord(focusedFile, window);
    VirtualFile finalFocusedFile = focusedFile;
    uiAccess.giveAndWaitIfNeed(() -> {
      EditorWithProviderComposite editor = window.findFileComposite(finalFocusedFile);
      if (editor != null) {
        window.setEditor(editor, true, true);
      }
    });
  }
  else {
    ToolWindowManager manager = ToolWindowManager.getInstance(getManager().getProject());
    manager.invokeLater(() -> {
      if (null == manager.getActiveToolWindowId()) {
        ToolWindow toolWindow = manager.getToolWindow(ToolWindowId.PROJECT_VIEW);
        if (toolWindow != null) toolWindow.activate(null);
      }
    });
  }
  return window.myPanel;
}
 
Example 16
Source File: AbstractDataGetter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void saveInCache(@Nonnull TIntObjectHashMap<T> details) {
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> details.forEachEntry((key, value) -> {
    myCache.put(key, value);
    return true;
  }));
}
 
Example 17
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void type(final char c) {
  assertInitialized();
  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      final EditorActionManager actionManager = EditorActionManager.getInstance();
      if (c == '\b') {
        performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE);
        return;
      }
      if (c == '\n') {
        if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM)) {
          return;
        }

        performEditorAction(IdeActions.ACTION_EDITOR_ENTER);
        return;
      }
      if (c == '\t') {
        if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE)) {
          return;
        }
        if (_performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)) {
          return;
        }
        if (_performEditorAction(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)) {
          return;
        }
        if (_performEditorAction(IdeActions.ACTION_EDITOR_TAB)) {
          return;
        }
      }
      if (c == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
        if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)) {
          return;
        }
      }

      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
          CommandProcessor.getInstance().setCurrentCommandGroupId(myEditor.getDocument());
          ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext());
          actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext());
        }
      }, null, DocCommandGroupId.noneGroupId(myEditor.getDocument()));
    }
  });
}
 
Example 18
Source File: DesktopApplicationImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public DesktopApplicationImpl(boolean isHeadless, @Nonnull Ref<? extends StartupProgress> splashRef) {
  super(splashRef);

  ApplicationManager.setApplication(this);

  AWTExceptionHandler.register(); // do not crash AWT on exceptions

  myIsInternal = ApplicationProperties.isInternal();

  String debugDisposer = System.getProperty("idea.disposer.debug");
  consulo.disposer.Disposer.setDebugMode((myIsInternal || "on".equals(debugDisposer)) && !"off".equals(debugDisposer));

  myHeadlessMode = isHeadless;

  myDoNotSave = isHeadless;
  myGatherStatistics = LOG.isDebugEnabled() || isInternal();

  if (!isHeadless) {
    consulo.disposer.Disposer.register(this, Disposable.newDisposable(), "ui");

    StartupUtil.addExternalInstanceListener(commandLineArgs -> {
      LOG.info("ApplicationImpl.externalInstanceListener invocation");

      CommandLineProcessor.processExternalCommandLine(commandLineArgs, null).doWhenDone(project -> {
        final IdeFrame frame = WindowManager.getInstance().getIdeFrame(project);

        if (frame != null) AppIcon.getInstance().requestFocus(frame);
      });
    });

    WindowsCommandLineProcessor.LISTENER = (currentDirectory, commandLine) -> {
      LOG.info("Received external Windows command line: current directory " + currentDirectory + ", command line " + commandLine);
      invokeLater(() -> {
        final List<String> args = StringUtil.splitHonorQuotes(commandLine, ' ');
        args.remove(0);   // process name
        CommandLineProcessor.processExternalCommandLine(CommandLineArgs.parse(ArrayUtil.toStringArray(args)), currentDirectory);
      });
    };
  }

  Thread edt = UIUtil.invokeAndWaitIfNeeded(() -> {
    // instantiate AppDelayQueue which starts "Periodic task thread" which we'll mark busy to prevent this EDT to die
    // that thread was chosen because we know for sure it's running
    AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService();
    Thread thread = service.getPeriodicTasksThread();
    AWTAutoShutdown.getInstance().notifyThreadBusy(thread); // needed for EDT not to exit suddenly
    consulo.disposer.Disposer.register(this, () -> {
      AWTAutoShutdown.getInstance().notifyThreadFree(thread); // allow for EDT to exit - needed for Upsource
    });
    return Thread.currentThread();
  });

  NoSwingUnderWriteAction.watchForEvents(this);
}
 
Example 19
Source File: EmbeditorUtil.java    From neovim-intellij-complete with MIT License 4 votes vote down vote up
public static void performCompletion(@NotNull final String path,
                                     @Nullable final String fileContent,
                                     final int line,
                                     final int column,
                                     @NotNull final CompletionCallback completionCallback) {
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
        @Override
        public void run() {
            final PsiFile targetPsiFile = findTargetFile(path);
            final VirtualFile targetVirtualFile = targetPsiFile != null ? targetPsiFile.getVirtualFile() : null;
            if (targetPsiFile != null && targetVirtualFile != null) {
                final EditorFactory editorFactory = EditorFactory.getInstance();
                final Project project = targetPsiFile.getProject();
                final Document originalDocument = PsiDocumentManager.getInstance(project).getDocument(targetPsiFile);
                if (originalDocument != null) {

                    PsiFile fileCopy = fileContent != null
                            ? createDummyPsiFile(project, fileContent, targetPsiFile)
                            : createDummyPsiFile(project, targetPsiFile.getText(), targetPsiFile);
                    final Document document = fileCopy.getViewProvider().getDocument();
                    if (document != null) {
                        final Editor editor = editorFactory.createEditor(document, project, targetVirtualFile, false);
                        int offset = lineAndColumnToOffset(document, line, column);
                        editor.getCaretModel().moveToOffset(offset);
                        CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                            @Override
                            public void run() {
                                final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(CompletionType.BASIC) {

                                    @Override
                                    protected void completionFinished(@NotNull CompletionProgressIndicator indicator,
                                                                      boolean hasModifiers) {
                                        CompletionServiceImpl.setCompletionPhase(new CompletionPhase.ItemsCalculated(indicator));
                                        completionCallback.completionFinished(indicator.getParameters(), indicator, document);
                                    }
                                };

                                handler.invokeCompletion(project, editor);
                            }
                        }, null, null);
                    }
                }
            }
        }
    });
}
 
Example 20
Source File: UsefulTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void edt(Runnable r) {
  UIUtil.invokeAndWaitIfNeeded(r);
}