terminals.rs

  1use crate::Project;
  2use anyhow::{Context as _, Result};
  3use collections::HashMap;
  4use gpui::{AnyWindowHandle, App, AppContext as _, Context, Entity, Task, WeakEntity};
  5use itertools::Itertools;
  6use language::LanguageName;
  7use settings::{Settings, SettingsLocation};
  8use smol::channel::bounded;
  9use std::{
 10    borrow::Cow,
 11    env::{self},
 12    iter,
 13    path::{Path, PathBuf},
 14    sync::Arc,
 15};
 16use task::{Shell, ShellBuilder, SpawnInTerminal};
 17use terminal::{
 18    terminal_settings::{self, TerminalSettings, VenvSettings},
 19    TaskState, TaskStatus, Terminal, TerminalBuilder,
 20};
 21use util::ResultExt;
 22
 23// #[cfg(target_os = "macos")]
 24// use std::os::unix::ffi::OsStrExt;
 25
 26pub struct Terminals {
 27    pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
 28}
 29
 30/// Terminals are opened either for the users shell, or to run a task.
 31#[allow(clippy::large_enum_variant)]
 32#[derive(Debug)]
 33pub enum TerminalKind {
 34    /// Run a shell at the given path (or $HOME if None)
 35    Shell(Option<PathBuf>),
 36    /// Run a task.
 37    Task(SpawnInTerminal),
 38}
 39
 40/// SshCommand describes how to connect to a remote server
 41#[derive(Debug, Clone, PartialEq, Eq)]
 42pub struct SshCommand {
 43    arguments: Vec<String>,
 44}
 45
 46impl Project {
 47    pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> {
 48        let worktree = self
 49            .active_entry()
 50            .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
 51            .into_iter()
 52            .chain(self.worktrees(cx))
 53            .find_map(|tree| tree.read(cx).root_dir());
 54        worktree
 55    }
 56
 57    pub fn first_project_directory(&self, cx: &App) -> Option<PathBuf> {
 58        let worktree = self.worktrees(cx).next()?;
 59        let worktree = worktree.read(cx);
 60        if worktree.root_entry()?.is_dir() {
 61            Some(worktree.abs_path().to_path_buf())
 62        } else {
 63            None
 64        }
 65    }
 66
 67    pub fn ssh_details(&self, cx: &App) -> Option<(String, SshCommand)> {
 68        if let Some(ssh_client) = &self.ssh_client {
 69            let ssh_client = ssh_client.read(cx);
 70            if let Some(args) = ssh_client.ssh_args() {
 71                return Some((
 72                    ssh_client.connection_options().host.clone(),
 73                    SshCommand { arguments: args },
 74                ));
 75            }
 76        }
 77
 78        return None;
 79    }
 80
 81    pub fn create_terminal(
 82        &mut self,
 83        kind: TerminalKind,
 84        window: AnyWindowHandle,
 85        cx: &mut Context<Self>,
 86    ) -> Task<Result<Entity<Terminal>>> {
 87        let path: Option<Arc<Path>> = match &kind {
 88            TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
 89            TerminalKind::Task(spawn_task) => {
 90                if let Some(cwd) = &spawn_task.cwd {
 91                    Some(Arc::from(cwd.as_ref()))
 92                } else {
 93                    self.active_project_directory(cx)
 94                }
 95            }
 96        };
 97
 98        let mut settings_location = None;
 99        if let Some(path) = path.as_ref() {
100            if let Some((worktree, _)) = self.find_worktree(path, cx) {
101                settings_location = Some(SettingsLocation {
102                    worktree_id: worktree.read(cx).id(),
103                    path,
104                });
105            }
106        }
107        let settings = TerminalSettings::get(settings_location, cx).clone();
108
109        cx.spawn(move |project, mut cx| async move {
110            let python_venv_directory = if let Some(path) = path.clone() {
111                project
112                    .update(&mut cx, |this, cx| {
113                        this.python_venv_directory(path, settings.detect_venv.clone(), cx)
114                    })?
115                    .await
116            } else {
117                None
118            };
119            project.update(&mut cx, |project, cx| {
120                project.create_terminal_with_venv(kind, python_venv_directory, window, cx)
121            })?
122        })
123    }
124
125    pub fn terminal_settings<'a>(
126        &'a self,
127        path: &'a Option<PathBuf>,
128        cx: &'a App,
129    ) -> &'a TerminalSettings {
130        let mut settings_location = None;
131        if let Some(path) = path.as_ref() {
132            if let Some((worktree, _)) = self.find_worktree(path, cx) {
133                settings_location = Some(SettingsLocation {
134                    worktree_id: worktree.read(cx).id(),
135                    path,
136                });
137            }
138        }
139        TerminalSettings::get(settings_location, cx)
140    }
141
142    pub fn exec_in_shell(&self, command: String, cx: &App) -> std::process::Command {
143        let path = self.first_project_directory(cx);
144        let ssh_details = self.ssh_details(cx);
145        let settings = self.terminal_settings(&path, cx).clone();
146
147        let builder = ShellBuilder::new(ssh_details.is_none(), &settings.shell);
148        let (command, args) = builder.build(command, &Vec::new());
149
150        let mut env = self
151            .environment
152            .read(cx)
153            .get_cli_environment()
154            .unwrap_or_default();
155        env.extend(settings.env.clone());
156
157        match &self.ssh_details(cx) {
158            Some((_, ssh_command)) => {
159                let (command, args) = wrap_for_ssh(
160                    ssh_command,
161                    Some((&command, &args)),
162                    path.as_deref(),
163                    env,
164                    None,
165                );
166                let mut command = std::process::Command::new(command);
167                command.args(args);
168                command
169            }
170            None => {
171                let mut command = std::process::Command::new(command);
172                command.args(args);
173                command.envs(env);
174                if let Some(path) = path {
175                    command.current_dir(path);
176                }
177                command
178            }
179        }
180    }
181
182    pub fn create_terminal_with_venv(
183        &mut self,
184        kind: TerminalKind,
185        python_venv_directory: Option<PathBuf>,
186        window: AnyWindowHandle,
187        cx: &mut Context<Self>,
188    ) -> Result<Entity<Terminal>> {
189        let this = &mut *self;
190        let path: Option<Arc<Path>> = match &kind {
191            TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
192            TerminalKind::Task(spawn_task) => {
193                if let Some(cwd) = &spawn_task.cwd {
194                    Some(Arc::from(cwd.as_ref()))
195                } else {
196                    this.active_project_directory(cx)
197                }
198            }
199        };
200        let ssh_details = this.ssh_details(cx);
201
202        let mut settings_location = None;
203        if let Some(path) = path.as_ref() {
204            if let Some((worktree, _)) = this.find_worktree(path, cx) {
205                settings_location = Some(SettingsLocation {
206                    worktree_id: worktree.read(cx).id(),
207                    path,
208                });
209            }
210        }
211        let settings = TerminalSettings::get(settings_location, cx).clone();
212
213        let (completion_tx, completion_rx) = bounded(1);
214
215        // Start with the environment that we might have inherited from the Zed CLI.
216        let mut env = this
217            .environment
218            .read(cx)
219            .get_cli_environment()
220            .unwrap_or_default();
221        // Then extend it with the explicit env variables from the settings, so they take
222        // precedence.
223        env.extend(settings.env.clone());
224
225        let local_path = if ssh_details.is_none() {
226            path.clone()
227        } else {
228            None
229        };
230
231        let mut python_venv_activate_command = None;
232
233        let (spawn_task, shell) = match kind {
234            TerminalKind::Shell(_) => {
235                if let Some(python_venv_directory) = &python_venv_directory {
236                    python_venv_activate_command =
237                        this.python_activate_command(python_venv_directory, &settings.detect_venv);
238                }
239
240                match &ssh_details {
241                    Some((host, ssh_command)) => {
242                        log::debug!("Connecting to a remote server: {ssh_command:?}");
243
244                        // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
245                        // to properly display colors.
246                        // We do not have the luxury of assuming the host has it installed,
247                        // so we set it to a default that does not break the highlighting via ssh.
248                        env.entry("TERM".to_string())
249                            .or_insert_with(|| "xterm-256color".to_string());
250
251                        let (program, args) =
252                            wrap_for_ssh(&ssh_command, None, path.as_deref(), env, None);
253                        env = HashMap::default();
254                        (
255                            Option::<TaskState>::None,
256                            Shell::WithArguments {
257                                program,
258                                args,
259                                title_override: Some(format!("{} — Terminal", host).into()),
260                            },
261                        )
262                    }
263                    None => (None, settings.shell.clone()),
264                }
265            }
266            TerminalKind::Task(spawn_task) => {
267                let task_state = Some(TaskState {
268                    id: spawn_task.id,
269                    full_label: spawn_task.full_label,
270                    label: spawn_task.label,
271                    command_label: spawn_task.command_label,
272                    hide: spawn_task.hide,
273                    status: TaskStatus::Running,
274                    show_summary: spawn_task.show_summary,
275                    show_command: spawn_task.show_command,
276                    completion_rx,
277                });
278
279                env.extend(spawn_task.env);
280
281                if let Some(venv_path) = &python_venv_directory {
282                    env.insert(
283                        "VIRTUAL_ENV".to_string(),
284                        venv_path.to_string_lossy().to_string(),
285                    );
286                }
287
288                match &ssh_details {
289                    Some((host, ssh_command)) => {
290                        log::debug!("Connecting to a remote server: {ssh_command:?}");
291                        env.entry("TERM".to_string())
292                            .or_insert_with(|| "xterm-256color".to_string());
293                        let (program, args) = wrap_for_ssh(
294                            &ssh_command,
295                            Some((&spawn_task.command, &spawn_task.args)),
296                            path.as_deref(),
297                            env,
298                            python_venv_directory.as_deref(),
299                        );
300                        env = HashMap::default();
301                        (
302                            task_state,
303                            Shell::WithArguments {
304                                program,
305                                args,
306                                title_override: Some(format!("{} — Terminal", host).into()),
307                            },
308                        )
309                    }
310                    None => {
311                        if let Some(venv_path) = &python_venv_directory {
312                            add_environment_path(&mut env, &venv_path.join("bin")).log_err();
313                        }
314
315                        (
316                            task_state,
317                            Shell::WithArguments {
318                                program: spawn_task.command,
319                                args: spawn_task.args,
320                                title_override: None,
321                            },
322                        )
323                    }
324                }
325            }
326        };
327        TerminalBuilder::new(
328            local_path.map(|path| path.to_path_buf()),
329            python_venv_directory,
330            spawn_task,
331            shell,
332            env,
333            settings.cursor_shape.unwrap_or_default(),
334            settings.alternate_scroll,
335            settings.max_scroll_history_lines,
336            ssh_details.is_some(),
337            window,
338            completion_tx,
339            cx,
340        )
341        .map(|builder| {
342            let terminal_handle = cx.new(|cx| builder.subscribe(cx));
343
344            this.terminals
345                .local_handles
346                .push(terminal_handle.downgrade());
347
348            let id = terminal_handle.entity_id();
349            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
350                let handles = &mut project.terminals.local_handles;
351
352                if let Some(index) = handles
353                    .iter()
354                    .position(|terminal| terminal.entity_id() == id)
355                {
356                    handles.remove(index);
357                    cx.notify();
358                }
359            })
360            .detach();
361
362            if let Some(activate_command) = python_venv_activate_command {
363                this.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
364            }
365            terminal_handle
366        })
367    }
368
369    fn python_venv_directory(
370        &self,
371        abs_path: Arc<Path>,
372        venv_settings: VenvSettings,
373        cx: &Context<Project>,
374    ) -> Task<Option<PathBuf>> {
375        cx.spawn(move |this, mut cx| async move {
376            if let Some((worktree, _)) = this
377                .update(&mut cx, |this, cx| this.find_worktree(&abs_path, cx))
378                .ok()?
379            {
380                let toolchain = this
381                    .update(&mut cx, |this, cx| {
382                        this.active_toolchain(
383                            worktree.read(cx).id(),
384                            LanguageName::new("Python"),
385                            cx,
386                        )
387                    })
388                    .ok()?
389                    .await;
390
391                if let Some(toolchain) = toolchain {
392                    let toolchain_path = Path::new(toolchain.path.as_ref());
393                    return Some(toolchain_path.parent()?.parent()?.to_path_buf());
394                }
395            }
396            let venv_settings = venv_settings.as_option()?;
397            this.update(&mut cx, move |this, cx| {
398                if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
399                    return Some(path);
400                }
401                this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
402            })
403            .ok()
404            .flatten()
405        })
406    }
407
408    fn find_venv_in_worktree(
409        &self,
410        abs_path: &Path,
411        venv_settings: &terminal_settings::VenvSettingsContent,
412        cx: &App,
413    ) -> Option<PathBuf> {
414        let bin_dir_name = match std::env::consts::OS {
415            "windows" => "Scripts",
416            _ => "bin",
417        };
418        venv_settings
419            .directories
420            .iter()
421            .map(|name| abs_path.join(name))
422            .find(|venv_path| {
423                let bin_path = venv_path.join(bin_dir_name);
424                self.find_worktree(&bin_path, cx)
425                    .and_then(|(worktree, relative_path)| {
426                        worktree.read(cx).entry_for_path(&relative_path)
427                    })
428                    .is_some_and(|entry| entry.is_dir())
429            })
430    }
431
432    fn find_venv_on_filesystem(
433        &self,
434        abs_path: &Path,
435        venv_settings: &terminal_settings::VenvSettingsContent,
436        cx: &App,
437    ) -> Option<PathBuf> {
438        let (worktree, _) = self.find_worktree(abs_path, cx)?;
439        let fs = worktree.read(cx).as_local()?.fs();
440        let bin_dir_name = match std::env::consts::OS {
441            "windows" => "Scripts",
442            _ => "bin",
443        };
444        venv_settings
445            .directories
446            .iter()
447            .map(|name| abs_path.join(name))
448            .find(|venv_path| {
449                let bin_path = venv_path.join(bin_dir_name);
450                // One-time synchronous check is acceptable for terminal/task initialization
451                smol::block_on(fs.metadata(&bin_path))
452                    .ok()
453                    .flatten()
454                    .map_or(false, |meta| meta.is_dir)
455            })
456    }
457
458    fn python_activate_command(
459        &self,
460        venv_base_directory: &Path,
461        venv_settings: &VenvSettings,
462    ) -> Option<String> {
463        let venv_settings = venv_settings.as_option()?;
464        let activate_keyword = match venv_settings.activate_script {
465            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
466                "windows" => ".",
467                _ => "source",
468            },
469            terminal_settings::ActivateScript::Nushell => "overlay use",
470            terminal_settings::ActivateScript::PowerShell => ".",
471            _ => "source",
472        };
473        let activate_script_name = match venv_settings.activate_script {
474            terminal_settings::ActivateScript::Default => "activate",
475            terminal_settings::ActivateScript::Csh => "activate.csh",
476            terminal_settings::ActivateScript::Fish => "activate.fish",
477            terminal_settings::ActivateScript::Nushell => "activate.nu",
478            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
479        };
480        let path = venv_base_directory
481            .join(match std::env::consts::OS {
482                "windows" => "Scripts",
483                _ => "bin",
484            })
485            .join(activate_script_name)
486            .to_string_lossy()
487            .to_string();
488        let quoted = shlex::try_quote(&path).ok()?;
489        let line_ending = match std::env::consts::OS {
490            "windows" => "\r",
491            _ => "\n",
492        };
493        smol::block_on(self.fs.metadata(path.as_ref()))
494            .ok()
495            .flatten()?;
496
497        Some(format!(
498            "{} {} ; clear{}",
499            activate_keyword, quoted, line_ending
500        ))
501    }
502
503    fn activate_python_virtual_environment(
504        &self,
505        command: String,
506        terminal_handle: &Entity<Terminal>,
507        cx: &mut App,
508    ) {
509        terminal_handle.update(cx, |terminal, _| terminal.input_bytes(command.into_bytes()));
510    }
511
512    pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
513        &self.terminals.local_handles
514    }
515}
516
517fn wrap_for_ssh(
518    ssh_command: &SshCommand,
519    command: Option<(&String, &Vec<String>)>,
520    path: Option<&Path>,
521    env: HashMap<String, String>,
522    venv_directory: Option<&Path>,
523) -> (String, Vec<String>) {
524    let to_run = if let Some((command, args)) = command {
525        let command = Cow::Borrowed(command.as_str());
526        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
527        iter::once(command).chain(args).join(" ")
528    } else {
529        "exec ${SHELL:-sh} -l".to_string()
530    };
531
532    let mut env_changes = String::new();
533    for (k, v) in env.iter() {
534        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
535            env_changes.push_str(&format!("{}={} ", k, v));
536        }
537    }
538    if let Some(venv_directory) = venv_directory {
539        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
540            env_changes.push_str(&format!("PATH={}:$PATH ", str));
541        }
542    }
543
544    let commands = if let Some(path) = path {
545        let path_string = path.to_string_lossy().to_string();
546        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
547        // replace ith with something that works
548        let tilde_prefix = "~/";
549        if path.starts_with(tilde_prefix) {
550            let trimmed_path = path_string
551                .trim_start_matches("/")
552                .trim_start_matches("~")
553                .trim_start_matches("/");
554
555            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
556        } else {
557            format!("cd {path:?}; {env_changes} {to_run}")
558        }
559    } else {
560        format!("cd; {env_changes} {to_run}")
561    };
562    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
563
564    let program = "ssh".to_string();
565    let mut args = ssh_command.arguments.clone();
566
567    args.push("-t".to_string());
568    args.push(shell_invocation);
569    (program, args)
570}
571
572fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
573    let mut env_paths = vec![new_path.to_path_buf()];
574    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
575        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
576        env_paths.append(&mut paths);
577    }
578
579    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
580    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
581
582    Ok(())
583}
584
585#[cfg(test)]
586mod tests {
587    use collections::HashMap;
588
589    #[test]
590    fn test_add_environment_path_with_existing_path() {
591        let tmp_path = std::path::PathBuf::from("/tmp/new");
592        let mut env = HashMap::default();
593        let old_path = if cfg!(windows) {
594            "/usr/bin;/usr/local/bin"
595        } else {
596            "/usr/bin:/usr/local/bin"
597        };
598        env.insert("PATH".to_string(), old_path.to_string());
599        env.insert("OTHER".to_string(), "aaa".to_string());
600
601        super::add_environment_path(&mut env, &tmp_path).unwrap();
602        if cfg!(windows) {
603            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
604        } else {
605            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
606        }
607        assert_eq!(env.get("OTHER").unwrap(), "aaa");
608    }
609
610    #[test]
611    fn test_add_environment_path_with_empty_path() {
612        let tmp_path = std::path::PathBuf::from("/tmp/new");
613        let mut env = HashMap::default();
614        env.insert("OTHER".to_string(), "aaa".to_string());
615        let os_path = std::env::var("PATH").unwrap();
616        super::add_environment_path(&mut env, &tmp_path).unwrap();
617        if cfg!(windows) {
618            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
619        } else {
620            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
621        }
622        assert_eq!(env.get("OTHER").unwrap(), "aaa");
623    }
624}