terminals.rs

  1use anyhow::Result;
  2use collections::HashMap;
  3use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity};
  4
  5use itertools::Itertools as _;
  6use language::LanguageName;
  7use remote::RemoteClient;
  8use settings::{Settings, SettingsLocation};
  9use smol::channel::bounded;
 10use std::{
 11    borrow::Cow,
 12    path::{Path, PathBuf},
 13    sync::Arc,
 14};
 15use task::{Shell, ShellBuilder, ShellKind, SpawnInTerminal};
 16use terminal::{
 17    TaskState, TaskStatus, Terminal, TerminalBuilder, terminal_settings::TerminalSettings,
 18};
 19use util::{get_default_system_shell, get_system_shell, maybe};
 20
 21use crate::{Project, ProjectPath};
 22
 23pub struct Terminals {
 24    pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
 25}
 26
 27impl Project {
 28    pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> {
 29        self.active_entry()
 30            .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
 31            .into_iter()
 32            .chain(self.worktrees(cx))
 33            .find_map(|tree| tree.read(cx).root_dir())
 34    }
 35
 36    pub fn first_project_directory(&self, cx: &App) -> Option<PathBuf> {
 37        let worktree = self.worktrees(cx).next()?;
 38        let worktree = worktree.read(cx);
 39        if worktree.root_entry()?.is_dir() {
 40            Some(worktree.abs_path().to_path_buf())
 41        } else {
 42            None
 43        }
 44    }
 45
 46    pub fn create_terminal_task(
 47        &mut self,
 48        spawn_task: SpawnInTerminal,
 49        cx: &mut Context<Self>,
 50    ) -> Task<Result<Entity<Terminal>>> {
 51        let is_via_remote = self.remote_client.is_some();
 52
 53        let path: Option<Arc<Path>> = if let Some(cwd) = &spawn_task.cwd {
 54            if is_via_remote {
 55                Some(Arc::from(cwd.as_ref()))
 56            } else {
 57                let cwd = cwd.to_string_lossy();
 58                let tilde_substituted = shellexpand::tilde(&cwd);
 59                Some(Arc::from(Path::new(tilde_substituted.as_ref())))
 60            }
 61        } else {
 62            self.active_project_directory(cx)
 63        };
 64
 65        let mut settings_location = None;
 66        if let Some(path) = path.as_ref()
 67            && let Some((worktree, _)) = self.find_worktree(path, cx)
 68        {
 69            settings_location = Some(SettingsLocation {
 70                worktree_id: worktree.read(cx).id(),
 71                path,
 72            });
 73        }
 74        let settings = TerminalSettings::get(settings_location, cx).clone();
 75        let detect_venv = settings.detect_venv.as_option().is_some();
 76
 77        let (completion_tx, completion_rx) = bounded(1);
 78
 79        // Start with the environment that we might have inherited from the Zed CLI.
 80        let mut env = self
 81            .environment
 82            .read(cx)
 83            .get_cli_environment()
 84            .unwrap_or_default();
 85        // Then extend it with the explicit env variables from the settings, so they take
 86        // precedence.
 87        env.extend(settings.env);
 88
 89        let local_path = if is_via_remote { None } else { path.clone() };
 90        let task_state = Some(TaskState {
 91            id: spawn_task.id,
 92            full_label: spawn_task.full_label,
 93            label: spawn_task.label,
 94            command_label: spawn_task.command_label,
 95            hide: spawn_task.hide,
 96            status: TaskStatus::Running,
 97            show_summary: spawn_task.show_summary,
 98            show_command: spawn_task.show_command,
 99            show_rerun: spawn_task.show_rerun,
100            completion_rx,
101        });
102        let remote_client = self.remote_client.clone();
103        let shell = match &remote_client {
104            Some(remote_client) => remote_client
105                .read(cx)
106                .shell()
107                .unwrap_or_else(get_default_system_shell),
108            None => match &settings.shell {
109                Shell::Program(program) => program.clone(),
110                Shell::WithArguments {
111                    program,
112                    args: _,
113                    title_override: _,
114                } => program.clone(),
115                Shell::System => get_system_shell(),
116            },
117        };
118
119        let project_path_contexts = self
120            .active_entry()
121            .and_then(|entry_id| self.path_for_entry(entry_id, cx))
122            .into_iter()
123            .chain(
124                self.visible_worktrees(cx)
125                    .map(|wt| wt.read(cx).id())
126                    .map(|worktree_id| ProjectPath {
127                        worktree_id,
128                        path: Arc::from(Path::new("")),
129                    }),
130            );
131        let toolchains = project_path_contexts
132            .filter(|_| detect_venv)
133            .map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx))
134            .collect::<Vec<_>>();
135        let lang_registry = self.languages.clone();
136        let fs = self.fs.clone();
137        cx.spawn(async move |project, cx| {
138            let shell_kind = ShellKind::new(&shell);
139            let activation_script = maybe!(async {
140                for toolchain in toolchains {
141                    let Some(toolchain) = toolchain.await else {
142                        continue;
143                    };
144                    let language = lang_registry
145                        .language_for_name(&toolchain.language_name.0)
146                        .await
147                        .ok();
148                    let lister = language?.toolchain_lister();
149                    return Some(
150                        lister?
151                            .activation_script(&toolchain, shell_kind, fs.as_ref())
152                            .await,
153                    );
154                }
155                None
156            })
157            .await
158            .unwrap_or_default();
159
160            project.update(cx, move |this, cx| {
161                let format_to_run = || {
162                    if let Some(command) = &spawn_task.command {
163                        let mut command: Option<Cow<str>> = shlex::try_quote(command).ok();
164                        if let Some(command) = &mut command
165                            && command.starts_with('"')
166                            && let Some(prefix) = shell_kind.command_prefix()
167                        {
168                            *command = Cow::Owned(format!("{prefix}{command}"));
169                        }
170
171                        let args = spawn_task
172                            .args
173                            .iter()
174                            .filter_map(|arg| shlex::try_quote(arg).ok());
175                        command.into_iter().chain(args).join(" ")
176                    } else {
177                        // todo: this breaks for remotes to windows
178                        format!("exec {shell} -l")
179                    }
180                };
181
182                let (shell, env) = {
183                    env.extend(spawn_task.env);
184                    match remote_client {
185                        Some(remote_client) => match activation_script.clone() {
186                            activation_script if !activation_script.is_empty() => {
187                                let activation_script = activation_script.join("; ");
188                                let to_run = format_to_run();
189                                let args =
190                                    vec!["-c".to_owned(), format!("{activation_script}; {to_run}")];
191                                create_remote_shell(
192                                    Some((
193                                        &remote_client
194                                            .read(cx)
195                                            .shell()
196                                            .unwrap_or_else(get_default_system_shell),
197                                        &args,
198                                    )),
199                                    env,
200                                    path,
201                                    remote_client,
202                                    cx,
203                                )?
204                            }
205                            _ => create_remote_shell(
206                                spawn_task
207                                    .command
208                                    .as_ref()
209                                    .map(|command| (command, &spawn_task.args)),
210                                env,
211                                path,
212                                remote_client,
213                                cx,
214                            )?,
215                        },
216                        None => match activation_script.clone() {
217                            activation_script if !activation_script.is_empty() => {
218                                let activation_script = activation_script.join("; ");
219                                let to_run = format_to_run();
220
221                                let arg = format!("{activation_script}; {to_run}");
222
223                                (
224                                    Shell::WithArguments {
225                                        program: shell,
226                                        args: vec!["-c".to_owned(), arg],
227                                        title_override: None,
228                                    },
229                                    env,
230                                )
231                            }
232                            _ => (
233                                if let Some(program) = spawn_task.command {
234                                    Shell::WithArguments {
235                                        program,
236                                        args: spawn_task.args,
237                                        title_override: None,
238                                    }
239                                } else {
240                                    Shell::System
241                                },
242                                env,
243                            ),
244                        },
245                    }
246                };
247                TerminalBuilder::new(
248                    local_path.map(|path| path.to_path_buf()),
249                    task_state,
250                    shell,
251                    env,
252                    settings.cursor_shape.unwrap_or_default(),
253                    settings.alternate_scroll,
254                    settings.max_scroll_history_lines,
255                    is_via_remote,
256                    cx.entity_id().as_u64(),
257                    Some(completion_tx),
258                    cx,
259                    activation_script,
260                )
261                .map(|builder| {
262                    let terminal_handle = cx.new(|cx| builder.subscribe(cx));
263
264                    this.terminals
265                        .local_handles
266                        .push(terminal_handle.downgrade());
267
268                    let id = terminal_handle.entity_id();
269                    cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
270                        let handles = &mut project.terminals.local_handles;
271
272                        if let Some(index) = handles
273                            .iter()
274                            .position(|terminal| terminal.entity_id() == id)
275                        {
276                            handles.remove(index);
277                            cx.notify();
278                        }
279                    })
280                    .detach();
281
282                    terminal_handle
283                })
284            })?
285        })
286    }
287
288    pub fn create_terminal_shell(
289        &mut self,
290        cwd: Option<PathBuf>,
291        cx: &mut Context<Self>,
292    ) -> Task<Result<Entity<Terminal>>> {
293        let path = cwd.map(|p| Arc::from(&*p));
294        let is_via_remote = self.remote_client.is_some();
295
296        let mut settings_location = None;
297        if let Some(path) = path.as_ref()
298            && let Some((worktree, _)) = self.find_worktree(path, cx)
299        {
300            settings_location = Some(SettingsLocation {
301                worktree_id: worktree.read(cx).id(),
302                path,
303            });
304        }
305        let settings = TerminalSettings::get(settings_location, cx).clone();
306        let detect_venv = settings.detect_venv.as_option().is_some();
307
308        // Start with the environment that we might have inherited from the Zed CLI.
309        let mut env = self
310            .environment
311            .read(cx)
312            .get_cli_environment()
313            .unwrap_or_default();
314        // Then extend it with the explicit env variables from the settings, so they take
315        // precedence.
316        env.extend(settings.env);
317
318        let local_path = if is_via_remote { None } else { path.clone() };
319
320        let project_path_contexts = self
321            .active_entry()
322            .and_then(|entry_id| self.path_for_entry(entry_id, cx))
323            .into_iter()
324            .chain(
325                self.visible_worktrees(cx)
326                    .map(|wt| wt.read(cx).id())
327                    .map(|worktree_id| ProjectPath {
328                        worktree_id,
329                        path: Arc::from(Path::new("")),
330                    }),
331            );
332        let toolchains = project_path_contexts
333            .filter(|_| detect_venv)
334            .map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx))
335            .collect::<Vec<_>>();
336        let remote_client = self.remote_client.clone();
337        let shell_kind = ShellKind::new(&match &remote_client {
338            Some(remote_client) => remote_client
339                .read(cx)
340                .shell()
341                .unwrap_or_else(get_default_system_shell),
342            None => match &settings.shell {
343                Shell::Program(program) => program.clone(),
344                Shell::WithArguments {
345                    program,
346                    args: _,
347                    title_override: _,
348                } => program.clone(),
349                Shell::System => get_system_shell(),
350            },
351        });
352
353        let lang_registry = self.languages.clone();
354        let fs = self.fs.clone();
355        cx.spawn(async move |project, cx| {
356            let activation_script = maybe!(async {
357                for toolchain in toolchains {
358                    let Some(toolchain) = toolchain.await else {
359                        continue;
360                    };
361                    let language = lang_registry
362                        .language_for_name(&toolchain.language_name.0)
363                        .await
364                        .ok();
365                    let lister = language?.toolchain_lister();
366                    return Some(
367                        lister?
368                            .activation_script(&toolchain, shell_kind, fs.as_ref())
369                            .await,
370                    );
371                }
372                None
373            })
374            .await
375            .unwrap_or_default();
376            project.update(cx, move |this, cx| {
377                let (shell, env) = {
378                    match remote_client {
379                        Some(remote_client) => {
380                            create_remote_shell(None, env, path, remote_client, cx)?
381                        }
382                        None => (settings.shell, env),
383                    }
384                };
385                TerminalBuilder::new(
386                    local_path.map(|path| path.to_path_buf()),
387                    None,
388                    shell,
389                    env,
390                    settings.cursor_shape.unwrap_or_default(),
391                    settings.alternate_scroll,
392                    settings.max_scroll_history_lines,
393                    is_via_remote,
394                    cx.entity_id().as_u64(),
395                    None,
396                    cx,
397                    activation_script,
398                )
399                .map(|builder| {
400                    let terminal_handle = cx.new(|cx| builder.subscribe(cx));
401
402                    this.terminals
403                        .local_handles
404                        .push(terminal_handle.downgrade());
405
406                    let id = terminal_handle.entity_id();
407                    cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
408                        let handles = &mut project.terminals.local_handles;
409
410                        if let Some(index) = handles
411                            .iter()
412                            .position(|terminal| terminal.entity_id() == id)
413                        {
414                            handles.remove(index);
415                            cx.notify();
416                        }
417                    })
418                    .detach();
419
420                    terminal_handle
421                })
422            })?
423        })
424    }
425
426    pub fn clone_terminal(
427        &mut self,
428        terminal: &Entity<Terminal>,
429        cx: &mut Context<'_, Project>,
430        cwd: impl FnOnce() -> Option<PathBuf>,
431    ) -> Result<Entity<Terminal>> {
432        terminal.read(cx).clone_builder(cx, cwd).map(|builder| {
433            let terminal_handle = cx.new(|cx| builder.subscribe(cx));
434
435            self.terminals
436                .local_handles
437                .push(terminal_handle.downgrade());
438
439            let id = terminal_handle.entity_id();
440            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
441                let handles = &mut project.terminals.local_handles;
442
443                if let Some(index) = handles
444                    .iter()
445                    .position(|terminal| terminal.entity_id() == id)
446                {
447                    handles.remove(index);
448                    cx.notify();
449                }
450            })
451            .detach();
452
453            terminal_handle
454        })
455    }
456
457    pub fn terminal_settings<'a>(
458        &'a self,
459        path: &'a Option<PathBuf>,
460        cx: &'a App,
461    ) -> &'a TerminalSettings {
462        let mut settings_location = None;
463        if let Some(path) = path.as_ref()
464            && let Some((worktree, _)) = self.find_worktree(path, cx)
465        {
466            settings_location = Some(SettingsLocation {
467                worktree_id: worktree.read(cx).id(),
468                path,
469            });
470        }
471        TerminalSettings::get(settings_location, cx)
472    }
473
474    pub fn exec_in_shell(&self, command: String, cx: &App) -> Result<std::process::Command> {
475        let path = self.first_project_directory(cx);
476        let remote_client = self.remote_client.as_ref();
477        let settings = self.terminal_settings(&path, cx).clone();
478        let remote_shell = remote_client
479            .as_ref()
480            .and_then(|remote_client| remote_client.read(cx).shell());
481        let builder = ShellBuilder::new(remote_shell.as_deref(), &settings.shell).non_interactive();
482        let (command, args) = builder.build(Some(command), &Vec::new());
483
484        let mut env = self
485            .environment
486            .read(cx)
487            .get_cli_environment()
488            .unwrap_or_default();
489        env.extend(settings.env);
490
491        match remote_client {
492            Some(remote_client) => {
493                let command_template =
494                    remote_client
495                        .read(cx)
496                        .build_command(Some(command), &args, &env, None, None)?;
497                let mut command = std::process::Command::new(command_template.program);
498                command.args(command_template.args);
499                command.envs(command_template.env);
500                Ok(command)
501            }
502            None => {
503                let mut command = std::process::Command::new(command);
504                command.args(args);
505                command.envs(env);
506                if let Some(path) = path {
507                    command.current_dir(path);
508                }
509                Ok(command)
510            }
511        }
512    }
513
514    pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
515        &self.terminals.local_handles
516    }
517}
518
519fn create_remote_shell(
520    spawn_command: Option<(&String, &Vec<String>)>,
521    mut env: HashMap<String, String>,
522    working_directory: Option<Arc<Path>>,
523    remote_client: Entity<RemoteClient>,
524    cx: &mut App,
525) -> Result<(Shell, HashMap<String, String>)> {
526    // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
527    // to properly display colors.
528    // We do not have the luxury of assuming the host has it installed,
529    // so we set it to a default that does not break the highlighting via ssh.
530    env.entry("TERM".to_string())
531        .or_insert_with(|| "xterm-256color".to_string());
532
533    let (program, args) = match spawn_command {
534        Some((program, args)) => (Some(program.clone()), args),
535        None => (None, &Vec::new()),
536    };
537
538    let command = remote_client.read(cx).build_command(
539        program,
540        args.as_slice(),
541        &env,
542        working_directory.map(|path| path.display().to_string()),
543        None,
544    )?;
545
546    log::debug!("Connecting to a remote server: {:?}", command.program);
547    let host = remote_client.read(cx).connection_options().display_name();
548
549    Ok((
550        Shell::WithArguments {
551            program: command.program,
552            args: command.args,
553            title_override: Some(format!("{} — Terminal", host).into()),
554        },
555        command.env,
556    ))
557}