summaryrefslogtreecommitdiff
path: root/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java
blob: f67f84412a02b562a97ecf2bae9a26bfc968ed85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package org.jetbrains.plugins.terminal;

import com.intellij.execution.TaskExecutor;
import com.intellij.execution.configurations.EncodingEnvironmentUtil;
import com.intellij.execution.process.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.containers.HashMap;
import com.jediterm.pty.PtyProcessTtyConnector;
import com.jediterm.terminal.TtyConnector;
import com.pty4j.PtyProcess;
import com.pty4j.util.PtyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author traff
 */
public class LocalTerminalDirectRunner extends AbstractTerminalRunner<PtyProcess> {
  private static final Logger LOG = Logger.getInstance(LocalTerminalDirectRunner.class);

  private final Charset myDefaultCharset;

  public LocalTerminalDirectRunner(Project project) {
    super(project);
    myDefaultCharset = Charset.forName("UTF-8");
  }

  private static boolean hasLoginArgument(String name) {
    return name.equals("bash") || name.equals("sh") || name.equals("zsh");
  }

  private static String getShellName(String path) {
    return new File(path).getName();
  }

  private static File findRCFile() {
    try {
      final String folder = PtyUtil.getPtyLibFolderPath();
      if (folder != null) {
        File rcFile = new File(folder, "jediterm.in");
        if (rcFile.exists()) {
          return rcFile;
        }
      }
    }
    catch (Exception e) {
      LOG.warn("Unable to get jar folder", e);
    }
    return null;
  }

  @NotNull
  public static LocalTerminalDirectRunner createTerminalRunner(Project project) {
    return new LocalTerminalDirectRunner(project);
  }

  @Override
  protected PtyProcess createProcess(@Nullable String directory) throws ExecutionException {
    Map<String, String> envs = new HashMap<String, String>(System.getenv());
    envs.put("TERM", "xterm-256color");
    EncodingEnvironmentUtil.fixDefaultEncodingIfMac(envs, getProject());
    try {
      return PtyProcess.exec(getCommand(), envs, directory != null ? directory : currentProjectFolder());
    }
    catch (IOException e) {
      throw new ExecutionException(e);
    }
  }

  private String currentProjectFolder() {
    final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject);

    final VirtualFile[] roots = projectRootManager.getContentRoots();
    if (roots.length == 1) {
      roots[0].getCanonicalPath();
    }
    final VirtualFile baseDir = myProject.getBaseDir();
    return baseDir == null ? null : baseDir.getCanonicalPath();
  }

  @Override
  protected ProcessHandler createProcessHandler(final PtyProcess process) {
    return new PtyProcessHandler(process);
  }

  @Override
  protected TtyConnector createTtyConnector(PtyProcess process) {
    return new PtyProcessTtyConnector(process, myDefaultCharset);
  }

  @Override
  protected String getTerminalConnectionName(PtyProcess process) {
    return "Local Terminal";
  }

  public String[] getCommand() {
    String[] command;
    String shellPath = TerminalOptionsProvider.getInstance().getShellPath();

    if (SystemInfo.isUnix) {
      File rcFile = findRCFile();

      String shellName = getShellName(shellPath);

      if (rcFile != null && (shellName.equals("bash") || shellName.equals("sh"))) {
        command = new String[]{shellPath, "--rcfile", rcFile.getAbsolutePath(), "-i"};
      }
      else if (hasLoginArgument(shellName)) {
        command = new String[]{shellPath, "--login"};
      }
      else {
        command = shellPath.split(" ");
      }
    }
    else {
      command = new String[]{shellPath};
    }

    return command;
  }

  private static class PtyProcessHandler extends ProcessHandler implements TaskExecutor {

    private final PtyProcess myProcess;
    private final ProcessWaitFor myWaitFor;

    public PtyProcessHandler(PtyProcess process) {
      myProcess = process;
      myWaitFor = new ProcessWaitFor(process, this);
    }

    @Override
    public void startNotify() {
      addProcessListener(new ProcessAdapter() {
        @Override
        public void startNotified(ProcessEvent event) {
          try {
            myWaitFor.setTerminationCallback(new Consumer<Integer>() {
              @Override
              public void consume(Integer integer) {
                notifyProcessTerminated(integer);
              }
            });
          }
          finally {
            removeProcessListener(this);
          }
        }
      });

      super.startNotify();
    }

    @Override
    protected void destroyProcessImpl() {
      myProcess.destroy();
    }

    @Override
    protected void detachProcessImpl() {
      destroyProcessImpl();
    }

    @Override
    public boolean detachIsDefault() {
      return false;
    }

    @Override
    public boolean isSilentlyDestroyOnClose() {
      return true;
    }

    @Nullable
    @Override
    public OutputStream getProcessInput() {
      return myProcess.getOutputStream();
    }

    @Override
    public Future<?> executeTask(Runnable task) {
      return executeOnPooledThread(task);
    }

    protected static Future<?> executeOnPooledThread(Runnable task) {
      final Application application = ApplicationManager.getApplication();

      if (application != null) {
        return application.executeOnPooledThread(task);
      }

      return BaseOSProcessHandler.ExecutorServiceHolder.submit(task);
    }
  }
}