Search in sources :

Example 71 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class InspectionProfileImpl method initialize.

@Override
protected void initialize(@Nullable Project project) {
    SchemeDataHolder<? super InspectionProfileImpl> dataHolder = myDataHolder;
    if (dataHolder != null) {
        myDataHolder = null;
        Element element = dataHolder.read();
        if (element.getName().equals("component")) {
            element = element.getChild("profile");
        }
        assert element != null;
        readExternal(element);
    }
    if (myBaseProfile != null) {
        myBaseProfile.initInspectionTools(project);
    }
    final List<InspectionToolWrapper> tools;
    try {
        tools = createTools(project);
    } catch (ProcessCanceledException ignored) {
        return;
    }
    final Map<String, List<String>> dependencies = new THashMap<>();
    for (InspectionToolWrapper toolWrapper : tools) {
        addTool(project, toolWrapper, dependencies);
    }
    DFSTBuilder<String> builder = new DFSTBuilder<>(GraphGenerator.generate(new InboundSemiGraph<String>() {

        @Override
        public Collection<String> getNodes() {
            return dependencies.keySet();
        }

        @Override
        public Iterator<String> getIn(String n) {
            return dependencies.get(n).iterator();
        }
    }));
    if (builder.isAcyclic()) {
        myScopesOrder = ArrayUtil.toStringArray(builder.getSortedNodes());
    }
    copyToolsConfigurations(project);
    initialized = true;
    if (dataHolder != null) {
        // should be only after set myInitialized
        dataHolder.updateDigest(this);
    }
}
Also used : InboundSemiGraph(com.intellij.util.graph.InboundSemiGraph) THashMap(gnu.trove.THashMap) PsiElement(com.intellij.psi.PsiElement) Element(org.jdom.Element) DFSTBuilder(com.intellij.util.graph.DFSTBuilder) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 72 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class DaemonRespondToChangesTest method testInterruptOnTyping.

public void testInterruptOnTyping() throws Throwable {
    @NonNls String filePath = "/psi/resolve/Thinlet.java";
    configureByFile(filePath);
    highlightErrors();
    final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(getProject());
    codeAnalyzer.restart();
    try {
        PsiDocumentManager.getInstance(myProject).commitAllDocuments();
        PsiFile file = getFile();
        Editor editor = getEditor();
        Project project = file.getProject();
        CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project);
        TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
        codeAnalyzer.runPasses(file, editor.getDocument(), textEditor, ArrayUtil.EMPTY_INT_ARRAY, true, () -> type(' '));
    } catch (ProcessCanceledException ignored) {
        return;
    }
    fail("PCE must have been thrown");
}
Also used : NonNls(org.jetbrains.annotations.NonNls) Project(com.intellij.openapi.project.Project) TextEditor(com.intellij.openapi.fileEditor.TextEditor) TextEditor(com.intellij.openapi.fileEditor.TextEditor) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 73 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class DaemonRespondToChangesTest method checkDaemonReaction.

