Search in sources :

Example 11 with Computable

use of com.intellij.openapi.util.Computable in project intellij-community by JetBrains.

the class ModuleToDoNode method getTodoItemCount.

@Override
public int getTodoItemCount(final Module val) {
    Iterator<PsiFile> iterator = myBuilder.getFiles(val);
    int count = 0;
    while (iterator.hasNext()) {
        final PsiFile psiFile = iterator.next();
        count += ApplicationManager.getApplication().runReadAction(new Computable<Integer>() {

            @Override
            public Integer compute() {
                return getTreeStructure().getTodoItemCount(psiFile);
            }
        });
    }
    return count;
}
Also used : PsiFile(com.intellij.psi.PsiFile) Computable(com.intellij.openapi.util.Computable)

Example 12 with Computable

use of com.intellij.openapi.util.Computable in project intellij-community by JetBrains.

the class FindManagerImpl method findInCommentsAndLiterals.

@NotNull
private FindResult findInCommentsAndLiterals(@NotNull CharSequence text, char[] textArray, int offset, @NotNull FindModel model, @NotNull final VirtualFile file) {
    synchronized (model) {
        FileType ftype = file.getFileType();
        Language lang = null;
        if (ftype instanceof LanguageFileType) {
            lang = ((LanguageFileType) ftype).getLanguage();
        }
        CommentsLiteralsSearchData data = model.getUserData(ourCommentsLiteralsSearchDataKey);
        if (data == null || !Comparing.equal(data.lastFile, file) || !data.model.equals(model)) {
            SyntaxHighlighter highlighter = getHighlighter(file, lang);
            if (highlighter == null) {
                // no syntax highlighter -> no search
                return NOT_FOUND_RESULT;
            }
            TokenSet tokensOfInterest = TokenSet.EMPTY;
            Set<Language> relevantLanguages;
            if (lang != null) {
                final Language finalLang = lang;
                relevantLanguages = ApplicationManager.getApplication().runReadAction(new Computable<Set<Language>>() {

                    @Override
                    public Set<Language> compute() {
                        THashSet<Language> result = new THashSet<>();
                        FileViewProvider viewProvider = PsiManager.getInstance(myProject).findViewProvider(file);
                        if (viewProvider != null) {
                            result.addAll(viewProvider.getLanguages());
                        }
                        if (result.isEmpty()) {
                            result.add(finalLang);
                        }
                        return result;
                    }
                });
                for (Language relevantLanguage : relevantLanguages) {
                    tokensOfInterest = addTokenTypesForLanguage(model, relevantLanguage, tokensOfInterest);
                }
                if (model.isInStringLiteralsOnly()) {
                    // TODO: xml does not have string literals defined so we add XmlAttributeValue element type as convenience
                    final Lexer xmlLexer = getHighlighter(null, Language.findLanguageByID("XML")).getHighlightingLexer();
                    final String marker = "xxx";
                    xmlLexer.start("<a href=\"" + marker + "\" />");
                    while (!marker.equals(xmlLexer.getTokenText())) {
                        xmlLexer.advance();
                        if (xmlLexer.getTokenType() == null)
                            break;
                    }
                    IElementType convenienceXmlAttrType = xmlLexer.getTokenType();
                    if (convenienceXmlAttrType != null) {
                        tokensOfInterest = TokenSet.orSet(tokensOfInterest, TokenSet.create(convenienceXmlAttrType));
                    }
                }
            } else {
                relevantLanguages = ContainerUtil.newHashSet();
                if (ftype instanceof AbstractFileType) {
                    if (model.isInCommentsOnly()) {
                        tokensOfInterest = TokenSet.create(CustomHighlighterTokenType.LINE_COMMENT, CustomHighlighterTokenType.MULTI_LINE_COMMENT);
                    }
                    if (model.isInStringLiteralsOnly()) {
                        tokensOfInterest = TokenSet.orSet(tokensOfInterest, TokenSet.create(CustomHighlighterTokenType.STRING, CustomHighlighterTokenType.SINGLE_QUOTED_STRING));
                    }
                }
            }
            Matcher matcher = model.isRegularExpressions() ? compileRegExp(model, "") : null;
            StringSearcher searcher = matcher != null ? null : new StringSearcher(model.getStringToFind(), model.isCaseSensitive(), true);
            SyntaxHighlighterOverEditorHighlighter highlighterAdapter = new SyntaxHighlighterOverEditorHighlighter(highlighter, file, myProject);
            data = new CommentsLiteralsSearchData(file, relevantLanguages, highlighterAdapter, tokensOfInterest, searcher, matcher, model.clone());
            data.highlighter.restart(text);
            model.putUserData(ourCommentsLiteralsSearchDataKey, data);
        }
        int initialStartOffset = model.isForward() && data.startOffset < offset ? data.startOffset : 0;
        data.highlighter.resetPosition(initialStartOffset);
        final Lexer lexer = data.highlighter.getHighlightingLexer();
        IElementType tokenType;
        TokenSet tokens = data.tokensOfInterest;
        int lastGoodOffset = 0;
        boolean scanningForward = model.isForward();
        FindResultImpl prevFindResult = NOT_FOUND_RESULT;
        while ((tokenType = lexer.getTokenType()) != null) {
            if (lexer.getState() == 0)
                lastGoodOffset = lexer.getTokenStart();
            final TextAttributesKey[] keys = data.highlighter.getTokenHighlights(tokenType);
            if (tokens.contains(tokenType) || (model.isInStringLiteralsOnly() && ChunkExtractor.isHighlightedAsString(keys)) || (model.isInCommentsOnly() && ChunkExtractor.isHighlightedAsComment(keys))) {
                int start = lexer.getTokenStart();
                int end = lexer.getTokenEnd();
                if (model.isInStringLiteralsOnly()) {
                    // skip literal quotes itself from matching
                    char c = text.charAt(start);
                    if (c == '"' || c == '\'') {
                        while (start < end && c == text.charAt(start)) {
                            ++start;
                            if (c == text.charAt(end - 1) && start < end)
                                --end;
                        }
                    }
                }
                while (true) {
                    FindResultImpl findResult = null;
                    if (data.searcher != null) {
                        int matchStart = data.searcher.scan(text, textArray, start, end);
                        if (matchStart != -1 && matchStart >= start) {
                            final int matchEnd = matchStart + model.getStringToFind().length();
                            if (matchStart >= offset || !scanningForward)
                                findResult = new FindResultImpl(matchStart, matchEnd);
                            else {
                                start = matchEnd;
                                continue;
                            }
                        }
                    } else if (start <= end) {
                        data.matcher.reset(StringPattern.newBombedCharSequence(text.subSequence(start, end)));
                        if (data.matcher.find()) {
                            final int matchEnd = start + data.matcher.end();
                            int matchStart = start + data.matcher.start();
                            if (matchStart >= offset || !scanningForward) {
                                findResult = new FindResultImpl(matchStart, matchEnd);
                            } else {
                                int diff = 0;
                                if (start == end) {
                                    diff = scanningForward ? 1 : -1;
                                }
                                start = matchEnd + diff;
                                continue;
                            }
                        }
                    }
                    if (findResult != null) {
                        if (scanningForward) {
                            data.startOffset = lastGoodOffset;
                            return findResult;
                        } else {
                            if (findResult.getEndOffset() >= offset)
                                return prevFindResult;
                            prevFindResult = findResult;
                            start = findResult.getEndOffset();
                            continue;
                        }
                    }
                    break;
                }
            } else {
                Language tokenLang = tokenType.getLanguage();
                if (tokenLang != lang && tokenLang != Language.ANY && !data.relevantLanguages.contains(tokenLang)) {
                    tokens = addTokenTypesForLanguage(model, tokenLang, tokens);
                    data.tokensOfInterest = tokens;
                    data.relevantLanguages.add(tokenLang);
                }
            }
            lexer.advance();
        }
        return prevFindResult;
    }
}
Also used : AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) Matcher(java.util.regex.Matcher) TokenSet(com.intellij.psi.tree.TokenSet) TextAttributesKey(com.intellij.openapi.editor.colors.TextAttributesKey) THashSet(gnu.trove.THashSet) LightweightHint(com.intellij.ui.LightweightHint) IElementType(com.intellij.psi.tree.IElementType) Lexer(com.intellij.lexer.Lexer) Language(com.intellij.lang.Language) AbstractFileType(com.intellij.openapi.fileTypes.impl.AbstractFileType) SyntaxHighlighterOverEditorHighlighter(com.intellij.usages.impl.SyntaxHighlighterOverEditorHighlighter) Computable(com.intellij.openapi.util.Computable) StringSearcher(com.intellij.util.text.StringSearcher) NotNull(org.jetbrains.annotations.NotNull)

