Java Code Examples for com.intellij.openapi.util.Ref#get()

The following examples show how to use com.intellij.openapi.util.Ref#get() . 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: ThriftPsiUtil.java    From intellij-thrift with Apache License 2.0 6 votes vote down vote up
@Nullable
public static ThriftInclude findImportByPrefix(@NotNull PsiFile psiFile, @NotNull final String fileName) {
  final Ref<ThriftInclude> result = new Ref<ThriftInclude>();
  processIncludes(psiFile, new Processor<ThriftInclude>() {
    @Override
    public boolean process(ThriftInclude include) {
      String path = include.getPath();
      if (FileUtil.getNameWithoutExtension(new File(path)).equals(fileName)) {
        result.set(include);
        return false;
      }
      return true;
    }
  });
  return result.get();
}
 
Example 2
Source File: ASTStructure.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int getChildren(@Nonnull final ASTNode astNode, @Nonnull final Ref<ASTNode[]> into) {
  ASTNode child = astNode.getFirstChildNode();
  if (child == null) return 0;

  ASTNode[] store = into.get();
  if (store == null) {
    store = new ASTNode[10];
    into.set(store);
  }

  int count = 0;
  while (child != null) {
    if (count >= store.length) {
      ASTNode[] newStore = new ASTNode[count * 3 / 2];
      System.arraycopy(store, 0, newStore, 0, count);
      into.set(newStore);
      store = newStore;
    }
    store[count++] = child;
    child = child.getTreeNext();
  }

  return count;
}
 
Example 3
Source File: FileStructureDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean navigateSelectedElement() {
  final Ref<Boolean> succeeded = new Ref<Boolean>();
  final CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      succeeded.set(MyCommanderPanel.super.navigateSelectedElement());
      IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
    }
  }, "Navigate", null);
  if (succeeded.get()) {
    close(CANCEL_EXIT_CODE);
  }
  return succeeded.get();
}
 
