Search in sources :

Example 36 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project moe-ide-integration by multi-os-engine.

the class MOEGenerateActionsAndOutletsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Module module = (Module) dataContext.getData(LangDataKeys.MODULE.getName());
    if (module == null) {
        Messages.showErrorDialog("Failed to locate module", "Actions and Outlets Generation Error");
        return;
    }
    boolean isMaven = ModuleUtils.isMOEMavenModule(module);
    if (!isMaven) {
        ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {

            @Override
            public void run() {
                ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
                if (progress == null) {
                    progress = new EmptyProgressIndicator();
                }
                progress.pushState();
                try {
                    progress.setText(ACTION_PROGRESS_LABEL);
                    runInternal();
                } catch (final Throwable t) {
                    t.printStackTrace(System.err);
                    UIUtil.invokeLaterIfNeeded(new Runnable() {

                        @Override
                        public void run() {
                            String message = t.getMessage();
                            if (message == null || message.length() == 0) {
                                message = "Unknown error";
                            }
                            Messages.showErrorDialog(message, "Actions and Outlets Generation Error");
                            final MOEToolWindow toolWindow = MOEToolWindow.getInstance(module.getProject());
                            toolWindow.show();
                        }
                    });
                } finally {
                    progress.popState();
                }
            }

            private void runInternal() throws IOException, ExecutionException {
                final GeneralCommandLine commandLine = MOEGradleRunner.construct(module, "moeGenerateUIObjCInterfaces");
                final OSProcessHandler handler = new OSProcessHandler(commandLine);
                handler.setShouldDestroyProcessRecursively(true);
                // Configure output
                final MOEToolWindow toolWindow = MOEToolWindow.getInstance(module.getProject());
                toolWindow.clear();
                handler.addProcessListener(new ProcessAdapter() {

                    @Override
                    public void onTextAvailable(ProcessEvent event, Key outputType) {
                        if (ProcessOutputTypes.STDERR.equals(outputType)) {
                            toolWindow.error(event.getText());
                        } else if (ProcessOutputTypes.STDOUT.equals(outputType)) {
                            toolWindow.log(event.getText());
                        }
                    }
                });
                handler.startNotify();
                // Start and wait
                handler.waitFor();
                final int exitValue = handler.getProcess().exitValue();
                if (exitValue != 0) {
                    throw new IOException(ACTION_TITLE + " finished with non-zero exit value (" + exitValue + ")");
                }
            }
        }, ACTION_TITLE, true, module.getProject());
    } else {
        CompilerTask compilerTask = new CompilerTask(module.getProject(), "", false, true, true, true);
        compilerTask.start(new Runnable() {

            @Override
            public void run() {
                MOEMavenTask task = new MOEMavenTask(module, ACTION_TITLE, false);
                task.setGoal("moe:generateUIObjCInterfaces");
                if (!task.runTask()) {
                    ModuleUtils.runInDispatchedThread(new Runnable() {

                        @Override
                        public void run() {
                            Messages.showErrorDialog("Unable run generation", "Actions and Outlets Generation Error");
                        }
                    });
                }
            }
        }, null);
        ModuleUtils.runInDispatchedThread(new Runnable() {

            @Override
            public void run() {
                MOEMavenTask task = new MOEMavenTask(module, ACTION_TITLE, false);
                task.setGoal("moe:generateUIObjCInterfaces");
                if (!task.runTask()) {
                    Messages.showErrorDialog("Unable run generation", "Actions and Outlets Generation Error");
                }
            }
        });
    }
}
Also used : EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) CompilerTask(com.intellij.compiler.progress.CompilerTask) IOException(java.io.IOException) MOEMavenTask(org.moe.idea.maven.MOEMavenTask) DataContext(com.intellij.openapi.actionSystem.DataContext) MOEToolWindow(org.moe.idea.ui.MOEToolWindow) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) OSProcessHandler(com.intellij.execution.process.OSProcessHandler) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) Module(com.intellij.openapi.module.Module) ExecutionException(com.intellij.execution.ExecutionException) Key(com.intellij.openapi.util.Key)

Example 37 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project intellij by bazelbuild.

the class BlazeIntellijPluginConfiguration method getState.

/**
 * Plugin jar has been previously created via blaze build. This method: - copies jar to sandbox
 * environment - cracks open jar and finds plugin.xml (with ID, etc., needed for JVM args) - sets
 * up the SDK, etc. (use project SDK?) - sets up the JVM, and returns a JavaCommandLineState
 */
