<commit_before>package com.atsebak.embeddedlinuxjvm.commandline;

import com.atsebak.embeddedlinuxjvm.console.EmbeddedLinuxJVMConsoleView;
import com.atsebak.embeddedlinuxjvm.console.EmbeddedLinuxJVMOutputForwarder;
import com.atsebak.embeddedlinuxjvm.deploy.DeploymentTarget;
import com.atsebak.embeddedlinuxjvm.localization.EmbeddedLinuxJVMBundle;
import com.atsebak.embeddedlinuxjvm.protocol.ssh.SSHHandlerTarget;
import com.atsebak.embeddedlinuxjvm.protocol.ssh.jsch.EmbeddedSSHClient;
import com.atsebak.embeddedlinuxjvm.runner.conf.EmbeddedLinuxJVMRunConfiguration;
import com.atsebak.embeddedlinuxjvm.runner.data.EmbeddedLinuxJVMRunConfigurationRunnerParameters;
import com.atsebak.embeddedlinuxjvm.services.ClasspathService;
import com.atsebak.embeddedlinuxjvm.utils.FileUtilities;
import com.atsebak.embeddedlinuxjvm.utils.RemoteCommandLineBuilder;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.process.*;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.execution.remote.RemoteConfigurationType;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.util.NotNullFunction;
import com.intellij.util.PathsList;
import com.jcraft.jsch.Session;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class AppCommandLineState extends JavaCommandLineState {
    @NonNls
    private static final String RUN_CONFIGURATION_NAME_PATTERN = "PI Debugger (%s)";
    @NonNls
    private static final String DEBUG_TCP_MESSAGE = "Listening for transport dt_socket at address: %s";
    @NotNull
    private final EmbeddedLinuxJVMRunConfiguration configuration;
    @NotNull
    private final ExecutionEnvironment environment;
    @NotNull
    private final RunnerSettings runnerSettings;
    @NotNull
    private final EmbeddedLinuxJVMOutputForwarder outputForwarder;
    @NotNull
    private final boolean isDebugMode;
    @NotNull
    private final Project project;

    /**
     * Command line state when runner is launch
     *
     * @param environment
     * @param configuration
     */
    public AppCommandLineState(@NotNull ExecutionEnvironment environment, @NotNull EmbeddedLinuxJVMRunConfiguration configuration) {
        super(environment);
        this.configuration = configuration;
        this.environment = environment;
        this.runnerSettings = environment.getRunnerSettings();
        this.project = environment.getProject();
        this.isDebugMode = runnerSettings instanceof DebuggingRunnerData;
        this.outputForwarder = new EmbeddedLinuxJVMOutputForwarder(EmbeddedLinuxJVMConsoleView.getInstance(project));
        this.outputForwarder.attachTo(null);
    }

    /**
     * Gets the debug runner
     *
     * @param debugPort
     * @return
     */
    @NotNull
    public static String getRunConfigurationName(String debugPort) {
        return String.format(RUN_CONFIGURATION_NAME_PATTERN, debugPort);
    }

    /**
     * Creates the console view
     * @param executor
     * @return
     * @throws ExecutionException
     */
    @Nullable
    @Override
    protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException {
        return EmbeddedLinuxJVMConsoleView.getInstance(project).getConsoleView(true);
    }

    /**
     * Creates the command line view
     * @return
     * @throws ExecutionException
     */
    @Override
    protected GeneralCommandLine createCommandLine() throws ExecutionException {
        return RemoteCommandLineBuilder.createFromJavaParameters(getJavaParameters(), CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()), true);
    }

    /**
     * Starts console process
     * @return
     * @throws ExecutionException
     */
    @NotNull
    @Override
    protected OSProcessHandler startProcess() throws ExecutionException {
        final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine());
        ProcessTerminatedListener.attach(handler, project, EmbeddedLinuxJVMBundle.message("pi.console.exited"));
        handler.addProcessListener(new ProcessAdapter() {
            private void closeSSHConnection() {
                try {
                    if (isDebugMode) {
                        //todo fix tcp connection closing issue random error message showing up
                    }
                    Session session = EmbeddedLinuxJVMConsoleView.getInstance(project).getSession();
                    if (session != null) {
                        session.disconnect();
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
                ProgressManager.getInstance().run(new Task.Backgroundable(project, EmbeddedLinuxJVMBundle.message("pi.closingsession"), true) {
                    @Override
                    public void run(@NotNull ProgressIndicator progressIndicator) {
                        closeSSHConnection();
                    }
                });
                super.processWillTerminate(event, willBeDestroyed);
            }

        });
        return handler;
    }

    /**
     * Creates the necessary Java parameters for the application.
     *
     * @return
     * @throws ExecutionException
     */<commit_msg>comment on closing process<commit_after>package com.atsebak.embeddedlinuxjvm.commandline;

import com.atsebak.embeddedlinuxjvm.console.EmbeddedLinuxJVMConsoleView;
import com.atsebak.embeddedlinuxjvm.console.EmbeddedLinuxJVMOutputForwarder;
import com.atsebak.embeddedlinuxjvm.deploy.DeploymentTarget;
import com.atsebak.embeddedlinuxjvm.localization.EmbeddedLinuxJVMBundle;
import com.atsebak.embeddedlinuxjvm.protocol.ssh.SSHHandlerTarget;
import com.atsebak.embeddedlinuxjvm.protocol.ssh.jsch.EmbeddedSSHClient;
import com.atsebak.embeddedlinuxjvm.runner.conf.EmbeddedLinuxJVMRunConfiguration;
import com.atsebak.embeddedlinuxjvm.runner.data.EmbeddedLinuxJVMRunConfigurationRunnerParameters;
import com.atsebak.embeddedlinuxjvm.services.ClasspathService;
import com.atsebak.embeddedlinuxjvm.utils.FileUtilities;
import com.atsebak.embeddedlinuxjvm.utils.RemoteCommandLineBuilder;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.process.*;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.execution.remote.RemoteConfigurationType;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.util.NotNullFunction;
import com.intellij.util.PathsList;
import com.jcraft.jsch.Session;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class AppCommandLineState extends JavaCommandLineState {
    @NonNls
    private static final String RUN_CONFIGURATION_NAME_PATTERN = "PI Debugger (%s)";
    @NonNls
    private static final String DEBUG_TCP_MESSAGE = "Listening for transport dt_socket at address: %s";
    @NotNull
    private final EmbeddedLinuxJVMRunConfiguration configuration;
    @NotNull
    private final ExecutionEnvironment environment;
    @NotNull
    private final RunnerSettings runnerSettings;
    @NotNull
    private final EmbeddedLinuxJVMOutputForwarder outputForwarder;
    @NotNull
    private final boolean isDebugMode;
    @NotNull
    private final Project project;

    /**
     * Command line state when runner is launch
     *
     * @param environment
     * @param configuration
     */
    public AppCommandLineState(@NotNull ExecutionEnvironment environment, @NotNull EmbeddedLinuxJVMRunConfiguration configuration) {
        super(environment);
        this.configuration = configuration;
        this.environment = environment;
        this.runnerSettings = environment.getRunnerSettings();
        this.project = environment.getProject();
        this.isDebugMode = runnerSettings instanceof DebuggingRunnerData;
        this.outputForwarder = new EmbeddedLinuxJVMOutputForwarder(EmbeddedLinuxJVMConsoleView.getInstance(project));
        this.outputForwarder.attachTo(null);
    }

    /**
     * Gets the debug runner
     *
     * @param debugPort
     * @return
     */
    @NotNull
    public static String getRunConfigurationName(String debugPort) {
        return String.format(RUN_CONFIGURATION_NAME_PATTERN, debugPort);
    }

    /**
     * Creates the console view
     * @param executor
     * @return
     * @throws ExecutionException
     */
    @Nullable
    @Override
    protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException {
        return EmbeddedLinuxJVMConsoleView.getInstance(project).getConsoleView(true);
    }

    /**
     * Creates the command line view
     * @return
     * @throws ExecutionException
     */
    @Override
    protected GeneralCommandLine createCommandLine() throws ExecutionException {
        return RemoteCommandLineBuilder.createFromJavaParameters(getJavaParameters(), CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()), true);
    }

    /**
     * Starts console process
     * @return
     * @throws ExecutionException
     */
    @NotNull
    @Override
    protected OSProcessHandler startProcess() throws ExecutionException {
        final OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine());
        ProcessTerminatedListener.attach(handler, project, EmbeddedLinuxJVMBundle.message("pi.console.exited"));
        handler.addProcessListener(new ProcessAdapter() {
            private void closeSSHConnection() {
                try {
                    if (isDebugMode) {
                        //todo fix tcp connection closing issue random error message showing up
                    }
                    Session session = EmbeddedLinuxJVMConsoleView.getInstance(project).getSession();
                    if (session != null) {
                        session.disconnect();
                    }
                } catch (Exception e) {
                }
            }

            /**
             * Called when user clicks the stop button
             *
             * @param event
             * @param willBeDestroyed
             */
            @Override
            public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
                ProgressManager.getInstance().run(new Task.Backgroundable(project, EmbeddedLinuxJVMBundle.message("pi.closingsession"), true) {
                    @Override
                    public void run(@NotNull ProgressIndicator progressIndicator) {
                        closeSSHConnection();
                    }
                });
                super.processWillTerminate(event, willBeDestroyed);
            }

        });
        return handler;
    }

    /**
     * Creates the necessary Java parameters for the application.
     *
     * @return
     * @throws ExecutionException
     */
{'fraction_non_alphanumeric': 0.08038298819861946, 'fraction_numerical': 0.0, 'mean_word_length': 3.47641196013289, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3523858', 'n_tokens_mistral': 3702, 'n_tokens_neox': 3539, 'n_words': 670}