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