terminal_container_view.rs

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