Search in sources :

Example 71 with ProgressIndicator

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

the class CodeSmellDetectorImpl method findCodeSmells.

@NotNull
private List<CodeSmellInfo> findCodeSmells(@NotNull final VirtualFile file, @NotNull final ProgressIndicator progress) {
    final List<CodeSmellInfo> result = Collections.synchronizedList(new ArrayList<CodeSmellInfo>());
    final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(myProject);
    final ProgressIndicator daemonIndicator = new DaemonProgressIndicator();
    ((ProgressIndicatorEx) progress).addStateDelegate(new AbstractProgressIndicatorExBase() {

        @Override
        public void cancel() {
            super.cancel();
            daemonIndicator.cancel();
        }
    });
    ProgressManager.getInstance().runProcess(new Runnable() {

        @Override
        public void run() {
            DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() {

                @Override
                public void run() {
                    final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
                    final Document document = FileDocumentManager.getInstance().getDocument(file);
                    if (psiFile == null || document == null) {
                        return;
                    }
                    List<HighlightInfo> infos = codeAnalyzer.runMainPasses(psiFile, document, daemonIndicator);
                    convertErrorsAndWarnings(infos, result, document);
                }
            });
        }
    }, daemonIndicator);
    return result;
}
Also used : CodeSmellInfo(com.intellij.codeInsight.CodeSmellInfo) Document(com.intellij.openapi.editor.Document) AbstractProgressIndicatorExBase(com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProgressIndicatorEx(com.intellij.openapi.wm.ex.ProgressIndicatorEx) PsiFile(com.intellij.psi.PsiFile) NotNull(org.jetbrains.annotations.NotNull)

Example 72 with ProgressIndicator

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

the class ExpressionStatisticsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    assert project != null;
    final Data topLevelData = new Data();
    final Data subData = new Data();
    final VirtualFile dir = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
    assert dir != null;
    final List<VirtualFile> javaFiles = collectJavaFiles(dir, project);
    if (!ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronouslyInReadAction(project, "Traversing PSI", true, "Cancel", null, new Runnable() {

        @Override
        public void run() {
            final PsiManager psiManager = PsiManager.getInstance(project);
            ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
            indicator.setIndeterminate(false);
            for (int i = 0; i < javaFiles.size(); i++) {
                VirtualFile file = javaFiles.get(i);
                indicator.setText2(file.getPath());
                indicator.setFraction((double) i / javaFiles.size());
                PsiFile psiFile = psiManager.findFile(file);
                if (psiFile instanceof PsiJavaFile) {
                    psiFile.accept(new PsiRecursiveElementWalkingVisitor() {

                        @Override
                        public void visitElement(PsiElement element) {
                            if (element instanceof PsiIdentifier) {
                                int offset = element.getTextRange().getStartOffset();
                                PsiExpression minExpression = PsiTreeUtil.getParentOfType(element, PsiExpression.class);
                                if (minExpression != null && minExpression.getTextRange().getStartOffset() == offset) {
                                    PsiExpression maxExpression = minExpression;
                                    while (true) {
                                        PsiExpression nextExpression = PsiTreeUtil.getParentOfType(maxExpression, PsiExpression.class, true);
                                        if (nextExpression == null || nextExpression.getTextRange().getStartOffset() != offset)
                                            break;
                                        maxExpression = nextExpression;
                                    }
                                    collectExpressionData(minExpression, maxExpression, topLevelData, subData);
                                }
                            }
                            super.visitElement(element);
                        }
                    });
                }
            }
        }
    })) {
        return;
    }
    Messages.showMessageDialog("Top-level: " + topLevelData.toString() + "\n\n" + "Sub-expressions: " + subData.toString(), "Expression Statistics", null);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Project(com.intellij.openapi.project.Project) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator)

Example 73 with ProgressIndicator

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

the class DocumentCommitThread method pollQueue.

