terminals.rs

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