Java Code Examples for com.intellij.openapi.progress.ProgressIndicatorProvider#checkCanceled()

The following examples show how to use com.intellij.openapi.progress.ProgressIndicatorProvider#checkCanceled() . 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: PsiBuilderImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int insertLeaves(int curToken, int lastIdx, final CompositeElement curNode) {
  lastIdx = Math.min(lastIdx, myLexemeCount);
  while (curToken < lastIdx) {
    ProgressIndicatorProvider.checkCanceled();
    final int start = myLexStarts[curToken];
    final int end = myLexStarts[curToken + 1];
    if (start < end || myLexTypes[curToken] instanceof ILeafElementType) { // Empty token. Most probably a parser directive like indent/dedent in Python
      final IElementType type = myLexTypes[curToken];
      final TreeElement leaf = createLeaf(type, start, end);
      curNode.rawAddChildrenWithoutNotifications(leaf);
    }
    curToken++;
  }

  return curToken;
}
 
Example 2
Source File: PSITokenSource.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Create an ANTLR Token from the current token type of the builder
	 *  then advance the builder to next token (which ultimately calls an
	 *  ANTLR lexer).  The {@link ANTLRLexerAdaptor} creates tokens via
	 *  an ANTLR lexer but converts to {@link TokenIElementType} and here
	 *  we have to convert back to an ANTLR token using what info we
	 *  can get from the builder. We lose info such as the original channel.
	 *  So, whitespace and comments (typically hidden channel) will look like
	 *  real tokens. Jetbrains uses {@link ParserDefinition#getWhitespaceTokens()}
	 *  and {@link ParserDefinition#getCommentTokens()} to strip these before
	 *  our ANTLR parser sees them.
	 */
	@Override
	public Token nextToken() {
		ProgressIndicatorProvider.checkCanceled();

		TokenIElementType ideaTType = (TokenIElementType)builder.getTokenType();
		int type = ideaTType!=null ? ideaTType.getANTLRTokenType() : Token.EOF;

		int channel = Token.DEFAULT_CHANNEL;
		Pair<TokenSource, CharStream> source = new Pair<TokenSource, CharStream>(this, null);
		String text = builder.getTokenText();
		int start = builder.getCurrentOffset();
		int length = text != null ? text.length() : 0;
		int stop = start + length - 1;
		// PsiBuilder doesn't provide line, column info
		int line = 0;
		int charPositionInLine = 0;
		Token t = tokenFactory.create(source, type, text, channel, start, stop, line, charPositionInLine);
		builder.advanceLexer();
//		System.out.println("TOKEN: "+t);
		return t;
	}
 
Example 3
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean processChildren(PsiElementProcessor<PsiFileSystemItem> processor) {
  checkValid();
  ProgressIndicatorProvider.checkCanceled();

  for (VirtualFile vFile : myFile.getChildren()) {
    boolean isDir = vFile.isDirectory();
    if (processor instanceof PsiFileSystemItemProcessor && !((PsiFileSystemItemProcessor)processor).acceptItem(vFile.getName(), isDir)) {
      continue;
    }
    if (isDir) {
      PsiDirectory dir = myManager.findDirectory(vFile);
      if (dir != null) {
        if (!processor.execute(dir)) return false;
      }
    }
    else {
      PsiFile file = myManager.findFile(vFile);
      if (file != null) {
        if (!processor.execute(file)) return false;
      }
    }
  }
  return true;
}
 
Example 4
Source File: CSharpHighlightVisitor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
public void visitElement(PsiElement element)
{
	ProgressIndicatorProvider.checkCanceled();

	IElementType elementType = PsiUtilCore.getElementType(element);
	if(CSharpSoftTokens.ALL.contains(elementType))
	{
		myHighlightInfoHolder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(element).textAttributes(CSharpHighlightKey.SOFT_KEYWORD).create());
	}
	else if(elementType == CSharpTokens.NON_ACTIVE_SYMBOL || elementType == CSharpPreprocessorElements.DISABLED_PREPROCESSOR_DIRECTIVE)
	{
		if(myDocument == null)
		{
			return;
		}
		int lineNumber = myDocument.getLineNumber(element.getTextOffset());
		if(!myProcessedLines.contains(lineNumber))
		{
			myProcessedLines.add(lineNumber);

			TextRange textRange = new TextRange(myDocument.getLineStartOffset(lineNumber), myDocument.getLineEndOffset(lineNumber));
			myHighlightInfoHolder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(textRange).textAttributes(CSharpHighlightKey.DISABLED_BLOCK).create());
		}
	}
}
 
