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