terminal_container_view.rs

  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 crate::TerminalSize;
 15use project::{LocalWorktree, Project, ProjectPath};
 16use settings::{AlternateScroll, Settings, WorkingDirectory};
 17use smallvec::SmallVec;
 18use std::ops::RangeInclusive;
 19use std::path::{Path, PathBuf};
 20
 21use crate::terminal_element::TerminalElement;
 22
 23actions!(terminal, [DeployModal]);
 24
 25pub fn init(cx: &mut MutableAppContext) {
 26    cx.add_action(TerminalContainer::deploy);
 27}
 28
 29//Make terminal view an enum, that can give you views for the error and non-error states
 30//Take away all the result unwrapping in the current TerminalView by making it 'infallible'
 31//Bubble up to deploy(_modal)() calls
 32
 33pub enum TerminalContainerContent {
 34    Connected(ViewHandle<TerminalView>),
 35    Error(ViewHandle<ErrorView>),
 36}
 37
 38impl TerminalContainerContent {
 39    fn handle(&self) -> AnyViewHandle {
 40        match self {
 41            Self::Connected(handle) => handle.into(),
 42            Self::Error(handle) => handle.into(),
 43        }
 44    }
 45}
 46
 47pub struct TerminalContainer {
 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            cx.window_id(),
117        ) {
118            Ok(terminal) => {
119                let terminal = cx.add_model(|cx| terminal.subscribe(cx));
120                let view = cx.add_view(|cx| TerminalView::from_terminal(terminal, modal, cx));
121                cx.subscribe(&view, |_this, _content, event, cx| cx.emit(*event))
122                    .detach();
123                TerminalContainerContent::Connected(view)
124            }
125            Err(error) => {
126                let view = cx.add_view(|_| ErrorView {
127                    error: error.downcast::<TerminalError>().unwrap(),
128                });
129                TerminalContainerContent::Error(view)
130            }
131        };
132        cx.focus(content.handle());
133
134        TerminalContainer {
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            content: TerminalContainerContent::Connected(connected_view),
148            associated_directory: None,
149        }
150    }
151
152    fn connected(&self) -> Option<ViewHandle<TerminalView>> {
153        match &self.content {
154            TerminalContainerContent::Connected(vh) => Some(vh.clone()),
155            TerminalContainerContent::Error(_) => None,
156        }
157    }
158}
159
160impl View for TerminalContainer {
161    fn ui_name() -> &'static str {
162        "Terminal"
163    }
164
165    fn render(&mut self, _cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
166        match &self.content {
167            TerminalContainerContent::Connected(connected) => ChildView::new(connected),
168            TerminalContainerContent::Error(error) => ChildView::new(error),
169        }
170        .boxed()
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
180impl View for ErrorView {
181    fn ui_name() -> &'static str {
182        "Terminal Error"
183    }
184
185    fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> ElementBox {
186        let settings = cx.global::<Settings>();
187        let style = TerminalElement::make_text_style(cx.font_cache(), settings);
188
189        //TODO:
190        //We want markdown style highlighting so we can format the program and working directory with ``
191        //We want a max-width of 75% with word-wrap
192        //We want to be able to select the text
193        //Want to be able to scroll if the error message is massive somehow (resiliency)
194
195        let program_text = {
196            match self.error.shell_to_string() {
197                Some(shell_txt) => format!("Shell Program: `{}`", shell_txt),
198                None => "No program specified".to_string(),
199            }
200        };
201
202        let directory_text = {
203            match self.error.directory.as_ref() {
204                Some(path) => format!("Working directory: `{}`", path.to_string_lossy()),
205                None => "No working directory specified".to_string(),
206            }
207        };
208
209        let error_text = self.error.source.to_string();
210
211        Flex::column()
212            .with_child(
213                Text::new("Failed to open the terminal.".to_string(), style.clone())
214                    .contained()
215                    .boxed(),
216            )
217            .with_child(Text::new(program_text, style.clone()).contained().boxed())
218            .with_child(Text::new(directory_text, style.clone()).contained().boxed())
219            .with_child(Text::new(error_text, style).contained().boxed())
220            .aligned()
221            .boxed()
222    }
223}
224
225impl Item for TerminalContainer {
226    fn tab_content(
227        &self,
228        _detail: Option<usize>,
229        tab_theme: &theme::Tab,
230        cx: &gpui::AppContext,
231    ) -> ElementBox {
232        let title = match &self.content {
233            TerminalContainerContent::Connected(connected) => connected
234                .read(cx)
235                .handle()
236                .read(cx)
237                .foreground_process_info
238                .as_ref()
239                .map(|fpi| {
240                    format!(
241                        "{}{}",
242                        truncate_and_trailoff(
243                            &fpi.cwd
244                                .file_name()
245                                .map(|name| name.to_string_lossy().to_string())
246                                .unwrap_or_default(),
247                            25
248                        ),
249                        truncate_and_trailoff(
250                            &{
251                                format!(
252                                    "{}{}",
253                                    fpi.name,
254                                    if fpi.argv.len() >= 1 {
255                                        format!(" {}", (&fpi.argv[1..]).join(" "))
256                                    } else {
257                                        "".to_string()
258                                    }
259                                )
260                            },
261                            25
262                        )
263                    )
264                })
265                .unwrap_or_else(|| "Terminal".to_string()),
266            TerminalContainerContent::Error(_) => "Terminal".to_string(),
267        };
268
269        Flex::row()
270            .with_child(
271                Label::new(title, tab_theme.label.clone())
272                    .aligned()
273                    .contained()
274                    .boxed(),
275            )
276            .boxed()
277    }
278
279    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self> {
280        //From what I can tell, there's no  way to tell the current working
281        //Directory of the terminal from outside the shell. There might be
282        //solutions to this, but they are non-trivial and require more IPC
283        Some(TerminalContainer::new(
284            self.associated_directory.clone(),
285            false,
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
382impl SearchableItem for TerminalContainer {
383    type Match = RangeInclusive<Point>;
384
385    fn supported_options() -> SearchOptions {
386        SearchOptions {
387            case: false,
388            word: false,
389            regex: false,
390        }
391    }
392
393    /// Convert events raised by this item into search-relevant events (if applicable)
394    fn to_search_event(event: &Self::Event) -> Option<SearchEvent> {
395        match event {
396            Event::Wakeup => Some(SearchEvent::MatchesInvalidated),
397            Event::SelectionsChanged => Some(SearchEvent::ActiveMatchChanged),
398            _ => None,
399        }
400    }
401
402    /// Clear stored matches
403    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
404        if let TerminalContainerContent::Connected(connected) = &self.content {
405            let terminal = connected.read(cx).terminal().clone();
406            terminal.update(cx, |term, _| term.matches.clear())
407        }
408    }
409
410    /// Store matches returned from find_matches somewhere for rendering
411    fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
412        if let TerminalContainerContent::Connected(connected) = &self.content {
413            let terminal = connected.read(cx).terminal().clone();
414            terminal.update(cx, |term, _| term.matches = matches)
415        }
416    }
417
418    /// Return the selection content to pre-load into this search
419    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
420        if let TerminalContainerContent::Connected(connected) = &self.content {
421            let terminal = connected.read(cx).terminal().clone();
422            terminal
423                .read(cx)
424                .last_content
425                .selection_text
426                .clone()
427                .unwrap_or_default()
428        } else {
429            Default::default()
430        }
431    }
432
433    /// Focus match at given index into the Vec of matches
434    fn activate_match(&mut self, index: usize, _: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
435        if let TerminalContainerContent::Connected(connected) = &self.content {
436            let terminal = connected.read(cx).terminal().clone();
437            terminal.update(cx, |term, _| term.activate_match(index));
438            cx.notify();
439        }
440    }
441
442    /// Get all of the matches for this query, should be done on the background
443    fn find_matches(
444        &mut self,
445        query: project::search::SearchQuery,
446        cx: &mut ViewContext<Self>,
447    ) -> Task<Vec<Self::Match>> {
448        if let TerminalContainerContent::Connected(connected) = &self.content {
449            let terminal = connected.read(cx).terminal().clone();
450            terminal.update(cx, |term, cx| term.find_matches(query, cx))
451        } else {
452            Task::ready(Vec::new())
453        }
454    }
455
456    /// Reports back to the search toolbar what the active match should be (the selection)
457    fn active_match_index(
458        &mut self,
459        matches: Vec<Self::Match>,
460        cx: &mut ViewContext<Self>,
461    ) -> Option<usize> {
462        let connected = self.connected();
463        // Selection head might have a value if there's a selection that isn't
464        // associated with a match. Therefore, if there are no matches, we should
465        // report None, no matter the state of the terminal
466        let res = if matches.len() > 0 && connected.is_some() {
467            if let Some(selection_head) = connected
468                .unwrap()
469                .read(cx)
470                .terminal()
471                .read(cx)
472                .selection_head
473            {
474                // If selection head is contained in a match. Return that match
475                if let Some(ix) = matches
476                    .iter()
477                    .enumerate()
478                    .find(|(_, search_match)| {
479                        search_match.contains(&selection_head)
480                            || search_match.start() > &selection_head
481                    })
482                    .map(|(ix, _)| ix)
483                {
484                    Some(ix)
485                } else {
486                    // If no selection after selection head, return the last match
487                    Some(matches.len().saturating_sub(1))
488                }
489            } else {
490                // Matches found but no active selection, return the first last one (closest to cursor)
491                Some(matches.len().saturating_sub(1))
492            }
493        } else {
494            None
495        };
496
497        res
498    }
499}
500
501///Get's the working directory for the given workspace, respecting the user's settings.
502pub fn get_working_directory(
503    workspace: &Workspace,
504    cx: &AppContext,
505    strategy: WorkingDirectory,
506) -> Option<PathBuf> {
507    let res = match strategy {
508        WorkingDirectory::CurrentProjectDirectory => current_project_directory(workspace, cx)
509            .or_else(|| first_project_directory(workspace, cx)),
510        WorkingDirectory::FirstProjectDirectory => first_project_directory(workspace, cx),
511        WorkingDirectory::AlwaysHome => None,
512        WorkingDirectory::Always { directory } => {
513            shellexpand::full(&directory) //TODO handle this better
514                .ok()
515                .map(|dir| Path::new(&dir.to_string()).to_path_buf())
516                .filter(|dir| dir.is_dir())
517        }
518    };
519    res.or_else(home_dir)
520}
521
522///Get's the first project's home directory, or the home directory
523fn first_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
524    workspace
525        .worktrees(cx)
526        .next()
527        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
528        .and_then(get_path_from_wt)
529}
530
531///Gets the intuitively correct working directory from the given workspace
532///If there is an active entry for this project, returns that entry's worktree root.
533///If there's no active entry but there is a worktree, returns that worktrees root.
534///If either of these roots are files, or if there are any other query failures,
535///  returns the user's home directory
536fn current_project_directory(workspace: &Workspace, cx: &AppContext) -> Option<PathBuf> {
537    let project = workspace.project().read(cx);
538
539    project
540        .active_entry()
541        .and_then(|entry_id| project.worktree_for_entry(entry_id, cx))
542        .or_else(|| workspace.worktrees(cx).next())
543        .and_then(|worktree_handle| worktree_handle.read(cx).as_local())
544        .and_then(get_path_from_wt)
545}
546
547fn get_path_from_wt(wt: &LocalWorktree) -> Option<PathBuf> {
548    wt.root_entry()
549        .filter(|re| re.is_dir())
550        .map(|_| wt.abs_path().to_path_buf())
551}
552
553#[cfg(test)]
554mod tests {
555
556    use super::*;
557    use gpui::TestAppContext;
558
559    use std::path::Path;
560
561    use crate::tests::terminal_test_context::TerminalTestContext;
562
563    ///Working directory calculation tests
564
565    ///No Worktrees in project -> home_dir()
566    #[gpui::test]
567    async fn no_worktree(cx: &mut TestAppContext) {
568        //Setup variables
569        let mut cx = TerminalTestContext::new(cx);
570        let (project, workspace) = cx.blank_workspace().await;
571        //Test
572        cx.cx.read(|cx| {
573            let workspace = workspace.read(cx);
574            let active_entry = project.read(cx).active_entry();
575
576            //Make sure enviroment is as expeted
577            assert!(active_entry.is_none());
578            assert!(workspace.worktrees(cx).next().is_none());
579
580            let res = current_project_directory(workspace, cx);
581            assert_eq!(res, None);
582            let res = first_project_directory(workspace, cx);
583            assert_eq!(res, None);
584        });
585    }
586
587    ///No active entry, but a worktree, worktree is a file -> home_dir()
588    #[gpui::test]
589    async fn no_active_entry_worktree_is_file(cx: &mut TestAppContext) {
590        //Setup variables
591
592        let mut cx = TerminalTestContext::new(cx);
593        let (project, workspace) = cx.blank_workspace().await;
594        cx.create_file_wt(project.clone(), "/root.txt").await;
595
596        cx.cx.read(|cx| {
597            let workspace = workspace.read(cx);
598            let active_entry = project.read(cx).active_entry();
599
600            //Make sure enviroment is as expeted
601            assert!(active_entry.is_none());
602            assert!(workspace.worktrees(cx).next().is_some());
603
604            let res = current_project_directory(workspace, cx);
605            assert_eq!(res, None);
606            let res = first_project_directory(workspace, cx);
607            assert_eq!(res, None);
608        });
609    }
610
611    //No active entry, but a worktree, worktree is a folder -> worktree_folder
612    #[gpui::test]
613    async fn no_active_entry_worktree_is_dir(cx: &mut TestAppContext) {
614        //Setup variables
615        let mut cx = TerminalTestContext::new(cx);
616        let (project, workspace) = cx.blank_workspace().await;
617        let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root/").await;
618
619        //Test
620        cx.cx.update(|cx| {
621            let workspace = workspace.read(cx);
622            let active_entry = project.read(cx).active_entry();
623
624            assert!(active_entry.is_none());
625            assert!(workspace.worktrees(cx).next().is_some());
626
627            let res = current_project_directory(workspace, cx);
628            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
629            let res = first_project_directory(workspace, cx);
630            assert_eq!(res, Some((Path::new("/root/")).to_path_buf()));
631        });
632    }
633
634    //Active entry with a work tree, worktree is a file -> home_dir()
635    #[gpui::test]
636    async fn active_entry_worktree_is_file(cx: &mut TestAppContext) {
637        //Setup variables
638        let mut cx = TerminalTestContext::new(cx);
639        let (project, workspace) = cx.blank_workspace().await;
640        let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
641        let (wt2, entry2) = cx.create_file_wt(project.clone(), "/root2.txt").await;
642        cx.insert_active_entry_for(wt2, entry2, project.clone());
643
644        //Test
645        cx.cx.update(|cx| {
646            let workspace = workspace.read(cx);
647            let active_entry = project.read(cx).active_entry();
648
649            assert!(active_entry.is_some());
650
651            let res = current_project_directory(workspace, cx);
652            assert_eq!(res, None);
653            let res = first_project_directory(workspace, cx);
654            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
655        });
656    }
657
658    //Active entry, with a worktree, worktree is a folder -> worktree_folder
659    #[gpui::test]
660    async fn active_entry_worktree_is_dir(cx: &mut TestAppContext) {
661        //Setup variables
662        let mut cx = TerminalTestContext::new(cx);
663        let (project, workspace) = cx.blank_workspace().await;
664        let (_wt, _entry) = cx.create_folder_wt(project.clone(), "/root1/").await;
665        let (wt2, entry2) = cx.create_folder_wt(project.clone(), "/root2/").await;
666        cx.insert_active_entry_for(wt2, entry2, project.clone());
667
668        //Test
669        cx.cx.update(|cx| {
670            let workspace = workspace.read(cx);
671            let active_entry = project.read(cx).active_entry();
672
673            assert!(active_entry.is_some());
674
675            let res = current_project_directory(workspace, cx);
676            assert_eq!(res, Some((Path::new("/root2/")).to_path_buf()));
677            let res = first_project_directory(workspace, cx);
678            assert_eq!(res, Some((Path::new("/root1/")).to_path_buf()));
679        });
680    }
681}