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        let composing = changed;
1091        match ek {
1092            EditKey::Left
1093            | EditKey::Right
1094            | EditKey::Up
1095            | EditKey::Down
1096            | EditKey::Home
1097            | EditKey::End
1098            | EditKey::PageUp
1099            | EditKey::PageDown => {
1100                let motion = match (ek, mods.word, mods.doc) {
1101                    (EditKey::Left, true, _) => Motion::LeftWord,
1102                    (EditKey::Right, true, _) => Motion::RightWord,
1103                    (EditKey::Left, _, true) => Motion::Home,
1104                    (EditKey::Right, _, true) => Motion::End,
1105                    (EditKey::Up, _, true) => Motion::BufferStart,
1106                    (EditKey::Down, _, true) => Motion::BufferEnd,
1107                    (EditKey::Left, ..) => Motion::Left,
1108                    (EditKey::Right, ..) => Motion::Right,
1109                    (EditKey::Up, ..) => Motion::Up,
1110                    (EditKey::Down, ..) => Motion::Down,
1111                    (EditKey::Home, _, true) => Motion::BufferStart,
1112                    (EditKey::End, _, true) => Motion::BufferEnd,
1113                    (EditKey::Home, ..) => Motion::Home,
1114                    (EditKey::End, ..) => Motion::End,
1115                    (EditKey::PageUp, ..) => Motion::PageUp,
1116                    (EditKey::PageDown, ..) => Motion::PageDown,
1117                    _ => unreachable!(),
1118                };
1119                if mods.shift {
1120                    if s.editor.selection() == Selection::None {
1121                        s.editor.set_selection(Selection::Normal(s.editor.cursor()));
1122                    }
1123                } else {
1124                    s.editor.set_selection(Selection::None);
1125                }
1126                s.editor.action(fs, Action::Motion(motion));
1127                s.break_coalesce();
1128            }
1129            EditKey::Backspace => {
1130                changed |= s.delete_selection_recorded()
1131                    || s.delete_motion_recorded(
1132                        if mods.word {
1133                            Motion::LeftWord
1134                        } else {
1135                            Motion::Left
1136                        },
1137                        Coalesce::Backspace,
1138                        fs,
1139                    );
1140            }
1141            EditKey::Delete => {
1142                changed |= s.delete_selection_recorded()
1143                    || s.delete_motion_recorded(
1144                        if mods.word {
1145                            Motion::RightWord
1146                        } else {
1147                            Motion::Right
1148                        },
1149                        Coalesce::Delete,
1150                        fs,
1151                    );
1152            }
1153            EditKey::Enter => {
1154                if s.multiline {
1155                    s.insert_recorded("\n");
1156                    changed = true;
1157                } else {
1158                    submit = true;
1159                }
1160            }
1161            EditKey::Tab => {
1162                if s.multiline {
1163                    s.insert_recorded("    ");
1164                    changed = true;
1165                }
1166            }
1167            EditKey::Undo => changed |= s.undo_one(),
1168            EditKey::Redo => changed |= s.redo_one(),
1169            EditKey::SelectAll => {
1170                s.editor.action(fs, Action::Motion(Motion::BufferStart));
1171                s.editor.set_selection(Selection::Normal(s.editor.cursor()));
1172                s.editor.action(fs, Action::Motion(Motion::BufferEnd));
1173                s.break_coalesce();
1174            }
1175            EditKey::Escape => {
1176                s.editor.action(fs, Action::Escape);
1177                s.break_coalesce();
1178            }
1179        }
1180        s.editor.shape_as_needed(fs, false);
1181        // A key the editor holds but could not act on (backlog F145): an
1182        // arrow, Backspace or Delete that left the caret where it was and
1183        // changed nothing, from a caret with no selection — the caret was
1184        // at the edge of the text the key moves toward. Not under Shift,
1185        // which extends a selection and has no edge to report, nor
1186        // mid-composition, whose key the IME let through.
1187        let still = !changed
1188            && !composing
1189            && !mods.shift
1190            && before.1 == Selection::None
1191            && (at(&s.editor), s.editor.selection()) == before;
1192        let boundary = match ek {
1193            EditKey::Up | EditKey::Left | EditKey::Backspace if still => Some(Edge::Start),
1194            EditKey::Down | EditKey::Right | EditKey::Delete if still => Some(Edge::End),
1195            _ => None,
1196        };
1197        if changed {
1198            s.version += 1;
1199            s.invalidate_measurements();
1200        }
1201        self.touch_caret(key);
1202        KeyOutcome {
1203            changed,
1204            submit,
1205            boundary,
1206        }
1207    }
1208
1209    /// Mouse press inside the edit at content-local logical position.
1210    /// `clicks` is the driver-counted multi-click: 2 selects the word,
1211    /// 3 the line (cosmic-text's double/triple click actions). With
1212    /// `extend` — a Shift-press — the caret moves there keeping the
1213    /// selection's anchor, seeding one at the caret when there is none
1214    /// (cosmic-text's `Drag` does both), and the
1215    /// click count says nothing. Either way it is a click: a live
1216    /// composition is abandoned and the next edit starts an undo unit.
1217    pub(crate) fn click(
1218        &mut self,
1219        key: Key,
1220        local: Vec2,
1221        clicks: u8,
1222        extend: bool,
1223        fs: &mut FontSystem,
1224    ) {
1225        if let Some(s) = self.states.get_mut(&key) {
1226            if s.abandon_preedit() {
1227                s.version += 1;
1228                s.invalidate_measurements();
1229            }
1230            let (x, y) = ((local.x * s.scale) as i32, (local.y * s.scale) as i32);
1231            let action = match (extend, clicks) {
1232                (true, _) => Action::Drag { x, y },
1233                (false, 0 | 1) => Action::Click { x, y },
1234                (false, 2) => Action::DoubleClick { x, y },
1235                (false, _) => Action::TripleClick { x, y },
1236            };
1237            s.editor.action(fs, action);
1238            s.editor.shape_as_needed(fs, false);
1239            s.break_coalesce();
1240            self.caret_stamp += 1;
1241        }
1242    }
1243
1244    /// Mouse motion with the button held: moves the caret to the point
1245    /// and keeps the selection's anchor (seeding one at the caret when
1246    /// there is none — cosmic-text's `Drag` does both). The caret moved,
1247    /// so it is marked like a keyboard motion's: a field scrolls its own
1248    /// text toward the drag at once, and a scroller above a document
1249    /// reveals the caret on the release — not under the held pointer,
1250    /// where the drag's own rate is what moves it
1251    /// (`scroll_caret_into_view`).
1252    pub(crate) fn drag(&mut self, key: Key, local: Vec2, fs: &mut FontSystem) {
1253        if let Some(s) = self.states.get_mut(&key) {
1254            let (x, y) = ((local.x * s.scale) as i32, (local.y * s.scale) as i32);
1255            let before = s.editor.cursor();
1256            s.editor.action(fs, Action::Drag { x, y });
1257            if s.editor.cursor() != before {
1258                self.touch_caret(key);
1259            } else {
1260                self.caret_stamp += 1;
1261            }
1262        }
1263    }
1264
1265    /// Replaces the focused editor's IME composition. The text lives in
1266    /// the buffer from the moment it appears — following text shifts and
1267    /// the paragraph rewraps — but never in the undo history; the caret
1268    /// sits at the IME-reported offset inside it. Empty text cancels
1269    /// (winit sends that before every commit). Returns true if anything
1270    /// visible changed.
1271    pub(crate) fn set_preedit(
1272        &mut self,
1273        key: Key,
1274        text: &str,
1275        cursor: Option<(usize, usize)>,
1276        fs: &mut FontSystem,
1277    ) -> bool {
1278        let Some(s) = self.states.get_mut(&key) else {
1279            return false;
1280        };
1281        if text.is_empty() {
1282            if !s.abandon_preedit() {
1283                return false;
1284            }
1285        } else {
1286            let start = match s.preedit.take() {
1287                Some(pre) => {
1288                    s.splice(pre.start, &pre.text, text);
1289                    pre.start
1290                }
1291                None => {
1292                    // Composing over a selection replaces it, as typing
1293                    // would — that part is a real, recorded edit.
1294                    s.delete_selection_recorded();
1295                    let at = s.editor.cursor();
1296                    s.editor.insert_string(text, None);
1297                    at
1298                }
1299            };
1300            // Caret at the IME's offset inside the composition (its end
1301            // when unreported), clamped to a char boundary.
1302            let mut at = cursor.map_or(text.len(), |(c, _)| c.min(text.len()));
1303            while at > 0 && !text.is_char_boundary(at) {
1304                at -= 1;
1305            }
1306            s.editor.set_cursor(end_cursor(start, &text[..at]));
1307            s.editor.set_selection(Selection::None);
1308            s.preedit = Some(Preedit {
1309                start,
1310                text: text.to_string(),
1311            });
1312            s.break_coalesce();
1313        }
1314        s.editor.shape_as_needed(fs, false);
1315        s.version += 1;
1316        s.invalidate_measurements();
1317        self.touch_caret(key);
1318        true
1319    }
1320
1321    /// Drops the selection of one editor, leaving the caret where the
1322    /// selection's live end was. What a selection started elsewhere in
1323    /// the window calls, so no window ever shows two selections.
1324    pub(crate) fn collapse_selection(&mut self, key: Key) -> bool {
1325        let Some(s) = self.states.get_mut(&key) else {
1326            return false;
1327        };
1328        if matches!(s.editor.selection(), Selection::None) {
1329            return false;
1330        }
1331        s.editor.set_selection(Selection::None);
1332        self.caret_stamp += 1;
1333        true
1334    }
1335
1336    /// The active composition text, if any (for tests and hosts).
1337    pub fn preedit(&self, key: Key) -> Option<&str> {
1338        self.states
1339            .get(&key)?
1340            .preedit
1341            .as_ref()
1342            .map(|p| p.text.as_str())
1343    }
1344
1345    pub fn is_multiline(&self, key: Key) -> bool {
1346        self.states.get(&key).is_some_and(|s| s.multiline)
1347    }
1348
1349    /// Whether Tab in `key` is the app's rather than the focus ring's: a
1350    /// field declared with `keep_tab` (a document's Tab is its own).
1351    pub fn keeps_tab(&self, key: Key) -> bool {
1352        self.states
1353            .get(&key)
1354            .is_some_and(|s| s.keep_tab && !s.multiline)
1355    }
1356
1357    /// Whether `key` lays its text out to its box's width: a document, or
1358    /// a field with `wrap` declared. What emission asks
1359    /// before narrowing a field's clip — an editor that folds never
1360    /// scrolls, so it keeps the node's.
1361    pub(crate) fn folds(&self, key: Key) -> bool {
1362        self.states.get(&key).is_some_and(|s| s.folds)
1363    }
1364
1365    /// Caret rect in physical px, relative to the edit's content origin.
1366    /// None when the caret isn't laid out (e.g. no state for `key`).
1367    pub(crate) fn caret_rect(&mut self, key: Key, fs: &mut FontSystem) -> Option<Rect> {
1368        let s = self.states.get_mut(&key)?;
1369        s.editor.shape_as_needed(fs, false);
1370        let (x, y) = s.editor.cursor_position()?;
1371        let line_height = s.editor.with_buffer(|b| b.metrics().line_height);
1372        Some(Rect::new(
1373            x as f32 - s.offset_x,
1374            y as f32,
1375            (2.0 * s.scale).max(2.0),
1376            line_height,
1377        ))
1378    }
1379
1380    /// How far a single-line field's text is scrolled left, in physical
1381    /// px, for a content box `inner_w` wide (physical too). 0 for an
1382    /// editor that folds — a document, or a field with `wrap` — which
1383    /// wraps instead.
1384    ///
1385    /// A field does not wrap ([`EditStore::wrapped`]), so a value that
1386    /// outgrows its box is moved under the caret rather than folded onto a
1387    /// second line — which is what a native field does, and what an app
1388    /// otherwise has to fake by declaring the box wider than the text it
1389    /// is about to hold. Recomputed where the box is known,
1390    /// so a field that grows or shrinks between frames re-anchors with it.
1391    pub(crate) fn line_offset(&mut self, key: Key, inner_w: f32, fs: &mut FontSystem) -> f32 {
1392        let focused = self.focused == Some(key);
1393        let Some(s) = self.states.get_mut(&key) else {
1394            return 0.0;
1395        };
1396        if s.folds {
1397            return 0.0;
1398        }
1399        // Unfocused, a field shows its value from the start: what it says
1400        // is what a reader wants, not where its caret was left.
1401        if !focused {
1402            s.offset_x = 0.0;
1403            return 0.0;
1404        }
1405        s.editor.shape_as_needed(fs, false);
1406        let caret_w = (2.0 * s.scale).max(2.0);
1407        let text_w = s
1408            .editor
1409            .with_buffer(|b| b.layout_runs().map(|r| r.line_w).fold(0.0f32, f32::max));
1410        if let Some((x, _)) = s.editor.cursor_position() {
1411            let x = x as f32;
1412            // Two ends, one rule: keep the caret inside the box, moving
1413            // the text by the least that does it.
1414            if x - s.offset_x > inner_w - caret_w {
1415                s.offset_x = x - inner_w + caret_w;
1416            }
1417            if x < s.offset_x {
1418                s.offset_x = x;
1419            }
1420        }
1421        // Never past the end of the text (a field that shrank, or one
1422        // whose value was replaced by a shorter one, scrolls back).
1423        s.offset_x = s.offset_x.clamp(0.0, (text_w + caret_w - inner_w).max(0.0));
1424        s.offset_x
1425    }
1426
1427    // -- Layout measurement (logical units)
1428
1429    /// What the text wants on its own: the width a `Fit` editor takes, and
1430    /// the floor under a `Min::FIT` one.
1431    ///
1432    /// Measured with the wrap taken *off*, and cached against the text and
1433    /// its metrics rather than read off the buffer as it stands. The
1434    /// buffer is still carrying whatever width `wrapped` last set on it,
1435    /// and a fit width measured under that is a width that feeds back on
1436    /// itself: the box takes the widest wrapped line, the next frame wraps
1437    /// to that, and a field declared to hug its text ratchets down to one
1438    /// character with every keystroke on its own line.
1439    pub(crate) fn intrinsic(&mut self, key: Key, fs: &mut FontSystem) -> Size {
1440        let Some(s) = self.states.get_mut(&key) else {
1441            return Size::ZERO;
1442        };
1443        if let Some((v, m, size)) = s.natural
1444            && (v, m) == (s.version, s.metrics_rev)
1445        {
1446            return size;
1447        }
1448        // Taken off and left off: `wrapped` runs after this in the same
1449        // pass, and putting the frame's width back is its job. Off
1450        // unconditionally rather than when `wrap` says it is on — a style
1451        // change clears that flag without touching the buffer, and
1452        // measuring the wrapped buffer is the whole bug.
1453        s.editor.with_buffer_mut(|b| b.set_size(None, None));
1454        s.wrap = None;
1455        s.editor.shape_as_needed(fs, false);
1456        // The same measurement a text node takes of itself, except that an
1457        // empty editor is still one line tall.
1458        let (w, h) = s.editor.with_buffer(|b| {
1459            let (size, lines) = crate::text::measure_buffer(b, 0);
1460            (size.w, lines.max(1) as f32 * b.metrics().line_height)
1461        });
1462        // Caret margin so the cursor at line end isn't clipped.
1463        let size = Size::new((w + 2.0 * s.scale) / s.scale, h / s.scale);
1464        s.natural = Some((s.version, s.metrics_rev, size));
1465        size
1466    }
1467
1468    /// The editor's height at its final content width — and, for a
1469    /// single-line field, the width it is *not* wrapped to.
1470    ///
1471    /// `multiline: false` is a field, not a short document: it lays out on
1472    /// one line whatever it is given and scrolls that line under the caret
1473    /// (see [`EditStore::line_offset`]), which is what a native field does
1474    /// and what the `<edit>` row has always said it is. Wrapping one was
1475    /// how a name that outgrew its box came to be drawn two lines tall
1476    /// inside a box measured for one. The exception is a
1477    /// field that asked to fold (`EditOptions::wrap`): it
1478    /// wraps to its width exactly as a document does, and keeps a field's
1479    /// keyboard.
1480    /// The first line's baseline of editor `key` as `wrapped` last laid it
1481    /// out, logical px below the top of its text: what a
1482    /// field beside its label lines up by. An empty editor is one line of
1483    /// its own metrics. `NaN` for a key no editor holds.
1484    pub(crate) fn baseline(&self, key: Key) -> f32 {
1485        let Some(s) = self.states.get(&key) else {
1486            return f32::NAN;
1487        };
1488        let b = s.editor.with_buffer(|b| {
1489            b.layout_runs()
1490                .next()
1491                .map_or(b.metrics().line_height * 0.8, |r| r.line_y.round())
1492        });
1493        b / s.scale
1494    }
1495
1496    pub(crate) fn wrapped(&mut self, key: Key, max_w: f32, fs: &mut FontSystem) -> Size {
1497        let Some(s) = self.states.get_mut(&key) else {
1498            return Size::ZERO;
1499        };
1500        if !s.folds {
1501            // The buffer stays unwrapped (an editor that folded last frame
1502            // may be carrying a width), and the box is one line tall
1503            // whatever the text has in it — a `\n` that reached a field
1504            // through `set_text` does not make it two.
1505            if s.wrap.is_some() {
1506                s.editor.with_buffer_mut(|b| b.set_size(None, None));
1507                s.wrap = None;
1508                s.invalidate_measurements();
1509            }
1510            s.editor.shape_as_needed(fs, false);
1511            let line = s.editor.with_buffer(|b| b.metrics().line_height);
1512            return Size::new(max_w, line / s.scale);
1513        }
1514        let target = (max_w * s.scale).max(1.0);
1515        if crate::text::wrap_differs(s.wrap, Some(target)) {
1516            s.editor.with_buffer_mut(|b| b.set_size(Some(target), None));
1517            s.wrap = Some(target);
1518        }
1519        let stamp = (s.version, s.metrics_rev, target.to_bits());
1520        if let Some((v, m, w, size)) = s.measured
1521            && (v, m, w) == stamp
1522        {
1523            return size;
1524        }
1525        s.editor.shape_as_needed(fs, false);
1526        let h = s.editor.with_buffer(|b| {
1527            let (_, lines) = crate::text::measure_buffer(b, 0);
1528            lines.max(1) as f32 * b.metrics().line_height
1529        });
1530        let size = Size::new(max_w, h / s.scale);
1531        s.measured = Some((stamp.0, stamp.1, stamp.2, size));
1532        size
1533    }
1534
1535    // -- Emission
1536
1537    /// Draws selection, glyphs, and caret. `origin` is the content box origin
1538    /// in physical px; everything emitted is clipped by `clip`. `selected`
1539    /// is whether the selection is drawn: an editor that lost the keyboard
1540    /// keeps its range for when focus comes back, and shows none of it
1541    /// meanwhile (backlog F147) — a page of fields would otherwise show a
1542    /// highlight in each, none of which ⌘C copies.
1543    #[allow(clippy::too_many_arguments)]
1544    pub(crate) fn emit(
1545        &mut self,
1546        key: Key,
1547        origin: Vec2,
1548        focused: bool,
1549        selected: bool,
1550        faint: Color,
1551        clip: Clip,
1552        clip_id: ClipId,
1553        fs: &mut FontSystem,
1554        text_system: &mut TextSystem,
1555        atlas: &mut crate::atlas::GlyphAtlas,
1556        out: &mut Vec<Quad>,
1557    ) {
1558        let blink_visible = self.blink_visible;
1559        let Some(s) = self.states.get_mut(&key) else {
1560            return;
1561        };
1562        let raster = text_system.raster_mut();
1563        s.editor.shape_as_needed(fs, false);
1564        let color = s.style.color_or_default();
1565        let accent = s.accent;
1566        let scale = s.scale;
1567        let selection = s.editor.selection_bounds().filter(|_| selected);
1568        // The composition range, marked like a selection but drawn as a
1569        // tint plus underline; the caret stays solid while composing so
1570        // the IME's offset inside the text is never hidden by a blink.
1571        let composing = focused && s.preedit.is_some();
1572        let preedit = s
1573            .preedit
1574            .as_ref()
1575            .map(|p| (p.start, end_cursor(p.start, &p.text)));
1576        let cursor_pos = if focused && (blink_visible || composing) {
1577            s.editor.cursor_position()
1578        } else {
1579            None
1580        };
1581        // A single-line field scrolls its text under the caret; the box it
1582        // scrolls inside is the clip emission was handed.
1583        let origin = Vec2::new(origin.x - s.offset_x, origin.y);
1584
1585        // What can show, in the glyphs' own space (ADR 0043).
1586        let vis = clip.visible();
1587        // An empty editor shows its placeholder where its text would start,
1588        // under the caret (backlog F149).
1589        let empty = s.preedit.is_none()
1590            && s.editor
1591                .with_buffer(|b| b.lines.len() == 1 && b.lines[0].text().is_empty());
1592        if empty && let Some((_, _, b)) = &s.placeholder {
1593            for run in b.layout_runs() {
1594                for glyph in run.glyphs.iter() {
1595                    let physical = glyph.physical((0.0, 0.0), 1.0);
1596                    let Some(slot) =
1597                        crate::text::raster_glyph(physical.cache_key, fs, raster, atlas)
1598                    else {
1599                        continue;
1600                    };
1601                    out.push(Quad {
1602                        rect: Rect::new(
1603                            origin.x + physical.x as f32 + slot.left as f32,
1604                            origin.y + run.line_y.round() + physical.y as f32 - slot.top as f32,
1605                            slot.w as f32,
1606                            slot.h as f32,
1607                        ),
1608                        color: faint,
1609                        border_color: Color::TRANSPARENT,
1610                        radius: [0.0; 4],
1611                        border_w: 0.0,
1612                        blur: 0.0,
1613                        kind: crate::text::glyph_kind(&slot),
1614                        uv: [slot.x, slot.y, slot.w, slot.h],
1615                        clip: clip_id,
1616                    });
1617                }
1618            }
1619        }
1620        s.editor.with_buffer(|b| {
1621            let line_height = b.metrics().line_height;
1622            // Runs come in line order: skip everything above the clip and
1623            // stop at the first run past its bottom — a 100k-line document
1624            // emits only the visible screenful of quads.
1625            let runs = b
1626                .layout_runs()
1627                .filter(|run| origin.y + run.line_top + line_height >= vis.y)
1628                .take_while(|run| origin.y + run.line_top <= vis.y + vis.h);
1629            for run in runs {
1630                // Selection highlight for this run (mixed BiDi runs can
1631                // yield several disjoint spans). `highlight` is only valid
1632                // for runs on lines inside the selection span — outside it
1633                // marks the whole run selected.
1634                if let Some((start, end)) = selection
1635                    && run.line_i >= start.line
1636                    && run.line_i <= end.line
1637                {
1638                    let mut any = false;
1639                    for (x, w) in run.highlight(start, end) {
1640                        any = true;
1641                        out.push(Quad {
1642                            rect: Rect::new(
1643                                origin.x + x,
1644                                origin.y + run.line_top,
1645                                w.max(2.0),
1646                                line_height,
1647                            ),
1648                            color: accent,
1649                            border_color: Color::TRANSPARENT,
1650                            radius: [0.0; 4],
1651                            border_w: 0.0,
1652                            blur: 0.0,
1653                            kind: QuadKind::Solid,
1654                            uv: [0; 4],
1655                            clip: clip_id,
1656                        });
1657                    }
1658                    // Empty line inside the selection: a stub for the
1659                    // selected newline keeps the highlight continuous.
1660                    if !any && run.glyphs.is_empty() && end.line > run.line_i {
1661                        out.push(Quad {
1662                            rect: Rect::new(origin.x, origin.y + run.line_top, 2.0, line_height),
1663                            color: accent,
1664                            border_color: Color::TRANSPARENT,
1665                            radius: [0.0; 4],
1666                            border_w: 0.0,
1667                            blur: 0.0,
1668                            kind: QuadKind::Solid,
1669                            uv: [0; 4],
1670                            clip: clip_id,
1671                        });
1672                    }
1673                }
1674                // Composition backdrop + underline under its glyphs.
1675                if let Some((ps, pe)) = preedit
1676                    && run.line_i >= ps.line
1677                    && run.line_i <= pe.line
1678                {
1679                    let underline_h = scale.max(1.0);
1680                    for (x, w) in run.highlight(ps, pe) {
1681                        let solid = |rect: Rect, color: Color| Quad {
1682                            rect,
1683                            color,
1684                            border_color: Color::TRANSPARENT,
1685                            radius: [0.0; 4],
1686                            border_w: 0.0,
1687                            blur: 0.0,
1688                            kind: QuadKind::Solid,
1689                            uv: [0; 4],
1690                            clip: clip_id,
1691                        };
1692                        out.push(solid(
1693                            Rect::new(origin.x + x, origin.y + run.line_top, w, line_height),
1694                            Color { a: 0.3, ..accent },
1695                        ));
1696                        out.push(solid(
1697                            Rect::new(
1698                                origin.x + x,
1699                                origin.y + run.line_top + line_height - underline_h,
1700                                w,
1701                                underline_h,
1702                            ),
1703                            color,
1704                        ));
1705                    }
1706                }
1707                // Glyphs.
1708                for glyph in run.glyphs.iter() {
1709                    let physical = glyph.physical((0.0, 0.0), 1.0);
1710                    let Some(slot) =
1711                        crate::text::raster_glyph(physical.cache_key, fs, raster, atlas)
1712                    else {
1713                        continue;
1714                    };
1715                    let x = origin.x + physical.x as f32 + slot.left as f32;
1716                    let y = origin.y + run.line_y.round() + physical.y as f32 - slot.top as f32;
1717                    let glyph_color = glyph
1718                        .color_opt
1719                        .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a()))
1720                        .unwrap_or(color);
1721                    out.push(Quad {
1722                        rect: Rect::new(x, y, slot.w as f32, slot.h as f32),
1723                        color: glyph_color,
1724                        border_color: Color::TRANSPARENT,
1725                        radius: [0.0; 4],
1726                        border_w: 0.0,
1727                        blur: 0.0,
1728                        kind: crate::text::glyph_kind(&slot),
1729                        uv: [slot.x, slot.y, slot.w, slot.h],
1730                        clip: clip_id,
1731                    });
1732                }
1733            }
1734            // Caret.
1735            if let Some((cx, cy)) = cursor_pos {
1736                out.push(Quad {
1737                    rect: Rect::new(
1738                        origin.x + cx as f32,
1739                        origin.y + cy as f32,
1740                        (2.0 * scale).max(2.0),
1741                        line_height,
1742                    ),
1743                    color,
1744                    border_color: Color::TRANSPARENT,
1745                    radius: [0.0; 4],
1746                    border_w: 0.0,
1747                    blur: 0.0,
1748                    kind: QuadKind::Solid,
1749                    uv: [0; 4],
1750                    clip: clip_id,
1751                });
1752            }
1753        });
1754    }
1755}
1756
1757fn buffer_text(b: &Buffer) -> String {
1758    let mut out = String::new();
1759    for (i, line) in b.lines.iter().enumerate() {
1760        if i > 0 {
1761            out.push('\n');
1762        }
1763        out.push_str(line.text());
1764    }
1765    out
1766}