Newer
Older
KisoJikkenNWP / src / main / java / istlab / KisoJikken / CommandRunner.java
@motoki miura motoki miura on 12 Sep 2023 2 KB v077-2
package istlab.KisoJikken;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class CommandRunner implements Runnable {
    public static String prompt = "> ";

    String command;

    Thread thread;
    Process process;
    // JButton runB;
    String workingDir;
    int win_height = 200;

    public CommandRunner(String cmd) {
        command = cmd;
        workingDir = App.userhome + App.nwpsrc;
        // runB = rB;
    }

    public CommandRunner(String cmd, String chdir) {
        command = cmd;
        if (chdir==null){
            workingDir = App.userhome + App.nwpsrc;
        } else {
            workingDir = chdir;
        }
        // runB = rB;
    }
    public CommandRunner(String cmd, String chdir, int winheight) {
        this(cmd, chdir);
        win_height = winheight;
    }

    public void startstop() {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
            // runB.setText("Stop");
        } else {
            process.destroyForcibly();
            thread = null;
            // runB.setText("Run");
        }
    }

    @Override
    public void run() {
        // Run script
        // System.out.println(scriptfile);
        List<String> cmds = Arrays.asList(command.split(" "));
        ProcessBuilder processBuilder = new ProcessBuilder(cmds);
        // ProcessBuilder processBuilder = new ProcessBuilder("pwd");
        processBuilder.directory(new File(workingDir));
        // processBuilder.inheritIO();
        JTAConsole con = new JTAConsole("(Exec) " + command, win_height);
        con.Systemoutprintln("=== 実行開始 ===");
        if (workingDir.equals(App.userhome + App.nwpsrc)) {
            con.Systemoutprintln(prompt+"cd ~" + App.nwpsrc);
        } else {
            con.Systemoutprintln(prompt+"cd " + workingDir);
        }
        con.Systemoutprintln(prompt + command);

        try {
            process = processBuilder.start();
            Launcher.allProcs.add(process);
            con.startBR(process);

            // BufferedReader reader = new BufferedReader(new
            // InputStreamReader(process.getInputStream()));
            // String line;
            // while ((line = reader.readLine()) != null) {
            // jta.append(line);
            // }
            process.waitFor();
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        con.Systemoutprintln("=== 終了 === (ALT+Wで閉じる)");

        thread = null;
        // runB.setText("Run");
    }

}