Search in sources :

Example 6 with Trinity

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

the class BraceMatcherBasedSelectioner method select.

@Override
public List<TextRange> select(final PsiElement e, final CharSequence editorText, final int cursorOffset, final Editor editor) {
    final VirtualFile file = e.getContainingFile().getVirtualFile();
    final FileType fileType = file == null ? null : file.getFileType();
    if (fileType == null)
        return super.select(e, editorText, cursorOffset, editor);
    final int textLength = editorText.length();
    final TextRange totalRange = e.getTextRange();
    final HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(totalRange.getStartOffset());
    final BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    final ArrayList<TextRange> result = new ArrayList<>();
    final LinkedList<Trinity<Integer, Integer, IElementType>> stack = new LinkedList<>();
    while (!iterator.atEnd() && iterator.getStart() < totalRange.getEndOffset()) {
        final Trinity<Integer, Integer, IElementType> last;
        if (braceMatcher.isLBraceToken(iterator, editorText, fileType)) {
            stack.addLast(Trinity.create(iterator.getStart(), iterator.getEnd(), iterator.getTokenType()));
        } else if (braceMatcher.isRBraceToken(iterator, editorText, fileType) && !stack.isEmpty() && braceMatcher.isPairBraces((last = stack.getLast()).third, iterator.getTokenType())) {
            stack.removeLast();
            result.addAll(expandToWholeLine(editorText, new TextRange(last.first, iterator.getEnd())));
            int bodyStart = last.second;
            int bodyEnd = iterator.getStart();
            while (bodyStart < textLength && Character.isWhitespace(editorText.charAt(bodyStart))) bodyStart++;
            while (bodyEnd > 0 && bodyStart < bodyEnd && Character.isWhitespace(editorText.charAt(bodyEnd - 1))) bodyEnd--;
            result.addAll(expandToWholeLine(editorText, new TextRange(bodyStart, bodyEnd)));
        }
        iterator.advance();
    }
    result.add(e.getTextRange());
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) Trinity(com.intellij.openapi.util.Trinity) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) LinkedList(java.util.LinkedList) IElementType(com.intellij.psi.tree.IElementType) FileType(com.intellij.openapi.fileTypes.FileType) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 7 with Trinity

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

the class ExecutionManagerImpl method startRunProfile.

