com.intellij.openapi.application.ApplicationManager Java Examples

The following examples show how to use com.intellij.openapi.application.ApplicationManager. 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: IntelliJIDEA.java    From intellijcoder with MIT License 6 votes vote down vote up
public void createModule(final String moduleName, final String className, final String classSource, final String testSource, final String htmlSource, final int memLimit) {
    //We run it in the event thread, so the DataContext would have current Project data;
    DumbService.getInstance(project).smartInvokeLater(new Runnable() {
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    try {
                        IntelliJIDEA.this.createModule(getCurrentProject(), moduleName, className, classSource, testSource, htmlSource, memLimit);
                    } catch (IntelliJCoderException e) {
                        showErrorMessage("Failed to create problem workspace. " + e.getMessage());
                    }
                }
            });
        }
    });
}
 
Example #2
Source File: FlutterSmallIDEProjectGenerator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void applyDartModule(FlutterSdk sdk, Project project, Module module, PubRoot root) {
  ApplicationManager.getApplication().runWriteAction(() -> {
    // Set up Dart SDK.
    final String dartSdkPath = sdk.getDartSdkPath();
    if (dartSdkPath == null) {
      FlutterMessages.showError("Error creating project", "unable to get Dart SDK"); // shouldn't happen; we just created it.
      return;
    }
    DartPlugin.ensureDartSdkConfigured(project, sdk.getDartSdkPath());
    DartPlugin.enableDartSdk(module);
    FlutterSdkUtil.updateKnownSdkPaths(sdk.getHomePath());

    // Set up module.
    final ModifiableRootModel modifiableModel = ModifiableModelsProvider.SERVICE.getInstance().getModuleModifiableModel(module);
    modifiableModel.addContentEntry(root.getRoot());
    ModifiableModelsProvider.SERVICE.getInstance().commitModuleModifiableModel(modifiableModel);

    FlutterModuleUtils.autoShowMain(project, root);
  });
}
 
Example #3
Source File: RefactoringsApplier.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
public static void moveRefactoring(final @NotNull List<MoveMethodRefactoring> refactorings) {
    if (!checkValid(refactorings)) {
        throw new IllegalArgumentException("Methods in refactorings list must be unique!");
    }

    final Map<PsiClass, List<MoveMethodRefactoring>> groupedRefactorings = prepareRefactorings(refactorings);

    ApplicationManager.getApplication().runReadAction(() -> {
        for (Map.Entry<PsiClass, List<MoveMethodRefactoring>> refactoring : groupedRefactorings.entrySet()) {
            final PsiClass target = refactoring.getKey();
            refactoring.getValue().forEach(r -> {
                if (canMoveInstanceMethod(r.getMethod(), target)) {
                    moveInstanceMethod(r, target);
                    if (!r.getOptionalMethod().isPresent()) {
                        IntelliJDeodorantCounterCollector.getInstance().moveMethodRefactoringApplied(target.getProject(),
                                r.getSourceAccessedMembers(), r.getTargetAccessedMembers(),
                                r.getMethodLength(), r.getMethodParametersCount());
                    }
                }
            });
        }
    });
}
 
Example #4
Source File: ExtensionProviderUtil.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@NotNull
private static Collection<JsonRegistrar> getTypesInner(@NotNull Project project) {
    Collection<JsonRegistrar> jsonRegistrars = new ArrayList<>();
    PhpToolboxApplicationService component = ApplicationManager.getApplication().getComponent(PhpToolboxApplicationService.class);
    if(component == null) {
        return jsonRegistrars;
    }

    for(JsonConfigFile jsonConfig: getJsonConfigs(project, component)) {
        Collection<JsonRegistrar> registrar = jsonConfig.getRegistrar();
        for (JsonRegistrar jsonRegistrar : registrar) {
            if(
                !"php".equals(jsonRegistrar.getLanguage()) ||
                ContainerUtil.find(jsonRegistrar.getSignatures(), ContainerConditions.RETURN_TYPE_TYPE) == null
              )
            {
                continue;
            }

            jsonRegistrars.addAll(registrar);
        }
    }

    return jsonRegistrars;
}
 
