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