public void runReadAction(@NotNull final Runnable action) { /** * if we are inside read action, do not try to acquire read lock again since it will deadlock if * there is a pending writeAction see {@link * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */ if (isReadAccessAllowed()) { action.run(); return; } LOG.assertTrue( !Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); try { myActionsLock.readLock().acquire(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } try { action.run(); } finally { myActionsLock.readLock().release(); } }
public boolean tryRunReadAction(@NotNull Runnable action) { /** * if we are inside read action, do not try to acquire read lock again since it will deadlock if * there is a pending writeAction see {@link * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */ boolean mustAcquire = !isReadAccessAllowed(); if (mustAcquire) { LOG.assertTrue( myTestModeFlag || !Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); try { if (!myActionsLock.readLock().attempt(0)) return false; } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } try { action.run(); } finally { if (mustAcquire) { myActionsLock.readLock().release(); } } return true; }
private void runAfterCommitActions(@NotNull Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); List<Runnable> list; synchronized (ACTION_AFTER_COMMIT) { list = document.getUserData(ACTION_AFTER_COMMIT); if (list != null) { list = new ArrayList<Runnable>(list); document.putUserData(ACTION_AFTER_COMMIT, null); } } if (list != null) { for (final Runnable runnable : list) { runnable.run(); } } if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) { List<Object> keys = new ArrayList<Object>(actionsWhenAllDocumentsAreCommitted.keySet()); for (Object key : keys) { Runnable action = actionsWhenAllDocumentsAreCommitted.remove(key); myDocumentCommitProcessor.log("Running after commit runnable: ", null, false, key, action); action.run(); } } }
@Override public void runCheckinHandlers(@NotNull final Runnable finishAction) { final VcsConfiguration configuration = VcsConfiguration.getInstance(myProject); final Collection<VirtualFile> files = myPanel.getVirtualFiles(); final Runnable performCheckoutAction = new Runnable() { @Override public void run() { FileDocumentManager.getInstance().saveAllDocuments(); finishAction.run(); } }; if (reformat(configuration, true) && !DumbService.isDumb(myProject)) { new ReformatCodeProcessor( myProject, CheckinHandlerUtil.getPsiFiles(myProject, files), FormatterUtil.REFORMAT_BEFORE_COMMIT_COMMAND_NAME, performCheckoutAction, true) .run(); } else { performCheckoutAction.run(); } }
void stop(Runnable callback) { if (player != null) { new Tween(player.getVolume()) .tweenToZero( 0.06, 10L, (curVolume) -> { player.setVolume(curVolume); }, (zeroVolume) -> { isPlaying = false; try { if (currentAudioIn != null) { currentAudioIn.close(); } player.stop(); callback.run(); } catch (IOException | IllegalStateException | NullPointerException ex) { log.log(Level.ERROR, null, ex); } }); } else { callback.run(); } }
public void fireBreakpointChanged(Breakpoint breakpoint) { breakpoint.reload(); breakpoint.updateUI(); RequestManagerImpl.updateRequests(breakpoint); if (myAllowMulticasting) { // can be invoked from non-AWT thread myAlarm.cancelAllRequests(); final Runnable runnable = new Runnable() { @Override public void run() { myAlarm.addRequest( new Runnable() { @Override public void run() { myDispatcher.getMulticaster().breakpointsChanged(); } }, 100); } }; if (ApplicationManager.getApplication().isDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } }
/** * sets the window passed as a current ('focused') window among all splitters. All file openings * will be done inside this current window * * @param window a window to be set as current * @param requestFocus whether to request focus to the editor currently selected in this window */ public void setCurrentWindow(@Nullable final EditorWindow window, final boolean requestFocus) { final EditorWithProviderComposite newEditor = window != null ? window.getSelectedEditor() : null; Runnable fireRunnable = new Runnable() { public void run() { getManager().fireSelectionChanged(newEditor); } }; setCurrentWindow(window); getManager().updateFileName(window == null ? null : window.getSelectedFile()); if (window != null) { final EditorWithProviderComposite selectedEditor = window.getSelectedEditor(); if (selectedEditor != null) { fireRunnable.run(); } if (requestFocus) { window.requestFocus(true); } } else { fireRunnable.run(); } }
private void updateFinished() { myDumb = false; if (myProject.isDisposed()) return; if (ApplicationManager.getApplication().isInternal()) LOG.info("updateFinished"); try { myPublisher.exitDumbMode(); FileEditorManagerEx.getInstanceEx(myProject).refreshIcons(); } finally { // It may happen that one of the pending runWhenSmart actions triggers new dumb mode; // in this case we should quit processing pending actions and postpone them until the newly // started dumb mode finishes. while (!myDumb) { final Runnable runnable; synchronized (myRunWhenSmartQueue) { if (myRunWhenSmartQueue.isEmpty()) { break; } runnable = myRunWhenSmartQueue.pullFirst(); } try { runnable.run(); } catch (Throwable e) { LOG.error(e); } } } }
private void doSelectModuleOrGroup(final Object toSelect, final boolean requestFocus) { ToolWindowManager windowManager = ToolWindowManager.getInstance(myProject); final Runnable runnable = new Runnable() { @Override public void run() { ProjectView projectView = ProjectView.getInstance(myProject); if (requestFocus) { projectView.changeView(getId(), getSubId()); } ((BaseProjectTreeBuilder) getTreeBuilder()) .selectInWidth( toSelect, requestFocus, new Condition<AbstractTreeNode>() { @Override public boolean value(final AbstractTreeNode node) { return node instanceof AbstractModuleNode || node instanceof ModuleGroupNode || node instanceof AbstractProjectNode; } }); } }; if (requestFocus) { windowManager.getToolWindow(ToolWindowId.PROJECT_VIEW).activate(runnable); } else { runnable.run(); } }
public void commitSynchronously( @NotNull Document document, @NotNull Project project, PsiFile excludeFile) { assert !isDisposed; if (!project.isInitialized() && !project.isDefault()) { @NonNls String s = project + "; Disposed: " + project.isDisposed() + "; Open: " + project.isOpen(); s += "; SA Passed: "; try { s += ((StartupManagerImpl) StartupManager.getInstance(project)).startupActivityPassed(); } catch (Exception e) { s += e; } throw new RuntimeException(s); } ApplicationManager.getApplication().assertWriteAccessAllowed(); synchronized (documentsToCommit) { setCommitStage(document, CommitStage.ABOUT_TO_BE_SYNC_COMMITTED, true); removeCommitFromQueue(document); } ProgressIndicatorBase indicator = new ProgressIndicatorBase(); indicator.start(); log("About to commit sync", document, true, indicator); Runnable finish = commit(document, project, excludeFile, indicator, true, "Sync commit"); log("Committed sync", document, true, finish, indicator); assert finish != null; finish.run(); }
@Override public void compileAndRun( @NotNull final Runnable startRunnable, @NotNull final ExecutionEnvironment environment, @Nullable final RunProfileState state, @Nullable final Runnable onCancelRunnable) { long id = environment.getExecutionId(); if (id == 0) { id = environment.assignNewExecutionId(); } RunProfile profile = environment.getRunProfile(); if (!(profile instanceof RunConfiguration)) { startRunnable.run(); return; } final RunConfiguration runConfiguration = (RunConfiguration) profile; final List<BeforeRunTask> beforeRunTasks = RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration); if (beforeRunTasks.isEmpty()) { startRunnable.run(); } else { DataContext context = environment.getDataContext(); final DataContext projectContext = context != null ? context : SimpleDataContext.getProjectContext(myProject); final long finalId = id; final Long executionSessionId = new Long(id); ApplicationManager.getApplication() .executeOnPooledThread( () -> { for (BeforeRunTask task : beforeRunTasks) { if (myProject.isDisposed()) { return; } @SuppressWarnings("unchecked") BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId()); if (provider == null) { LOG.warn( "Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'"); continue; } ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build(); taskEnvironment.setExecutionId(finalId); EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId); if (!provider.executeTask( projectContext, runConfiguration, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable); } return; } } doRun(environment, startRunnable); }); } }
@Override protected void invokeTestRunnable(@NotNull final Runnable runnable) throws Exception { final Exception[] e = new Exception[1]; Runnable runnable1 = new Runnable() { @Override public void run() { try { if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) { ApplicationManager.getApplication().runWriteAction(runnable); } else { runnable.run(); } } catch (Exception e1) { e[0] = e1; } } }; if (annotatedWith(WrapInCommand.class)) { CommandProcessor.getInstance().executeCommand(myProject, runnable1, "", null); } else { runnable1.run(); } if (e[0] != null) { throw e[0]; } }
public void expire() { NotificationsManager.getNotificationsManager().expire(this); hideBalloon(); myExpired = true; Runnable whenExpired = myWhenExpired; if (whenExpired != null) whenExpired.run(); }
public void runWriteAction(@NotNull final Runnable action) { final AccessToken token = acquireWriteActionLock(action.getClass()); try { action.run(); } finally { token.finish(); } }
public void onTestingFinished(@NotNull SMTestProxy.SMRootTestProxy testsRoot) { myEndTime = System.currentTimeMillis(); if (myTotalTestCount == 0) { myTotalTestCount = myStartedTestCount; myStatusLine.setFraction(1); } updateStatusLabel(true); updateIconProgress(true); myAnimator.stopMovie(); myTreeBuilder.updateFromRoot(); LvcsHelper.addLabel(this); final Runnable onDone = new Runnable() { @Override public void run() { myTestsRunning = false; final boolean sortByDuration = TestConsoleProperties.SORT_BY_DURATION.value(myProperties); if (sortByDuration) { myTreeBuilder.setStatisticsComparator(myProperties, sortByDuration); } } }; if (myLastSelected == null) { selectAndNotify(myTestsRootNode, onDone); } else { onDone.run(); } fireOnTestingFinished(); if (testsRoot.wasTerminated() && myStatusLine.getStatusColor() == ColorProgressBar.GREEN) { myStatusLine.setStatusColor(JBColor.LIGHT_GRAY); } if (testsRoot.isEmptySuite() && testsRoot.isTestsReporterAttached() && myProperties instanceof SMTRunnerConsoleProperties && ((SMTRunnerConsoleProperties) myProperties).fixEmptySuite()) { return; } final TestsUIUtil.TestResultPresentation presentation = new TestsUIUtil.TestResultPresentation(testsRoot, myStartTime > 0, null) .getPresentation( myFailedTestCount, myFinishedTestCount - myFailedTestCount - myIgnoredTestCount, myTotalTestCount - myFinishedTestCount, myIgnoredTestCount); TestsUIUtil.notifyByBalloon(myProperties.getProject(), testsRoot, myProperties, presentation); addToHistory(testsRoot, myProperties, this); }
public <T> T getCurrentWriteAction(@Nullable Class<T> actionClass) { assertCanRunWriteAction(); for (int i = myWriteActionsStack.size() - 1; i >= 0; i--) { Runnable action = myWriteActionsStack.get(i); if (actionClass == null || ReflectionCache.isAssignable(actionClass, action.getClass())) return (T) action; } return null; }
private void highlightNotification( final Notification notification, String message, final int line1, final int line2) { final MarkupModel markupModel = myLogEditor.getValue().getMarkupModel(); TextAttributes bold = new TextAttributes(null, null, null, null, Font.BOLD); final List<RangeHighlighter> lineColors = new ArrayList<RangeHighlighter>(); for (int line = line1; line < line2; line++) { final RangeHighlighter lineHighlighter = markupModel.addLineHighlighter(line, HighlighterLayer.CARET_ROW + 1, bold); Color color = notification.getType() == NotificationType.ERROR ? JBColor.RED : notification.getType() == NotificationType.WARNING ? JBColor.YELLOW : JBColor.GREEN; lineHighlighter.setErrorStripeMarkColor(color); lineHighlighter.setErrorStripeTooltip(message); lineColors.add(lineHighlighter); } final Runnable removeHandler = new Runnable() { @Override public void run() { for (RangeHighlighter color : lineColors) { markupModel.removeHighlighter(color); } TextAttributes attributes = EditorColorsManager.getInstance() .getGlobalScheme() .getAttributes(ConsoleViewContentType.LOG_EXPIRED_ENTRY); for (int line = line1; line < line2; line++) { markupModel.addLineHighlighter(line, HighlighterLayer.CARET_ROW + 1, attributes); } TextAttributes italic = new TextAttributes(null, null, null, null, Font.ITALIC); for (int line = line1; line < line2; line++) { for (RangeHighlighter highlighter : myHyperlinkSupport.getValue().findAllHyperlinksOnLine(line)) { markupModel.addRangeHighlighter( highlighter.getStartOffset(), highlighter.getEndOffset(), HighlighterLayer.CARET_ROW + 2, italic, HighlighterTargetArea.EXACT_RANGE); myHyperlinkSupport.getValue().removeHyperlink(highlighter); } } } }; if (!notification.isExpired()) { myProjectModel.removeHandlers.put(notification, removeHandler); } else { removeHandler.run(); } }
public void dispose() { for (Runnable runnable : myDisposeRunnables) { runnable.run(); } myDisposeRunnables.clear(); myEditor.dispose(); DebuggerManagerEx.getInstanceEx(myProject) .getContextManager() .removeListener(myContextListener); myEvaluationPanel.dispose(); super.dispose(); }
/** Refresh the data in this table. */ public void refreshTable() { Runnable refresh = new Runnable() { public synchronized void run() { tableChanged(new TableModelEvent(tableModel, TableModelEvent.HEADER_ROW)); refreshCellWidths(); } }; if (SwingUtilities.isEventDispatchThread()) { refresh.run(); } else { SwingUtilities.invokeLater(refresh); } }
public void perform(final boolean generatePrivate) { final Runnable runnable = new Runnable() { public void run() { final DocumentEx document = (DocumentEx) myEditor.getDocument(); int exprOffset = myExprMarker.getStartOffset(); final int lineOffset = getLineOffset(document, exprOffset); if (generatePrivate) { final Collection<RangeMarker> leftGreedyMarker = ContainerUtil.newArrayList(); final Collection<RangeMarker> emptyMarkers = ContainerUtil.newArrayList(); for (RangeHighlighter rangeHighlighter : myEditor.getMarkupModel().getAllHighlighters()) { collectRangeMarker(rangeHighlighter, lineOffset, leftGreedyMarker, emptyMarkers); } document.processRangeMarkers( new Processor<RangeMarker>() { @Override public boolean process(RangeMarker rangeMarker) { collectRangeMarker(rangeMarker, lineOffset, leftGreedyMarker, emptyMarkers); return true; } }); setLeftGreedy(leftGreedyMarker, false); setRightGreedy(emptyMarkers, true); // workaround for shifting empty ranges to the left document.insertString(lineOffset, " "); document.insertString(lineOffset, PRIVATE); document.deleteString( lineOffset + PRIVATE.length(), lineOffset + PRIVATE.length() + 1); setLeftGreedy(leftGreedyMarker, true); setRightGreedy(emptyMarkers, false); } else { int idx = document.getText().indexOf(PRIVATE, lineOffset); if (idx > -1 && idx < exprOffset) { document.deleteString(idx, idx + PRIVATE.length()); } } PsiDocumentManager.getInstance(myProject).commitDocument(document); } }; final LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor); if (lookup != null) { lookup.performGuardedChange(runnable); } else { runnable.run(); } }
@NotNull @Override public Promise<Void> detachAndClose() { Promise<Void> callback; try { Runnable runnable = connectCancelHandler.getAndSet(null); if (runnable != null) { runnable.run(); } } finally { callback = super.detachAndClose(); } return callback; }
protected void performIntroduce() { boolean isDeleteLocalVariable = false; PsiExpression parameterInitializer = myExpr; if (getLocalVariable() != null) { if (myPanel.isUseInitializer()) { parameterInitializer = getLocalVariable().getInitializer(); } isDeleteLocalVariable = myPanel.isDeleteLocalVariable(); } final TIntArrayList parametersToRemove = myPanel.getParametersToRemove(); final IntroduceParameterProcessor processor = new IntroduceParameterProcessor( myProject, myMethod, myMethodToSearchFor, parameterInitializer, myExpr, (PsiLocalVariable) getLocalVariable(), isDeleteLocalVariable, getInputName(), myPanel.isReplaceAllOccurences(), myPanel.getReplaceFieldsWithGetters(), myMustBeFinal || myPanel.isGenerateFinal(), isGenerateDelegate(), getType(), parametersToRemove); final Runnable runnable = () -> { final Runnable performRefactoring = () -> { processor.setPrepareSuccessfulSwingThreadCallback(() -> {}); processor.run(); normalizeParameterIdxAccordingToRemovedParams(parametersToRemove); final PsiParameter parameter = getParameter(); if (parameter != null) { super.saveSettings(parameter); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { performRefactoring.run(); } else { TransactionGuard.getInstance().submitTransactionLater(myProject, performRefactoring); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), null); }
/** * Cancel previously registered action and schedules (new) action to be executed when all * documents are committed. * * @param key the (unique) id of the action. * @param action The action to be executed after automatic commit. This action will overwrite any * action which was registered under this key earlier. The action will be executed in EDT. * @return true if action has been run immediately, or false if action was scheduled for execution * later. */ public boolean cancelAndRunWhenAllCommitted( @NonNls @NotNull Object key, @NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) { action.run(); return true; } if (myUncommittedDocuments.isEmpty()) { action.run(); assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted; return true; } actionsWhenAllDocumentsAreCommitted.put(key, action); return false; }
protected void runForClass( final PsiClass aClass, final PsiMethod psiMethod, final ConfigurationContext context, final Runnable performRunnable) { performRunnable.run(); }
public void actionPerformed(ActionEvent event) { if (target != null) { target.setVisible(false); } else if (runnable != null) { runnable.run(); } }
protected void doRun( @NotNull final ExecutionEnvironment environment, @NotNull final Runnable startRunnable) { Boolean allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN); if (allowSkipRun != null && allowSkipRun) { environment .getProject() .getMessageBus() .syncPublisher(EXECUTION_TOPIC) .processNotStarted(environment.getExecutor().getId(), environment); } else { // important! Do not use DumbService.smartInvokeLater here because it depends on modality // state // and execution of startRunnable could be skipped if modality state check fails //noinspection SSBasedInspection SwingUtilities.invokeLater( () -> { if (!myProject.isDisposed()) { if (!Registry.is("dumb.aware.run.configurations")) { DumbService.getInstance(myProject).runWhenSmart(startRunnable); } else { try { DumbService.getInstance(myProject).setAlternativeResolveEnabled(true); startRunnable.run(); } catch (IndexNotReadyException ignored) { ExecutionUtil.handleExecutionError( environment, new ExecutionException("cannot start while indexing is in progress.")); } finally { DumbService.getInstance(myProject).setAlternativeResolveEnabled(false); } } } }); } }
/** * Invokes the given Runnable in the AWT event dispatching thread, not necessarily right away. * This method may be called from any thread, including the event dispatching thread itself. * * @see SwingUtilities#invokeLater(Runnable) * @param runnable the Runnable to be executed. */ public static void invokeLater(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } }
/** * This method runs the Runnable and measures how long it takes. * * @param r is the Runnable for the task that we want to measure * @return the time it took to execute this task */ public static long time(Runnable r) { long time = -System.currentTimeMillis(); r.run(); time += System.currentTimeMillis(); System.out.println("Took " + time + "ms"); return time; }
public static void invoke(Runnable runnable) { if (ApplicationManager.getApplication().isDispatchThread()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL); } }
@Override public void rebuildList() { if (myInRebuildList) return; try { myInRebuildList = true; if (myChangesToDisplay == null) { // changes set not fixed === local changes final ChangeListManager manager = ChangeListManager.getInstance(myProject); myChangeListsMap = new HashMap<Change, LocalChangeList>(); final List<LocalChangeList> lists = manager.getChangeListsCopy(); Collection<Change> allChanges = new ArrayList<Change>(); for (LocalChangeList list : lists) { final Collection<Change> changes = list.getChanges(); allChanges.addAll(changes); for (Change change : changes) { myChangeListsMap.put(change, list); } } myAllChanges = allChanges; // refresh selected list also updateListsInChooser(); } super.rebuildList(); if (myRebuildListListener != null) { myRebuildListListener.run(); } } finally { myInRebuildList = false; } }