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