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(); } }
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(); } } }
@SuppressWarnings("unchecked") private void executeAndRestoreDefaultProjectSettings( @NotNull Project project, @NotNull Runnable task) { if (!project.isDefault()) { task.run(); return; } AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, myExternalSystemId); Object systemStateToRestore = null; if (systemSettings instanceof PersistentStateComponent) { systemStateToRestore = ((PersistentStateComponent) systemSettings).getState(); } systemSettings.copyFrom(myControl.getSystemSettings()); Collection projectSettingsToRestore = systemSettings.getLinkedProjectsSettings(); systemSettings.setLinkedProjectsSettings( Collections.singleton(getCurrentExternalProjectSettings())); try { task.run(); } finally { if (systemStateToRestore != null) { ((PersistentStateComponent) systemSettings).loadState(systemStateToRestore); } else { systemSettings.setLinkedProjectsSettings(projectSettingsToRestore); } } }
/** * 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(); } }
@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); }); } }
/** invokes the given Runnable */ public void invoke(boolean wait, Runnable r) { if (r == null) { return; } if (NativeWindowFactory.isAWTAvailable()) { initAWTReflection(); // handover to AWT MainThread .. try { if (((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null)) .booleanValue()) { r.run(); return; } if (wait) { ReflectionUtil.callMethod(null, mAWTInvokeAndWait, new Object[] {r}); } else { ReflectionUtil.callMethod(null, mAWTInvokeLater, new Object[] {r}); } } catch (Exception e) { throw new NativeWindowException(e); } return; } // if this main thread is not being used or // if this is already the main thread .. just execute. if (!isRunning() || mainThread == Thread.currentThread()) { r.run(); return; } boolean doWait = wait && isRunning() && mainThread != Thread.currentThread(); Object lock = new Object(); RunnableTask rTask = new RunnableTask(r, doWait ? lock : null, true); Throwable throwable = null; synchronized (lock) { invokeLater(rTask); if (doWait) { try { lock.wait(); } catch (InterruptedException ie) { throwable = ie; } } } if (null == throwable) { throwable = rTask.getThrowable(); } if (null != throwable) { throw new RuntimeException(throwable); } }
/** * 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; }
@Override public Node.PropertySet[] getPropertySets() { final Node.PropertySet[][] props = new Node.PropertySet[1][]; Runnable runnable = new Runnable() { @Override public void run() { FormLAF.executeWithLAFLocks( new Runnable() { @Override public void run() { props[0] = component.getProperties(); } }); } }; if (EventQueue.isDispatchThread()) { runnable.run(); } else { try { // We have made some attempts to keep initialization // of properties outside AWT thread, but it always // deadlocked with AWT thread for various reasons. EventQueue.invokeAndWait(runnable); } catch (InterruptedException iex) { FormUtils.LOGGER.log(Level.INFO, iex.getMessage(), iex); } catch (InvocationTargetException itex) { FormUtils.LOGGER.log(Level.INFO, itex.getMessage(), itex); } } return props[0]; }
@Nullable public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) { final PsiClass[][] holder = new PsiClass[1][]; final Runnable process = () -> { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final Collection<PsiClass> set = new LinkedHashSet<>(); final PsiManager manager = PsiManager.getInstance(filter.getProject()); final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope()); for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) { if (filter.isAccepted(psiClass)) { if (indicator != null) { indicator.setText2( "Found test class " + ReadAction.compute(psiClass::getQualifiedName)); } set.add(psiClass); } } holder[0] = set.toArray(new PsiClass[set.size()]); }; if (sync) { ProgressManager.getInstance() .runProcessWithProgressSynchronously( process, "Searching For Tests...", true, filter.getProject()); } else { process.run(); } return holder[0]; }
public void updateIssues(final @Nullable Runnable onComplete) { TaskRepository first = ContainerUtil.find( getAllRepositories(), new Condition<TaskRepository>() { public boolean value(TaskRepository repository) { return repository.isConfigured(); } }); if (first == null) { myIssueCache.clear(); if (onComplete != null) { onComplete.run(); } return; } myUpdating = true; if (ApplicationManager.getApplication().isUnitTestMode()) { doUpdate(onComplete); } else { ApplicationManager.getApplication() .executeOnPooledThread( new Runnable() { public void run() { doUpdate(onComplete); } }); } }
public boolean analyze( @NotNull PsiFile file, TextRange dirtyScope, @NotNull Runnable analyze, @NotNull ProgressIndicator indicator) { ProgressIndicator old = myState.get(); if (old != VIRGIN && old != READY) return false; if (!myState.compareAndSet(old, indicator)) { log("a: failed to change ", old, "->", indicator); return false; } log("a: changed ", old, "->", indicator); analyzedUnder = null; boolean completed = false; try { if (dirtyScope != null) { if (dirtyScope.equals(file.getTextRange())) { clear(); } else { removeInvalidRefs(); } } analyze.run(); analyzedUnder = indicator; completed = true; } finally { ProgressIndicator resultState = completed ? READY : VIRGIN; boolean set = myState.compareAndSet(indicator, resultState); assert set : myState.get(); log("a: changed after analyze", indicator, "->", resultState); } return true; }
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); } } } }); } }
private void queueNotificationAction(final Runnable action) { if (myAvailabilityNotificationsActive) { action.run(); } else { mySuspendedListenerActions.add(action); } }
/** * Creates a new debug scope that is unrelated to the current scope and runs a given task in the * new scope. * * @param name new scope name * @param context the context objects of the new scope * @param config the debug configuration to use for the new scope * @param runnable the task to run in the new scope */ public static void sandbox(String name, Object[] context, DebugConfig config, Runnable runnable) { if (ENABLED) { DebugScope.getInstance().scope(name, runnable, null, true, config, context); } else { runnable.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); } } }
private List<VFileEvent> getEvents(String msg, @Nullable Runnable action) { LOG.debug("** waiting for " + msg); myAccept = true; if (action != null) { action.run(); } int timeout = myTimeout; try { synchronized (myWaiter) { //noinspection WaitNotInLoop myWaiter.wait(timeout); } } catch (InterruptedException e) { LOG.warn(e); } LOG.debug("** waited for " + timeout); myFileSystem.refresh(false); ArrayList<VFileEvent> result; synchronized (myEvents) { result = new ArrayList<VFileEvent>(myEvents); myEvents.clear(); } LOG.debug("** events: " + result.size()); return result; }
@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; } }
/** * 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; }
private void doUpdate(@Nullable Runnable onComplete) { try { List<Task> issues = getIssuesFromRepositories( null, myConfig.updateIssuesCount, 0, false, new EmptyProgressIndicator()); if (issues == null) return; synchronized (myIssueCache) { myIssueCache.clear(); for (Task issue : issues) { myIssueCache.put(issue.getId(), issue); } } // update local tasks synchronized (myTasks) { for (Map.Entry<String, LocalTask> entry : myTasks.entrySet()) { Task issue = myIssueCache.get(entry.getKey()); if (issue != null) { entry.getValue().updateFromIssue(issue); } } } } finally { if (onComplete != null) { onComplete.run(); } myUpdating = false; } }
public static void scope(String name, Object[] context, Runnable runnable) { if (ENABLED) { DebugScope.getInstance().scope(name, runnable, null, false, null, context); } else { runnable.run(); } }
private void detectAndDisconnectLoops(@NotNull TopDownAnalysisContext c) { // Loop detection and disconnection List<Runnable> tasks = new ArrayList<Runnable>(); for (final MutableClassDescriptorLite klass : c.getClassesTopologicalOrder()) { for (final JetType supertype : klass.getSupertypes()) { ClassifierDescriptor supertypeDescriptor = supertype.getConstructor().getDeclarationDescriptor(); if (supertypeDescriptor instanceof MutableClassDescriptorLite) { MutableClassDescriptorLite superclass = (MutableClassDescriptorLite) supertypeDescriptor; if (isReachable(superclass, klass, new HashSet<ClassDescriptor>())) { tasks.add( new Runnable() { @Override public void run() { klass.getSupertypes().remove(supertype); } }); reportCyclicInheritanceHierarchyError(trace, klass, superclass); } } } } for (Runnable task : tasks) { task.run(); } }
/** * @param xmlFile * @param tagName * @param tagValue * @param path hierarchy path, this will be the parent of the new tag, ex: root/node1/node2 * @return */ public static XmlTag createTagInFile( final XmlFile xmlFile, String tagName, String tagValue, String path, Map<String, String> attributes) { XmlTag root = xmlFile.getRootTag(); String[] pathElements = path.split("/"); if (pathElements.length > 0 && pathElements[0].equals(root.getName())) { XmlTag lastExistentParent = root; String curPath = pathElements[0]; pathElements = (String[]) ArrayUtils.remove( pathElements, 0); // ArrayUtils.removeElement(pathElements, pathElements[0]); for (String curTagName : pathElements) { lastExistentParent = lastExistentParent.findFirstSubTag(curTagName); if (lastExistentParent == null) { lastExistentParent = createTagInFile(xmlFile, curTagName, "", curPath); if (lastExistentParent == null) { return null; } } curPath += "/" + curTagName; } final XmlTag newTag = lastExistentParent.createChildTag(tagName, "", tagValue, false); if (attributes != null) { for (Map.Entry<String, String> entry : attributes.entrySet()) { newTag.setAttribute(entry.getKey(), entry.getValue()); } } final XmlTag parent = lastExistentParent; Runnable runnable = new Runnable() { @Override public void run() { new WriteCommandAction.Simple( xmlFile.getProject(), "Create Xml Tag in File", xmlFile) { @Override protected void run() { // newTag = (XmlTag)parent.add(newTag); parent.addAfter(newTag, null); } }.execute(); } }; runnable.run(); // PsiDocumentManager.getInstance(xmlFile.getProject()).commitDocument(document); return findSubTag(xmlFile, path + "/" + newTag.getName()); } else { return null; } }
@Override public void commitAndRunReadAction(@NotNull final Runnable runnable) { final Application application = ApplicationManager.getApplication(); if (SwingUtilities.isEventDispatchThread()) { commitAllDocuments(); runnable.run(); } else { LOG.assertTrue( !ApplicationManager.getApplication().isReadAccessAllowed(), "Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock otherwise."); final Semaphore s1 = new Semaphore(); final Semaphore s2 = new Semaphore(); final boolean[] committed = {false}; application.runReadAction( new Runnable() { @Override public void run() { if (myUncommittedDocuments.isEmpty()) { runnable.run(); committed[0] = true; } else { s1.down(); s2.down(); final Runnable commitRunnable = new Runnable() { @Override public void run() { commitAllDocuments(); s1.up(); s2.waitFor(); } }; final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator == null) { ApplicationManager.getApplication().invokeLater(commitRunnable); } else { ApplicationManager.getApplication() .invokeLater(commitRunnable, progressIndicator.getModalityState()); } } } }); if (!committed[0]) { s1.waitFor(); application.runReadAction( new Runnable() { @Override public void run() { s2.up(); runnable.run(); } }); } } }
public void runIngnoringUserEvents(Runnable runnable) { try { myIgnoreUserEvents = true; runnable.run(); } finally { myIgnoreUserEvents = false; } }
public void run(Runnable runnable) { // What if we are already in the client thread?? What happens then ? if (runningOnClientThread()) { runnable.run(); } else { service.submit(errorHandling(runnable)); } }
private MenuItem menuItem(String title, Runnable r) { MenuItem mi = new MenuItem(title); mi.setOnAction( event -> { r.run(); }); return mi; }
private void runInBackground(final Project project, final String name, final Runnable runnable) { if (ApplicationManager.getApplication().isDispatchThread()) { ProgressManager.getInstance() .runProcessWithProgressSynchronously(runnable, name, false, project); } else { runnable.run(); } }
@Override public boolean startTemplate(@NotNull Editor editor, char shortcutChar) { Runnable runnable = prepareTemplate(editor, shortcutChar, null); if (runnable != null) { PsiDocumentManager.getInstance(myProject).commitDocument(editor.getDocument()); runnable.run(); } return runnable != null; }
protected void assertNoThrowable(final Runnable closure) { String throwableName = null; try { closure.run(); } catch (Throwable thr) { throwableName = thr.getClass().getName(); } assertNull(throwableName); }
/** Retries sending requests. */ private void retryRequests() { retryFuture = null; List<Runnable> retries = new ArrayList<>(this.retries); this.retries.clear(); resetMembers(); for (Runnable retry : retries) { retry.run(); } }