Example 5
Source File: PsiRecursiveElementVisitor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void visitFile(final PsiFile file) {
  if (myVisitAllFileRoots) {
    final FileViewProvider viewProvider = file.getViewProvider();
    final List<PsiFile> allFiles = viewProvider.getAllFiles();
    if (allFiles.size() > 1) {
      if (file == viewProvider.getPsi(viewProvider.getBaseLanguage())) {
        for (PsiFile lFile : allFiles) {
          ProgressIndicatorProvider.checkCanceled();
          lFile.acceptChildren(this);
        }
        return;
      }
    }
  }

  super.visitFile(file);
}
 
Example 6
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Like {@link #getStub()}, but can return a non-null value after the element has been switched to AST. Can be used
 * to retrieve the information which is cheaper to get from a stub than by tree traversal.
 *
 * @see PsiFileImpl#getGreenStub()
 */
@Nullable
public final T getGreenStub() {
  ProgressIndicatorProvider.checkCanceled(); // Hope, this is called often
  //noinspection unchecked
  return (T)mySubstrateRef.getGreenStub();
}
 
Example 7
Source File: PsiScopesUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiScopeProcessor processor,
                                 @Nonnull final PsiElement entrance,
                                 @Nullable final PsiElement maxScope,
                                 @Nonnull final ResolveState state) {
  if (!entrance.isValid()) {
    LOGGER.error(new PsiInvalidElementAccessException(entrance));
  }
  PsiElement prevParent = entrance;
  PsiElement scope = entrance;

  while (scope != null) {
    ProgressIndicatorProvider.checkCanceled();

    if (!scope.processDeclarations(processor, state, prevParent, entrance)) {
      return false; // resolved
    }


    if (scope == maxScope) break;
    prevParent = scope;
    scope = prevParent.getContext();
    if (scope != null && scope != prevParent.getParent() && !scope.isValid()) {
      break;
    }

  }

  return true;
}
 
Example 8
Source File: CompositeElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public final PsiElement getPsi() {
  ProgressIndicatorProvider.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly

  PsiElement wrapper = myWrapper;
  if (wrapper != null) return wrapper;

  wrapper = createPsiNoLock();
  return ourPsiUpdater.compareAndSet(this, null, wrapper) ? wrapper : ObjectUtils.assertNotNull(myWrapper);
}
 
Example 9
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void performFileProcessing(@Nonnull PsiFile file) {
  for (AbstractLayoutCodeProcessor processor : myProcessors) {
    FutureTask<Boolean> writeTask = ReadAction.compute(() -> processor.prepareTask(file, myProcessChangedTextOnly));

    ProgressIndicatorProvider.checkCanceled();

    ApplicationManager.getApplication().invokeAndWait(() -> WriteCommandAction.runWriteCommandAction(myProject, myCommandName, null, writeTask));

    checkStop(writeTask, file);
  }
}
 
Example 10
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public <T extends PsiPolyVariantReference> ResolveResult[] resolveWithCaching(@Nonnull final T ref,
                                                                              @Nonnull final PolyVariantContextResolver<T> resolver,
                                                                              boolean needToPreventRecursion,
                                                                              final boolean incompleteCode,
                                                                              @Nonnull final PsiFile containingFile) {
  ProgressIndicatorProvider.checkCanceled();
  ApplicationManager.getApplication().assertReadAccessAllowed();

  boolean physical = containingFile.isPhysical();
  int index = getIndex(incompleteCode, true);
  Map<T, ResolveResult[]> map = getMap(physical, index);
  ResolveResult[] result = map.get(ref);
  if (result != null) {
    return result;
  }

  RecursionGuard.StackStamp stamp = RecursionManager.markStack();
  result = needToPreventRecursion
           ? RecursionManager.doPreventingRecursion(Pair.create(ref, incompleteCode), true, () -> resolver.resolve(ref, containingFile, incompleteCode))
           : resolver.resolve(ref, containingFile, incompleteCode);
  if (result != null) {
    ensureValidResults(result);
  }

  if (stamp.mayCacheNow()) {
    cache(ref, map, result);
  }
  return result == null ? ResolveResult.EMPTY_ARRAY : result;
}
 
