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

The following examples show how to use com.intellij.openapi.util.Ref#set() . 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: CSharpEnterInDocLineCommentHandler.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredUIAccess
public Result preprocessEnter(@Nonnull final PsiFile file,
		@Nonnull final Editor editor,
		@Nonnull final Ref<Integer> caretOffsetRef,
		@Nonnull final Ref<Integer> caretAdvance,
		@Nonnull final DataContext dataContext,
		final EditorActionHandler originalHandler)
{
	final int caretOffset = caretOffsetRef.get();
	final Document document = editor.getDocument();
	final PsiElement psiAtOffset = file.findElementAt(caretOffset);
	final PsiElement probablyDocComment = psiAtOffset instanceof PsiWhiteSpace && psiAtOffset.getText().startsWith("\n") ? psiAtOffset.getPrevSibling() : psiAtOffset == null && caretOffset > 0
			&& caretOffset == document.getTextLength() ? file.findElementAt(caretOffset - 1) : psiAtOffset;

	if(probablyDocComment != null && PsiTreeUtil.getParentOfType(probablyDocComment, CSharpDocRoot.class, false) != null)
	{
		document.insertString(caretOffset, DOC_LINE_START + " ");
		caretAdvance.set(4);
		return Result.Default;
	}

	return Result.Continue;
}
 
Example 2
Source File: EncodingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
static FailReason checkCanReload(@Nonnull VirtualFile virtualFile, @Nullable Ref<? super Charset> current) {
  if (virtualFile.isDirectory()) {
    return FailReason.IS_DIRECTORY;
  }
  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  Document document = documentManager.getDocument(virtualFile);
  if (document == null) return FailReason.IS_BINARY;
  Charset charsetFromContent = ((EncodingManagerImpl)EncodingManager.getInstance()).computeCharsetFromContent(virtualFile);
  Charset existing = virtualFile.getCharset();
  LoadTextUtil.AutoDetectionReason autoDetectedFrom = LoadTextUtil.getCharsetAutoDetectionReason(virtualFile);
  FailReason result;
  if (autoDetectedFrom != null) {
    // no point changing encoding if it was auto-detected
    result = autoDetectedFrom == LoadTextUtil.AutoDetectionReason.FROM_BOM ? FailReason.BY_BOM : FailReason.BY_BYTES;
  }
  else if (charsetFromContent != null) {
    result = FailReason.BY_FILE;
    existing = charsetFromContent;
  }
  else {
    result = fileTypeDescriptionError(virtualFile);
  }
  if (current != null) current.set(existing);
  return result;
}
 
Example 3
Source File: BlazeBuildFileRunConfigurationProducer.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doSetupConfigFromContext(
    BlazeCommandRunConfiguration configuration,
    ConfigurationContext context,
    Ref<PsiElement> sourceElement) {
  BlazeProjectData blazeProjectData =
      BlazeProjectDataManager.getInstance(configuration.getProject()).getBlazeProjectData();
  if (blazeProjectData == null) {
    return false;
  }
  BuildTarget target = getBuildTarget(context);
  if (target == null) {
    return false;
  }
  sourceElement.set(target.rule);
  setupConfiguration(configuration.getProject(), blazeProjectData, configuration, target);
  return true;
}
 
Example 4
Source File: PantsPythonTestRunConfigurationProducer.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private boolean buildFromPyTest(
  PsiElement testElem,
  String elemStr,
  String path,
  List<String> targets,
  ExternalSystemTaskExecutionSettings taskSettings,
  Ref<PsiElement> sourceElement,
  ExternalSystemRunConfiguration configuration
) {
  sourceElement.set(testElem);
  configuration.setName("Pants tests in " + elemStr);
  taskSettings.setExternalProjectPath(path);
  String scriptParams = StringUtil.join(targets, " ");
  scriptParams += " " + PantsConstants.PANTS_CLI_OPTION_PYTEST + "=\"-k " + elemStr + "\"";
  final Optional<String> rcIterate = IJRC.getIteratePantsRc(path);
  scriptParams += rcIterate.orElse("");

  taskSettings.setExecutionName(elemStr);
  taskSettings.setScriptParameters(scriptParams);
  return true;
}
 
