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 return 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().to_usize(),
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 .into_iter()
265 .map(|virtual_environment_name| abs_path.join(virtual_environment_name))
266 .find(|venv_path| {
267 self.find_worktree(&venv_path, cx)
268 .and_then(|(worktree, relative_path)| {
269 worktree.read(cx).entry_for_path(&relative_path)
270 })
271 .is_some_and(|entry| entry.is_dir())
272 })
273 }
274
275 fn python_activate_command(
276 &self,
277 venv_base_directory: &Path,
278 settings: &TerminalSettings,
279 ) -> Option<String> {
280 let venv_settings = settings.detect_venv.as_option()?;
281 let activate_script_name = match venv_settings.activate_script {
282 terminal_settings::ActivateScript::Default => "activate",
283 terminal_settings::ActivateScript::Csh => "activate.csh",
284 terminal_settings::ActivateScript::Fish => "activate.fish",
285 terminal_settings::ActivateScript::Nushell => "activate.nu",
286 };
287 let path = venv_base_directory
288 .join("bin")
289 .join(activate_script_name)
290 .to_string_lossy()
291 .to_string();
292 let quoted = shlex::try_quote(&path).ok()?;
293
294 Some(match venv_settings.activate_script {
295 terminal_settings::ActivateScript::Nushell => format!("overlay use {}\n", quoted),
296 _ => format!("source {}\n", quoted),
297 })
298 }
299
300 fn activate_python_virtual_environment(
301 &self,
302 command: String,
303 terminal_handle: &Model<Terminal>,
304 cx: &mut ModelContext<Project>,
305 ) {
306 terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
307 }
308
309 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
310 &self.terminals.local_handles
311 }
312}
313
314pub fn wrap_for_ssh(
315 ssh_command: &SshCommand,
316 command: Option<(&String, &Vec<String>)>,
317 path: Option<&Path>,
318 env: HashMap<String, String>,
319 venv_directory: Option<PathBuf>,
320) -> (String, Vec<String>) {
321 let to_run = if let Some((command, args)) = command {
322 iter::once(command)
323 .chain(args)
324 .filter_map(|arg| shlex::try_quote(arg).ok())
325 .join(" ")
326 } else {
327 "exec ${SHELL:-sh} -l".to_string()
328 };
329
330 let mut env_changes = String::new();
331 for (k, v) in env.iter() {
332 if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
333 env_changes.push_str(&format!("{}={} ", k, v));
334 }
335 }
336 if let Some(venv_directory) = venv_directory {
337 if let Some(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()).ok() {
338 env_changes.push_str(&format!("PATH={}:$PATH ", str));
339 }
340 }
341
342 let commands = if let Some(path) = path {
343 format!("cd {:?}; {} {}", path, env_changes, to_run)
344 } else {
345 format!("cd; {env_changes} {to_run}")
346 };
347 let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
348
349 let (program, mut args) = match ssh_command {
350 SshCommand::DevServer(ssh_command) => {
351 let mut args = shlex::split(&ssh_command).unwrap_or_default();
352 let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
353 (program, args)
354 }
355 SshCommand::Direct(ssh_args) => ("ssh".to_string(), ssh_args.clone()),
356 };
357
358 if command.is_none() {
359 args.push("-t".to_string())
360 }
361 args.push(shell_invocation);
362 (program, args)
363}
364
365fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
366 let mut env_paths = vec![new_path.to_path_buf()];
367 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
368 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
369 env_paths.append(&mut paths);
370 }
371
372 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
373 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
374
375 Ok(())
376}
377
378#[cfg(test)]
379mod tests {
380 use collections::HashMap;
381
382 #[test]
383 fn test_add_environment_path_with_existing_path() {
384 let tmp_path = std::path::PathBuf::from("/tmp/new");
385 let mut env = HashMap::default();
386 let old_path = if cfg!(windows) {
387 "/usr/bin;/usr/local/bin"
388 } else {
389 "/usr/bin:/usr/local/bin"
390 };
391 env.insert("PATH".to_string(), old_path.to_string());
392 env.insert("OTHER".to_string(), "aaa".to_string());
393
394 super::add_environment_path(&mut env, &tmp_path).unwrap();
395 if cfg!(windows) {
396 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
397 } else {
398 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
399 }
400 assert_eq!(env.get("OTHER").unwrap(), "aaa");
401 }
402
403 #[test]
404 fn test_add_environment_path_with_empty_path() {
405 let tmp_path = std::path::PathBuf::from("/tmp/new");
406 let mut env = HashMap::default();
407 env.insert("OTHER".to_string(), "aaa".to_string());
408 let os_path = std::env::var("PATH").unwrap();
409 super::add_environment_path(&mut env, &tmp_path).unwrap();
410 if cfg!(windows) {
411 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
412 } else {
413 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
414 }
415 assert_eq!(env.get("OTHER").unwrap(), "aaa");
416 }
417}