Example 11
Source File: PsiManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) {
  ProgressIndicatorProvider.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly

  if (element1 == element2) return true;
  if (element1 == null || element2 == null) {
    return false;
  }

  return element1.equals(element2) || element1.isEquivalentTo(element2) || element2.isEquivalentTo(element1);
}
 
Example 12
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public ThreeState deepEqual(@Nonnull final ASTNode oldNode, @Nonnull final LighterASTNode newNode) {
  ProgressIndicatorProvider.checkCanceled();

  boolean oldIsErrorElement = oldNode instanceof PsiErrorElement;
  boolean newIsErrorElement = newNode.getTokenType() == TokenType.ERROR_ELEMENT;
  if (oldIsErrorElement != newIsErrorElement) return ThreeState.NO;
  if (oldIsErrorElement) {
    final PsiErrorElement e1 = (PsiErrorElement)oldNode;
    return Comparing.equal(e1.getErrorDescription(), getErrorMessage(newNode)) ? ThreeState.UNSURE : ThreeState.NO;
  }

  if (custom != null) {
    ThreeState customResult = custom.fun(oldNode, newNode, myTreeStructure);

    if (customResult != ThreeState.UNSURE) {
      return customResult;
    }
  }
  if (newNode instanceof Token) {
    final IElementType type = newNode.getTokenType();
    final Token token = (Token)newNode;

    if (oldNode instanceof ForeignLeafPsiElement) {
      return type instanceof ForeignLeafType && StringUtil.equals(((ForeignLeafType)type).getValue(), oldNode.getText()) ? ThreeState.YES : ThreeState.NO;
    }

    if (oldNode instanceof LeafElement) {
      if (type instanceof ForeignLeafType) return ThreeState.NO;

      return ((LeafElement)oldNode).textMatches(token.getText()) ? ThreeState.YES : ThreeState.NO;
    }

    if (type instanceof ILightLazyParseableElementType) {
      return ((TreeElement)oldNode).textMatches(token.getText())
             ? ThreeState.YES
             : TreeUtil.isCollapsedChameleon(oldNode) ? ThreeState.NO  // do not dive into collapsed nodes
                                                      : ThreeState.UNSURE;
    }

    if (oldNode.getElementType() instanceof ILazyParseableElementType && type instanceof ILazyParseableElementType ||
        oldNode.getElementType() instanceof ICustomParsingType && type instanceof ICustomParsingType) {
      return ((TreeElement)oldNode).textMatches(token.getText()) ? ThreeState.YES : ThreeState.NO;
    }
  }

  return ThreeState.UNSURE;
}
 
Example 13
Source File: PsiRecursiveElementVisitor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void visitElement(final PsiElement element) {
  ProgressIndicatorProvider.checkCanceled();
  element.acceptChildren(this);
}
 
Example 14
Source File: PsiElementVisitor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void visitElement(PsiElement element) {
  ProgressIndicatorProvider.checkCanceled();
}
 
Example 15
Source File: PsiRecursiveElementWalkingVisitor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void visitElement(final PsiElement element) {
  ProgressIndicatorProvider.checkCanceled();

  myWalkingState.elementStarted(element);
}
 
Example 16
Source File: PsiManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public FileViewProvider findViewProvider(@Nonnull VirtualFile file) {
  ProgressIndicatorProvider.checkCanceled();
  return myFileManager.findViewProvider(file);
}
 
Example 17
Source File: DiffLog.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected LogEntry() {
  ProgressIndicatorProvider.checkCanceled();
}
 