Example 4
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Isolate getCurrentIsolate() {
  final Ref<Isolate> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getIsolate(isolateRef.getId(), new GetIsolateConsumer() {
    @Override
    public void received(Isolate isolate) {
      resultRef.set(isolate);
      semaphore.up();
    }

    @Override
    public void received(Sentinel sentinel) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example 5
Source File: ChangesTreeList.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int findRowContainingFile(@Nonnull TreeNode root, @Nonnull final VirtualFile toSelect) {
  final Ref<Integer> row = Ref.create(-1);
  TreeUtil.traverse(root, node -> {
    if (node instanceof DefaultMutableTreeNode) {
      Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
      if (userObject instanceof Change) {
        if (matches((Change)userObject, toSelect)) {
          TreeNode[] path = ((DefaultMutableTreeNode)node).getPath();
          row.set(getRowForPath(new TreePath(path)));
        }
      }
    }

    return row.get() == -1;
  });
  return row.get();
}
 
Example 6
Source File: MemberChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ElementNodeImpl(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) {
  myOrder = order.get();
  order.set(myOrder + 1);
  myDelegate = delegate;
  if (parent != null) {
    parent.add(this);
  }
}
 
Example 7
Source File: SkylarkDebugProcess.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void handleConditionalBreakpointError(
    XLineBreakpoint<XBreakpointProperties> breakpoint, PausedThread thread) {
  // TODO(brendandouglas): also navigate to the problematic breakpoint
  String error = Preconditions.checkNotNull(thread.getConditionalBreakpointError().getMessage());
  String title = "Breakpoint Condition Error";
  String message =
      String.format(
          "Breakpoint: %s\nError: %s\nWould you like to stop at the breakpoint?",
          breakpoint.getType().getDisplayText(breakpoint), error);
  Ref<Boolean> stop = new Ref<>(true);
  ApplicationManager.getApplication()
      .invokeAndWait(
          () ->
              stop.set(
                  Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon())
                      == Messages.YES));
  if (stop.get()) {
    notifyThreadPaused(thread);
    return;
  }
  // else resume the thread
  transport.sendRequest(
      DebugRequest.newBuilder()
          .setContinueExecution(
              ContinueExecutionRequest.newBuilder()
                  .setThreadId(thread.getId())
                  .setStepping(Stepping.NONE)
                  .build()));
}
 
Example 8
Source File: VmServiceWrapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) {
  assertSyncRequestAllowed();

  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  final Ref<Script> resultRef = Ref.create();

  addRequest(() -> myVmService.getObject(isolateId, scriptId, new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  }));

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example 9
Source File: UnixProcessManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void findChildProcesses(final int our_pid,
                                       final int process_pid,
                                       final Ref<Integer> foundPid,
                                       final ProcessInfo processInfo,
                                       final List<Integer> childrenPids) {
  final Ref<Boolean> ourPidFound = Ref.create(false);
  processPSOutput(getPSCmd(false), new Processor<String>() {
    @Override
    public boolean process(String s) {
      StringTokenizer st = new StringTokenizer(s, " ");

      int parent_pid = Integer.parseInt(st.nextToken());
      int pid = Integer.parseInt(st.nextToken());

      processInfo.register(pid, parent_pid);

      if (parent_pid == process_pid) {
        childrenPids.add(pid);
      }

      if (pid == our_pid) {
        ourPidFound.set(true);
      }
      else if (pid == process_pid) {
        if (parent_pid == our_pid || our_pid == -1) {
          foundPid.set(pid);
        }
        else {
          throw new IllegalStateException("Process (pid=" + process_pid + ") is not our child(our pid = " + our_pid + ")");
        }
      }
      return false;
    }
  });
  if (our_pid != -1 && !ourPidFound.get()) {
    throw new IllegalStateException("IDE pid is not found in ps list(" + our_pid + ")");
  }
}
 
Example 10
Source File: CSharpCreateFileAction.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static boolean isCreationOfAssemblyFileAvailable(PsiDirectory directory)
{
	Module module = ModuleUtilCore.findModuleForPsiElement(directory);
	if(module != null)
	{
		DotNetModuleExtension extension = ModuleUtilCore.getExtension(module, DotNetModuleExtension.class);
		if(extension != null && extension.isAllowSourceRoots())
		{
			return false;
		}
	}
	if(module == null || ModuleUtilCore.getExtension(module, CSharpSimpleModuleExtension.class) == null)
	{
		return false;
	}

	final Ref<VirtualFile> ref = Ref.create();
	VirtualFile moduleDir = module.getModuleDir();
	if(moduleDir == null)
	{
		return false;
	}
	VfsUtil.visitChildrenRecursively(moduleDir, new VirtualFileVisitor<Object>()
	{
		@Override
		public boolean visitFile(@Nonnull VirtualFile file)
		{
			if(file.getName().equals(CSharpAssemblyConstants.FileName))
			{
				ref.set(file);
				return false;
			}
			return true;
		}
	});

	return ref.get() == null;
}
 
Example 11
Source File: ApplicationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to interrupt a process which does not performs checkCancelled() calls by itself.
 * Note that the process may continue to run in background indefinitely - so <b>avoid using this method unless absolutely needed</b>.
 */
public static <T> T runWithCheckCanceled(@Nonnull final Callable<T> callable, @Nonnull final ProgressIndicator indicator) throws Exception {
  final Ref<T> result = Ref.create();
  final Ref<Throwable> error = Ref.create();

  Future<?> future = PooledThreadExecutor.INSTANCE.submit(() -> ProgressManager.getInstance().executeProcessUnderProgress(() -> {
    try {
      result.set(callable.call());
    }
    catch (Throwable t) {
      error.set(t);
    }
  }, indicator));

  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      future.cancel(true);
      throw e;
    }

    try {
      future.get(200, TimeUnit.MILLISECONDS);
      ExceptionUtil.rethrowAll(error.get());
      return result.get();
    }
    catch (TimeoutException ignored) {
    }
  }
}
 
Example 12
Source File: VmServiceWrapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) {
  assertSyncRequestAllowed();

  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  final Ref<Script> resultRef = Ref.create();

  addRequest(() -> myVmService.getObject(isolateId, scriptId, new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  }));

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example 13
Source File: ReplaceInProjectManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
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 14
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private LocalFileSystem.WatchRequest watch(final File watchFile, final boolean recursive) {
  final Ref<LocalFileSystem.WatchRequest> request = Ref.create();
  getEvents("events to add watch " + watchFile, new Runnable() {
    @Override
    public void run() {
      request.set(myFileSystem.addRootToWatch(watchFile.getPath(), recursive));
    }
  });
  assertFalse(request.isNull());
  assertFalse(myWatcher.isSettingRoots());
  return request.get();
}
 