private void checkDaemonReaction(boolean mustCancelItself, @NotNull final Runnable action) {
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    highlightErrors();
    myDaemonCodeAnalyzer.waitForTermination();
    TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(getEditor());
    final AtomicBoolean run = new AtomicBoolean();
    Disposable disposable = Disposer.newDisposable();
    final AtomicReference<RuntimeException> stopDaemonReason = new AtomicReference<>();
    StorageUtilKt.setDEBUG_LOG("");
    getProject().getMessageBus().connect(disposable).subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, new DaemonCodeAnalyzer.DaemonListenerAdapter() {

        @Override
        public void daemonCancelEventOccurred(@NotNull String reason) {
            RuntimeException e = new RuntimeException("Some bastard's restarted daemon: " + reason + "\nStorage write log: ----------\n" + StorageUtilKt.getDEBUG_LOG() + "\n--------------");
            stopDaemonReason.compareAndSet(null, e);
        }
    });
    try {
        while (true) {
            try {
                myDaemonCodeAnalyzer.runPasses(getFile(), getDocument(getFile()), textEditor, new int[0], true, () -> {
                    if (!run.getAndSet(true)) {
                        action.run();
                    }
                });
                break;
            } catch (ProcessCanceledException ignored) {
            }
        }
        if (mustCancelItself) {
            assertNotNull(stopDaemonReason.get());
        } else {
            if (stopDaemonReason.get() != null)
                throw stopDaemonReason.get();
        }
    } finally {
        StorageUtilKt.setDEBUG_LOG(null);
        Disposer.dispose(disposable);
    }
}
Also used : Disposable(com.intellij.openapi.Disposable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TextEditor(com.intellij.openapi.fileEditor.TextEditor) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 74 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class DaemonRespondToChangesTest method startCPUProfiling.

/*
  private void inspect(LocalInspectionToolWrapper wrapper) {
    PsiFile file = getFile();
    TextRange range = file.getTextRange();

    List<Divider.DividedElements> allDivided = new ArrayList<>();
    Divider.divideInsideAndOutsideAllRoots(file, range, range, Conditions.alwaysTrue(), new CommonProcessors.CollectProcessor<>(allDivided));

    List<PsiElement> elements = ContainerUtil.concat(
      (List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> ContainerUtil.concat(d.inside, d.outside, d.parents)));

    PsiErrorElement errorElement = ContainerUtil.findInstance(elements, PsiErrorElement.class);
    assertNull(file.getText(), errorElement);

    Set<String> elementDialectIds = InspectionEngine.calcElementDialectIds(elements);

    //List<HighlightInfo> errors = DaemonAnalyzerTestCase.filter(doHighlighting(), HighlightSeverity.ERROR);// warmup
    //assertEmpty(errors);

    timeInspection(wrapper, elements, elementDialectIds); // warmup
  }

  private int timeInspection(@NotNull LocalInspectionToolWrapper wrapper, @NotNull List<PsiElement> elements, @NotNull Set<String> elementDialectIds) {
    long start = System.currentTimeMillis();
    InspectionEngine.inspectElements(Collections.singletonList(wrapper), getFile(), InspectionManager.getInstance(getProject()), true, true, new EmptyProgressIndicator(), elements,
                                     elementDialectIds);
    return (int)(System.currentTimeMillis() - start);
  }

  public void testTypingLatencyForAllInspectionsPerformance() throws Throwable {
    @NonNls String filePath = "/psi/resolve/ThinletBig.java";

    //Collection<LocalInspectionTool> tools = getInspectionsFor(JavaLanguage.INSTANCE);
    //enableInspectionTools(tools.toArray(new InspectionProfileEntry[tools.size()]));

    configureByFile(filePath);

    //type(' ');
    //CompletionContributor.forLanguage(getFile().getLanguage());
    //long s = System.currentTimeMillis();
    //highlightErrors();
    //long e = System.currentTimeMillis();
    //System.out.println("Hi elapsed: "+(e-s));

    final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject());
    int N = Math.max(5, Timings.adjustAccordingToMySpeed(80, false));
    System.out.println("N = " + N);
    final long[] interruptTimes = new long[N];
    LossyEncodingInspection encodingInspection = new LossyEncodingInspection();
    LocalInspectionToolWrapper wrapper = new LocalInspectionToolWrapper(encodingInspection);
    codeAnalyzer.setUpdateByTimerEnabled(false);
    ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(getProject())).disableBackgroundCommit(getTestRootDisposable());

    // position caret away from line start to disable smart backspace heuristics which does commit document
    int offset = getEditor().getDocument().getText().indexOf("{ ")+1;
    getEditor().getCaretModel().moveToOffset(offset);

    for (int i = 0; i < N; i++) {
      type(' ');

      System.out.println("i = " + i);
      //codeAnalyzer.restart();
      //final int finalI = i;
      //final long start = System.currentTimeMillis();
      try {
        //PsiFile file = getFile();
        //Editor editor = getEditor();
        //Project project = file.getProject();
        //CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project);
        //TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
        //PsiDocumentManager.getInstance(myProject).commitAllDocuments();

        inspect(wrapper);
      }
      catch (ProcessCanceledException ignored) {
      }
      backspace();
    }

    //long mean = ArrayUtil.averageAmongMedians(interruptTimes, 3);
    //long avg = Arrays.stream(interruptTimes).sum() / interruptTimes.length;
    //long max = Arrays.stream(interruptTimes).max().getAsLong();
    //long min = Arrays.stream(interruptTimes).min().getAsLong();
    //System.out.println("Average among the N/3 median times: " + mean + "ms; max: "+max+"; min:"+min+"; avg: "+avg);
    //assertTrue(mean < 10);
  }

  public void testResolveAllAfterTypingLatencyPerformance() throws Throwable {
    @NonNls String filePath = "/psi/resolve/ThinletBig.java";

    //Collection<LocalInspectionTool> tools = getInspectionsFor(JavaLanguage.INSTANCE);
    //enableInspectionTools(tools.toArray(new InspectionProfileEntry[tools.size()]));

    configureByFile(filePath);

    //type(' ');
    //CompletionContributor.forLanguage(getFile().getLanguage());
    //long s = System.currentTimeMillis();
    //highlightErrors();
    //long e = System.currentTimeMillis();
    //System.out.println("Hi elapsed: "+(e-s));

    final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject());
    int N = Math.max(5, Timings.adjustAccordingToMySpeed(80, false));
    System.out.println("N = " + N);
    final long[] interruptTimes = new long[N];
    LossyEncodingInspection encodingInspection = new LossyEncodingInspection();
    LocalInspectionToolWrapper wrapper = new LocalInspectionToolWrapper(encodingInspection);
    codeAnalyzer.setUpdateByTimerEnabled(false);
    ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(getProject())).disableBackgroundCommit(getTestRootDisposable());

    // position caret away from line start to disable smart backspace heuristics which does commit document
    int offset = getEditor().getDocument().getText().indexOf("{ ")+1;
    getEditor().getCaretModel().moveToOffset(offset);

    for (int i = 0; i < N; i++) {
      type(' ');

      System.out.println("i = " + i);
      //codeAnalyzer.restart();
      //final int finalI = i;
      //final long start = System.currentTimeMillis();
      try {
        //PsiFile file = getFile();
        //Editor editor = getEditor();
        //Project project = file.getProject();
        //CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project);
        //TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
        //PsiDocumentManager.getInstance(myProject).commitAllDocuments();
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        //getFile().accept(new PsiRecursiveElementWalkingVisitor() {
        //  @Override
        //  public void visitElement(PsiElement element) {
        //    for (PsiReference reference : element.getReferences()) {
        //      reference.resolve();
        //    }
        //    super.visitElement(element);
        //  }
        //});
      }
      catch (ProcessCanceledException ignored) {
      }
      backspace();
    }

    //long mean = ArrayUtil.averageAmongMedians(interruptTimes, 3);
    //long avg = Arrays.stream(interruptTimes).sum() / interruptTimes.length;
    //long max = Arrays.stream(interruptTimes).max().getAsLong();
    //long min = Arrays.stream(interruptTimes).min().getAsLong();
    //System.out.println("Average among the N/3 median times: " + mean + "ms; max: "+max+"; min:"+min+"; avg: "+avg);
    //assertTrue(mean < 10);
  }
  */
private static void startCPUProfiling() {
    try {
        Class<?> aClass = Class.forName("com.intellij.util.ProfilingUtil");
        Method method = ReflectionUtil.getDeclaredMethod(aClass, "startCPUProfiling");
        method.invoke(null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Method(java.lang.reflect.Method) IOException(java.io.IOException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 75 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class MultiHostRegistrarImpl method doneInjecting.

@Override
public void doneInjecting() {
    try {
        if (shreds.isEmpty()) {
            throw new IllegalStateException("Seems you haven't called addPlace()");
        }
        if (myReferenceInjector != null) {
            addToResults(new Place(shreds), null);
            return;
        }
        PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase) PsiDocumentManager.getInstance(myProject);
        Place place = new Place(shreds);
        DocumentWindowImpl documentWindow = new DocumentWindowImpl(myHostDocument, isOneLineEditor, place);
        String fileName = PathUtil.makeFileName(myHostVirtualFile.getName(), fileExtension);
        VirtualFileWindowImpl virtualFile = new VirtualFileWindowImpl(fileName, myHostVirtualFile, documentWindow, myLanguage, outChars);
        Language forcedLanguage = myContextElement.getUserData(InjectedFileViewProvider.LANGUAGE_FOR_INJECTED_COPY_KEY);
        myLanguage = forcedLanguage == null ? LanguageSubstitutors.INSTANCE.substituteLanguage(myLanguage, virtualFile, myProject) : forcedLanguage;
        createDocument(virtualFile);
        InjectedFileViewProvider viewProvider = new InjectedFileViewProvider(myPsiManager, virtualFile, documentWindow, myLanguage);
        ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(myLanguage);
        assert parserDefinition != null : "Parser definition for language " + myLanguage + " is null";
        PsiFile psiFile = parserDefinition.createFile(viewProvider);
        SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = ((ShredImpl) shreds.get(0)).getSmartPointer();
        synchronized (InjectedLanguageManagerImpl.ourInjectionPsiLock) {
            final ASTNode parsedNode = keepTreeFromChameleoningBack(psiFile);
            assert parsedNode instanceof FileElement : "Parsed to " + parsedNode + " instead of FileElement";
            String documentText = documentManager.getLastCommittedDocument(documentWindow).getText();
            assert ((FileElement) parsedNode).textMatches(outChars) : exceptionContext("Before patch: doc:\n'" + documentText + "'\n---PSI:\n'" + parsedNode.getText() + "'\n---chars:\n'" + outChars + "'");
            viewProvider.setPatchingLeaves(true);
            try {
                patchLeaves(parsedNode, escapers, place);
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (RuntimeException e) {
                throw new RuntimeException(exceptionContext("Patch error"), e);
            } finally {
                viewProvider.setPatchingLeaves(false);
            }
            if (!((FileElement) parsedNode).textMatches(documentText)) {
                throw new AssertionError(exceptionContext("After patch: doc:\n'" + documentText + "'\n---PSI:\n'" + parsedNode.getText() + "'\n---chars:\n'" + outChars + "'"));
            }
            virtualFile.setContent(null, documentWindow.getText(), false);
            virtualFile.setWritable(virtualFile.getDelegate().isWritable());
            cacheEverything(place, documentWindow, viewProvider, psiFile, pointer);
            PsiFile cachedPsiFile = documentManager.getCachedPsiFile(documentWindow);
            assert cachedPsiFile == psiFile : "Cached psi :" + cachedPsiFile + " instead of " + psiFile;
            assert place.isValid();
            assert viewProvider.isValid();
            PsiFile newFile = registerDocument(documentWindow, psiFile, place, myHostPsiFile, documentManager);
            boolean mergeHappened = newFile != psiFile;
            if (mergeHappened) {
                InjectedLanguageUtil.clearCaches(psiFile, documentWindow);
                psiFile = newFile;
                viewProvider = (InjectedFileViewProvider) psiFile.getViewProvider();
                documentWindow = (DocumentWindowImpl) viewProvider.getDocument();
                virtualFile = (VirtualFileWindowImpl) viewProvider.getVirtualFile();
                boolean shredsRewritten = cacheEverything(place, documentWindow, viewProvider, psiFile, pointer);
                if (!shredsRewritten) {
                    place.dispose();
                    place = documentWindow.getShreds();
                }
            }
            assert psiFile.isValid();
            assert place.isValid();
            assert viewProvider.isValid();
            try {
                List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>> tokens = obtainHighlightTokensFromLexer(myLanguage, outChars, escapers, place, virtualFile, myProject);
                psiFile.putUserData(InjectedLanguageUtil.HIGHLIGHT_TOKENS, tokens);
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (RuntimeException e) {
                throw new RuntimeException(exceptionContext("Obtaining tokens error"), e);
            }
            addToResults(place, psiFile);
            assertEverythingIsAllright(documentManager, documentWindow, psiFile);
        }
    } finally {
        clear();
    }
}
Also used : VirtualFileWindowImpl(com.intellij.injected.editor.VirtualFileWindowImpl) PsiDocumentManagerBase(com.intellij.psi.impl.PsiDocumentManagerBase) ParserDefinition(com.intellij.lang.ParserDefinition) DocumentWindowImpl(com.intellij.injected.editor.DocumentWindowImpl) Language(com.intellij.lang.Language) ASTNode(com.intellij.lang.ASTNode) FileElement(com.intellij.psi.impl.source.tree.FileElement) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Aggregations

ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)175 NotNull (org.jetbrains.annotations.NotNull)45 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)41 VirtualFile (com.intellij.openapi.vfs.VirtualFile)38 Project (com.intellij.openapi.project.Project)28 Nullable (org.jetbrains.annotations.Nullable)23 IOException (java.io.IOException)20 Task (com.intellij.openapi.progress.Task)16 File (java.io.File)16 Document (com.intellij.openapi.editor.Document)14 Ref (com.intellij.openapi.util.Ref)13 PsiFile (com.intellij.psi.PsiFile)12 IndexNotReadyException (com.intellij.openapi.project.IndexNotReadyException)11 Logger (com.intellij.openapi.diagnostic.Logger)10 StringUtil (com.intellij.openapi.util.text.StringUtil)9 ContainerUtil (com.intellij.util.containers.ContainerUtil)9 ArrayList (java.util.ArrayList)9 NonNls (org.jetbrains.annotations.NonNls)9 ProgressManager (com.intellij.openapi.progress.ProgressManager)8 java.util (java.util)8