Example 13 with Computable

use of com.intellij.openapi.util.Computable in project intellij-community by JetBrains.

the class PathEditor method isJarFile.

private static boolean isJarFile(final VirtualFile file) {
    return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {

        @Override
        public Boolean compute() {
            VirtualFile tempFile = file;
            if ((file.getFileSystem() instanceof JarFileSystem) && file.getParent() == null) {
                //[myakovlev] It was bug - directories with *.jar extensions was saved as files of JarFileSystem.
                //    so we can not just return true, we should filter such directories.
                String path = file.getPath().substring(0, file.getPath().length() - JarFileSystem.JAR_SEPARATOR.length());
                tempFile = LocalFileSystem.getInstance().findFileByPath(path);
            }
            if (tempFile != null && !tempFile.isDirectory()) {
                return Boolean.valueOf(tempFile.getFileType().equals(FileTypes.ARCHIVE));
            }
            return Boolean.FALSE;
        }
    }).booleanValue();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) JarFileSystem(com.intellij.openapi.vfs.JarFileSystem) Computable(com.intellij.openapi.util.Computable)

Example 14 with Computable

use of com.intellij.openapi.util.Computable in project intellij-community by JetBrains.

the class SliceNullnessAnalyzer method calcNullableLeaves.

@NotNull
static NullAnalysisResult calcNullableLeaves(@NotNull final SliceNode root, @NotNull AbstractTreeStructure treeStructure, @NotNull final Map<SliceNode, NullAnalysisResult> map) {
    final SliceLeafAnalyzer.SliceNodeGuide guide = new SliceLeafAnalyzer.SliceNodeGuide(treeStructure);
    WalkingState<SliceNode> walkingState = new WalkingState<SliceNode>(guide) {

        @Override
        public void visit(@NotNull final SliceNode element) {
            element.calculateDupNode();
            node(element, map).clear();
            SliceNode duplicate = element.getDuplicate();
            if (duplicate != null) {
                node(element, map).add(node(duplicate, map));
            } else {
                final PsiElement value = ApplicationManager.getApplication().runReadAction(new Computable<PsiElement>() {

                    @Override
                    public PsiElement compute() {
                        return element.getValue().getElement();
                    }
                });
                Nullness nullness = ApplicationManager.getApplication().runReadAction(new Computable<Nullness>() {

                    @Override
                    public Nullness compute() {
                        return checkNullness(value);
                    }
                });
                if (nullness == Nullness.NULLABLE) {
                    group(element, map, NullAnalysisResult.NULLS).add(value);
                } else if (nullness == Nullness.NOT_NULL) {
                    group(element, map, NullAnalysisResult.NOT_NULLS).add(value);
                } else {
                    Collection<? extends AbstractTreeNode> children = ApplicationManager.getApplication().runReadAction(new Computable<Collection<? extends AbstractTreeNode>>() {

                        @Override
                        public Collection<? extends AbstractTreeNode> compute() {
                            return element.getChildren();
                        }
                    });
                    if (children.isEmpty()) {
                        group(element, map, NullAnalysisResult.UNKNOWNS).add(value);
                    }
                    super.visit(element);
                }
            }
        }

        @Override
        public void elementFinished(@NotNull SliceNode element) {
            SliceNode parent = guide.getParent(element);
            if (parent != null) {
                node(parent, map).add(node(element, map));
            }
        }
    };
    walkingState.visit(root);
    return node(root, map);
}
Also used : WalkingState(com.intellij.util.WalkingState) AbstractTreeNode(com.intellij.ide.util.treeView.AbstractTreeNode) NotNull(org.jetbrains.annotations.NotNull) Nullness(com.intellij.codeInspection.dataFlow.Nullness) Computable(com.intellij.openapi.util.Computable) NotNull(org.jetbrains.annotations.NotNull)

