1use crate::Project;
2use collections::HashMap;
3use gpui::{AnyWindowHandle, Context, Entity, Model, ModelContext, WeakModel};
4use settings::Settings;
5use smol::channel::bounded;
6use std::path::{Path, PathBuf};
7use terminal::{
8 terminal_settings::{self, Shell, TerminalSettings, VenvSettingsContent},
9 SpawnTask, TaskState, TaskStatus, Terminal, TerminalBuilder,
10};
11use util::ResultExt;
12
13// #[cfg(target_os = "macos")]
14// use std::os::unix::ffi::OsStrExt;
15
16pub struct Terminals {
17 pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
18}
19
20impl Project {
21 pub fn create_terminal(
22 &mut self,
23 working_directory: Option<PathBuf>,
24 spawn_task: Option<SpawnTask>,
25 window: AnyWindowHandle,
26 cx: &mut ModelContext<Self>,
27 ) -> anyhow::Result<Model<Terminal>> {
28 anyhow::ensure!(
29 !self.is_remote(),
30 "creating terminals as a guest is not supported yet"
31 );
32
33 let is_terminal = spawn_task.is_none();
34 let settings = TerminalSettings::get_global(cx);
35 let python_settings = settings.detect_venv.clone();
36 let (completion_tx, completion_rx) = bounded(1);
37
38 let mut env = settings.env.clone();
39 // Alacritty uses parent project's working directory when no working directory is provided
40 // https://github.com/alacritty/alacritty/blob/fd1a3cc79192d1d03839f0fd8c72e1f8d0fce42e/extra/man/alacritty.5.scd?plain=1#L47-L52
41
42 let venv_base_directory = working_directory
43 .as_deref()
44 .unwrap_or_else(|| Path::new(""));
45
46 let (spawn_task, shell) = if let Some(spawn_task) = spawn_task {
47 env.extend(spawn_task.env);
48 // Activate minimal Python virtual environment
49 if let Some(python_settings) = &python_settings.as_option() {
50 self.set_python_venv_path_for_tasks(python_settings, venv_base_directory, &mut env);
51 }
52 (
53 Some(TaskState {
54 id: spawn_task.id,
55 full_label: spawn_task.full_label,
56 label: spawn_task.label,
57 status: TaskStatus::Running,
58 completion_rx,
59 }),
60 Shell::WithArguments {
61 program: spawn_task.command,
62 args: spawn_task.args,
63 },
64 )
65 } else {
66 (None, settings.shell.clone())
67 };
68
69 let terminal = TerminalBuilder::new(
70 working_directory.clone(),
71 spawn_task,
72 shell,
73 env,
74 Some(settings.blinking.clone()),
75 settings.alternate_scroll,
76 settings.max_scroll_history_lines,
77 window,
78 completion_tx,
79 )
80 .map(|builder| {
81 let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
82
83 self.terminals
84 .local_handles
85 .push(terminal_handle.downgrade());
86
87 let id = terminal_handle.entity_id();
88 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
89 let handles = &mut project.terminals.local_handles;
90
91 if let Some(index) = handles
92 .iter()
93 .position(|terminal| terminal.entity_id() == id)
94 {
95 handles.remove(index);
96 cx.notify();
97 }
98 })
99 .detach();
100
101 // if the terminal is not a task, activate full Python virtual environment
102 if is_terminal {
103 if let Some(python_settings) = &python_settings.as_option() {
104 if let Some(activate_script_path) =
105 self.find_activate_script_path(python_settings, venv_base_directory)
106 {
107 self.activate_python_virtual_environment(
108 Project::get_activate_command(python_settings),
109 activate_script_path,
110 &terminal_handle,
111 cx,
112 );
113 }
114 }
115 }
116 terminal_handle
117 });
118
119 terminal
120 }
121
122 pub fn find_activate_script_path(
123 &mut self,
124 settings: &VenvSettingsContent,
125 venv_base_directory: &Path,
126 ) -> Option<PathBuf> {
127 let activate_script_name = match settings.activate_script {
128 terminal_settings::ActivateScript::Default => "activate",
129 terminal_settings::ActivateScript::Csh => "activate.csh",
130 terminal_settings::ActivateScript::Fish => "activate.fish",
131 terminal_settings::ActivateScript::Nushell => "activate.nu",
132 };
133
134 settings
135 .directories
136 .into_iter()
137 .find_map(|virtual_environment_name| {
138 let path = venv_base_directory
139 .join(virtual_environment_name)
140 .join("bin")
141 .join(activate_script_name);
142 path.exists().then_some(path)
143 })
144 }
145
146 pub fn set_python_venv_path_for_tasks(
147 &mut self,
148 settings: &VenvSettingsContent,
149 venv_base_directory: &Path,
150 env: &mut HashMap<String, String>,
151 ) {
152 let activate_path = settings
153 .directories
154 .into_iter()
155 .find_map(|virtual_environment_name| {
156 let path = venv_base_directory.join(virtual_environment_name);
157 path.exists().then_some(path)
158 });
159
160 if let Some(path) = activate_path {
161 // Some tools use VIRTUAL_ENV to detect the virtual environment
162 env.insert(
163 "VIRTUAL_ENV".to_string(),
164 path.to_string_lossy().to_string(),
165 );
166
167 let path_bin = path.join("bin");
168 // We need to set the PATH to include the virtual environment's bin directory
169 if let Some(paths) = std::env::var_os("PATH") {
170 let paths = std::iter::once(path_bin).chain(std::env::split_paths(&paths));
171 if let Some(new_path) = std::env::join_paths(paths).log_err() {
172 env.insert("PATH".to_string(), new_path.to_string_lossy().to_string());
173 }
174 } else {
175 env.insert(
176 "PATH".to_string(),
177 path.join("bin").to_string_lossy().to_string(),
178 );
179 }
180 }
181 }
182
183 fn get_activate_command(settings: &VenvSettingsContent) -> &'static str {
184 match settings.activate_script {
185 terminal_settings::ActivateScript::Nushell => "overlay use",
186 _ => "source",
187 }
188 }
189
190 fn activate_python_virtual_environment(
191 &mut self,
192 activate_command: &'static str,
193 activate_script: PathBuf,
194 terminal_handle: &Model<Terminal>,
195 cx: &mut ModelContext<Project>,
196 ) {
197 // Paths are not strings so we need to jump through some hoops to format the command without `format!`
198 let mut command = Vec::from(activate_command.as_bytes());
199 command.push(b' ');
200 // Wrapping path in double quotes to catch spaces in folder name
201 command.extend_from_slice(b"\"");
202 command.extend_from_slice(activate_script.as_os_str().as_encoded_bytes());
203 command.extend_from_slice(b"\"");
204 command.push(b'\n');
205
206 terminal_handle.update(cx, |this, _| this.input_bytes(command));
207 }
208
209 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
210 &self.terminals.local_handles
211 }
212}
213
214// TODO: Add a few tests for adding and removing terminal tabs