Search in sources :

Example 16 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project android by JetBrains.

the class AndroidCommonUtils method executeZipAlign.

@Nullable
public static String executeZipAlign(@NotNull String zipAlignPath, @NotNull File source, @NotNull File destination) {
    List<String> commandLine = Arrays.asList(zipAlignPath, "-f", "4", source.getAbsolutePath(), destination.getAbsolutePath());
    final ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
    BaseOSProcessHandler handler;
    try {
        handler = new BaseOSProcessHandler(processBuilder.start(), StringUtil.join(commandLine, " "), null);
    } catch (IOException e) {
        return e.getMessage();
    }
    final StringBuilder builder = new StringBuilder();
    handler.addProcessListener(new ProcessAdapter() {

        @Override
        public void onTextAvailable(ProcessEvent event, Key outputType) {
            builder.append(event.getText());
        }
    });
    handler.startNotify();
    handler.waitFor();
    int exitCode = handler.getProcess().exitValue();
    return exitCode != 0 ? builder.toString() : null;
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) BaseOSProcessHandler(com.intellij.execution.process.BaseOSProcessHandler) Key(com.intellij.openapi.util.Key) Nullable(org.jetbrains.annotations.Nullable)

Example 17 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project android by JetBrains.

the class AndroidUtils method executeCommand.

@NotNull
public static ExecutionStatus executeCommand(@NotNull GeneralCommandLine commandLine, @Nullable final OutputProcessor processor, @Nullable WaitingStrategies.Strategy strategy) throws ExecutionException {
    LOG.info(commandLine.getCommandLineString());
    OSProcessHandler handler = new OSProcessHandler(commandLine);
    final ProcessAdapter listener = new ProcessAdapter() {

        @Override
        public void onTextAvailable(final ProcessEvent event, final Key outputType) {
            if (processor != null) {
                final String message = event.getText();
                processor.onTextAvailable(message);
            }
        }
    };
    if (!(strategy instanceof WaitingStrategies.DoNotWait)) {
        handler.addProcessListener(listener);
    }
    handler.startNotify();
    try {
        if (!(strategy instanceof WaitingStrategies.WaitForever)) {
            if (strategy instanceof WaitingStrategies.WaitForTime) {
                handler.waitFor(((WaitingStrategies.WaitForTime) strategy).getTimeMs());
            }
        } else {
            handler.waitFor();
        }
    } catch (ProcessCanceledException e) {
        return ExecutionStatus.ERROR;
    }
    if (!handler.isProcessTerminated()) {
        return ExecutionStatus.TIMEOUT;
    }
    if (!(strategy instanceof WaitingStrategies.DoNotWait)) {
        handler.removeProcessListener(listener);
    }
    int exitCode = handler.getProcess().exitValue();
    return exitCode == 0 ? ExecutionStatus.SUCCESS : ExecutionStatus.ERROR;
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) OSProcessHandler(com.intellij.execution.process.OSProcessHandler) Key(com.intellij.openapi.util.Key) RelativePoint(com.intellij.ui.awt.RelativePoint) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project intellij-community by JetBrains.

the class ExternalSystemUtil method runTask.