Example #5
Source File: OnCodeAnalysisFinishedListenerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void daemonFinished_settingsTrue_resolved() throws IOException {
  final PsiFile specPsiFile = testHelper.configure("LayoutSpec.java");
  testHelper.configure("ResolveRedSymbolsActionTest.java");
  final Project project = testHelper.getFixture().getProject();
  AppSettingsState.getInstance(project).getState().resolveRedSymbols = true;
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            PsiSearchUtils.addMock(
                "LayoutSpec", PsiTreeUtil.findChildOfType(specPsiFile, PsiClass.class));
            new OnCodeAnalysisFinishedListener(project).daemonFinished();
          });
  final PsiClass cached = ComponentsCacheService.getInstance(project).getComponent("Layout");
  assertThat(cached).isNotNull();
}
 
Example #6
Source File: AbstractLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static void removeFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
  final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();

  try {
    boolean wasFound = false;

    for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
      if (orderEntry instanceof LibraryOrderEntry &&
          LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
          StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
        wasFound = true;
        modifiableModel.removeOrderEntry(orderEntry);
      }
    }

    if (wasFound) {
      ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
    }
  }
  finally {
    if (!modifiableModel.isDisposed()) {
      modifiableModel.dispose();
    }
  }
}
 
Example #7
Source File: EditorBasedStatusBarPopup.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void install(@Nonnull StatusBar statusBar) {
  super.install(statusBar);
  registerCustomListeners();
  EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      updateForDocument(document);
    }
  }, this);
  if (myWriteableFileRequired) {
    ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new VirtualFileListener() {
      @Override
      public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
        if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) {
          updateForFile(event.getFile());
        }
      }
    }));
  }
}
 
Example #8
Source File: GeneratedFilesListenerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void after_Remove() throws IOException {
  final Project project = testHelper.getFixture().getProject();
  final GeneratedFilesListener listener = new GeneratedFilesListener(project);
  final PsiFile file = testHelper.configure("LayoutSpec.java");
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            final PsiClass cls = PsiTreeUtil.findChildOfType(file, PsiClass.class);
            // Add file to cache
            final ComponentsCacheService service = ComponentsCacheService.getInstance(project);
            service.maybeUpdate(cls, false);
            final PsiClass component = service.getComponent("Layout");
            assertThat(component).isNotNull();

            // Mock file created and found on disk
            final VFileEvent mockEvent = mockEvent();
            PsiSearchUtils.addMock("Layout", cls);
            listener.after(Collections.singletonList(mockEvent));
            // Ensure cache is cleaned
            final PsiClass component2 = service.getComponent("Layout");
            assertThat(component2).isNull();
          });
}
 
Example #9
Source File: VmServiceWrapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void attachIsolate(@NotNull IsolateRef isolateRef, @NotNull Isolate isolate) {
  final boolean newIsolate = myIsolatesInfo.addIsolate(isolateRef);
  // Just to make sure that the main isolate is not handled twice, both from handleDebuggerConnected() and DartVmServiceListener.received(PauseStart)
  if (newIsolate) {
    final XDebugSessionImpl session = (XDebugSessionImpl)myDebugProcess.getSession();
    ApplicationManager.getApplication().runReadAction(() -> {
      session.reset();
      session.initBreakpoints();
    });
    addRequest(() -> myVmService.setExceptionPauseMode(isolateRef.getId(),
                                                       myDebugProcess.getBreakOnExceptionMode(),
                                                       new VmServiceConsumers.SuccessConsumerWrapper() {
                                                         @Override
                                                         public void received(Success response) {
                                                           setInitialBreakpointsAndCheckExtensions(isolateRef, isolate);
                                                         }
                                                       }));
  }
}
 
Example #10
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 #11
Source File: ModuleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void fireErrors(final List<ModuleLoadingErrorDescription> errors) {
  if (errors.isEmpty()) return;

  myModuleModel.myModulesCache = null;
  for (ModuleLoadingErrorDescription error : errors) {
    String dirUrl = error.getModuleLoadItem().getDirUrl();
    if (dirUrl == null) {
      continue;
    }
    final Module module = myModuleModel.removeModuleByDirUrl(dirUrl);
    if (module != null) {
      ApplicationManager.getApplication().invokeLater(() -> Disposer.dispose(module));
    }
  }

  if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
    throw new RuntimeException(errors.get(0).getDescription());
  }

  ProjectLoadingErrorsNotifier.getInstance(myProject).registerErrors(errors);
}
 
Example #12
Source File: CoverageViewManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
void closeView(String displayName) {
  final CoverageView oldView = myViews.get(displayName);
  if (oldView != null) {
    final Content content = myContentManager.getContent(oldView);
    final Runnable runnable = new Runnable() {
      public void run() {
        if (content != null) {
          myContentManager.removeContent(content, true);
        }
        Disposer.dispose(oldView);
      }
    };
    ApplicationManager.getApplication().invokeLater(runnable);
  }
  setReady(false);
}
 