Example 5
Source File: ChangeRange.java    From consulo with Apache License 2.0 6 votes vote down vote up
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 6
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 7
Source File: ReplaceInProjectManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean getStringToReplace(int textOffset, int textEndOffset, Document document, FindModel findModel, Ref<? super String> stringToReplace)
        throws FindManager.MalformedReplacementStringException {
  if (textOffset < 0 || textOffset >= document.getTextLength()) {
    return false;
  }
  if (textEndOffset < 0 || textEndOffset > document.getTextLength()) {
    return false;
  }
  FindManager findManager = FindManager.getInstance(myProject);
  final CharSequence foundString = document.getCharsSequence().subSequence(textOffset, textEndOffset);
  PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
  FindResult findResult = findManager.findString(document.getCharsSequence(), textOffset, findModel, file != null ? file.getVirtualFile() : null);
  if (!findResult.isStringFound() ||
      // find result should be in needed range
      !(findResult.getStartOffset() >= textOffset && findResult.getEndOffset() <= textEndOffset)) {
    return false;
  }

  stringToReplace.set(FindManager.getInstance(myProject).getStringToReplace(foundString.toString(), findModel, textOffset, document.getText()));

  return true;
}
 
Example 8
Source File: EnterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void formatComment(Ref<PsiComment> commentRef, CodeStyleManager codeStyleManager) {
  PsiComment comment = commentRef.get();
  RangeMarker commentMarker = myDocument.createRangeMarker(comment.getTextRange().getStartOffset(), comment.getTextRange().getEndOffset());
  codeStyleManager.reformatNewlyAddedElement(comment.getNode().getTreeParent(), comment.getNode());
  commentRef.set(PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(commentMarker.getStartOffset()), PsiComment.class));
  commentMarker.dispose();
}
 
Example 9
Source File: JSGraphQLEndpointErrorAnnotator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Compares the signatures of two fields, ignoring comments, whitespace, and annotations
 */
private boolean hasSameSignature(JSGraphQLEndpointFieldDefinition override, JSGraphQLEndpointFieldDefinition toImplement) {
	final StringBuilder toImplementSignature = new StringBuilder();
	final StringBuilder overrideSignature = new StringBuilder();

	final Ref<StringBuilder> sb = new Ref<>();
	final PsiElementVisitor visitor = new PsiRecursiveElementVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof JSGraphQLEndpointAnnotation) {
				return;
			}
			if (element instanceof PsiWhiteSpace) {
				return;
			}
			if (element instanceof PsiComment) {
				return;
			}
			if (element instanceof LeafPsiElement) {
				sb.get().append(element.getText()).append(" ");
			}
			super.visitElement(element);
		}
	};

	sb.set(overrideSignature);
	override.accept(visitor);

	sb.set(toImplementSignature);
	toImplement.accept(visitor);

	return toImplementSignature.toString().equals(overrideSignature.toString());
}
 
Example 10
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 11
Source File: MemberChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * should be invoked in read action
 */
private DefaultTreeModel buildModel() {
  final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
  final Ref<Integer> count = new Ref<Integer>(0);
  Ref<Map<MemberChooserObject, ParentNode>> mapRef = new Ref<>();
  mapRef.set(FactoryMap.create(key -> {
    ParentNode node = null;
    DefaultMutableTreeNode parentNode1 = rootNode;

    if (supportsNestedContainers() && key instanceof ClassMember) {
      MemberChooserObject parentNodeDelegate = ((ClassMember)key).getParentNodeDelegate();

      if (parentNodeDelegate != null) {
        parentNode1 = mapRef.get().get(parentNodeDelegate);
      }
    }
    if (isContainerNode(key)) {
      final ContainerNode containerNode = new ContainerNode(parentNode1, key, count);
      node = containerNode;
      myContainerNodes.add(containerNode);
    }
    if (node == null) {
      node = new ParentNode(parentNode1, key, count);
    }
    return node;
  }));

  final Map<MemberChooserObject, ParentNode> map = mapRef.get();

  for (T object : myElements) {
    final ParentNode parentNode = map.get(object.getParentNodeDelegate());
    final MemberNode elementNode = createMemberNode(count, object, parentNode);
    myNodeToParentMap.put(elementNode, parentNode);
    myElementToNodeMap.put(object, elementNode);
  }
  return new DefaultTreeModel(rootNode);
}
 
