1use crate::Project;
2use anyhow::Context as _;
3use collections::HashMap;
4use gpui::{AnyWindowHandle, AppContext, Context, Entity, Model, ModelContext, WeakModel};
5use itertools::Itertools;
6use settings::{Settings, SettingsLocation};
7use smol::channel::bounded;
8use std::{
9 borrow::Cow,
10 env::{self},
11 iter,
12 path::{Path, PathBuf},
13};
14use task::{Shell, SpawnInTerminal};
15use terminal::{
16 terminal_settings::{self, TerminalSettings},
17 TaskState, TaskStatus, Terminal, TerminalBuilder,
18};
19use util::ResultExt;
20
21// #[cfg(target_os = "macos")]
22// use std::os::unix::ffi::OsStrExt;
23
24pub struct Terminals {
25 pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
26}
27
28/// Terminals are opened either for the users shell, or to run a task.
29#[allow(clippy::large_enum_variant)]
30#[derive(Debug)]
31pub enum TerminalKind {
32 /// Run a shell at the given path (or $HOME if None)
33 Shell(Option<PathBuf>),
34 /// Run a task.
35 Task(SpawnInTerminal),
36}
37
38/// SshCommand describes how to connect to a remote server
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum SshCommand {
41 /// DevServers give a string from the user
42 DevServer(String),
43 /// Direct ssh has a list of arguments to pass to ssh
44 Direct(Vec<String>),
45}
46
47impl Project {
48 pub fn active_project_directory(&self, cx: &AppContext) -> Option<PathBuf> {
49 let worktree = self
50 .active_entry()
51 .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
52 .or_else(|| self.worktrees(cx).next())?;
53 let worktree = worktree.read(cx);
54 if !worktree.root_entry()?.is_dir() {
55 return None;
56 }
57 Some(worktree.abs_path().to_path_buf())
58 }
59
60 pub fn first_project_directory(&self, cx: &AppContext) -> Option<PathBuf> {
61 let worktree = self.worktrees(cx).next()?;
62 let worktree = worktree.read(cx);
63 if worktree.root_entry()?.is_dir() {
64 Some(worktree.abs_path().to_path_buf())
65 } else {
66 None
67 }
68 }
69
70 fn ssh_command(&self, cx: &AppContext) -> Option<SshCommand> {
71 if let Some(args) = self
72 .ssh_client
73 .as_ref()
74 .and_then(|session| session.read(cx).ssh_args())
75 {
76 return Some(SshCommand::Direct(args));
77 }
78
79 let dev_server_project_id = self.dev_server_project_id()?;
80 let projects_store = dev_server_projects::Store::global(cx).read(cx);
81 let ssh_command = projects_store
82 .dev_server_for_project(dev_server_project_id)?
83 .ssh_connection_string
84 .as_ref()?
85 .to_string();
86 Some(SshCommand::DevServer(ssh_command))
87 }
88
89 pub fn create_terminal(
90 &mut self,
91 kind: TerminalKind,
92 window: AnyWindowHandle,
93 cx: &mut ModelContext<Self>,
94 ) -> anyhow::Result<Model<Terminal>> {
95 let path = match &kind {
96 TerminalKind::Shell(path) => path.as_ref().map(|path| path.to_path_buf()),
97 TerminalKind::Task(spawn_task) => {
98 if let Some(cwd) = &spawn_task.cwd {
99 Some(cwd.clone())
100 } else {
101 self.active_project_directory(cx)
102 }
103 }
104 };
105 let ssh_command = self.ssh_command(cx);
106
107 let mut settings_location = None;
108 if let Some(path) = path.as_ref() {
109 if let Some((worktree, _)) = self.find_worktree(path, cx) {
110 settings_location = Some(SettingsLocation {
111 worktree_id: worktree.read(cx).id(),
112 path,
113 });
114 }
115 }
116 let settings = TerminalSettings::get(settings_location, cx);
117
118 let (completion_tx, completion_rx) = bounded(1);
119
120 // Start with the environment that we might have inherited from the Zed CLI.
121 let mut env = self
122 .environment
123 .read(cx)
124 .get_cli_environment()
125 .unwrap_or_default();
126 // Then extend it with the explicit env variables from the settings, so they take
127 // precedence.
128 env.extend(settings.env.clone());
129
130 let local_path = if ssh_command.is_none() {
131 path.clone()
132 } else {
133 None
134 };
135 let python_venv_directory = path
136 .as_ref()
137 .and_then(|path| self.python_venv_directory(path, settings, cx));
138 let mut python_venv_activate_command = None;
139
140 let (spawn_task, shell) = match kind {
141 TerminalKind::Shell(_) => {
142 if let Some(python_venv_directory) = python_venv_directory {
143 python_venv_activate_command =
144 self.python_activate_command(&python_venv_directory, settings);
145 }
146
147 match &ssh_command {
148 Some(ssh_command) => {
149 log::debug!("Connecting to a remote server: {ssh_command:?}");
150
151 // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
152 // to properly display colors.
153 // We do not have the luxury of assuming the host has it installed,
154 // so we set it to a default that does not break the highlighting via ssh.
155 env.entry("TERM".to_string())
156 .or_insert_with(|| "xterm-256color".to_string());
157
158 let (program, args) =
159 wrap_for_ssh(ssh_command, None, path.as_deref(), env, None);
160 env = HashMap::default();
161 (None, Shell::WithArguments { program, args })
162 }
163 None => (None, settings.shell.clone()),
164 }
165 }
166 TerminalKind::Task(spawn_task) => {
167 let task_state = Some(TaskState {
168 id: spawn_task.id,
169 full_label: spawn_task.full_label,
170 label: spawn_task.label,
171 command_label: spawn_task.command_label,
172 hide: spawn_task.hide,
173 status: TaskStatus::Running,
174 completion_rx,
175 });
176
177 env.extend(spawn_task.env);
178
179 if let Some(venv_path) = &python_venv_directory {
180 env.insert(
181 "VIRTUAL_ENV".to_string(),
182 venv_path.to_string_lossy().to_string(),
183 );
184 }
185
186 match &ssh_command {
187 Some(ssh_command) => {
188 log::debug!("Connecting to a remote server: {ssh_command:?}");
189 env.entry("TERM".to_string())
190 .or_insert_with(|| "xterm-256color".to_string());
191 let (program, args) = wrap_for_ssh(
192 ssh_command,
193 Some((&spawn_task.command, &spawn_task.args)),
194 path.as_deref(),
195 env,
196 python_venv_directory,
197 );
198 env = HashMap::default();
199 (task_state, Shell::WithArguments { program, args })
200 }
201 None => {
202 if let Some(venv_path) = &python_venv_directory {
203 add_environment_path(&mut env, &venv_path.join("bin")).log_err();
204 }
205
206 (
207 task_state,
208 Shell::WithArguments {
209 program: spawn_task.command,
210 args: spawn_task.args,
211 },
212 )
213 }
214 }
215 }
216 };
217
218 let terminal = TerminalBuilder::new(
219 local_path,
220 spawn_task,
221 shell,
222 env,
223 settings.cursor_shape.unwrap_or_default(),
224 settings.alternate_scroll,
225 settings.max_scroll_history_lines,
226 window,
227 completion_tx,
228 cx,
229 )
230 .map(|builder| {
231 let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
232
233 self.terminals
234 .local_handles
235 .push(terminal_handle.downgrade());
236
237 let id = terminal_handle.entity_id();
238 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
239 let handles = &mut project.terminals.local_handles;
240
241 if let Some(index) = handles
242 .iter()
243 .position(|terminal| terminal.entity_id() == id)
244 {
245 handles.remove(index);
246 cx.notify();
247 }
248 })
249 .detach();
250
251 if let Some(activate_command) = python_venv_activate_command {
252 self.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
253 }
254 terminal_handle
255 });
256
257 terminal
258 }
259
260 pub fn python_venv_directory(
261 &self,
262 abs_path: &Path,
263 settings: &TerminalSettings,
264 cx: &AppContext,
265 ) -> Option<PathBuf> {
266 let venv_settings = settings.detect_venv.as_option()?;
267 let bin_dir_name = match std::env::consts::OS {
268 "windows" => "Scripts",
269 _ => "bin",
270 };
271 venv_settings
272 .directories
273 .iter()
274 .map(|virtual_environment_name| abs_path.join(virtual_environment_name))
275 .find(|venv_path| {
276 let bin_path = venv_path.join(bin_dir_name);
277 self.find_worktree(&bin_path, cx)
278 .and_then(|(worktree, relative_path)| {
279 worktree.read(cx).entry_for_path(&relative_path)
280 })
281 .is_some_and(|entry| entry.is_dir())
282 })
283 }
284
285 fn python_activate_command(
286 &self,
287 venv_base_directory: &Path,
288 settings: &TerminalSettings,
289 ) -> Option<String> {
290 let venv_settings = settings.detect_venv.as_option()?;
291 let activate_keyword = match venv_settings.activate_script {
292 terminal_settings::ActivateScript::Default => match std::env::consts::OS {
293 "windows" => ".",
294 _ => "source",
295 },
296 terminal_settings::ActivateScript::Nushell => "overlay use",
297 terminal_settings::ActivateScript::PowerShell => ".",
298 _ => "source",
299 };
300 let activate_script_name = match venv_settings.activate_script {
301 terminal_settings::ActivateScript::Default => "activate",
302 terminal_settings::ActivateScript::Csh => "activate.csh",
303 terminal_settings::ActivateScript::Fish => "activate.fish",
304 terminal_settings::ActivateScript::Nushell => "activate.nu",
305 terminal_settings::ActivateScript::PowerShell => "activate.ps1",
306 };
307 let path = venv_base_directory
308 .join(match std::env::consts::OS {
309 "windows" => "Scripts",
310 _ => "bin",
311 })
312 .join(activate_script_name)
313 .to_string_lossy()
314 .to_string();
315 let quoted = shlex::try_quote(&path).ok()?;
316 let line_ending = match std::env::consts::OS {
317 "windows" => "\r",
318 _ => "\n",
319 };
320 Some(format!("{} {}{}", activate_keyword, quoted, line_ending))
321 }
322
323 fn activate_python_virtual_environment(
324 &self,
325 command: String,
326 terminal_handle: &Model<Terminal>,
327 cx: &mut ModelContext<Project>,
328 ) {
329 terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
330 }
331
332 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
333 &self.terminals.local_handles
334 }
335}
336
337pub fn wrap_for_ssh(
338 ssh_command: &SshCommand,
339 command: Option<(&String, &Vec<String>)>,
340 path: Option<&Path>,
341 env: HashMap<String, String>,
342 venv_directory: Option<PathBuf>,
343) -> (String, Vec<String>) {
344 let to_run = if let Some((command, args)) = command {
345 let command = Cow::Borrowed(command.as_str());
346 let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
347 iter::once(command).chain(args).join(" ")
348 } else {
349 "exec ${SHELL:-sh} -l".to_string()
350 };
351
352 let mut env_changes = String::new();
353 for (k, v) in env.iter() {
354 if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
355 env_changes.push_str(&format!("{}={} ", k, v));
356 }
357 }
358 if let Some(venv_directory) = venv_directory {
359 if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
360 env_changes.push_str(&format!("PATH={}:$PATH ", str));
361 }
362 }
363
364 let commands = if let Some(path) = path {
365 let path_string = path.to_string_lossy().to_string();
366 // shlex will wrap the command in single quotes (''), disabling ~ expansion,
367 // replace ith with something that works
368 let tilde_prefix = "~/";
369 if path.starts_with(tilde_prefix) {
370 let trimmed_path = path_string
371 .trim_start_matches("/")
372 .trim_start_matches("~")
373 .trim_start_matches("/");
374
375 format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
376 } else {
377 format!("cd {path:?}; {env_changes} {to_run}")
378 }
379 } else {
380 format!("cd; {env_changes} {to_run}")
381 };
382 let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
383
384 let (program, mut args) = match ssh_command {
385 SshCommand::DevServer(ssh_command) => {
386 let mut args = shlex::split(ssh_command).unwrap_or_default();
387 let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
388 (program, args)
389 }
390 SshCommand::Direct(ssh_args) => ("ssh".to_string(), ssh_args.clone()),
391 };
392
393 args.push("-t".to_string());
394 args.push(shell_invocation);
395 (program, args)
396}
397
398fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
399 let mut env_paths = vec![new_path.to_path_buf()];
400 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
401 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
402 env_paths.append(&mut paths);
403 }
404
405 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
406 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
407
408 Ok(())
409}
410
411#[cfg(test)]
412mod tests {
413 use collections::HashMap;
414
415 #[test]
416 fn test_add_environment_path_with_existing_path() {
417 let tmp_path = std::path::PathBuf::from("/tmp/new");
418 let mut env = HashMap::default();
419 let old_path = if cfg!(windows) {
420 "/usr/bin;/usr/local/bin"
421 } else {
422 "/usr/bin:/usr/local/bin"
423 };
424 env.insert("PATH".to_string(), old_path.to_string());
425 env.insert("OTHER".to_string(), "aaa".to_string());
426
427 super::add_environment_path(&mut env, &tmp_path).unwrap();
428 if cfg!(windows) {
429 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
430 } else {
431 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
432 }
433 assert_eq!(env.get("OTHER").unwrap(), "aaa");
434 }
435
436 #[test]
437 fn test_add_environment_path_with_empty_path() {
438 let tmp_path = std::path::PathBuf::from("/tmp/new");
439 let mut env = HashMap::default();
440 env.insert("OTHER".to_string(), "aaa".to_string());
441 let os_path = std::env::var("PATH").unwrap();
442 super::add_environment_path(&mut env, &tmp_path).unwrap();
443 if cfg!(windows) {
444 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
445 } else {
446 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
447 }
448 assert_eq!(env.get("OTHER").unwrap(), "aaa");
449 }
450}