terminals.rs

  1use crate::Project;
  2use collections::HashMap;
  3use gpui::{
  4    AnyWindowHandle, AppContext, Context, Entity, Model, ModelContext, SharedString, WeakModel,
  5};
  6use itertools::Itertools;
  7use settings::{Settings, SettingsLocation};
  8use smol::channel::bounded;
  9use std::{
 10    env,
 11    fs::File,
 12    io::Write,
 13    path::{Path, PathBuf},
 14};
 15use task::{SpawnInTerminal, TerminalWorkDir};
 16use terminal::{
 17    terminal_settings::{self, Shell, TerminalSettings, VenvSettingsContent},
 18    TaskState, TaskStatus, Terminal, TerminalBuilder,
 19};
 20use util::ResultExt;
 21
 22// #[cfg(target_os = "macos")]
 23// use std::os::unix::ffi::OsStrExt;
 24
 25pub struct Terminals {
 26    pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
 27}
 28
 29#[derive(Debug, Clone)]
 30pub struct ConnectRemoteTerminal {
 31    pub ssh_connection_string: SharedString,
 32    pub project_path: SharedString,
 33}
 34
 35impl Project {
 36    pub fn terminal_work_dir_for(
 37        &self,
 38        pathbuf: Option<&Path>,
 39        cx: &AppContext,
 40    ) -> Option<TerminalWorkDir> {
 41        if self.is_local() {
 42            return Some(TerminalWorkDir::Local(pathbuf?.to_owned()));
 43        }
 44        let dev_server_project_id = self.dev_server_project_id()?;
 45        let projects_store = dev_server_projects::Store::global(cx).read(cx);
 46        let ssh_command = projects_store
 47            .dev_server_for_project(dev_server_project_id)?
 48            .ssh_connection_string
 49            .as_ref()?
 50            .to_string();
 51
 52        let path = if let Some(pathbuf) = pathbuf {
 53            pathbuf.to_string_lossy().to_string()
 54        } else {
 55            projects_store
 56                .dev_server_project(dev_server_project_id)?
 57                .path
 58                .to_string()
 59        };
 60
 61        Some(TerminalWorkDir::Ssh {
 62            ssh_command,
 63            path: Some(path),
 64        })
 65    }
 66
 67    pub fn create_terminal(
 68        &mut self,
 69        working_directory: Option<TerminalWorkDir>,
 70        spawn_task: Option<SpawnInTerminal>,
 71        window: AnyWindowHandle,
 72        cx: &mut ModelContext<Self>,
 73    ) -> anyhow::Result<Model<Terminal>> {
 74        // used only for TerminalSettings::get
 75        let worktree = {
 76            let terminal_cwd = working_directory.as_ref().and_then(|cwd| cwd.local_path());
 77            let task_cwd = spawn_task
 78                .as_ref()
 79                .and_then(|spawn_task| spawn_task.cwd.as_ref())
 80                .and_then(|cwd| cwd.local_path());
 81
 82            terminal_cwd
 83                .and_then(|terminal_cwd| self.find_local_worktree(&terminal_cwd, cx))
 84                .or_else(|| task_cwd.and_then(|spawn_cwd| self.find_local_worktree(&spawn_cwd, cx)))
 85        };
 86
 87        let settings_location = worktree.as_ref().map(|(worktree, path)| SettingsLocation {
 88            worktree_id: worktree.read(cx).id().to_usize(),
 89            path,
 90        });
 91
 92        let is_terminal = spawn_task.is_none() && (working_directory.as_ref().is_none())
 93            || (working_directory.as_ref().unwrap().is_local());
 94        let settings = TerminalSettings::get(settings_location, cx);
 95        let python_settings = settings.detect_venv.clone();
 96        let (completion_tx, completion_rx) = bounded(1);
 97
 98        let mut env = settings.env.clone();
 99        // Alacritty uses parent project's working directory when no working directory is provided
100        // https://github.com/alacritty/alacritty/blob/fd1a3cc79192d1d03839f0fd8c72e1f8d0fce42e/extra/man/alacritty.5.scd?plain=1#L47-L52
101
102        let mut retained_script = None;
103
104        let venv_base_directory = working_directory
105            .as_ref()
106            .and_then(|cwd| cwd.local_path())
107            .unwrap_or_else(|| Path::new(""));
108
109        let (spawn_task, shell) = match working_directory.as_ref() {
110            Some(TerminalWorkDir::Ssh { ssh_command, path }) => {
111                log::debug!("Connecting to a remote server: {ssh_command:?}");
112                let tmp_dir = tempfile::tempdir()?;
113                let ssh_shell_result = prepare_ssh_shell(
114                    &mut env,
115                    tmp_dir.path(),
116                    spawn_task.as_ref(),
117                    ssh_command,
118                    path.as_deref(),
119                );
120                retained_script = Some(tmp_dir);
121                let ssh_shell = ssh_shell_result?;
122
123                (
124                    spawn_task.map(|spawn_task| TaskState {
125                        id: spawn_task.id,
126                        full_label: spawn_task.full_label,
127                        label: spawn_task.label,
128                        command_label: spawn_task.command_label,
129                        status: TaskStatus::Running,
130                        completion_rx,
131                    }),
132                    ssh_shell,
133                )
134            }
135            _ => {
136                if let Some(spawn_task) = spawn_task {
137                    log::debug!("Spawning task: {spawn_task:?}");
138                    env.extend(spawn_task.env);
139                    // Activate minimal Python virtual environment
140                    if let Some(python_settings) = &python_settings.as_option() {
141                        self.set_python_venv_path_for_tasks(
142                            python_settings,
143                            &venv_base_directory,
144                            &mut env,
145                        );
146                    }
147                    (
148                        Some(TaskState {
149                            id: spawn_task.id,
150                            full_label: spawn_task.full_label,
151                            label: spawn_task.label,
152                            command_label: spawn_task.command_label,
153                            status: TaskStatus::Running,
154                            completion_rx,
155                        }),
156                        Shell::WithArguments {
157                            program: spawn_task.command,
158                            args: spawn_task.args,
159                        },
160                    )
161                } else {
162                    (None, settings.shell.clone())
163                }
164            }
165        };
166
167        let terminal = TerminalBuilder::new(
168            working_directory
169                .as_ref()
170                .and_then(|cwd| cwd.local_path())
171                .map(ToOwned::to_owned),
172            spawn_task,
173            shell,
174            env,
175            Some(settings.blinking),
176            settings.alternate_scroll,
177            settings.max_scroll_history_lines,
178            window,
179            completion_tx,
180        )
181        .map(|builder| {
182            let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
183
184            self.terminals
185                .local_handles
186                .push(terminal_handle.downgrade());
187
188            let id = terminal_handle.entity_id();
189            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
190                drop(retained_script);
191                let handles = &mut project.terminals.local_handles;
192
193                if let Some(index) = handles
194                    .iter()
195                    .position(|terminal| terminal.entity_id() == id)
196                {
197                    handles.remove(index);
198                    cx.notify();
199                }
200            })
201            .detach();
202
203            // if the terminal is not a task, activate full Python virtual environment
204            if is_terminal {
205                if let Some(python_settings) = &python_settings.as_option() {
206                    if let Some(activate_script_path) =
207                        self.find_activate_script_path(python_settings, &venv_base_directory)
208                    {
209                        self.activate_python_virtual_environment(
210                            Project::get_activate_command(python_settings),
211                            activate_script_path,
212                            &terminal_handle,
213                            cx,
214                        );
215                    }
216                }
217            }
218            terminal_handle
219        });
220
221        terminal
222    }
223
224    pub fn find_activate_script_path(
225        &mut self,
226        settings: &VenvSettingsContent,
227        venv_base_directory: &Path,
228    ) -> Option<PathBuf> {
229        let activate_script_name = match settings.activate_script {
230            terminal_settings::ActivateScript::Default => "activate",
231            terminal_settings::ActivateScript::Csh => "activate.csh",
232            terminal_settings::ActivateScript::Fish => "activate.fish",
233            terminal_settings::ActivateScript::Nushell => "activate.nu",
234        };
235
236        settings
237            .directories
238            .into_iter()
239            .find_map(|virtual_environment_name| {
240                let path = venv_base_directory
241                    .join(virtual_environment_name)
242                    .join("bin")
243                    .join(activate_script_name);
244                path.exists().then_some(path)
245            })
246    }
247
248    pub fn set_python_venv_path_for_tasks(
249        &mut self,
250        settings: &VenvSettingsContent,
251        venv_base_directory: &Path,
252        env: &mut HashMap<String, String>,
253    ) {
254        let activate_path = settings
255            .directories
256            .into_iter()
257            .find_map(|virtual_environment_name| {
258                let path = venv_base_directory.join(virtual_environment_name);
259                path.exists().then_some(path)
260            });
261
262        if let Some(path) = activate_path {
263            // Some tools use VIRTUAL_ENV to detect the virtual environment
264            env.insert(
265                "VIRTUAL_ENV".to_string(),
266                path.to_string_lossy().to_string(),
267            );
268
269            let path_bin = path.join("bin");
270            // We need to set the PATH to include the virtual environment's bin directory
271            if let Some(paths) = std::env::var_os("PATH") {
272                let paths = std::iter::once(path_bin).chain(std::env::split_paths(&paths));
273                if let Some(new_path) = std::env::join_paths(paths).log_err() {
274                    env.insert("PATH".to_string(), new_path.to_string_lossy().to_string());
275                }
276            } else {
277                env.insert(
278                    "PATH".to_string(),
279                    path.join("bin").to_string_lossy().to_string(),
280                );
281            }
282        }
283    }
284
285    fn get_activate_command(settings: &VenvSettingsContent) -> &'static str {
286        match settings.activate_script {
287            terminal_settings::ActivateScript::Nushell => "overlay use",
288            _ => "source",
289        }
290    }
291
292    fn activate_python_virtual_environment(
293        &mut self,
294        activate_command: &'static str,
295        activate_script: PathBuf,
296        terminal_handle: &Model<Terminal>,
297        cx: &mut ModelContext<Project>,
298    ) {
299        // Paths are not strings so we need to jump through some hoops to format the command without `format!`
300        let mut command = Vec::from(activate_command.as_bytes());
301        command.push(b' ');
302        // Wrapping path in double quotes to catch spaces in folder name
303        command.extend_from_slice(b"\"");
304        command.extend_from_slice(activate_script.as_os_str().as_encoded_bytes());
305        command.extend_from_slice(b"\"");
306        command.push(b'\n');
307
308        terminal_handle.update(cx, |this, _| this.input_bytes(command));
309    }
310
311    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
312        &self.terminals.local_handles
313    }
314}
315
316fn prepare_ssh_shell(
317    env: &mut HashMap<String, String>,
318    tmp_dir: &Path,
319    spawn_task: Option<&SpawnInTerminal>,
320    ssh_command: &str,
321    path: Option<&str>,
322) -> anyhow::Result<Shell> {
323    // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
324    // to properly display colors.
325    // We do not have the luxury of assuming the host has it installed,
326    // so we set it to a default that does not break the highlighting via ssh.
327    env.entry("TERM".to_string())
328        .or_insert_with(|| "xterm-256color".to_string());
329
330    let real_ssh = which::which("ssh")?;
331    let ssh_path = tmp_dir.join("ssh");
332    let mut ssh_file = File::create(&ssh_path)?;
333
334    let to_run = if let Some(spawn_task) = spawn_task {
335        Some(shlex::try_quote(&spawn_task.command)?)
336            .into_iter()
337            .chain(
338                spawn_task
339                    .args
340                    .iter()
341                    .filter_map(|arg| shlex::try_quote(arg).ok()),
342            )
343            .join(" ")
344    } else {
345        "exec $SHELL -l".to_string()
346    };
347
348    let (port_forward, local_dev_env) =
349        if env::var("ZED_RPC_URL").as_deref() == Ok("http://localhost:8080/rpc") {
350            (
351                "-R 8080:localhost:8080",
352                "export ZED_RPC_URL=http://localhost:8080/rpc;",
353            )
354        } else {
355            ("", "")
356        };
357
358    let commands = if let Some(path) = path {
359        // I've found that `ssh -t dev sh -c 'cd; cd /tmp; pwd'` gives /tmp
360        // but `ssh -t dev sh -c 'cd /tmp; pwd'` gives /root
361        format!("cd {path}; {local_dev_env} {to_run}")
362    } else {
363        format!("cd; {local_dev_env} {to_run}")
364    };
365    let shell_invocation = &format!("sh -c {}", shlex::try_quote(&commands)?);
366
367    // To support things like `gh cs ssh`/`coder ssh`, we run whatever command
368    // you have configured, but place our custom script on the path so that it will
369    // be run instead.
370    write!(
371        &mut ssh_file,
372        "#!/bin/sh\nexec {} \"$@\" {} {} {}",
373        real_ssh.to_string_lossy(),
374        if spawn_task.is_none() { "-t" } else { "" },
375        port_forward,
376        shlex::try_quote(shell_invocation)?,
377    )?;
378
379    // todo(windows)
380    #[cfg(not(target_os = "windows"))]
381    std::fs::set_permissions(ssh_path, smol::fs::unix::PermissionsExt::from_mode(0o755))?;
382    let path = format!(
383        "{}:{}",
384        tmp_dir.to_string_lossy(),
385        env.get("PATH")
386            .cloned()
387            .or(env::var("PATH").ok())
388            .unwrap_or_default()
389    );
390    env.insert("PATH".to_string(), path);
391
392    let mut args = shlex::split(&ssh_command).unwrap_or_default();
393    let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
394    Ok(Shell::WithArguments { program, args })
395}