Example 12
Source File: SMTestRunnerResultsFormTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testChangeSelectionAction() {
  final Marker onSelectedHappend = new Marker();
  final Ref<SMTestProxy> proxyRef = new Ref<>();
  final Ref<Boolean> focusRequestedRef = new Ref<>();

  myResultsViewer.setShowStatisticForProxyHandler(new PropagateSelectionHandler() {
    @Override
    public void handlePropagateSelectionRequest(@Nullable final SMTestProxy selectedTestProxy, @Nonnull final Object sender,
                                                final boolean requestFocus) {
      onSelectedHappend.set();
      proxyRef.set(selectedTestProxy);
      focusRequestedRef.set(requestFocus);
    }
  });

  final SMTestProxy suite = createSuiteProxy("suite", myTestsRootNode);
  final SMTestProxy test = createTestProxy("test", myTestsRootNode);
  myResultsViewer.onSuiteStarted(suite);
  myResultsViewer.onTestStarted(test);

  //On test
  myResultsViewer.selectAndNotify(test);
  myResultsViewer.showStatisticsForSelectedProxy();
  assertTrue(onSelectedHappend.isSet());
  assertEquals(test, proxyRef.get());
  assertTrue(focusRequestedRef.get());

  //on suite
  //reset markers
  onSelectedHappend.reset();
  proxyRef.set(null);
  focusRequestedRef.set(null);

  myResultsViewer.selectAndNotify(suite);
  myResultsViewer.showStatisticsForSelectedProxy();
  assertTrue(onSelectedHappend.isSet());
  assertEquals(suite, proxyRef.get());
  assertTrue(focusRequestedRef.get());
}
 
Example 13
Source File: GraphQLPsiUtil.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public static String getTypeName(PsiElement psiElement, @Nullable Ref<GraphQLIdentifier> typeNameRef) {

        if (psiElement != null) {

            final PsiElement typeOwner = PsiTreeUtil.getParentOfType(psiElement, GraphQLTypeNameDefinitionOwnerPsiElement.class, GraphQLTypeNameExtensionOwnerPsiElement.class);

            GraphQLIdentifier nameIdentifier = null;

            if (typeOwner instanceof GraphQLTypeNameDefinitionOwnerPsiElement) {
                final GraphQLTypeNameDefinition typeNameDefinition = ((GraphQLTypeNameDefinitionOwnerPsiElement) typeOwner).getTypeNameDefinition();
                if (typeNameDefinition != null) {
                    nameIdentifier = typeNameDefinition.getNameIdentifier();
                }
            } else if (typeOwner instanceof GraphQLTypeNameExtensionOwnerPsiElement) {
                final GraphQLTypeName typeName = ((GraphQLTypeNameExtensionOwnerPsiElement) typeOwner).getTypeName();
                if (typeName != null) {
                    nameIdentifier = typeName.getNameIdentifier();
                }
            }

            if (nameIdentifier != null) {
                if (typeNameRef != null) {
                    typeNameRef.set(nameIdentifier);
                }
                return nameIdentifier.getText();
            }

        }

        return null;
    }
 
Example 14
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
boolean processFiles(@Nonnull FindSymbolParameters parameters,
                     @Nonnull Processor<FoundItemDescriptor<?>> processor,
                     @Nonnull Ref<Boolean> hasSuggestions,
                     @Nonnull DirectoryPathMatcher dirMatcher) {
  MinusculeMatcher qualifierMatcher = getQualifiedNameMatcher(parameters.getLocalPatternName());

  List<MatchResult> matchingNames = this.matchingNames;
  if (patternSuffix.length() <= 3 && !dirMatcher.dirPattern.isEmpty()) {
    // just enumerate over files
    // otherwise there are too many names matching the remaining few letters, and querying index for all of them with a very constrained scope is expensive
    Set<String> existingNames = dirMatcher.findFileNamesMatchingIfCheap(patternSuffix.charAt(0), matcher);
    if (existingNames != null) {
      matchingNames = ContainerUtil.filter(matchingNames, mr -> existingNames.contains(mr.elementName));
    }
  }

  List<List<MatchResult>> groups = groupByMatchingDegree(!parameters.getCompletePattern().startsWith("*"), matchingNames);
  for (List<MatchResult> group : groups) {
    JBIterable<FoundItemDescriptor<PsiFileSystemItem>> filesMatchingPath = getFilesMatchingPath(parameters, group, dirMatcher, indicator);
    Iterable<FoundItemDescriptor<PsiFileSystemItem>> matchedFiles =
            parameters.getLocalPatternName().isEmpty() ? filesMatchingPath : matchQualifiers(qualifierMatcher, filesMatchingPath.map(res -> res.getItem()));

    matchedFiles = moveDirectoriesToEnd(matchedFiles);
    Processor<FoundItemDescriptor<PsiFileSystemItem>> trackingProcessor = res -> {
      hasSuggestions.set(true);
      return processor.process(res);
    };
    if (!ContainerUtil.process(matchedFiles, trackingProcessor)) {
      return false;
    }
  }

  // let the framework switch to searching outside project to display these well-matching suggestions
  // instead of worse-matching ones in project (that are very expensive to calculate)
  return hasSuggestions.get() || parameters.isSearchInLibraries() || !hasSuggestionsOutsideProject(parameters.getCompletePattern(), groups, dirMatcher);
}
 
