diff --git a/crates/ui-egui/src/canvas/ime.rs b/crates/ui-egui/src/canvas/ime.rs deleted file mode 100644 index 61f47bc14..000000000 --- a/crates/ui-egui/src/canvas/ime.rs +++ /dev/null @@ -1,43 +0,0 @@ -use super::{Rect, SlideApp, Ui, Xf, screen_rect, vec2}; - -/// Where an input method composes for the slide (#101), on screen: at the insertion point while -/// editing text, or over the one selected shape (typing on it starts editing). `None` when there is -/// nothing to type into. -pub fn ime_area(app: &SlideApp, xf: Xf) -> Option { - let st = app.session.active()?; - if let Some(ts) = &st.selection.text { - if ts.notes { - return None; - } - if let Some((top, bot)) = deckcraft_engine::cmd::text::caret_line(st, ts) { - return Some(Rect::from_two_pos(xf.to_screen(top), xf.to_screen(bot)).expand2(vec2(1.0, 0.0))); - } - let sh = st.shape(ts.shape)?; - return Some(screen_rect(xf, &deckcraft_engine::cmd::xfrm_of(&st.doc, &st.selection, sh))); - } - if st.selection.shapes.len() != 1 { - return None; - } - let sh = st.shape(*st.selection.shapes.first()?)?; - if sh.is_line() { - return None; - } - Some(screen_rect(xf, &deckcraft_engine::cmd::xfrm_of(&st.doc, &st.selection, sh))) -} - -/// Turn the input method on for the slide while it takes typing, with its candidate window at -/// the insertion point (#101). Without this egui leaves it off, and a Korean keyboard types -/// separate jamo (ㅇ ㅏ ㄴ) instead of syllables. A focused text field sets its own. -/// -/// This only records the screen rect for this pass. [`crate::SlideApp`] observes the committed -/// text, owner and cause once at the end of the pass, after every IME event and editor command -/// has settled. -pub(super) fn ime_output(app: &mut SlideApp, ui: &Ui, xf: Xf) { - let ctx = ui.ctx(); - if ctx.memory(|m| m.focused().is_some()) || app.dialog.as_ref().is_some_and(|d| d.modal()) || app.palette.is_some() || app.backstage_open() { - return; - } - let Some(r) = ime_area(app, xf) else { return }; - let to_global = ctx.layer_transform_to_global(ui.layer_id()).unwrap_or_default(); - app.ime_pending = Some(to_global * r); -} diff --git a/crates/ui-egui/src/canvas/text_host.rs b/crates/ui-egui/src/canvas/text_host.rs index 4ef9fccaa..ebe526cf5 100644 --- a/crates/ui-egui/src/canvas/text_host.rs +++ b/crates/ui-egui/src/canvas/text_host.rs @@ -1,10 +1,352 @@ -/// Hosts the text editor over the slide picture, except during animation previews. -#[allow(dead_code)] // P3(canvas-w8): cv.A3 -pub(crate) fn show_editor( - app: &mut crate::SlideApp, - ui: &mut egui::Ui, - space: &craft::ui::canvas::CanvasSpace, -) -> Option { - let _ = (app, ui, space); - todo!("cv.A3") +use std::ops::Range; + +use craft::behavior::{MotionMode, kurbo::Point}; +use craft::text::ui::editor::{ + CaretAffinity, CaretLine, ClickRuns, EditKind, EditorComposition, EditorEnd, HostLine, HostRun, TextEditor, TextEditorHost, TextEditorOutput, + TextReplacement, TextSelection, +}; +use craft::ui::canvas::CanvasSpace; +use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::runtime::{env::with_env, focus}; +use deckcraft_engine::{Session, TextReplaceKind, TextSel, cmd::text}; +use deckcraft_geom::Affine; +use deckcraft_model::text::TextBody; +use deckcraft_text::{Affinity, Pos, TextLayout}; +use egui::{Rect, Ui}; + +/// Paragraph boundaries in the editor's character coordinates, including one separator per paragraph pair. +struct TextOffsets { + text: String, + paragraphs: Vec>, + bytes: Vec, +} + +impl TextOffsets { + fn new(body: Option<&TextBody>) -> Self { + let mut text = String::new(); + let mut paragraphs = Vec::new(); + let mut offset = 0; + for paragraph in body.into_iter().flat_map(|body| &body.paragraphs) { + if !paragraphs.is_empty() { + text.push('\n'); + offset += 1; + } + let value = paragraph.text(); + let end = offset + value.chars().count(); + text.push_str(&value); + paragraphs.push(offset..end); + offset = end; + } + let bytes = text.char_indices().map(|(byte, _)| byte).chain(std::iter::once(text.len())).collect(); + Self { text, paragraphs, bytes } + } + + fn offset(&self, pos: (usize, usize)) -> usize { + self.paragraphs.get(pos.0).map_or_else(|| self.paragraphs.last().map_or(0, |p| p.end), |p| p.start + pos.1.min(p.len())) + } + + fn pos(&self, offset: usize) -> Pos { + for (para, range) in self.paragraphs.iter().enumerate() { + if offset <= range.end { + return Pos { para, ch: offset.saturating_sub(range.start).min(range.len()) }; + } + } + Pos { para: self.paragraphs.len().saturating_sub(1), ch: self.paragraphs.last().map_or(0, Range::len) } + } + + fn slice(&self, range: Range) -> &str { + let start = self.bytes.get(range.start).copied().unwrap_or(self.text.len()); + let end = self.bytes.get(range.end).copied().unwrap_or(self.text.len()); + self.text.get(start..end).unwrap_or_default() + } + + fn selection(&self, selection: &TextSel) -> TextSelection { + TextSelection::new(self.offset(selection.anchor), self.offset(selection.caret)) + .with_affinity(if selection.at_line_end() { CaretAffinity::Upstream } else { CaretAffinity::Downstream }) + } + + fn apply(&self, selection: TextSelection, target: &mut TextSel) { + let anchor = self.pos(selection.anchor); + let caret = self.pos(selection.caret); + target.anchor = (anchor.para, anchor.ch); + target.caret = (caret.para, caret.ch); + target.line_end = (selection.affinity == CaretAffinity::Upstream).then_some(target.caret); + } +} + +/// Adapts one edited engine body without retaining text or layout across passes. +struct EngineTextHost<'a> { + session: &'a mut Session, + target: TextSel, + offsets: TextOffsets, + frame: Option<(TextLayout, Affine)>, + error: Option, +} + +impl<'a> EngineTextHost<'a> { + fn new(session: &'a mut Session, target: TextSel) -> Self { + let mut host = Self { session, target, offsets: TextOffsets::new(None), frame: None, error: None }; + host.refresh(); + host + } + + fn refresh(&mut self) { + let state = self.session.active(); + self.offsets = TextOffsets::new(state.and_then(|state| text::body_of(state, &self.target))); + self.frame = state.and_then(|state| text::text_frame(state, &self.target)); + } + + fn select(&mut self, selection: TextSelection) { + self.offsets.apply(selection, &mut self.target); + let target = self.target.clone(); + if let Err(error) = self.session.select(|_, selection| selection.text = Some(target)) { + self.error = Some(error.to_string()); + } + } + + fn bounds(&self, space: &CanvasSpace) -> Option { + let (layout, transform) = self.frame.as_ref()?; + // The inner box also gives empty paragraphs a hit surface, without inventing padding around glyphs. + let bounds = layout.bounds().union(layout.inner); + Some(screen_bounds(quad(bounds).map(|p| space.view.to_screen(*transform * p)))) + } +} + +impl TextEditorHost for EngineTextHost<'_> { + fn text(&self) -> &str { + &self.offsets.text + } + + fn composition(&self) -> Option { + let composition = self.session.active()?.composition.as_ref()?; + let start = self.offsets.offset(composition.start); + Some(EditorComposition::new(start..start + composition.len, composition.active.map(|(start, end)| start..end))) + } + + fn settle_composition(&mut self) { + self.session.settle_composition(); + } + + fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> Option { + let kind = match kind { + EditKind::Typed => TextReplaceKind::Typed, + EditKind::Pasted => TextReplaceKind::Pasted, + EditKind::Deleted => TextReplaceKind::Deleted, + EditKind::Composing => TextReplaceKind::Composing, + EditKind::Committed => TextReplaceKind::Committed, + _ => return None, + }; + match self.session.replace_text_range(range, text, kind) { + Ok(result) => { + self.target = result.selection; + self.refresh(); + Some(TextReplacement::new(result.range, self.offsets.selection(&self.target))) + } + Err(error) => { + self.error = Some(error.to_string()); + None + } + } + } + + fn hit(&mut self, at: Point) -> (usize, usize) { + let Some(state) = self.session.active() else { return (0, 0) }; + let at = deckcraft_geom::Point::new(at.x, at.y); + let pos = text::text_pos_at(state, &self.target, at); + let line = self.frame.as_ref().and_then(|(layout, transform)| { + let (_, affinity) = layout.hit_affinity(transform.inverse() * at); + layout.line_index(Pos { para: pos.0, ch: pos.1 }, affinity) + }); + (self.offsets.offset(pos), line.unwrap_or(0)) + } + + fn caret(&mut self, offset: usize, affinity: CaretAffinity) -> Option { + let mut target = self.target.clone(); + self.offsets.apply(TextSelection::caret_at(offset).with_affinity(affinity), &mut target); + let (top, bottom) = text::caret_line(self.session.active()?, &target)?; + Some(CaretLine::new(Point::new(top.x, top.y), Point::new(bottom.x, bottom.y))) + } + + fn selection_quads(&mut self, range: Range) -> Vec<[Point; 4]> { + let Some((layout, transform)) = &self.frame else { return Vec::new() }; + layout + .selection_rects(self.offsets.pos(range.start), self.offsets.pos(range.end)) + .into_iter() + .map(|rect| quad(rect).map(|p| document_point(*transform * p))) + .collect() + } + + fn underline_segments(&mut self, range: Range) -> Vec<[Point; 2]> { + let Some((layout, transform)) = &self.frame else { return Vec::new() }; + layout + .composition_underlines(self.offsets.pos(range.start), self.offsets.pos(range.end)) + .into_iter() + .map(|(x0, x1, y)| [deckcraft_geom::Point::new(x0, y), deckcraft_geom::Point::new(x1, y)].map(|p| document_point(*transform * p))) + .collect() + } + + fn lines(&mut self) -> Vec { + let Some((layout, transform)) = &self.frame else { return Vec::new() }; + layout + .lines + .iter() + .map(|line| { + let range = self.offsets.offset((line.para, line.start))..self.offsets.offset((line.para, line.end)); + let value = self.offsets.slice(range.clone()).to_owned(); + let rect = document_bounds(quad(deckcraft_geom::Rect::new(line.extent.0, line.top, line.extent.1, line.bottom)), *transform); + let mut runs = Vec::new(); + let mut chars = value.char_indices().peekable(); + let mut index = 0; + while let Some((start, _)) = chars.peek().copied() { + let rtl = line.levels.get(index).is_some_and(|level| level % 2 == 1); + let mut positions = Vec::new(); + let mut widths = Vec::new(); + let mut end = start; + while let Some((byte, character)) = chars.peek().copied() { + if line.levels.get(index).is_some_and(|level| level % 2 == 1) != rtl { + break; + } + chars.next(); + let (left, right) = line.edges.get(index).copied().unwrap_or((line.extent.0, line.extent.0)); + let a = *transform * deckcraft_geom::Point::new(left, line.baseline); + let b = *transform * deckcraft_geom::Point::new(right, line.baseline); + positions.push((a.x - f64::from(rect.left())) as f32); + widths.push((b - a).hypot() as f32); + end = byte + character.len_utf8(); + index += 1; + } + runs.push(HostRun::new(start..end, rtl, positions, widths)); + } + let baseline = (*transform * deckcraft_geom::Point::new(line.extent.0, line.baseline)).y as f32; + HostLine::new(value, range, rect, baseline, runs) + }) + .collect() + } + + fn line_range(&mut self, line: usize) -> Range { + self.frame.as_ref().and_then(|(layout, _)| layout.lines.get(line)).map_or(0..0, |line| { + self.offsets.offset((line.para, line.start))..self.offsets.offset((line.para, line.end)) + }) + } + + fn line_step(&mut self, offset: usize, affinity: CaretAffinity, lines: i32) -> (usize, CaretAffinity) { + let Some((layout, _)) = &self.frame else { return (offset, affinity) }; + let mut pos = self.offsets.pos(offset); + let mut affinity = layout_affinity(affinity); + let Some((x, _, _)) = layout.caret_drawn(pos, affinity) else { return (offset, editor_affinity(affinity)) }; + for _ in 0..lines.unsigned_abs().min(layout.lines.len() as u32) { + let next = layout.vertical_affine(pos, affinity, lines > 0, x); + if next == (pos, affinity) { + break; + } + (pos, affinity) = next; + } + (self.offsets.offset((pos.para, pos.ch)), editor_affinity(affinity)) + } + + fn line_edge(&mut self, offset: usize, affinity: CaretAffinity, end: bool) -> (usize, CaretAffinity) { + let Some((layout, _)) = &self.frame else { return (offset, affinity) }; + let pos = self.offsets.pos(offset); + let affinity = layout_affinity(affinity); + let (pos, affinity) = + if end { layout.line_end_caret(pos, affinity) } else { (layout.line_bounds_affine(pos, affinity).0, Affinity::Downstream) }; + (self.offsets.offset((pos.para, pos.ch)), editor_affinity(affinity)) + } + + fn vertical(&self) -> bool { + use deckcraft_engine::Target; + use deckcraft_model::resolve::{self, Ctx}; + use deckcraft_model::text::TextDir; + + let Some(state) = self.session.active() else { return false }; + let doc = &state.doc; + let context = match state.selection.target { + Target::Slides => doc.slides.get(state.selection.slide).and_then(|slide| Ctx::for_slide(doc, slide)), + Target::Master { master } => doc.masters.get(master).map(|master| Ctx::for_master(doc, master)), + Target::Layout { master, layout } => { + doc.masters.get(master).and_then(|master| master.layouts.get(layout).map(|layout| Ctx::for_layout(doc, master, layout))) + } + target @ (Target::Handout | Target::NotesMaster) => deckcraft_engine::page_master(doc, target).map(|master| Ctx::for_master(doc, master)), + }; + let Some(context) = context else { return false }; + let Some(shape) = state.shape(self.target.shape) else { return false }; + let props = if let (Some((row, col)), deckcraft_model::ShapeKind::Table(table)) = (self.target.cell, &shape.kind) { + let Some(cell) = table.cell(row, col) else { return false }; + deckcraft_render::table_cell_body(&context, table, row, col, cell).body + } else { + resolve::body(&context, shape) + }; + props.vert.unwrap_or(TextDir::Horizontal) != TextDir::Horizontal + } +} + +fn layout_affinity(affinity: CaretAffinity) -> Affinity { + if affinity == CaretAffinity::Upstream { Affinity::Upstream } else { Affinity::Downstream } +} + +fn editor_affinity(affinity: Affinity) -> CaretAffinity { + if affinity == Affinity::Upstream { CaretAffinity::Upstream } else { CaretAffinity::Downstream } +} + +fn document_point(point: deckcraft_geom::Point) -> Point { + Point::new(point.x, point.y) +} + +fn quad(rect: deckcraft_geom::Rect) -> [deckcraft_geom::Point; 4] { + [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1)].map(|(x, y)| deckcraft_geom::Point::new(x, y)) +} + +fn screen_bounds(points: [egui::Pos2; 4]) -> Rect { + points.into_iter().fold(Rect::NOTHING, |rect, point| rect.union(Rect::from_min_max(point, point))) +} + +fn document_bounds(points: [deckcraft_geom::Point; 4], transform: Affine) -> Rect { + screen_bounds(points.map(|point| { + let point = transform * point; + egui::pos2(point.x as f32, point.y as f32) + })) +} + +/// Hosts the edited shape or cell while no dialog, palette, File view or other text field owns input. +pub(crate) fn show_editor(app: &mut crate::SlideApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + if crate::dialogs::modal_open(ui.ctx()) || app.palette_open || app.backstage_open() { + return None; + } + let state = app.session.active()?; + let target = state.selection.text.as_ref().filter(|target| !target.notes)?.clone(); + let id = ui.make_persistent_id(("slide-text-editor", state.uid, target.shape, target.cell)); + if focus::focused_rec(ui.ctx()) + .is_some_and(|record| record.stop.id != id && record.stop.text && !record.stop.keys.is_document_editor()) + { + return None; + } + if let Err(error) = app.session.begin_text_edit_session() { + app.set_status(error.to_string()); + return None; + } + let mut host = EngineTextHost::new(&mut app.session, target); + let bounds = host.bounds(space)?; + let mut selection = host.offsets.selection(&host.target); + let editor = TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).id(id).click_runs(ClickRuns::Paragraphs); + let output = if app.caret_blink == Some(false) { + with_env(ui, |env| env.motion = Some(MotionMode::Off), |ui| editor.show_at(ui, bounds)) + } else { + editor.show_at(ui, bounds) + }; + if output.selection_changed || output.changed { + host.select(selection); + } + let error = host.error.take(); + if let Some(error) = error { + app.set_status(error); + } + if let Some(ended) = output.ended { + match app.session.finish_text_edit_session(ended == EditorEnd::Cancel) { + Ok(()) => { + let _ = app.run("text.exit", serde_json::json!({})); + } + Err(error) => app.set_status(error.to_string()), + } + } + Some(output) }