Search in sources :

Example 16 with Task

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

the class ExternalSystemUtil method refreshProject.

public static void refreshProject(@NotNull final String externalProjectPath, @NotNull final ImportSpec importSpec) {
    Project project = importSpec.getProject();
    ProjectSystemId externalSystemId = importSpec.getExternalSystemId();
    ExternalProjectRefreshCallback callback = importSpec.getCallback();
    boolean isPreviewMode = importSpec.isPreviewMode();
    ProgressExecutionMode progressExecutionMode = importSpec.getProgressExecutionMode();
    boolean reportRefreshError = importSpec.isReportRefreshError();
    String arguments = importSpec.getArguments();
    String vmOptions = importSpec.getVmOptions();
    File projectFile = new File(externalProjectPath);
    final String projectName;
    if (projectFile.isFile()) {
        projectName = projectFile.getParentFile().getName();
    } else {
        projectName = projectFile.getName();
    }
    final TaskUnderProgress refreshProjectStructureTask = new TaskUnderProgress() {

        private final ExternalSystemResolveProjectTask myTask = new ExternalSystemResolveProjectTask(externalSystemId, project, externalProjectPath, vmOptions, arguments, isPreviewMode);

        @SuppressWarnings({ "ThrowableResultOfMethodCallIgnored", "IOResourceOpenedButNotSafelyClosed" })
        @Override
        public void execute(@NotNull ProgressIndicator indicator) {
            if (project.isDisposed())
                return;
            if (indicator instanceof ProgressIndicatorEx) {
                ((ProgressIndicatorEx) indicator).addStateDelegate(new AbstractProgressIndicatorExBase() {

                    @Override
                    public void cancel() {
                        super.cancel();
                        ApplicationManager.getApplication().executeOnPooledThread((Runnable) () -> myTask.cancel(ExternalSystemTaskNotificationListener.EP_NAME.getExtensions()));
                    }
                });
            }
            ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
            if (processingManager.findTask(ExternalSystemTaskType.RESOLVE_PROJECT, externalSystemId, externalProjectPath) != null) {
                if (callback != null) {
                    callback.onFailure(ExternalSystemBundle.message("error.resolve.already.running", externalProjectPath), null);
                }
                return;
            }
            if (!(callback instanceof MyMultiExternalProjectRefreshCallback)) {
                ExternalSystemNotificationManager.getInstance(project).clearNotifications(null, NotificationSource.PROJECT_SYNC, externalSystemId);
            }
            final ExternalSystemTaskActivator externalSystemTaskActivator = ExternalProjectsManager.getInstance(project).getTaskActivator();
            if (!isPreviewMode && !externalSystemTaskActivator.runTasks(externalProjectPath, ExternalSystemTaskActivator.Phase.BEFORE_SYNC)) {
                return;
            }
            myTask.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
            if (project.isDisposed())
                return;
            final Throwable error = myTask.getError();
            if (error == null) {
                if (callback != null) {
                    DataNode<ProjectData> externalProject = myTask.getExternalProject();
                    if (externalProject != null && importSpec.shouldCreateDirectoriesForEmptyContentRoots()) {
                        externalProject.putUserData(ContentRootDataService.CREATE_EMPTY_DIRECTORIES, Boolean.TRUE);
                    }
                    callback.onSuccess(externalProject);
                }
                if (!isPreviewMode) {
                    externalSystemTaskActivator.runTasks(externalProjectPath, ExternalSystemTaskActivator.Phase.AFTER_SYNC);
                }
                return;
            }
            if (error instanceof ImportCanceledException) {
                // stop refresh task
                return;
            }
            String message = ExternalSystemApiUtil.buildErrorMessage(error);
            if (StringUtil.isEmpty(message)) {
                message = String.format("Can't resolve %s project at '%s'. Reason: %s", externalSystemId.getReadableName(), externalProjectPath, message);
            }
            if (callback != null) {
                callback.onFailure(message, extractDetails(error));
            }
            ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
            if (manager == null) {
                return;
            }
            AbstractExternalSystemSettings<?, ?, ?> settings = manager.getSettingsProvider().fun(project);
            ExternalProjectSettings projectSettings = settings.getLinkedProjectSettings(externalProjectPath);
            if (projectSettings == null || !reportRefreshError) {
                return;
            }
            ExternalSystemNotificationManager.getInstance(project).processExternalProjectRefreshError(error, projectName, externalSystemId);
        }
    };
    final String title;
    switch(progressExecutionMode) {
        case NO_PROGRESS_SYNC:
        case NO_PROGRESS_ASYNC:
            throw new ExternalSystemException("Please, use progress for the project import!");
        case MODAL_SYNC:
            title = ExternalSystemBundle.message("progress.import.text", projectName, externalSystemId.getReadableName());
            new Task.Modal(project, title, true) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    refreshProjectStructureTask.execute(indicator);
                }
            }.queue();
            break;
        case IN_BACKGROUND_ASYNC:
            title = ExternalSystemBundle.message("progress.refresh.text", projectName, externalSystemId.getReadableName());
            new Task.Backgroundable(project, title) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    refreshProjectStructureTask.execute(indicator);
                }
            }.queue();
            break;
        case START_IN_FOREGROUND_ASYNC:
            title = ExternalSystemBundle.message("progress.refresh.text", projectName, externalSystemId.getReadableName());
            new Task.Backgroundable(project, title, true, PerformInBackgroundOption.DEAF) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    refreshProjectStructureTask.execute(indicator);
                }
            }.queue();
    }
}
Also used : ExternalSystemTaskActivator(com.intellij.openapi.externalSystem.service.project.manage.ExternalSystemTaskActivator) Task(com.intellij.openapi.progress.Task) ExternalSystemResolveProjectTask(com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask) ExternalSystemProcessingManager(com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager) ImportCanceledException(com.intellij.openapi.externalSystem.service.ImportCanceledException) NotNull(org.jetbrains.annotations.NotNull) ExternalSystemResolveProjectTask(com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ExternalProjectRefreshCallback(com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback) ProjectData(com.intellij.openapi.externalSystem.model.project.ProjectData) ProgressExecutionMode(com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode) ExternalProjectSettings(com.intellij.openapi.externalSystem.settings.ExternalProjectSettings) Project(com.intellij.openapi.project.Project) AbstractProgressIndicatorExBase(com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase) DisposeAwareRunnable(com.intellij.util.DisposeAwareRunnable) ProgressIndicatorEx(com.intellij.openapi.wm.ex.ProgressIndicatorEx) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 17 with Task

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

the class FindUsagesManager method startProcessUsages.

@NotNull
public static ProgressIndicator startProcessUsages(@NotNull final FindUsagesHandler handler, @NotNull final PsiElement[] primaryElements, @NotNull final PsiElement[] secondaryElements, @NotNull final Processor<Usage> processor, @NotNull final FindUsagesOptions findUsagesOptions, @NotNull final Runnable onComplete) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final ProgressIndicatorBase indicator = new ProgressIndicatorBase();
    Task.Backgroundable task = new Task.Backgroundable(handler.getProject(), "Finding Usages") {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            UsageSearcher usageSearcher = ReadAction.compute(() -> {
                PsiElement2UsageTargetAdapter[] primaryTargets = PsiElement2UsageTargetAdapter.convert(primaryElements);
                PsiElement2UsageTargetAdapter[] secondaryTargets = PsiElement2UsageTargetAdapter.convert(secondaryElements);
                return createUsageSearcher(primaryTargets, secondaryTargets, handler, findUsagesOptions, null);
            });
            usageSearcher.generate(processor);
        }
    };
    ((ProgressManagerImpl) ProgressManager.getInstance()).runProcessWithProgressAsynchronously(task, indicator, onComplete);
    return indicator;
}
Also used : Task(com.intellij.openapi.progress.Task) ProgressIndicatorBase(com.intellij.openapi.progress.util.ProgressIndicatorBase) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProgressManagerImpl(com.intellij.openapi.progress.impl.ProgressManagerImpl) NotNull(org.jetbrains.annotations.NotNull) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with Task

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