@Override
public void startRunProfile(@NotNull final RunProfileStarter starter, @NotNull final RunProfileState state, @NotNull final ExecutionEnvironment environment) {
    final Project project = environment.getProject();
    RunContentDescriptor reuseContent = getContentManager().getReuseContent(environment);
    if (reuseContent != null) {
        reuseContent.setExecutionId(environment.getExecutionId());
        environment.setContentToReuse(reuseContent);
    }
    final Executor executor = environment.getExecutor();
    project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.getId(), environment);
    Runnable startRunnable;
    startRunnable = () -> {
        if (project.isDisposed()) {
            return;
        }
        RunProfile profile = environment.getRunProfile();
        project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarting(executor.getId(), environment);
        starter.executeAsync(state, environment).done(descriptor -> {
            AppUIUtil.invokeOnEdt(() -> {
                if (descriptor != null) {
                    final Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity = Trinity.create(descriptor, environment.getRunnerAndConfigurationSettings(), executor);
                    myRunningConfigurations.add(trinity);
                    Disposer.register(descriptor, () -> myRunningConfigurations.remove(trinity));
                    getContentManager().showRunContent(executor, descriptor, environment.getContentToReuse());
                    final ProcessHandler processHandler = descriptor.getProcessHandler();
                    if (processHandler != null) {
                        if (!processHandler.isStartNotified()) {
                            processHandler.startNotify();
                        }
                        project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarted(executor.getId(), environment, processHandler);
                        ProcessExecutionListener listener = new ProcessExecutionListener(project, executor.getId(), environment, processHandler, descriptor);
                        processHandler.addProcessListener(listener);
                        boolean terminating = processHandler.isProcessTerminating();
                        boolean terminated = processHandler.isProcessTerminated();
                        if (terminating || terminated) {
                            listener.processWillTerminate(new ProcessEvent(processHandler), false);
                            if (terminated) {
                                int exitCode = processHandler.isStartNotified() ? processHandler.getExitCode() : -1;
                                listener.processTerminated(new ProcessEvent(processHandler, exitCode));
                            }
                        }
                    }
                    environment.setContentToReuse(descriptor);
                } else {
                    project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
                }
            }, o -> project.isDisposed());
        }).rejected(e -> {
            if (!(e instanceof ProcessCanceledException)) {
                ExecutionException error = e instanceof ExecutionException ? (ExecutionException) e : new ExecutionException(e);
                ExecutionUtil.handleExecutionError(project, ExecutionManager.getInstance(project).getContentManager().getToolWindowIdByEnvironment(environment), profile, error);
            }
            LOG.info(e);
            project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
        });
    };
    if (ApplicationManager.getApplication().isUnitTestMode() && !myForceCompilationInTests) {
        startRunnable.run();
    } else {
        compileAndRun(() -> TransactionGuard.submitTransaction(project, startRunnable), environment, state, () -> {
            if (!project.isDisposed()) {
                project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
            }
        });
    }
}
Also used : Trinity(com.intellij.openapi.util.Trinity) ModalityState(com.intellij.openapi.application.ModalityState) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) RunProfileState(com.intellij.execution.configurations.RunProfileState) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) SmartList(com.intellij.util.SmartList) SaveAndSyncHandler(com.intellij.ide.SaveAndSyncHandler) Disposer(com.intellij.openapi.util.Disposer) Messages(com.intellij.openapi.ui.Messages) Logger(com.intellij.openapi.diagnostic.Logger) RunnerLayoutUi(com.intellij.execution.ui.RunnerLayoutUi) DumbService(com.intellij.openapi.project.DumbService) AppUIUtil(com.intellij.ui.AppUIUtil) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) ExecutionEnvironmentBuilder(com.intellij.execution.runners.ExecutionEnvironmentBuilder) Nullable(org.jetbrains.annotations.Nullable) ServiceManager(com.intellij.openapi.components.ServiceManager) RunContentDescriptor(com.intellij.execution.ui.RunContentDescriptor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ProcessEvent(com.intellij.execution.process.ProcessEvent) ExecutionUtil(com.intellij.execution.runners.ExecutionUtil) Registry(com.intellij.openapi.util.registry.Registry) NotNull(org.jetbrains.annotations.NotNull) java.util(java.util) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) DataContext(com.intellij.openapi.actionSystem.DataContext) RunContentManager(com.intellij.execution.ui.RunContentManager) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RunContentManagerImpl(com.intellij.execution.ui.RunContentManagerImpl) ContainerUtil(com.intellij.util.containers.ContainerUtil) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) CommonBundle(com.intellij.CommonBundle) Project(com.intellij.openapi.project.Project) ProgramRunner(com.intellij.execution.runners.ProgramRunner) StringUtil(com.intellij.openapi.util.text.StringUtil) Key(com.intellij.openapi.util.Key) RunProfile(com.intellij.execution.configurations.RunProfile) Disposable(com.intellij.openapi.Disposable) ProcessHandler(com.intellij.execution.process.ProcessHandler) com.intellij.execution(com.intellij.execution) TestOnly(org.jetbrains.annotations.TestOnly) DockManager(com.intellij.ui.docking.DockManager) CompatibilityAwareRunProfile(com.intellij.execution.configuration.CompatibilityAwareRunProfile) SimpleDataContext(com.intellij.openapi.actionSystem.impl.SimpleDataContext) TransactionGuard(com.intellij.openapi.application.TransactionGuard) Condition(com.intellij.openapi.util.Condition) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) Project(com.intellij.openapi.project.Project) RunContentDescriptor(com.intellij.execution.ui.RunContentDescriptor) Trinity(com.intellij.openapi.util.Trinity) ProcessEvent(com.intellij.execution.process.ProcessEvent) ProcessHandler(com.intellij.execution.process.ProcessHandler) RunProfile(com.intellij.execution.configurations.RunProfile) CompatibilityAwareRunProfile(com.intellij.execution.configuration.CompatibilityAwareRunProfile) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 8 with Trinity

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

the class VcsContentAnnotationExceptionFilter method applyHeavyFilter.