Example 15
Source File: SimpleElementGroupCollector.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredReadAction
@SuppressWarnings("unchecked")
private Collection<E> calcElements()
{
	final Ref<List<E>> listRef = Ref.create();
	Consumer consumer = e ->
	{
		List<E> es = listRef.get();
		if(es == null)
		{
			listRef.set(es = new SmartList<>());
		}

		es.add((E) e);
	};

	CSharpElementVisitor visitor = createVisitor(consumer);

	myResolveContext.acceptChildren(visitor);

	for(CSharpAdditionalMemberProvider memberProvider : CSharpAdditionalMemberProvider.EP_NAME.getExtensionList())
	{
		if(memberProvider.getTarget() == myTarget)
		{
			memberProvider.processAdditionalMembers(myResolveContext.getElement(), getExtractor(), consumer);
		}
	}

	List<E> list = listRef.get();
	if(list == null)
	{
		return Collections.emptyList();
	}
	return list;
}
 
Example 16
Source File: EnterInStringLiteralHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull Ref<Integer> caretOffsetRef,
                              @Nonnull final Ref<Integer> caretAdvanceRef, @Nonnull final DataContext dataContext,
                              final EditorActionHandler originalHandler) {
  int caretOffset = caretOffsetRef.get().intValue();
  int caretAdvance = caretAdvanceRef.get().intValue();
  if (!isInStringLiteral(editor, dataContext, caretOffset)) return Result.Continue;
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
  PsiElement psiAtOffset = file.findElementAt(caretOffset);
  if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) {
    Document document = editor.getDocument();
    CharSequence text = document.getText();
    ASTNode token = psiAtOffset.getNode();
    JavaLikeQuoteHandler quoteHandler = getJavaLikeQuoteHandler(editor, psiAtOffset);

    if (quoteHandler != null &&
        quoteHandler.getConcatenatableStringTokenTypes() != null &&
        quoteHandler.getConcatenatableStringTokenTypes().contains(token.getElementType())) {
      TextRange range = token.getTextRange();
      final char literalStart = token.getText().charAt(0);
      final StringLiteralLexer lexer = new StringLiteralLexer(literalStart, token.getElementType());
      lexer.start(text, range.getStartOffset(), range.getEndOffset());

      while (lexer.getTokenType() != null) {
        if (lexer.getTokenStart() < caretOffset && caretOffset < lexer.getTokenEnd()) {
          if (StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(lexer.getTokenType())) {
            caretOffset = lexer.getTokenEnd();
          }
          break;
        }
        lexer.advance();
      }

      if (quoteHandler.needParenthesesAroundConcatenation(psiAtOffset)) {
        document.insertString(psiAtOffset.getTextRange().getEndOffset(), ")");
        document.insertString(psiAtOffset.getTextRange().getStartOffset(), "(");
        caretOffset++;
        caretAdvance++;
      }

      final String insertedFragment = literalStart + " " + quoteHandler.getStringConcatenationOperatorRepresentation();
      document.insertString(caretOffset, insertedFragment + " " + literalStart);
      caretOffset += insertedFragment.length();
      caretAdvance = 1;
      CommonCodeStyleSettings langSettings =
              CodeStyleSettingsManager.getSettings(file.getProject()).getCommonSettings(file.getLanguage());
      if (langSettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) {
        caretOffset -= 1;
        caretAdvance = 3;
      }
      caretOffsetRef.set(caretOffset);
      caretAdvanceRef.set(caretAdvance);
      return Result.DefaultForceIndent;
    }
  }
  return Result.Continue;
}
 