the class AbstractDataGetter method loadCommitsData.

private void loadCommitsData(@NotNull final TIntIntHashMap commits, @NotNull final Consumer<List<T>> consumer, @Nullable ProgressIndicator indicator) {
    final List<T> result = ContainerUtil.newArrayList();
    final TIntHashSet toLoad = new TIntHashSet();
    long taskNumber = myCurrentTaskIndex++;
    for (int id : commits.keys()) {
        T details = getFromCache(id);
        if (details == null || details instanceof LoadingDetails) {
            toLoad.add(id);
            cacheCommit(id, taskNumber);
        } else {
            result.add(details);
        }
    }
    if (toLoad.isEmpty()) {
        sortCommitsByRow(result, commits);
        consumer.consume(result);
    } else {
        Task.Backgroundable task = new Task.Backgroundable(null, "Loading Selected Details", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {

            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
                indicator.checkCanceled();
                try {
                    TIntObjectHashMap<T> map = preLoadCommitData(toLoad);
                    map.forEachValue(value -> {
                        result.add(value);
                        return true;
                    });
                    sortCommitsByRow(result, commits);
                    notifyLoaded();
                } catch (VcsException e) {
                    LOG.error(e);
                }
            }

            @Override
            public void onSuccess() {
                consumer.consume(result);
            }
        };
        if (indicator != null) {
            ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator);
        } else {
            ProgressManager.getInstance().run(task);
        }
    }
}
Also used : Task(com.intellij.openapi.progress.Task) NotNull(org.jetbrains.annotations.NotNull) TIntHashSet(gnu.trove.TIntHashSet) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) VcsException(com.intellij.openapi.vcs.VcsException)