// returns true if queue changed
private boolean pollQueue() {
    assert !myApplication.isDispatchThread() : Thread.currentThread();
    boolean success = false;
    Document document = null;
    Project project = null;
    CommitTask task = null;
    Object failureReason = null;
    try {
        ProgressIndicator indicator;
        synchronized (lock) {
            if (!myEnabled || (task = documentsToCommit.poll()) == null) {
                return false;
            }
            document = task.getDocument();
            indicator = task.indicator;
            project = task.project;
            if (project.isDisposed() || !((PsiDocumentManagerBase) PsiDocumentManager.getInstance(project)).isInUncommittedSet(document)) {
                log(project, "Abandon and proceed to next", task);
                return true;
            }
            if (indicator.isCanceled()) {
                // document has been marked as removed, e.g. by synchronous commit
                return true;
            }
            startNewTask(task, "Pulled new task");
            // transfer to documentsToApplyInEDT
            documentsToApplyInEDT.add(task);
        }
        if (indicator.isCanceled()) {
            success = false;
        } else {
            final CommitTask commitTask = task;
            final Ref<Pair<Runnable, Object>> result = new Ref<>();
            ProgressManager.getInstance().executeProcessUnderProgress(() -> result.set(commitUnderProgress(commitTask, false)), indicator);
            final Runnable finishRunnable = result.get().first;
            success = finishRunnable != null;
            failureReason = result.get().second;
            if (success) {
                assert !myApplication.isDispatchThread();
                TransactionGuardImpl guard = (TransactionGuardImpl) TransactionGuard.getInstance();
                guard.submitTransaction(project, task.myCreationContext, finishRunnable);
            }
        }
    } catch (ProcessCanceledException e) {
        // leave queue unchanged
        cancel(e + " (cancel reason: " + ((UserDataHolder) task.indicator).getUserData(CANCEL_REASON) + ")");
        success = false;
        failureReason = e;
    } catch (Throwable e) {
        cancel(e);
        failureReason = ExceptionUtil.getThrowableText(e);
    }
    if (!success && task != null) {
        final Project finalProject = project;
        final Document finalDocument = document;
        Object finalFailureReason = failureReason;
        CommitTask finalTask = task;
        ReadAction.run(() -> {
            if (finalProject.isDisposed())
                return;
            PsiDocumentManager documentManager = PsiDocumentManager.getInstance(finalProject);
            // sync commit hasn't intervened
            if (documentManager.isCommitted(finalDocument))
                return;
            CharSequence lastCommittedText = documentManager.getLastCommittedText(finalDocument);
            PsiFile file = documentManager.getPsiFile(finalDocument);
            List<Pair<PsiFileImpl, FileASTNode>> oldFileNodes = file == null ? null : getAllFileNodes(file);
            if (oldFileNodes != null) {
                doQueue(finalProject, finalDocument, oldFileNodes, "re-added on failure: " + finalFailureReason, finalTask.myCreationContext, lastCommittedText);
            }
        });
    }
    synchronized (lock) {
        // do not cancel, it's being invokeLatered
        currentTask = null;
    }
    return true;
}
Also used : Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 74 with ProgressIndicator

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

the class AntConfigurationImpl method loadState.

