Java Code Examples for com.intellij.openapi.application.ApplicationManager
The following examples show how to use
com.intellij.openapi.application.ApplicationManager.
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 Author: consulo File: EditorFactoryImpl.java License: Apache License 2.0 | 6 votes |
@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 #2
Source Project: consulo Author: consulo File: ShowUsagesAction.java License: Apache License 2.0 | 6 votes |
@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 #3
Source Project: consulo Author: consulo File: CoverageViewManager.java License: Apache License 2.0 | 6 votes |
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 #4
Source Project: CppTools Author: nicity File: Communicator.java License: Apache License 2.0 | 6 votes |
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 #5
Source Project: IntelliJDeodorant Author: JetBrains-Research File: RefactoringsApplier.java License: MIT License | 6 votes |
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 #6
Source Project: litho Author: facebook File: OnCodeAnalysisFinishedListenerTest.java License: Apache License 2.0 | 6 votes |
@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 #7
Source Project: flutter-intellij Author: flutter File: AbstractLibraryManager.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source Project: consulo Author: consulo File: ModuleManagerImpl.java License: Apache License 2.0 | 6 votes |
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 #9
Source Project: intellij-plugin-v4 Author: antlr File: ANTLRv4ExternalAnnotator.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
/** 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 #10
Source Project: intellij-plugin-v4 Author: antlr File: RunANTLROnGrammarFile.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #11
Source Project: idea-php-toolbox Author: Haehnchen File: ExtensionProviderUtil.java License: MIT License | 6 votes |
@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 #12
Source Project: consulo Author: consulo File: UiNotifyConnector.java License: Apache License 2.0 | 6 votes |
@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 #13
Source Project: flutter-intellij Author: flutter File: FlutterSmallIDEProjectGenerator.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #14
Source Project: consulo Author: consulo File: EditorBasedStatusBarPopup.java License: Apache License 2.0 | 6 votes |
@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 #15
Source Project: litho Author: facebook File: GeneratedFilesListenerTest.java License: Apache License 2.0 | 6 votes |
@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 #16
Source Project: flutter-intellij Author: flutter File: VmServiceWrapper.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #17
Source Project: intellijcoder Author: fadeyev File: IntelliJIDEA.java License: MIT License | 6 votes |
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 #18
Source Project: consulo Author: consulo File: SimpleDiffPanelState.java License: Apache License 2.0 | 6 votes |
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 #19
Source Project: consulo Author: consulo File: ChangesViewManager.java License: Apache License 2.0 | 6 votes |
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 #20
Source Project: crud-intellij-plugin Author: mars05 File: CrudUtils.java License: Apache License 2.0 | 5 votes |
public static void invokeAndWait(Project p, ModalityState state, Runnable r) { if (isNoBackgroundMode()) { r.run(); } else { ApplicationManager.getApplication().invokeAndWait(DisposeAwareRunnable.create(r, p), state); } }
Example #21
Source Project: consulo Author: consulo File: CustomizationUtil.java License: Apache License 2.0 | 5 votes |
public static MouseListener installPopupHandler(JComponent component, @Nonnull final String groupId, final String place) { if (ApplicationManager.getApplication() == null) return new MouseAdapter(){}; PopupHandler popupHandler = new PopupHandler() { public void invokePopup(Component comp, int x, int y) { ActionGroup group = (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(groupId); final ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(place, group); popupMenu.getComponent().show(comp, x, y); } }; component.addMouseListener(popupHandler); return popupHandler; }
Example #22
Source Project: consulo Author: consulo File: UsageViewImpl.java License: Apache License 2.0 | 5 votes |
public Usage getNextToSelect(@Nonnull Collection<? extends Usage> toDelete) { ApplicationManager.getApplication().assertIsDispatchThread(); Usage toSelect = null; for (Usage usage : toDelete) { Usage next = getNextToSelect(usage); if (!toDelete.contains(next)) { toSelect = next; break; } } return toSelect; }
Example #23
Source Project: consulo Author: consulo File: HintManagerImpl.java License: Apache License 2.0 | 5 votes |
private static void doShowInGivenLocation(final LightweightHint hint, final Editor editor, Point p, HintHint hintInfo, boolean updateSize) { if (ApplicationManager.getApplication().isUnitTestMode()) return; JComponent externalComponent = getExternalComponent(editor); Dimension size = updateSize ? hint.getComponent().getPreferredSize() : hint.getComponent().getSize(); if (hint.isRealPopup() || hintInfo.isPopupForced()) { final Point point = new Point(p); SwingUtilities.convertPointToScreen(point, externalComponent); final Rectangle editorScreen = ScreenUtil.getScreenRectangle(point.x, point.y); p = new Point(p); if (hintInfo.getPreferredPosition() == Balloon.Position.atLeft) { p.x -= size.width; } SwingUtilities.convertPointToScreen(p, externalComponent); final Rectangle rectangle = new Rectangle(p, size); ScreenUtil.moveToFit(rectangle, editorScreen, null); p = rectangle.getLocation(); SwingUtilities.convertPointFromScreen(p, externalComponent); if (hintInfo.getPreferredPosition() == Balloon.Position.atLeft) { p.x += size.width; } } else if (externalComponent.getWidth() < p.x + size.width && !hintInfo.isAwtTooltip()) { p.x = Math.max(0, externalComponent.getWidth() - size.width); } if (hint.isVisible()) { if (updateSize) { hint.pack(); } hint.updatePosition(hintInfo.getPreferredPosition()); hint.updateLocation(p.x, p.y); } else { hint.show(externalComponent, p.x, p.y, editor.getContentComponent(), hintInfo); } }
Example #24
Source Project: consulo Author: consulo File: TestErrorViewAction.java License: Apache License 2.0 | 5 votes |
private void addMessage(final ErrorTreeView view, final String[] message, final int type) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final long start = System.currentTimeMillis(); view.addMessage(type, message, null, -1, -1, null); final long duration = System.currentTimeMillis() - start; myMillis += duration; incMessageCount(); } }, ModalityState.NON_MODAL); }
Example #25
Source Project: intellij-pants-plugin Author: pantsbuild File: PantsExecutionException.java License: Apache License 2.0 | 5 votes |
@Override public String getMessage() { final String originalMessage = super.getMessage(); if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isInternal()) { return originalMessage + "\n" + getExecutionDetails(); } return originalMessage; }
Example #26
Source Project: jetbrains-plugin-graph-database-support Author: neueda File: ParametersPanel.java License: Apache License 2.0 | 5 votes |
private void setInitialContent(Document document) { if (document != null && document.getText().isEmpty()) { final Runnable setTextRunner = () -> document.setText("{}"); ApplicationManager.getApplication() .invokeLater(() -> ApplicationManager.getApplication().runWriteAction(setTextRunner)); } }
Example #27
Source Project: intellij-bpmn-editor Author: Blenta File: BPMNFileEditor.java License: GNU General Public License v3.0 | 5 votes |
public void saveChanges() { ApplicationManager.getApplication().invokeLater(() -> { if (myFile.isValid()) { String content = XMLModelUtils.getXml(new BPMNCodec(editor.getGraph()).encode().getDocumentElement()); ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> myDocument.setText(convertString(content)), "BPMN Diagram edit operation", null)); } }); }
Example #28
Source Project: consulo Author: consulo File: DefaultRemoteContentProvider.java License: Apache License 2.0 | 5 votes |
@Override public void saveContent(final String url, @Nonnull final File file, @Nonnull final DownloadingCallback callback) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { downloadContent(url, file, callback); } }); }
Example #29
Source Project: azure-devops-intellij Author: microsoft File: TeamServicesSettingsService.java License: MIT License | 5 votes |
public static TeamServicesSettingsService getInstance() { TeamServicesSettingsService service = null; if (ApplicationManager.getApplication() != null) { service = ServiceManager.getService(TeamServicesSettingsService.class); } if (service == null) { service = DEFAULT_INSTANCE; } return service; }
Example #30
Source Project: consulo Author: consulo File: DesktopCaretImpl.java License: Apache License 2.0 | 5 votes |
private static void validateContext(boolean requireEdt) { if (requireEdt) { ApplicationManager.getApplication().assertIsDispatchThread(); } else { ApplicationManager.getApplication().assertReadAccessAllowed(); } }