Example 19 with Task

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

the class TemplateModuleBuilder method createProject.

@Nullable
@Override
public Project createProject(String name, final String path) {
    final File location = new File(FileUtil.toSystemDependentName(path));
    LOG.assertTrue(location.exists());
    final VirtualFile baseDir = ApplicationManager.getApplication().runWriteAction((Computable<VirtualFile>) () -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(location));
    if (baseDir == null) {
        LOG.error("Couldn't find path '" + path + "' in VFS");
        return null;
    }
    VirtualFile[] children = baseDir.getChildren();
    boolean isSomehowOverwriting = children.length > 1 || (children.length == 1 && !PathMacroUtil.DIRECTORY_STORE_NAME.equals(children[0].getName()));
    Task.WithResult<Project, RuntimeException> task = new Task.WithResult<Project, RuntimeException>(null, "Applying Template", true) {

        @Override
        public Project compute(@NotNull ProgressIndicator indicator) {
            try {
                myProjectMode = true;
                unzip(name, path, false, indicator, false);
                return ProjectManagerEx.getInstanceEx().convertAndLoadProject(path);
            } catch (IOException e) {
                LOG.error(e);
                return null;
            } finally {
                cleanup();
                if (indicator.isCanceled()) {
                    if (!isSomehowOverwriting) {
                        ApplicationManager.getApplication().invokeLater(() -> {
                            try {
                                WriteAction.run(() -> baseDir.delete(TemplateProjectDirectoryGenerator.class));
                            } catch (IOException e) {
                                LOG.error(e);
                            }
                        });
                    }
                }
            }
        }
    };
    return ProgressManager.getInstance().run(task);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) IOException(java.io.IOException) NotNull(org.jetbrains.annotations.NotNull) Project(com.intellij.openapi.project.Project) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Example 20 with Task

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

the class DiffActionExecutor method showDiff.

