com.intellij.openapi.util.Computable Java Examples
The following examples show how to use
com.intellij.openapi.util.Computable.
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: FlutterProjectCreator.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) { // See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary. boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> { try { if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) { return true; } } catch (Exception e) { LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e); } return false; }); if (!couldEnsureLocationExists) { String msg = "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path."; Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project"); return false; } return true; }
Example #2
Source File: GotoTargetHandler.java From consulo with Apache License 2.0 | 6 votes |
public boolean addTarget(final PsiElement element) { if (ArrayUtil.find(targets, element) > -1) return false; targets = ArrayUtil.append(targets, element); renderers.put(element, createRenderer(this, element)); if (!hasDifferentNames && element instanceof PsiNamedElement) { final String name = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Override public String compute() { return ((PsiNamedElement)element).getName(); } }); myNames.add(name); hasDifferentNames = myNames.size() > 1; } return true; }
Example #3
Source File: UsageViewManager.java From consulo with Apache License 2.0 | 6 votes |
public static boolean isSelfUsage(@Nonnull final Usage usage, @Nonnull final UsageTarget[] searchForTarget) { if (!(usage instanceof PsiElementUsage)) return false; return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { @Override public Boolean compute() { final PsiElement element = ((PsiElementUsage)usage).getElement(); if (element == null) return false; for (UsageTarget ut : searchForTarget) { if (ut instanceof PsiElementUsageTarget) { if (isSelfUsage(element, ((PsiElementUsageTarget)ut).getElement())) { return true; } } } return false; } }); }
Example #4
Source File: BlazeRenderErrorContributor.java From intellij with Apache License 2.0 | 6 votes |
private File getSourceFileForClass(String className) { return ApplicationManager.getApplication() .runReadAction( (Computable<File>) () -> { try { PsiClass psiClass = JavaPsiFacade.getInstance(project) .findClass(className, GlobalSearchScope.projectScope(project)); if (psiClass == null) { return null; } return VfsUtilCore.virtualToIoFile( psiClass.getContainingFile().getVirtualFile()); } catch (IndexNotReadyException ignored) { // We're in dumb mode. Abort! Abort! return null; } }); }
Example #5
Source File: CurrentContentRevision.java From consulo with Apache License 2.0 | 6 votes |
@javax.annotation.Nullable public String getContent() { VirtualFile vFile = getVirtualFile(); if (vFile == null) { myFile.refresh(); vFile = getVirtualFile(); if (vFile == null) return null; } final VirtualFile finalVFile = vFile; final Document doc = ApplicationManager.getApplication().runReadAction(new Computable<Document>() { public Document compute() { return FileDocumentManager.getInstance().getDocument(finalVFile); }}); if (doc == null) return null; return doc.getText(); }
Example #6
Source File: Workspace.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Returns the Bazel WORKSPACE file for a Project, or null if not using Bazel. * <p> * At least one content root must be within the workspace, and the project cannot have * content roots in more than one workspace. */ @Nullable private static VirtualFile findWorkspaceFile(@NotNull Project p) { final Computable<VirtualFile> readAction = () -> { final Map<String, VirtualFile> candidates = new HashMap<>(); for (VirtualFile contentRoot : ProjectRootManager.getInstance(p).getContentRoots()) { final VirtualFile wf = findContainingWorkspaceFile(contentRoot); if (wf != null) { candidates.put(wf.getPath(), wf); } } if (candidates.size() == 1) { return candidates.values().iterator().next(); } // not found return null; }; return ApplicationManager.getApplication().runReadAction(readAction); }
Example #7
Source File: HLint.java From intellij-haskforce with Apache License 2.0 | 6 votes |
@NotNull public static Either<ExecError, Problems> parseProblems(final HaskellToolsConsole.Curried toolConsole, final @NotNull String workingDirectory, final @NotNull String path, final @NotNull String flags, final @NotNull HaskellFile haskellFile) { return getVersion(toolConsole, workingDirectory, path).flatMap(version -> { final boolean useJson = version.$greater$eq(HLINT_MIN_VERSION_WITH_JSON_SUPPORT); final String[] params = getParams(haskellFile, useJson); final String fileContents = ApplicationManager.getApplication().runReadAction( (Computable<String>) haskellFile::getText ); return runHlint(toolConsole, workingDirectory, path, flags, fileContents, params).map(stdout -> { toolConsole.writeOutput(stdout); if (useJson) return parseProblemsJson(toolConsole, stdout); return parseProblemsFallback(stdout); }); }); }
Example #8
Source File: StubSerializationHelper.java From consulo with Apache License 2.0 | 6 votes |
void assignId(@Nonnull Computable<ObjectStubSerializer> serializer, String name) throws IOException { Computable<ObjectStubSerializer> old = myNameToLazySerializer.put(name, serializer); if (old != null) { ObjectStubSerializer existing = old.compute(); ObjectStubSerializer computed = serializer.compute(); if (existing != computed) { throw new AssertionError("ID: " + name + " is not unique, but found in both " + existing.getClass().getName() + " and " + computed.getClass().getName()); } return; } int id; if (myUnmodifiable) { id = myNameStorage.tryEnumerate(name); if (id == 0) { LOG.debug("serialized " + name + " is ignored in unmodifiable stub serialization manager"); return; } } else { id = myNameStorage.enumerate(name); } myIdToName.put(id, name); myNameToId.put(name, id); }
Example #9
Source File: FlutterProjectCreator.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) { // See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary. boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> { try { if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) { return true; } } catch (Exception e) { LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e); } return false; }); if (!couldEnsureLocationExists) { String msg = "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path."; Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project"); return false; } return true; }
Example #10
Source File: LazyRangeMarkerFactoryImpl.java From consulo with Apache License 2.0 | 6 votes |
@Override @Nonnull public RangeMarker createRangeMarker(@Nonnull final VirtualFile file, final int line, final int column, final boolean persistent) { return ApplicationManager.getApplication().runReadAction(new Computable<RangeMarker>() { @Override public RangeMarker compute() { final Document document = FileDocumentManager.getInstance().getCachedDocument(file); if (document != null) { int myTabSize = CodeStyleFacade.getInstance(myProject).getTabSize(file.getFileType()); final int offset = calculateOffset(document, line, column, myTabSize); return document.createRangeMarker(offset, offset, persistent); } final LazyMarker marker = new LineColumnLazyMarker(myProject, file, line, column); addToLazyMarkersList(marker, file); return marker; } }); }
Example #11
Source File: FlutterProjectCreator.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
private VirtualFile getLocationFromModel(@Nullable Project projectToClose, boolean saveLocation) { final File location = new File(FileUtil.toSystemDependentName(myModel.projectLocation().get())); if (!location.exists() && !location.mkdirs()) { String message = ActionsBundle.message("action.NewDirectoryProject.cannot.create.dir", location.getAbsolutePath()); Messages.showErrorDialog(projectToClose, message, ActionsBundle.message("action.NewDirectoryProject.title")); return null; } final File baseFile = new File(location, myModel.projectName().get()); //noinspection ResultOfMethodCallIgnored baseFile.mkdirs(); final VirtualFile baseDir = ApplicationManager.getApplication().runWriteAction( (Computable<VirtualFile>)() -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(baseFile)); if (baseDir == null) { FlutterUtils.warn(LOG, "Couldn't find '" + location + "' in VFS"); return null; } if (saveLocation) { RecentProjectsManager.getInstance().setLastProjectCreationLocation(location.getPath()); } return baseDir; }
Example #12
Source File: HaxelibClasspathUtils.java From intellij-haxe with Apache License 2.0 | 5 votes |
/** * Finds the first file on the classpath having the given name or relative path. * This is attempting to emulate what the compiler would do. * * @param module - Module from which to gather the classpath. * @param filePath - filePath name or relative path. * @return a VirtualFile if found, or null otherwise. */ @Nullable public static VirtualFile findFileOnClasspath(@NotNull final Module module, @NotNull final String filePath) { if (filePath.isEmpty()) { return null; } return ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile>() { @Override public VirtualFile compute() { final String fixedPath = null == VirtualFileManager.extractProtocol(filePath) ? VirtualFileManager.constructUrl(URLUtil.FILE_PROTOCOL, filePath) : filePath; VirtualFile found = VirtualFileManager.getInstance().findFileByUrl(fixedPath); if (null == found) { found = findFileOnOneClasspath(getImplicitClassPath(module), filePath); } if (null == found) { found = findFileOnOneClasspath(getModuleClasspath(module), filePath); } if (null == found) { found = findFileOnOneClasspath(getProjectLibraryClasspath(module.getProject()), filePath); } if (null == found) { // This grabs either the module's SDK, or the inherited one, if any. found = findFileOnOneClasspath(getSdkClasspath(HaxelibSdkUtils.lookupSdk(module)), filePath); } return found; } }); }
Example #13
Source File: NavigationGutterIconRenderer.java From consulo with Apache License 2.0 | 5 votes |
protected NavigationGutterIconRenderer(final String popupTitle, final String emptyText, @Nonnull Computable<PsiElementListCellRenderer> cellRenderer, @Nonnull NotNullLazyValue<List<SmartPsiElementPointer>> pointers) { myPopupTitle = popupTitle; myEmptyText = emptyText; myCellRenderer = cellRenderer; myPointers = pointers; }
Example #14
Source File: HighlightCommand.java From CppTools with Apache License 2.0 | 5 votes |
public static List<String> getErrorListIfCached(String str, Computable<PsiFile> fileComputable) { List<String> cachedErrorsList = null; if (str.startsWith("NOT-CHANGED:")) { final List<String> strings = fileComputable.compute().getUserData(myErrorsKey); if (strings != null) { cachedErrorsList = strings; } } return cachedErrorsList; }
Example #15
Source File: AbstractExternalFilter.java From consulo with Apache License 2.0 | 5 votes |
public CharSequence refFilter(final String root, @Nonnull CharSequence read) { CharSequence toMatch = StringUtilRt.toUpperCase(read); StringBuilder ready = new StringBuilder(); int prev = 0; Matcher matcher = mySelector.matcher(toMatch); while (matcher.find()) { CharSequence before = read.subSequence(prev, matcher.start(1) - 1); // Before reference final CharSequence href = read.subSequence(matcher.start(1), matcher.end(1)); // The URL prev = matcher.end(1) + 1; ready.append(before); ready.append("\""); ready.append(ApplicationManager.getApplication().runReadAction( new Computable<String>() { @Override public String compute() { return convertReference(root, href.toString()); } } )); ready.append("\""); } ready.append(read, prev, read.length()); return ready; }
Example #16
Source File: BackwardDependenciesBuilder.java From consulo with Apache License 2.0 | 5 votes |
public BackwardDependenciesBuilder(final Project project, final AnalysisScope scope, final @Nullable AnalysisScope scopeOfInterest) { super(project, scope, scopeOfInterest); myForwardScope = ApplicationManager.getApplication().runReadAction(new Computable<AnalysisScope>() { @Override public AnalysisScope compute() { return getScope().getNarrowedComplementaryScope(getProject()); } }); myFileCount = myForwardScope.getFileCount(); myTotalFileCount = myFileCount + scope.getFileCount(); }
Example #17
Source File: SafeDialogUtils.java From saros with GNU General Public License v2.0 | 5 votes |
/** * Synchronously shows an input dialog. This method must not be called from a write safe context * as it needs to be executed synchronously and AWT actions are not allowed from a write safe * context. * * @param project the project used as a reference to generate and position the dialog * @param message the text displayed as the message of the dialog * @param initialValue the initial value contained in the text field of the input dialog * @param title the text displayed as the title of the dialog * @param selection the input range that is selected by default * @return the <code>String</code> entered by the user or <code>null</code> if the dialog did not * finish with the exit code 0 (it was not closed by pressing the "OK" button) * @throws IllegalAWTContextException if the calling thread is currently inside a write safe * context * @see Messages.InputDialog#getInputString() * @see com.intellij.openapi.ui.DialogWrapper#OK_EXIT_CODE */ public static String showInputDialog( Project project, final String message, final String initialValue, final String title, InputValidator inputValidator, TextRange selection) throws IllegalAWTContextException { if (application.isWriteAccessAllowed()) { throw new IllegalAWTContextException("AWT events are not allowed " + "inside write actions."); } log.info("Showing input dialog: " + title + " - " + message + " - " + initialValue); return EDTExecutor.invokeAndWait( (Computable<String>) () -> Messages.showInputDialog( project, message, title, Messages.getQuestionIcon(), initialValue, inputValidator, selection), ModalityState.defaultModalityState()); }
Example #18
Source File: CoverageListNode.java From consulo with Apache License 2.0 | 5 votes |
@Override public int getWeight() { return ApplicationManager.getApplication().runReadAction(new Computable<Integer>() { @Override public Integer compute() { //todo weighted final Object value = getValue(); if (value instanceof PsiElement && ((PsiElement)value).getContainingFile() != null) return 40; return 30; } }); }
Example #19
Source File: Messages.java From consulo with Apache License 2.0 | 5 votes |
@Override public void show() { if (isMacSheetEmulation()) { setInitialLocationCallback(new Computable<Point>() { @Override public Point compute() { JRootPane rootPane = SwingUtilities.getRootPane(getWindow().getParent()); if (rootPane == null) { rootPane = SwingUtilities.getRootPane(getWindow().getOwner()); } Point p = rootPane.getLocationOnScreen(); p.x += (rootPane.getWidth() - getWindow().getWidth()) / 2; return p; } }); animate(); if (SystemInfo.isJavaVersionAtLeast(7, 0, 0)) { try { Method method = Class.forName("java.awt.Window").getDeclaredMethod("setOpacity", float.class); if (method != null) method.invoke(getPeer().getWindow(), .8f); } catch (Exception exception) { } } setAutoAdjustable(false); setSize(getPreferredSize().width, 0);//initial state before animation, zero height } super.show(); }
Example #20
Source File: NewBashFileActionTest.java From BashSupport with Apache License 2.0 | 5 votes |
@Test public void testNewFile() throws Exception { ActionManager actionManager = ActionManager.getInstance(); final NewBashFileAction action = (NewBashFileAction) actionManager.getAction("Bash.NewBashScript"); // @see https://devnet.jetbrains.com/message/5539349#5539349 VirtualFile directoryVirtualFile = myFixture.getTempDirFixture().findOrCreateDir(""); final PsiDirectory directory = myFixture.getPsiManager().findDirectory(directoryVirtualFile); Assert.assertEquals(BashStrings.message("newfile.command.name"), action.getCommandName()); Assert.assertEquals(BashStrings.message("newfile.menu.action.text"), action.getActionName(directory, "")); PsiElement result = ApplicationManager.getApplication().runWriteAction(new Computable<PsiElement>() { @Override public PsiElement compute() { try { PsiElement[] elements = action.create("bash_file", directory); return elements.length >= 1 ? elements[0] : null; //the firet element is the BashFile } catch (Exception e) { return null; } } }); assertNotNull("Expected a newly created bash file", result); assertTrue("Expected a newly created bash file", result instanceof BashFile); VirtualFile vFile = ((BashFile) result).getVirtualFile(); File ioFile = VfsUtilCore.virtualToIoFile(vFile); assertTrue("Expected that the new file is executable", ioFile.canExecute()); Assert.assertEquals("Expected default bash file template content", "#!/usr/bin/env bash", result.getText()); }
Example #21
Source File: XQuickEvaluateHandler.java From consulo with Apache License 2.0 | 5 votes |
@Override public AbstractValueHint createValueHint(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final Point point, final ValueHintType type) { final XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession(); if (session == null) { return null; } final XDebuggerEvaluator evaluator = session.getDebugProcess().getEvaluator(); if (evaluator == null) { return null; } return PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Computable<XValueHint>() { @Override public XValueHint compute() { int offset = AbstractValueHint.calculateOffset(editor, point); ExpressionInfo expressionInfo = getExpressionInfo(evaluator, project, type, editor, offset); if (expressionInfo == null) { return null; } int textLength = editor.getDocument().getTextLength(); TextRange range = expressionInfo.getTextRange(); if (range.getStartOffset() > range.getEndOffset() || range.getStartOffset() < 0 || range.getEndOffset() > textLength) { LOG.error("invalid range: " + range + ", text length = " + textLength + ", evaluator: " + evaluator); return null; } return new XValueHint(project, editor, point, type, expressionInfo, evaluator, session); } }); }
Example #22
Source File: OutputFileUtil.java From consulo with Apache License 2.0 | 5 votes |
@Override public Result applyFilter(String line, int entireLength) { if (line.startsWith(CONSOLE_OUTPUT_FILE_MESSAGE)) { final String filePath = StringUtil.trimEnd(line.substring(CONSOLE_OUTPUT_FILE_MESSAGE.length()), "\n"); return new Result(entireLength - filePath.length() - 1, entireLength, new HyperlinkInfo() { @Override public void navigate(final Project project) { final VirtualFile file = ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() { @Nullable @Override public VirtualFile compute() { return LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(filePath)); } }); if (file != null) { file.refresh(false, false); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); } }); } } }); } return null; }
Example #23
Source File: VirtualFilePointerTest.java From consulo with Apache License 2.0 | 5 votes |
private static VirtualFile refreshAndFind(@Nonnull final String url) { return ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() { @Override public VirtualFile compute() { return VirtualFileManager.getInstance().refreshAndFindFileByUrl(url); } }); }
Example #24
Source File: CodeStyleManagerImpl.java From consulo with Apache License 2.0 | 5 votes |
@Override public <T> T performActionWithFormatterDisabled(final Computable<T> r) { return ((FormatterImpl)FormatterEx.getInstance()).runWithFormattingDisabled(() -> { final PostprocessReformattingAspect component = PostprocessReformattingAspect.getInstance(getProject()); return component.disablePostprocessFormattingInside(r); }); }
Example #25
Source File: VcsUtil.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public static VirtualFile getVirtualFile(final File file) { return ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile>() { @Override @javax.annotation.Nullable public VirtualFile compute() { return LocalFileSystem.getInstance().findFileByIoFile(file); } }); }
Example #26
Source File: VcsRootIterator.java From consulo with Apache License 2.0 | 5 votes |
private static boolean isExcluded(final FileIndexFacade indexFacade, final VirtualFile file) { return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { @Override public Boolean compute() { return indexFacade.isExcludedFile(file); } }); }
Example #27
Source File: FlutterAppAction.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 5 votes |
public FlutterAppAction(@NotNull FlutterApp app, @NotNull String text, @NotNull String description, @NotNull Icon icon, @NotNull Computable<Boolean> isApplicable, @NotNull String actionId) { super(text, description, icon); myApp = app; myIsApplicable = isApplicable; myActionId = actionId; updateActionRegistration(app.isConnected()); }
Example #28
Source File: FlutterWidgetPerfManager.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void syncBooleanServiceExtension(String serviceExtension, Computable<Boolean> valueProvider) { final StreamSubscription<Boolean> subscription = app.hasServiceExtension(serviceExtension, (supported) -> { if (supported) { app.callBooleanExtension(serviceExtension, valueProvider.compute()); } }); if (subscription != null) { streamSubscriptions.add(subscription); } }
Example #29
Source File: GhcModi.java From intellij-haskforce with Apache License 2.0 | 5 votes |
public static Option<GhcModi> get(PsiElement element) { final Module module = ApplicationManager.getApplication().runReadAction((Computable<Module>) () -> ModuleUtilCore.findModuleForPsiElement(element) ); if (module == null) return Option.apply(null); return get(module); }
Example #30
Source File: InspectorPanel.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 5 votes |
public InspectorPanel(FlutterView flutterView, @NotNull FlutterApp flutterApp, @NotNull InspectorService inspectorService, @NotNull Computable<Boolean> isApplicable, @NotNull InspectorService.FlutterTreeType treeType, boolean isSummaryTree, boolean legacyMode, @NotNull EventStream<Boolean> shouldAutoHorizontalScroll, @NotNull EventStream<Boolean> highlightNodesShownInBothTrees ) { this(flutterView, flutterApp, inspectorService, isApplicable, treeType, false, null, isSummaryTree, legacyMode, shouldAutoHorizontalScroll, highlightNodesShownInBothTrees); }