1use crate::connected_view::ConnectedView;
2use crate::{Event, Terminal, TerminalBuilder, TerminalError};
3
4use dirs::home_dir;
5use gpui::{
6 actions, elements::*, AnyViewHandle, AppContext, Entity, ModelHandle, MutableAppContext, View,
7 ViewContext, ViewHandle,
8};
9use workspace::{Item, Workspace};
10
11use crate::TerminalSize;
12use project::{LocalWorktree, Project, ProjectPath};
13use settings::{AlternateScroll, Settings, WorkingDirectory};
14use smallvec::SmallVec;
15use std::path::{Path, PathBuf};
16
17use crate::connected_el::TerminalEl;
18
19actions!(terminal, [DeployModal]);
20
21pub fn init(cx: &mut MutableAppContext) {
22 cx.add_action(TerminalView::deploy);
23}
24
25//Make terminal view an enum, that can give you views for the error and non-error states
26//Take away all the result unwrapping in the current TerminalView by making it 'infallible'
27//Bubble up to deploy(_modal)() calls
28
29pub enum TerminalContent {
30 Connected(ViewHandle<ConnectedView>),
31 Error(ViewHandle<ErrorView>),
32}
33
34impl TerminalContent {
35 fn handle(&self) -> AnyViewHandle {
36 match self {
37 Self::Connected(handle) => handle.into(),
38 Self::Error(handle) => handle.into(),
39 }
40 }
41}
42
43pub struct TerminalView {
44 modal: bool,
45 pub content: TerminalContent,
46 associated_directory: Option<PathBuf>,
47}
48
49pub struct ErrorView {
50 error: TerminalError,
51}
52
53impl Entity for TerminalView {
54 type Event = Event;
55}
56
57impl Entity for ConnectedView {
58 type Event = Event;
59}
60
61impl Entity for ErrorView {
62 type Event = Event;
63}
64
65impl TerminalView {
66 ///Create a new Terminal in the current working directory or the user's home directory
67 pub fn deploy(
68 workspace: &mut Workspace,
69 _: &workspace::NewTerminal,
70 cx: &mut ViewContext<Workspace>,
71 ) {
72 let strategy = cx
73 .global::<Settings>()
74 .terminal_overrides
75 .working_directory
76 .clone()
77 .unwrap_or(WorkingDirectory::CurrentProjectDirectory);
78
79 let working_directory = get_working_directory(workspace, cx, strategy);
80 let view = cx.add_view(|cx| TerminalView::new(working_directory, false, cx));
81 workspace.add_item(Box::new(view), cx);
82 }
83
84 ///Create a new Terminal view. This spawns a task, a thread, and opens the TTY devices
85 pub fn new(
86 working_directory: Option<PathBuf>,
87 modal: bool,
88 cx: &mut ViewContext<Self>,
89 ) -> Self {
90 //The exact size here doesn't matter, the terminal will be resized on the first layout
91 let size_info = TerminalSize::default();
92
93 let settings = cx.global::<Settings>();
94 let shell = settings.terminal_overrides.shell.clone();
95 let envs = settings.terminal_overrides.env.clone(); //Should be short and cheap.
96
97 //TODO: move this pattern to settings
98 let scroll = settings
99 .terminal_overrides
100 .alternate_scroll
101 .as_ref()
102 .unwrap_or(
103 settings
104 .terminal_defaults
105 .alternate_scroll
106 .as_ref()
107 .unwrap_or_else(|| &AlternateScroll::On),
108 );
109
110 let content = match TerminalBuilder::new(
111 working_directory.clone(),
112 shell,
113 envs,
114 size_info,
115 settings.terminal_overrides.blinking.clone(),
116 scroll,
117 ) {
118 Ok(terminal) => {
119 let terminal = cx.add_model(|cx| terminal.subscribe(cx));
120 let view = cx.add_view(|cx| ConnectedView::from_terminal(terminal, modal, cx));
121 cx.subscribe(&view, |_this, _content, event, cx| cx.emit(*event))
122 .detach();
123 TerminalContent::Connected(view)
124 }
125 Err(error) => {
126 let view = cx.add_view(|_| ErrorView {
127 error: error.downcast::<TerminalError>().unwrap(),
128 });
129 TerminalContent::Error(view)
130 }
131 };
132 cx.focus(content.handle());
133
134 TerminalView {
135 modal,
136 content,
137 associated_directory: working_directory,
138 }
139 }
140
141 pub fn from_terminal(
142 terminal: ModelHandle<Terminal>,
143 modal: bool,
144 cx: &mut ViewContext<Self>,
145 ) -> Self {
146 let connected_view = cx.add_view(|cx| ConnectedView::from_terminal(terminal, modal, cx));
147 TerminalView {
148 modal,
149 content: TerminalContent::Connected(connected_view),
150 associated_directory: None,
151 }
152 }
153}
154
155impl View for TerminalView {
156 fn ui_name() -> &'static str {
157 "Terminal"
158 }
159
160 fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
161 let child_view = match &self.content {
162 TerminalContent::Connected(connected) => ChildView::new(connected),
163 TerminalContent::Error(error) => ChildView::new(error),
164 };
165 if self.modal {
166 let settings = cx.global::<Settings>();
167 let container_style = settings.theme.terminal.modal_container;
168 child_view.contained().with_style(container_style).boxed()
169 } else {
170 child_view.boxed()
171 }
172 }
173
174 fn on_focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
175 if cx.is_self_focused() {
176 cx.focus(self.content.handle());
177 }
178 }
179
180 fn keymap_context(&self, _: &gpui::AppContext) -> gpui::keymap::Context {
181 let mut context = Self::default_keymap_context();
182 if self.modal {
183 context.set.insert("ModalTerminal".into());
184 }
185 context
186 }
187}
188
189impl View for ErrorView {
190 fn ui_name() -> &'static str {
191 "Terminal Error"
192 }
193
194 fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
195 let settings = cx.global::<Settings>();
196 let style = TerminalEl::make_text_style(cx.font_cache(), settings);
197
198 //TODO:
199 //We want markdown style highlighting so we can format the program and working directory with ``
200 //We want a max-width of 75% with word-wrap
201 //We want to be able to select the text
202 //Want to be able to scroll if the error message is massive somehow (resiliency)
203
204 let program_text = {
205 match self.error.shell_to_string() {
206 Some(shell_txt) => format!("Shell Program: `{}`", shell_txt),
207 None => "No program specified".to_string(),
208 }
209 };
210
211 let directory_text = {
212 match self.error.directory.as_ref() {
213 Some(path) => format!("Working directory: `{}`", path.to_string_lossy()),
214 None => "No working directory specified".to_string(),
215 }
216 };
217
218 let error_text = self.error.source.to_string();
219
220 Flex::column()
221 .with_child(
222 Text::new("Failed to open the terminal.".to_string(), style.clone())
223 .contained()
224 .boxed(),
225 )
226 .with_child(Text::new(program_text, style.clone()).contained().boxed())
227 .with_child(Text::new(directory_text, style.clone()).contained().boxed())
228 .with_child(Text::new(error_text, style).contained().boxed())
229 .aligned()
230 .boxed()
231 }
232}
233
234impl Item for TerminalView {
235 fn tab_content(
236 &self,
237 _detail: Option<usize>,
238 tab_theme: &theme::Tab,
239 cx: &gpui::AppContext,
240 ) -> ElementBox {
241 let title = match &self.content {
242 TerminalContent::Connected(connected) => {
243 connected.read(cx).handle().read(cx).title.to_string()
244 }
245 TerminalContent::Error(_) => "Terminal".to_string(),
246 };
247
248 Flex::row()
249 .with_child(
250 Label::new(title, tab_theme.label.clone())
251 .aligned()
252 .contained()
253 .boxed(),
254 )
255 .boxed()
256 }
257
258 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self> {
259 //From what I can tell, there's no way to tell the current working
260 //Directory of the terminal from outside the shell. There might be
261 //solutions to this, but they are non-trivial and require more IPC
262 Some(TerminalView::new(
263 self.associated_directory.clone(),
264 false,
265 cx,
266 ))
267 }
268
269 fn project_path(&self, _cx: &gpui::AppContext) -> Option<ProjectPath> {
270 None
271 }
272
273 fn project_entry_ids(&self, _cx: &gpui::AppContext) -> SmallVec<[project::ProjectEntryId; 3]> {
274 SmallVec::new()
275 }
276
277 fn is_singleton(&self, _cx: &gpui::AppContext) -> bool {
278 false
279 }
280
281 fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {}
282
283 fn can_save(&self, _cx: &gpui::AppContext) -> bool {
284 false
285 }
286
287 fn save(
288 &mut self,
289 _project: gpui::ModelHandle<Project>,
290 _cx: &mut ViewContext<Self>,
291 ) -> gpui::Task<gpui::anyhow::Result<()>> {
292 unreachable!("save should not have been called");
293 }
294
295 fn save_as(
296 &mut self,
297 _project: gpui::ModelHandle<Project>,
298 _abs_path: std::path::PathBuf,
299 _cx: &mut ViewContext<Self>,
300 ) -> gpui::Task<gpui::anyhow::Result<()>> {
301 unreachable!("save_as should not have been called");
302 }
303
304 fn reload(
305 &mut self,
306 _project: gpui::ModelHandle<Project>,
307 _cx: &mut ViewContext<Self>,
308 ) -> gpui::Task<gpui::anyhow::Result<()>> {
309 gpui::Task::ready(Ok(()))
310 }
311
312 fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
313 if let TerminalContent::Connected(connected) = &self.content {
314 connected.read(cx).has_new_content()
315 } else {
316 false
317 }
318 }
319
320 fn has_conflict(&self, cx: &AppContext) -> bool {
321 if let TerminalContent::Connected(connected) = &self.content {
322 connected.read(cx).has_bell()
323 } else {
324 false
325 }
326 }
327
328 fn should_update_tab_on_event(event: &Self::Event) -> bool {
329 matches!(event, &Event::TitleChanged | &Event::Wakeup)
330 }
331
332 fn should_close_item_on_event(event: &Self::Event) -> bool {
333 matches!(event, &Event::CloseTerminal)
334 }
335}
336
337///Get's the working directory for the given workspace, respecting the user's settings.
338pub fn get_working_directory(
339 workspace: &Workspace,
340 cx: &AppContext,
341 strategy: WorkingDirectory,
342) -> Option<PathBuf> {
343 let res = match strategy {
344 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
345 .or_else(|| first_project_directory(workspace, cx)),
346 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
347 WorkingDirectory::AlwaysHome => None,
348 WorkingDirectory::Always { directory } => {
349 shellexpand::full(&directory) //TODO handle this better
350 .ok()
351 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
352 .filter(|dir| dir.is_dir())
353 }
354 };
355 res.or_else(home_dir)
356}
357
358///Get's the first project's home directory, or the home directory
359fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
360 workspace
361 .worktrees(cx)
362 .next()
363 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
364 .and_then(get_path_from_wt)
365}
366
367///Gets the intuitively correct working directory from the given workspace
368///If there is an active entry for this project, returns that entry's worktree root.
369///If there's no active entry but there is a worktree, returns that worktrees root.
370///If either of these roots are files, or if there are any other query failures,
371/// returns the user's home directory
372fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
373 let project = workspace.project().read(cx);
374
375 project
376 .active_entry()
377 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
378 .or_else(|| workspace.worktrees(cx).next())
379 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
380 .and_then(get_path_from_wt)
381}
382
383fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
384 wt.root_entry()
385 .filter(|re| re.is_dir())
386 .map(|_| wt.abs_path().to_path_buf())
387}
388
389#[cfg(test)]
390mod tests {
391
392 use super::*;
393 use gpui::TestAppContext;
394
395 use std::path::Path;
396
397 use crate::tests::terminal_test_context::TerminalTestContext;
398
399 ///Working directory calculation tests
400
401 ///No Worktrees in project -> home_dir()
402 #[gpui::test]
403 async fn no_worktree(cx: &mut TestAppContext) {
404 //Setup variables
405 let mut cx = TerminalTestContext::new(cx);
406 let (project, workspace) = cx.blank_workspace().await;
407 //Test
408 cx.cx.read(|cx| {
409 let workspace = workspace.read(cx);
410 let active_entry = project.read(cx).active_entry();
411
412 //Make sure enviroment is as expeted
413 assert!(active_entry.is_none());
414 assert!(workspace.worktrees(cx).next().is_none());
415
416 let res = current_project_directory(workspace, cx);
417 assert_eq!(res, None);
418 let res = first_project_directory(workspace, cx);
419 assert_eq!(res, None);
420 });
421 }
422
423 ///No active entry, but a worktree, worktree is a file -> home_dir()
424 #[gpui::test]
425 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
426 //Setup variables
427
428 let mut cx = TerminalTestContext::new(cx);
429 let (project, workspace) = cx.blank_workspace().await;
430 cx.create_file_wt(project.clone(), "/root.txt").await;
431
432 cx.cx.read(|cx| {
433 let workspace = workspace.read(cx);
434 let active_entry = project.read(cx).active_entry();
435
436 //Make sure enviroment is as expeted
437 assert!(active_entry.is_none());
438 assert!(workspace.worktrees(cx).next().is_some());
439
440 let res = current_project_directory(workspace, cx);
441 assert_eq!(res, None);
442 let res = first_project_directory(workspace, cx);
443 assert_eq!(res, None);
444 });
445 }
446
447 //No active entry, but a worktree, worktree is a folder -> worktree_folder
448 #[gpui::test]
449 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
450 //Setup variables
451 let mut cx = TerminalTestContext::new(cx);
452 let (project, workspace) = cx.blank_workspace().await;
453 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root/").await;
454
455 //Test
456 cx.cx.update(|cx| {
457 let workspace = workspace.read(cx);
458 let active_entry = project.read(cx).active_entry();
459
460 assert!(active_entry.is_none());
461 assert!(workspace.worktrees(cx).next().is_some());
462
463 let res = current_project_directory(workspace, cx);
464 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
465 let res = first_project_directory(workspace, cx);
466 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
467 });
468 }
469
470 //Active entry with a work tree, worktree is a file -> home_dir()
471 #[gpui::test]
472 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
473 //Setup variables
474 let mut cx = TerminalTestContext::new(cx);
475 let (project, workspace) = cx.blank_workspace().await;
476 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
477 let (wt2, entry2) = cx.create_file_wt(project.clone(), "/root2.txt").await;
478 cx.insert_active_entry_for(wt2, entry2, project.clone());
479
480 //Test
481 cx.cx.update(|cx| {
482 let workspace = workspace.read(cx);
483 let active_entry = project.read(cx).active_entry();
484
485 assert!(active_entry.is_some());
486
487 let res = current_project_directory(workspace, cx);
488 assert_eq!(res, None);
489 let res = first_project_directory(workspace, cx);
490 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
491 });
492 }
493
494 //Active entry, with a worktree, worktree is a folder -> worktree_folder
495 #[gpui::test]
496 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
497 //Setup variables
498 let mut cx = TerminalTestContext::new(cx);
499 let (project, workspace) = cx.blank_workspace().await;
500 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
501 let (wt2, entry2) = cx.create_folder_wt(project.clone(), "/root2/").await;
502 cx.insert_active_entry_for(wt2, entry2, project.clone());
503
504 //Test
505 cx.cx.update(|cx| {
506 let workspace = workspace.read(cx);
507 let active_entry = project.read(cx).active_entry();
508
509 assert!(active_entry.is_some());
510
511 let res = current_project_directory(workspace, cx);
512 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
513 let res = first_project_directory(workspace, cx);
514 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
515 });
516 }
517}