Java Code Examples for com.intellij.openapi.util.Ref#isNull()
The following examples show how to use
com.intellij.openapi.util.Ref#isNull() .
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: SelectionManager.java From consulo with Apache License 2.0 | 6 votes |
private TreeNodeState getStateImpl(final StateWorker stateWorker) { if (stateWorker.getVf() == null) return TreeNodeState.CLEAR; final TreeNodeState stateSelf = myState.get(stateWorker.getVf()); if (stateSelf != null) return stateSelf; final Ref<TreeNodeState> result = new Ref<>(); stateWorker.iterateParents(myState, (virtualFile, state) -> { if (state != null) { if (TreeNodeState.SELECTED.equals(state) || TreeNodeState.HAVE_SELECTED_ABOVE.equals(state)) { result.set(myState.putAndPass(stateWorker.getVf(), TreeNodeState.HAVE_SELECTED_ABOVE)); } return false; // exit } return true; }); if (! result.isNull()) return result.get(); for (VirtualFile selected : myState.getSelected()) { if (VfsUtilCore.isAncestor(stateWorker.getVf(), selected, true)) { return myState.putAndPass(stateWorker.getVf(), TreeNodeState.HAVE_SELECTED_BELOW); } } return TreeNodeState.CLEAR; }
Example 2
Source File: CommittedChangesCache.java From consulo with Apache License 2.0 | 6 votes |
private static List<CommittedChangeList> writeChangesInReadAction(final ChangesCacheFile cacheFile, final List<CommittedChangeList> newChanges) throws IOException { // ensure that changes are loaded before taking read action, to avoid stalling UI for (CommittedChangeList changeList : newChanges) { changeList.getChanges(); } final Ref<IOException> ref = new Ref<IOException>(); final List<CommittedChangeList> savedChanges = ApplicationManager.getApplication().runReadAction(new Computable<List<CommittedChangeList>>() { @Override public List<CommittedChangeList> compute() { try { return cacheFile.writeChanges(newChanges); // skip duplicates; } catch (IOException e) { ref.set(e); return null; } } }); if (!ref.isNull()) { throw ref.get(); } return savedChanges; }
Example 3
Source File: VcsUtil.java From consulo with Apache License 2.0 | 6 votes |
public static boolean runVcsProcessWithProgress(final VcsRunnable runnable, String progressTitle, boolean canBeCanceled, Project project) throws VcsException { final Ref<VcsException> ex = new Ref<>(); boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { try { runnable.run(); } catch (VcsException e) { ex.set(e); } } }, progressTitle, canBeCanceled, project); if (!ex.isNull()) { throw ex.get(); } return result; }
Example 4
Source File: ChangeRange.java From consulo with Apache License 2.0 | 6 votes |
public ChangeRange revert(ChangeRange reverse) throws IOException { final Ref<Long> first = new Ref<Long>(); final Ref<Long> last = new Ref<Long>(); LocalHistoryFacade.Listener l = new LocalHistoryFacade.Listener() { public void changeAdded(Change c) { if (first.isNull()) first.set(c.getId()); last.set(c.getId()); } }; myVcs.addListener(l, null); try { myVcs.accept(new UndoChangeRevertingVisitor(myGateway, myToChangeId, myFromChangeId)); } catch (UndoChangeRevertingVisitor.RuntimeIOException e) { throw (IOException)e.getCause(); } finally { myVcs.removeListener(l); } if (reverse != null) { if (first.isNull()) first.set(reverse.myFromChangeId); if (last.isNull()) last.set(reverse.myToChangeId); } return new ChangeRange(myGateway, myVcs, first.get(), last.get()); }
Example 5
Source File: NotificationsManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private static JPanel createButtons(@Nonnull Notification notification, @Nonnull final JPanel content, @Nullable HyperlinkListener listener) { if (notification instanceof NotificationActionProvider) { JPanel buttons = new JPanel(new HorizontalLayout(5)); buttons.setOpaque(false); content.add(BorderLayout.SOUTH, buttons); final Ref<JButton> defaultButton = new Ref<>(); NotificationActionProvider provider = (NotificationActionProvider)notification; for (NotificationActionProvider.Action action : provider.getActions(listener)) { JButton button = new JButton(action); button.setOpaque(false); if (action.isDefaultAction()) { defaultButton.setIfNull(button); } buttons.add(HorizontalLayout.RIGHT, button); } if (!defaultButton.isNull()) { UIUtil.addParentChangeListener(content, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getOldValue() == null && event.getNewValue() != null) { UIUtil.removeParentChangeListener(content, this); JRootPane rootPane = UIUtil.getRootPane(content); if (rootPane != null) { rootPane.setDefaultButton(defaultButton.get()); } } } }); } return buttons; } return null; }
Example 6
Source File: RemoteProcessSupport.java From consulo with Apache License 2.0 | 5 votes |
public EntryPoint acquire(@Nonnull Target target, @Nonnull Parameters configuration) throws Exception { ApplicationManagerEx.getApplicationEx().assertTimeConsuming(); Ref<RunningInfo> ref = Ref.create(null); Pair<Target, Parameters> key = Pair.create(target, configuration); if (!getExistingInfo(ref, key)) { startProcess(target, configuration, key); if (ref.isNull()) { try { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (ref) { while (ref.isNull()) { ref.wait(1000); ProgressManager.checkCanceled(); } } } catch (InterruptedException e) { ProgressManager.checkCanceled(); } } } if (ref.isNull()) throw new RuntimeException("Unable to acquire remote proxy for: " + getName(target)); RunningInfo info = ref.get(); if (info.handler == null) { String message = info.name; if (message != null && message.startsWith("ERROR: transport error 202:")) { message = "Unable to start java process in debug mode: -Xdebug parameters are already in use."; } throw new ExecutionException(message); } return acquire(info); }
Example 7
Source File: ReplaceInProjectManager.java From consulo with Apache License 2.0 | 5 votes |
public boolean replaceUsage(@Nonnull final Usage usage, @Nonnull final FindModel findModel, @Nonnull final Set<Usage> excludedSet, final boolean justCheck) throws FindManager.MalformedReplacementStringException { final Ref<FindManager.MalformedReplacementStringException> exceptionResult = Ref.create(); final boolean result = WriteAction.compute(() -> { if (excludedSet.contains(usage)) { return false; } final Document document = ((UsageInfo2UsageAdapter)usage).getDocument(); if (!document.isWritable()) return false; return ((UsageInfo2UsageAdapter)usage).processRangeMarkers(segment -> { final int textOffset = segment.getStartOffset(); final int textEndOffset = segment.getEndOffset(); final Ref<String> stringToReplace = Ref.create(); try { if (!getStringToReplace(textOffset, textEndOffset, document, findModel, stringToReplace)) return true; if (!stringToReplace.isNull() && !justCheck) { document.replaceString(textOffset, textEndOffset, stringToReplace.get()); } } catch (FindManager.MalformedReplacementStringException e) { exceptionResult.set(e); return false; } return true; }); }); if (!exceptionResult.isNull()) { throw exceptionResult.get(); } return result; }
Example 8
Source File: Bookmark.java From consulo with Apache License 2.0 | 5 votes |
public void release() { int line = getLine(); if (line < 0) { return; } final Document document = getDocument(); if (document == null) return; MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true); final Document markupDocument = markup.getDocument(); if (markupDocument.getLineCount() <= line) return; final int startOffset = markupDocument.getLineStartOffset(line); final int endOffset = markupDocument.getLineEndOffset(line); final Ref<RangeHighlighterEx> found = new Ref<RangeHighlighterEx>(); markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor<RangeHighlighterEx>() { @Override public boolean process(RangeHighlighterEx highlighter) { GutterMark renderer = highlighter.getGutterIconRenderer(); if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) { found.set(highlighter); return false; } return true; } }); if (!found.isNull()) found.get().dispose(); }
Example 9
Source File: UnixProcessManager.java From consulo with Apache License 2.0 | 5 votes |
public static boolean sendSignalToProcessTree(int processId, int signal) { checkCLib(); final int our_pid = C_LIB.getpid(); if (LOG.isDebugEnabled()) { LOG.debug("Sending signal " + signal + " to process tree with root PID " + processId); } final Ref<Integer> foundPid = new Ref<Integer>(); final ProcessInfo processInfo = new ProcessInfo(); final List<Integer> childrenPids = new ArrayList<Integer>(); findChildProcesses(our_pid, processId, foundPid, processInfo, childrenPids); // result is true if signal was sent to at least one process final boolean result; if (!foundPid.isNull()) { processInfo.killProcTree(foundPid.get(), signal); result = true; } else { for (Integer pid : childrenPids) { processInfo.killProcTree(pid, signal); } result = !childrenPids.isEmpty(); //we've tried to kill at least one process } if (LOG.isDebugEnabled()) { LOG.debug("Done sending signal " + signal + "; found: " + foundPid.get() + ", children: " + childrenPids + ", result: " + result); } return result; }
Example 10
Source File: UsageInfoSearcherAdapter.java From consulo with Apache License 2.0 | 5 votes |
protected void processUsages(final @Nonnull Processor<Usage> processor, @Nonnull Project project) { final Ref<UsageInfo[]> refUsages = new Ref<UsageInfo[]>(); final Ref<Boolean> dumbModeOccurred = new Ref<Boolean>(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { try { refUsages.set(findUsages()); } catch (IndexNotReadyException e) { dumbModeOccurred.set(true); } } }); if (!dumbModeOccurred.isNull()) { DumbService.getInstance(project).showDumbModeNotification("Usage search is not available until indices are ready"); return; } final Usage[] usages = ApplicationManager.getApplication().runReadAction(new Computable<Usage[]>() { @Override public Usage[] compute() { return UsageInfo2UsageAdapter.convert(refUsages.get()); } }); for (final Usage usage : usages) { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { processor.process(usage); } }); } }
Example 11
Source File: SequentialTaskExecutor.java From consulo with Apache License 2.0 | 5 votes |
public <V> V queueAndWaitTask(final Callable<V> task) throws Throwable { final Ref<V> resultRef = new Ref<V>(); final Ref<Throwable> throwableRef = new Ref<Throwable>(); final Semaphore taskSemaphore = new Semaphore(); taskSemaphore.down(); queueTask(new Runnable() { @Override public void run() { try { resultRef.set(task.call()); } catch (Throwable e) { throwableRef.set(e); LOG.error(e); } finally { taskSemaphore.up(); } } }); taskSemaphore.waitFor(); if (!throwableRef.isNull()) { throw throwableRef.get(); } return resultRef.get(); }
Example 12
Source File: DirDiffTableModel.java From consulo with Apache License 2.0 | 5 votes |
public void performDelete(final DirDiffElementImpl element) { final DiffElement source = element.getSource(); final DiffElement target = element.getTarget(); LOG.assertTrue(source == null || target == null); if (source instanceof BackgroundOperatingDiffElement || target instanceof BackgroundOperatingDiffElement) { final Ref<String> errorMessage = new Ref<>(); Runnable onFinish = () -> { if (!myDisposed) { if (!errorMessage.isNull()) { reportException(errorMessage.get()); } else { if (myElements.indexOf(element) != -1) { removeElement(element, true); } } } }; if (source != null) { ((BackgroundOperatingDiffElement)source).delete(errorMessage, onFinish); } else { ((BackgroundOperatingDiffElement)target).delete(errorMessage, onFinish); } } else { if (myElements.indexOf(element) != -1) { removeElement(element, true); } WriteAction.run(() -> { if (source != null) { source.delete(); } if (target != null) { target.delete(); } }); } }
Example 13
Source File: DirDiffTableModel.java From consulo with Apache License 2.0 | 5 votes |
public void performCopyFrom(final DirDiffElementImpl element) { final DiffElement<?> target = element.getTarget(); if (target != null) { final String path = element.getParentNode().getPath(); if (target instanceof BackgroundOperatingDiffElement) { final Ref<String> errorMessage = new Ref<>(); final Ref<DiffElement> diff = new Ref<>(); Runnable onFinish = () -> { ApplicationManager.getApplication().assertIsDispatchThread(); if (!myDisposed) { refreshElementAfterCopyFrom(element, diff.get()); if (!errorMessage.isNull()) { reportException(errorMessage.get()); } } }; ((BackgroundOperatingDiffElement)target).copyTo(mySrc, errorMessage, diff, onFinish, element.getSource(), path); } else { WriteAction.run(() -> { final DiffElement<?> diffElement = target.copyTo(mySrc, path); refreshElementAfterCopyFrom(element, diffElement); }); } } }
Example 14
Source File: DirDiffTableModel.java From consulo with Apache License 2.0 | 5 votes |
public void performCopyTo(final DirDiffElementImpl element) { final DiffElement<?> source = element.getSource(); if (source != null) { final String path = element.getParentNode().getPath(); if (source instanceof BackgroundOperatingDiffElement) { final Ref<String> errorMessage = new Ref<>(); final Ref<DiffElement> diff = new Ref<>(); Runnable onFinish = () -> { ApplicationManager.getApplication().assertIsDispatchThread(); if (!myDisposed) { DiffElement newElement = diff.get(); if (newElement == null && element.getTarget() != null) { final int row = myElements.indexOf(element); element.updateTargetData(); fireTableRowsUpdated(row, row); } refreshElementAfterCopyTo(newElement, element); if (!errorMessage.isNull()) { reportException(errorMessage.get()); } } }; ((BackgroundOperatingDiffElement)source).copyTo(myTrg, errorMessage, diff, onFinish, element.getTarget(), path); } else { WriteAction.run(() -> { final DiffElement<?> diffElement = source.copyTo(myTrg, path); refreshElementAfterCopyTo(diffElement, element); }); } } }
Example 15
Source File: BaseRefactoringProcessor.java From consulo with Apache License 2.0 | 5 votes |
private void showUsageView(@Nonnull UsageViewDescriptor viewDescriptor, @Nonnull Factory<UsageSearcher> factory, @Nonnull UsageInfo[] usageInfos) { UsageViewManager viewManager = UsageViewManager.getInstance(myProject); final PsiElement[] initialElements = viewDescriptor.getElements(); final UsageTarget[] targets = PsiElement2UsageTargetAdapter.convert(initialElements); final Ref<Usage[]> convertUsagesRef = new Ref<>(); if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos))), "Preprocess Usages", true, myProject)) return; if (convertUsagesRef.isNull()) return; final Usage[] usages = convertUsagesRef.get(); final UsageViewPresentation presentation = createPresentation(viewDescriptor, usages); if (myUsageView == null) { myUsageView = viewManager.showUsages(targets, usages, presentation, factory); customizeUsagesView(viewDescriptor, myUsageView); } else { myUsageView.removeUsagesBulk(myUsageView.getUsages()); ((UsageViewImpl)myUsageView).appendUsagesInBulk(Arrays.asList(usages)); } Set<UnloadedModuleDescription> unloadedModules = computeUnloadedModulesFromUseScope(viewDescriptor); if (!unloadedModules.isEmpty()) { myUsageView.appendUsage(new UnknownUsagesInUnloadedModules(unloadedModules)); } }
Example 16
Source File: ExternalSystemImportingTestCase.java From intellij-quarkus with Eclipse Public License 2.0 | 4 votes |
private void doImportProject() { AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(myProject, getExternalSystemId()); final ExternalProjectSettings projectSettings = getCurrentExternalProjectSettings(); projectSettings.setExternalProjectPath(getProjectPath()); //noinspection unchecked Set<ExternalProjectSettings> projects = ContainerUtilRt.newHashSet(systemSettings.getLinkedProjectsSettings()); projects.remove(projectSettings); projects.add(projectSettings); //noinspection unchecked systemSettings.setLinkedProjectsSettings(projects); final Ref<Couple<String>> error = Ref.create(); ImportSpec importSpec = createImportSpec(); if (importSpec.getCallback() == null) { importSpec = new ImportSpecBuilder(importSpec).callback(new ExternalProjectRefreshCallback() { @Override public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) { if (externalProject == null) { System.err.println("Got null External project after import"); return; } ServiceManager.getService(ProjectDataManager.class).importData(externalProject, myProject, true); System.out.println("External project was successfully imported"); } @Override public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) { error.set(Couple.of(errorMessage, errorDetails)); } }).build(); } ExternalSystemProgressNotificationManager notificationManager = ServiceManager.getService(ExternalSystemProgressNotificationManager.class); ExternalSystemTaskNotificationListenerAdapter listener = new ExternalSystemTaskNotificationListenerAdapter() { @Override public void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut) { if (StringUtil.isEmptyOrSpaces(text)) return; (stdOut ? System.out : System.err).print(text); } }; notificationManager.addNotificationListener(listener); try { ExternalSystemUtil.refreshProjects(importSpec); } finally { notificationManager.removeNotificationListener(listener); } if (!error.isNull()) { String failureMsg = "Import failed: " + error.get().first; if (StringUtil.isNotEmpty(error.get().second)) { failureMsg += "\nError details: \n" + error.get().second; } fail(failureMsg); } }
Example 17
Source File: MultipleFileMergeDialog.java From consulo with Apache License 2.0 | 4 votes |
private void acceptRevision(final boolean isCurrent) { FileDocumentManager.getInstance().saveAllDocuments(); final Collection<VirtualFile> files = myTable.getSelection(); if (!beforeResolve(files)) { return; } for (final VirtualFile file : files) { final Ref<Exception> ex = new Ref<Exception>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { @Override public void run() { try { if (!(myProvider instanceof MergeProvider2) || myMergeSession.canMerge(file)) { if (!DiffUtil.makeWritable(myProject, file)) { throw new IOException("File is read-only: " + file.getPresentableName()); } MergeData data = myProvider.loadRevisions(file); if (isCurrent) { file.setBinaryContent(data.CURRENT); } else { file.setBinaryContent(data.LAST); checkMarkModifiedProject(file); } } markFileProcessed(file, isCurrent ? MergeSession.Resolution.AcceptedYours : MergeSession.Resolution.AcceptedTheirs); } catch (Exception e) { ex.set(e); } } }, "Accept " + (isCurrent ? "Yours" : "Theirs"), null); } }); if (!ex.isNull()) { //noinspection ThrowableResultOfMethodCallIgnored Messages.showErrorDialog(myRootPanel, "Error saving merged data: " + ex.get().getMessage()); break; } } updateModelFromFiles(); }
Example 18
Source File: GraphQLReferenceService.java From js-graphql-intellij-plugin with MIT License | 4 votes |
PsiReference resolveFieldReference(GraphQLReferencePsiElement element, GraphQLField field) { final String name = element.getName(); Ref<PsiReference> reference = new Ref<>(); if (name != null) { final GraphQLPsiSearchHelper graphQLPsiSearchHelper = GraphQLPsiSearchHelper.getService(element.getProject()); if (name.startsWith("__")) { // __typename or introspection fields __schema and __type which implicitly extends the query root type graphQLPsiSearchHelper.getBuiltInSchema().accept(new PsiRecursiveElementVisitor() { @Override public void visitElement(final PsiElement schemaElement) { if (schemaElement instanceof GraphQLReferencePsiElement && schemaElement.getText().equals(name)) { reference.set(createReference(element, schemaElement)); return; } super.visitElement(schemaElement); } }); } final GraphQLTypeScopeProvider typeScopeProvider = PsiTreeUtil.getParentOfType(field, GraphQLTypeScopeProvider.class); if (reference.isNull() && typeScopeProvider != null) { GraphQLType typeScope = typeScopeProvider.getTypeScope(); if (typeScope != null) { final GraphQLType fieldType = GraphQLUtil.getUnmodifiedType(typeScope); graphQLPsiSearchHelper.processElementsWithWord(element, name, psiNamedElement -> { if (psiNamedElement.getParent() instanceof com.intellij.lang.jsgraphql.psi.GraphQLFieldDefinition) { final GraphQLFieldDefinition fieldDefinition = (GraphQLFieldDefinition) psiNamedElement.getParent(); if (!Objects.equals(fieldDefinition.getName(), name)) { // field name doesn't match, keep looking return true; } boolean isTypeMatch = false; final GraphQLTypeDefinition typeDefinition = PsiTreeUtil.getParentOfType(psiNamedElement, GraphQLTypeDefinition.class); if (typeDefinition != null) { final GraphQLTypeNameDefinition typeNameDefinition = PsiTreeUtil.findChildOfType(typeDefinition, GraphQLTypeNameDefinition.class); isTypeMatch = typeNameDefinition != null && GraphQLUtil.getName(fieldType).equals(typeNameDefinition.getName()); } if (!isTypeMatch) { // check type extension final GraphQLTypeExtension typeExtension = PsiTreeUtil.getParentOfType(psiNamedElement, GraphQLTypeExtension.class); if (typeExtension != null) { final GraphQLTypeName typeName = PsiTreeUtil.findChildOfType(typeExtension, GraphQLTypeName.class); isTypeMatch = typeName != null && GraphQLUtil.getName(fieldType).equals(typeName.getName()); } } if (isTypeMatch) { reference.set(createReference(element, psiNamedElement)); return false; // done searching } } return true; }); if (reference.isNull()) { // Endpoint language final JSGraphQLEndpointNamedTypeRegistry endpointNamedTypeRegistry = JSGraphQLEndpointNamedTypeRegistry.getService(element.getProject()); final JSGraphQLNamedType namedType = endpointNamedTypeRegistry.getNamedType(GraphQLUtil.getUnmodifiedType(typeScope).getName(), field); if (namedType != null) { JSGraphQLPropertyType property = namedType.properties.get(name); if (property != null) { reference.set(createReference(element, property.propertyElement)); } else if (namedType.definitionElement instanceof JSGraphQLEndpointObjectTypeDefinition) { // field is potentially auto-implemented, so look in the interfaces types final JSGraphQLEndpointImplementsInterfaces implementsInterfaces = ((JSGraphQLEndpointObjectTypeDefinition) namedType.definitionElement).getImplementsInterfaces(); if (implementsInterfaces != null) { for (JSGraphQLEndpointNamedType implementedType : implementsInterfaces.getNamedTypeList()) { final JSGraphQLNamedType interfaceType = endpointNamedTypeRegistry.getNamedType(implementedType.getName(), field); if (interfaceType != null) { property = interfaceType.properties.get(name); if (property != null) { reference.set(createReference(element, property.propertyElement)); break; } } } } } } } } } } return reference.get(); }
Example 19
Source File: QuickDocUtil.java From consulo with Apache License 2.0 | 4 votes |
public static void updateQuickDocAsync(@Nonnull PsiElement element, @Nonnull CharSequence prefix, @Nonnull Consumer<Consumer<Object>> provider) { Project project = element.getProject(); StringBuilder sb = new StringBuilder(prefix); ConcurrentLinkedQueue<Object> queue = new ConcurrentLinkedQueue<>(); Disposable alarmDisposable = Disposable.newDisposable(); Disposer.register(project, alarmDisposable); AtomicBoolean stop = new AtomicBoolean(false); Ref<Object> cutAt = Ref.create(null); SingleAlarm alarm = new SingleAlarm(() -> { DocumentationComponent component = getActiveDocComponent(project); if (component == null) { stop.set(true); Disposer.dispose(alarmDisposable); return; } Object s = queue.poll(); while (s != null) { if (s == CUT_AT_CMD || cutAt.get() == CUT_AT_CMD) { cutAt.set(s); s = ""; } else if (!cutAt.isNull()) { int idx = StringUtil.indexOf(sb, cutAt.get().toString()); if (idx >= 0) sb.setLength(idx); cutAt.set(null); } sb.append(s); s = queue.poll(); } if (stop.get()) { Disposer.dispose(alarmDisposable); } String newText = sb.toString() + "<br><br><br>"; String prevText = component.getText(); if (!Comparing.equal(newText, prevText)) { component.replaceText(newText, element); } }, 100, alarmDisposable); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { provider.consume(str -> { ProgressManager.checkCanceled(); if (stop.get()) throw new ProcessCanceledException(); queue.add(str); alarm.cancelAndRequest(); }); } finally { if (stop.compareAndSet(false, true)) { alarm.cancelAndRequest(); } } }); }
Example 20
Source File: QuickDocOnMouseOverManager.java From consulo with Apache License 2.0 | 4 votes |
@Override public void run() { Ref<PsiElement> targetElementRef = new Ref<>(); QuickDocUtil.runInReadActionWithWriteActionPriorityWithRetries(() -> { if (originalElement.isValid()) { targetElementRef.set(docManager.findTargetElement(editor, offset, originalElement.getContainingFile(), originalElement)); } }, 5000, 100, myProgressIndicator); Ref<String> documentationRef = new Ref<>(); if (!targetElementRef.isNull()) { try { documentationRef.set(docManager.generateDocumentation(targetElementRef.get(), originalElement, true)); } catch (Exception e) { LOG.info(e); } } ApplicationManager.getApplication().invokeLater(() -> { myCurrentRequest = null; if (editor.isDisposed() || (IdeTooltipManager.getInstance().hasCurrent() || IdeTooltipManager.getInstance().hasScheduled()) && !docManager.hasActiveDockedDocWindow()) { return; } PsiElement targetElement = targetElementRef.get(); String documentation = documentationRef.get(); if (targetElement == null || StringUtil.isEmpty(documentation)) { closeQuickDocIfPossible(); return; } myAlarm.cancelAllRequests(); if (!originalElement.equals(SoftReference.dereference(myActiveElements.get(editor)))) { return; } // Skip the request if there is a control shown as a result of explicit 'show quick doc' (Ctrl + Q) invocation. if (docManager.getDocInfoHint() != null && !docManager.isCloseOnSneeze()) { return; } editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, editor.offsetToVisualPosition(originalElement.getTextRange().getStartOffset())); docManager.showJavaDocInfo(editor, targetElement, originalElement, new MyCloseDocCallback(editor), documentation, true, false); myDocumentationManager = new WeakReference<>(docManager); }, ApplicationManager.getApplication().getNoneModalityState()); }