Java Code Examples for com.intellij.openapi.util.Ref#create()
The following examples show how to use
com.intellij.openapi.util.Ref#create() .
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: TableModelEditor.java From consulo with Apache License 2.0 | 6 votes |
public void selectItem(@Nonnull final T item) { table.clearSelection(); final Ref<T> ref; if (helper.hasModifiedItems()) { ref = Ref.create(); helper.process(new TObjectObjectProcedure<T, T>() { @Override public boolean execute(T modified, T original) { if (item == original) { ref.set(modified); } return ref.isNull(); } }); } else { ref = null; } table.addSelection(ref == null || ref.isNull() ? item : ref.get()); }
Example 2
Source File: ModuleTestCase.java From consulo with Apache License 2.0 | 6 votes |
@Nullable protected Module loadAllModulesUnder(@Nonnull VirtualFile rootDir, @javax.annotation.Nullable final Consumer<Module> moduleConsumer) { final Ref<Module> result = Ref.create(); /* VfsUtilCore.visitChildrenRecursively(rootDir, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (!file.isDirectory() && file.getName().endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) { ModuleImpl module = (ModuleImpl)loadModule(file); if (moduleConsumer != null) { moduleConsumer.consume(module); } result.setIfNull(module); } return true; } });*/ return result.get(); }
Example 3
Source File: CreateFileFromTemplateDialog.java From consulo with Apache License 2.0 | 6 votes |
@RequiredUIAccess @Override public <T extends PsiElement> void show(@Nonnull String errorTitle, @Nullable String selectedTemplateName, @Nonnull final FileCreator<T> creator, @Nonnull Consumer<T> consumer) { final Ref<T> created = Ref.create(null); myDialog.getKindCombo().setSelectedName(selectedTemplateName); myDialog.myCreator = new ElementCreator(myProject, errorTitle) { @Override protected PsiElement[] create(String newName) throws Exception { final T element = creator.createFile(myDialog.getEnteredName(), myDialog.getKindCombo().getSelectedName()); created.set(element); if (element != null) { return new PsiElement[]{element}; } return PsiElement.EMPTY_ARRAY; } @Override protected String getActionName(String newName) { return creator.getActionName(newName, myDialog.getKindCombo().getSelectedName()); } }; myDialog.showAsync().doWhenDone(() -> consumer.accept(created.get())); }
Example 4
Source File: StubUpdatingForwardIndexAccessor.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public InputDataDiffBuilder<Integer, SerializedStubTree> getDiffBuilder(int inputId, @Nullable ByteArraySequence sequence) throws IOException { Ref<Map<Integer, SerializedStubTree>> dataRef = Ref.create(); StorageException[] ex = {null}; ProgressManager.getInstance().executeNonCancelableSection(() -> { try { dataRef.set(myIndex.getIndexedFileData(inputId)); } catch (StorageException e) { ex[0] = e; } }); if (ex[0] != null) { throw new IOException(ex[0]); } Map<Integer, SerializedStubTree> data = dataRef.get(); SerializedStubTree tree = ContainerUtil.isEmpty(data) ? null : ContainerUtil.getFirstItem(data.values()); if (tree != null) { tree.restoreIndexedStubs(StubForwardIndexExternalizer.IdeStubForwardIndexesExternalizer.INSTANCE); } return new StubCumulativeInputDiffBuilder(inputId, tree); }
Example 5
Source File: ScriptManager.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Nullable private Library getLibrary(LibraryRef libraryRef) { // TODO(devoncarew): Consider changing the signature to `CompletableFuture getLibrary(LibraryRef instance)` // (see also the EvalOnDartLibrary implementation). final Ref<Library> resultRef = Ref.create(); final Semaphore semaphore = new Semaphore(); semaphore.down(); vmService.getLibrary(isolateRef.getId(), libraryRef.getId(), new GetLibraryConsumer() { @Override public void received(Library library) { resultRef.set(library); semaphore.up(); } @Override public void onError(RPCError error) { semaphore.up(); } }); semaphore.waitFor(RESPONSE_WAIT_TIMEOUT); return resultRef.get(); }
Example 6
Source File: SingleEntryIndexForwardIndexAccessor.java From consulo with Apache License 2.0 | 6 votes |
@Nonnull @Override public InputDataDiffBuilder<Integer, V> getDiffBuilder(int inputId, @Nullable ByteArraySequence sequence) throws IOException { Ref<Map<Integer, V>> dataRef = Ref.create(); StorageException[] ex = {null}; ProgressManager.getInstance().executeNonCancelableSection(() -> { try { dataRef.set(myIndex.getValue().getIndexedFileData(inputId)); } catch (StorageException e) { ex[0] = e; } }); if (ex[0] != null) { throw new IOException(ex[0]); } Map<Integer, V> currentData = dataRef.get(); return new SingleValueDiffBuilder<>(inputId, currentData); }
Example 7
Source File: EmbeditorRequestHandler.java From neovim-intellij-complete with MIT License | 5 votes |
public int getCompletionStartOffsetInLine(String path, String fileContent, int line, int column) { LOG.debug(String.format("getCompletionStartOffsetInLine(%s:%d:%d)", path, line, column)); final Ref<Integer> integerRef = Ref.create(0); EmbeditorUtil.performCompletion(path, fileContent, line, column, new EmbeditorUtil.CompletionCallback() { @Override public void completionFinished(@NotNull CompletionParameters parameters, @NotNull CompletionProgressIndicator indicator, @NotNull Document document) { integerRef.set(EmbeditorUtil.getOffsetFromLineStart(parameters, document)); } }); return integerRef.get(); }
Example 8
Source File: PatternCompilerImpl.java From consulo with Apache License 2.0 | 5 votes |
private static Object invokeMethod(@Nullable final Object target, final String methodName, final Object[] arguments, final Collection<Method> staticMethods) throws Throwable { final Ref<Boolean> convertVarArgs = Ref.create(Boolean.FALSE); final Collection<Method> methods = target == null ? staticMethods : Arrays.asList(target.getClass().getMethods()); final Method method = findMethod(methodName, arguments, methods, convertVarArgs); if (method != null) { try { final Object[] newArgs; if (!convertVarArgs.get()) newArgs = arguments; else { final Class<?>[] parameterTypes = method.getParameterTypes(); newArgs = new Object[parameterTypes.length]; System.arraycopy(arguments, 0, newArgs, 0, parameterTypes.length - 1); final Object[] varArgs = (Object[])Array .newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(), arguments.length - parameterTypes.length + 1); System.arraycopy(arguments, parameterTypes.length - 1, varArgs, 0, varArgs.length); newArgs[parameterTypes.length - 1] = varArgs; } return method.invoke(target, newArgs); } catch (InvocationTargetException e) { throw e.getTargetException(); } } throw new NoSuchMethodException("unknown symbol: "+methodName + "(" + StringUtil.join(arguments, new Function<Object, String>() { public String fun(Object o) { return String.valueOf(o); } }, ", ")+")"); }
Example 9
Source File: GraphQLReferenceService.java From js-graphql-intellij-plugin with MIT License | 5 votes |
private PsiReference resolveObjectField(GraphQLReferencePsiElement element, GraphQLObjectField field) { final String name = element.getName(); if (name != null) { final GraphQLTypeScopeProvider fieldTypeScopeProvider = PsiTreeUtil.getParentOfType(field, GraphQLTypeScopeProvider.class); if (fieldTypeScopeProvider != null) { GraphQLType typeScope = fieldTypeScopeProvider.getTypeScope(); if (typeScope != null) { final String namedTypeScope = GraphQLUtil.getUnmodifiedType(typeScope).getName(); final Ref<Boolean> resolved = Ref.create(false); final PsiReference reference = resolveUsingIndex(element, psiNamedElement -> { if (psiNamedElement.getParent() instanceof GraphQLInputValueDefinition) { final GraphQLInputObjectTypeDefinition inputTypeDefinition = PsiTreeUtil.getParentOfType(psiNamedElement, GraphQLInputObjectTypeDefinition.class); if (inputTypeDefinition != null && inputTypeDefinition.getTypeNameDefinition() != null) { if (namedTypeScope.equals(inputTypeDefinition.getTypeNameDefinition().getName())) { resolved.set(true); return true; } } } return false; }); if (!resolved.get()) { // Endpoint language final JSGraphQLEndpointNamedTypeRegistry endpointNamedTypeRegistry = JSGraphQLEndpointNamedTypeRegistry.getService(element.getProject()); final JSGraphQLNamedType namedType = endpointNamedTypeRegistry.getNamedType(namedTypeScope, element); if (namedType != null) { final JSGraphQLPropertyType property = namedType.properties.get(field.getName()); if (property != null) { return createReference(element, property.propertyElement); } } } return reference; } } } return null; }
Example 10
Source File: RenameProjectHandler.java From consulo with Apache License 2.0 | 5 votes |
@Override public boolean canClose(final String inputString) { if (!inputString.equals(myProject.getName())) { myProject.setProjectName(inputString); myProject.save(); } if (myModule != null && !inputString.equals(myModule.getName())) { final ModifiableModuleModel modifiableModel = ModuleManager.getInstance(myProject).getModifiableModel(); try { modifiableModel.renameModule(myModule, inputString); } catch (ModuleWithNameAlreadyExistsException moduleWithNameAlreadyExists) { Messages.showErrorDialog(myProject, IdeBundle.message("error.module.already.exists", inputString), IdeBundle.message("title.rename.module")); return false; } final Ref<Boolean> success = Ref.create(Boolean.TRUE); CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { modifiableModel.commit(); } }); } }, IdeBundle.message("command.renaming.module", myModule.getName()), null); return success.get().booleanValue(); } return true; }
Example 11
Source File: EncodingUtil.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public static Pair<Charset, String> getCharsetAndTheReasonTooltip(@Nonnull VirtualFile file) { FailReason r1 = checkCanConvert(file); if (r1 == null) return null; Ref<Charset> current = Ref.create(); FailReason r2 = checkCanReload(file, current); if (r2 == null) return null; String errorDescription = r1 == r2 ? reasonToString(r1, file) : reasonToString(r1, file) + ", " + reasonToString(r2, file); return Pair.create(current.get(), errorDescription); }
Example 12
Source File: ActionUpdateEdtExecutor.java From consulo with Apache License 2.0 | 5 votes |
/** * Compute the supplied value on Swing thread, but try to avoid deadlocks by periodically performing {@link ProgressManager#checkCanceled()} in the current thread. * Makes sense to be used in background read actions running with a progress indicator that's canceled when a write action is about to occur. * * @see com.intellij.openapi.application.ReadAction#nonBlocking(Runnable) */ public static <T> T computeOnEdt(Supplier<T> supplier) { Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { return supplier.get(); } Semaphore semaphore = new Semaphore(1); ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator(); Ref<T> result = Ref.create(); ApplicationManager.getApplication().invokeLater(() -> { try { if (indicator == null || !indicator.isCanceled()) { result.set(supplier.get()); } } finally { semaphore.up(); } }); while (!semaphore.waitFor(10)) { if (indicator != null && indicator.isCanceled()) { // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788 throw new ProcessCanceledException(); } } // check cancellation one last time, to ensure the EDT action wasn't no-op due to cancellation if (indicator != null && indicator.isCanceled()) { throw new ProcessCanceledException(); } return result.get(); }
Example 13
Source File: XQueryBreakpointType.java From intellij-xquery with Apache License 2.0 | 5 votes |
private boolean hasAnExpression(Project project, Document document, int line) { final Ref<Boolean> isPartOfExpression = Ref.create(Boolean.FALSE); XDebuggerUtil.getInstance().iterateLine(project, document, line, new Processor<PsiElement>() { @Override public boolean process(PsiElement psiElement) { if (PsiTreeUtil.getParentOfType(psiElement, XQueryExprSingle.class, false) != null) { isPartOfExpression.set(Boolean.TRUE); return false; } else { return true; } } }); return isPartOfExpression.get(); }
Example 14
Source File: XDebuggerTestUtil.java From consulo with Apache License 2.0 | 5 votes |
public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@Nonnull final Project project, @Nonnull final Class<T> exceptionType, @Nonnull final XBreakpointProperties properties) { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); List<XBreakpointType> types = XBreakpointUtil.getBreakpointTypes(); final Ref<XBreakpoint> breakpoint = Ref.create(null); for (XBreakpointType type : types) { if (exceptionType.isInstance(type)) { final T breakpointType = exceptionType.cast(type); WriteAction.run(() -> breakpoint.set(breakpointManager.addBreakpoint(breakpointType, properties))); break; } } return breakpoint.get(); }
Example 15
Source File: EnterHandler.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings) throws IncorrectOperationException { myDocument.insertString(myOffset, buffer); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); CodeStyleManager.getInstance(getProject()).adjustLineIndent(myFile, myOffset + buffer.length() - 2); PsiComment comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class); comment = createJavaDocStub(settings, comment, getProject()); if (comment == null) { return null; } CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject()); final Ref<PsiComment> commentRef = Ref.create(comment); codeStyleManager.runWithDocCommentFormattingDisabled(myFile, () -> formatComment(commentRef, codeStyleManager)); comment = commentRef.get(); PsiElement next = comment.getNextSibling(); if (next == null && comment.getParent().getClass() == comment.getClass()) { next = comment.getParent().getNextSibling(); // expanding chameleon comment produces comment under comment } if (next != null) { next = myFile.findElementAt(next.getTextRange().getStartOffset()); // maybe switch to another tree } if (next != null && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode()) || !next.getText().contains(LINE_SEPARATOR))) { int lineBreakOffset = comment.getTextRange().getEndOffset(); myDocument.insertString(lineBreakOffset, LINE_SEPARATOR); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1); comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class); } return comment; }
Example 16
Source File: DownloadUtil.java From consulo with Apache License 2.0 | 4 votes |
@Nonnull public static <V> Outcome<V> provideDataWithProgressSynchronously( @Nullable Project project, @Nonnull String progressTitle, @Nonnull final String actionShortDescription, @Nonnull final Callable<V> supplier, @Nullable Producer<Boolean> tryAgainProvider) { int attemptNumber = 1; while (true) { final Ref<V> dataRef = Ref.create(null); final Ref<Exception> innerExceptionRef = Ref.create(null); boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); indicator.setText(actionShortDescription); try { V data = supplier.call(); dataRef.set(data); } catch (Exception ex) { innerExceptionRef.set(ex); } } }, progressTitle, true, project); if (!completed) { return Outcome.createAsCancelled(); } Exception latestInnerException = innerExceptionRef.get(); if (latestInnerException == null) { return Outcome.createNormal(dataRef.get()); } LOG.warn("[attempt#" + attemptNumber + "] Can not '" + actionShortDescription + "'", latestInnerException); boolean onceMore = false; if (tryAgainProvider != null) { onceMore = Boolean.TRUE.equals(tryAgainProvider.produce()); } if (!onceMore) { return Outcome.createAsException(latestInnerException); } attemptNumber++; } }
Example 17
Source File: ExternalSystemApiUtil.java From consulo with Apache License 2.0 | 4 votes |
public static <T> T executeOnEdt(@Nonnull final Computable<T> task) { final Application app = ApplicationManager.getApplication(); final Ref<T> result = Ref.create(); app.invokeAndWait(() -> result.set(task.compute())); return result.get(); }
Example 18
Source File: FutureResult.java From consulo with Apache License 2.0 | 4 votes |
public void set(@Nullable T result) { if (myValue != null) throw new IllegalStateException("Result is already set"); myValue = Ref.create(Pair.create((Object)result, true)); mySema.release(); }
Example 19
Source File: GraphQLReferenceService.java From js-graphql-intellij-plugin with MIT License | 4 votes |
private PsiReference resolveEnumValue(GraphQLReferencePsiElement element) { final String name = element.getName(); if (name != null) { final GraphQLTypeScopeProvider enumTypeScopeProvider = PsiTreeUtil.getParentOfType(element, GraphQLTypeScopeProvider.class); if (enumTypeScopeProvider != null) { GraphQLType typeScope = enumTypeScopeProvider.getTypeScope(); if (typeScope != null) { final String namedTypeScope = GraphQLUtil.getUnmodifiedType(typeScope).getName(); final Ref<Boolean> resolved = Ref.create(false); final PsiReference reference = resolveUsingIndex(element, psiNamedElement -> { if (psiNamedElement.getParent() instanceof GraphQLEnumValue) { final GraphQLEnumTypeDefinition enumTypeDefinition = PsiTreeUtil.getParentOfType(psiNamedElement, GraphQLEnumTypeDefinition.class); if (enumTypeDefinition != null && enumTypeDefinition.getTypeNameDefinition() != null) { if (namedTypeScope.equals(enumTypeDefinition.getTypeNameDefinition().getName())) { resolved.set(true); return true; } } } return false; }); if (!resolved.get()) { // Endpoint Language final JSGraphQLEndpointNamedTypeRegistry endpointNamedTypeRegistry = JSGraphQLEndpointNamedTypeRegistry.getService(element.getProject()); final JSGraphQLNamedType namedType = endpointNamedTypeRegistry.getNamedType(namedTypeScope, element); if (namedType != null && namedType.definitionElement instanceof JSGraphQLEndpointEnumTypeDefinition) { final JSGraphQLEndpointEnumValueDefinitionSet enumValueDefinitionSet = ((JSGraphQLEndpointEnumTypeDefinition) namedType.definitionElement).getEnumValueDefinitionSet(); if (enumValueDefinitionSet != null) { for (JSGraphQLEndpointEnumValueDefinition enumValueDefinition : enumValueDefinitionSet.getEnumValueDefinitionList()) { if (enumValueDefinition.getIdentifier().getText().equals(element.getName())) { return createReference(element, enumValueDefinition); } } } } } return reference; } } } return null; }
Example 20
Source File: GraphQLIntrospectionHelper.java From js-graphql-intellij-plugin with MIT License | 4 votes |
@SuppressWarnings("unchecked") public String printIntrospectionJsonAsGraphQL(String introspectionJson) { Map<String, Object> introspectionAsMap = new Gson().fromJson(sanitizeIntrospectionJson(introspectionJson), Map.class); if (!introspectionAsMap.containsKey("__schema")) { // possibly a full query result if (introspectionAsMap.containsKey("errors")) { throw new IllegalArgumentException("Introspection query returned errors: " + new Gson().toJson(introspectionAsMap.get("errors"))); } if (!introspectionAsMap.containsKey("data")) { throw new IllegalArgumentException("Expected data key to be present in query result. Got keys: " + introspectionAsMap.keySet()); } introspectionAsMap = (Map<String, Object>) introspectionAsMap.get("data"); if (!introspectionAsMap.containsKey("__schema")) { throw new IllegalArgumentException("Expected __schema key to be present in query result data. Got keys: " + introspectionAsMap.keySet()); } } if (!GraphQLSettings.getSettings(myProject).isEnableIntrospectionDefaultValues()) { // strip out the defaultValues that are potentially non-spec compliant Ref<Consumer<Object>> defaultValueVisitJson = Ref.create(); defaultValueVisitJson.set((value) -> { if (value instanceof Collection) { ((Collection) value).forEach(colValue -> defaultValueVisitJson.get().consume(colValue)); } else if (value instanceof Map) { ((Map) value).remove("defaultValue"); ((Map) value).values().forEach(mapValue -> defaultValueVisitJson.get().consume(mapValue)); } }); defaultValueVisitJson.get().consume(introspectionAsMap); } final Document schemaDefinition = new GraphQLIntrospectionResultToSchema().createSchemaDefinition(introspectionAsMap); final SchemaPrinter.Options options = SchemaPrinter.Options .defaultOptions() .includeScalarTypes(false) .includeSchemaDefinition(true) .includeDirectives(directive -> !DEFAULT_DIRECTIVES.contains(directive.getName())); final TypeDefinitionRegistry registry = new SchemaParser().buildRegistry(schemaDefinition); final StringBuilder sb = new StringBuilder(new SchemaPrinter(options).print(buildIntrospectionSchema(registry))); // graphql-java only prints scalars that are used by fields since it visits fields to discover types, so add the scalars here manually final Set<String> knownScalars = Sets.newHashSet(); for (Node definition : schemaDefinition.getChildren()) { if (definition instanceof ScalarTypeDefinition) { final ScalarTypeDefinition scalarTypeDefinition = (ScalarTypeDefinition) definition; String scalarName = scalarTypeDefinition.getName(); if (knownScalars.add(scalarName)) { sb.append("\n\n"); final Description description = scalarTypeDefinition.getDescription(); if (description != null) { if (description.isMultiLine()) { sb.append("\"\"\"").append(description.getContent()).append("\"\"\""); } else { sb.append("\"").append(description.getContent()).append("\""); } sb.append("\n"); } sb.append("scalar ").append(scalarName); } } } return sb.toString(); }