public void showDiff() {
    final Ref<VcsException> exceptionRef = new Ref<>();
    final Ref<DiffRequest> requestRef = new Ref<>();
    final Task.Backgroundable task = new Task.Backgroundable(myProject, VcsBundle.message("show.diff.progress.title.detailed", mySelectedFile.getPresentableUrl()), true) {

        public void run(@NotNull ProgressIndicator indicator) {
            final VcsRevisionNumber revisionNumber = getRevisionNumber();
            try {
                if (revisionNumber == null) {
                    return;
                }
                DiffContent content1 = createRemote(revisionNumber);
                if (content1 == null)
                    return;
                DiffContent content2 = DiffContentFactory.getInstance().create(myProject, mySelectedFile);
                String title = DiffRequestFactory.getInstance().getTitle(mySelectedFile);
                boolean inverted = false;
                String title1;
                String title2;
                final FileStatus status = FileStatusManager.getInstance(myProject).getStatus(mySelectedFile);
                if (status == null || FileStatus.NOT_CHANGED.equals(status) || FileStatus.UNKNOWN.equals(status) || FileStatus.IGNORED.equals(status)) {
                    final VcsRevisionNumber currentRevision = myDiffProvider.getCurrentRevision(mySelectedFile);
                    inverted = revisionNumber.compareTo(currentRevision) > 0;
                    title1 = revisionNumber.asString();
                    title2 = VcsBundle.message("diff.title.local.with.number", currentRevision.asString());
                } else {
                    title1 = revisionNumber.asString();
                    title2 = VcsBundle.message("diff.title.local");
                }
                Integer line = null;
                if (content2 instanceof DocumentContent) {
                    Editor[] editors = EditorFactory.getInstance().getEditors(((DocumentContent) content2).getDocument(), myProject);
                    if (editors.length != 0)
                        line = editors[0].getCaretModel().getLogicalPosition().line;
                }
                if (inverted) {
                    SimpleDiffRequest request = new SimpleDiffRequest(title, content2, content1, title2, title1);
                    if (line != null)
                        request.putUserData(DiffUserDataKeys.SCROLL_TO_LINE, Pair.create(Side.LEFT, line));
                    request.putUserData(DiffUserDataKeys.MASTER_SIDE, Side.LEFT);
                    requestRef.set(request);
                } else {
                    SimpleDiffRequest request = new SimpleDiffRequest(title, content1, content2, title1, title2);
                    if (line != null)
                        request.putUserData(DiffUserDataKeys.SCROLL_TO_LINE, Pair.create(Side.RIGHT, line));
                    request.putUserData(DiffUserDataKeys.MASTER_SIDE, Side.RIGHT);
                    requestRef.set(request);
                }
            } catch (ProcessCanceledException e) {
            //ignore
            } catch (VcsException e) {
                exceptionRef.set(e);
            } catch (IOException e) {
                exceptionRef.set(new VcsException(e));
            }
        }

        @Override
        public void onCancel() {
            onSuccess();
        }

        @Override
        public void onSuccess() {
            myHandler.completed(VcsBackgroundableActions.keyFrom(mySelectedFile));
            if (!exceptionRef.isNull()) {
                AbstractVcsHelper.getInstance(myProject).showError(exceptionRef.get(), VcsBundle.message("message.title.diff"));
                return;
            }
            if (!requestRef.isNull()) {
                DiffManager.getInstance().showDiff(myProject, requestRef.get());
            }
        }
    };
    myHandler.register(VcsBackgroundableActions.keyFrom(mySelectedFile));
    ProgressManager.getInstance().run(task);
}
Also used : SimpleDiffRequest(com.intellij.diff.requests.SimpleDiffRequest) Task(com.intellij.openapi.progress.Task) DiffRequest(com.intellij.diff.requests.DiffRequest) SimpleDiffRequest(com.intellij.diff.requests.SimpleDiffRequest) IOException(java.io.IOException) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) DocumentContent(com.intellij.diff.contents.DocumentContent) VcsRevisionNumber(com.intellij.openapi.vcs.history.VcsRevisionNumber) Editor(com.intellij.openapi.editor.Editor) DiffContent(com.intellij.diff.contents.DiffContent) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Aggregations

Task (com.intellij.openapi.progress.Task)33 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)28 NotNull (org.jetbrains.annotations.NotNull)20 Project (com.intellij.openapi.project.Project)10 VirtualFile (com.intellij.openapi.vfs.VirtualFile)8 File (java.io.File)6 IOException (java.io.IOException)5 Editor (com.intellij.openapi.editor.Editor)3 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)3 Ref (com.intellij.openapi.util.Ref)3 Semaphore (com.intellij.util.concurrency.Semaphore)3 ArrayList (java.util.ArrayList)3 Nullable (org.jetbrains.annotations.Nullable)3 Disposable (com.intellij.openapi.Disposable)2 ProgressExecutionMode (com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode)2 BackgroundableProcessIndicator (com.intellij.openapi.progress.impl.BackgroundableProcessIndicator)2 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 Installer (com.android.repository.api.Installer)1 InstallerFactory (com.android.repository.api.InstallerFactory)1