terminal_view.rs

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