@Override
public void applyHeavyFilter(@NotNull final Document copiedFragment, int startOffset, int startLineNumber, @NotNull Consumer<AdditionalHighlight> consumer) {
    VcsContentAnnotation vcsContentAnnotation = VcsContentAnnotationImpl.getInstance(myProject);
    final LocalChangesCorrector localChangesCorrector = new LocalChangesCorrector(myProject);
    Trinity<PsiClass, PsiFile, String> previousLineResult = null;
    for (int i = 0; i < copiedFragment.getLineCount(); i++) {
        final int lineStartOffset = copiedFragment.getLineStartOffset(i);
        final int lineEndOffset = copiedFragment.getLineEndOffset(i);
        final ExceptionWorker worker = new ExceptionWorker(myCache);
        final String lineText = copiedFragment.getText(new TextRange(lineStartOffset, lineEndOffset));
        if (ReadAction.compute(() -> worker.execute(lineText, lineEndOffset)) != null) {
            VirtualFile vf = worker.getFile().getVirtualFile();
            if (vf.getFileSystem().isReadOnly())
                continue;
            VcsRevisionNumber recentChangeRevision = myRevNumbersCache.get(vf);
            if (recentChangeRevision == null) {
                recentChangeRevision = vcsContentAnnotation.fileRecentlyChanged(vf);
                if (recentChangeRevision == null) {
                    myRevNumbersCache.put(vf, VcsRevisionNumber.NULL);
                } else {
                    myRevNumbersCache.put(vf, recentChangeRevision);
                }
            }
            if (VcsRevisionNumber.NULL.equals(recentChangeRevision)) {
                recentChangeRevision = null;
            }
            if (localChangesCorrector.isFileAlreadyIdentifiedAsChanged(vf) || ChangeListManager.isFileChanged(myProject, vf) || recentChangeRevision != null) {
                final Document document = getDocumentForFile(worker);
                if (document == null)
                    return;
                int startFileOffset = worker.getInfo().getThird().getStartOffset();
                int idx = lineText.indexOf(':', startFileOffset);
                int endIdx = idx == -1 ? worker.getInfo().getThird().getEndOffset() : idx;
                consumer.consume(new MyAdditionalHighlight(startOffset + lineStartOffset + startFileOffset + 1, startOffset + lineStartOffset + endIdx));
                if (worker.getPsiClass() != null) {
                    // also check method
                    final List<TextRange> ranges = findMethodRange(worker, document, previousLineResult);
                    if (ranges != null) {
                        boolean methodChanged = false;
                        for (TextRange range : ranges) {
                            if (localChangesCorrector.isRangeChangedLocally(vf, document, range)) {
                                methodChanged = true;
                                break;
                            }
                            final TextRange correctedRange = localChangesCorrector.getCorrectedRange(vf, document, range);
                            if (vcsContentAnnotation.intervalRecentlyChanged(vf, correctedRange, recentChangeRevision)) {
                                methodChanged = true;
                                break;
                            }
                        }
                        if (methodChanged) {
                            consumer.consume(new MyAdditionalHighlight(startOffset + lineStartOffset + worker.getInfo().getSecond().getStartOffset(), startOffset + lineStartOffset + worker.getInfo().getSecond().getEndOffset()));
                        }
                    }
                }
            }
        }
        previousLineResult = worker.getResult() == null ? null : new Trinity<>(worker.getPsiClass(), worker.getFile(), worker.getMethod());
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Trinity(com.intellij.openapi.util.Trinity) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) ExceptionWorker(com.intellij.execution.filters.ExceptionWorker) VcsRevisionNumber(com.intellij.openapi.vcs.history.VcsRevisionNumber)

Example 9 with Trinity

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

the class AddAnnotationFixTest method testAnnotateLibrary.

public void testAnnotateLibrary() throws Throwable {
    addDefaultLibrary();
    myFixture.configureByFiles("lib/p/TestPrimitive.java", "content/anno/p/annotations.xml");
    myFixture.configureByFiles("lib/p/Test.java");
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();
    // expecting other @Nullable annotations to be removed, and default @NotNull to be added
    List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence = new ArrayList<>();
    for (String notNull : NullableNotNullManager.getInstance(myProject).getNullables()) {
        expectedSequence.add(Trinity.create(getOwner(), notNull, false));
    }
    expectedSequence.add(Trinity.create(getOwner(), AnnotationUtil.NOT_NULL, true));
    startListening(expectedSequence);
    myFixture.launchAction(myFixture.findSingleIntention("Annotate method 'get' as @NotNull"));
    FileDocumentManager.getInstance().saveAllDocuments();
    final PsiElement psiElement = file.findElementAt(editor.getCaretModel().getOffset());
    assertNotNull(psiElement);
    final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(psiElement, PsiModifierListOwner.class);
    assertNotNull(listOwner);
    assertNotNull(ExternalAnnotationsManager.getInstance(myProject).findExternalAnnotation(listOwner, AnnotationUtil.NOT_NULL));
    stopListeningAndCheckEvents();
    myFixture.checkResultByFile("content/anno/p/annotations.xml", "content/anno/p/annotationsAnnotateLibrary_after.xml", false);
}
Also used : Trinity(com.intellij.openapi.util.Trinity) ArrayList(java.util.ArrayList) Editor(com.intellij.openapi.editor.Editor)

Example 10 with Trinity

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

the class GroovyConstructorNamedArgumentProvider method processClass.

public static void processClass(@NotNull GrCall call, PsiClassType type, @Nullable String argumentName, final Map<String, NamedArgumentDescriptor> result) {
    if (argumentName == null) {
        final HashMap<String, Trinity<PsiType, PsiElement, PsiSubstitutor>> map = ContainerUtil.newHashMap();
        MyPsiScopeProcessor processor = new MyPsiScopeProcessor() {

            @Override
            protected void addNamedArgument(String propertyName, PsiType type, PsiElement element, PsiSubstitutor substitutor) {
                if (result.containsKey(propertyName))
                    return;
                Trinity<PsiType, PsiElement, PsiSubstitutor> pair = map.get(propertyName);
                if (pair != null) {
                    if (element instanceof PsiMethod && pair.second instanceof PsiField) {
                    // methods should override fields
                    } else {
                        return;
                    }
                }
                map.put(propertyName, Trinity.create(type, element, substitutor));
            }
        };
        processor.setResolveTargetKinds(ClassHint.RESOLVE_KINDS_METHOD_PROPERTY);
        ResolveUtil.processAllDeclarations(type, processor, ResolveState.initial(), call);
        for (Map.Entry<String, Trinity<PsiType, PsiElement, PsiSubstitutor>> entry : map.entrySet()) {
            result.put(entry.getKey(), new TypeCondition(entry.getValue().first, entry.getValue().getSecond(), entry.getValue().getThird(), NamedArgumentDescriptor.Priority.AS_LOCAL_VARIABLE));
        }
    } else {
        MyPsiScopeProcessor processor = new MyPsiScopeProcessor() {

            @Override
            protected void addNamedArgument(String propertyName, PsiType type, PsiElement element, PsiSubstitutor substitutor) {
                if (result.containsKey(propertyName))
                    return;
                result.put(propertyName, new TypeCondition(type, element, substitutor, NamedArgumentDescriptor.Priority.AS_LOCAL_VARIABLE));
            }
        };
        processor.setResolveTargetKinds(ClassHint.RESOLVE_KINDS_METHOD);
        processor.setNameHint(GroovyPropertyUtils.getSetterName(argumentName));
        ResolveUtil.processAllDeclarations(type, processor, ResolveState.initial(), call);
        processor.setResolveTargetKinds(ClassHint.RESOLVE_KINDS_PROPERTY);
        processor.setNameHint(argumentName);
        ResolveUtil.processAllDeclarations(type, processor, ResolveState.initial(), call);
    }
}
Also used : Trinity(com.intellij.openapi.util.Trinity) TypeCondition(org.jetbrains.plugins.groovy.extensions.impl.TypeCondition) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Trinity (com.intellij.openapi.util.Trinity)24 VirtualFile (com.intellij.openapi.vfs.VirtualFile)9 Pair (com.intellij.openapi.util.Pair)6 ArrayList (java.util.ArrayList)6 NotNull (org.jetbrains.annotations.NotNull)6 Nullable (org.jetbrains.annotations.Nullable)5 Project (com.intellij.openapi.project.Project)4 File (java.io.File)4 RunConfiguration (com.intellij.execution.configurations.RunConfiguration)3 Language (com.intellij.lang.Language)3 FileType (com.intellij.openapi.fileTypes.FileType)3 TextRange (com.intellij.openapi.util.TextRange)3 BraceMatcher (com.intellij.codeInsight.highlighting.BraceMatcher)2 ProcessHandler (com.intellij.execution.process.ProcessHandler)2 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)2 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Logger (com.intellij.openapi.diagnostic.Logger)2 HighlighterIterator (com.intellij.openapi.editor.highlighter.HighlighterIterator)2 Module (com.intellij.openapi.module.Module)2 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)2