org.jetbrains.concurrency.Promise Java Examples
The following examples show how to use
org.jetbrains.concurrency.Promise.
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: AsyncFilterRunner.java From consulo with Apache License 2.0 | 6 votes |
void highlightHyperlinks(@Nonnull Project project, @Nonnull Filter customFilter, final int startLine, final int endLine) { if (endLine < 0) return; myQueue.offer(new HighlighterJob(project, customFilter, startLine, endLine, myEditor.getDocument())); if (ApplicationManager.getApplication().isWriteAccessAllowed()) { runTasks(); highlightAvailableResults(); return; } Promise<?> promise = ReadAction.nonBlocking(this::runTasks).submit(ourExecutor); if (isQuick(promise)) { highlightAvailableResults(); } else { promise.onSuccess(__ -> { if (hasResults()) { ApplicationManager.getApplication().invokeLater(this::highlightAvailableResults, ModalityState.any()); } }); } }
Example #2
Source File: TreeUtil.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private static Promise<TreePath> promiseMakeVisibleOne(@Nonnull JTree tree, @Nonnull TreeVisitor visitor, @Nullable Consumer<? super TreePath> consumer) { AsyncPromise<TreePath> promise = new AsyncPromise<>(); promiseMakeVisible(tree, visitor, promise).onError(promise::setError).onSuccess(path -> { if (promise.isCancelled()) return; UIUtil.invokeLaterIfNeeded(() -> { if (promise.isCancelled()) return; if (tree.isVisible(path)) { if (consumer != null) consumer.accept(path); promise.setResult(path); } else { promise.cancel(); } }); }); return promise; }
Example #3
Source File: TreeUtil.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private static Promise<TreePath> promiseMakeVisible(@Nonnull JTree tree, @Nonnull TreeVisitor visitor, @Nonnull AsyncPromise<?> promise) { return promiseVisit(tree, path -> { if (promise.isCancelled()) return TreeVisitor.Action.SKIP_SIBLINGS; TreeVisitor.Action action = visitor.visit(path); if (action == TreeVisitor.Action.CONTINUE || action == TreeVisitor.Action.INTERRUPT) { // do not expand children if parent path is collapsed if (!tree.isVisible(path)) { if (!promise.isCancelled()) { LOG.debug("tree expand canceled"); promise.cancel(); } return TreeVisitor.Action.SKIP_SIBLINGS; } if (action == TreeVisitor.Action.CONTINUE) expandPathWithDebug(tree, path); } return action; }); }
Example #4
Source File: StructureTreeModel.java From consulo with Apache License 2.0 | 6 votes |
/** * @param element an element of the internal tree structure * @param function a function to process corresponding node on a valid thread * @return a promise that will be succeed if the specified function returns non-null value */ @Nonnull private <Result> Promise<Result> onValidThread(@Nonnull Object element, @Nonnull Function<? super Node, ? extends Result> function) { return onValidThread(structure -> { Node node = root.get(); if (node == null) return null; if (node.matches(element)) return function.apply(node); ArrayDeque<Object> stack = new ArrayDeque<>(); for (Object e = element; e != null; e = structure.getParentElement(e)) stack.push(e); if (!node.matches(stack.pop())) return null; while (!stack.isEmpty()) { node = node.findChild(stack.pop()); if (node == null) return null; } return function.apply(node); }); }
Example #5
Source File: FileStructurePopup.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private Promise<TreePath> rebuildAndSelect(boolean refilterOnly, Object selection) { AsyncPromise<TreePath> result = new AsyncPromise<>(); myStructureTreeModel.getInvoker().runOrInvokeLater(() -> { if (refilterOnly) { myFilteringStructure.refilter(); myStructureTreeModel.invalidate().onSuccess( res -> (selection == null ? myAsyncTreeModel.accept(o -> TreeVisitor.Action.CONTINUE) : select(selection)).onError(ignore2 -> result.setError("rejected")).onSuccess(p -> UIUtil.invokeLaterIfNeeded(() -> { TreeUtil.expand(getTree(), myTreeModel instanceof StructureViewCompositeModel ? 3 : 2); TreeUtil.ensureSelection(myTree); mySpeedSearch.refreshSelection(); result.setResult(p); }))); } else { myTreeStructure.rebuildTree(); myStructureTreeModel.invalidate().onSuccess(res -> rebuildAndSelect(true, selection).processed(result)); } }); return result; }
Example #6
Source File: BaseProjectTreeBuilder.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public Promise<Object> revalidateElement(@Nonnull Object element) { if (!(element instanceof AbstractTreeNode)) { return Promises.rejectedPromise(); } final AsyncPromise<Object> result = new AsyncPromise<>(); AbstractTreeNode node = (AbstractTreeNode)element; final Object value = node.getValue(); final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(ObjectUtils.tryCast(value, PsiElement.class)); batch(indicator -> { final Ref<Object> target = new Ref<>(); Promise<Object> callback = _select(element, virtualFile, true, Conditions.alwaysTrue()); callback.onSuccess(it -> result.setResult(target.get())).onError(e -> result.setError(e)); }); return result; }
Example #7
Source File: UIProjectUtils.java From saros with GNU General Public License v2.0 | 6 votes |
/** * Runs the given method with a current project object. * * <p>If there is currently a session, the given method is run immediately using the project * contained in the session context. Otherwise, the currently focused project is requested and the * method is run asynchronously when the request is done. In this case, the used project object * can be <code>null</code> if the request fails. * * <p><b>NOTE:</b> This method should only be used to for UI purposes. To interact with the * project of a shared reference point, please use {@link IntellijReferencePoint#getProject()} * instead. * * @param projectRunner the method to call with the currently focused project */ public void runWithProject(@NotNull ProjectRunner projectRunner) { Project sessionProject = getProjectFromSession(); if (sessionProject != null) { projectRunner.run(sessionProject); return; } Promise<DataContext> promisedDataContext = DataManager.getInstance().getDataContextFromFocusAsync(); Promise<Project> promisedProject = promisedDataContext.then(LangDataKeys.PROJECT::getData); promisedProject.onProcessed(projectRunner::run); }
Example #8
Source File: AbstractTreeUi.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull private Promise<?> execute(@Nonnull AsyncRunnable runnable) throws ProcessCanceledException { try { if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } Promise<?> promise = runnable.run(); if (!canInitiateNewActivity()) { throw new ProcessCanceledException(); } return promise; } catch (ProcessCanceledException e) { if (!isReleased()) { setCancelRequested(true); resetToReady(); } throw e; } }
Example #9
Source File: ApplicationPasswordRegistry.java From p4ic4idea with Apache License 2.0 | 6 votes |
/** * Retrieve the stored password. If it was not stored, then the promise's * resolved value will be null. * * @param config source * @return promise with a null value (if no password stored) or the password. */ @NotNull public final Promise<OneTimeString> get(@NotNull final ServerConfig config) { if (LOG.isDebugEnabled()) { LOG.debug("Fetching password for config " + config.getServerName()); } final CredentialAttributes attr = getCredentialAttributes(config, true); return PasswordSafe.getInstance().getAsync(attr) .then((c) -> c == null ? null : c.getPassword()) // should use onProcessed, but that's a higher API version. .processed((p) -> { if (LOG.isDebugEnabled()) { LOG.debug("Fetched password for config " + config.getServerName()); } }) .rejected((t) -> LOG.warn("Password fetch generated an error", t)); }
Example #10
Source File: OptionsTree.java From consulo with Apache License 2.0 | 6 votes |
@Override protected Promise<?> refilterNow(Object preferredSelection, boolean adjustSelection) { final List<Object> toRestore = new ArrayList<>(); if (myContext.isHoldingFilter() && !myWasHoldingFilter && myToExpandOnResetFilter == null) { myToExpandOnResetFilter = myBuilder.getUi().getExpandedElements(); } else if (!myContext.isHoldingFilter() && myWasHoldingFilter && myToExpandOnResetFilter != null) { toRestore.addAll(myToExpandOnResetFilter); myToExpandOnResetFilter = null; } myWasHoldingFilter = myContext.isHoldingFilter(); Promise<?> result = super.refilterNow(preferredSelection, adjustSelection); myRefilteringNow = true; return result.onSuccess((c) -> { myRefilteringNow = false; if (!myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { restoreExpandedState(toRestore); } }); }
Example #11
Source File: ApplicationPasswordRegistryComponent.java From p4ic4idea with Apache License 2.0 | 6 votes |
private Promise<OneTimeString> promptForPassword(@Nullable Project project, @NotNull ServerConfig config) { final AsyncPromise<OneTimeString> ret = new AsyncPromise<>(); // Because this can happen while a dialog is shown, we instead want to force it to run. // So don't use the ApplicationManager to run later. EventQueue.invokeLater(() -> { CredentialPromptDialog.askPassword( project, P4Bundle.getString("login.password.title"), P4Bundle.message("login.password.message", config.getServerName().getDisplayName(), config.getUsername()), getCredentialAttributes(config, false), true, null); }); return ret; }
Example #12
Source File: AsyncTreeModel.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private Promise<Node> promiseChildren(@Nonnull Node node) { if (disposed) return rejectedPromise(); return node.queue.promise(processor, () -> { node.setLoading(!showLoadingNode ? null : new Node(new LoadingNode(), true)); return new CmdGetChildren("Load children", node, false); }); }
Example #13
Source File: AsyncTreeModel.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private Promise<TreePath> resolve(Promise<TreePath> promise) { if (promise == null && isValidThread()) { return rejectedPromise(); } AsyncPromise<TreePath> async = new AsyncPromise<>(); if (promise == null) { onValidThread(() -> async.setError("rejected")); } else { promise.onError(onValidThread(async::setError)); promise.onSuccess(onValidThread(path -> resolve(async, path))); } return async; }
Example #14
Source File: StructureTreeModel.java From consulo with Apache License 2.0 | 5 votes |
/** * @param path a path to the node * @param function a function to process corresponding node on a valid thread * @return a promise that will be succeed if the specified function returns non-null value */ @Nonnull private <Result> Promise<Result> onValidThread(@Nonnull TreePath path, @Nonnull Function<? super Node, ? extends Result> function) { Object component = path.getLastPathComponent(); if (component instanceof Node) { Node node = (Node)component; return onValidThread(structure -> disposed || isNodeRemoved(node) ? null : function.apply(node)); } return rejectedPromise("unexpected node: " + component); }
Example #15
Source File: LombokLightActionTestCase.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void performActionTest() throws TimeoutException, ExecutionException { AnAction anAction = getAction(); Promise<DataContext> contextResult = DataManager.getInstance().getDataContextFromFocusAsync(); AnActionEvent anActionEvent = new AnActionEvent(null, contextResult.blockingGet(10, TimeUnit.SECONDS), "", anAction.getTemplatePresentation(), ActionManager.getInstance(), 0); anAction.actionPerformed(anActionEvent); FileDocumentManager.getInstance().saveAllDocuments(); }
Example #16
Source File: FilteringTreeBuilder.java From consulo with Apache License 2.0 | 5 votes |
public FilteringTreeBuilder(Tree tree, ElementFilter filter, AbstractTreeStructure structure, @Nullable Comparator<? super NodeDescriptor> comparator) { super(tree, (DefaultTreeModel)tree.getModel(), structure instanceof FilteringTreeStructure ? structure : new FilteringTreeStructure(filter, structure), comparator); myTree = tree; initRootNode(); if (filter instanceof ElementFilter.Active) { ((ElementFilter.Active)filter).addListener(new ElementFilter.Listener() { @Nonnull @Override public Promise<?> update(final Object preferredSelection, final boolean adjustSelection, final boolean now) { return refilter(preferredSelection, adjustSelection, now); } }, this); } myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { TreePath newPath = e.getNewLeadSelectionPath(); if (newPath != null) { Object element = getElementFor(newPath.getLastPathComponent()); if (element != null) { myLastSuccessfulSelect = element; } } } }); }
Example #17
Source File: BuckCommandBeforeRunTaskProvider.java From buck with Apache License 2.0 | 5 votes |
@Override public Promise<Boolean> configureTask( @NotNull DataContext context, @NotNull RunConfiguration configuration, @NotNull BuckCommandBeforeRunTask task) { Project project = configuration.getProject(); final BuckCommandToolEditorDialog dialog = new BuckCommandToolEditorDialog(project); dialog.setArguments(task.getArguments()); if (dialog.showAndGet()) { task.setArguments(dialog.getArguments()); Promises.resolvedPromise(true); } return Promises.resolvedPromise(false); }
Example #18
Source File: DonePromise.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public CancellablePromise<T> processed(@Nonnull Promise<? super T> child) { if (child instanceof InternalPromiseUtil.PromiseImpl) { //noinspection unchecked ((InternalPromiseUtil.PromiseImpl<T>)child)._setValue(value); } else if (child instanceof InternalPromiseUtil.CompletablePromise) { //noinspection unchecked ((InternalPromiseUtil.CompletablePromise<T>)child).setResult(value.result); } return this; }
Example #19
Source File: DonePromise.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public <SUB_RESULT> Promise<SUB_RESULT> then(@Nonnull Function<? super T, ? extends SUB_RESULT> done) { if (value.error != null) { //noinspection unchecked return (Promise<SUB_RESULT>)this; } else if (isHandlerObsolete(done)) { //noinspection unchecked return (Promise<SUB_RESULT>)CANCELLED_PROMISE.get(); } else { return new DonePromise<>(PromiseValue.createFulfilled(done.apply(value.result))); } }
Example #20
Source File: AbstractProjectViewPane.java From consulo with Apache License 2.0 | 5 votes |
@TestOnly @Deprecated @Nonnull public Promise<TreePath> promisePathToElement(@Nonnull Object element) { AbstractTreeBuilder builder = getTreeBuilder(); if (builder != null) { DefaultMutableTreeNode node = builder.getNodeForElement(element); if (node == null) return Promises.rejectedPromise(); return Promises.resolvedPromise(new TreePath(node.getPath())); } TreeVisitor visitor = createVisitor(element); if (visitor == null || myTree == null) return Promises.rejectedPromise(); return TreeUtil.promiseVisit(myTree, visitor); }
Example #21
Source File: FavoritesViewTreeBuilder.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public Promise<Object> selectAsync(Object element, VirtualFile file, boolean requestFocus) { final DefaultMutableTreeNode node = findSmartFirstLevelNodeByElement(element); if (node != null) { return Promises.toPromise(TreeUtil.selectInTree(node, requestFocus, getTree())); } return super.selectAsync(element, file, requestFocus); }
Example #22
Source File: ContextAwareDebugProcess.java From mule-intellij-plugins with Apache License 2.0 | 5 votes |
@Override @NotNull public Promise stopAsync() { final Collection<XDebugProcess> values = debugProcesses.values(); for (XDebugProcess value : values) { value.stopAsync(); } return getDefaultDebugProcesses().stopAsync(); }
Example #23
Source File: TreeUtil.java From consulo with Apache License 2.0 | 5 votes |
/** * Promises to process nodes in the specified tree. * <strong>NB!:</strong> * The returned promise may be resolved immediately, * if this method is called on inappropriate background thread. * * @param tree a tree, which nodes should be processed * @param visitor a visitor that controls processing of tree nodes * @return a promise that will be succeed when visiting is finished */ @Nonnull public static Promise<TreePath> promiseVisit(@Nonnull JTree tree, @Nonnull TreeVisitor visitor) { TreeModel model = tree.getModel(); if (model instanceof TreeVisitor.Acceptor) { TreeVisitor.Acceptor acceptor = (TreeVisitor.Acceptor)model; return acceptor.accept(visitor); } if (model == null) return Promises.rejectedPromise("tree model is not set"); AsyncPromise<TreePath> promise = new AsyncPromise<>(); UIUtil.invokeLaterIfNeeded(() -> promise.setResult(visitModel(model, visitor))); return promise; }
Example #24
Source File: StructureTreeModel.java From consulo with Apache License 2.0 | 5 votes |
/** * @param function a function to process current structure on a valid thread * @return a promise that will be succeed if the specified function returns non-null value */ @Nonnull private <Result> Promise<Result> onValidThread(@Nonnull Function<? super Structure, ? extends Result> function) { AsyncPromise<Result> promise = new AsyncPromise<>(); invoker.runOrInvokeLater(() -> { if (!disposed) { Result result = function.apply(structure); if (result != null) promise.setResult(result); } if (!promise.isDone()) promise.cancel(); }).onError(promise::setError); return promise; }
Example #25
Source File: AsyncFilterRunner.java From consulo with Apache License 2.0 | 5 votes |
private static boolean isQuick(Promise<?> future) { try { future.blockingGet(5, TimeUnit.MILLISECONDS); return true; } catch (TimeoutException ignored) { return false; } catch (Exception e) { throw new RuntimeException(e); } }
Example #26
Source File: TreeState.java From consulo with Apache License 2.0 | 5 votes |
/** * @deprecated Temporary solution to resolve simultaneous expansions with async tree model. * Note that the specified consumer must resolve async promise at the end. */ @Deprecated public static void expand(@Nonnull JTree tree, @Nonnull Consumer<? super AsyncPromise<Void>> consumer) { Promise<Void> expanding = UIUtil.getClientProperty(tree, EXPANDING); LOG.debug("EXPANDING: ", expanding); if (expanding == null) expanding = Promises.resolvedPromise(); expanding.onProcessed(value -> { AsyncPromise<Void> promise = new AsyncPromise<>(); UIUtil.putClientProperty(tree, EXPANDING, promise); consumer.accept(promise); }); }
Example #27
Source File: ActionUpdater.java From consulo with Apache License 2.0 | 5 votes |
private static void cancelAndRestartOnUserActivity(Promise<?> promise, ProgressIndicator indicator) { Disposable disposable = Disposable.newDisposable("Action Update"); IdeEventQueue.getInstance().addPostprocessor(e -> { if (e instanceof ComponentEvent && !(e instanceof PaintEvent) && (e.getID() & AWTEvent.MOUSE_MOTION_EVENT_MASK) == 0) { indicator.cancel(); } return false; }, disposable); promise.onProcessed(__ -> Disposer.dispose(disposable)); }
Example #28
Source File: ActionUpdater.java From consulo with Apache License 2.0 | 5 votes |
CancellablePromise<List<AnAction>> expandActionGroupAsync(ActionGroup group, boolean hideDisabled) { AsyncPromise<List<AnAction>> promise = new AsyncPromise<>(); ProgressIndicator indicator = new EmptyProgressIndicator(); promise.onError(__ -> { indicator.cancel(); ActionUpdateEdtExecutor.computeOnEdt(() -> { applyPresentationChanges(); return null; }); }); cancelAndRestartOnUserActivity(promise, indicator); ourExecutor.execute(() -> { while (promise.getState() == Promise.State.PENDING) { try { boolean success = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> { List<AnAction> result = expandActionGroup(group, hideDisabled, myRealUpdateStrategy); ActionUpdateEdtExecutor.computeOnEdt(() -> { applyPresentationChanges(); promise.setResult(result); return null; }); }, new SensitiveProgressWrapper(indicator)); if (!success) { ProgressIndicatorUtils.yieldToPendingWriteActions(); } } catch (Throwable e) { promise.setError(e); } } }); return promise; }
Example #29
Source File: OptionsEditor.java From consulo with Apache License 2.0 | 5 votes |
public Promise<?> refilterFor(String text, boolean adjustSelection, final boolean now) { try { myUpdateEnabled = false; mySearch.setText(text); } finally { myUpdateEnabled = true; } return update(DocumentEvent.EventType.CHANGE, adjustSelection, now); }
Example #30
Source File: BaseProjectTreeBuilder.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private Promise<Object> _select(final Object element, final VirtualFile file, final boolean requestFocus, final Condition<? super AbstractTreeNode> nonStopCondition) { AbstractTreeUpdater updater = getUpdater(); if (updater == null) { return Promises.rejectedPromise(); } final AsyncPromise<Object> result = new AsyncPromise<>(); UiActivityMonitor.getInstance().addActivity(myProject, new UiActivity.AsyncBgOperation("projectViewSelect"), updater.getModalityState()); batch(indicator -> { _select(element, file, requestFocus, nonStopCondition, result, indicator, null, null, false); UiActivityMonitor.getInstance().removeActivity(myProject, new UiActivity.AsyncBgOperation("projectViewSelect")); }); return result; }