Skip to main content

kui_core/
edit.rs

1//! Editable text: the retained state of every `text_edit` node, keyed by
2//! node `Key`, built on cosmic-text's editor.
3//!
4//! A view declares an editor with `Ui::text_edit(label, initial, &opts,
5//! spec)`, where `opts` is an [`EditOptions`]. The core keeps the buffer,
6//! caret, selection, IME composition and undo history across frames,
7//! routes `InputEvent::Text` / `InputEvent::Key` to the focused editor and
8//! posts `changed` and `submit` events. An app reads the draft back with
9//! `Core::edit_text` / `Ui::edit_text` and replaces it with
10//! `Core::set_edit_text`; the store itself is not something an app
11//! touches.
12//!
13//! ```rust
14//! use kui_core::{Core, EditOptions, InputEvent, NodeSpec, Size, TextStyle};
15//!
16//! let mut core = Core::new();
17//! let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
18//! let opts = EditOptions {
19//!     style: TextStyle::new(14.0),
20//!     autofocus: true,
21//!     ..Default::default()
22//! };
23//! let field = ui.text_edit("name", "hello", &opts, NodeSpec::row().grow_width().pad(4.0));
24//! ui.finish();
25//!
26//! // Typing reaches the focused editor; the host reads the draft back.
27//! core.handle_input(InputEvent::Text(" world".into()));
28//! assert_eq!(core.edit_text(field).as_deref(), Some("hello world"));
29//! ```
30
31use std::collections::VecDeque;
32
33use cosmic_text::{
34    Action, Attrs, AttrsList, Buffer, Cursor, Edit as _, Editor, FontSystem, Motion, Selection,
35    Shaping, Wrap,
36};
37use rustc_hash::FxHashMap;
38
39use crate::color::Color;
40use crate::display::{Clip, ClipId, Quad, QuadKind};
41use crate::geom::{Rect, Size, Vec2};
42use crate::input::{EditKey, Mods};
43use crate::key::Key;
44use crate::resources::Resources;
45use crate::spec::{TextStyle, TextWrap};
46use crate::text::TextSystem;
47use crate::tree::OriginId;
48
49/// How a `text_edit` node behaves: its text style, whether it is a
50/// single-line field or a multiline document, and how it takes focus and
51/// paints its selection. Build one with struct update syntax from
52/// `Default`.
53#[derive(Clone, Debug, Default)]
54pub struct EditOptions {
55    pub style: TextStyle,
56    /// A document rather than a field: Enter inserts a newline, the text
57    /// wraps to the box, and the caret opens at the top.
58    pub multiline: bool,
59    /// A single-line editor that folds to its width, by `style.wrap`, the
60    /// way a document does — instead of taking one line and scrolling it
61    /// under the caret. Its keyboard is still a field's:
62    /// Enter submits, a newline is never admitted, the caret opens at the
63    /// end. In the bindings this is the `wrap` row being declared on the
64    /// element; off, a field does not read `style.wrap` at all. A
65    /// `multiline` editor wraps either way and ignores this.
66    pub wrap: bool,
67    /// Takes keyboard focus on the frame this declaration starts — a new
68    /// editor, one back after a gap, one whose flag just turned on — and
69    /// only while nothing holds focus: never from a focused control, and
70    /// never again after a blur.
71    pub autofocus: bool,
72    /// A single-line editor whose Tab is the app's: Tab and Shift-Tab do
73    /// not walk the focus ring from it, and the press goes to the key
74    /// sink above it as a chord the editor does not claim does — so a
75    /// list or an outline built from fields indents on Tab (backlog F146).
76    /// With no sink above, Tab does nothing here. A `multiline` editor
77    /// keeps Tab for indentation either way and ignores this.
78    pub keep_tab: bool,
79    /// What an empty editor shows where its text would be, in the theme's
80    /// `faint` (backlog F149): never part of the value, gone with the
81    /// first character typed or composed, and read by assistive
82    /// technology as the field's description when it declares none.
83    pub placeholder: Option<String>,
84    /// Selection highlight color. `None` is the theme's `selection`,
85    /// which is what a field gets unless the caller says otherwise — so a
86    /// selection over a label and one over a field are the same tint on
87    /// both bases.
88    pub accent: Option<Color>,
89}
90
91/// What an editing key did to an editor: whether the text changed,
92/// whether it submitted the field, and the edge it met when it could do
93/// neither (backlog F145).
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub(crate) struct KeyOutcome {
96    pub changed: bool,
97    pub submit: bool,
98    pub boundary: Option<Edge>,
99}
100
101/// Which end of an editor's text a key met: the start (↑ on the first
102/// line, ← or Backspace at offset 0) or the end (↓ on the last line, → or
103/// Delete at the end).
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub(crate) enum Edge {
106    Start,
107    End,
108}
109
110impl Edge {
111    pub fn name(self) -> &'static str {
112        match self {
113            Edge::Start => "start",
114            Edge::End => "end",
115        }
116    }
117}
118
119pub(crate) struct EditState {
120    editor: Editor<'static>,
121    pub(crate) style: TextStyle,
122    pub(crate) accent: Color,
123    pub(crate) multiline: bool,
124    /// `EditOptions::keep_tab`, as last declared.
125    keep_tab: bool,
126    /// `EditOptions::placeholder`, shaped in a buffer of its own at the
127    /// editor's metrics, beside the `metrics_rev` it was shaped at.
128    placeholder: Option<(String, u32, Buffer)>,
129    /// Whether the buffer is laid out to its box's width: a document, or a
130    /// field with `wrap` declared. What `wrapped`,
131    /// `line_offset` and emission's clip decide by — a field that does not
132    /// fold takes one line and scrolls it.
133    folds: bool,
134    pub(crate) origin: OriginId,
135    scale: f32,
136    /// Wrap width (physical) the buffer is laid out at; None = unwrapped.
137    wrap: Option<f32>,
138    /// Bumped on every content change.
139    pub version: u64,
140    /// Bumped whenever the same text is laid out under new metrics (a
141    /// style or a scale change), so neither cache below can answer a
142    /// question about this font with a size measured for the last one.
143    metrics_rev: u32,
144    /// Cached wrapped measurement: (version, metrics, wrap bits, size).
145    measured: Option<(u64, u32, u32, Size)>,
146    /// Cached unwrapped measurement: (version, metrics, size). What the
147    /// fit width reads, and the reason it is cached rather than taken off
148    /// the buffer as it stands: the buffer is still carrying whatever
149    /// width `wrapped` last set on it.
150    natural: Option<(u64, u32, Size)>,
151    /// How far a single-line field has scrolled its text left, in physical
152    /// px. A field keeps the caret inside its box by moving the text under
153    /// it, the way a native field does, rather than by wrapping; an
154    /// editor that folds (`folds`) wraps and this stays 0.
155    offset_x: f32,
156    /// In-progress IME composition: a marked, uncommitted range living
157    /// inside the buffer (so the text around it reflows as it grows).
158    preedit: Option<Preedit>,
159    /// Edit history, oldest first. The widget owns its buffer, so it owns
160    /// undo too — hosts with their own text model (on_key sinks) bring
161    /// their own history and never touch this.
162    undo: VecDeque<EditOp>,
163    redo: VecDeque<EditOp>,
164    /// What the top undo op can still absorb (typing bursts, delete runs).
165    coalesce: Option<Coalesce>,
166    /// Whether the last declaration carried `autofocus`: with
167    /// `last_declared`, what makes the next one an edge or a repeat.
168    autofocus: bool,
169    /// The frame this key was last declared in. Only the budget reads it
170    /// (see [`MAX_UNDECLARED_EDITS`]); a state declared every frame never
171    /// looks at it again.
172    last_declared: u64,
173}
174
175/// How many *undeclared* editors the store keeps before the longest
176/// undeclared one is dropped. A declared editor is never evicted, however
177/// many there are: retention across absence is what `text_edit` promises,
178/// so this is a ceiling, not a prune. An editor holding a short line is a
179/// few KB and one holding a long line about 22 KB, so a full budget is a
180/// few MB.
181pub const MAX_UNDECLARED_EDITS: usize = 256;
182
183const UNDO_CAP: usize = 1000;
184/// Max bytes one coalesced op absorbs before a new unit starts.
185const COALESCE_MAX: usize = 64;
186
187/// One reversible edit: `deleted` was removed at `at` and `inserted` put in
188/// its place. Operational, not a snapshot — undo cost tracks the edit size,
189/// never the document size.
190struct EditOp {
191    at: Cursor,
192    deleted: String,
193    inserted: String,
194    /// Caret restore points for undo / redo.
195    cursor_before: Cursor,
196    cursor_after: Cursor,
197}
198
199#[derive(Clone, Copy, PartialEq)]
200enum Coalesce {
201    /// Plain typing: appends to the top op's `inserted`.
202    Insert,
203    /// Backspace runs walking left: prepends to `deleted`.
204    Backspace,
205    /// Forward-delete runs at a fixed spot: appends to `deleted`.
206    Delete,
207}
208
209/// Where a cursor lands after inserting `s` at `at`.
210fn end_cursor(at: Cursor, s: &str) -> Cursor {
211    match s.rsplit_once('\n') {
212        None => Cursor::new(at.line, at.index + s.len()),
213        Some((head, tail)) => Cursor::new(at.line + head.matches('\n').count() + 1, tail.len()),
214    }
215}
216
217/// Position equality, ignoring affinity (which editor cursors carry but
218/// computed ones don't).
219fn same_pos(a: Cursor, b: Cursor) -> bool {
220    a.line == b.line && a.index == b.index
221}
222
223/// IME composition state. The text is *in* the buffer starting at `start`
224/// — inserted without touching the undo history, replaced on every update,
225/// removed on commit or cancel — so the paragraph wraps and the following
226/// text shifts exactly as if it had been typed. The editor's own caret is
227/// parked at the IME-reported offset inside it.
228struct Preedit {
229    start: Cursor,
230    text: String,
231}
232
233/// Byte offset of `c` in the buffer's full text (lines joined by '\n').
234fn abs_offset(b: &Buffer, c: Cursor) -> usize {
235    b.lines
236        .iter()
237        .take(c.line)
238        .map(|l| l.text().len() + 1)
239        .sum::<usize>()
240        + c.index
241}
242
243impl EditState {
244    /// Both measurement caches, dropped together: the text under them
245    /// changed, so neither the wrapped size nor the natural one still
246    /// describes it.
247    fn invalidate_measurements(&mut self) {
248        self.measured = None;
249        self.natural = None;
250    }
251
252    /// Pushes a fresh op (clearing redo), merging into the top op when the
253    /// declared coalesce kind matches and the edits are adjacent.
254    fn record(&mut self, op: EditOp, kind: Option<Coalesce>) {
255        self.redo.clear();
256        if let (Some(k), Some(last)) = (kind, self.undo.back_mut())
257            && self.coalesce == Some(k)
258            && last.deleted.len() + last.inserted.len() + op.deleted.len() + op.inserted.len()
259                <= COALESCE_MAX
260        {
261            let merged = match k {
262                Coalesce::Insert => {
263                    same_pos(op.at, end_cursor(last.at, &last.inserted)) && {
264                        last.inserted.push_str(&op.inserted);
265                        true
266                    }
267                }
268                Coalesce::Backspace => {
269                    same_pos(end_cursor(op.at, &op.deleted), last.at) && {
270                        last.at = op.at;
271                        last.deleted.insert_str(0, &op.deleted);
272                        true
273                    }
274                }
275                Coalesce::Delete => {
276                    same_pos(op.at, last.at) && {
277                        last.deleted.push_str(&op.deleted);
278                        true
279                    }
280                }
281            };
282            if merged {
283                last.cursor_after = op.cursor_after;
284                return;
285            }
286        }
287        if self.undo.len() >= UNDO_CAP {
288            self.undo.pop_front();
289        }
290        self.undo.push_back(op);
291        self.coalesce = kind;
292    }
293
294    /// Caret motion, clicks, blur: the next edit starts a new undo unit.
295    fn break_coalesce(&mut self) {
296        self.coalesce = None;
297    }
298
299    /// Replaces `[at .. at+remove]` with `insert`, no recording — the raw
300    /// mechanism undo/redo replay through.
301    fn splice(&mut self, at: Cursor, remove: &str, insert: &str) {
302        if remove.is_empty() {
303            self.editor.set_selection(Selection::None);
304            self.editor.set_cursor(at);
305        } else {
306            self.editor.set_selection(Selection::Normal(at));
307            self.editor.set_cursor(end_cursor(at, remove));
308            self.editor.delete_selection();
309        }
310        if !insert.is_empty() {
311            self.editor.insert_string(insert, None);
312        }
313    }
314
315    /// Replaces the selection (if any) with `text`, as one recorded op.
316    fn insert_recorded(&mut self, text: &str) {
317        let cursor_before = self.editor.cursor();
318        let deleted = self.editor.copy_selection().unwrap_or_default();
319        self.editor.delete_selection();
320        let at = self.editor.cursor();
321        self.editor.insert_string(text, None);
322        let kind = (deleted.is_empty() && !text.contains('\n')).then_some(Coalesce::Insert);
323        self.record(
324            EditOp {
325                at,
326                deleted,
327                inserted: text.to_string(),
328                cursor_before,
329                cursor_after: self.editor.cursor(),
330            },
331            kind,
332        );
333    }
334
335    /// Deletes the selection as one recorded op; false when there is none.
336    fn delete_selection_recorded(&mut self) -> bool {
337        let cursor_before = self.editor.cursor();
338        let Some(deleted) = self.editor.copy_selection() else {
339            return false;
340        };
341        if !self.editor.delete_selection() {
342            return false;
343        }
344        let at = self.editor.cursor();
345        self.record(
346            EditOp {
347                at,
348                deleted,
349                inserted: String::new(),
350                cursor_before,
351                cursor_after: at,
352            },
353            None,
354        );
355        true
356    }
357
358    /// Backspace/Delete (plain or word): selects via `motion`, deletes as a
359    /// recorded op. False at the buffer boundary (nothing to delete).
360    fn delete_motion_recorded(
361        &mut self,
362        motion: Motion,
363        kind: Coalesce,
364        fs: &mut FontSystem,
365    ) -> bool {
366        let cursor_before = self.editor.cursor();
367        self.editor.set_selection(Selection::Normal(cursor_before));
368        self.editor.action(fs, Action::Motion(motion));
369        let deleted = self.editor.copy_selection().unwrap_or_default();
370        if deleted.is_empty() {
371            self.editor.set_selection(Selection::None);
372            return false;
373        }
374        self.editor.delete_selection();
375        let at = self.editor.cursor();
376        self.record(
377            EditOp {
378                at,
379                deleted,
380                inserted: String::new(),
381                cursor_before,
382                cursor_after: at,
383            },
384            Some(kind),
385        );
386        true
387    }
388
389    /// Removes an in-progress composition from the buffer (cancel, blur,
390    /// or anything that must act on committed text only), leaving the
391    /// caret where the composition began. Unrecorded, like its insertion.
392    fn abandon_preedit(&mut self) -> bool {
393        let Some(pre) = self.preedit.take() else {
394            return false;
395        };
396        self.splice(pre.start, &pre.text, "");
397        self.editor.set_cursor(pre.start);
398        self.editor.set_selection(Selection::None);
399        true
400    }
401
402    fn undo_one(&mut self) -> bool {
403        let Some(op) = self.undo.pop_back() else {
404            return false;
405        };
406        self.splice(op.at, &op.inserted, &op.deleted);
407        self.editor.set_cursor(op.cursor_before);
408        self.editor.set_selection(Selection::None);
409        self.redo.push_back(op);
410        self.coalesce = None;
411        true
412    }
413
414    fn redo_one(&mut self) -> bool {
415        let Some(op) = self.redo.pop_back() else {
416            return false;
417        };
418        self.splice(op.at, &op.deleted, &op.inserted);
419        self.editor.set_cursor(op.cursor_after);
420        self.editor.set_selection(Selection::None);
421        self.undo.push_back(op);
422        self.coalesce = None;
423        true
424    }
425}
426
427/// A held `set_edit_text` the frame after it did not claim, in whichever
428/// spelling the call used — the two name the same mistake and raise the
429/// same code, but a warning that says "key" for a call that said "label"
430/// sends its reader looking in the wrong place.
431pub(crate) enum Unclaimed {
432    Key(Key),
433    Label(String),
434}
435
436/// The retained editors of one window, owned by `Core`. Reach it through
437/// `Ui::text_edit`, `Core::edit_text` and `Core::set_edit_text` rather
438/// than directly.
439pub struct EditStore {
440    states: FxHashMap<Key, EditState>,
441    /// Text set for a key nothing has declared yet: `set_text` holds it
442    /// here and the next `declare` under that key seeds with it instead of
443    /// with `initial`. An `update` that opens an editor and sets its text
444    /// in the same turn runs a frame ahead of the view that declares it,
445    /// so without this the call lands on nothing and the app sees the
446    /// editor open with `initial`. What the frame after it
447    /// does not claim is dropped by `finish_frame`, with a warning.
448    pending: FxHashMap<Key, String>,
449    /// The same seed named by label instead of by key, for the app that
450    /// has no key to give: the hex key comes from an event the node
451    /// fired, and an editor a rename is opening for the first time has
452    /// fired none. Held until `text_edit` declares an
453    /// editor under the label and claims it — which is also where a
454    /// *retained* editor is reached, since a key kept off screen (F20,
455    /// F26) has a state `declare` would not reseed and a label
456    /// `Core::key_of` cannot resolve while it goes undeclared.
457    pending_labels: FxHashMap<String, String>,
458    pub(crate) focused: Option<Key>,
459    /// Edit node being drag-selected (with its content origin, logical).
460    pub(crate) dragging: Option<(Key, Vec2)>,
461    /// Edit whose caret moved since the last frame; `finish_frame` scrolls
462    /// the nearest scrollable ancestor to keep the caret visible, then clears.
463    pub(crate) caret_moved: Option<Key>,
464    /// Bumped on anything that should restart the caret blink cycle (edits,
465    /// motion, clicks, focus changes). Frame drivers watch it to re-arm
466    /// their blink timer — the core itself stays clock-free.
467    caret_stamp: u64,
468    /// Whether the caret is currently drawn; toggled by the frame driver's
469    /// blink timer. Headless drivers never touch it, so the caret is solid.
470    blink_visible: bool,
471    /// The frame being built, stamped onto every state `declare` touches.
472    frame_no: u64,
473}
474
475impl Default for EditStore {
476    fn default() -> Self {
477        Self {
478            states: FxHashMap::default(),
479            pending: FxHashMap::default(),
480            pending_labels: FxHashMap::default(),
481            focused: None,
482            dragging: None,
483            caret_moved: None,
484            caret_stamp: 0,
485            blink_visible: true,
486            frame_no: 0,
487        }
488    }
489}
490
491/// What an editor's buffer may hold: a field is one line, so a newline that
492/// arrived in a seed or a `set_text` is dropped rather than drawn below a
493/// box measured for one line. The same rule `apply_text` applies to
494/// typing and pasting, so the two doors agree.
495fn admitted(text: &str, multiline: bool) -> std::borrow::Cow<'_, str> {
496    if multiline || !text.contains(['\n', '\r']) {
497        return std::borrow::Cow::Borrowed(text);
498    }
499    std::borrow::Cow::Owned(text.chars().filter(|c| *c != '\n' && *c != '\r').collect())
500}
501
502/// At the family's regular weight, or its bold for a bold style, as
503/// text draws it.
504fn attrs_for<'a>(style: &TextStyle, res: &'a Resources) -> Attrs<'a> {
505    res.weights_of(style.family).apply(
506        Attrs::new()
507            .family(res.family_of(style.family))
508            .font_features(crate::text::cosmic_features(&style.features)),
509        style.bold,
510    )
511}
512
513impl EditStore {
514    /// Gives every editor's text the weights its family is asked at now:
515    /// a face of a registered family came or went. The text,
516    /// caret and history stay; every line shapes again, and every
517    /// measurement of it is of the old weights. Whether or not a line's
518    /// attributes moved: a new fallback list (`set_fallback_fonts`)
519    /// changes the faces a line is shaped in and none of its attributes
520    /// (RG114).
521    pub(crate) fn reweigh(&mut self, res: &Resources) {
522        for s in self.states.values_mut() {
523            let a = AttrsList::new(&attrs_for(&s.style, res));
524            s.editor.with_buffer_mut(|b| {
525                for line in &mut b.lines {
526                    line.set_attrs_list(a.clone());
527                    line.reset_shaping();
528                }
529            });
530            s.editor.set_redraw(true);
531            s.wrap = None;
532            s.metrics_rev = s.metrics_rev.wrapping_add(1);
533            s.invalidate_measurements();
534        }
535    }
536
537    pub fn focused(&self) -> Option<Key> {
538        self.focused
539    }
540
541    pub fn set_focus(&mut self, key: Option<Key>) {
542        if self.focused != key {
543            self.caret_stamp += 1;
544            // A blurred editor abandons any in-progress composition.
545            if let Some(old) = self.focused
546                && let Some(s) = self.states.get_mut(&old)
547                && s.abandon_preedit()
548            {
549                s.version += 1;
550                s.invalidate_measurements();
551            }
552        }
553        self.focused = key;
554    }
555
556    /// See `caret_stamp` field: compare across frames to restart blink.
557    pub fn caret_stamp(&self) -> u64 {
558        self.caret_stamp
559    }
560
561    /// Blink-phase toggle for frame drivers; `true` draws the caret.
562    pub fn set_blink_visible(&mut self, visible: bool) {
563        self.blink_visible = visible;
564    }
565
566    /// The phase as last set; `true` draws the caret.
567    pub fn blink_visible(&self) -> bool {
568        self.blink_visible
569    }
570
571    fn touch_caret(&mut self, key: Key) {
572        self.caret_moved = Some(key);
573        self.caret_stamp += 1;
574    }
575
576    /// How many states are retained — declared and undeclared together.
577    /// What a test watches the budget through.
578    pub fn len(&self) -> usize {
579        self.states.len()
580    }
581
582    pub fn is_empty(&self) -> bool {
583        self.states.is_empty()
584    }
585
586    /// Stamps the frame being built and, if the map has grown past the
587    /// budget, drops the longest-undeclared states
588    /// ([`MAX_UNDECLARED_EDITS`]). A state the frame that just ended
589    /// declared is never evicted, and neither is the focused or the
590    /// drag-selected one — the store still points at those.
591    ///
592    /// The length test is what an ordinary frame pays: a store inside the
593    /// budget never walks itself, which is why this can run every frame
594    /// rather than every 240th like the anim store's cutoff sweep.
595    pub(crate) fn begin_frame(&mut self, frame_no: u64) {
596        self.frame_no = frame_no;
597        if self.states.len() > MAX_UNDECLARED_EDITS {
598            self.evict(frame_no.saturating_sub(1));
599        }
600    }
601
602    /// Drops the oldest undeclared states down to the budget. `declared_at`
603    /// is the frame that just ended: a state stamped with it is declared.
604    fn evict(&mut self, declared_at: u64) {
605        let focused = self.focused;
606        let dragging = self.dragging.map(|(k, _)| k);
607        let caret_moved = &mut self.caret_moved;
608        crate::retain::evict_undeclared(
609            &mut self.states,
610            MAX_UNDECLARED_EDITS,
611            declared_at,
612            |s| s.last_declared,
613            |k| Some(k) == focused || Some(k) == dragging,
614            |k| {
615                if *caret_moved == Some(k) {
616                    *caret_moved = None;
617                }
618            },
619        );
620    }
621
622    /// Ensures state exists for `key`, seeding `initial` on first creation
623    /// — or, if a `set_text` for this key arrived before anything declared
624    /// it, that text instead (see [`EditStore::pending`]). Returns whether
625    /// this declaration is an *autofocus edge*: the key was not declared
626    /// with `autofocus` on the frame before this one — a new editor, one
627    /// back after a gap, or one whose `autofocus` just turned on — which
628    /// is the one frame the flag may act on.
629    #[allow(clippy::too_many_arguments)]
630    pub(crate) fn declare(
631        &mut self,
632        key: Key,
633        initial: &str,
634        opts: &EditOptions,
635        origin: OriginId,
636        scale: f32,
637        fs: &mut FontSystem,
638        res: &Resources,
639    ) -> bool {
640        let frame_no = self.frame_no;
641        let edge = self
642            .states
643            .get(&key)
644            .is_none_or(|s| s.last_declared + 1 != frame_no || !s.autofocus);
645        // Only a creation consumes the seed: a key already declared has
646        // no pending text (a `set_text` with state behind it is applied
647        // where it is called), and taking one here would drop it.
648        let seed = if self.states.contains_key(&key) {
649            None
650        } else {
651            self.pending.remove(&key)
652        };
653        let seeded = seed.is_some();
654        let initial = seed.as_deref().unwrap_or(initial);
655        let state = self.states.entry(key).or_insert_with(|| {
656            let metrics = crate::text::shaper_metrics(
657                opts.style.size * scale,
658                opts.style.line_height * scale,
659            );
660            let mut buffer = Buffer::new(fs, metrics);
661            buffer.set_size(None, None);
662            buffer.set_text(
663                &admitted(initial, opts.multiline),
664                &attrs_for(&opts.style, res),
665                Shaping::Advanced,
666                None,
667            );
668            let mut editor = Editor::new(buffer);
669            // A single-line field opens with the caret after its seeded
670            // text — what a native field does with a prefilled value, and
671            // what a rename wants, since typing into a name meant to be
672            // extended otherwise prepends to it. A multiline
673            // editor is a document and opens at its top, as native text
674            // views do. Placed, not moved: no `touch_caret`, so nothing
675            // scrolls to reveal it before the user has touched it.
676            //
677            // A held `set_text` is not `initial`: it is that call arriving
678            // where it can land, so it leaves the caret where the call
679            // does — at the end, document or not.
680            if seeded || !opts.multiline {
681                let end = editor.with_buffer(|b| {
682                    let line = b.lines.len().saturating_sub(1);
683                    Cursor::new(line, b.lines.get(line).map_or(0, |l| l.text().len()))
684                });
685                editor.set_cursor(end);
686            }
687            EditState {
688                editor,
689                style: opts.style,
690                accent: opts.accent.unwrap_or(crate::select::TINT),
691                multiline: opts.multiline,
692                keep_tab: opts.keep_tab,
693                placeholder: None,
694                folds: false,
695                origin,
696                scale,
697                wrap: None,
698                version: 0,
699                metrics_rev: 0,
700                measured: None,
701                natural: None,
702                offset_x: 0.0,
703                preedit: None,
704                undo: VecDeque::new(),
705                redo: VecDeque::new(),
706                coalesce: None,
707                autofocus: false,
708                last_declared: frame_no,
709            }
710        });
711        state.last_declared = frame_no;
712        state.autofocus = opts.autofocus;
713        state.origin = origin;
714        state.multiline = opts.multiline;
715        state.keep_tab = opts.keep_tab;
716        state.accent = opts.accent.unwrap_or(crate::select::TINT);
717        // A document wraps between words whatever its style says, as it
718        // always has; a field folds only when asked, and then by the mode
719        // the `wrap` row picked — so a rename field breaks where the label
720        // it renames breaks. `wrap="none"` on a field is the
721        // field: one line, scrolled.
722        let folds = opts.multiline || (opts.wrap && opts.style.wrap != TextWrap::None);
723        let mode = match (opts.multiline, opts.style.wrap) {
724            (false, TextWrap::Glyph) => Wrap::Glyph,
725            _ => Wrap::WordOrGlyph,
726        };
727        if state.folds != folds || state.editor.with_buffer(|b| b.wrap()) != mode {
728            state.folds = folds;
729            state.editor.with_buffer_mut(|b| b.set_wrap(mode));
730            state.invalidate_measurements();
731        }
732        // Style/scale changes re-metric the buffer (text and cursor survive).
733        // The text is the same, so `version` does not move — but every
734        // measurement of it is now of the wrong font, which is what
735        // `metrics_rev` is for: without it a cache keyed on the text alone
736        // answers the new frame with the old size.
737        if state.scale != scale || state.style != opts.style {
738            state.style = opts.style;
739            state.scale = scale;
740            let metrics = crate::text::shaper_metrics(
741                opts.style.size * scale,
742                opts.style.line_height * scale,
743            );
744            state.editor.with_buffer_mut(|b| b.set_metrics(metrics));
745            state.wrap = None;
746            state.metrics_rev = state.metrics_rev.wrapping_add(1);
747            state.invalidate_measurements();
748        }
749        // The placeholder, shaped again only when its text or the
750        // editor's metrics moved.
751        match opts.placeholder.as_deref().filter(|p| !p.is_empty()) {
752            None => state.placeholder = None,
753            Some(p) => {
754                let rev = state.metrics_rev;
755                if state
756                    .placeholder
757                    .as_ref()
758                    .is_none_or(|(t, r, _)| t != p || *r != rev)
759                {
760                    let metrics = state.editor.with_buffer(|b| b.metrics());
761                    let mut b = Buffer::new(fs, metrics);
762                    b.set_size(None, None);
763                    b.set_text(p, &attrs_for(&opts.style, res), Shaping::Advanced, None);
764                    b.shape_until_scroll(fs, false);
765                    state.placeholder = Some((p.to_string(), rev, b));
766                }
767            }
768        }
769        // `autofocus` is the core's decision (it owns the one focus).
770        edge
771    }
772
773    /// The placeholder `key` was declared with, if any.
774    pub fn placeholder(&self, key: Key) -> Option<&str> {
775        let s = self.states.get(&key)?;
776        s.placeholder.as_ref().map(|(t, ..)| t.as_str())
777    }
778
779    pub fn contains(&self, key: Key) -> bool {
780        self.states.contains_key(&key)
781    }
782
783    pub fn origin_of(&self, key: Key) -> Option<OriginId> {
784        self.states.get(&key).map(|s| s.origin)
785    }
786
787    /// The committed text: an in-progress composition is not part of it.
788    pub fn text(&self, key: Key) -> Option<String> {
789        let s = self.states.get(&key)?;
790        Some(s.editor.with_buffer(|b| {
791            let mut text = buffer_text(b);
792            if let Some(pre) = &s.preedit {
793                let at = abs_offset(b, pre.start);
794                if text.is_char_boundary(at) && at + pre.text.len() <= text.len() {
795                    text.replace_range(at..at + pre.text.len(), "");
796                }
797            }
798            text
799        }))
800    }
801
802    /// Returns whether the text landed in an editor: `false` says it was
803    /// held for the frame that declares the key, so nothing on screen
804    /// changed yet and the frame that will change it is the app's — a
805    /// driver that redraws on every write would re-lower the tree that
806    /// declares no editor and drop the seed to the warning.
807    pub fn set_text(&mut self, key: Key, text: &str, fs: &mut FontSystem, res: &Resources) -> bool {
808        let Some(s) = self.states.get_mut(&key) else {
809            // Nothing has declared this key yet. The call is not wrong —
810            // the `update` that opens an editor runs before the view that
811            // declares it — so hold the text for the frame that does
812            // rather than falling through silently.
813            self.pending.insert(key, text.to_string());
814            return false;
815        };
816        s.preedit = None;
817        let a = attrs_for(&s.style, res);
818        let text = admitted(text, s.multiline);
819        s.editor
820            .with_buffer_mut(|b| b.set_text(&text, &a, Shaping::Advanced, None));
821        s.editor.set_selection(Selection::None);
822        s.editor.action(fs, Action::Motion(Motion::BufferEnd));
823        s.version += 1;
824        s.invalidate_measurements();
825        s.wrap = None;
826        // A wholesale replacement invalidates the recorded deltas.
827        s.undo.clear();
828        s.redo.clear();
829        s.coalesce = None;
830        self.touch_caret(key);
831        true
832    }
833
834    /// Holds `text` for the next editor declared under `label`, for a
835    /// `set_edit_text` by a name nothing has declared yet.
836    /// The key path is [`EditStore::pending`]; this one is claimed by
837    /// [`EditStore::claim_label`] from inside the build, where the label
838    /// and the key it resolves to are both in hand.
839    pub(crate) fn hold_label(&mut self, label: &str, text: &str) {
840        self.pending_labels
841            .insert(label.to_string(), text.to_string());
842    }
843
844    /// A declaring editor takes the seed held for its label, if there is
845    /// one. Two shapes, and the second is the one a seed by key cannot
846    /// have: a *new* editor takes it as `declare` takes a pending key,
847    /// over `initial`; an editor that already has a state — retained
848    /// while its key was off screen — takes it as `set_text`, since
849    /// `declare` reseeds nothing that exists and the draft would
850    /// otherwise come back over the model's text.
851    pub(crate) fn claim_label(
852        &mut self,
853        key: Key,
854        label: &str,
855        fs: &mut FontSystem,
856        res: &Resources,
857    ) {
858        if self.pending_labels.is_empty() {
859            return;
860        }
861        let Some(text) = self.pending_labels.remove(label) else {
862            return;
863        };
864        if self.states.contains_key(&key) {
865            self.set_text(key, &text, fs, res);
866        } else {
867            self.pending.insert(key, text);
868        }
869    }
870
871    /// The seeds no frame claimed, dropped: `finish_frame` drains this
872    /// after the build and raises [`crate::diag::EDIT_TEXT_WITHOUT_EDITOR`]
873    /// for each, so a `set_edit_text` on a key — or a label — the view
874    /// never declares is a line rather than nothing at all. Sorted within
875    /// each spelling, so the order two unclaimed seeds are reported in
876    /// does not depend on a hash seed.
877    pub(crate) fn take_unclaimed_seeds(&mut self) -> Vec<Unclaimed> {
878        let mut out: Vec<Unclaimed> = Vec::new();
879        if !self.pending.is_empty() {
880            let mut keys: Vec<Key> = self.pending.drain().map(|(k, _)| k).collect();
881            keys.sort_unstable();
882            out.extend(keys.into_iter().map(Unclaimed::Key));
883        }
884        if !self.pending_labels.is_empty() {
885            let mut labels: Vec<String> = self.pending_labels.drain().map(|(l, _)| l).collect();
886            labels.sort_unstable();
887            out.extend(labels.into_iter().map(Unclaimed::Label));
888        }
889        out
890    }
891
892    pub fn version(&self, key: Key) -> u64 {
893        self.states.get(&key).map_or(0, |s| s.version)
894    }
895
896    /// The caret as a byte offset into the committed text, and the
897    /// non-empty selection as a byte range, for the access tree.
898    pub fn caret_and_selection(&self, key: Key) -> Option<(usize, Option<(usize, usize)>)> {
899        let s = self.states.get(&key)?;
900        Some(s.editor.with_buffer(|b| {
901            let caret = abs_offset(b, s.editor.cursor());
902            let selection = s
903                .editor
904                .selection_bounds()
905                .map(|(a, z)| (abs_offset(b, a), abs_offset(b, z)))
906                .filter(|(a, z)| a != z);
907            (caret, selection)
908        }))
909    }
910
911    /// The selection's anchor and the caret as (line, byte index) pairs
912    /// (equal without a selection), for the access tree.
913    pub fn selection_cursors(&self, key: Key) -> Option<((usize, usize), (usize, usize))> {
914        let s = self.states.get(&key)?;
915        let caret = s.editor.cursor();
916        let anchor = match s.editor.selection() {
917            Selection::Normal(c) | Selection::Line(c) | Selection::Word(c) => c,
918            Selection::None => caret,
919        };
920        Some(((anchor.line, anchor.index), (caret.line, caret.index)))
921    }
922
923    /// The editor's laid-out lines as access runs (see
924    /// [`crate::access::AccessRun`]); `origin` is where the content box
925    /// starts, logical px.
926    pub(crate) fn runs(
927        &self,
928        key: Key,
929        node: Key,
930        origin: Vec2,
931        scale: f32,
932    ) -> Vec<crate::access::AccessRun> {
933        let Some(s) = self.states.get(&key) else {
934            return Vec::new();
935        };
936        let mut out = Vec::new();
937        let mut n = 0;
938        // Where the glyphs are, not where they would be unscrolled: a
939        // screen reader's character rects have to land on the pixels
940        // emission drew (a scrolled field, F41).
941        let origin = Vec2::new(origin.x - s.offset_x, origin.y);
942        s.editor.with_buffer(|b| {
943            crate::access::runs_of_buffer(
944                b,
945                crate::access::RunSource {
946                    key: node,
947                    line: 0,
948                    byte_base: 0,
949                    origin,
950                    scale,
951                    newline_after_last: false,
952                },
953                &mut n,
954                &mut out,
955            )
956        });
957        out
958    }
959
960    /// Moves the caret to `focus` and the selection's other end to
961    /// `anchor`, both (line, byte index) pairs clamped into the text; equal
962    /// pairs clear the selection. What a screen reader's "select from here
963    /// to there" becomes.
964    pub fn set_selection(&mut self, key: Key, anchor: (usize, usize), focus: (usize, usize)) {
965        let Some(s) = self.states.get_mut(&key) else {
966            return;
967        };
968        s.abandon_preedit();
969        let clamp = |b: &Buffer, (line, index): (usize, usize)| {
970            let line = line.min(b.lines.len().saturating_sub(1));
971            let text = b.lines[line].text();
972            let mut index = index.min(text.len());
973            while !text.is_char_boundary(index) {
974                index -= 1;
975            }
976            Cursor::new(line, index)
977        };
978        let (a, f) = s
979            .editor
980            .with_buffer(|b| (clamp(b, anchor), clamp(b, focus)));
981        s.editor.set_cursor(f);
982        s.editor.set_selection(if a == f {
983            Selection::None
984        } else {
985            Selection::Normal(a)
986        });
987        s.break_coalesce();
988        self.touch_caret(key);
989    }
990
991    /// Types `text` over the selection (or at the caret), as one undo
992    /// step; true when the content changed.
993    pub fn replace_selection(&mut self, key: Key, text: &str, fs: &mut FontSystem) -> bool {
994        let Some(s) = self.states.get_mut(&key) else {
995            return false;
996        };
997        s.abandon_preedit();
998        if text.is_empty() && s.editor.selection_bounds().is_none() {
999            return false;
1000        }
1001        s.insert_recorded(text);
1002        s.editor.shape_as_needed(fs, false);
1003        s.version += 1;
1004        s.invalidate_measurements();
1005        self.touch_caret(key);
1006        true
1007    }
1008
1009    pub fn copy_selection(&self, key: Key) -> Option<String> {
1010        self.states.get(&key)?.editor.copy_selection()
1011    }
1012
1013    /// Whether the editor `key` has a non-empty selection — what
1014    /// `copy_selection` would answer, without building the string. A
1015    /// menu asking whether Copy applies asks this every time it opens.
1016    pub fn has_selection(&self, key: Key) -> bool {
1017        self.states
1018            .get(&key)
1019            .and_then(|s| s.editor.selection_bounds())
1020            .is_some_and(|(a, b)| a != b)
1021    }
1022
1023    /// Whether the editor `key` has an edit to undo, and one to redo.
1024    pub fn history(&self, key: Key) -> (bool, bool) {
1025        self.states
1026            .get(&key)
1027            .map_or((false, false), |s| (!s.undo.is_empty(), !s.redo.is_empty()))
1028    }
1029
1030    /// Deletes the selection; returns true if anything was deleted.
1031    pub fn delete_selection(&mut self, key: Key, fs: &mut FontSystem) -> bool {
1032        let Some(s) = self.states.get_mut(&key) else {
1033            return false;
1034        };
1035        let _ = fs;
1036        s.abandon_preedit();
1037        if s.delete_selection_recorded() {
1038            s.version += 1;
1039            s.invalidate_measurements();
1040            self.touch_caret(key);
1041            true
1042        } else {
1043            false
1044        }
1045    }
1046
1047    // -- Input application (focused editor). Returns true if content changed.
1048
1049    pub(crate) fn apply_text(&mut self, key: Key, text: &str, fs: &mut FontSystem) -> bool {
1050        let Some(s) = self.states.get_mut(&key) else {
1051            return false;
1052        };
1053        // A commit ends the composition (winit also clears preedit first);
1054        // the committed text goes in where the composition began.
1055        s.abandon_preedit();
1056        let filtered: String = text
1057            .chars()
1058            .filter(|c| !c.is_control() || (*c == '\n' && s.multiline) || *c == '\t')
1059            .collect();
1060        if filtered.is_empty() {
1061            return false;
1062        }
1063        s.insert_recorded(&filtered);
1064        s.editor.shape_as_needed(fs, false);
1065        s.version += 1;
1066        s.invalidate_measurements();
1067        self.touch_caret(key);
1068        true
1069    }
1070
1071    /// Returns (content_changed, submit) — submit is Enter in single-line.
1072    pub(crate) fn apply_key(
1073        &mut self,
1074        key: Key,
1075        ek: EditKey,
1076        mods: Mods,
1077        fs: &mut FontSystem,
1078    ) -> KeyOutcome {
1079        let Some(s) = self.states.get_mut(&key) else {
1080            return KeyOutcome::default();
1081        };
1082        // Keys reaching the editor mid-composition mean the IME let them
1083        // through; act on committed text only.
1084        let mut changed = s.abandon_preedit();
1085        let mut submit = false;
1086        // Where the caret was, to tell a key that moved or deleted nothing
1087        // — the caret at an edge of the text — from one that did.
1088        let at = |e: &Editor<'static>| (e.cursor().line, e.cursor().index);
1089        let before = (at(&s.editor), s.editor.selection());
1090        // The visual line the caret is on, for ↑ and ↓: on the first or
1091        // last one the motion moves the caret along it (to an end of the
1092        // text) but not off it, and that is the edge.
1093        let row = |e: &Editor<'static>| e.cursor_position().map(|(_, y)| y);
1094        let row_before = row(&s.editor);
1095        let composing = changed;
1096        // ↑ and ↓ by paragraphs: an edge only where they could not move.
1097        let mut by_paragraph = false;
1098        match ek {
1099            EditKey::Left
1100            | EditKey::Right
1101            | EditKey::Up
1102            | EditKey::Down
1103            | EditKey::Home
1104            | EditKey::End
1105            | EditKey::PageUp
1106            | EditKey::PageDown => {
1107                // What the modifiers mean is each platform's fields'. On
1108                // a Mac ⌥ moves by words, and ⌥↑ ⌥↓ by paragraphs; ⌘ to
1109                // the line's ends, and ⌘↑ ⌘↓ to the text's. Elsewhere Ctrl
1110                // moves by words, and Ctrl+↑ Ctrl+↓ by paragraphs; Alt
1111                // stays a word, as it was here before.
1112                let mac = cfg!(target_os = "macos");
1113                let word = mods.word || (!mac && mods.doc);
1114                let line = mac && mods.doc;
1115                let motion = match (ek, line, word) {
1116                    (EditKey::Left, true, _) => Motion::Home,
1117                    (EditKey::Right, true, _) => Motion::End,
1118                    (EditKey::Up, true, _) => Motion::BufferStart,
1119                    (EditKey::Down, true, _) => Motion::BufferEnd,
1120                    (EditKey::Left, _, true) => Motion::LeftWord,
1121                    (EditKey::Right, _, true) => Motion::RightWord,
1122                    (EditKey::Up, _, true) => Motion::ParagraphStart,
1123                    (EditKey::Down, _, true) => Motion::ParagraphEnd,
1124                    (EditKey::Left, ..) => Motion::Left,
1125                    (EditKey::Right, ..) => Motion::Right,
1126                    (EditKey::Up, ..) => Motion::Up,
1127                    (EditKey::Down, ..) => Motion::Down,
1128                    (EditKey::Home, ..) if mods.doc => Motion::BufferStart,
1129                    (EditKey::End, ..) if mods.doc => Motion::BufferEnd,
1130                    (EditKey::Home, ..) => Motion::Home,
1131                    (EditKey::End, ..) => Motion::End,
1132                    (EditKey::PageUp, ..) => Motion::PageUp,
1133                    (EditKey::PageDown, ..) => Motion::PageDown,
1134                    _ => unreachable!(),
1135                };
1136                if mods.shift {
1137                    if s.editor.selection() == Selection::None {
1138                        s.editor.set_selection(Selection::Normal(s.editor.cursor()));
1139                    }
1140                } else {
1141                    s.editor.set_selection(Selection::None);
1142                }
1143                // A paragraph's start or end the caret is already at: the
1144                // one before or after, as a Mac's ⌥↑ ⌥↓ go on.
1145                by_paragraph = matches!(motion, Motion::ParagraphStart | Motion::ParagraphEnd);
1146                if by_paragraph {
1147                    let c = s.editor.cursor();
1148                    let len = s
1149                        .editor
1150                        .with_buffer(|b| b.lines.get(c.line).map_or(0, |l| l.text().len()));
1151                    let last = s.editor.with_buffer(|b| b.lines.len().saturating_sub(1));
1152                    if motion == Motion::ParagraphStart && c.index == 0 && c.line > 0 {
1153                        s.editor.action(fs, Action::Motion(Motion::Previous));
1154                    } else if motion == Motion::ParagraphEnd && c.index >= len && c.line < last {
1155                        s.editor.action(fs, Action::Motion(Motion::Next));
1156                    }
1157                }
1158                s.editor.action(fs, Action::Motion(motion));
1159                s.break_coalesce();
1160            }
1161            EditKey::Backspace | EditKey::Delete => {
1162                // ⌘⌫ on a Mac takes the line back to its start and ⌘⌦ on
1163                // to its end, as AppKit's fields do; elsewhere the primary
1164                // modifier is Ctrl, and Ctrl+Backspace takes a word, as
1165                // Windows' and GTK's fields do.
1166                let (line, word) = if cfg!(target_os = "macos") {
1167                    (mods.doc, mods.word)
1168                } else {
1169                    (false, mods.word || mods.doc)
1170                };
1171                let back = ek == EditKey::Backspace;
1172                let motion = match (back, line, word) {
1173                    (true, true, _) => Motion::Home,
1174                    (true, _, true) => Motion::LeftWord,
1175                    (true, ..) => Motion::Left,
1176                    (false, true, _) => Motion::End,
1177                    (false, _, true) => Motion::RightWord,
1178                    (false, ..) => Motion::Right,
1179                };
1180                let kind = if back {
1181                    Coalesce::Backspace
1182                } else {
1183                    Coalesce::Delete
1184                };
1185                changed |=
1186                    s.delete_selection_recorded() || s.delete_motion_recorded(motion, kind, fs);
1187            }
1188            EditKey::Enter => {
1189                if s.multiline {
1190                    s.insert_recorded("\n");
1191                    changed = true;
1192                } else {
1193                    submit = true;
1194                }
1195            }
1196            EditKey::Tab => {
1197                if s.multiline {
1198                    s.insert_recorded("    ");
1199                    changed = true;
1200                }
1201            }
1202            EditKey::Undo => changed |= s.undo_one(),
1203            EditKey::Redo => changed |= s.redo_one(),
1204            EditKey::SelectAll => {
1205                s.editor.action(fs, Action::Motion(Motion::BufferStart));
1206                s.editor.set_selection(Selection::Normal(s.editor.cursor()));
1207                s.editor.action(fs, Action::Motion(Motion::BufferEnd));
1208                s.break_coalesce();
1209            }
1210            EditKey::Escape => {
1211                s.editor.action(fs, Action::Escape);
1212                s.break_coalesce();
1213            }
1214        }
1215        s.editor.shape_as_needed(fs, false);
1216        // A key the editor holds but could not act on (backlog F145): an
1217        // arrow, Backspace or Delete that left the caret where it was and
1218        // changed nothing, from a caret with no selection — the caret was
1219        // at the edge of the text the key moves toward. Not under Shift,
1220        // which extends a selection and has no edge to report, nor
1221        // mid-composition, whose key the IME let through.
1222        let plain = !changed && !composing && !mods.shift && before.1 == Selection::None;
1223        let still = plain && (at(&s.editor), s.editor.selection()) == before;
1224        // ↑ and ↓ meet the edge when they leave the caret on its visual
1225        // line, wherever along it they moved it: a field's ↓ from the
1226        // middle of its one line is the end of the field, not a caret
1227        // walked to the end first and an edge on the second press.
1228        let same_row = plain && row_before.is_some() && row(&s.editor) == row_before;
1229        let boundary = match ek {
1230            EditKey::Up if by_paragraph && still => Some(Edge::Start),
1231            EditKey::Down if by_paragraph && still => Some(Edge::End),
1232            EditKey::Up | EditKey::Down if by_paragraph => None,
1233            EditKey::Up if same_row => Some(Edge::Start),
1234            EditKey::Down if same_row => Some(Edge::End),
1235            EditKey::Left | EditKey::Backspace if still => Some(Edge::Start),
1236            EditKey::Right | EditKey::Delete if still => Some(Edge::End),
1237            _ => None,
1238        };
1239        if changed {
1240            s.version += 1;
1241            s.invalidate_measurements();
1242        }
1243        self.touch_caret(key);
1244        KeyOutcome {
1245            changed,
1246            submit,
1247            boundary,
1248        }
1249    }
1250
1251    /// Mouse press inside the edit at content-local logical position.
1252    /// `clicks` is the driver-counted multi-click: 2 selects the word,
1253    /// 3 the line (cosmic-text's double/triple click actions). With
1254    /// `extend` — a Shift-press — the caret moves there keeping the
1255    /// selection's anchor, seeding one at the caret when there is none
1256    /// (cosmic-text's `Drag` does both), and the
1257    /// click count says nothing. Either way it is a click: a live
1258    /// composition is abandoned and the next edit starts an undo unit.
1259    pub(crate) fn click(
1260        &mut self,
1261        key: Key,
1262        local: Vec2,
1263        clicks: u8,
1264        extend: bool,
1265        fs: &mut FontSystem,
1266    ) {
1267        if let Some(s) = self.states.get_mut(&key) {
1268            if s.abandon_preedit() {
1269                s.version += 1;
1270                s.invalidate_measurements();
1271            }
1272            let (x, y) = ((local.x * s.scale) as i32, (local.y * s.scale) as i32);
1273            let action = match (extend, clicks) {
1274                (true, _) => Action::Drag { x, y },
1275                (false, 0 | 1) => Action::Click { x, y },
1276                (false, 2) => Action::DoubleClick { x, y },
1277                (false, _) => Action::TripleClick { x, y },
1278            };
1279            s.editor.action(fs, action);
1280            s.editor.shape_as_needed(fs, false);
1281            s.break_coalesce();
1282            self.caret_stamp += 1;
1283        }
1284    }
1285
1286    /// Mouse motion with the button held: moves the caret to the point
1287    /// and keeps the selection's anchor (seeding one at the caret when
1288    /// there is none — cosmic-text's `Drag` does both). The caret moved,
1289    /// so it is marked like a keyboard motion's: a field scrolls its own
1290    /// text toward the drag at once, and a scroller above a document
1291    /// reveals the caret on the release — not under the held pointer,
1292    /// where the drag's own rate is what moves it
1293    /// (`scroll_caret_into_view`).
1294    pub(crate) fn drag(&mut self, key: Key, local: Vec2, fs: &mut FontSystem) {
1295        if let Some(s) = self.states.get_mut(&key) {
1296            let (x, y) = ((local.x * s.scale) as i32, (local.y * s.scale) as i32);
1297            let before = s.editor.cursor();
1298            s.editor.action(fs, Action::Drag { x, y });
1299            if s.editor.cursor() != before {
1300                self.touch_caret(key);
1301            } else {
1302                self.caret_stamp += 1;
1303            }
1304        }
1305    }
1306
1307    /// Replaces the focused editor's IME composition. The text lives in
1308    /// the buffer from the moment it appears — following text shifts and
1309    /// the paragraph rewraps — but never in the undo history; the caret
1310    /// sits at the IME-reported offset inside it. Empty text cancels
1311    /// (winit sends that before every commit). Returns true if anything
1312    /// visible changed.
1313    pub(crate) fn set_preedit(
1314        &mut self,
1315        key: Key,
1316        text: &str,
1317        cursor: Option<(usize, usize)>,
1318        fs: &mut FontSystem,
1319    ) -> bool {
1320        let Some(s) = self.states.get_mut(&key) else {
1321            return false;
1322        };
1323        if text.is_empty() {
1324            if !s.abandon_preedit() {
1325                return false;
1326            }
1327        } else {
1328            let start = match s.preedit.take() {
1329                Some(pre) => {
1330                    s.splice(pre.start, &pre.text, text);
1331                    pre.start
1332                }
1333                None => {
1334                    // Composing over a selection replaces it, as typing
1335                    // would — that part is a real, recorded edit.
1336                    s.delete_selection_recorded();
1337                    let at = s.editor.cursor();
1338                    s.editor.insert_string(text, None);
1339                    at
1340                }
1341            };
1342            // Caret at the IME's offset inside the composition (its end
1343            // when unreported), clamped to a char boundary.
1344            let mut at = cursor.map_or(text.len(), |(c, _)| c.min(text.len()));
1345            while at > 0 && !text.is_char_boundary(at) {
1346                at -= 1;
1347            }
1348            s.editor.set_cursor(end_cursor(start, &text[..at]));
1349            s.editor.set_selection(Selection::None);
1350            s.preedit = Some(Preedit {
1351                start,
1352                text: text.to_string(),
1353            });
1354            s.break_coalesce();
1355        }
1356        s.editor.shape_as_needed(fs, false);
1357        s.version += 1;
1358        s.invalidate_measurements();
1359        self.touch_caret(key);
1360        true
1361    }
1362
1363    /// Drops the selection of one editor, leaving the caret where the
1364    /// selection's live end was. What a selection started elsewhere in
1365    /// the window calls, so no window ever shows two selections.
1366    pub(crate) fn collapse_selection(&mut self, key: Key) -> bool {
1367        let Some(s) = self.states.get_mut(&key) else {
1368            return false;
1369        };
1370        if matches!(s.editor.selection(), Selection::None) {
1371            return false;
1372        }
1373        s.editor.set_selection(Selection::None);
1374        self.caret_stamp += 1;
1375        true
1376    }
1377
1378    /// The active composition text, if any (for tests and hosts).
1379    pub fn preedit(&self, key: Key) -> Option<&str> {
1380        self.states
1381            .get(&key)?
1382            .preedit
1383            .as_ref()
1384            .map(|p| p.text.as_str())
1385    }
1386
1387    pub fn is_multiline(&self, key: Key) -> bool {
1388        self.states.get(&key).is_some_and(|s| s.multiline)
1389    }
1390
1391    /// Whether Tab in `key` is the app's rather than the focus ring's: a
1392    /// field declared with `keep_tab` (a document's Tab is its own).
1393    pub fn keeps_tab(&self, key: Key) -> bool {
1394        self.states
1395            .get(&key)
1396            .is_some_and(|s| s.keep_tab && !s.multiline)
1397    }
1398
1399    /// Whether `key` lays its text out to its box's width: a document, or
1400    /// a field with `wrap` declared. What emission asks
1401    /// before narrowing a field's clip — an editor that folds never
1402    /// scrolls, so it keeps the node's.
1403    pub(crate) fn folds(&self, key: Key) -> bool {
1404        self.states.get(&key).is_some_and(|s| s.folds)
1405    }
1406
1407    /// Caret rect in physical px, relative to the edit's content origin.
1408    /// None when the caret isn't laid out (e.g. no state for `key`).
1409    pub(crate) fn caret_rect(&mut self, key: Key, fs: &mut FontSystem) -> Option<Rect> {
1410        let s = self.states.get_mut(&key)?;
1411        s.editor.shape_as_needed(fs, false);
1412        let (x, y) = s.editor.cursor_position()?;
1413        let line_height = s.editor.with_buffer(|b| b.metrics().line_height);
1414        Some(Rect::new(
1415            x as f32 - s.offset_x,
1416            y as f32,
1417            (2.0 * s.scale).max(2.0),
1418            line_height,
1419        ))
1420    }
1421
1422    /// The caret of `key` in logical px from the start of its text, as laid
1423    /// out and before a field's scroll: zero wide, one line tall.
1424    pub(crate) fn caret_local(&mut self, key: Key, fs: &mut FontSystem) -> Option<Rect> {
1425        let s = self.states.get_mut(&key)?;
1426        s.editor.shape_as_needed(fs, false);
1427        let (x, y) = s.editor.cursor_position()?;
1428        let line_height = s.editor.with_buffer(|b| b.metrics().line_height);
1429        Some(Rect::new(
1430            x as f32 / s.scale,
1431            y as f32 / s.scale,
1432            0.0,
1433            line_height / s.scale,
1434        ))
1435    }
1436
1437    /// How far a single-line field's text is scrolled left, in physical
1438    /// px, for a content box `inner_w` wide (physical too). 0 for an
1439    /// editor that folds — a document, or a field with `wrap` — which
1440    /// wraps instead.
1441    ///
1442    /// A field does not wrap ([`EditStore::wrapped`]), so a value that
1443    /// outgrows its box is moved under the caret rather than folded onto a
1444    /// second line — which is what a native field does, and what an app
1445    /// otherwise has to fake by declaring the box wider than the text it
1446    /// is about to hold. Recomputed where the box is known,
1447    /// so a field that grows or shrinks between frames re-anchors with it.
1448    pub(crate) fn line_offset(&mut self, key: Key, inner_w: f32, fs: &mut FontSystem) -> f32 {
1449        let focused = self.focused == Some(key);
1450        let Some(s) = self.states.get_mut(&key) else {
1451            return 0.0;
1452        };
1453        if s.folds {
1454            return 0.0;
1455        }
1456        // Unfocused, a field shows its value from the start: what it says
1457        // is what a reader wants, not where its caret was left.
1458        if !focused {
1459            s.offset_x = 0.0;
1460            return 0.0;
1461        }
1462        s.editor.shape_as_needed(fs, false);
1463        let caret_w = (2.0 * s.scale).max(2.0);
1464        let text_w = s
1465            .editor
1466            .with_buffer(|b| b.layout_runs().map(|r| r.line_w).fold(0.0f32, f32::max));
1467        if let Some((x, _)) = s.editor.cursor_position() {
1468            let x = x as f32;
1469            // Two ends, one rule: keep the caret inside the box, moving
1470            // the text by the least that does it.
1471            if x - s.offset_x > inner_w - caret_w {
1472                s.offset_x = x - inner_w + caret_w;
1473            }
1474            if x < s.offset_x {
1475                s.offset_x = x;
1476            }
1477        }
1478        // Never past the end of the text (a field that shrank, or one
1479        // whose value was replaced by a shorter one, scrolls back).
1480        s.offset_x = s.offset_x.clamp(0.0, (text_w + caret_w - inner_w).max(0.0));
1481        s.offset_x
1482    }
1483
1484    // -- Layout measurement (logical units)
1485
1486    /// What the text wants on its own: the width a `Fit` editor takes, and
1487    /// the floor under a `Min::FIT` one.
1488    ///
1489    /// Measured with the wrap taken *off*, and cached against the text and
1490    /// its metrics rather than read off the buffer as it stands. The
1491    /// buffer is still carrying whatever width `wrapped` last set on it,
1492    /// and a fit width measured under that is a width that feeds back on
1493    /// itself: the box takes the widest wrapped line, the next frame wraps
1494    /// to that, and a field declared to hug its text ratchets down to one
1495    /// character with every keystroke on its own line.
1496    pub(crate) fn intrinsic(&mut self, key: Key, fs: &mut FontSystem) -> Size {
1497        let Some(s) = self.states.get_mut(&key) else {
1498            return Size::ZERO;
1499        };
1500        if let Some((v, m, size)) = s.natural
1501            && (v, m) == (s.version, s.metrics_rev)
1502        {
1503            return size;
1504        }
1505        // Taken off and left off: `wrapped` runs after this in the same
1506        // pass, and putting the frame's width back is its job. Off
1507        // unconditionally rather than when `wrap` says it is on — a style
1508        // change clears that flag without touching the buffer, and
1509        // measuring the wrapped buffer is the whole bug.
1510        s.editor.with_buffer_mut(|b| b.set_size(None, None));
1511        s.wrap = None;
1512        s.editor.shape_as_needed(fs, false);
1513        // The same measurement a text node takes of itself, except that an
1514        // empty editor is still one line tall.
1515        let (w, h) = s.editor.with_buffer(|b| {
1516            let (size, lines) = crate::text::measure_buffer(b, 0);
1517            (size.w, lines.max(1) as f32 * b.metrics().line_height)
1518        });
1519        // Caret margin so the cursor at line end isn't clipped.
1520        let size = Size::new((w + 2.0 * s.scale) / s.scale, h / s.scale);
1521        s.natural = Some((s.version, s.metrics_rev, size));
1522        size
1523    }
1524
1525    /// The editor's height at its final content width — and, for a
1526    /// single-line field, the width it is *not* wrapped to.
1527    ///
1528    /// `multiline: false` is a field, not a short document: it lays out on
1529    /// one line whatever it is given and scrolls that line under the caret
1530    /// (see [`EditStore::line_offset`]), which is what a native field does
1531    /// and what the `<edit>` row has always said it is. Wrapping one was
1532    /// how a name that outgrew its box came to be drawn two lines tall
1533    /// inside a box measured for one. The exception is a
1534    /// field that asked to fold (`EditOptions::wrap`): it
1535    /// wraps to its width exactly as a document does, and keeps a field's
1536    /// keyboard.
1537    /// The first line's baseline of editor `key` as `wrapped` last laid it
1538    /// out, logical px below the top of its text: what a
1539    /// field beside its label lines up by. An empty editor is one line of
1540    /// its own metrics. `NaN` for a key no editor holds.
1541    pub(crate) fn baseline(&self, key: Key) -> f32 {
1542        let Some(s) = self.states.get(&key) else {
1543            return f32::NAN;
1544        };
1545        let b = s.editor.with_buffer(|b| {
1546            b.layout_runs()
1547                .next()
1548                .map_or(b.metrics().line_height * 0.8, |r| r.line_y.round())
1549        });
1550        b / s.scale
1551    }
1552
1553    pub(crate) fn wrapped(&mut self, key: Key, max_w: f32, fs: &mut FontSystem) -> Size {
1554        let Some(s) = self.states.get_mut(&key) else {
1555            return Size::ZERO;
1556        };
1557        if !s.folds {
1558            // The buffer stays unwrapped (an editor that folded last frame
1559            // may be carrying a width), and the box is one line tall
1560            // whatever the text has in it — a `\n` that reached a field
1561            // through `set_text` does not make it two.
1562            if s.wrap.is_some() {
1563                s.editor.with_buffer_mut(|b| b.set_size(None, None));
1564                s.wrap = None;
1565                s.invalidate_measurements();
1566            }
1567            s.editor.shape_as_needed(fs, false);
1568            let line = s.editor.with_buffer(|b| b.metrics().line_height);
1569            return Size::new(max_w, line / s.scale);
1570        }
1571        let target = (max_w * s.scale).max(1.0);
1572        if crate::text::wrap_differs(s.wrap, Some(target)) {
1573            s.editor.with_buffer_mut(|b| b.set_size(Some(target), None));
1574            s.wrap = Some(target);
1575        }
1576        let stamp = (s.version, s.metrics_rev, target.to_bits());
1577        if let Some((v, m, w, size)) = s.measured
1578            && (v, m, w) == stamp
1579        {
1580            return size;
1581        }
1582        s.editor.shape_as_needed(fs, false);
1583        let h = s.editor.with_buffer(|b| {
1584            let (_, lines) = crate::text::measure_buffer(b, 0);
1585            lines.max(1) as f32 * b.metrics().line_height
1586        });
1587        let size = Size::new(max_w, h / s.scale);
1588        s.measured = Some((stamp.0, stamp.1, stamp.2, size));
1589        size
1590    }
1591
1592    // -- Emission
1593
1594    /// Draws selection, glyphs, and caret. `origin` is the content box origin
1595    /// in physical px; everything emitted is clipped by `clip`. `selected`
1596    /// is whether the selection is drawn: an editor that lost the keyboard
1597    /// keeps its range for when focus comes back, and shows none of it
1598    /// meanwhile (backlog F147) — a page of fields would otherwise show a
1599    /// highlight in each, none of which ⌘C copies.
1600    #[allow(clippy::too_many_arguments)]
1601    pub(crate) fn emit(
1602        &mut self,
1603        key: Key,
1604        origin: Vec2,
1605        focused: bool,
1606        selected: bool,
1607        faint: Color,
1608        clip: Clip,
1609        clip_id: ClipId,
1610        fs: &mut FontSystem,
1611        text_system: &mut TextSystem,
1612        atlas: &mut crate::atlas::GlyphAtlas,
1613        out: &mut Vec<Quad>,
1614    ) {
1615        let blink_visible = self.blink_visible;
1616        let Some(s) = self.states.get_mut(&key) else {
1617            return;
1618        };
1619        let raster = text_system.raster_mut();
1620        s.editor.shape_as_needed(fs, false);
1621        let color = s.style.color_or_default();
1622        let accent = s.accent;
1623        let scale = s.scale;
1624        let selection = s.editor.selection_bounds().filter(|_| selected);
1625        // The composition range, marked like a selection but drawn as a
1626        // tint plus underline; the caret stays solid while composing so
1627        // the IME's offset inside the text is never hidden by a blink.
1628        let composing = focused && s.preedit.is_some();
1629        let preedit = s
1630            .preedit
1631            .as_ref()
1632            .map(|p| (p.start, end_cursor(p.start, &p.text)));
1633        let cursor_pos = if focused && (blink_visible || composing) {
1634            s.editor.cursor_position()
1635        } else {
1636            None
1637        };
1638        // A single-line field scrolls its text under the caret; the box it
1639        // scrolls inside is the clip emission was handed.
1640        let origin = Vec2::new(origin.x - s.offset_x, origin.y);
1641
1642        // What can show, in the glyphs' own space (ADR 0043).
1643        let vis = clip.visible();
1644        // An empty editor shows its placeholder where its text would start,
1645        // under the caret (backlog F149).
1646        let empty = s.preedit.is_none()
1647            && s.editor
1648                .with_buffer(|b| b.lines.len() == 1 && b.lines[0].text().is_empty());
1649        if empty && let Some((_, _, b)) = &s.placeholder {
1650            for run in b.layout_runs() {
1651                for glyph in run.glyphs.iter() {
1652                    let physical = glyph.physical((0.0, 0.0), 1.0);
1653                    let Some(slot) =
1654                        crate::text::raster_glyph(physical.cache_key, fs, raster, atlas)
1655                    else {
1656                        continue;
1657                    };
1658                    out.push(Quad {
1659                        rect: Rect::new(
1660                            origin.x + physical.x as f32 + slot.left as f32,
1661                            origin.y + run.line_y.round() + physical.y as f32 - slot.top as f32,
1662                            slot.w as f32,
1663                            slot.h as f32,
1664                        ),
1665                        color: faint,
1666                        border_color: Color::TRANSPARENT,
1667                        radius: [0.0; 4],
1668                        border_w: 0.0,
1669                        blur: 0.0,
1670                        kind: crate::text::glyph_kind(&slot),
1671                        uv: [slot.x, slot.y, slot.w, slot.h],
1672                        clip: clip_id,
1673                    });
1674                }
1675            }
1676        }
1677        s.editor.with_buffer(|b| {
1678            let line_height = b.metrics().line_height;
1679            // Runs come in line order: skip everything above the clip and
1680            // stop at the first run past its bottom — a 100k-line document
1681            // emits only the visible screenful of quads.
1682            let runs = b
1683                .layout_runs()
1684                .filter(|run| origin.y + run.line_top + line_height >= vis.y)
1685                .take_while(|run| origin.y + run.line_top <= vis.y + vis.h);
1686            for run in runs {
1687                // Selection highlight for this run (mixed BiDi runs can
1688                // yield several disjoint spans). `highlight` is only valid
1689                // for runs on lines inside the selection span — outside it
1690                // marks the whole run selected.
1691                if let Some((start, end)) = selection
1692                    && run.line_i >= start.line
1693                    && run.line_i <= end.line
1694                {
1695                    let mut any = false;
1696                    for (x, w) in run.highlight(start, end) {
1697                        any = true;
1698                        out.push(Quad {
1699                            rect: Rect::new(
1700                                origin.x + x,
1701                                origin.y + run.line_top,
1702                                w.max(2.0),
1703                                line_height,
1704                            ),
1705                            color: accent,
1706                            border_color: Color::TRANSPARENT,
1707                            radius: [0.0; 4],
1708                            border_w: 0.0,
1709                            blur: 0.0,
1710                            kind: QuadKind::Solid,
1711                            uv: [0; 4],
1712                            clip: clip_id,
1713                        });
1714                    }
1715                    // Empty line inside the selection: a stub for the
1716                    // selected newline keeps the highlight continuous.
1717                    if !any && run.glyphs.is_empty() && end.line > run.line_i {
1718                        out.push(Quad {
1719                            rect: Rect::new(origin.x, origin.y + run.line_top, 2.0, line_height),
1720                            color: accent,
1721                            border_color: Color::TRANSPARENT,
1722                            radius: [0.0; 4],
1723                            border_w: 0.0,
1724                            blur: 0.0,
1725                            kind: QuadKind::Solid,
1726                            uv: [0; 4],
1727                            clip: clip_id,
1728                        });
1729                    }
1730                }
1731                // Composition backdrop + underline under its glyphs.
1732                if let Some((ps, pe)) = preedit
1733                    && run.line_i >= ps.line
1734                    && run.line_i <= pe.line
1735                {
1736                    let underline_h = scale.max(1.0);
1737                    for (x, w) in run.highlight(ps, pe) {
1738                        let solid = |rect: Rect, color: Color| Quad {
1739                            rect,
1740                            color,
1741                            border_color: Color::TRANSPARENT,
1742                            radius: [0.0; 4],
1743                            border_w: 0.0,
1744                            blur: 0.0,
1745                            kind: QuadKind::Solid,
1746                            uv: [0; 4],
1747                            clip: clip_id,
1748                        };
1749                        out.push(solid(
1750                            Rect::new(origin.x + x, origin.y + run.line_top, w, line_height),
1751                            Color { a: 0.3, ..accent },
1752                        ));
1753                        out.push(solid(
1754                            Rect::new(
1755                                origin.x + x,
1756                                origin.y + run.line_top + line_height - underline_h,
1757                                w,
1758                                underline_h,
1759                            ),
1760                            color,
1761                        ));
1762                    }
1763                }
1764                // Glyphs.
1765                for glyph in run.glyphs.iter() {
1766                    let physical = glyph.physical((0.0, 0.0), 1.0);
1767                    let Some(slot) =
1768                        crate::text::raster_glyph(physical.cache_key, fs, raster, atlas)
1769                    else {
1770                        continue;
1771                    };
1772                    let x = origin.x + physical.x as f32 + slot.left as f32;
1773                    let y = origin.y + run.line_y.round() + physical.y as f32 - slot.top as f32;
1774                    let glyph_color = glyph
1775                        .color_opt
1776                        .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a()))
1777                        .unwrap_or(color);
1778                    out.push(Quad {
1779                        rect: Rect::new(x, y, slot.w as f32, slot.h as f32),
1780                        color: glyph_color,
1781                        border_color: Color::TRANSPARENT,
1782                        radius: [0.0; 4],
1783                        border_w: 0.0,
1784                        blur: 0.0,
1785                        kind: crate::text::glyph_kind(&slot),
1786                        uv: [slot.x, slot.y, slot.w, slot.h],
1787                        clip: clip_id,
1788                    });
1789                }
1790            }
1791            // Caret.
1792            if let Some((cx, cy)) = cursor_pos {
1793                out.push(Quad {
1794                    rect: Rect::new(
1795                        origin.x + cx as f32,
1796                        origin.y + cy as f32,
1797                        (2.0 * scale).max(2.0),
1798                        line_height,
1799                    ),
1800                    color,
1801                    border_color: Color::TRANSPARENT,
1802                    radius: [0.0; 4],
1803                    border_w: 0.0,
1804                    blur: 0.0,
1805                    kind: QuadKind::Solid,
1806                    uv: [0; 4],
1807                    clip: clip_id,
1808                });
1809            }
1810        });
1811    }
1812}
1813
1814fn buffer_text(b: &Buffer) -> String {
1815    let mut out = String::new();
1816    for (i, line) in b.lines.iter().enumerate() {
1817        if i > 0 {
1818            out.push('\n');
1819        }
1820        out.push_str(line.text());
1821    }
1822    out
1823}