@Nullable
@Override
public RunProfileState getState(Executor executor, ExecutionEnvironment env) throws ExecutionException {
    final Sdk ideaJdk = pluginSdk;
    if (!IdeaJdkHelper.isIdeaJdk(ideaJdk)) {
        throw new ExecutionException("Choose an IntelliJ Platform Plugin SDK");
    }
    String sandboxHome = IdeaJdkHelper.getSandboxHome(ideaJdk);
    if (sandboxHome == null) {
        throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK");
    }
    try {
        sandboxHome = new File(sandboxHome).getCanonicalPath();
    } catch (IOException e) {
        throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK");
    }
    String buildNumber = IdeaJdkHelper.getBuildNumber(ideaJdk);
    final BlazeIntellijPluginDeployer deployer = new BlazeIntellijPluginDeployer(sandboxHome, buildNumber, getTarget());
    env.putUserData(BlazeIntellijPluginDeployer.USER_DATA_KEY, deployer);
    // copy license from running instance of idea
    IdeaJdkHelper.copyIDEALicense(sandboxHome);
    return new JavaCommandLineState(env) {

        @Override
        protected JavaParameters createJavaParameters() throws ExecutionException {
            List<String> pluginIds = deployer.deployNonBlocking();
            final JavaParameters params = new JavaParameters();
            ParametersList vm = params.getVMParametersList();
            fillParameterList(vm, vmParameters);
            fillParameterList(params.getProgramParametersList(), programParameters);
            IntellijWithPluginClasspathHelper.addRequiredVmParams(params, ideaJdk);
            vm.defineProperty(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY, Joiner.on(',').join(pluginIds));
            if (!vm.hasProperty(PlatformUtils.PLATFORM_PREFIX_KEY) && buildNumber != null) {
                String prefix = IdeaJdkHelper.getPlatformPrefix(buildNumber);
                if (prefix != null) {
                    vm.defineProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix);
                }
            }
            return params;
        }

        @Override
        protected OSProcessHandler startProcess() throws ExecutionException {
            deployer.blockUntilDeployComplete();
            final OSProcessHandler handler = super.startProcess();
            handler.addProcessListener(new ProcessAdapter() {

                @Override
                public void processTerminated(ProcessEvent event) {
                    deployer.deleteDeployment();
                }
            });
            return handler;
        }
    };
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) IOException(java.io.IOException) JavaCommandLineState(com.intellij.execution.configurations.JavaCommandLineState) ParametersList(com.intellij.execution.configurations.ParametersList) OSProcessHandler(com.intellij.execution.process.OSProcessHandler) JavaParameters(com.intellij.execution.configurations.JavaParameters) Sdk(com.intellij.openapi.projectRoots.Sdk) ExecutionException(com.intellij.execution.ExecutionException) File(java.io.File) Nullable(javax.annotation.Nullable)

Example 38 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project ballerina by ballerina-lang.

the class BallerinaExecutor method execute.

public boolean execute() {
    Logger.getInstance(getClass()).assertTrue(!ApplicationManager.getApplication().isDispatchThread(), "It's bad idea to run external tool on EDT");
    Logger.getInstance(getClass()).assertTrue(myProcessHandler == null, "Process has already run with this executor instance");
    Ref<Boolean> result = Ref.create(false);
    GeneralCommandLine commandLine = null;
    try {
        commandLine = createCommandLine();
        GeneralCommandLine finalCommandLine = commandLine;
        myProcessHandler = new KillableColoredProcessHandler(finalCommandLine, true) {

            @Override
            public void startNotify() {
                if (myShowBallerinaEnvVariables) {
                    BallerinaRunUtil.printBallerinaEnvVariables(finalCommandLine, this);
                }
                super.startNotify();
            }
        };
        BallerinaHistoryProcessListener historyProcessListener = new BallerinaHistoryProcessListener();
        myProcessHandler.addProcessListener(historyProcessListener);
        for (ProcessListener listener : myProcessListeners) {
            myProcessHandler.addProcessListener(listener);
        }
        CapturingProcessAdapter processAdapter = new CapturingProcessAdapter(myProcessOutput) {

            @Override
            public void processTerminated(@NotNull ProcessEvent event) {
                super.processTerminated(event);
                boolean success = event.getExitCode() == 0 && myProcessOutput.getStderr().isEmpty();
                boolean nothingToShow = myProcessOutput.getStdout().isEmpty() && myProcessOutput.getStderr().isEmpty();
                boolean cancelledByUser = (event.getExitCode() == -1 || event.getExitCode() == 2) && nothingToShow;
                result.set(success);
                if (success) {
                    if (myShowNotificationsOnSuccess) {
                        showNotification("Finished successfully", NotificationType.INFORMATION);
                    }
                } else if (cancelledByUser) {
                    if (myShowNotificationsOnError) {
                        showNotification("Interrupted", NotificationType.WARNING);
                    }
                } else if (myShowOutputOnError) {
                    ApplicationManager.getApplication().invokeLater(() -> showOutput(myProcessHandler, historyProcessListener));
                }
            }
        };
        myProcessHandler.addProcessListener(processAdapter);
        myProcessHandler.startNotify();
        ExecutionModes.SameThreadMode sameThreadMode = new ExecutionModes.SameThreadMode(getPresentableName());
        ExecutionHelper.executeExternalProcess(myProject, myProcessHandler, sameThreadMode, commandLine);
        LOGGER.debug("Finished `" + getPresentableName() + "` with result: " + result.get());
        return result.get();
    } catch (ExecutionException e) {
        if (myShowOutputOnError) {
            ExecutionHelper.showErrors(myProject, Collections.singletonList(e), getPresentableName(), null);
        }
        if (myShowNotificationsOnError) {
            showNotification(StringUtil.notNullize(e.getMessage(), "Unknown error, see logs for details"), NotificationType.ERROR);
        }
        String commandLineInfo = commandLine != null ? commandLine.getCommandLineString() : "not constructed";
        LOGGER.debug("Finished `" + getPresentableName() + "` with an exception. Commandline: " + commandLineInfo, e);
        return false;
    }
}
Also used : CapturingProcessAdapter(com.intellij.execution.process.CapturingProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) ProcessListener(com.intellij.execution.process.ProcessListener) NotNull(org.jetbrains.annotations.NotNull) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) ExecutionModes(com.intellij.execution.ExecutionModes) ExecutionException(com.intellij.execution.ExecutionException) KillableColoredProcessHandler(com.intellij.execution.process.KillableColoredProcessHandler)