Example 18
Source File: CSharpDirectTypeInheritorsSearcherExecutor.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public boolean execute(@Nonnull final DirectTypeInheritorsSearch.SearchParameters p, @Nonnull final Processor<? super DotNetTypeDeclaration> consumer)
{
	String vmQName = p.getVmQName();

	/*if(DotNetTypes.System_Object.equals(qualifiedName))
	{
		final SearchScope scope = useScope;

		return AllClassesSearch.search(scope, aClass.getProject()).forEach(new Processor<DotNetTypeDeclaration>()
		{
			@Override
			public boolean process(final DotNetTypeDeclaration typeDcl)
			{
				if(typeDcl.isInterface())
				{
					return consumer.process(typeDcl);
				}
				final DotNetTypeDeclaration superClass = typeDcl.getSuperClass();
				if(superClass != null && DotNetTypes.System_Object.equals(ApplicationManager.getApplication().runReadAction(
						new Computable<String>()
				{
					public String compute()
					{
						return superClass.getPresentableQName();
					}
				})))
				{
					return consumer.process(typeDcl);
				}
				return true;
			}
		});
	}  */

	SearchScope useScope = p.getScope();
	final GlobalSearchScope scope = useScope instanceof GlobalSearchScope ? (GlobalSearchScope) useScope : new EverythingGlobalScope(p
			.getProject());
	final String searchKey = MsilHelper.cutGenericMarker(StringUtil.getShortName(vmQName));

	if(StringUtil.isEmpty(searchKey))
	{
		return true;
	}

	Collection<DotNetTypeList> candidates = ApplicationManager.getApplication().runReadAction((Computable<Collection<DotNetTypeList>>) () -> ExtendsListIndex.getInstance().get(searchKey, p.getProject(), scope));

	Map<String, List<DotNetTypeDeclaration>> classes = new HashMap<>();

	for(DotNetTypeList referenceList : candidates)
	{
		ProgressIndicatorProvider.checkCanceled();
		final DotNetTypeDeclaration candidate = ReadAction.compute(() -> (DotNetTypeDeclaration) referenceList.getParent());
		if(!checkInheritance(p, vmQName, candidate))
		{
			continue;
		}

		String fqn = ReadAction.compute(candidate::getPresentableQName);
		List<DotNetTypeDeclaration> list = classes.get(fqn);
		if(list == null)
		{
			list = new ArrayList<>();
			classes.put(fqn, list);
		}
		list.add(candidate);
	}

	for(List<DotNetTypeDeclaration> sameNamedClasses : classes.values())
	{
		for(DotNetTypeDeclaration sameNamedClass : sameNamedClasses)
		{
			if(!consumer.process(sameNamedClass))
			{
				return false;
			}
		}
	}

	return true;
}
 
Example 19
Source File: PsiManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public PsiFile findFile(@Nonnull VirtualFile file) {
  ProgressIndicatorProvider.checkCanceled();
  return myFileManager.findFile(file);
}
 
Example 20
Source File: ANTLRParserAdaptor.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
	ProgressIndicatorProvider.checkCanceled();

	TokenSource source = new PSITokenSource(builder);
	TokenStream tokens = new CommonTokenStream(source);
	parser.setTokenStream(tokens);
	parser.setErrorHandler(new ErrorStrategyAdaptor()); // tweaks missing tokens
	parser.removeErrorListeners();
	parser.addErrorListener(new SyntaxErrorListener()); // trap errors
	ParseTree parseTree = null;
	PsiBuilder.Marker rollbackMarker = builder.mark();
	try {
		parseTree = parse(parser, root);
	}
	finally {
		rollbackMarker.rollbackTo();
	}

	// Now convert ANTLR parser tree to PSI tree by mimicking subtree
	// enter/exit with mark/done calls. I *think* this creates their parse
	// tree (AST as they call it) when you call {@link PsiBuilder#getTreeBuilt}
	ANTLRParseTreeToPSIConverter listener = createListener(parser, root, builder);
	PsiBuilder.Marker rootMarker = builder.mark();
	ParseTreeWalker.DEFAULT.walk(listener, parseTree);
	while (!builder.eof()) {
		ProgressIndicatorProvider.checkCanceled();
		builder.advanceLexer();
	}
	// NOTE: parse tree returned from parse will be the
	// usual ANTLR tree ANTLRParseTreeToPSIConverter will
	// convert that to the analogous jetbrains AST nodes
	// When parsing an entire file, the root IElementType
	// will be a IFileElementType.
	//
	// When trying to rename IDs and so on, you get a
	// dummy root and a type arg identifier IElementType.
	// This results in a weird tree that has for example
	// (ID (expr (primary ID))) with the ID IElementType
	// as a subtree root as well as the appropriate leaf
	// all the way at the bottom.  The dummy ID root is a
	// CompositeElement and created by
	// ParserDefinition.createElement() despite having
	// being TokenIElementType.
	rootMarker.done(root);
	return builder.getTreeBuilt(); // calls the ASTFactory.createComposite() etc...
}