1use crate::persistence::TERMINAL_CONNECTION;
2use crate::terminal_view::TerminalView;
3use crate::{Event, TerminalBuilder, TerminalError};
4
5use alacritty_terminal::index::Point;
6use dirs::home_dir;
7use gpui::{
8 actions, elements::*, AnyViewHandle, AppContext, Entity, ModelHandle, MutableAppContext, Task,
9 View, ViewContext, ViewHandle, WeakViewHandle,
10};
11use util::{truncate_and_trailoff, ResultExt};
12use workspace::searchable::{SearchEvent, SearchOptions, SearchableItem, SearchableItemHandle};
13use workspace::{
14 item::{Item, ItemEvent},
15 ToolbarItemLocation, Workspace,
16};
17use workspace::{register_deserializable_item, Pane, WorkspaceId};
18
19use project::{LocalWorktree, Project, ProjectPath};
20use settings::{AlternateScroll, Settings, WorkingDirectory};
21use smallvec::SmallVec;
22use std::ops::RangeInclusive;
23use std::path::{Path, PathBuf};
24
25use crate::terminal_element::TerminalElement;
26
27actions!(terminal, [DeployModal]);
28
29pub fn init(cx: &mut MutableAppContext) {
30 cx.add_action(TerminalContainer::deploy);
31
32 register_deserializable_item::<TerminalContainer>(cx);
33}
34
35//Make terminal view an enum, that can give you views for the error and non-error states
36//Take away all the result unwrapping in the current TerminalView by making it 'infallible'
37//Bubble up to deploy(_modal)() calls
38
39pub enum TerminalContainerContent {
40 Connected(ViewHandle<TerminalView>),
41 Error(ViewHandle<ErrorView>),
42}
43
44impl TerminalContainerContent {
45 fn handle(&self) -> AnyViewHandle {
46 match self {
47 Self::Connected(handle) => handle.into(),
48 Self::Error(handle) => handle.into(),
49 }
50 }
51}
52
53pub struct TerminalContainer {
54 pub content: TerminalContainerContent,
55 associated_directory: Option<PathBuf>,
56}
57
58pub struct ErrorView {
59 error: TerminalError,
60}
61
62impl Entity for TerminalContainer {
63 type Event = Event;
64}
65
66impl Entity for ErrorView {
67 type Event = Event;
68}
69
70impl TerminalContainer {
71 ///Create a new Terminal in the current working directory or the user's home directory
72 pub fn deploy(
73 workspace: &mut Workspace,
74 _: &workspace::NewTerminal,
75 cx: &mut ViewContext<Workspace>,
76 ) {
77 let strategy = cx
78 .global::<Settings>()
79 .terminal_overrides
80 .working_directory
81 .clone()
82 .unwrap_or(WorkingDirectory::CurrentProjectDirectory);
83
84 let working_directory = get_working_directory(workspace, cx, strategy);
85 let view = cx.add_view(|cx| {
86 TerminalContainer::new(working_directory, false, workspace.database_id(), cx)
87 });
88 workspace.add_item(Box::new(view), cx);
89 }
90
91 ///Create a new Terminal view. This spawns a task, a thread, and opens the TTY devices
92 pub fn new(
93 working_directory: Option<PathBuf>,
94 modal: bool,
95 workspace_id: WorkspaceId,
96 cx: &mut ViewContext<Self>,
97 ) -> Self {
98 let settings = cx.global::<Settings>();
99 let shell = settings.terminal_overrides.shell.clone();
100 let envs = settings.terminal_overrides.env.clone(); //Should be short and cheap.
101
102 //TODO: move this pattern to settings
103 let scroll = settings
104 .terminal_overrides
105 .alternate_scroll
106 .as_ref()
107 .unwrap_or(
108 settings
109 .terminal_defaults
110 .alternate_scroll
111 .as_ref()
112 .unwrap_or_else(|| &AlternateScroll::On),
113 );
114
115 let content = match TerminalBuilder::new(
116 working_directory.clone(),
117 shell,
118 envs,
119 settings.terminal_overrides.blinking.clone(),
120 scroll,
121 cx.window_id(),
122 cx.view_id(),
123 workspace_id,
124 ) {
125 Ok(terminal) => {
126 let terminal = cx.add_model(|cx| terminal.subscribe(cx));
127 let view = cx.add_view(|cx| TerminalView::from_terminal(terminal, modal, cx));
128
129 cx.subscribe(&view, |_this, _content, event, cx| cx.emit(*event))
130 .detach();
131 TerminalContainerContent::Connected(view)
132 }
133 Err(error) => {
134 let view = cx.add_view(|_| ErrorView {
135 error: error.downcast::<TerminalError>().unwrap(),
136 });
137 TerminalContainerContent::Error(view)
138 }
139 };
140
141 TerminalContainer {
142 content,
143 associated_directory: working_directory,
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(
275 &self,
276 workspace_id: WorkspaceId,
277 cx: &mut ViewContext<Self>,
278 ) -> Option<Self> {
279 //From what I can tell, there's no way to tell the current working
280 //Directory of the terminal from outside the shell. There might be
281 //solutions to this, but they are non-trivial and require more IPC
282 Some(TerminalContainer::new(
283 self.associated_directory.clone(),
284 false,
285 workspace_id,
286 cx,
287 ))
288 }
289
290 fn project_path(&self, _cx: &gpui::AppContext) -> Option<ProjectPath> {
291 None
292 }
293
294 fn project_entry_ids(&self, _cx: &gpui::AppContext) -> SmallVec<[project::ProjectEntryId; 3]> {
295 SmallVec::new()
296 }
297
298 fn is_singleton(&self, _cx: &gpui::AppContext) -> bool {
299 false
300 }
301
302 fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {}
303
304 fn can_save(&self, _cx: &gpui::AppContext) -> bool {
305 false
306 }
307
308 fn save(
309 &mut self,
310 _project: gpui::ModelHandle<Project>,
311 _cx: &mut ViewContext<Self>,
312 ) -> gpui::Task<gpui::anyhow::Result<()>> {
313 unreachable!("save should not have been called");
314 }
315
316 fn save_as(
317 &mut self,
318 _project: gpui::ModelHandle<Project>,
319 _abs_path: std::path::PathBuf,
320 _cx: &mut ViewContext<Self>,
321 ) -> gpui::Task<gpui::anyhow::Result<()>> {
322 unreachable!("save_as should not have been called");
323 }
324
325 fn reload(
326 &mut self,
327 _project: gpui::ModelHandle<Project>,
328 _cx: &mut ViewContext<Self>,
329 ) -> gpui::Task<gpui::anyhow::Result<()>> {
330 gpui::Task::ready(Ok(()))
331 }
332
333 fn is_dirty(&self, cx: &gpui::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 has_conflict(&self, _cx: &AppContext) -> bool {
342 false
343 }
344
345 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
346 Some(Box::new(handle.clone()))
347 }
348
349 fn to_item_events(event: &Self::Event) -> Vec<ItemEvent> {
350 match event {
351 Event::BreadcrumbsChanged => vec![ItemEvent::UpdateBreadcrumbs],
352 Event::TitleChanged | Event::Wakeup => vec![ItemEvent::UpdateTab],
353 Event::CloseTerminal => vec![ItemEvent::CloseItem],
354 _ => vec![],
355 }
356 }
357
358 fn breadcrumb_location(&self) -> ToolbarItemLocation {
359 if self.connected().is_some() {
360 ToolbarItemLocation::PrimaryLeft { flex: None }
361 } else {
362 ToolbarItemLocation::Hidden
363 }
364 }
365
366 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {
367 let connected = self.connected()?;
368
369 Some(vec![Text::new(
370 connected
371 .read(cx)
372 .terminal()
373 .read(cx)
374 .breadcrumb_text
375 .to_string(),
376 theme.breadcrumbs.text.clone(),
377 )
378 .boxed()])
379 }
380
381 fn serialized_item_kind() -> Option<&'static str> {
382 Some("Terminal")
383 }
384
385 fn deserialize(
386 _project: ModelHandle<Project>,
387 _workspace: WeakViewHandle<Workspace>,
388 workspace_id: workspace::WorkspaceId,
389 item_id: workspace::ItemId,
390 cx: &mut ViewContext<Pane>,
391 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
392 let working_directory = TERMINAL_CONNECTION.get_working_directory(item_id, workspace_id);
393 Task::ready(Ok(cx.add_view(|cx| {
394 TerminalContainer::new(
395 working_directory.log_err().flatten(),
396 false,
397 workspace_id,
398 cx,
399 )
400 })))
401 }
402
403 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
404 if let Some(connected) = self.connected() {
405 let id = workspace.database_id();
406 let terminal_handle = connected.read(cx).terminal().clone();
407 terminal_handle.update(cx, |terminal, cx| terminal.set_workspace_id(id, cx))
408 }
409 }
410}
411
412impl SearchableItem for TerminalContainer {
413 type Match = RangeInclusive<Point>;
414
415 fn supported_options() -> SearchOptions {
416 SearchOptions {
417 case: false,
418 word: false,
419 regex: false,
420 }
421 }
422
423 /// Convert events raised by this item into search-relevant events (if applicable)
424 fn to_search_event(event: &Self::Event) -> Option<SearchEvent> {
425 match event {
426 Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
427 Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
428 _ => None,
429 }
430 }
431
432 /// Clear stored matches
433 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
434 if let TerminalContainerContent::Connected(connected) = &self.content {
435 let terminal = connected.read(cx).terminal().clone();
436 terminal.update(cx, |term, _| term.matches.clear())
437 }
438 }
439
440 /// Store matches returned from find_matches somewhere for rendering
441 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
442 if let TerminalContainerContent::Connected(connected) = &self.content {
443 let terminal = connected.read(cx).terminal().clone();
444 terminal.update(cx, |term, _| term.matches = matches)
445 }
446 }
447
448 /// Return the selection content to pre-load into this search
449 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
450 if let TerminalContainerContent::Connected(connected) = &self.content {
451 let terminal = connected.read(cx).terminal().clone();
452 terminal
453 .read(cx)
454 .last_content
455 .selection_text
456 .clone()
457 .unwrap_or_default()
458 } else {
459 Default::default()
460 }
461 }
462
463 /// Focus match at given index into the Vec of matches
464 fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
465 if let TerminalContainerContent::Connected(connected) = &self.content {
466 let terminal = connected.read(cx).terminal().clone();
467 terminal.update(cx, |term, _| term.activate_match(index));
468 cx.notify();
469 }
470 }
471
472 /// Get all of the matches for this query, should be done on the background
473 fn find_matches(
474 &mut self,
475 query: project::search::SearchQuery,
476 cx: &mut ViewContext<Self>,
477 ) -> Task<Vec<Self::Match>> {
478 if let TerminalContainerContent::Connected(connected) = &self.content {
479 let terminal = connected.read(cx).terminal().clone();
480 terminal.update(cx, |term, cx| term.find_matches(query, cx))
481 } else {
482 Task::ready(Vec::new())
483 }
484 }
485
486 /// Reports back to the search toolbar what the active match should be (the selection)
487 fn active_match_index(
488 &mut self,
489 matches: Vec<Self::Match>,
490 cx: &mut ViewContext<Self>,
491 ) -> Option<usize> {
492 let connected = self.connected();
493 // Selection head might have a value if there's a selection that isn't
494 // associated with a match. Therefore, if there are no matches, we should
495 // report None, no matter the state of the terminal
496 let res = if matches.len() > 0 && connected.is_some() {
497 if let Some(selection_head) = connected
498 .unwrap()
499 .read(cx)
500 .terminal()
501 .read(cx)
502 .selection_head
503 {
504 // If selection head is contained in a match. Return that match
505 if let Some(ix) = matches
506 .iter()
507 .enumerate()
508 .find(|(_, search_match)| {
509 search_match.contains(&selection_head)
510 || search_match.start() > &selection_head
511 })
512 .map(|(ix, _)| ix)
513 {
514 Some(ix)
515 } else {
516 // If no selection after selection head, return the last match
517 Some(matches.len().saturating_sub(1))
518 }
519 } else {
520 // Matches found but no active selection, return the first last one (closest to cursor)
521 Some(matches.len().saturating_sub(1))
522 }
523 } else {
524 None
525 };
526
527 res
528 }
529}
530
531///Get's the working directory for the given workspace, respecting the user's settings.
532pub fn get_working_directory(
533 workspace: &Workspace,
534 cx: &AppContext,
535 strategy: WorkingDirectory,
536) -> Option<PathBuf> {
537 let res = match strategy {
538 WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
539 .or_else(|| first_project_directory(workspace, cx)),
540 WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
541 WorkingDirectory::AlwaysHome => None,
542 WorkingDirectory::Always { directory } => {
543 shellexpand::full(&directory) //TODO handle this better
544 .ok()
545 .map(|dir| Path::new(&dir.to_string()).to_path_buf())
546 .filter(|dir| dir.is_dir())
547 }
548 };
549 res.or_else(home_dir)
550}
551
552///Get's the first project's home directory, or the home directory
553fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
554 workspace
555 .worktrees(cx)
556 .next()
557 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
558 .and_then(get_path_from_wt)
559}
560
561///Gets the intuitively correct working directory from the given workspace
562///If there is an active entry for this project, returns that entry's worktree root.
563///If there's no active entry but there is a worktree, returns that worktrees root.
564///If either of these roots are files, or if there are any other query failures,
565/// returns the user's home directory
566fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
567 let project = workspace.project().read(cx);
568
569 project
570 .active_entry()
571 .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
572 .or_else(|| workspace.worktrees(cx).next())
573 .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
574 .and_then(get_path_from_wt)
575}
576
577fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
578 wt.root_entry()
579 .filter(|re| re.is_dir())
580 .map(|_| wt.abs_path().to_path_buf())
581}
582
583#[cfg(test)]
584mod tests {
585
586 use super::*;
587 use gpui::TestAppContext;
588
589 use std::path::Path;
590
591 use crate::tests::terminal_test_context::TerminalTestContext;
592
593 ///Working directory calculation tests
594
595 ///No Worktrees in project -> home_dir()
596 #[gpui::test]
597 async fn no_worktree(cx: &mut TestAppContext) {
598 //Setup variables
599 let mut cx = TerminalTestContext::new(cx);
600 let (project, workspace) = cx.blank_workspace().await;
601 //Test
602 cx.cx.read(|cx| {
603 let workspace = workspace.read(cx);
604 let active_entry = project.read(cx).active_entry();
605
606 //Make sure enviroment is as expeted
607 assert!(active_entry.is_none());
608 assert!(workspace.worktrees(cx).next().is_none());
609
610 let res = current_project_directory(workspace, cx);
611 assert_eq!(res, None);
612 let res = first_project_directory(workspace, cx);
613 assert_eq!(res, None);
614 });
615 }
616
617 ///No active entry, but a worktree, worktree is a file -> home_dir()
618 #[gpui::test]
619 async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
620 //Setup variables
621
622 let mut cx = TerminalTestContext::new(cx);
623 let (project, workspace) = cx.blank_workspace().await;
624 cx.create_file_wt(project.clone(), "/root.txt").await;
625
626 cx.cx.read(|cx| {
627 let workspace = workspace.read(cx);
628 let active_entry = project.read(cx).active_entry();
629
630 //Make sure enviroment is as expeted
631 assert!(active_entry.is_none());
632 assert!(workspace.worktrees(cx).next().is_some());
633
634 let res = current_project_directory(workspace, cx);
635 assert_eq!(res, None);
636 let res = first_project_directory(workspace, cx);
637 assert_eq!(res, None);
638 });
639 }
640
641 //No active entry, but a worktree, worktree is a folder -> worktree_folder
642 #[gpui::test]
643 async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
644 //Setup variables
645 let mut cx = TerminalTestContext::new(cx);
646 let (project, workspace) = cx.blank_workspace().await;
647 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root/").await;
648
649 //Test
650 cx.cx.update(|cx| {
651 let workspace = workspace.read(cx);
652 let active_entry = project.read(cx).active_entry();
653
654 assert!(active_entry.is_none());
655 assert!(workspace.worktrees(cx).next().is_some());
656
657 let res = current_project_directory(workspace, cx);
658 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
659 let res = first_project_directory(workspace, cx);
660 assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
661 });
662 }
663
664 //Active entry with a work tree, worktree is a file -> home_dir()
665 #[gpui::test]
666 async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
667 //Setup variables
668 let mut cx = TerminalTestContext::new(cx);
669 let (project, workspace) = cx.blank_workspace().await;
670 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
671 let (wt2, entry2) = cx.create_file_wt(project.clone(), "/root2.txt").await;
672 cx.insert_active_entry_for(wt2, entry2, project.clone());
673
674 //Test
675 cx.cx.update(|cx| {
676 let workspace = workspace.read(cx);
677 let active_entry = project.read(cx).active_entry();
678
679 assert!(active_entry.is_some());
680
681 let res = current_project_directory(workspace, cx);
682 assert_eq!(res, None);
683 let res = first_project_directory(workspace, cx);
684 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
685 });
686 }
687
688 //Active entry, with a worktree, worktree is a folder -> worktree_folder
689 #[gpui::test]
690 async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
691 //Setup variables
692 let mut cx = TerminalTestContext::new(cx);
693 let (project, workspace) = cx.blank_workspace().await;
694 let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
695 let (wt2, entry2) = cx.create_folder_wt(project.clone(), "/root2/").await;
696 cx.insert_active_entry_for(wt2, entry2, project.clone());
697
698 //Test
699 cx.cx.update(|cx| {
700 let workspace = workspace.read(cx);
701 let active_entry = project.read(cx).active_entry();
702
703 assert!(active_entry.is_some());
704
705 let res = current_project_directory(workspace, cx);
706 assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
707 let res = first_project_directory(workspace, cx);
708 assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
709 });
710 }
711}