Example 17
Source File: GraphQLFragmentNameIndex.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
public GraphQLFragmentNameIndex() {
    myDataIndexer = inputData -> {

        final Ref<Boolean> hasFragments = Ref.create(false);

        final Ref<PsiRecursiveElementVisitor> identifierVisitor = Ref.create();
        identifierVisitor.set(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (hasFragments.get()) {
                    // done
                    return;
                }
                if (element instanceof GraphQLDefinition) {
                    if (element instanceof GraphQLFragmentDefinition) {
                        hasFragments.set(true);
                    }
                    return; // no need to visit deeper than definitions since fragments are top level
                } else if (element instanceof PsiLanguageInjectionHost && graphQLInjectionSearchHelper != null) {
                    if (graphQLInjectionSearchHelper.isJSGraphQLLanguageInjectionTarget(element)) {
                        final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(element.getProject());
                        final String graphqlBuffer = StringUtils.strip(element.getText(), "` \t\n");
                        final PsiFile graphqlInjectedPsiFile = psiFileFactory.createFileFromText("", GraphQLFileType.INSTANCE, graphqlBuffer, 0, false, false);
                        graphqlInjectedPsiFile.accept(identifierVisitor.get());
                        return;
                    }
                }
                super.visitElement(element);
            }
        });

        inputData.getPsiFile().accept(identifierVisitor.get());

        if (hasFragments.get()) {
            return Collections.singletonMap(HAS_FRAGMENTS, true);
        } else {
            return Collections.emptyMap();
        }

    };
    includedFileTypes = GraphQLFindUsagesUtil.getService().getIncludedFileTypes();
    graphQLInjectionSearchHelper = ServiceManager.getService(GraphQLInjectionSearchHelper.class);
}
 
Example 18
Source File: AbstractExternalModuleImportProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Asks current builder to ensure that target external project is defined.
 *
 * @param context current wizard context
 * @throws WizardStepValidationException if gradle project is not defined and can't be constructed
 */
@SuppressWarnings("unchecked")
public void ensureProjectIsDefined(@Nonnull ExternalModuleImportContext<C> context) throws WizardStepValidationException {
  final String externalSystemName = myExternalSystemId.getReadableName();
  File projectFile = getProjectFile();
  if (projectFile == null) {
    throw new WizardStepValidationException(ExternalSystemBundle.message("error.project.undefined"));
  }
  projectFile = getExternalProjectConfigToUse(projectFile);
  final Ref<WizardStepValidationException> error = new Ref<>();
  final ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
    @Override
    public void onSuccess(@Nullable DataNode<ProjectData> externalProject) {
      myExternalProjectNode = externalProject;
    }

    @Override
    public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) {
      if (!StringUtil.isEmpty(errorDetails)) {
        LOG.warn(errorDetails);
      }
      error.set(new WizardStepValidationException(ExternalSystemBundle.message("error.resolve.with.reason", errorMessage)));
    }
  };

  final Project project = getContextOrDefaultProject(context);
  final File finalProjectFile = projectFile;
  final String externalProjectPath = FileUtil.toCanonicalPath(finalProjectFile.getAbsolutePath());
  final Ref<WizardStepValidationException> exRef = new Ref<>();
  executeAndRestoreDefaultProjectSettings(project, new Runnable() {
    @Override
    public void run() {
      try {
        ExternalSystemUtil.refreshProject(project, myExternalSystemId, externalProjectPath, callback, true, ProgressExecutionMode.MODAL_SYNC);
      }
      catch (IllegalArgumentException e) {
        exRef.set(new WizardStepValidationException(ExternalSystemBundle.message("error.cannot.parse.project", externalSystemName)));
      }
    }
  });
  WizardStepValidationException ex = exRef.get();
  if (ex != null) {
    throw ex;
  }
  if (myExternalProjectNode == null) {
    WizardStepValidationException exception = error.get();
    if (exception != null) {
      throw exception;
    }
  }
  else {
    applyProjectSettings(context);
  }
}
 