Example 39 with ProcessEvent

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

the class DaemonApi method listen.

/**
 * Receive responses and events from a process until it shuts down.
 */
void listen(@NotNull ProcessHandler process, @NotNull DaemonEvent.Listener listener) {
    process.addProcessListener(new ProcessAdapter() {

        @Override
        public void onTextAvailable(ProcessEvent event, Key outputType) {
            if (outputType.equals(ProcessOutputTypes.STDERR)) {
                // Append text to last line in buffer.
                final String last = stderr.peekLast();
                if (last != null && !last.endsWith("\n")) {
                    stderr.removeLast();
                    stderr.add(last + event.getText());
                } else {
                    stderr.add(event.getText());
                }
                // Trim buffer size.
                while (stderr.size() > STDERR_LINES_TO_KEEP) {
                    stderr.removeFirst();
                }
            } else if (outputType.equals(ProcessOutputTypes.STDOUT)) {
                final String text = event.getText();
                if (FlutterSettings.getInstance().isVerboseLogging()) {
                    LOG.info("[<-- " + text.trim() + "]");
                }
                stdoutParser.appendOutput(text);
                for (String line : stdoutParser.getAvailableLines()) {
                    final JsonObject obj = parseAndValidateDaemonEvent(line);
                    if (obj != null) {
                        dispatch(obj, listener);
                    }
                }
            }
        }

        @Override
        public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
            listener.processWillTerminate();
        }

        @Override
        public void processTerminated(ProcessEvent event) {
            listener.processTerminated(event.getExitCode());
        }
    });
    // All hooked up and ready to receive events.
    process.startNotify();
}
Also used : ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) Key(com.intellij.openapi.util.Key)

Example 40 with ProcessEvent

use of com.intellij.execution.process.ProcessEvent in project azure-tools-for-java by Microsoft.

the class AzureRunProfileState method execute.

@Nullable
@Override
public ExecutionResult execute(Executor executor, @NotNull ProgramRunner programRunner) throws ExecutionException {
    final RunProcessHandler processHandler = new RunProcessHandler();
    processHandler.addDefaultListener();
    ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(this.project).getConsole();
    processHandler.startNotify();
    consoleView.attachToProcess(processHandler);
    final Operation operation = createOperation();
    final Disposable subscribe = Mono.fromCallable(() -> {
        try {
            operation.start();
            return this.executeSteps(processHandler, operation);
        } finally {
            // Once the operation done, whether success or not, `setText` should not throw new exception
            processHandler.setProcessTerminatedHandler(RunProcessHandler.DO_NOTHING);
        }
    }).subscribeOn(Schedulers.boundedElastic()).subscribe((res) -> {
        this.sendTelemetry(operation, null);
        this.onSuccess(res, processHandler);
    }, (err) -> {
        err.printStackTrace();
        this.sendTelemetry(operation, err);
        this.onFail(err, processHandler);
    });
    processHandler.addProcessListener(new ProcessAdapter() {

        @Override
        public void processTerminated(@NotNull ProcessEvent event) {
            subscribe.dispose();
        }
    });
    return new DefaultExecutionResult(consoleView, processHandler);
}
Also used : Disposable(reactor.core.Disposable) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) DefaultExecutionResult(com.intellij.execution.DefaultExecutionResult) ConsoleView(com.intellij.execution.ui.ConsoleView) ProcessEvent(com.intellij.execution.process.ProcessEvent) RunProcessHandler(com.microsoft.intellij.RunProcessHandler) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) Nullable(org.jetbrains.annotations.Nullable)

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