Example #13
Source File: ShowUsagesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static MyModel setTableModel(@Nonnull JTable table,
                                     @Nonnull UsageViewImpl usageView,
                                     @Nonnull final List<UsageNode> data,
                                     @Nonnull AtomicInteger outOfScopeUsages,
                                     @Nonnull SearchScope searchScope) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  final int columnCount = calcColumnCount(data);
  MyModel model = table.getModel() instanceof MyModel ? (MyModel)table.getModel() : null;
  if (model == null || model.getColumnCount() != columnCount) {
    model = new MyModel(data, columnCount);
    table.setModel(model);

    ShowUsagesTableCellRenderer renderer = new ShowUsagesTableCellRenderer(usageView, outOfScopeUsages, searchScope);
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
      TableColumn column = table.getColumnModel().getColumn(i);
      column.setPreferredWidth(0);
      column.setCellRenderer(renderer);
    }
  }
  return model;
}
 
Example #14
Source File: RunANTLROnGrammarFile.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static boolean hasPackageDeclarationInHeader(Project project, VirtualFile grammarFile) {
	return ApplicationManager.getApplication().runReadAction((Computable<Boolean>) () -> {
		PsiFile file = PsiManager.getInstance(project).findFile(grammarFile);
		GrammarSpecNode grammarSpecNode = getChildOfType(file, GrammarSpecNode.class);

		if ( grammarSpecNode != null ) {
			RuleIElementType prequelElementType = ANTLRv4TokenTypes.getRuleElementType(ANTLRv4Parser.RULE_prequelConstruct);

			for ( PsiElement prequelConstruct : findChildrenOfType(grammarSpecNode, prequelElementType) ) {
				AtAction atAction = getChildOfType(prequelConstruct, AtAction.class);

				if ( atAction!=null && atAction.getIdText().equals("header") ) {
					return PACKAGE_DEFINITION_REGEX.matcher(atAction.getActionBlockText()).find();
				}
			}
		}

		return false;
	});
}
 
Example #15
Source File: EditorFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Inject
public EditorFactoryImpl(Application application) {
  MessageBusConnection busConnection = application.getMessageBus().connect();
  busConnection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
    @Override
    public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
      // validate all editors are disposed after fireProjectClosed() was called, because it's the place where editor should be released
      Disposer.register(project, () -> {
        Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
        boolean isLastProjectClosed = openProjects.length == 0;
        // EditorTextField.releaseEditorLater defer releasing its editor; invokeLater to avoid false positives about such editors.
        ApplicationManager.getApplication().invokeLater(() -> validateEditorsAreReleased(project, isLastProjectClosed));
      });
    }
  });
  busConnection.subscribe(EditorColorsManager.TOPIC, scheme -> refreshAllEditors());

  LaterInvocator.addModalityStateListener(new ModalityStateListener() {
    @Override
    public void beforeModalityStateChanged(boolean entering) {
      for (Editor editor : myEditors) {
        ((DesktopEditorImpl)editor).beforeModalityStateChanged();
      }
    }
  }, ApplicationManager.getApplication());
}
 
Example #16
Source File: ANTLRv4ExternalAnnotator.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Called 3rd */
@Override
public void apply(@NotNull PsiFile file,
				  List<GrammarIssue> issues,
				  @NotNull AnnotationHolder holder)
{
	for ( GrammarIssue issue : issues ) {
		if ( issue.getOffendingTokens().isEmpty() ) {
			annotateFileIssue(file, holder, issue);
		} else {
			annotateIssue(file, holder, issue);
		}
	}

	final ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(file.getProject());
	if ( controller!=null && !ApplicationManager.getApplication().isUnitTestMode() ) {
		controller.getPreviewPanel().autoRefreshPreview(file.getVirtualFile());
	}
}
 
Example #17
Source File: SimpleDiffPanelState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private LineBlocks addMarkup(final List<LineFragment> lines) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    public void run() {
      final FragmentHighlighterImpl fragmentHighlighter = new FragmentHighlighterImpl(myAppender1, myAppender2);
      for (Iterator<LineFragment> iterator = lines.iterator(); iterator.hasNext();) {
        LineFragment line = iterator.next();
        fragmentHighlighter.setIsLast(!iterator.hasNext());
        line.highlight(fragmentHighlighter);
      }
    }
  });
  ArrayList<LineFragment> allLineFragments = new ArrayList<LineFragment>();
  for (LineFragment lineFragment : lines) {
    allLineFragments.add(lineFragment);
    lineFragment.addAllDescendantsTo(allLineFragments);
  }
  myFragmentList = FragmentListImpl.fromList(allLineFragments);
  return LineBlocks.fromLineFragments(allLineFragments);
}
 