Example 15 with Computable

use of com.intellij.openapi.util.Computable in project intellij-community by JetBrains.

the class JavaTestGenerator method generateTest.

public PsiElement generateTest(final Project project, final CreateTestDialog d) {
    return PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> ApplicationManager.getApplication().runWriteAction(new Computable<PsiElement>() {

        public PsiElement compute() {
            try {
                IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
                PsiClass targetClass = createTestClass(d);
                if (targetClass == null) {
                    return null;
                }
                final TestFramework frameworkDescriptor = d.getSelectedTestFrameworkDescriptor();
                final String defaultSuperClass = frameworkDescriptor.getDefaultSuperClass();
                final String superClassName = d.getSuperClassName();
                if (!Comparing.strEqual(superClassName, defaultSuperClass)) {
                    addSuperClass(targetClass, project, superClassName);
                }
                Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.getContainingFile(), targetClass);
                addTestMethods(editor, targetClass, d.getTargetClass(), frameworkDescriptor, d.getSelectedMethods(), d.shouldGeneratedBefore(), d.shouldGeneratedAfter());
                return targetClass;
            } catch (IncorrectOperationException e) {
                showErrorLater(project, d.getClassName());
                return null;
            }
        }
    }));
}
Also used : TestFramework(com.intellij.testIntegration.TestFramework) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) Computable(com.intellij.openapi.util.Computable)

Aggregations

Computable (com.intellij.openapi.util.Computable)49 VirtualFile (com.intellij.openapi.vfs.VirtualFile)15 NotNull (org.jetbrains.annotations.NotNull)11 Nullable (org.jetbrains.annotations.Nullable)11 Project (com.intellij.openapi.project.Project)10 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)8 PsiFile (com.intellij.psi.PsiFile)6 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 Application (com.intellij.openapi.application.Application)5 Task (com.intellij.openapi.progress.Task)5 IOException (java.io.IOException)5 ApplicationManager (com.intellij.openapi.application.ApplicationManager)4 Editor (com.intellij.openapi.editor.Editor)4 Ref (com.intellij.openapi.util.Ref)4 Module (com.intellij.openapi.module.Module)3 PsiDirectory (com.intellij.psi.PsiDirectory)3 PsiElement (com.intellij.psi.PsiElement)3 UsageInfo (com.intellij.usageView.UsageInfo)3 Logger (com.intellij.openapi.diagnostic.Logger)2