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