Example #18
Source File: ChangesViewManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshView() {
  if (myDisposed || !myProject.isInitialized() || ApplicationManager.getApplication().isUnitTestMode()) return;
  if (!ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss()) return;

  ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(myProject);

  TreeModelBuilder treeModelBuilder =
          new TreeModelBuilder(myProject, myView.isShowFlatten()).setChangeLists(changeListManager.getChangeListsCopy()).setLocallyDeletedPaths(changeListManager.getDeletedFiles())
                  .setModifiedWithoutEditing(changeListManager.getModifiedWithoutEditing()).setSwitchedFiles(changeListManager.getSwitchedFilesMap())
                  .setSwitchedRoots(changeListManager.getSwitchedRoots()).setLockedFolders(changeListManager.getLockedFolders())
                  .setLogicallyLockedFiles(changeListManager.getLogicallyLockedFolders()).setUnversioned(changeListManager.getUnversionedFiles());
  if (myState.myShowIgnored) {
    treeModelBuilder.setIgnored(changeListManager.getIgnoredFiles(), changeListManager.isIgnoredInUpdateMode());
  }
  myView.updateModel(treeModelBuilder.build());

  changeDetails();
}
 
Example #19
Source File: Communicator.java    From CppTools with Apache License 2.0 6 votes vote down vote up
private void doServerStartup(final Runnable startServerAction) {
  if (ApplicationManager.getApplication().isUnitTestMode()) return;
  serverState = ServerState.STARTING;

  ApplicationManager.getApplication().invokeAndWait(new Runnable() {
    public void run() {
      ProgressManager.getInstance().runProcessWithProgressAsynchronously(
        myProject,
        "analyzing c / c++ sources",
        startServerAction,
        null,
        null,
        new PerformInBackgroundOption() {
          public boolean shouldStartInBackground() {
            return true;
          }

          public void processSentToBackground() {
          }
        }
      );
    }
  }, ModalityState.NON_MODAL);
}
 
Example #20
Source File: BazelTestRunner.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempt to find a local Dart file corresponding to a script in Observatory.
 */
@Nullable
@Override
protected VirtualFile findLocalFile(@NotNull final String uri) {
  // Get the workspace directory name provided by the test harness.
  final String workspaceDirName = connector.getWorkspaceDirName();

  // Verify the returned workspace directory name, we weren't passed a workspace name or if the valid workspace name does not start the
  // uri then return the super invocation of this method. This prevents the unknown URI type from being passed to the analysis server.
  if (StringUtils.isEmpty(workspaceDirName) || !uri.startsWith(workspaceDirName + ":/")) return super.findLocalFile(uri);

  final String pathFromWorkspace = uri.substring(workspaceDirName.length() + 1);

  // For each root in each module, look for a bazel workspace path, if found attempt to compute the VirtualFile, return when found.
  return ApplicationManager.getApplication().runReadAction((Computable<VirtualFile>)() -> {
    for (Module module : DartSdkLibUtil.getModulesWithDartSdkEnabled(getProject())) {
      for (ContentEntry contentEntry : ModuleRootManager.getInstance(module).getContentEntries()) {
        final VirtualFile includedRoot = contentEntry.getFile();
        if (includedRoot == null) continue;

        final String includedRootPath = includedRoot.getPath();
        final int workspaceOffset = includedRootPath.indexOf(workspaceDirName);
        if (workspaceOffset == -1) continue;

        final String pathToWorkspace = includedRootPath.substring(0, workspaceOffset + workspaceDirName.length());
        final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(pathToWorkspace + pathFromWorkspace);
        if (virtualFile != null) {
          return virtualFile;
        }
      }
    }
    return super.findLocalFile(uri);
  });
}
 
Example #21
Source File: OCamlModuleWizardStep.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public boolean validate() {
    Sdk odk = c_sdk.getSelectedJdk();
    if (odk == null && !ApplicationManager.getApplication().isUnitTestMode()) {
        int result = Messages.showOkCancelDialog(
                "Do you want to create a project with no SDK assigned?\\nAn SDK is required for compiling as well as for the standard SDK modules resolution and type inference.",
                IdeBundle.message("title.no.jdk.specified"), Messages.OK_BUTTON, Messages.CANCEL_BUTTON, Messages.getWarningIcon());
        return result == Messages.OK;
    }
    return true;
}
 