public static void runTask(@NotNull final ExternalSystemTaskExecutionSettings taskSettings, @NotNull final String executorId, @NotNull final Project project, @NotNull final ProjectSystemId externalSystemId, @Nullable final TaskCallback callback, @NotNull final ProgressExecutionMode progressExecutionMode, boolean activateToolWindowBeforeRun) {
    ExecutionEnvironment environment = createExecutionEnvironment(project, externalSystemId, taskSettings, executorId);
    if (environment == null)
        return;
    RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings();
    assert runnerAndConfigurationSettings != null;
    runnerAndConfigurationSettings.setActivateToolWindowBeforeRun(activateToolWindowBeforeRun);
    final TaskUnderProgress task = new TaskUnderProgress() {

        @Override
        public void execute(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            final Semaphore targetDone = new Semaphore();
            final Ref<Boolean> result = new Ref<>(false);
            final Disposable disposable = Disposer.newDisposable();
            project.getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() {

                public void processStartScheduled(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        targetDone.down();
                    }
                }

                public void processNotStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        targetDone.up();
                    }
                }

                public void processStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal, @NotNull final ProcessHandler handler) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        handler.addProcessListener(new ProcessAdapter() {

                            public void processTerminated(ProcessEvent event) {
                                result.set(event.getExitCode() == 0);
                                targetDone.up();
                            }
                        });
                    }
                }
            });
            try {
                ApplicationManager.getApplication().invokeAndWait(() -> {
                    try {
                        environment.getRunner().execute(environment);
                    } catch (ExecutionException e) {
                        targetDone.up();
                        LOG.error(e);
                    }
                }, ModalityState.defaultModalityState());
            } catch (Exception e) {
                LOG.error(e);
                Disposer.dispose(disposable);
                return;
            }
            targetDone.waitFor();
            Disposer.dispose(disposable);
            if (callback != null) {
                if (result.get()) {
                    callback.onSuccess();
                } else {
                    callback.onFailure();
                }
            }
        }
    };
    final String title = AbstractExternalSystemTaskConfigurationType.generateName(project, taskSettings);
    switch(progressExecutionMode) {
        case NO_PROGRESS_SYNC:
            task.execute(new EmptyProgressIndicator());
            break;
        case MODAL_SYNC:
            new Task.Modal(project, title, true) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
            break;
        case NO_PROGRESS_ASYNC:
            ApplicationManager.getApplication().executeOnPooledThread(() -> task.execute(new EmptyProgressIndicator()));
            break;
        case IN_BACKGROUND_ASYNC:
            new Task.Backgroundable(project, title) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
            break;
        case START_IN_FOREGROUND_ASYNC:
            new Task.Backgroundable(project, title, true, PerformInBackgroundOption.DEAF) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
    }
}
Also used : Disposable(com.intellij.openapi.Disposable) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) Task(com.intellij.openapi.progress.Task) ExternalSystemResolveProjectTask(com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProcessEvent(com.intellij.execution.process.ProcessEvent) Semaphore(com.intellij.util.concurrency.Semaphore) NotNull(org.jetbrains.annotations.NotNull) ImportCanceledException(com.intellij.openapi.externalSystem.service.ImportCanceledException) IOException(java.io.IOException) Ref(com.intellij.openapi.util.Ref) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProcessHandler(com.intellij.execution.process.ProcessHandler)

Example 19 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project intellij-community by JetBrains.

the class RunContentExecutor method run.

public void run() {
    FileDocumentManager.getInstance().saveAllDocuments();
    // Use user-provided console if exist. Create new otherwise
    ConsoleView view = (myUserProvidedConsole != null ? myUserProvidedConsole : createConsole());
    view.attachToProcess(myProcess);
    if (myAfterCompletion != null) {
        myProcess.addProcessListener(new ProcessAdapter() {

            @Override
            public void processTerminated(ProcessEvent event) {
                ApplicationManager.getApplication().invokeLater(myAfterCompletion);
            }
        });
    }
    myProcess.startNotify();
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ConsoleView(com.intellij.execution.ui.ConsoleView) ProcessEvent(com.intellij.execution.process.ProcessEvent)

Example 20 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent 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)

Aggregations

ProcessEvent (com.intellij.execution.process.ProcessEvent)89 ProcessAdapter (com.intellij.execution.process.ProcessAdapter)81 Key (com.intellij.openapi.util.Key)33 OSProcessHandler (com.intellij.execution.process.OSProcessHandler)24 NotNull (org.jetbrains.annotations.NotNull)24 ExecutionException (com.intellij.execution.ExecutionException)21 ProcessHandler (com.intellij.execution.process.ProcessHandler)18 GeneralCommandLine (com.intellij.execution.configurations.GeneralCommandLine)15 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)12 IOException (java.io.IOException)12 Nullable (org.jetbrains.annotations.Nullable)12 Project (com.intellij.openapi.project.Project)9 File (java.io.File)9 ProcessListener (com.intellij.execution.process.ProcessListener)8 RunContentDescriptor (com.intellij.execution.ui.RunContentDescriptor)7 ExecutionEnvironmentBuilder (com.intellij.execution.runners.ExecutionEnvironmentBuilder)5 ProgramRunner (com.intellij.execution.runners.ProgramRunner)5 VirtualFile (com.intellij.openapi.vfs.VirtualFile)5 DefaultRunExecutor (com.intellij.execution.executors.DefaultRunExecutor)4 Disposable (com.intellij.openapi.Disposable)4