public void loadState(Element state) {
    myIsInitialized = Boolean.FALSE;
    try {
        myAntWorkspaceConfiguration.loadFromProjectSettings(state);
    } catch (InvalidDataException e) {
        LOG.error(e);
        return;
    }
    List<Pair<Element, String>> files = new ArrayList<>();
    for (Iterator<Element> iterator = state.getChildren(BUILD_FILE).iterator(); iterator.hasNext(); ) {
        Element element = iterator.next();
        iterator.remove();
        String url = element.getAttributeValue(URL);
        if (url != null) {
            files.add(Pair.create(element, url));
        }
    }
    final VirtualFileManager vfManager = VirtualFileManager.getInstance();
    // contexts
    myAntFileToContextFileMap.clear();
    for (Element element : state.getChildren(CONTEXT_MAPPING)) {
        String url = element.getAttributeValue(URL);
        String contextUrl = element.getAttributeValue(CONTEXT);
        VirtualFile file = vfManager.findFileByUrl(url);
        VirtualFile contextFile = vfManager.findFileByUrl(contextUrl);
        if (file != null && contextFile != null) {
            myAntFileToContextFileMap.put(file, contextFile);
        }
    }
    getProperties().readExternal(state);
    runWhenInitialized(() -> {
        String title = AntBundle.message("loading.ant.config.progress");
        queueLater(new Task.Backgroundable(getProject(), title, false) {

            public void run(@NotNull final ProgressIndicator indicator) {
                if (getProject().isDisposed()) {
                    return;
                }
                indicator.setIndeterminate(true);
                indicator.pushState();
                try {
                    indicator.setText(title);
                    ApplicationManager.getApplication().runReadAction(() -> {
                        try {
                            myInitThread = Thread.currentThread();
                            // first, remove existing files
                            for (AntBuildFile file : myBuildFiles) {
                                removeBuildFileImpl(file);
                            }
                            myBuildFiles.clear();
                            // then fill the configuration with the files configured in xml
                            List<Pair<Element, AntBuildFileBase>> buildFiles = new ArrayList<>(files.size());
                            for (Pair<Element, String> pair : files) {
                                final Element element = pair.getFirst();
                                final VirtualFile file = vfManager.findFileByUrl(pair.getSecond());
                                if (file == null) {
                                    continue;
                                }
                                try {
                                    final AntBuildFileBase buildFile = addBuildFileImpl(file);
                                    buildFile.readProperties(element);
                                    buildFiles.add(Pair.create(element, buildFile));
                                } catch (AntNoFileException ignored) {
                                } catch (InvalidDataException e) {
                                    LOG.error(e);
                                }
                            }
                            // updating properties separately to avoid unnecessary building of PSI after clearing caches
                            for (Pair<Element, AntBuildFileBase> pair : buildFiles) {
                                final AntBuildFileBase buildFile = pair.getSecond();
                                buildFile.updateProperties();
                                final VirtualFile vFile = buildFile.getVirtualFile();
                                final String buildFileUrl = vFile != null ? vFile.getUrl() : null;
                                for (Element e : pair.getFirst().getChildren(EXECUTE_ON_ELEMENT)) {
                                    final String eventId = e.getAttributeValue(EVENT_ELEMENT);
                                    ExecutionEvent event = null;
                                    final String targetName = e.getAttributeValue(TARGET_ELEMENT);
                                    if (ExecuteBeforeCompilationEvent.TYPE_ID.equals(eventId)) {
                                        event = ExecuteBeforeCompilationEvent.getInstance();
                                    } else if (ExecuteAfterCompilationEvent.TYPE_ID.equals(eventId)) {
                                        event = ExecuteAfterCompilationEvent.getInstance();
                                    } else if ("beforeRun".equals(eventId)) {
                                        /*
                      for compatibility with previous format

                      <buildFile url="file://$PROJECT_DIR$/module/src/support-scripts.xml">
                        <executeOn event="beforeRun" target="prebuild-steps" runConfigurationType="Application" runConfigurationName="Main" />
                      </buildFile>
                      */
                                        final String configType = e.getAttributeValue("runConfigurationType");
                                        final String configName = e.getAttributeValue("runConfigurationName");
                                        convertToBeforeRunTask(myProject, buildFileUrl, targetName, configType, configName);
                                    } else if (ExecuteCompositeTargetEvent.TYPE_ID.equals(eventId)) {
                                        try {
                                            event = new ExecuteCompositeTargetEvent(targetName);
                                        } catch (WrongNameFormatException e1) {
                                            LOG.info(e1);
                                            event = null;
                                        }
                                    }
                                    if (event != null) {
                                        try {
                                            event.readExternal(e, getProject());
                                            setTargetForEvent(buildFile, targetName, event);
                                        } catch (InvalidDataException readFailed) {
                                            LOG.info(readFailed.getMessage());
                                        }
                                    }
                                }
                            }
                            AntWorkspaceConfiguration.getInstance(getProject()).loadFileProperties();
                        } catch (InvalidDataException e) {
                            LOG.error(e);
                        } finally {
                            try {
                                incModificationCount();
                                updateRegisteredActions();
                            } finally {
                                myInitThread = null;
                                myIsInitialized = Boolean.TRUE;
                                ApplicationManager.getApplication().invokeLater(() -> myEventDispatcher.getMulticaster().configurationLoaded(), ModalityState.any());
                            }
                        }
                    });
                } finally {
                    indicator.popState();
                }
            }
        });
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) VirtualFileManager(com.intellij.openapi.vfs.VirtualFileManager) PsiElement(com.intellij.psi.PsiElement) Element(org.jdom.Element) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 75 with ProgressIndicator

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

the class ExecutionHandler method runBuildImpl.

/**
   * @param antBuildListener should not be null. Use {@link com.intellij.lang.ant.config.AntBuildListener#NULL}
   */
@Nullable
private static FutureResult<ProcessHandler> runBuildImpl(final AntBuildFileBase buildFile, String[] targets, @Nullable final AntBuildMessageView buildMessageViewToReuse, final DataContext dataContext, List<BuildFileProperty> additionalProperties, @NotNull final AntBuildListener antBuildListener, final boolean waitFor) {
    final AntBuildMessageView messageView;
    final GeneralCommandLine commandLine;
    final Project project = buildFile.getProject();
    try {
        FileDocumentManager.getInstance().saveAllDocuments();
        final AntCommandLineBuilder builder = new AntCommandLineBuilder();
        builder.setBuildFile(buildFile.getAllOptions(), VfsUtilCore.virtualToIoFile(buildFile.getVirtualFile()));
        builder.calculateProperties(dataContext, buildFile.getProject(), additionalProperties);
        builder.addTargets(targets);
        builder.getCommandLine().setCharset(EncodingProjectManager.getInstance(buildFile.getProject()).getDefaultCharset());
        messageView = prepareMessageView(buildMessageViewToReuse, buildFile, targets, additionalProperties);
        commandLine = builder.getCommandLine().toCommandLine();
        messageView.setBuildCommandLine(commandLine.getCommandLineString());
    } catch (RunCanceledException e) {
        e.showMessage(project, AntBundle.message("run.ant.error.dialog.title"));
        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
        return null;
    } catch (CantRunException e) {
        ExecutionErrorDialog.show(e, AntBundle.message("cant.run.ant.error.dialog.title"), project);
        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
        return null;
    } catch (Macro.ExecutionCancelledException e) {
        antBuildListener.buildFinished(AntBuildListener.ABORTED, 0);
        return null;
    } catch (Throwable e) {
        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
        LOG.error(e);
        return null;
    }
    final FutureResult<ProcessHandler> future = new FutureResult<>();
    new Task.Backgroundable(buildFile.getProject(), AntBundle.message("ant.build.progress.dialog.title"), true) {

        public boolean shouldStartInBackground() {
            return true;
        }

        public void onCancel() {
            antBuildListener.buildFinished(AntBuildListener.ABORTED, 0);
        }

        public void run(@NotNull final ProgressIndicator indicator) {
            try {
                ProcessHandler handler = runBuild(indicator, messageView, buildFile, antBuildListener, commandLine);
                future.set(handler);
                if (waitFor && handler != null) {
                    handler.waitFor();
                }
            } catch (Throwable e) {
                LOG.error(e);
                antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
            }
        }
    }.queue();
    return future;
}
Also used : Task(com.intellij.openapi.progress.Task) Macro(com.intellij.ide.macro.Macro) Project(com.intellij.openapi.project.Project) CantRunException(com.intellij.execution.CantRunException) FutureResult(com.intellij.util.concurrency.FutureResult) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)352 Task (com.intellij.openapi.progress.Task)139 NotNull (org.jetbrains.annotations.NotNull)98 VirtualFile (com.intellij.openapi.vfs.VirtualFile)96 Project (com.intellij.openapi.project.Project)78 File (java.io.File)52 IOException (java.io.IOException)48 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)44 Nullable (org.jetbrains.annotations.Nullable)43 ProgressManager (com.intellij.openapi.progress.ProgressManager)35 List (java.util.List)30 EmptyProgressIndicator (com.intellij.openapi.progress.EmptyProgressIndicator)28 Ref (com.intellij.openapi.util.Ref)27 VcsException (com.intellij.openapi.vcs.VcsException)25 ArrayList (java.util.ArrayList)23 ApplicationManager (com.intellij.openapi.application.ApplicationManager)22 Module (com.intellij.openapi.module.Module)21 Logger (com.intellij.openapi.diagnostic.Logger)20 java.util (java.util)20 Processor (com.intellij.util.Processor)18