use std::{ iter, path::PathBuf, }; use crate::{ buffer::Buffer, command_list::CommandList, diagnostic_list::DiagnosticList, document::Document, file_picker::{ FileIndex, FilePicker, }, jujutsu::JJPoller, lsp::{ LspClient, LspEvent, LspTextEdit, }, ui::{ AppEvent, EditorDimensions, Layer, LayerKind, Position, }, }; pub(crate) struct Editor { document: Document, layers: Vec>, file_index: FileIndex, dimensions: EditorDimensions, jj_poller: JJPoller, lsp: Option, } impl Editor { pub(crate) fn new( file_path: PathBuf, dimensions: EditorDimensions, lsp: Option, jj_poller: JJPoller, file_index: FileIndex, ) -> anyhow::Result { let document = Document::new(file_path, dimensions)?; if let Some(ref client) = lsp { client.document_opened(document.lsp_snapshot()); } Ok(Self { document, layers: vec![], file_index, dimensions, jj_poller, lsp, }) } pub(crate) fn visual_cursor_position(&self) -> Position { self.layers() .rev() .find_map(Layer::visual_cursor_position) .expect( "at least one visual layer must have a cursor position (i.e. `Document` cursor \ position is always `Some`)", ) } pub(crate) fn handle_event(&mut self, event: &AppEvent) -> EventOutcome { puffin::profile_function!(); match *event { AppEvent::Resize(dimensions) => { self.resize(dimensions); EventOutcome::Handled } AppEvent::Layer(ref layer_event) => { let mut event_context = EventContext::new(); let result = self .layers_mut() .rev() .find_map(|layer| { match layer.handle_event(layer_event, &mut event_context) { EventOutcome::Handled => Some(EventOutcome::Handled), EventOutcome::CloseApp => Some(EventOutcome::CloseApp), EventOutcome::Unhandled => None, } }) .unwrap_or(EventOutcome::Unhandled); match result { EventOutcome::Handled => self.apply_actions(event_context.actions()), EventOutcome::Unhandled | EventOutcome::CloseApp => result, } } } } pub(crate) fn render(&mut self, buffer: &mut Buffer) { puffin::profile_function!(); for layer in self.layers_mut() { layer.render(buffer); } } pub(crate) fn handle_layer_events(&mut self) -> EventOutcome { let mut result = if let Some(status) = self.jj_poller.refresh() { self.document.set_jj_info(status); EventOutcome::Handled } else { EventOutcome::Unhandled }; if let Some(ref lsp) = self.lsp { for event in lsp.events() { match event { LspEvent::PublishDiagnostics { params, position_encoding, } => { // TODO: when we support multiple open documents, match // up `params.uri` with the // correct doc if self.document.url() == ¶ms.uri && params .version .is_none_or(|version| version == self.document.version().value()) { self.document.publish_diagnostics(params, position_encoding); result = EventOutcome::Handled; } } } } } for layer in self.layers_mut() { match layer.handle_internal_events() { EventOutcome::Handled => result = EventOutcome::Handled, EventOutcome::CloseApp => return EventOutcome::CloseApp, EventOutcome::Unhandled => {} } } result } fn layers(&self) -> impl DoubleEndedIterator { iter::once(&self.document as &dyn Layer).chain(self.layers.iter().map(AsRef::as_ref)) } fn layers_mut(&mut self) -> impl DoubleEndedIterator { iter::once(&mut self.document as &mut dyn Layer) .chain(self.layers.iter_mut().map(|l| l.as_mut() as &mut dyn Layer)) } fn apply_actions(&mut self, actions: Vec) -> EventOutcome { for action in actions { match action { EditorAction::AddLayer(layer) => { match layer { LayerKind::CommandList => { self.layers .push(Box::new(CommandList::new(self.dimensions))); } LayerKind::FilePicker => { self.layers .push(Box::new(FilePicker::new(&self.file_index, self.dimensions))); } LayerKind::DiagnosticList => { let diagnostics = self.document.diagnostics_for_cursor_line(); if !diagnostics.is_empty() { self.layers.push(Box::new(DiagnosticList::new( &diagnostics, self.dimensions, ))); } } } } EditorAction::RemoveLayer(layer_kind) => { // TODO: will we ever have multiple layers of the same type? // if so, the layers will need ids so that we can ensure we // remove the correct one let remove_index = self .layers .iter() .position(|layer| layer.kind() == Some(layer_kind)); if let Some(idx) = remove_index { self.layers.remove(idx); } } EditorAction::Quit => return EventOutcome::CloseApp, EditorAction::Write => { match self.save_document() { Ok(()) => {} Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::WriteQuit => { match self.save_document() { Ok(()) => return EventOutcome::CloseApp, Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::OpenFile(path) => { match self.replace_document(path) { Ok(()) => {} Err(err) => self.document.set_error(format!("{err:#}")), } } EditorAction::DocumentChanged(edit) => { if let Some(ref lsp) = self.lsp { lsp.document_changed(self.document.lsp_snapshot(), edit); } } } } EventOutcome::Handled } fn resize(&mut self, dimensions: EditorDimensions) { self.dimensions = dimensions; for layer in self.layers_mut() { layer.resize(dimensions); } } fn save_document(&self) -> anyhow::Result<()> { self.document.save()?; if let Some(ref lsp) = self.lsp { lsp.document_saved(self.document.lsp_snapshot()); } Ok(()) } fn replace_document(&mut self, path: PathBuf) -> anyhow::Result<()> { let new_doc = Document::new(path.clone(), self.dimensions)?; if let Some(ref lsp) = self.lsp { let old_doc_id = self.document.lsp_id(); lsp.document_closed(old_doc_id.clone()); lsp.document_opened(new_doc.lsp_snapshot()); } self.document = new_doc; self.jj_poller.update_path(path); Ok(()) } #[cfg(test)] pub(crate) const fn document(&self) -> &Document { &self.document } } #[derive(Debug)] #[must_use] pub(crate) enum EventOutcome { Handled, Unhandled, CloseApp, } pub(crate) struct EventContext { actions: Vec, } impl EventContext { pub(crate) const fn new() -> Self { Self { actions: Vec::new(), } } /// Queue a new action to be applied to the /// [`Editor`](crate::editor::Editor). pub(crate) fn push_action(&mut self, action: EditorAction) { self.actions.push(action); } pub(crate) fn actions(self) -> Vec { self.actions } } #[derive(Debug)] pub(crate) enum EditorAction { AddLayer(LayerKind), RemoveLayer(LayerKind), Quit, Write, WriteQuit, OpenFile(PathBuf), DocumentChanged(LspTextEdit), } #[cfg(test)] mod tests { use crossterm::event::KeyCode; use crate::{ test_harness::TestHarness, ui::{ Columns, Dimensions, EditorDimensions, Rectangle, Rows, }, }; #[test] fn displays_basic_screen() { let harness = TestHarness::new( "hello\nthere\nworld", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), ); insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────▼──────────────────┐ ▶ 1 hello │ │ 1 there │ │ 2 world │ │ │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ " ); } #[test] fn moves_cursor_and_inserts_text() { let mut harness = TestHarness::new( "hello\nthere\nworld", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), ); insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────▼──────────────────┐ ▶ 1 hello │ │ 1 there │ │ 2 world │ │ │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ " ); // navigate harness.send_key(KeyCode::Char('j')); harness.send_key(KeyCode::Char('l')); // enter text harness.send_key(KeyCode::Char('i')); harness.send_key(KeyCode::Char('h')); harness.send_key(KeyCode::Char('e')); harness.send_key(KeyCode::Char('y')); insta::assert_snapshot!( harness.screen().to_string(), @" ┌─────────▼──────────────┐ │ 1 hello │ ▶ 2 theyhere │ │ 1 world │ │ │ │ INSERT test.txt text │ │ │ └────────────────────────┘ " ); } #[test] #[expect( clippy::unicode_not_nfc, reason = "it's the point of the test that it displays correctly, so i want to see it" )] fn zero_width_graphemes_display_as_dotted_circle() { let mut harness = TestHarness::new( "\u{301}x\n\u{200B}\na\u{200B}\na\u{301}", EditorDimensions::new(Dimensions::new(Columns::new(24), Rows::new(6))).unwrap(), ); harness.send_key(KeyCode::Char('w')); harness.send_key(KeyCode::Char('w')); insta::assert_snapshot!(harness.screen().to_string(), @" ┌─────▼──────────────────┐ │ 1 ◌x │ ▶ 2 ◌ │ │ 1 a◌ │ │ 2 á │ │ NORMAL test.txt text │ │ │ └────────────────────────┘ "); } #[test] fn cursor_stays_on_screen_when_eof_wraps() { let mut harness = TestHarness::new("", EditorDimensions::MIN); let initial_screen = harness.screen(); let text_start = initial_screen.cursor(); let text_width = initial_screen.dimensions().width() - text_start.left(); assert!(text_width > Columns::new(0)); // insert text until cursor is one past the right edge. this should // cause it to wrap onto the next row harness.send_key(KeyCode::Char('i')); for _ in 0..text_width.value() { harness.send_key(KeyCode::Char('a')); } let screen = harness.screen(); assert!(Rectangle::from_dimensions(screen.dimensions()).contains(&screen.cursor())); assert_eq!(screen.cursor(), text_start.row_offset(Rows::new(1))); } #[test] fn cursor_stays_on_screen_for_lines_taller_than_screen() { let dimensions = EditorDimensions::MIN; let text_width = { let harness = TestHarness::new("", dimensions); let screen = harness.screen(); screen.dimensions().width() - screen.cursor().left() }; let height = dimensions.get().height(); // when wrapped, this single line is taller than the editor let contents = "a".repeat(text_width.value() * height.value() + 1); let mut harness = TestHarness::new(&contents, dimensions); harness.send_key(KeyCode::Char('$')); let screen = harness.screen(); let cursor = screen.cursor(); assert!(Rectangle::from_dimensions(screen.dimensions()).contains(&cursor)); } }