Example 19
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
private void completeFragmentOnTypeName() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {

            final PsiElement completionElement = parameters.getPosition();

            // the type condition that the 'on' keyword belongs to
            GraphQLTypeCondition typeCondition = PsiTreeUtil.getParentOfType(completionElement, GraphQLTypeCondition.class);
            if (typeCondition == null) {
                // typeCondition is on the left if the selection set follows
                typeCondition = PsiTreeUtil.getPrevSiblingOfType(completionElement, GraphQLTypeCondition.class);
            }
            final boolean fragmentDefinition = typeCondition != null && typeCondition.getParent() instanceof GraphQLFragmentDefinition;

            final GraphQLTypeDefinitionRegistryServiceImpl typeDefinitionRegistryService = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject());
            final TypeDefinitionRegistry typeDefinitionRegistry = typeDefinitionRegistryService.getRegistry(parameters.getOriginalFile());

            final List<Pair<TypeDefinition, Description>> fragmentTypes = Lists.newArrayList();

            if (fragmentDefinition) {
                // completion in a top-level fragment definition, so add all known types, interfaces, unions
                typeDefinitionRegistry.types().forEach((key, value) -> {
                    final boolean canFragment = value instanceof ObjectTypeDefinition || value instanceof UnionTypeDefinition || value instanceof InterfaceTypeDefinition;
                    if (canFragment) {
                        fragmentTypes.add(Pair.create(value, typeDefinitionRegistryService.getTypeDefinitionDescription(value)));
                    }
                });
            } else {

                // inline fragment, so get type scope
                GraphQLTypeScopeProvider typeScopeProvider = PsiTreeUtil.getParentOfType(completionElement, GraphQLTypeScopeProvider.class);

                if (typeScopeProvider instanceof GraphQLInlineFragment && ((GraphQLInlineFragment) typeScopeProvider).getTypeCondition() == typeCondition) {
                    // if the type condition belongs to the type scope provider, we want the parent scope since that
                    // is the real source of what we can fragment on
                    typeScopeProvider = PsiTreeUtil.getParentOfType(typeScopeProvider, GraphQLTypeScopeProvider.class);
                }

                GraphQLType rawTypeScope = typeScopeProvider != null ? typeScopeProvider.getTypeScope() : null;
                if (rawTypeScope != null) {
                    GraphQLUnmodifiedType typeScope = GraphQLUtil.getUnmodifiedType(rawTypeScope); // unwrap non-null and lists since fragments are about the raw type
                    final TypeDefinition fragmentType = typeDefinitionRegistry.getType(typeScope.getName()).orElse(null);
                    if (fragmentType != null) {
                        final Ref<Consumer<TypeDefinition<?>>> addTypesRecursive = new Ref<>();
                        final Consumer<TypeDefinition<?>> addTypes = (typeToFragmentOn) -> {
                            if (typeToFragmentOn instanceof ObjectTypeDefinition) {
                                fragmentTypes.add(Pair.create(typeToFragmentOn, typeDefinitionRegistryService.getTypeDefinitionDescription(typeToFragmentOn)));
                                final List<Type> anImplements = ((ObjectTypeDefinition) typeToFragmentOn).getImplements();
                                if (anImplements != null) {
                                    anImplements.forEach(type -> {
                                        final TypeDefinition typeDefinition = typeDefinitionRegistry.getType(type).orElse(null);
                                        if (typeDefinition instanceof InterfaceTypeDefinition) {
                                            fragmentTypes.add(Pair.create(typeDefinition, typeDefinitionRegistryService.getTypeDefinitionDescription(typeDefinition)));
                                        }
                                    });
                                }
                            } else if (typeToFragmentOn instanceof InterfaceTypeDefinition) {
                                fragmentTypes.add(Pair.create(typeToFragmentOn, typeDefinitionRegistryService.getTypeDefinitionDescription(typeToFragmentOn)));
                                final List<ObjectTypeDefinition> implementationsOf = typeDefinitionRegistry.getImplementationsOf((InterfaceTypeDefinition) typeToFragmentOn);
                                implementationsOf.forEach(impl -> fragmentTypes.add(Pair.create(impl, typeDefinitionRegistryService.getTypeDefinitionDescription(impl))));
                            } else if (typeToFragmentOn instanceof UnionTypeDefinition) {
                                final List<Type> memberTypes = ((UnionTypeDefinition) typeToFragmentOn).getMemberTypes();
                                if (memberTypes != null) {
                                    memberTypes.forEach(memberType -> {
                                        typeDefinitionRegistry.getType(memberType).ifPresent(memberTypeDefinition -> addTypesRecursive.get().consume(memberTypeDefinition));
                                    });
                                }
                            }
                        };
                        addTypesRecursive.set(addTypes);
                        addTypes.consume(fragmentType);
                    }
                }

            }

            fragmentTypes.forEach(fragmentType -> {
                LookupElementBuilder element = LookupElementBuilder
                        .create(fragmentType.first.getName())
                        .withBoldness(true);
                if (fragmentType.second != null) {
                    final String documentation = GraphQLDocumentationMarkdownRenderer.getDescriptionAsPlainText(fragmentType.second.getContent(), true);
                    element = element.withTailText(" - " + documentation, true);
                }
                result.addElement(element);
            });

        }
    };
    extend(CompletionType.BASIC, psiElement().afterLeaf(psiElement(GraphQLElementTypes.ON_KEYWORD)), provider);
}
 
Example 20
Source File: GraphQLIntrospectionHelper.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@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();
}