1use crate::Project;
2use anyhow::{Context as _, Result};
3use collections::HashMap;
4use gpui::{AnyWindowHandle, AppContext, Context, Entity, Model, ModelContext, Task, WeakModel};
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, 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<WeakModel<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: &AppContext) -> 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: &AppContext) -> 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 fn ssh_details(&self, cx: &AppContext) -> 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 ModelContext<Self>,
86 ) -> Task<Result<Model<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 create_terminal_with_venv(
126 &mut self,
127 kind: TerminalKind,
128 python_venv_directory: Option<PathBuf>,
129 window: AnyWindowHandle,
130 cx: &mut ModelContext<Self>,
131 ) -> Result<Model<Terminal>> {
132 let this = &mut *self;
133 let path: Option<Arc<Path>> = match &kind {
134 TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
135 TerminalKind::Task(spawn_task) => {
136 if let Some(cwd) = &spawn_task.cwd {
137 Some(Arc::from(cwd.as_ref()))
138 } else {
139 this.active_project_directory(cx)
140 }
141 }
142 };
143 let ssh_details = this.ssh_details(cx);
144
145 let mut settings_location = None;
146 if let Some(path) = path.as_ref() {
147 if let Some((worktree, _)) = this.find_worktree(path, cx) {
148 settings_location = Some(SettingsLocation {
149 worktree_id: worktree.read(cx).id(),
150 path,
151 });
152 }
153 }
154 let settings = TerminalSettings::get(settings_location, cx).clone();
155
156 let (completion_tx, completion_rx) = bounded(1);
157
158 // Start with the environment that we might have inherited from the Zed CLI.
159 let mut env = this
160 .environment
161 .read(cx)
162 .get_cli_environment()
163 .unwrap_or_default();
164 // Then extend it with the explicit env variables from the settings, so they take
165 // precedence.
166 env.extend(settings.env.clone());
167
168 let local_path = if ssh_details.is_none() {
169 path.clone()
170 } else {
171 None
172 };
173
174 let mut python_venv_activate_command = None;
175
176 let (spawn_task, shell) = match kind {
177 TerminalKind::Shell(_) => {
178 if let Some(python_venv_directory) = &python_venv_directory {
179 python_venv_activate_command =
180 this.python_activate_command(python_venv_directory, &settings.detect_venv);
181 }
182
183 match &ssh_details {
184 Some((host, ssh_command)) => {
185 log::debug!("Connecting to a remote server: {ssh_command:?}");
186
187 // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
188 // to properly display colors.
189 // We do not have the luxury of assuming the host has it installed,
190 // so we set it to a default that does not break the highlighting via ssh.
191 env.entry("TERM".to_string())
192 .or_insert_with(|| "xterm-256color".to_string());
193
194 let (program, args) =
195 wrap_for_ssh(&ssh_command, None, path.as_deref(), env, None);
196 env = HashMap::default();
197 (
198 Option::<TaskState>::None,
199 Shell::WithArguments {
200 program,
201 args,
202 title_override: Some(format!("{} — Terminal", host).into()),
203 },
204 )
205 }
206 None => (None, settings.shell.clone()),
207 }
208 }
209 TerminalKind::Task(spawn_task) => {
210 let task_state = Some(TaskState {
211 id: spawn_task.id,
212 full_label: spawn_task.full_label,
213 label: spawn_task.label,
214 command_label: spawn_task.command_label,
215 hide: spawn_task.hide,
216 status: TaskStatus::Running,
217 show_summary: spawn_task.show_summary,
218 show_command: spawn_task.show_command,
219 completion_rx,
220 });
221
222 env.extend(spawn_task.env);
223
224 if let Some(venv_path) = &python_venv_directory {
225 env.insert(
226 "VIRTUAL_ENV".to_string(),
227 venv_path.to_string_lossy().to_string(),
228 );
229 }
230
231 match &ssh_details {
232 Some((host, ssh_command)) => {
233 log::debug!("Connecting to a remote server: {ssh_command:?}");
234 env.entry("TERM".to_string())
235 .or_insert_with(|| "xterm-256color".to_string());
236 let (program, args) = wrap_for_ssh(
237 &ssh_command,
238 Some((&spawn_task.command, &spawn_task.args)),
239 path.as_deref(),
240 env,
241 python_venv_directory.as_deref(),
242 );
243 env = HashMap::default();
244 (
245 task_state,
246 Shell::WithArguments {
247 program,
248 args,
249 title_override: Some(format!("{} — Terminal", host).into()),
250 },
251 )
252 }
253 None => {
254 if let Some(venv_path) = &python_venv_directory {
255 add_environment_path(&mut env, &venv_path.join("bin")).log_err();
256 }
257
258 (
259 task_state,
260 Shell::WithArguments {
261 program: spawn_task.command,
262 args: spawn_task.args,
263 title_override: None,
264 },
265 )
266 }
267 }
268 }
269 };
270 TerminalBuilder::new(
271 local_path.map(|path| path.to_path_buf()),
272 python_venv_directory,
273 spawn_task,
274 shell,
275 env,
276 settings.cursor_shape.unwrap_or_default(),
277 settings.alternate_scroll,
278 settings.max_scroll_history_lines,
279 ssh_details.is_some(),
280 window,
281 completion_tx,
282 cx,
283 )
284 .map(|builder| {
285 let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
286
287 this.terminals
288 .local_handles
289 .push(terminal_handle.downgrade());
290
291 let id = terminal_handle.entity_id();
292 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
293 let handles = &mut project.terminals.local_handles;
294
295 if let Some(index) = handles
296 .iter()
297 .position(|terminal| terminal.entity_id() == id)
298 {
299 handles.remove(index);
300 cx.notify();
301 }
302 })
303 .detach();
304
305 if let Some(activate_command) = python_venv_activate_command {
306 this.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
307 }
308 terminal_handle
309 })
310 }
311
312 fn python_venv_directory(
313 &self,
314 abs_path: Arc<Path>,
315 venv_settings: VenvSettings,
316 cx: &ModelContext<Project>,
317 ) -> Task<Option<PathBuf>> {
318 cx.spawn(move |this, mut cx| async move {
319 if let Some((worktree, _)) = this
320 .update(&mut cx, |this, cx| this.find_worktree(&abs_path, cx))
321 .ok()?
322 {
323 let toolchain = this
324 .update(&mut cx, |this, cx| {
325 this.active_toolchain(
326 worktree.read(cx).id(),
327 LanguageName::new("Python"),
328 cx,
329 )
330 })
331 .ok()?
332 .await;
333
334 if let Some(toolchain) = toolchain {
335 let toolchain_path = Path::new(toolchain.path.as_ref());
336 return Some(toolchain_path.parent()?.parent()?.to_path_buf());
337 }
338 }
339 let venv_settings = venv_settings.as_option()?;
340 this.update(&mut cx, move |this, cx| {
341 if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
342 return Some(path);
343 }
344 this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
345 })
346 .ok()
347 .flatten()
348 })
349 }
350
351 fn find_venv_in_worktree(
352 &self,
353 abs_path: &Path,
354 venv_settings: &terminal_settings::VenvSettingsContent,
355 cx: &AppContext,
356 ) -> Option<PathBuf> {
357 let bin_dir_name = match std::env::consts::OS {
358 "windows" => "Scripts",
359 _ => "bin",
360 };
361 venv_settings
362 .directories
363 .iter()
364 .map(|name| abs_path.join(name))
365 .find(|venv_path| {
366 let bin_path = venv_path.join(bin_dir_name);
367 self.find_worktree(&bin_path, cx)
368 .and_then(|(worktree, relative_path)| {
369 worktree.read(cx).entry_for_path(&relative_path)
370 })
371 .is_some_and(|entry| entry.is_dir())
372 })
373 }
374
375 fn find_venv_on_filesystem(
376 &self,
377 abs_path: &Path,
378 venv_settings: &terminal_settings::VenvSettingsContent,
379 cx: &AppContext,
380 ) -> Option<PathBuf> {
381 let (worktree, _) = self.find_worktree(abs_path, cx)?;
382 let fs = worktree.read(cx).as_local()?.fs();
383 let bin_dir_name = match std::env::consts::OS {
384 "windows" => "Scripts",
385 _ => "bin",
386 };
387 venv_settings
388 .directories
389 .iter()
390 .map(|name| abs_path.join(name))
391 .find(|venv_path| {
392 let bin_path = venv_path.join(bin_dir_name);
393 // One-time synchronous check is acceptable for terminal/task initialization
394 smol::block_on(fs.metadata(&bin_path))
395 .ok()
396 .flatten()
397 .map_or(false, |meta| meta.is_dir)
398 })
399 }
400
401 fn python_activate_command(
402 &self,
403 venv_base_directory: &Path,
404 venv_settings: &VenvSettings,
405 ) -> Option<String> {
406 let venv_settings = venv_settings.as_option()?;
407 let activate_keyword = match venv_settings.activate_script {
408 terminal_settings::ActivateScript::Default => match std::env::consts::OS {
409 "windows" => ".",
410 _ => "source",
411 },
412 terminal_settings::ActivateScript::Nushell => "overlay use",
413 terminal_settings::ActivateScript::PowerShell => ".",
414 _ => "source",
415 };
416 let activate_script_name = match venv_settings.activate_script {
417 terminal_settings::ActivateScript::Default => "activate",
418 terminal_settings::ActivateScript::Csh => "activate.csh",
419 terminal_settings::ActivateScript::Fish => "activate.fish",
420 terminal_settings::ActivateScript::Nushell => "activate.nu",
421 terminal_settings::ActivateScript::PowerShell => "activate.ps1",
422 };
423 let path = venv_base_directory
424 .join(match std::env::consts::OS {
425 "windows" => "Scripts",
426 _ => "bin",
427 })
428 .join(activate_script_name)
429 .to_string_lossy()
430 .to_string();
431 let quoted = shlex::try_quote(&path).ok()?;
432 let line_ending = match std::env::consts::OS {
433 "windows" => "\r",
434 _ => "\n",
435 };
436 if smol::block_on(self.fs.metadata(path.as_ref())).is_err() {
437 return None;
438 }
439 Some(format!(
440 "{} {} ; clear{}",
441 activate_keyword, quoted, line_ending
442 ))
443 }
444
445 fn activate_python_virtual_environment(
446 &self,
447 command: String,
448 terminal_handle: &Model<Terminal>,
449 cx: &mut AppContext,
450 ) {
451 terminal_handle.update(cx, |terminal, _| terminal.input_bytes(command.into_bytes()));
452 }
453
454 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
455 &self.terminals.local_handles
456 }
457}
458
459fn wrap_for_ssh(
460 ssh_command: &SshCommand,
461 command: Option<(&String, &Vec<String>)>,
462 path: Option<&Path>,
463 env: HashMap<String, String>,
464 venv_directory: Option<&Path>,
465) -> (String, Vec<String>) {
466 let to_run = if let Some((command, args)) = command {
467 let command = Cow::Borrowed(command.as_str());
468 let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
469 iter::once(command).chain(args).join(" ")
470 } else {
471 "exec ${SHELL:-sh} -l".to_string()
472 };
473
474 let mut env_changes = String::new();
475 for (k, v) in env.iter() {
476 if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
477 env_changes.push_str(&format!("{}={} ", k, v));
478 }
479 }
480 if let Some(venv_directory) = venv_directory {
481 if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
482 env_changes.push_str(&format!("PATH={}:$PATH ", str));
483 }
484 }
485
486 let commands = if let Some(path) = path {
487 let path_string = path.to_string_lossy().to_string();
488 // shlex will wrap the command in single quotes (''), disabling ~ expansion,
489 // replace ith with something that works
490 let tilde_prefix = "~/";
491 if path.starts_with(tilde_prefix) {
492 let trimmed_path = path_string
493 .trim_start_matches("/")
494 .trim_start_matches("~")
495 .trim_start_matches("/");
496
497 format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
498 } else {
499 format!("cd {path:?}; {env_changes} {to_run}")
500 }
501 } else {
502 format!("cd; {env_changes} {to_run}")
503 };
504 let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
505
506 let program = "ssh".to_string();
507 let mut args = ssh_command.arguments.clone();
508
509 args.push("-t".to_string());
510 args.push(shell_invocation);
511 (program, args)
512}
513
514fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
515 let mut env_paths = vec![new_path.to_path_buf()];
516 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
517 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
518 env_paths.append(&mut paths);
519 }
520
521 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
522 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
523
524 Ok(())
525}
526
527#[cfg(test)]
528mod tests {
529 use collections::HashMap;
530
531 #[test]
532 fn test_add_environment_path_with_existing_path() {
533 let tmp_path = std::path::PathBuf::from("/tmp/new");
534 let mut env = HashMap::default();
535 let old_path = if cfg!(windows) {
536 "/usr/bin;/usr/local/bin"
537 } else {
538 "/usr/bin:/usr/local/bin"
539 };
540 env.insert("PATH".to_string(), old_path.to_string());
541 env.insert("OTHER".to_string(), "aaa".to_string());
542
543 super::add_environment_path(&mut env, &tmp_path).unwrap();
544 if cfg!(windows) {
545 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
546 } else {
547 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
548 }
549 assert_eq!(env.get("OTHER").unwrap(), "aaa");
550 }
551
552 #[test]
553 fn test_add_environment_path_with_empty_path() {
554 let tmp_path = std::path::PathBuf::from("/tmp/new");
555 let mut env = HashMap::default();
556 env.insert("OTHER".to_string(), "aaa".to_string());
557 let os_path = std::env::var("PATH").unwrap();
558 super::add_environment_path(&mut env, &tmp_path).unwrap();
559 if cfg!(windows) {
560 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
561 } else {
562 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
563 }
564 assert_eq!(env.get("OTHER").unwrap(), "aaa");
565 }
566}