Example 15
Source File: SequentialTaskExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
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 16
Source File: GraphQLReferenceService.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
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 17
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(
    PsiFile file,
    Editor editor,
    Ref<Integer> caretOffset,
    Ref<Integer> caretAdvance,
    DataContext dataContext,
    EditorActionHandler originalHandler) {
  int offset = caretOffset.get();
  if (editor instanceof EditorWindow) {
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    editor = InjectedLanguageUtil.getTopLevelEditor(editor);
    offset = editor.getCaretModel().getOffset();
  }
  if (!isApplicable(file, dataContext)) {
    return Result.Continue;
  }

  // Previous enter handler's (e.g. EnterBetweenBracesHandler) can introduce a mismatch
  // between the editor's caret model and the offset we've been provided with.
  editor.getCaretModel().moveToOffset(offset);

  Document doc = editor.getDocument();
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);

  // #api173: get file, language specific settings instead
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
  Integer indent = determineIndent(file, editor, offset, settings);
  if (indent == null) {
    return Result.Continue;
  }

  removeTrailingWhitespace(doc, file, offset);
  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  LogicalPosition position = editor.getCaretModel().getLogicalPosition();
  if (position.column == indent) {
    return Result.Stop;
  }
  if (position.column > indent) {
    // default enter handler has added too many spaces -- remove them
    int excess = position.column - indent;
    doc.deleteString(
        editor.getCaretModel().getOffset() - excess, editor.getCaretModel().getOffset());
  } else if (position.column < indent) {
    String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
    doc.insertString(editor.getCaretModel().getOffset(), spaces);
  }
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
  return Result.Stop;
}
 
Example 18
Source File: GraphQLScopeEditorNotificationProvider.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
private boolean showNotification(@NotNull VirtualFile file) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        // injection enumerate below causes missing JSON schemas in 2019.2 for eslint
        return false;
    }
    if (!isGraphQLRelatedFile(file) || DumbService.getInstance(myProject).isDumb()) {
        return false;
    }
    final GraphQLConfigManager graphQLConfigManager = GraphQLConfigManager.getService(myProject);
    if (!graphQLConfigManager.isInitialized()) {
        return false;
    }
    if (file.getFileType() != GraphQLFileType.INSTANCE) {
        // for injected files, must contain graphql before the warning is shown
        final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
        final Ref<Boolean> hasGraphQL = new Ref<>(false);
        if (psiFile != null) {
            final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject);
            psiFile.accept(new PsiRecursiveElementVisitor() {
                @Override
                public void visitElement(PsiElement element) {
                    if (hasGraphQL.get()) {
                        return;
                    }
                    if (element instanceof PsiLanguageInjectionHost) {
                        injectedLanguageManager.enumerate(element, (injectedPsi, places) -> {
                            if (injectedPsi instanceof GraphQLFile) {
                                hasGraphQL.set(true);
                            }
                        });
                    } else {
                        super.visitElement(element);
                    }
                }
            });
        }
        if (!hasGraphQL.get()) {
            return false;
        }
    }
    if (GlobalSearchScope.projectScope(myProject).accept(file)) {
        if (graphQLConfigManager.getClosestConfigFile(file) != null) {
            if (graphQLConfigManager.getClosestIncludingConfigFile(file) == null) {
                // has config, but is not included
                return true;
            }
        }
    }
    return false;
}
 
Example 19
Source File: EnterAfterJavadocTagHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull PsiFile file,
                              @Nonnull Editor editor,
                              @Nonnull Ref<Integer> caretOffset,
                              @Nonnull Ref<Integer> caretAdvance,
                              @Nonnull DataContext dataContext,
                              EditorActionHandler originalHandler) {
  if (!CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
    return Result.Continue;
  }

  Document document = editor.getDocument();
  CharSequence text = document.getCharsSequence();
  int line = document.getLineNumber(caretOffset.get());
  int start = document.getLineStartOffset(line);
  int end = document.getLineEndOffset(line);

  CodeDocumentationUtil.CommentContext commentContext = CodeDocumentationUtil.tryParseCommentContext(file, text, caretOffset.get(), start);
  if (!commentContext.docAsterisk) {
    return Result.Continue;
  }

  Context context = parse(text, start, end, caretOffset.get());
  if (!context.shouldGenerateLine()) {
    return context.shouldIndent() ? Result.DefaultForceIndent : Result.Continue;
  }

  String indentInsideJavadoc = CodeDocumentationUtil.getIndentInsideJavadoc(document, caretOffset.get());

  boolean restoreCaret = false;
  if (caretOffset.get() != context.endTagStartOffset) {
    editor.getCaretModel().moveToOffset(context.endTagStartOffset);
    restoreCaret = true;
  }

  originalHandler.execute(editor, dataContext);
  Project project = editor.getProject();
  if (indentInsideJavadoc != null && project != null && CodeStyleSettingsManager.getSettings(project).JD_LEADING_ASTERISKS_ARE_ENABLED) {
    document.insertString(editor.getCaretModel().getOffset(), "*" + indentInsideJavadoc);
  }

  if (restoreCaret) {
    editor.getCaretModel().moveToOffset(caretOffset.get());
  }

  return Result.DefaultForceIndent;
}
 
Example 20
Source File: CoreProgressManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T runProcess(@Nonnull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException {
  final Ref<T> ref = new Ref<>();
  runProcess(() -> ref.set(process.compute()), progress);
  return ref.get();
}