Example #22
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 #23
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void dropAllUnsavedDocuments() {
  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    throw new RuntimeException("This method is only for test mode!");
  }
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  if (!myUnsavedDocuments.isEmpty()) {
    myUnsavedDocuments.clear();
    fireUnsavedDocumentsDropped();
  }
}
 
Example #24
Source File: AbstractBaseIntention.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) {
        return;
    }

    PsiDocumentManager.getInstance(project).commitAllDocuments();
    T parentAtCaret = getParentAtCaret(editor, file);
    if (parentAtCaret != null) {
        ApplicationManager.getApplication().runWriteAction(() -> runInvoke(project, parentAtCaret));
    }
}
 
Example #25
Source File: VirtualFilePointerTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void refreshVFS() {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      VirtualFileManager.getInstance().syncRefresh();
    }
  });
  UIUtil.dispatchAllInvocationEvents();
}
 
Example #26
Source File: BlockingCommand.java    From CppTools with Apache License 2.0 5 votes vote down vote up
public void await(Project project, PollingConditional conditional) {
  final Communicator communicator = Communicator.getInstance(project);
  boolean readAccessAllowed = ApplicationManager.getApplication().isReadAccessAllowed();
  int cycles = 50;

  while(true) {
    synchronized(this) {
      if (conditional.isReady() || failed) break;

      try { wait(MS_TO_WAIT); }
      catch(InterruptedException e) {
        //System.out.println("Interrupted");
      }
      if (conditional.isReady() || failed) {
        break;
      }
    }
    try {
      ProgressManager.checkCanceled();
      --cycles;
      if (cycles == 0 && readAccessAllowed) {
        // ProgressManager.checkCanceled() should cancel via beforeWrite callback of ApplicationListener
        // here we just avoid waiting for the server too much
        throw new ProcessCanceledException();
      }
    } catch(ProcessCanceledException ex) {
      communicator.cancelCommand(this);
      throw ex;
    }
  }
}
 
Example #27
Source File: CrudUtils.java    From crud-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static void invokeAndWait(Project p, ModalityState state, Runnable r) {
    if (isNoBackgroundMode()) {
        r.run();
    } else {
        ApplicationManager.getApplication().invokeAndWait(DisposeAwareRunnable.create(r, p), state);
    }
}
 
Example #28
Source File: StatusBarProgress.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void update() {
  String text;
  if (!isRunning()) {
    text = "";
  }
  else {
    text = getText();
    double fraction = getFraction();
    if (fraction > 0) {
      text += " " + (int)(fraction * 100 + 0.5) + "%";
    }
  }
  final String _text = text;
  if (!myScheduledStatusBarTextSave) {
    myScheduledStatusBarTextSave = true;
    //noinspection SSBasedInspection
    SwingUtilities.invokeLater(() -> {
      if (ApplicationManager.getApplication().isDisposed()) return;
      WindowManager windowManager = WindowManager.getInstance();
      if (windowManager == null) return;

      Project[] projects = ProjectManager.getInstance().getOpenProjects();
      if (projects.length == 0) projects = new Project[]{null};

      for (Project project : projects) {
        StatusBar statusBar = windowManager.getStatusBar(project);
        if (statusBar != null) {
          String info = ObjectUtil.notNull(statusBar.getInfo(), "");
          myStatusBar2SavedText.put(statusBar, pair(info, info));  // initial value
        }
      }
    });
  }
  //noinspection SSBasedInspection
  SwingUtilities.invokeLater(() -> {
    for (StatusBar statusBarEx : myStatusBar2SavedText.keySet()) {
      setStatusBarText(statusBarEx, _text);
    }
  });
}
 
Example #29
Source File: CoreCommandProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setCurrentCommandName(String name) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  CommandDescriptor currentCommand = myCurrentCommand;
  CommandLog.LOG.assertTrue(currentCommand != null);
  currentCommand.myName = name;
}
 
Example #30
Source File: GradleDslLiteral.java    From ok-gradle with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Object produceValue() {
  PsiElement element = getCurrentElement();
  if (element == null) {
    return null;
  }
  return ApplicationManager.getApplication()
                           .runReadAction((Computable<Object>)() -> getDslFile().getParser().extractValue(this, element, true));
}