1
//! Unified text editing manager
2
//!
3
//! Single source of truth for all text editing state. `MultiCursorState` is
4
//! the primary cursor/selection system. `BlinkState` handles the caret blink
5
//! animation. (Non-editable drag-select is not yet wired — the former
6
//! `SelectionManager` scaffolding was dead and has been removed; a future
7
//! implementation should build on `MultiCursorState`.)
8
//!
9
//! Every mutation that affects visual output sets `display_list_dirty = true`,
10
//! ensuring the display list is always regenerated.
11

            
12
use alloc::{collections::BTreeMap, sync::Arc};
13
use core::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
14

            
15
use azul_core::{
16
    dom::{DomId, DomNodeId, NodeId},
17
    events::SyntheticEvent,
18
    geom::{LogicalPosition, LogicalRect},
19
    selection::{MultiCursorState, Selection, SelectionRange, TextCursor},
20
    styled_dom::NodeHierarchyItemId,
21
    task::{Duration, Instant},
22
};
23
use azul_css::props::basic::color::ColorU;
24

            
25
/// Default cursor blink interval in milliseconds
26
pub const CURSOR_BLINK_INTERVAL_MS: u64 = 530;
27

            
28
/// Default cursor blink interval as a variant-agnostic [`Duration`].
29
///
30
/// The interval is a `Duration`, not a bare `u64` of milliseconds, so a
31
/// stylesheet can express it in the clockless `t` unit (`caret-animation-duration:
32
/// 5t`) and have it survive all the way to the comparison. `Duration`'s
33
/// comparisons are unit-aware, so a tick-unit interval and a wall-clock elapsed
34
/// value (or vice versa) still compare truthfully.
35
pub const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(CURSOR_BLINK_INTERVAL_MS);
36

            
37
/// Cursor blink animation state.
38
///
39
/// Extracted from the old `CursorManager` so it can live independently
40
/// on `TextEditManager` without coupling to cursor position.
41
#[derive(Debug, Clone)]
42
pub struct BlinkState {
43
    /// Whether the cursor is currently visible (toggled by blink timer)
44
    pub is_visible: bool,
45
    /// Timestamp of the last user input event (keyboard, mouse click in text).
46
    /// Used to determine whether to blink or stay solid while typing.
47
    pub last_input_time: Option<Instant>,
48
    /// Whether the cursor blink timer is currently active
49
    pub blink_timer_active: bool,
50
    /// How long the caret stays solid after input before blinking resumes, and
51
    /// the interval the blink timer is armed with.
52
    ///
53
    /// Defaults to [`CURSOR_BLINK_INTERVAL`]; `caret-animation-duration` on the
54
    /// focused node overrides it, in whichever unit the stylesheet used.
55
    pub blink_interval: Duration,
56
}
57

            
58
impl Default for BlinkState {
59
7665
    fn default() -> Self {
60
7665
        Self {
61
7665
            is_visible: false,
62
7665
            last_input_time: None,
63
7665
            blink_timer_active: false,
64
7665
            blink_interval: CURSOR_BLINK_INTERVAL,
65
7665
        }
66
7665
    }
67
}
68

            
69
impl BlinkState {
70
    #[must_use]
71
7665
    pub fn new() -> Self {
72
7665
        Self::default()
73
7665
    }
74

            
75
    /// Override the blink interval (from `caret-animation-duration`).
76
    ///
77
    /// Takes a [`Duration`] rather than milliseconds so a `t`-unit stylesheet
78
    /// value stays a frame count: a `5t` caret flips on the 5th frame exactly,
79
    /// on any machine, at any load.
80
    ///
81
    /// Prefer [`Self::adopt_blink_interval`] on a focus change: a RUNNING timer
82
    /// does not pick the new value up on its own.
83
4
    pub const fn set_blink_interval(&mut self, interval: Duration) {
84
4
        self.blink_interval = interval;
85
4
    }
86

            
87
    /// Adopt `interval`, reporting whether it actually CHANGED.
88
    ///
89
    /// The blink timer bakes the interval into the `Timer` once, at
90
    /// construction (`LayoutWindow::create_cursor_blink_timer`), so a timer
91
    /// that is already running keeps the PREVIOUS node's period no matter what
92
    /// this state says. Refocusing between two editables with different
93
    /// `caret-animation-duration` must therefore rebuild the timer — and only
94
    /// then, because rebuilding it on every focus change would restart the
95
    /// blink phase for nothing.
96
    ///
97
    /// This is the predicate that decides (see `HANDOFF-text-fix.md` for the
98
    /// `CursorBlinkTimerAction::Restart` half). A change of UNIT is a change:
99
    /// `5t` and `530ms` are different intervals, not one interval spelled two
100
    /// ways — the tick-unit caret must stay clockless.
101
    #[must_use]
102
77
    pub fn adopt_blink_interval(&mut self, interval: Duration) -> bool {
103
77
        let changed = self.blink_interval != interval;
104
77
        self.blink_interval = interval;
105
77
        changed
106
77
    }
107

            
108
    /// Reset blink on user input — cursor stays solid until blink interval elapses.
109
4850
    pub fn reset_blink_on_input(&mut self, now: Instant) {
110
4850
        self.is_visible = true;
111
4850
        self.last_input_time = Some(now);
112
4850
    }
113

            
114
    /// Toggle cursor visibility (called by blink timer callback).
115
1005
    pub const fn toggle_visibility(&mut self) -> bool {
116
1005
        self.is_visible = !self.is_visible;
117
1005
        self.is_visible
118
1005
    }
119

            
120
132
    pub const fn set_visibility(&mut self, visible: bool) {
121
132
        self.is_visible = visible;
122
132
    }
123

            
124
88
    pub const fn set_blink_timer_active(&mut self, active: bool) {
125
88
        self.blink_timer_active = active;
126
88
    }
127

            
128
    #[must_use]
129
135
    pub const fn is_blink_timer_active(&self) -> bool {
130
135
        self.blink_timer_active
131
135
    }
132

            
133
    /// Check if enough time has passed since last input to start blinking.
134
    ///
135
    /// The interval is [`Self::blink_interval`], compared unit-aware: a tick
136
    /// interval against wall-clock elapsed time (or the reverse) both answer
137
    /// truthfully. This used to build a `Duration::System` constant inline, which
138
    /// meant a tick-driven clock produced a `Duration::Tick` elapsed value that
139
    /// could never be "greater than" it — the caret stopped blinking, silently
140
    /// and permanently, on every clockless build.
141
    #[must_use]
142
37
    pub fn should_blink(&self, now: &Instant) -> bool {
143
37
        self.last_input_time.as_ref().is_none_or(|last_input| {
144
33
            now.duration_since(last_input)
145
33
                .greater_than(&self.blink_interval)
146
33
        })
147
37
    }
148

            
149
    /// Clear all blink state (when editing ends).
150
    ///
151
    /// The interval goes back to the default too: it was read off the node that
152
    /// just lost focus, and leaving it behind would apply that node's
153
    /// `caret-animation-duration` to the next element focused — including one
154
    /// that never set the property.
155
83
    pub fn clear(&mut self) {
156
83
        self.is_visible = false;
157
83
        self.last_input_time = None;
158
83
        self.blink_timer_active = false;
159
83
        self.blink_interval = CURSOR_BLINK_INTERVAL;
160
83
    }
161
}
162

            
163
/// One in-flight caret tween: the caret is gliding from `from` (what the
164
/// previous frame rendered) toward wherever the current layout puts it.
165
#[derive(Debug, Clone)]
166
pub struct CaretTweenTrack {
167
    /// Rect the tween starts from (the previously RENDERED rect, so a
168
    /// mid-flight retarget stays continuous).
169
    pub from: LogicalRect,
170
    /// Rect the tween is seeking. Retargeting happens ONLY when the layout's
171
    /// current rect stops matching this — comparing against the rendered
172
    /// rect would re-arm (and restart the clock) every animation tick.
173
    pub to: LogicalRect,
174
    /// When the tween (re)started.
175
    pub start: Instant,
176
    /// The caret moves because text was TYPED at it: the glyphs between
177
    /// `from` and `to` are new and are revealed by the caret as it slides
178
    /// over them, clipped at its centre, instead of appearing whole before it
179
    /// arrives. False for a plain caret move (arrow keys, a click), where the
180
    /// text it passes was already on screen and must stay visible.
181
    pub reveal: bool,
182
}
183

            
184
/// One in-flight selection tween (same contract as [`CaretTweenTrack`],
185
/// for the whole selection band geometry).
186
#[derive(Debug, Clone)]
187
pub struct SelectionTweenTrack {
188
    pub from: Vec<LogicalRect>,
189
    /// Geometry the tween is seeking (same retarget contract as
190
    /// [`CaretTweenTrack::to`]).
191
    pub to: Vec<LogicalRect>,
192
    pub start: Instant,
193
}
194

            
195
/// Caret / selection tween bookkeeping, updated by the display-list
196
/// post-pass (`LayoutWindow::apply_text_tweens`). `tick_flag` is shared
197
/// with the tween timer's `RefAny` data so the timer can terminate itself
198
/// the tick after both tweens finish.
199
#[derive(Debug, Default)]
200
pub struct TextTweenState {
201
    /// DOM the tracked geometry belongs to. A caret/selection appearing on a
202
    /// DIFFERENT dom resets tracking (no cross-dom tween).
203
    pub dom_id: Option<DomId>,
204
    /// Node the tracked caret/selection geometry belongs to — the editing
205
    /// session's node, maintained by [`TextEditManager`].
206
    ///
207
    /// Without it the geometry is unattributable, and a DOM reconcile that
208
    /// moves or unmounts the edited node leaves `last_caret`/`last_selection`
209
    /// describing a rectangle that belongs to nothing: the next frame then
210
    /// glides the caret across the screen from a dead rect.
211
    pub node: Option<DomNodeId>,
212
    /// Focusable the tracked caret geometry currently sits inside, as
213
    /// [`super::super::window::LayoutWindow::find_focusable_ancestor`] reports
214
    /// it. `None` is a real value — text outside any focusable — and compares
215
    /// equal to itself.
216
    ///
217
    /// A text field is a focusable container around a contenteditable child, so
218
    /// the caret's own node cannot tell two fields apart from two paragraphs of
219
    /// one field. This can.
220
    pub focus_scope: Option<DomNodeId>,
221
    /// In-flight caret tween, if any.
222
    pub caret: Option<CaretTweenTrack>,
223
    /// Caret rect the last display-list pass RENDERED (tween target space).
224
    pub last_caret: Option<LogicalRect>,
225
    /// In-flight selection tween, if any.
226
    pub selection: Option<SelectionTweenTrack>,
227
    /// Selection rects the last display-list pass RENDERED.
228
    pub last_selection: Vec<LogicalRect>,
229
    /// In-flight focus-ring glide (ledger #29; opt-in via
230
    /// `SystemAnimations.focus_ring_duration_ms`).
231
    pub focus_ring: Option<CaretTweenTrack>,
232
    /// Focus-ring rect the last display-list pass RENDERED.
233
    pub last_focus_ring: Option<LogicalRect>,
234
    /// Shared "a tween is in flight" flag: written by the post-pass, read
235
    /// by `caret_tween_timer_callback` (via its `RefAny`) to self-terminate.
236
    pub tick_flag: Arc<AtomicBool>,
237
    /// Text was just INSERTED at the primary caret and no caret glide has
238
    /// consumed that yet: the next glide the caret makes is the one the
239
    /// insertion causes, so it reveals the new glyphs
240
    /// ([`CaretTweenTrack::reveal`]). A flag set by the insertion itself,
241
    /// not a revision compared per pass: `apply_text_changeset` rebuilds the
242
    /// list once BEFORE the relayout moves the caret, and that pass would
243
    /// otherwise consume the edit with the caret still standing still.
244
    pub reveal_pending: bool,
245
}
246

            
247
/// Cloning a manager must NOT share the original's tween-timer flag: the two
248
/// copies would steer one timer, and dropping either would tell that timer the
249
/// other's tweens had finished. So the flag is the ONE field that is not
250
/// shared — the clone gets its own `Arc` holding the same value. Everything
251
/// else is copied, because a `clone()` that quietly returned
252
/// `Self::default()` reported "no tween in flight, no rendered geometry" for a
253
/// manager that had both.
254
impl Clone for TextTweenState {
255
3
    fn clone(&self) -> Self {
256
3
        Self {
257
3
            dom_id: self.dom_id,
258
3
            node: self.node,
259
3
            focus_scope: self.focus_scope,
260
3
            caret: self.caret.clone(),
261
3
            last_caret: self.last_caret,
262
3
            selection: self.selection.clone(),
263
3
            last_selection: self.last_selection.clone(),
264
3
            focus_ring: self.focus_ring.clone(),
265
3
            last_focus_ring: self.last_focus_ring,
266
3
            tick_flag: Arc::new(AtomicBool::new(
267
3
                self.tick_flag.load(AtomicOrdering::Acquire),
268
3
            )),
269
3
            reveal_pending: self.reveal_pending,
270
3
        }
271
3
    }
272
}
273

            
274
impl TextTweenState {
275
    /// True while any tween is mid-flight (drives the 16ms tween timer and
276
    /// forces the caret solid — blinking is suppressed during animation).
277
    #[must_use]
278
7187
    pub const fn is_active(&self) -> bool {
279
7187
        self.caret.is_some() || self.selection.is_some() || self.focus_ring.is_some()
280
7187
    }
281

            
282
    /// Publish `is_active()` to the shared flag the tween timer polls.
283
4008
    pub fn publish_active(&self) {
284
4008
        self.tick_flag
285
4008
            .store(self.is_active(), AtomicOrdering::Release);
286
4008
    }
287

            
288
    /// Reset all tracking (focus lost / editing cleared / dom switched).
289
1
    pub fn reset(&mut self) {
290
1
        self.dom_id = None;
291
1
        self.reveal_pending = false;
292
1
        self.node = None;
293
1
        self.focus_scope = None;
294
1
        self.caret = None;
295
1
        self.last_caret = None;
296
1
        self.selection = None;
297
1
        self.last_selection.clear();
298
1
        self.focus_ring = None;
299
1
        self.last_focus_ring = None;
300
1
        self.publish_active();
301
1
    }
302

            
303
    /// Reset only the TEXT tweens (caret + selection) — the focus ring has
304
    /// its own lifecycle (it runs without an editing session).
305
    ///
306
    /// `node` goes with them: it anchors the caret/selection geometry, not the
307
    /// ring.
308
162
    pub fn reset_text_tweens(&mut self) {
309
162
        self.reveal_pending = false;
310
162
        self.node = None;
311
162
        self.focus_scope = None;
312
162
        self.caret = None;
313
162
        self.last_caret = None;
314
162
        self.selection = None;
315
162
        self.last_selection.clear();
316
162
        self.publish_active();
317
162
    }
318
}
319

            
320
/// The range selections of ONE editing session, as
321
/// [`TextEditManager::session_selection_ranges`] reports them.
322
///
323
/// All ranges of a session live on the same IFC root — `MultiCursorState` is
324
/// single-node by construction; a selection spanning several roots takes the
325
/// `cross_block` path instead.
326
#[derive(Debug, Clone, PartialEq)]
327
pub struct SessionSelectionRanges {
328
    /// DOM the session's node belongs to.
329
    pub dom_id: DomId,
330
    /// IFC root every range is expressed against.
331
    pub node_id: NodeId,
332
    /// Every range, in `MultiCursorState` order (position-sorted,
333
    /// non-overlapping). Never empty.
334
    pub ranges: Vec<SelectionRange>,
335
    /// The primary range: the most recently added one (Ctrl+D's newest
336
    /// occurrence), or the document-first range when the primary selection is
337
    /// a bare caret. Always an element of `ranges`.
338
    pub primary: SelectionRange,
339
}
340

            
341
/// Other participants' range selections on one editing session's node, as
342
/// [`TextEditManager::remote_selection_ranges`] reports them.
343
///
344
/// Only ever non-empty once an app has injected selections for a non-local
345
/// owner (`set_owner_selections`); a single-user app never sees one.
346
#[derive(Debug, Clone, PartialEq)]
347
pub struct RemoteSelectionRanges {
348
    /// DOM the session's node belongs to.
349
    pub dom_id: DomId,
350
    /// IFC root every range is expressed against.
351
    pub node_id: NodeId,
352
    /// Each range and whose it is. Never empty.
353
    pub ranges: Vec<(azul_core::selection::SelectionOwner, SelectionRange)>,
354
    /// The local participant's own caret, when they have one.
355
    ///
356
    /// Carried because a `TextSelection` has to name an anchor and a focus
357
    /// even when the only thing being painted belongs to somebody else, and
358
    /// the honest answer for the LOCAL pair is "wherever the local caret is".
359
    pub local_cursor: Option<TextCursor>,
360
}
361

            
362
/// Does `range` run FORWARD — anchor before focus in logical order?
363
///
364
/// `SelectionRange.start` is the ANCHOR and `.end` the FOCUS (the moving end:
365
/// `build_cursor_locations` reads the caret off `.end`), so a backward drag
366
/// arrives with `start > end`. This is the per-range form of the question
367
/// `LayoutWindow::set_cross_block_selection` answers for its node pair. A
368
/// degenerate range counts as forward, matching `TextSelection::new_collapsed`.
369
#[must_use]
370
232
pub fn range_is_forward(range: &SelectionRange) -> bool {
371
232
    range.start <= range.end
372
232
}
373

            
374
/// Which end of an IME composition a pending event describes.
375
///
376
/// The boundary is decided by the engine, not the shells: Win32 sends an
377
/// explicit `WM_IME_STARTCOMPOSITION`, but Wayland's `preedit_string` has no
378
/// start event at all, so no per-platform mapping could agree on it.
379
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380
pub enum CompositionPhase {
381
    /// A composition opened — the first preedit after none was pending.
382
    Start,
383
    /// The preedit text or its caret moved.
384
    Update,
385
    /// The composition committed or was cancelled.
386
    End,
387
}
388

            
389
/// One painted caret: where it is, and WHOSE it is (U1).
390
///
391
/// This was a bare `(DomId, NodeId, TextCursor)` tuple. The owner has to
392
/// travel with it - the paint site is where a participant's colour is chosen,
393
/// and looking it up from a parallel list would be a desync waiting to happen.
394
/// A named struct rather than a fourth tuple field so the reader at the paint
395
/// site can tell which is which.
396
#[derive(Debug, Clone, Copy, PartialEq)]
397
pub struct CursorLocation {
398
    pub dom: DomId,
399
    pub node: NodeId,
400
    pub cursor: TextCursor,
401
    /// [`SelectionOwner::LOCAL`] for this machine's caret.
402
    ///
403
    /// [`SelectionOwner::LOCAL`]: azul_core::selection::SelectionOwner::LOCAL
404
    pub owner: azul_core::selection::SelectionOwner,
405
    /// A seat's composing text spliced in after this caret (9b-ii-a-i-d-ii-c):
406
    /// its byte and char counts, for the underline. `0` = none. The primary's
407
    /// preedit travels in the display-list context instead.
408
    pub preedit_bytes: u32,
409
    pub preedit_chars: u32,
410
}
411

            
412
/// A seat's composition phase waiting to be reported (9b-ii-a-i-d-ii-c-i).
413
#[derive(Debug, Clone, PartialEq, Eq)]
414
pub struct SeatPendingComposition {
415
    pub phase: CompositionPhase,
416
    pub text: String,
417
    pub cursor_begin: i32,
418
    pub cursor_end: i32,
419
}
420

            
421
/// A non-primary seat's input-method composition (9b-ii-a-i-d-ii-c): the
422
/// text being composed and the IME's cursor span in it.
423
#[derive(Debug, Clone, PartialEq, Eq)]
424
pub struct SeatPreedit {
425
    pub text: String,
426
    pub cursor_begin: i32,
427
    pub cursor_end: i32,
428
}
429

            
430
/// Unified text editing manager.
431
///
432
/// `multi_cursor` is the single source of truth for cursor/selection positions.
433
/// `blink` manages the caret blink animation.
434
/// `SelectionManager` (sibling module) handles non-editable text drag-select.
435
#[derive(Debug, Clone)]
436
pub struct TextEditManager {
437
    /// Multi-cursor state for contenteditable elements (Sublime Text style).
438
    /// `Some` whenever a contenteditable element has focus.
439
    /// Source of truth for `edit_text()` and display list painting.
440
    pub multi_cursor: Option<MultiCursorState>,
441
    /// Cross-block (multi-IFC-root) selection, render-ready. Precomputed by
442
    /// `LayoutWindow::set_cross_block_selection`; wins over `multi_cursor`
443
    /// in `build_text_selections_map` while set.
444
    pub cross_block: Option<azul_core::selection::TextSelection>,
445
    /// Cursor blink animation state.
446
    pub blink: BlinkState,
447
    /// IME preedit (composition) text currently being composed.
448
    /// Applies to the primary cursor only.
449
    pub preedit_text: Option<String>,
450
    /// Byte offset of cursor within preedit text (from IME), or -1 if unset.
451
    /// Uses -1 sentinel (rather than `Option`) to match platform IME C API conventions.
452
    pub preedit_cursor_begin: i32,
453
    /// Byte offset of cursor end within preedit text (from IME), or -1 if unset.
454
    /// Uses -1 sentinel (rather than `Option`) to match platform IME C API conventions.
455
    pub preedit_cursor_end: i32,
456
    /// Composition phase awaiting emission as a `Composition*` event, set by
457
    /// `set_preedit` / `commit_composition` and drained by
458
    /// `take_pending_composition`.
459
    pub pending_composition: Option<CompositionPhase>,
460
    /// Text that goes with `pending_composition`: the preedit for Start and
461
    /// Update, the COMMITTED string for End.
462
    pub composition_text: String,
463
    /// Pending on-screen-keyboard request: `Some(true)` = show, `Some(false)`
464
    /// = hide, `None` = nothing asked this pass.
465
    pub pending_soft_keyboard: Option<bool>,
466
    /// Per-participant caret/selection colours (U1). Empty for a single-user
467
    /// app, which is every app until one injects a remote owner.
468
    pub owner_colors: BTreeMap<azul_core::selection::SelectionOwner, ColorU>,
469
    /// Whether the ENGINE paints draggable selection handles - the teardrops
470
    /// under each end of a touch selection (U2-a). ON where the platform has
471
    /// no handles of its own to lend a custom view (Android: `TextView`'s
472
    /// `Editor` draws them, nothing draws them for anyone else); OFF where it
473
    /// does (iOS: `UITextInteraction` draws and drags them and calls the
474
    /// `UITextInput` seams) and on desktop, which has no handles at all.
475
    /// Set by the shell at window creation.
476
    pub selection_handles: bool,
477
    /// The handle the user is currently dragging, if any (U2-a).
478
    pub handle_drag: Option<SelectionHandleDrag>,
479
    /// Set to true by any mutation that changes visual output.
480
    pub display_list_dirty: bool,
481
    /// Caret / selection tween bookkeeping (see [`TextTweenState`]).
482
    pub tween: TextTweenState,
483
    /// The OTHER seats' carets (9b-ii-a-i-d-ii): a second seat typing into
484
    /// its own focused node inserts at ITS caret, not the primary's. Seat 0
485
    /// is the primary and lives in `multi_cursor`. One caret per seat, on the
486
    /// node that seat last edited; shifted across every edit of that node
487
    /// like a peer caret, cleared when the node unmounts. Not yet DRAWN
488
    /// (9b-ii-a-i-d-ii-a).
489
    pub seat_carets: BTreeMap<u64, SeatCaret>,
490
    /// The other seats' compositions (9b-ii-a-i-d-ii-c); the primary's is
491
    /// `preedit_text` / `preedit_cursor_*`.
492
    pub seat_preedits: BTreeMap<u64, SeatPreedit>,
493
    /// The other seats' composition phases awaiting their events
494
    /// (9b-ii-a-i-d-ii-c-i): phase, text, IME cursor begin / end. Drained by
495
    /// `take_pending_seat_compositions` after the pass that emitted them.
496
    pub seat_pending_compositions: BTreeMap<u64, SeatPendingComposition>,
497
    /// The value the currently focused editable node had WHEN IT GAINED FOCUS.
498
    ///
499
    /// `Change` is not "the value was edited" - `TextInput` already reports
500
    /// that, per keystroke. `Change` is "the value COMMITTED and it differs
501
    /// from what the user found", which is what every form on the web means by
502
    /// it. Without a snapshot to compare against there is nothing to subtract
503
    /// the starting value from, so focusing a field and tabbing straight back
504
    /// out emitted a spurious `Change` on a field the user never touched -
505
    /// enough to re-run validation, mark a form dirty, or fire a save.
506
    ///
507
    /// Keyed by node so a snapshot cannot outlive its field and be compared
508
    /// against a DIFFERENT one: focus moving A -> B -> A must compare A's
509
    /// current text against A's own starting value, not against B's.
510
    pub value_at_focus: Option<(DomNodeId, String)>,
511
    /// Editing hosts whose text was mutated OUTSIDE the text-input record
512
    /// pipeline this pass (deletions, multi-cursor paste, the Enter line
513
    /// break). The host pass drains this and dispatches an `Input` event per
514
    /// host, so widget mirrors observe every committed edit, not only
515
    /// insertions. Filled by `LayoutWindow::record_text_edit_undo`.
516
    pub pending_edit_notifications: Vec<DomNodeId>,
517
    /// Text nodes whose committed content changed this pass - one entry per
518
    /// `LayoutWindow::update_text_cache_after_edit` (the single overlay
519
    /// writer), so every path that lands text here: typed characters,
520
    /// deletions, paste, the Enter split. The host pass drains this and
521
    /// dispatches a `TextChanged` event per node AFTER the commit, when
522
    /// `get_unsynced_text_edits` already reads the new text (`Input` fires
523
    /// BEFORE a typed character lands, so a model synced from `Input` is one
524
    /// keystroke behind).
525
    pub pending_text_changed: Vec<DomNodeId>,
526
}
527

            
528
/// The colour a seat's caret and selection are drawn in (9b-ii-a-i-d-ii-a):
529
/// a small fixed palette, deterministic per seat, distinct from the local
530
/// caret's foreground and from each other - the peer-caret scheme, but a
531
/// seat is not a network peer and gets no app-assigned colour of its own.
532
#[must_use]
533
136
pub const fn seat_owner_color(seat_id: u64) -> ColorU {
534
    const PALETTE: [ColorU; 6] = [
535
        ColorU {
536
            r: 0xE0,
537
            g: 0x6C,
538
            b: 0x00,
539
            a: 0xFF,
540
        }, // orange
541
        ColorU {
542
            r: 0x2E,
543
            g: 0x9E,
544
            b: 0x44,
545
            a: 0xFF,
546
        }, // green
547
        ColorU {
548
            r: 0x8E,
549
            g: 0x44,
550
            b: 0xAD,
551
            a: 0xFF,
552
        }, // purple
553
        ColorU {
554
            r: 0x00,
555
            g: 0x8B,
556
            b: 0x9E,
557
            a: 0xFF,
558
        }, // teal
559
        ColorU {
560
            r: 0xC2,
561
            g: 0x18,
562
            b: 0x5B,
563
            a: 0xFF,
564
        }, // magenta
565
        ColorU {
566
            r: 0x7A,
567
            g: 0x5C,
568
            b: 0x00,
569
            a: 0xFF,
570
        }, // olive
571
    ];
572
136
    PALETTE[(seat_id % 6) as usize]
573
136
}
574

            
575
/// A non-primary seat's caret: the node it sits in and where. With an
576
/// `anchor` it is a SELECTION from the anchor to the cursor (a seat's
577
/// Shift+arrow, 9b-ii-a-i-d-ii-b).
578
#[derive(Debug, Clone, Copy, PartialEq)]
579
pub struct SeatCaret {
580
    pub node: DomNodeId,
581
    pub cursor: TextCursor,
582
    pub anchor: Option<TextCursor>,
583
}
584

            
585
impl SeatCaret {
586
    /// The caret as a selection: a range when anchored, else the cursor.
587
    #[must_use]
588
290
    pub fn selection(&self) -> Selection {
589
100
        match self.anchor {
590
100
            Some(anchor) if anchor != self.cursor => Selection::Range(SelectionRange {
591
100
                start: anchor,
592
100
                end: self.cursor,
593
100
            }),
594
190
            _ => Selection::Cursor(self.cursor),
595
        }
596
290
    }
597
}
598

            
599
impl Default for TextEditManager {
600
4
    fn default() -> Self {
601
4
        Self::new()
602
4
    }
603
}
604

            
605
/// Which end of the selection a handle sits under (U2-a). `Start` is the
606
/// document-first end whatever direction the selection was made in.
607
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608
pub enum SelectionHandleEnd {
609
    Start,
610
    End,
611
}
612

            
613
/// A selection handle being dragged (U2-a).
614
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
615
pub struct SelectionHandleDrag {
616
    /// The handle under the finger.
617
    pub end: SelectionHandleEnd,
618
    /// The OTHER end of the selection, fixed for the whole drag - the anchor
619
    /// in the anchor/focus model the mouse drag already uses.
620
    pub anchor: TextCursor,
621
    /// The selection spanned BLOCKS when the handle was grabbed (U2-a-i).
622
    /// The drag then runs through the cross-block mouse-drag machinery,
623
    /// which resolves the pointer against every block and collapses back to
624
    /// a single-block range when it returns to the anchor block - the
625
    /// single-block path resolves within the session's own inline layout and
626
    /// could never leave it.
627
    pub cross_block: bool,
628
}
629

            
630
/// One painted / hit-testable selection handle (U2-a), in WINDOW
631
/// coordinates.
632
#[derive(Debug, Clone, Copy, PartialEq)]
633
pub struct SelectionHandleGeometry {
634
    pub end: SelectionHandleEnd,
635
    /// The centre of the teardrop's circle.
636
    pub center: LogicalPosition,
637
    /// What a press has to land in to grab it: the circle's bounds inflated
638
    /// by [`SELECTION_HANDLE_SLOP`] on every side. A finger is not a pointer.
639
    pub hit: LogicalRect,
640
}
641

            
642
/// Radius of a selection handle's circle, in logical px (U2-a). Android's
643
/// `text_select_handle` assets are 22dp wide, so the same size a user of the
644
/// platform's own text fields is used to.
645
pub const SELECTION_HANDLE_RADIUS: f32 = 11.0;
646
/// Extra hit slop around a handle on every side, in logical px.
647
pub const SELECTION_HANDLE_SLOP: f32 = 8.0;
648

            
649
impl SelectionHandleGeometry {
650
    /// The handle hanging under the bottom-`x` corner of a caret rect: the
651
    /// circle sits entirely below the line, touching it, so it never covers
652
    /// the character it marks.
653
    #[must_use]
654
740
    pub fn under(end: SelectionHandleEnd, x: f32, line_bottom: f32) -> Self {
655
740
        let center = LogicalPosition::new(x, line_bottom + SELECTION_HANDLE_RADIUS);
656
740
        let reach = SELECTION_HANDLE_RADIUS + SELECTION_HANDLE_SLOP;
657
740
        Self {
658
740
            end,
659
740
            center,
660
740
            hit: LogicalRect::new(
661
740
                LogicalPosition::new(center.x - reach, center.y - reach),
662
740
                azul_core::geom::LogicalSize::new(2.0 * reach, 2.0 * reach),
663
740
            ),
664
740
        }
665
740
    }
666

            
667
    /// The circle's own bounds - what is painted.
668
    #[must_use]
669
260
    pub fn circle(&self) -> LogicalRect {
670
260
        let r = SELECTION_HANDLE_RADIUS;
671
260
        LogicalRect::new(
672
260
            LogicalPosition::new(self.center.x - r, self.center.y - r),
673
260
            azul_core::geom::LogicalSize::new(2.0 * r, 2.0 * r),
674
        )
675
260
    }
676

            
677
    #[must_use]
678
140
    pub fn contains(&self, p: LogicalPosition) -> bool {
679
140
        p.x >= self.hit.origin.x
680
110
            && p.y >= self.hit.origin.y
681
80
            && p.x <= self.hit.origin.x + self.hit.size.width
682
80
            && p.y <= self.hit.origin.y + self.hit.size.height
683
140
    }
684
}
685

            
686
/// Only compares `multi_cursor` — blink state, preedit, and dirty flag are
687
/// transient visual state that should not affect logical equality of the
688
/// editing session.
689
impl PartialEq for TextEditManager {
690
4
    fn eq(&self, other: &Self) -> bool {
691
4
        self.multi_cursor == other.multi_cursor
692
4
    }
693
}
694

            
695
impl TextEditManager {
696
    /// Create a new text edit manager with no active editing state
697
    #[must_use]
698
7650
    pub fn new() -> Self {
699
7650
        Self {
700
7650
            multi_cursor: None,
701
7650
            cross_block: None,
702
7650
            blink: BlinkState::new(),
703
7650
            preedit_text: None,
704
7650
            preedit_cursor_begin: -1,
705
7650
            preedit_cursor_end: -1,
706
7650
            pending_composition: None,
707
7650
            composition_text: String::new(),
708
7650
            pending_soft_keyboard: None,
709
7650
            owner_colors: BTreeMap::new(),
710
7650
            selection_handles: false,
711
7650
            handle_drag: None,
712
7650
            display_list_dirty: false,
713
7650
            tween: TextTweenState::default(),
714
7650
            seat_carets: BTreeMap::new(),
715
7650
            seat_preedits: BTreeMap::new(),
716
7650
            seat_pending_compositions: BTreeMap::new(),
717
7650
            pending_edit_notifications: Vec::new(),
718
7650
            pending_text_changed: Vec::new(),
719
7650
            value_at_focus: None,
720
7650
        }
721
7650
    }
722

            
723
    // === Dirty flag ===
724

            
725
    /// Mark that the display list needs regeneration.
726
2186
    pub const fn mark_dirty(&mut self) {
727
2186
        self.display_list_dirty = true;
728
2186
    }
729

            
730
    // === Editing lifecycle ===
731

            
732
    /// Whether a contenteditable element is currently being edited.
733
    #[must_use]
734
4719
    pub const fn has_active_editing(&self) -> bool {
735
4719
        self.multi_cursor.is_some()
736
4719
    }
737

            
738
    /// Get the `DomId` of the node being edited.
739
    #[must_use]
740
16887
    pub fn get_editing_dom_id(&self) -> Option<DomId> {
741
16887
        self.multi_cursor.as_ref().map(|mc| mc.node_id.dom)
742
16887
    }
743

            
744
    /// Get the `NodeId` of the node being edited.
745
    #[must_use]
746
4968
    pub fn get_editing_node_id(&self) -> Option<NodeId> {
747
4968
        self.multi_cursor
748
4968
            .as_ref()
749
4968
            .and_then(|mc| mc.node_id.node.into_crate_internal())
750
4968
    }
751

            
752
    /// Get the primary cursor position (last-added cursor).
753
    #[must_use]
754
    /// The selected text, for an IME that asks (`getSelectedText`).
755
    ///
756
    /// `None` when there is no selection at all. An IME distinguishes that from
757
    /// an EMPTY selection — the latter means "a range exists and is empty" and
758
    /// changes how it offers replacements — so the two must not collapse.
759
    pub fn selected_text_for_ime(&self) -> Option<String> {
760
        // The preedit is the composing text, which is the closest thing to a
761
        // live selection the IME itself put there; a real document selection
762
        // needs the inline content, which lives on LayoutWindow, not here.
763
        self.preedit_text.clone()
764
    }
765

            
766
10158
    pub fn get_primary_cursor(&self) -> Option<TextCursor> {
767
10158
        self.multi_cursor
768
10158
            .as_ref()
769
10158
            .and_then(MultiCursorState::get_primary_cursor)
770
10158
    }
771

            
772
    /// Seat `seat_id`'s caret (9b-ii-a-i-d-ii); the primary's for seat 0,
773
    /// on the multi-cursor's node.
774
    #[must_use]
775
492
    pub fn seat_caret(&self, seat_id: u64) -> Option<SeatCaret> {
776
492
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
777
            let mc = self.multi_cursor.as_ref()?;
778
            return mc.get_primary_cursor().map(|cursor| SeatCaret {
779
                node: mc.node_id,
780
                cursor,
781
                anchor: None,
782
            });
783
492
        }
784
492
        self.seat_carets.get(&seat_id).copied()
785
492
    }
786

            
787
    /// Place seat `seat_id`'s caret (non-primary seats only; the primary's
788
    /// caret is the multi-cursor's).
789
140
    pub fn set_seat_caret(&mut self, seat_id: u64, node: DomNodeId, cursor: TextCursor) {
790
140
        self.set_seat_selection(seat_id, node, cursor, None);
791
140
    }
792

            
793
    /// Place seat `seat_id`'s caret with an anchor: a selection from `anchor`
794
    /// to `cursor` (9b-ii-a-i-d-ii-b).
795
220
    pub fn set_seat_selection(
796
220
        &mut self,
797
220
        seat_id: u64,
798
220
        node: DomNodeId,
799
220
        cursor: TextCursor,
800
220
        anchor: Option<TextCursor>,
801
220
    ) {
802
220
        if seat_id != azul_core::window::PRIMARY_POINTER_SEAT {
803
220
            self.seat_carets.insert(
804
220
                seat_id,
805
                SeatCaret {
806
220
                    node,
807
220
                    cursor,
808
220
                    anchor: anchor.filter(|a| *a != cursor),
809
                },
810
            );
811
            // Drawn in the seat's colour (9b-ii-a-i-d-ii-a) - registered once
812
            // so the app can still override it through `set_owner_color`.
813
220
            self.owner_colors
814
220
                .entry(azul_core::selection::SelectionOwner::seat(seat_id))
815
220
                .or_insert_with(|| seat_owner_color(seat_id));
816
220
            self.mark_dirty();
817
        }
818
220
    }
819

            
820
    /// Whether the seats' carets are drawn solid on their own (9b-ii-a-i-d-ii-a):
821
    /// while the primary edits, they blink on ITS clock through the shared
822
    /// `cursor_is_visible`; with no primary session there is no clock, so a
823
    /// seat caret is simply shown.
824
    #[must_use]
825
9746
    pub fn seat_carets_solid(&self) -> bool {
826
9746
        !self.seat_carets.is_empty() && !self.has_active_editing()
827
9746
    }
828

            
829
    /// Forget seat `seat_id`'s caret.
830
    pub fn clear_seat_caret(&mut self, seat_id: u64) {
831
        self.seat_carets.remove(&seat_id);
832
    }
833

            
834
    /// Shift every non-primary seat caret on `node` across an edit of that
835
    /// node - the peer-caret rule (U3) applied to seats. `except` is the
836
    /// seat whose own edit this is: its caret was already set from the edit
837
    /// result.
838
    pub fn shift_seat_carets_across(
839
        &mut self,
840
        node: DomNodeId,
841
        changes: &[azul_core::selection::RunTextChange],
842
        except: Option<u64>,
843
    ) {
844
        let diff = azul_core::selection::RunTextDiff {
845
            remap: None,
846
            changes: changes.to_vec(),
847
        };
848
        self.shift_seat_carets_across_diff(node, &diff, except);
849
    }
850

            
851
    /// `shift_seat_carets_across` for a diff that may also have changed the
852
    /// run count (U3-a-i).
853
2870
    pub fn shift_seat_carets_across_diff(
854
2870
        &mut self,
855
2870
        node: DomNodeId,
856
2870
        diff: &azul_core::selection::RunTextDiff,
857
2870
        except: Option<u64>,
858
2870
    ) {
859
2870
        if diff.is_empty() {
860
            return;
861
2870
        }
862
3000
        for (seat, caret) in &mut self.seat_carets {
863
130
            if Some(*seat) == except || caret.node != node {
864
110
                continue;
865
20
            }
866
20
            caret.cursor = diff.map_cursor(caret.cursor);
867
20
            if let Some(anchor) = caret.anchor {
868
                let mapped = diff.map_cursor(anchor);
869
                caret.anchor = if mapped == caret.cursor {
870
                    None
871
                } else {
872
                    Some(mapped)
873
                };
874
20
            }
875
        }
876
2870
    }
877

            
878
    /// Whether the cursor should be drawn (editing active AND blink visible).
879
    #[must_use]
880
4636
    pub const fn should_draw_cursor(&self) -> bool {
881
4636
        self.has_active_editing() && self.blink.is_visible
882
4636
    }
883

            
884
    /// Initialize editing for a newly focused contenteditable element.
885
    ///
886
    /// Creates a `MultiCursorState` with a single cursor, starts the blink,
887
    /// and sets preedit to None.
888
    ///
889
    /// # The caret is SOLID for the first half-period, not just "visible"
890
    ///
891
    /// This used to set `is_visible = true` and, in the same breath,
892
    /// `last_input_time = None`. Those two statements contradict each other:
893
    /// `None` is the "no input has EVER been recorded" encoding, for which
894
    /// [`BlinkState::should_blink`] is true immediately — so the blink timer's
895
    /// FIRST tick (a `Timer` with an interval and no delay runs on the first
896
    /// pump) toggled the freshly-shown caret straight back OFF. Clicking or
897
    /// tabbing into a field made the caret disappear on the next frame and only
898
    /// reappear a blink-interval later, which reads as a glitch and matches no
899
    /// other toolkit.
900
    ///
901
    /// It also made every caller responsible for repairing the state this
902
    /// method had just broken. Two of the three did:
903
    /// `LayoutWindow::handle_focus_change_for_cursor_blink` calls
904
    /// `reset_blink_on_input` BEFORE the deferred `finalize_pending_focus_changes`
905
    /// gets here (so its timestamp was overwritten with `None`), and
906
    /// `process_mouse_click_for_selection` calls it immediately AFTER (so its
907
    /// caret survived). The third, `process_accessibility_action`, did not — an
908
    /// AT-driven focus got the broken phase.
909
    ///
910
    /// `reset_blink_on_input(now)` sets BOTH halves consistently: caret shown
911
    /// AND the blink phase anchored at this instant, so `should_blink` stays
912
    /// false for `CURSOR_BLINK_INTERVAL_MS` and the first toggle happens one
913
    /// half-period after focus. That is the behaviour every other toolkit ships,
914
    /// and it makes the callers' own `reset_blink_on_input` calls redundant
915
    /// rather than load-bearing.
916
    ///
917
    /// `Instant::now()` honours the thread-scoped E2E test clock, so this stays
918
    /// deterministic under `tick_ms`.
919
    /// Record which focusable the caret is about to sit inside, dropping the
920
    /// tracked caret/selection geometry when that is a DIFFERENT one.
921
    ///
922
    /// Call this immediately before [`Self::initialize_editing`], with
923
    /// `LayoutWindow::find_focusable_ancestor` of the node the caret is landing
924
    /// on. The geometry is what the tween glides FROM, so dropping it is what
925
    /// turns a glide into a jump.
926
    ///
927
    /// Node identity is the wrong test: a text field is a focusable container
928
    /// wrapping a contenteditable child, so every caret move inside one field
929
    /// would look like a "different node" while two separate fields' carets
930
    /// look no different from two paragraphs of the same editor. The caret
931
    /// should glide between paragraphs sitting next to each other — it really
932
    /// did travel that distance — but never between two text inputs, where it
933
    /// would animate out of one box, across whatever lies between, and into
934
    /// the other.
935
425
    pub fn enter_focus_scope(&mut self, scope: Option<DomNodeId>) {
936
        // A scope of None (text in no focusable at all) compares equal to
937
        // itself, so plain prose keeps gliding within itself.
938
425
        if self.tween.focus_scope != scope {
939
156
            self.tween.reset_text_tweens();
940
269
        }
941
425
        self.tween.focus_scope = scope;
942
425
    }
943

            
944
1348
    pub fn initialize_editing(
945
1348
        &mut self,
946
1348
        cursor: TextCursor,
947
1348
        dom_id: DomId,
948
1348
        node_id: NodeId,
949
1348
        contenteditable_key: u64,
950
1348
    ) {
951
1348
        let dom_node_id = DomNodeId {
952
1348
            dom: dom_id,
953
1348
            node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
954
1348
        };
955
1348
        self.multi_cursor = Some(MultiCursorState::new_with_cursor(
956
1348
            cursor,
957
1348
            dom_node_id,
958
1348
            contenteditable_key,
959
1348
        ));
960
        // The tween now tracks THIS node's caret. The previously rendered
961
        // geometry is kept on purpose — that is what makes the caret glide
962
        // from where it was to where it landed.
963
        //
964
        // Whether that glide is WANTED is decided by focus scope, not by node
965
        // identity, and only the tree knows the scopes: see
966
        // [`Self::enter_focus_scope`], which the caller invokes first and which
967
        // drops this geometry when the caret crosses into a different
968
        // focusable.
969
1348
        self.tween.node = Some(dom_node_id);
970
1348
        self.blink.reset_blink_on_input(Instant::now());
971
1348
        self.clear_preedit();
972
1348
        self.mark_dirty();
973
1348
    }
974

            
975
    /// End editing (focus left the contenteditable element).
976
70
    pub fn clear_editing(&mut self) {
977
        // Only ask for a repaint if there was something to erase.
978
        //
979
        // This used to mark dirty unconditionally, and it is reached on EVERY
980
        // focus change — including a Tab between two nodes that were never
981
        // editable. The manager then owed a repaint it had no pixels for, and
982
        // because `display_list_dirty` is a latch, one such focus move left the
983
        // window permanently "not idle": a permanent repaint request, on every
984
        // frame, for the rest of the window's life.
985
        //
986
        // Caught by the E2E non-interference gate, which saw `text_edit` move
987
        // on a focus-only step with the fingerprint otherwise identical —
988
        // cursor=none, preedit="" both before and after, and only `dirty`
989
        // flipping. Nothing changed, so nothing was owed.
990
70
        let had_cursor = self.multi_cursor.is_some();
991
70
        let had_blink = self.blink.is_visible
992
28
            || self.blink.last_input_time.is_some()
993
28
            || self.blink.blink_timer_active;
994

            
995
70
        self.multi_cursor = None;
996
70
        self.blink.clear();
997
70
        let had_preedit = self.clear_preedit_returning_changed();
998

            
999
70
        if had_cursor || had_blink || had_preedit {
42
            self.mark_dirty();
68
        }
70
    }
    // === IME preedit ===
    /// Set the IME preedit (composition) text.
    ///
    /// Also records the composition phase so the engine can emit
    /// `CompositionStart` / `CompositionUpdate`. The four desktop shells each
    /// run a real IME client and all of them funnelled into here, which is why
    /// the built-in text widgets composed correctly while the `Composition*`
    /// filters never fired: the state landed, the event never existed.
    ///
    /// Start vs. update is decided by whether a composition was already open,
    /// not by which platform callback ran — Win32 sends an explicit
    /// `WM_IME_STARTCOMPOSITION` but Wayland's `preedit_string` has no start
    /// event at all, so the shells cannot agree on the boundary and the engine
    /// has to own it.
153
    pub fn set_preedit(&mut self, text: String, cursor_begin: i32, cursor_end: i32) {
153
        let was_composing = self.preedit_text.is_some();
153
        self.pending_composition = Some(if was_composing {
8
            CompositionPhase::Update
        } else {
145
            CompositionPhase::Start
        });
153
        self.composition_text.clone_from(&text);
153
        self.preedit_text = if text.is_empty() { None } else { Some(text) };
153
        self.preedit_cursor_begin = cursor_begin;
153
        self.preedit_cursor_end = cursor_end;
153
        self.mark_dirty();
153
    }
    /// Record that a composition was committed, carrying the committed string.
    ///
    /// W3C defines `compositionend.data` as what was COMMITTED, not what was
    /// pending, which is why the text is passed in rather than read off the
    /// (already cleared) preedit.
    /// `set_preedit` for seat `seat_id` (9b-ii-a-i-d-ii-c); the primary's for
    /// seat 0. Empty text clears.
60
    pub fn set_preedit_for_seat(
60
        &mut self,
60
        seat_id: u64,
60
        text: String,
60
        cursor_begin: i32,
60
        cursor_end: i32,
60
    ) {
60
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.set_preedit(text, cursor_begin, cursor_end);
            return;
60
        }
60
        let was_composing = self.seat_preedits.contains_key(&seat_id);
60
        if text.is_empty() {
            self.clear_preedit_for_seat(seat_id);
            return;
60
        }
        // The seat's composition event (9b-ii-a-i-d-ii-c-i): Start on the
        // first preedit, Update after - the primary's rule.
60
        self.seat_pending_compositions.insert(
60
            seat_id,
            SeatPendingComposition {
60
                phase: if was_composing {
10
                    CompositionPhase::Update
                } else {
50
                    CompositionPhase::Start
                },
60
                text: text.clone(),
60
                cursor_begin,
60
                cursor_end,
            },
        );
60
        self.seat_preedits.insert(
60
            seat_id,
60
            SeatPreedit {
60
                text,
60
                cursor_begin,
60
                cursor_end,
60
            },
        );
60
        self.mark_dirty();
60
    }
    /// `clear_preedit` for seat `seat_id`.
20
    pub fn clear_preedit_for_seat(&mut self, seat_id: u64) {
20
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.clear_preedit();
20
        } else if self.seat_preedits.remove(&seat_id).is_some() {
20
            // A composition that vanished without a commit ENDS with empty
20
            // text - a cancel, as for the primary (9b-ii-a-i-d-ii-c-i) -
20
            // unless a phase is already waiting from this pass.
20
            self.seat_pending_compositions
20
                .entry(seat_id)
20
                .or_insert(SeatPendingComposition {
20
                    phase: CompositionPhase::End,
20
                    text: String::new(),
20
                    cursor_begin: 0,
20
                    cursor_end: 0,
20
                });
20
            self.mark_dirty();
20
        }
20
    }
    /// Drain the other seats' composition phases after the pass that
    /// emitted them (9b-ii-a-i-d-ii-c-i), as `take_pending_composition`
    /// does for the primary's.
4
    pub fn take_pending_seat_compositions(&mut self) -> BTreeMap<u64, SeatPendingComposition> {
4
        core::mem::take(&mut self.seat_pending_compositions)
4
    }
    /// Seat `seat_id`'s composition, if one is in progress.
    #[must_use]
120
    pub fn seat_preedit(&self, seat_id: u64) -> Option<&SeatPreedit> {
120
        self.seat_preedits.get(&seat_id)
120
    }
    /// `commit_composition` for seat `seat_id`: ends its preedit and queues
    /// its `CompositionEnd` with the committed text (9b-ii-a-i-d-ii-c-i).
20
    pub fn commit_composition_for_seat(&mut self, seat_id: u64, committed: String) {
20
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.commit_composition(committed);
20
        } else {
20
            // `CompositionEnd` carries the COMMITTED text (W3C), whether or
20
            // not a preedit was pending.
20
            self.seat_pending_compositions.insert(
20
                seat_id,
20
                SeatPendingComposition {
20
                    phase: CompositionPhase::End,
20
                    text: committed,
20
                    cursor_begin: 0,
20
                    cursor_end: 0,
20
                },
20
            );
20
            self.seat_preedits.remove(&seat_id);
20
            self.mark_dirty();
20
        }
20
    }
1
    pub fn commit_composition(&mut self, committed: String) {
1
        self.pending_composition = Some(CompositionPhase::End);
1
        self.composition_text = committed;
1
        self.clear_preedit();
1
    }
    /// Request that the on-screen keyboard be shown or hidden.
    ///
    /// A REQUEST, not a state: only the OS knows whether a keyboard is
    /// actually up (a hardware keyboard suppresses it, the user can dismiss
    /// it), so this records intent and the shell reconciles. Desktop shells
    /// ignore it entirely.
    /// # LAST WRITER WINS, and that is the whole ordering rule (10a-iv)
    ///
    /// TWO writers share this queue: the focus-driven raise the shell issues
    /// when an editable gains focus, and the app's own
    /// `CallbackInfo::request_soft_keyboard`. They used to be separate paths -
    /// the shell called the platform directly while the app's request was
    /// drained per platform - so two writers hit one piece of OS state with no
    /// ordering between them, and an app that focused a field and then asked
    /// for the keyboard to stay down raced its own request.
    ///
    /// One queue makes the order defined: a callback runs AFTER the focus
    /// change that triggered it, so the app's call is an override of the focus
    /// default rather than a coin flip.
    /// # LAST WRITER WINS, and that is the whole ordering rule (10a-iv)
    ///
    /// TWO writers share this queue: the focus-driven raise the shell issues
    /// when an editable gains focus, and the app's own
    /// `CallbackInfo::request_soft_keyboard`. They used to be separate paths -
    /// the shell called the platform directly while the app's request was
    /// drained per platform - so two writers hit one piece of OS state with no
    /// ordering between them, and an app that focused a field and then asked
    /// for the keyboard to stay down raced its own request.
    ///
    /// One queue makes the order defined: a callback runs AFTER the focus
    /// change that triggered it, so the app's call is an override of the focus
    /// default rather than a coin flip.
4
    pub const fn request_soft_keyboard(&mut self, visible: bool) {
4
        self.pending_soft_keyboard = Some(visible);
4
    }
    /// Drain the on-screen keyboard request, if one was made this pass.
4
    pub const fn take_soft_keyboard_request(&mut self) -> Option<bool> {
4
        self.pending_soft_keyboard.take()
4
    }
    /// Record what `node` contained at the moment it gained focus.
    ///
    /// Called for every node that receives focus, editable or not: whether it
    /// was editable is not knowable here, and a snapshot of a non-editable
    /// node simply never gets compared.
8
    pub fn snapshot_value_at_focus(&mut self, node: DomNodeId, value: String) {
8
        self.value_at_focus = Some((node, value));
8
    }
    /// Whether `node`'s value differs from what it held when it gained focus.
    ///
    /// `None` means the question cannot be answered - no snapshot, or one
    /// belonging to a DIFFERENT node - and the caller must not emit `Change`
    /// on a guess. That case is reachable: focus can be set programmatically
    /// before any snapshot exists.
    #[must_use]
9
    pub fn value_changed_since_focus(&self, node: DomNodeId, current: &str) -> Option<bool> {
7
        match &self.value_at_focus {
7
            Some((snapshot_node, snapshot)) if *snapshot_node == node => {
5
                Some(snapshot.as_str() != current)
            }
4
            _ => None,
        }
9
    }
    /// Drop the snapshot, once the node it belongs to has lost focus.
1
    pub fn clear_value_at_focus(&mut self) {
1
        self.value_at_focus = None;
1
    }
    /// Take the pending composition phase, if any. Drained once per pass by
    /// the event-determination path.
7
    pub fn take_pending_composition(&mut self) -> Option<(CompositionPhase, String)> {
7
        self.pending_composition
7
            .take()
7
            .map(|phase| (phase, core::mem::take(&mut self.composition_text)))
7
    }
    /// Clear the IME preedit text (composition ended or cancelled).
1433
    pub fn clear_preedit(&mut self) {
1433
        let _ = self.clear_preedit_returning_changed();
1433
    }
    /// Clear the preedit, reporting whether anything was actually cleared.
    ///
    /// Split out so `clear_editing` can decide whether a repaint is owed
    /// without marking dirty twice — and so clearing an ALREADY-clear preedit
    /// costs nothing, which is the common case on a focus change.
1503
    fn clear_preedit_returning_changed(&mut self) -> bool {
1503
        let changed = self.preedit_text.is_some()
1418
            || self.preedit_cursor_begin != -1
1418
            || self.preedit_cursor_end != -1;
1503
        if !changed {
1418
            return false;
85
        }
        // A cancelled composition still ENDS. Recording the phase here rather
        // than at each call site means every shell's cancel path — macOS
        // `unmarkText`, Wayland's empty preedit, Win32 `WM_IME_ENDCOMPOSITION`,
        // focus loss — fires `CompositionEnd` without four separate edits, and
        // an app that opened a composition overlay always gets told to close
        // it. `commit_composition` runs first and has already set the phase
        // plus the committed text, so it is not clobbered here; a cancel
        // carries no text, which is the difference an app reads.
85
        if self.preedit_text.is_some() && self.pending_composition.is_none() {
1
            self.pending_composition = Some(CompositionPhase::End);
1
            self.composition_text = String::new();
84
        }
85
        self.preedit_text = None;
85
        self.preedit_cursor_begin = -1;
85
        self.preedit_cursor_end = -1;
85
        self.mark_dirty();
85
        true
1503
    }
    // === Convenience for building cursor_locations ===
    /// Build the Vec of cursor locations for `LayoutContext`.
    ///
    /// Returns all cursor positions from `MultiCursorState`, or empty if not editing.
    #[must_use]
14395
    pub fn build_cursor_locations(&self) -> Vec<CursorLocation> {
14395
        let mut out: Vec<CursorLocation> = Vec::new();
14395
        if let Some(ref mc) = self.multi_cursor {
5387
            if let Some(node_id) = mc.node_id.node.into_crate_internal() {
6396
                out.extend(mc.selections.iter().map(|s| {
6396
                    let cursor = match &s.selection {
6163
                        Selection::Cursor(c) => *c,
233
                        Selection::Range(r) => r.end,
                    };
6396
                    CursorLocation {
6396
                        dom: mc.node_id.dom,
6396
                        node: node_id,
6396
                        cursor,
6396
                        owner: s.owner,
6396
                        preedit_bytes: 0,
6396
                        preedit_chars: 0,
6396
                    }
6396
                }));
1
            }
9008
        }
        // The other seats' carets (9b-ii-a-i-d-ii-a), drawn like peer carets
        // under their seat owner - on whatever node each sits in.
14585
        for (seat, caret) in &self.seat_carets {
190
            let Some(node_id) = caret.node.node.into_crate_internal() else {
                continue;
            };
190
            let (preedit_bytes, preedit_chars) = self.seat_preedits.get(seat).map_or((0, 0), |p| {
50
                (p.text.len() as u32, p.text.chars().count() as u32)
50
            });
190
            out.push(CursorLocation {
190
                dom: caret.node.dom,
190
                node: node_id,
190
                cursor: caret.cursor,
190
                owner: azul_core::selection::SelectionOwner::seat(*seat),
190
                preedit_bytes,
190
                preedit_chars,
190
            });
        }
14395
        out
14395
    }
    /// The colour a participant's caret and selection are painted in (U1).
    ///
    /// `None` for an owner the app has not named, which is the answer for the
    /// LOCAL caret too: it keeps using the node's own `caret-color`, so a
    /// single-user app is unaffected by any of this.
    #[must_use]
186
    pub fn owner_color(&self, owner: azul_core::selection::SelectionOwner) -> Option<ColorU> {
186
        self.owner_colors.get(&owner).copied()
186
    }
    /// Name a participant's colour, or drop it with `None`.
    ///
    /// Per OWNER rather than per node, which is why this is a registry and not
    /// a CSS property: `caret-color` answers "what colour is the caret in this
    /// field", and a shared session needs "what colour is Alice" - a different
    /// axis, and one the stylesheet cannot know.
    pub fn set_owner_color(
        &mut self,
        owner: azul_core::selection::SelectionOwner,
        color: Option<ColorU>,
    ) {
        match color {
            Some(c) => {
                self.owner_colors.insert(owner, c);
            }
            None => {
                self.owner_colors.remove(&owner);
            }
        }
        self.mark_dirty();
    }
    /// Cross-block selection (spans multiple IFC roots), precomputed by
    /// `LayoutWindow::set_cross_block_selection` — the manager stores it
    /// render-ready because computing the per-IFC ranges needs layout/text
    /// access the manager does not have. Cleared by any single-node cursor
    /// interaction. When set, it wins over `multi_cursor` for rendering.
345
    pub fn set_cross_block_selection(&mut self, sel: azul_core::selection::TextSelection) {
345
        self.cross_block = Some(sel);
345
        self.display_list_dirty = true;
345
    }
    /// Clear the cross-block selection (single-node interactions do this).
123
    pub fn clear_cross_block_selection(&mut self) {
123
        if self.cross_block.take().is_some() {
20
            self.display_list_dirty = true;
103
        }
123
    }
    /// Take the cross-block selection (delete/apply flows consume it).
80
    pub const fn take_cross_block_selection(
80
        &mut self,
80
    ) -> Option<azul_core::selection::TextSelection> {
80
        let s = self.cross_block.take();
80
        if s.is_some() {
80
            self.display_list_dirty = true;
80
        }
80
        s
80
    }
    /// The active cross-block selection, if any.
    #[must_use]
64
    pub const fn get_cross_block_selection(&self) -> Option<&azul_core::selection::TextSelection> {
64
        self.cross_block.as_ref()
64
    }
    /// Every range selection of the current editing session.
    ///
    /// `None` when there is no session, the session's node is detached, or the
    /// session holds only bare carets — a collapsed caret is not a selection,
    /// so there is nothing to highlight.
    ///
    /// This is the COMPLETE selection data. `select_next_occurrence` (Ctrl+D)
    /// builds sessions with several ranges on one node, and the render-facing
    /// [`Self::build_text_selections_map`] can carry only one of them (see
    /// there); anything that needs all of them reads this.
    #[must_use]
14184
    pub fn session_selection_ranges(&self) -> Option<SessionSelectionRanges> {
14184
        let mc = self.multi_cursor.as_ref()?;
5328
        let node_id = mc.node_id.node.into_crate_internal()?;
5325
        let mut ranges = Vec::new();
5325
        let mut primary = None;
10669
        for sel in &mc.selections {
5344
            if let Selection::Range(range) = &sel.selection {
                // LOCAL ONLY (U1-a). Before the owner existed every range in
                // this list was the local session's by definition; after U1 a
                // remote participant's range landed in the same list and every
                // reader treated it as the local user's own - painted in the
                // one `::selection` colour, and copied by Ctrl+C. Other
                // participants' ranges come from
                // [`Self::remote_selection_ranges`] instead.
248
                if !sel.owner.is_local() {
4
                    continue;
244
                }
244
                if sel.id == mc.primary_id {
230
                    primary = Some(*range);
230
                }
244
                ranges.push(*range);
5096
            }
        }
        // The primary selection can be a bare caret while other selections are
        // ranges (a multi-cursor click adds one; an edit can collapse the
        // primary range). The document-first range then stands in, so the
        // endpoints always describe a range that is actually painted.
5325
        let primary = primary.or_else(|| ranges.first().copied())?;
232
        Some(SessionSelectionRanges {
232
            dom_id: mc.node_id.dom,
232
            node_id,
232
            ranges,
232
            primary,
232
        })
14184
    }
    /// OTHER PARTICIPANTS' range selections on the current session's node.
    ///
    /// A separate accessor rather than a field on
    /// [`SessionSelectionRanges`], because a remote range exists independently
    /// of whether the local user has one: the ordinary collaborative case is
    /// "I have a caret, you have a selection", and that case returns `None`
    /// from the local accessor by design - a bare caret is not a selection.
    /// Hanging the remote ranges off the local result would have made
    /// everybody else's highlight disappear the moment the local user
    /// collapsed their own.
    ///
    /// `None` when there is no session or its node is detached; empty is
    /// reported as `None` too, so a single-user app never allocates.
    #[must_use]
14179
    pub fn remote_selection_ranges(&self) -> Option<RemoteSelectionRanges> {
14179
        let mc = self.multi_cursor.as_ref()?;
5324
        let node_id = mc.node_id.node.into_crate_internal()?;
5322
        let mut ranges = Vec::new();
5322
        let mut local_cursor = None;
10659
        for sel in &mc.selections {
5337
            if sel.owner.is_local() {
                // The local caret stands in for the anchor/focus of a
                // remote-only paint, so remember it here rather than walking
                // the list twice.
5334
                if local_cursor.is_none() {
5321
                    local_cursor = Some(match &sel.selection {
5090
                        Selection::Cursor(c) => *c,
231
                        Selection::Range(r) => r.end,
                    });
13
                }
5334
                continue;
3
            }
3
            if let Selection::Range(range) = &sel.selection {
3
                ranges.push((sel.owner, *range));
3
            }
        }
5322
        if ranges.is_empty() {
5319
            return None;
3
        }
3
        Some(RemoteSelectionRanges {
3
            dom_id: mc.node_id.dom,
3
            node_id,
3
            ranges,
3
            local_cursor,
3
        })
14179
    }
    /// Build a `TextSelection` map for the display list's `paint_selections`.
    ///
    /// Extracts Range selections from `MultiCursorState` into the format that
    /// `LayoutContext.text_selections` expects: `BTreeMap<DomId, TextSelection>`.
    /// The `affected_nodes` map uses the editing node's `NodeId` as key.
    ///
    /// `anchor`, `focus` and `is_forward` all describe the SAME range — the
    /// session's primary, which is also one of the ranges in `affected_nodes`.
    /// They used to disagree: the endpoints came from the first range,
    /// `affected_nodes` kept the last (each insert overwrote the same key), and
    /// `is_forward` was hard-coded.
    ///
    /// `affected_nodes` carries EVERY range of the session under the one node
    /// key, so a multi-range (Ctrl+D) session paints all of its occurrences and
    /// not just the primary one.
    #[must_use]
14408
    pub fn build_text_selections_map(
14408
        &self,
14408
    ) -> BTreeMap<DomId, azul_core::selection::TextSelection> {
14408
        let mut map = self.build_primary_text_selections_map();
14408
        self.fold_seat_selections(&mut map);
14408
        map
14408
    }
    /// The other seats' SELECTIONS (an anchored seat caret, 9b-ii-a-i-d-ii-a)
    /// into the map the display list paints, as remote ranges under the
    /// seat's owner - so they take the seat's tint like a peer's. A dom
    /// with no primary selection gets a collapsed entry to hang them on.
14408
    fn fold_seat_selections(&self, map: &mut BTreeMap<DomId, azul_core::selection::TextSelection>) {
        use azul_core::selection::{SelectionOwner, TextSelection};
14588
        for (seat, caret) in &self.seat_carets {
180
            let Selection::Range(range) = caret.selection() else {
130
                continue;
            };
50
            let Some(node_id) = caret.node.node.into_crate_internal() else {
                continue;
            };
50
            let owner = SelectionOwner::seat(*seat);
50
            let entry = map.entry(caret.node.dom).or_insert_with(|| {
50
                TextSelection::new_collapsed(
50
                    caret.node.dom,
50
                    node_id,
50
                    caret.cursor,
50
                    LogicalRect::zero(),
50
                    LogicalPosition::zero(),
                )
50
            });
50
            entry
50
                .remote_ranges
50
                .entry(node_id)
50
                .or_default()
50
                .push((owner, range));
        }
14408
    }
14408
    fn build_primary_text_selections_map(
14408
        &self,
14408
    ) -> BTreeMap<DomId, azul_core::selection::TextSelection> {
14408
        if let Some(cb) = &self.cross_block {
231
            let mut map = BTreeMap::new();
231
            map.insert(cb.dom_id, cb.clone());
231
            return map;
14177
        }
        use azul_core::selection::{SelectionAnchor, SelectionFocus, TextSelection};
14177
        let mut map = BTreeMap::new();
14177
        let remote = self.remote_selection_ranges();
14177
        let Some(session) = self.session_selection_ranges() else {
            // NO LOCAL RANGE, but somebody else may still have one - the usual
            // collaborative case, since the local user having a bare caret is
            // the default state. Paint a collapsed selection at the local
            // caret carrying the remote ranges: `is_collapsed` is then true,
            // so the local highlight path draws nothing while the remote one
            // still runs.
13948
            if let Some(remote) = remote {
                // A collapsed pair still has to name a cursor. With no
                // local caret to name (defensive - a session always has one)
                // the first remote range's start stands in: anchor and focus
                // are equal either way, so nothing local is painted from it.
1
                let cursor = remote
1
                    .local_cursor
1
                    .unwrap_or_else(|| remote.ranges[0].1.start);
1
                let mut sel = TextSelection::new_collapsed(
1
                    remote.dom_id,
1
                    remote.node_id,
1
                    cursor,
1
                    LogicalRect::zero(),
1
                    LogicalPosition::zero(),
                );
1
                sel.remote_ranges.insert(remote.node_id, remote.ranges);
1
                map.insert(remote.dom_id, sel);
13947
            }
13948
            return map;
        };
229
        let range = session.primary;
229
        let mut affected_nodes = BTreeMap::new();
229
        affected_nodes.insert(session.node_id, session.ranges);
229
        let mut remote_ranges = BTreeMap::new();
229
        if let Some(remote) = remote {
1
            remote_ranges.insert(remote.node_id, remote.ranges);
228
        }
229
        map.insert(
229
            session.dom_id,
229
            TextSelection {
229
                dom_id: session.dom_id,
229
                anchor: SelectionAnchor {
229
                    ifc_root_node_id: session.node_id,
229
                    cursor: range.start,
229
                    char_bounds: LogicalRect::zero(),
229
                    mouse_position: LogicalPosition::zero(),
229
                },
229
                focus: SelectionFocus {
229
                    ifc_root_node_id: session.node_id,
229
                    cursor: range.end,
229
                    mouse_position: LogicalPosition::zero(),
229
                },
229
                affected_nodes,
229
                remote_ranges,
229
                is_forward: range_is_forward(&range),
229
            },
        );
229
        map
14408
    }
}
impl crate::managers::NodeIdRemap for TextEditManager {
    /// Remap every node-keyed piece of editing state onto the rebuilt DOM: the
    /// multi-cursor session, the caret/selection tween geometry, the
    /// cross-block selection, and the queued edit notifications.
    ///
    /// `MultiCursorState::remap_node_ids` clears the selections when the edited
    /// node is gone; here we additionally drop the whole editing session, since a
    /// cursor whose IFC root no longer exists is not an editing session.
464
    fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
        // The other seats' carets (9b-ii-a-i-d-ii): follow the node, drop on
        // an unmounted one - the same rule as the primary's below.
464
        self.seat_carets.retain(|_, caret| {
            if caret.node.dom != dom {
                return true;
            }
            match caret
                .node
                .node
                .into_crate_internal()
                .and_then(|old| map.resolve(old))
            {
                Some(new_id) => {
                    caret.node.node = NodeHierarchyItemId::from_crate_internal(Some(new_id));
                    true
                }
                None => false,
            }
        });
        // The tween's caret/selection geometry belongs to the session's node.
        // Resolve that anchor BEFORE the session below can be dropped — and
        // fall back to the session for state that was installed by writing
        // `multi_cursor` directly (which cannot set the anchor), so a stale
        // `None` heals itself here instead of leaving the geometry orphaned.
464
        let tween_node = self
464
            .tween
464
            .node
464
            .or_else(|| self.multi_cursor.as_ref().map(|mc| mc.node_id));
464
        if let Some(ref mut mc) = self.multi_cursor {
63
            if mc.node_id.dom == dom {
61
                let unmounted = mc
61
                    .node_id
61
                    .node
61
                    .into_crate_internal()
61
                    .is_none_or(|old| map.resolve(old).is_none());
61
                if unmounted {
6
                    self.multi_cursor = None;
6
                    self.preedit_text = None;
6
                    self.preedit_cursor_begin = -1;
6
                    self.preedit_cursor_end = -1;
6
                    self.display_list_dirty = true;
58
                } else {
55
                    mc.remap_node_ids(dom, map.as_btree_map());
55
                }
2
            }
401
        }
        // The tween follows its node, and dies with it: `last_caret` /
        // `last_selection` describe a rectangle that belonged to a node which
        // is now gone, and the next display-list pass would glide the caret
        // out of it across the screen.
464
        if let Some(old) = tween_node {
63
            match map.resolve_dom_node_id(dom, old) {
57
                Some(new_id) => self.tween.node = Some(new_id),
6
                None => self.tween.reset_text_tweens(),
            }
401
        }
        // A cross-block selection is render-ready geometry keyed by IFC-root
        // NodeIds. Unremapped, it paints a highlight over whichever nodes
        // inherited those indices.
464
        if self.cross_block.as_ref().is_some_and(|cb| cb.dom_id == dom) {
3
            self.remap_cross_block_selection(map);
461
        }
        // Queued `Input` notifications name the host they belong to; a host
        // that was unmounted has no event to dispatch, and keeping the id
        // would dispatch it at the node that took its place.
464
        self.pending_edit_notifications.retain_mut(|node| {
3
            match map.resolve_dom_node_id(dom, *node) {
2
                Some(new_id) => {
2
                    *node = new_id;
2
                    true
                }
1
                None => false,
            }
3
        });
        // Same for the post-commit `TextChanged` queue: a text node that the
        // rebuild unmounted (the Enter split moves its text into a new leaf)
        // has nothing to report; the surviving one is renamed in place.
464
        self.pending_text_changed
464
            .retain_mut(|node| match map.resolve_dom_node_id(dom, *node) {
12
                Some(new_id) => {
12
                    *node = new_id;
12
                    true
                }
1
                None => false,
13
            });
464
    }
}
impl TextEditManager {
    /// Rewrite the cross-block selection's IFC-root ids for the rebuilt DOM.
    ///
    /// The selection is dropped outright when either endpoint's root is gone:
    /// a band whose anchor or focus no longer exists has no endpoints to paint
    /// between. Interior roots that were unmounted are dropped individually.
3
    fn remap_cross_block_selection(&mut self, map: &crate::managers::NodeIdMap) {
3
        let Some(ref mut cb) = self.cross_block else {
            return;
        };
2
        let (Some(anchor), Some(focus)) = (
3
            map.resolve(cb.anchor.ifc_root_node_id),
3
            map.resolve(cb.focus.ifc_root_node_id),
        ) else {
1
            self.cross_block = None;
1
            self.display_list_dirty = true;
1
            return;
        };
2
        let mut changed =
2
            anchor != cb.anchor.ifc_root_node_id || focus != cb.focus.ifc_root_node_id;
2
        cb.anchor.ifc_root_node_id = anchor;
2
        cb.focus.ifc_root_node_id = focus;
2
        let before: Vec<NodeId> = cb.affected_nodes.keys().copied().collect();
2
        cb.affected_nodes = core::mem::take(&mut cb.affected_nodes)
2
            .into_iter()
4
            .filter_map(|(node, ranges)| map.resolve(node).map(|new| (new, ranges)))
2
            .collect();
2
        changed |= !cb.affected_nodes.keys().copied().eq(before);
        // Only owe a repaint when the painted band actually moved:
        // `display_list_dirty` is a latch, and a rebuild that renumbered
        // nothing has no pixels to redraw (see `clear_editing`).
2
        if changed {
1
            self.display_list_dirty = true;
1
        }
3
    }
}
// ============================================================================
// AUTOTEST: adversarial tests for `BlinkState` + `TextEditManager`
// ============================================================================
#[cfg(test)]
mod autotest_generated {
    use super::*;
    /// The old `(DomId, NodeId, TextCursor)` shape, for tests written before
    /// `CursorLocation` gained its owner (U1). Keeping them comparing the
    /// three fields they were written about is better than rewriting each
    /// assertion around a field they say nothing about.
    fn locs_as_triples(m: &TextEditManager) -> Vec<(DomId, NodeId, TextCursor)> {
        m.build_cursor_locations()
            .into_iter()
            .map(|l| (l.dom, l.node, l.cursor))
            .collect()
    }
    /// THE ORDERING RULE (10a-iv). Two writers share one queue - the shell's
    /// focus-driven raise and the app's explicit request - and the app must be
    /// able to override, because a callback runs after the focus change that
    /// triggered it.
    #[test]
    fn the_last_soft_keyboard_request_in_a_pass_wins() {
        let mut m = TextEditManager::new();
        assert_eq!(m.take_soft_keyboard_request(), None, "nothing asked yet");
        // Focus raises it, then the app says no in its callback.
        m.request_soft_keyboard(true);
        m.request_soft_keyboard(false);
        assert_eq!(
            m.take_soft_keyboard_request(),
            Some(false),
            "the app's later call must override the focus default"
        );
        assert_eq!(
            m.take_soft_keyboard_request(),
            None,
            "a drained request must not fire twice - one raise per pass"
        );
        // And the other way round.
        m.request_soft_keyboard(false);
        m.request_soft_keyboard(true);
        assert_eq!(m.take_soft_keyboard_request(), Some(true));
    }
    use azul_core::{
        selection::{
            CursorAffinity, GraphemeClusterId, IdentifiedSelection, SelectionId, SelectionRange,
        },
        task::{Duration, SystemTick, SystemTimeDiff},
    };
    use super::*;
    use crate::managers::{NodeIdMap, NodeIdRemap};
    const DOM0: DomId = DomId { inner: 0 };
    const DOM1: DomId = DomId { inner: 1 };
    /// A `DomId` at the very top of the `usize` range — nothing indexes with it,
    /// so it must be carried through unchanged like any other id.
    const DOM_MAX: DomId = DomId { inner: usize::MAX };
    /// `NodeHierarchyItemId` stores nodes 1-based (`from_crate_internal` computes
    /// `index + 1`), so the largest node index that can survive a round-trip
    /// through a `DomNodeId` is `usize::MAX - 1`. `NodeId::new(usize::MAX)` is not
    /// representable and is deliberately never fed to `initialize_editing`.
    const MAX_ENCODABLE_NODE: usize = usize::MAX - 1;
    fn cursor(run: u32, byte: u32) -> TextCursor {
        TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: run,
                start_byte_in_run: byte,
            },
            affinity: CursorAffinity::Leading,
        }
    }
    fn range(from: TextCursor, to: TextCursor) -> SelectionRange {
        SelectionRange {
            start: from,
            end: to,
        }
    }
    fn dom_node(dom: DomId, node: Option<NodeId>) -> DomNodeId {
        DomNodeId {
            dom,
            node: NodeHierarchyItemId::from_crate_internal(node),
        }
    }
    /// Build a `MultiCursorState` with an arbitrary selection list, bypassing
    /// `add_cursor`/`add_selection` (which sort + merge) so the exact ordering
    /// under test is preserved.
    fn multi_cursor_with(
        node_id: DomNodeId,
        selections: Vec<Selection>,
        key: u64,
    ) -> MultiCursorState {
        let identified: Vec<IdentifiedSelection> = selections
            .into_iter()
            .map(|selection| IdentifiedSelection {
                id: SelectionId::new(),
                selection,
                owner: azul_core::selection::SelectionOwner::LOCAL,
            })
            .collect();
        let primary_id = identified.last().map_or_else(SelectionId::new, |s| s.id);
        MultiCursorState {
            selections: identified,
            primary_id,
            node_id,
            contenteditable_key: key,
        }
    }
    /// `base + ms`, using the engine's own saturating instant arithmetic.
    fn plus_ms(base: &Instant, ms: u64) -> Instant {
        base.add_optional_duration(Some(&Duration::System(SystemTimeDiff::from_millis(ms))))
    }
    // ------------------------------------------------------------------
    // BlinkState
    // ------------------------------------------------------------------
    #[test]
    fn autotest_blink_new_invariants() {
        let b = BlinkState::new();
        assert!(!b.is_visible, "a fresh BlinkState starts hidden");
        assert!(b.last_input_time.is_none());
        assert!(!b.is_blink_timer_active());
        assert!(!b.blink_timer_active);
        // The default interval is the wall-clock one, so every existing caller
        // that never sets an interval keeps the 530ms behaviour it had.
        assert_eq!(b.blink_interval, CURSOR_BLINK_INTERVAL);
        assert_eq!(
            b.blink_interval,
            Duration::from_millis(CURSOR_BLINK_INTERVAL_MS)
        );
        // No input has ever been recorded, so blinking is allowed immediately.
        assert!(b.should_blink(&Instant::now()));
    }
    #[test]
    fn autotest_blink_toggle_visibility_alternates_and_returns_new_state() {
        let mut b = BlinkState::new();
        assert!(b.toggle_visibility(), "first toggle turns the caret on");
        assert!(b.is_visible);
        assert!(!b.toggle_visibility(), "second toggle turns it back off");
        assert!(!b.is_visible);
        // 1000 toggles: the return value must always equal the new field value,
        // and parity must be exactly preserved (no drift, no panic).
        let mut expected = false;
        for _ in 0..1000 {
            expected = !expected;
            let returned = b.toggle_visibility();
            assert_eq!(returned, expected);
            assert_eq!(b.is_visible, expected);
        }
        assert!(
            !b.is_visible,
            "an even number of toggles restores the state"
        );
    }
    #[test]
    fn autotest_blink_set_visibility_is_idempotent_and_orthogonal() {
        let mut b = BlinkState::new();
        b.set_blink_timer_active(true);
        b.set_visibility(true);
        b.set_visibility(true);
        assert!(b.is_visible);
        assert!(
            b.is_blink_timer_active(),
            "visibility must not disturb the timer flag"
        );
        b.set_visibility(false);
        b.set_visibility(false);
        assert!(!b.is_visible);
        assert!(b.is_blink_timer_active());
    }
    #[test]
    fn autotest_blink_timer_active_true_false_and_idempotent() {
        let mut b = BlinkState::new();
        assert!(!b.is_blink_timer_active(), "known-false: default state");
        b.set_blink_timer_active(true);
        assert!(b.is_blink_timer_active(), "known-true: after activation");
        b.set_blink_timer_active(true);
        assert!(b.is_blink_timer_active(), "re-activation is idempotent");
        b.set_blink_timer_active(false);
        assert!(!b.is_blink_timer_active());
        b.set_blink_timer_active(false);
        assert!(!b.is_blink_timer_active(), "re-deactivation is idempotent");
        // The timer flag never leaks into visibility.
        assert!(!b.is_visible);
    }
    #[test]
    fn autotest_blink_reset_on_input_forces_solid_caret() {
        let mut b = BlinkState::new();
        b.set_blink_timer_active(true);
        b.set_visibility(false);
        let now = Instant::now();
        b.reset_blink_on_input(now.clone());
        assert!(b.is_visible, "typing must show a solid caret");
        assert_eq!(b.last_input_time.as_ref(), Some(&now));
        assert!(
            b.is_blink_timer_active(),
            "reset_blink_on_input must not stop the timer"
        );
        // Immediately after input, the blink interval has not elapsed.
        assert!(!b.should_blink(&now));
    }
    #[test]
    fn autotest_blink_reset_on_input_repeated_keeps_latest_timestamp() {
        let mut b = BlinkState::new();
        let base = Instant::now();
        // Simulate a fast typist: 500 keystrokes, 1ms apart.
        for i in 0..500u64 {
            b.reset_blink_on_input(plus_ms(&base, i));
            assert!(b.is_visible, "the caret stays solid throughout typing");
        }
        let last = plus_ms(&base, 499);
        assert_eq!(b.last_input_time.as_ref(), Some(&last));
        // The whole burst spans 499ms < 530ms, so blinking has still not resumed.
        assert!(!b.should_blink(&last));
    }
    #[test]
    fn autotest_blink_should_blink_without_input_is_true() {
        let b = BlinkState::new();
        let now = Instant::now();
        assert!(b.should_blink(&now));
        // Also true for an instant far in the past — no input means no gate at all.
        assert!(b.should_blink(&Instant::Tick(SystemTick::new(0))));
    }
    #[test]
    fn autotest_blink_should_blink_interval_boundary_is_strict() {
        let base = Instant::now();
        let mut b = BlinkState::new();
        b.reset_blink_on_input(base.clone());
        assert!(
            !b.should_blink(&base),
            "zero elapsed time must not restart the blink"
        );
        assert!(
            !b.should_blink(&plus_ms(&base, CURSOR_BLINK_INTERVAL_MS - 1)),
            "one millisecond before the interval: still solid"
        );
        assert!(
            !b.should_blink(&plus_ms(&base, CURSOR_BLINK_INTERVAL_MS)),
            "exactly at the interval: the comparison is strictly greater-than"
        );
        assert!(
            b.should_blink(&plus_ms(&base, CURSOR_BLINK_INTERVAL_MS + 1)),
            "one millisecond past the interval: blinking resumes"
        );
        // Far past the interval (one day) — no overflow, still blinking.
        assert!(b.should_blink(&plus_ms(&base, 86_400_000)));
    }
    #[test]
    fn autotest_blink_should_blink_reversed_clock_saturates_to_false() {
        // `now` is *earlier* than the recorded input (clock skew / reordered
        // events). `Instant::duration_since` saturates to zero rather than
        // panicking, so the caret stays solid instead of the call blowing up.
        let base = Instant::now();
        let mut b = BlinkState::new();
        b.reset_blink_on_input(plus_ms(&base, 10_000));
        assert!(!b.should_blink(&base));
        assert!(b.is_visible);
    }
    #[test]
    fn autotest_blink_should_blink_mismatched_instant_kinds_are_deterministic() {
        // A Tick instant compared against a System instant has no meaningful
        // span: the two counters have no common origin, so `duration_since`
        // saturates to `Duration::Tick(0)` and nothing is ever "elapsed".
        // (This is about mismatched INSTANTS, which really are incomparable —
        // unlike mismatched DURATIONS, which are just two units of the same
        // thing and now convert.)
        let mut b = BlinkState::new();
        b.reset_blink_on_input(Instant::now());
        let tick_now = Instant::Tick(SystemTick::new(u64::MAX));
        assert_eq!(b.should_blink(&tick_now), b.should_blink(&tick_now));
        assert!(!b.should_blink(&tick_now));
    }
    /// A tick-only clock (no_std, or any clockless build) MUST resume blinking.
    ///
    /// Both endpoints are Tick, so the elapsed span is a `Duration::Tick`, which
    /// is compared against the wall-clock-typed blink interval on a canonical
    /// scale. Before that comparison was unit-aware, the answer was `false`
    /// forever and the caret on a clockless build simply never blinked again.
    #[test]
    fn autotest_blink_a_tick_only_clock_resumes_blinking_at_the_exact_frame() {
        let mut t = BlinkState::new();
        t.reset_blink_on_input(Instant::Tick(SystemTick::new(0)));
        // 530ms is 31.8 frames at 60Hz, so frame 31 is early and frame 32 blinks.
        assert!(!t.should_blink(&Instant::Tick(SystemTick::new(31))));
        assert!(t.should_blink(&Instant::Tick(SystemTick::new(32))));
        assert!(t.should_blink(&Instant::Tick(SystemTick::new(u64::MAX))));
    }
    /// The whole point of the `t` unit: a blink interval expressed in FRAMES
    /// flips on exactly the Nth frame — frame N-1 is solid, frame N blinks.
    /// There is no rounding, no clock, and nothing for a slow machine to shift.
    #[test]
    fn autotest_blink_a_tick_interval_flips_on_exactly_the_nth_frame() {
        let mut b = BlinkState::new();
        b.set_blink_interval(Duration::from_ticks(5));
        b.reset_blink_on_input(Instant::Tick(SystemTick::new(100)));
        for frame in 100..=105 {
            assert!(
                !b.should_blink(&Instant::Tick(SystemTick::new(frame))),
                "frame {frame} is within 5 frames of the input and must stay solid"
            );
        }
        assert!(
            b.should_blink(&Instant::Tick(SystemTick::new(106))),
            "frame 106 is strictly more than 5 frames past the input"
        );
    }
    /// The same tick interval, driven off a WALL-CLOCK instant: 5 frames is
    /// 83.33ms, so 83ms is solid and 84ms blinks. A `5t` stylesheet value
    /// therefore behaves identically on a desktop shell and on a clockless one.
    #[test]
    fn autotest_blink_a_tick_interval_converts_on_a_wall_clock_instant() {
        let base = Instant::now();
        let mut b = BlinkState::new();
        b.set_blink_interval(Duration::from_ticks(5));
        b.reset_blink_on_input(base.clone());
        assert!(!b.should_blink(&plus_ms(&base, 83)));
        assert!(b.should_blink(&plus_ms(&base, 84)));
    }
    /// The refocus predicate: a running blink timer holds the interval it was
    /// BUILT with, so the only safe trigger for rebuilding it is "the value
    /// actually changed". Same value ⇒ false (never restart the blink phase for
    /// nothing); different value — including a different UNIT — ⇒ true.
    #[test]
    fn autotest_blink_adopt_interval_reports_only_real_changes() {
        let mut b = BlinkState::new();
        assert!(
            !b.adopt_blink_interval(CURSOR_BLINK_INTERVAL),
            "the default adopted again is not a change"
        );
        assert!(b.adopt_blink_interval(Duration::from_millis(250)));
        assert_eq!(b.blink_interval, Duration::from_millis(250));
        assert!(
            !b.adopt_blink_interval(Duration::from_millis(250)),
            "idempotent: refocusing a node with the SAME duration must not restart the timer"
        );
        // 5 frames is 83.33ms, and 83ms is not 5 frames: the unit is part of
        // the value, so switching between them is a real change.
        assert!(b.adopt_blink_interval(Duration::from_ticks(5)));
        assert!(b.adopt_blink_interval(Duration::from_millis(83)));
        assert!(b.adopt_blink_interval(Duration::from_ticks(5)));
        assert_eq!(b.blink_interval, Duration::from_ticks(5));
        // `clear()` puts the default back, so the next focus on a node with an
        // explicit duration sees a change and rebuilds.
        b.clear();
        assert!(b.adopt_blink_interval(Duration::from_ticks(5)));
    }
    #[test]
    fn autotest_blink_clear_resets_every_field_and_is_idempotent() {
        let mut b = BlinkState::new();
        b.reset_blink_on_input(Instant::now());
        b.set_blink_timer_active(true);
        b.set_blink_interval(Duration::from_ticks(5));
        b.clear();
        assert!(!b.is_visible);
        assert!(b.last_input_time.is_none());
        assert!(!b.is_blink_timer_active());
        assert_eq!(
            b.blink_interval, CURSOR_BLINK_INTERVAL,
            "the previous node's caret-animation-duration must not leak to the next"
        );
        // Clearing an already-cleared state must not panic or resurrect anything.
        b.clear();
        assert!(!b.is_visible);
        assert!(b.last_input_time.is_none());
        assert!(!b.is_blink_timer_active());
        // With no last input, blinking is unblocked again.
        assert!(b.should_blink(&Instant::now()));
    }
    // ------------------------------------------------------------------
    // TextEditManager — construction / predicates / getters
    // ------------------------------------------------------------------
    #[test]
    fn autotest_manager_new_invariants() {
        let m = TextEditManager::new();
        assert!(m.multi_cursor.is_none());
        assert!(!m.has_active_editing());
        assert!(m.get_editing_dom_id().is_none());
        assert!(m.get_editing_node_id().is_none());
        assert!(m.get_primary_cursor().is_none());
        assert!(!m.should_draw_cursor());
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, -1, "-1 is the 'unset' IME sentinel");
        assert_eq!(m.preedit_cursor_end, -1);
        assert!(!m.display_list_dirty, "a fresh manager owes no repaint");
        assert!(m.build_cursor_locations().is_empty());
        assert!(m.build_text_selections_map().is_empty());
        assert_eq!(m, TextEditManager::default());
    }
    #[test]
    fn autotest_manager_mark_dirty_is_sticky() {
        let mut m = TextEditManager::new();
        m.mark_dirty();
        assert!(m.display_list_dirty);
        m.mark_dirty();
        assert!(m.display_list_dirty, "marking twice must not toggle it off");
    }
    #[test]
    fn autotest_manager_partial_eq_ignores_transient_state() {
        // Documented contract: only `multi_cursor` participates in equality.
        let mut a = TextEditManager::new();
        let mut b = TextEditManager::new();
        assert_eq!(a, b);
        a.set_preedit("か".to_string(), 0, 3);
        a.blink.set_visibility(true);
        a.mark_dirty();
        assert_eq!(a, b, "preedit / blink / dirty are transient visual state");
        b.initialize_editing(cursor(0, 0), DOM0, NodeId::ZERO, 1);
        assert_ne!(a, b, "a live editing session is not equal to no session");
    }
    // ------------------------------------------------------------------
    // TextEditManager — initialize_editing (numeric edges)
    // ------------------------------------------------------------------
    #[test]
    fn autotest_initialize_editing_at_zero() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 0), DOM0, NodeId::ZERO, 0);
        assert!(m.has_active_editing());
        assert_eq!(m.get_editing_dom_id(), Some(DOM0));
        assert_eq!(
            m.get_editing_node_id(),
            Some(NodeId::ZERO),
            "node index 0 must not be confused with the 'no node' encoding"
        );
        assert_eq!(m.get_primary_cursor(), Some(cursor(0, 0)));
        assert_eq!(
            m.multi_cursor.as_ref().map(|mc| mc.contenteditable_key),
            Some(0)
        );
        assert!(m.blink.is_visible);
        // The caret is SOLID for the first half-period after focus, so the blink
        // phase must be ANCHORED here. `None` would mean "no input ever", for
        // which `should_blink` is true immediately and the timer's first tick
        // hides the caret the user just placed. See `initialize_editing`.
        let anchored = m
            .blink
            .last_input_time
            .as_ref()
            .expect("initialize_editing must anchor the blink phase, not clear it");
        assert!(
            !m.blink.should_blink(anchored),
            "at the instant of focus, zero time has elapsed — blinking must not be allowed yet"
        );
        assert!(m.should_draw_cursor());
        assert!(m.display_list_dirty);
        {
            let locs = m.build_cursor_locations();
            assert_eq!(locs.len(), 1);
            assert_eq!(locs[0].dom, DOM0);
            assert_eq!(locs[0].node, NodeId::ZERO);
            assert_eq!(locs[0].cursor, cursor(0, 0));
            assert!(locs[0].owner.is_local());
        }
    }
    #[test]
    fn autotest_initialize_editing_at_integer_extremes() {
        // Max representable node index, max DomId, max contenteditable key, and a
        // cursor at the top of the u32 grapheme-coordinate space.
        let node = NodeId::new(MAX_ENCODABLE_NODE);
        let extreme_cursor = TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: u32::MAX,
                start_byte_in_run: u32::MAX,
            },
            affinity: CursorAffinity::Trailing,
        };
        let mut m = TextEditManager::new();
        m.initialize_editing(extreme_cursor, DOM_MAX, node, u64::MAX);
        assert_eq!(m.get_editing_dom_id(), Some(DOM_MAX));
        assert_eq!(
            m.get_editing_node_id(),
            Some(node),
            "usize::MAX - 1 is the largest 1-based-encodable node index"
        );
        assert_eq!(m.get_primary_cursor(), Some(extreme_cursor));
        assert_eq!(
            m.multi_cursor.as_ref().map(|mc| mc.contenteditable_key),
            Some(u64::MAX),
            "the contenteditable key is opaque — u64::MAX must survive verbatim"
        );
        assert_eq!(locs_as_triples(&m), vec![(DOM_MAX, node, extreme_cursor)]);
    }
    #[test]
    fn autotest_initialize_editing_overwrites_previous_session() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(1, 1), DOM0, NodeId::new(7), 111);
        m.initialize_editing(cursor(2, 2), DOM1, NodeId::new(9), 222);
        assert_eq!(m.get_editing_dom_id(), Some(DOM1));
        assert_eq!(m.get_editing_node_id(), Some(NodeId::new(9)));
        assert_eq!(m.get_primary_cursor(), Some(cursor(2, 2)));
        assert_eq!(
            m.build_cursor_locations().len(),
            1,
            "re-initializing replaces the cursor set, it does not accumulate"
        );
        assert_eq!(
            m.multi_cursor.as_ref().map(|mc| mc.contenteditable_key),
            Some(222)
        );
    }
    #[test]
    fn autotest_initialize_editing_clears_stale_preedit() {
        let mut m = TextEditManager::new();
        m.set_preedit("漢字".to_string(), 3, 6);
        m.initialize_editing(cursor(0, 0), DOM0, NodeId::new(4), 42);
        assert!(
            m.preedit_text.is_none(),
            "focusing a new element must drop the old composition"
        );
        assert_eq!(m.preedit_cursor_begin, -1);
        assert_eq!(m.preedit_cursor_end, -1);
    }
    // ------------------------------------------------------------------
    // TextEditManager — clear_editing
    // ------------------------------------------------------------------
    #[test]
    fn autotest_clear_editing_on_fresh_manager_is_safe() {
        let mut m = TextEditManager::new();
        m.clear_editing();
        m.clear_editing();
        assert!(!m.has_active_editing());
        assert!(!m.should_draw_cursor());
        assert!(m.build_cursor_locations().is_empty());
        // A fresh manager has no cursor, no blink and no preedit, so clearing it
        // erases NOTHING and owes no repaint. This assertion used to read
        // `assert!(m.display_list_dirty, "clear_editing marks dirty
        // unconditionally")` — it documented the behaviour as found rather than
        // as intended, and what it documented was a bug: `clear_editing` runs on
        // every focus change, `display_list_dirty` is a LATCH, and so one Tab
        // between two never-editable nodes left the window owing a repaint on
        // every frame for the rest of its life.
        assert!(
            !m.display_list_dirty,
            "clearing an already-clear manager must not request a repaint"
        );
    }
    #[test]
    fn autotest_clear_editing_tears_down_everything() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 5), DOM0, NodeId::new(3), 77);
        m.set_preedit("ab".to_string(), 0, 2);
        m.blink.set_blink_timer_active(true);
        m.blink.reset_blink_on_input(Instant::now());
        m.clear_editing();
        assert!(m.multi_cursor.is_none());
        assert!(!m.has_active_editing());
        assert!(m.get_editing_dom_id().is_none());
        assert!(m.get_editing_node_id().is_none());
        assert!(m.get_primary_cursor().is_none());
        assert!(!m.should_draw_cursor());
        assert!(!m.blink.is_visible);
        assert!(!m.blink.is_blink_timer_active());
        assert!(m.blink.last_input_time.is_none());
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, -1);
        assert_eq!(m.preedit_cursor_end, -1);
        assert!(m.display_list_dirty);
        assert!(m.build_cursor_locations().is_empty());
        assert!(m.build_text_selections_map().is_empty());
    }
    // ------------------------------------------------------------------
    // TextEditManager — IME preedit (numeric edges + unicode)
    // ------------------------------------------------------------------
    #[test]
    fn autotest_set_preedit_zero_offsets_are_not_the_unset_sentinel() {
        let mut m = TextEditManager::new();
        m.set_preedit("a".to_string(), 0, 0);
        assert_eq!(m.preedit_text.as_deref(), Some("a"));
        assert_eq!(
            m.preedit_cursor_begin, 0,
            "0 is a valid offset and must not be coerced to the -1 sentinel"
        );
        assert_eq!(m.preedit_cursor_end, 0);
        assert!(m.display_list_dirty);
    }
    #[test]
    fn autotest_set_preedit_stores_i32_extremes_verbatim() {
        let mut m = TextEditManager::new();
        m.set_preedit("x".to_string(), i32::MIN, i32::MAX);
        assert_eq!(m.preedit_cursor_begin, i32::MIN);
        assert_eq!(m.preedit_cursor_end, i32::MAX);
        // Negative (non-sentinel) values and an inverted begin > end range are
        // stored as-is: the manager performs no arithmetic on them, so there is
        // nothing to overflow. Consumers must clamp.
        m.set_preedit("x".to_string(), -42, -7);
        assert_eq!(m.preedit_cursor_begin, -42);
        assert_eq!(m.preedit_cursor_end, -7);
        m.set_preedit("x".to_string(), 10, 2);
        assert_eq!(m.preedit_cursor_begin, 10);
        assert_eq!(m.preedit_cursor_end, 2);
    }
    #[test]
    fn autotest_set_preedit_offsets_beyond_text_length_are_not_validated() {
        // A hostile / buggy IME can report offsets far outside the string. The
        // setter must not panic and must not silently rewrite them — it stores
        // them verbatim, which is the contract callers have to defend against.
        let mut m = TextEditManager::new();
        m.set_preedit("ab".to_string(), i32::MAX, i32::MAX);
        assert_eq!(m.preedit_text.as_deref(), Some("ab"));
        assert_eq!(m.preedit_cursor_begin, i32::MAX);
        assert_eq!(m.preedit_cursor_end, i32::MAX);
    }
    #[test]
    fn autotest_set_preedit_empty_text_becomes_none_but_keeps_offsets() {
        // Documented behaviour of `set_preedit`: an empty composition string maps
        // to `None`, yet the offsets are still overwritten with whatever the IME
        // passed. The result is a `None` text with non-sentinel offsets — callers
        // must key off `preedit_text`, not off the offsets.
        let mut m = TextEditManager::new();
        m.set_preedit(String::new(), 5, 9);
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, 5);
        assert_eq!(m.preedit_cursor_end, 9);
        assert!(m.display_list_dirty);
    }
    #[test]
    fn autotest_set_preedit_preserves_unicode_verbatim() {
        let mut m = TextEditManager::new();
        for text in [
            "こんにちは",        // CJK — the common IME case
            "👨‍👩‍👧‍👦",                // ZWJ emoji family (one grapheme, many bytes)
            "e\u{0301}\u{0327}", // combining acute + cedilla
            "مرحبا",             // RTL
            "a\u{0000}b",        // interior NUL
            "\u{FEFF}bom",       // byte-order mark
            "🇩🇪🇯🇵",              // regional-indicator flags
        ] {
            m.set_preedit(text.to_string(), 0, 1);
            assert_eq!(
                m.preedit_text.as_deref(),
                Some(text),
                "preedit text must round-trip byte-for-byte"
            );
        }
    }
    #[test]
    fn autotest_set_preedit_huge_text_does_not_panic() {
        let huge = "あ".repeat(100_000); // 300_000 bytes
        let mut m = TextEditManager::new();
        m.set_preedit(huge.clone(), 0, 299_999);
        assert_eq!(m.preedit_text.as_deref(), Some(huge.as_str()));
        assert_eq!(m.preedit_text.as_ref().map(String::len), Some(300_000));
    }
    #[test]
    fn autotest_clear_preedit_is_idempotent_and_marks_dirty() {
        let mut m = TextEditManager::new();
        m.set_preedit("ば".to_string(), 0, 3);
        m.clear_preedit();
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, -1);
        assert_eq!(m.preedit_cursor_end, -1);
        m.display_list_dirty = false;
        m.clear_preedit();
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, -1);
        assert_eq!(m.preedit_cursor_end, -1);
        // The FIRST clear (above) really did clear a preedit and correctly marked
        // dirty. This second one has nothing left to clear, so it must not.
        // Previously asserted the opposite, in as many words: "clear_preedit
        // marks dirty even when nothing changed".
        assert!(
            !m.display_list_dirty,
            "a no-op clear_preedit must not request a repaint"
        );
    }
    #[test]
    fn autotest_preedit_does_not_create_an_editing_session() {
        let mut m = TextEditManager::new();
        m.set_preedit("compose".to_string(), 0, 7);
        assert!(
            !m.has_active_editing(),
            "IME text alone must not fake an editing session"
        );
        assert!(!m.should_draw_cursor());
        assert!(m.get_primary_cursor().is_none());
    }
    // ------------------------------------------------------------------
    // TextEditManager — build_cursor_locations
    // ------------------------------------------------------------------
    #[test]
    fn autotest_build_cursor_locations_empty_without_session() {
        assert!(TextEditManager::new().build_cursor_locations().is_empty());
    }
    #[test]
    fn autotest_build_cursor_locations_uses_range_end_and_keeps_order() {
        let node = NodeId::new(12);
        let a = cursor(0, 0);
        let b = cursor(0, 4);
        let c = cursor(1, 8);
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM1, Some(node)),
            vec![
                Selection::Cursor(a),
                Selection::Range(range(b, c)),
                Selection::Cursor(c),
            ],
            5,
        ));
        assert_eq!(
            locs_as_triples(&m),
            vec![(DOM1, node, a), (DOM1, node, c), (DOM1, node, c)],
            "a Range contributes its `end` as the caret position"
        );
    }
    #[test]
    fn autotest_build_cursor_locations_with_detached_node_is_empty() {
        // A `MultiCursorState` whose node encodes "no node" must yield nothing
        // rather than panicking or fabricating NodeId(0).
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, None),
            vec![Selection::Cursor(cursor(0, 0))],
            1,
        ));
        assert!(m.has_active_editing());
        assert!(m.get_editing_node_id().is_none());
        assert!(m.build_cursor_locations().is_empty());
        assert!(m.build_text_selections_map().is_empty());
    }
    #[test]
    fn autotest_build_cursor_locations_with_no_selections_is_empty() {
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(NodeId::ZERO)),
            Vec::new(),
            0,
        ));
        assert!(m.build_cursor_locations().is_empty());
        assert!(m.get_primary_cursor().is_none());
        assert!(m.build_text_selections_map().is_empty());
    }
    #[test]
    fn autotest_build_cursor_locations_scales_to_many_cursors() {
        let node = NodeId::new(2);
        let selections: Vec<Selection> = (0..1000u32)
            .map(|i| Selection::Cursor(cursor(0, i)))
            .collect();
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(dom_node(DOM0, Some(node)), selections, 9));
        let locations = m.build_cursor_locations();
        assert_eq!(locations.len(), 1000);
        assert_eq!(
            (locations[0].dom, locations[0].node, locations[0].cursor),
            (DOM0, node, cursor(0, 0))
        );
        assert_eq!(
            (
                locations[999].dom,
                locations[999].node,
                locations[999].cursor
            ),
            (DOM0, node, cursor(0, 999))
        );
    }
    // ------------------------------------------------------------------
    // TextEditManager — build_text_selections_map
    // ------------------------------------------------------------------
    #[test]
    fn autotest_build_text_selections_map_empty_without_session() {
        assert!(TextEditManager::new()
            .build_text_selections_map()
            .is_empty());
    }
    #[test]
    fn autotest_build_text_selections_map_ignores_pure_cursors() {
        // Collapsed carets are not selections — nothing to paint.
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 3), DOM0, NodeId::new(1), 8);
        assert!(m.build_text_selections_map().is_empty());
    }
    // ---------------------------------------------------------------
    // U1-a — the selection HIGHLIGHT is per owner, not per node
    // ---------------------------------------------------------------
    fn owner(n: u64) -> azul_core::selection::SelectionOwner {
        azul_core::selection::SelectionOwner { high: 0, low: n }
    }
    #[test]
    fn autotest_session_ranges_exclude_a_remote_participants_range() {
        // THE DEFECT U1 INTRODUCED. `session_selection_ranges` walked every
        // selection in the list; once an app could inject a peer's range, that
        // range came back as if the local user had made it — painted in the
        // node's one `::selection` colour and, worse, treated as the local
        // selection by everything downstream of it (copy included).
        let node = NodeId::new(6);
        let mine = range(cursor(0, 0), cursor(0, 2));
        let theirs = range(cursor(0, 5), cursor(0, 9));
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(node)),
            vec![Selection::Range(mine)],
            3,
        ));
        assert!(m
            .multi_cursor
            .as_mut()
            .unwrap()
            .set_owner_selections(owner(7), &[Selection::Range(theirs)]));
        let session = m.session_selection_ranges().expect("the local range");
        assert_eq!(session.ranges, vec![mine], "local ranges only");
        assert_eq!(session.primary, mine);
        let remote = m.remote_selection_ranges().expect("the peer's range");
        assert_eq!(remote.ranges, vec![(owner(7), theirs)]);
        assert_eq!(remote.node_id, node);
        assert_eq!(remote.dom_id, DOM0);
        assert_eq!(
            remote.local_cursor,
            Some(mine.end),
            "the local caret rides along for the collapsed case"
        );
    }
    #[test]
    fn autotest_build_text_selections_map_separates_remote_ranges() {
        let node = NodeId::new(2);
        let mine = range(cursor(0, 0), cursor(0, 2));
        let theirs = range(cursor(0, 5), cursor(0, 9));
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(node)),
            vec![Selection::Range(mine)],
            3,
        ));
        m.multi_cursor
            .as_mut()
            .unwrap()
            .set_owner_selections(owner(1), &[Selection::Range(theirs)]);
        let sel = m.build_text_selections_map().remove(&DOM0).expect("a map");
        assert_eq!(
            sel.ranges_for_node(&node),
            &[mine],
            "affected_nodes is the LOCAL selection and takes ::selection"
        );
        assert_eq!(
            sel.remote_ranges.get(&node).map(|v| v.as_slice()),
            Some(&[(owner(1), theirs)][..]),
        );
        // The endpoints still describe the local primary, not the peer's.
        assert_eq!(sel.anchor.cursor, mine.start);
        assert_eq!(sel.focus.cursor, mine.end);
    }
    #[test]
    fn autotest_remote_range_survives_a_collapsed_local_caret() {
        // THE ORDINARY COLLABORATIVE CASE: I am typing (a bare caret, which is
        // not a selection) while somebody else has text selected. Hanging the
        // remote ranges off `session_selection_ranges` would have dropped them
        // here, because that accessor reports `None` for a caret-only session
        // by design — everybody else's highlight would blink out the instant
        // the local user collapsed their own.
        let node = NodeId::new(9);
        let theirs = range(cursor(0, 3), cursor(0, 7));
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM1, Some(node)),
            vec![Selection::Cursor(cursor(0, 1))],
            4,
        ));
        m.multi_cursor
            .as_mut()
            .unwrap()
            .set_owner_selections(owner(3), &[Selection::Range(theirs)]);
        assert!(
            m.session_selection_ranges().is_none(),
            "a bare local caret is not a selection"
        );
        let map = m.build_text_selections_map();
        let sel = map.get(&DOM1).expect("the peer's range still gets a map");
        assert!(
            sel.is_collapsed(),
            "collapsed, so the LOCAL highlight path paints nothing"
        );
        assert_eq!(sel.anchor.cursor, cursor(0, 1), "at the local caret");
        assert_eq!(
            sel.remote_ranges.get(&node).map(|v| v.as_slice()),
            Some(&[(owner(3), theirs)][..]),
        );
        // `new_collapsed` still lists the caret as a degenerate range, so the
        // suppression of the local highlight is `is_collapsed` above and NOT
        // an empty map — worth pinning, because painting that range would put
        // a zero-width `::selection` rect under the caret.
        assert_eq!(
            sel.ranges_for_node(&node),
            &[range(cursor(0, 1), cursor(0, 1))]
        );
    }
    #[test]
    fn autotest_no_remote_map_for_a_single_user_session() {
        // The single-user path must not start allocating a second map.
        let node = NodeId::new(1);
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(node)),
            vec![Selection::Range(range(cursor(0, 0), cursor(0, 3)))],
            3,
        ));
        assert!(m.remote_selection_ranges().is_none());
        let sel = m.build_text_selections_map().remove(&DOM0).expect("a map");
        assert!(sel.remote_ranges.is_empty());
    }
    #[test]
    fn autotest_remote_selection_tint_keeps_text_readable() {
        use crate::solver3::display_list::{remote_selection_tint, REMOTE_SELECTION_ALPHA};
        let opaque = ColorU {
            r: 10,
            g: 200,
            b: 30,
            a: 255,
        };
        let tinted = remote_selection_tint(opaque);
        assert_eq!(
            (tinted.r, tinted.g, tinted.b),
            (10, 200, 30),
            "the hue identifies the participant and must not shift"
        );
        assert_eq!(tinted.a, REMOTE_SELECTION_ALPHA);
        assert!(tinted.a < opaque.a, "an opaque fill would hide the text");
        // An app that deliberately picked a faint colour asked for faint.
        let faint = ColorU { a: 0x10, ..opaque };
        assert_eq!(remote_selection_tint(faint).a, 0x10);
    }
    #[test]
    fn autotest_build_text_selections_map_single_range() {
        let node = NodeId::new(6);
        let start = cursor(0, 2);
        let end = cursor(0, 9);
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM1, Some(node)),
            vec![Selection::Range(range(start, end))],
            3,
        ));
        let map = m.build_text_selections_map();
        assert_eq!(map.len(), 1);
        let sel = map.get(&DOM1).expect("keyed by the editing DomId");
        assert_eq!(sel.dom_id, DOM1);
        assert_eq!(sel.anchor.ifc_root_node_id, node);
        assert_eq!(sel.anchor.cursor, start);
        assert_eq!(sel.focus.ifc_root_node_id, node);
        assert_eq!(sel.focus.cursor, end);
        assert!(sel.is_forward);
        assert_eq!(sel.affected_nodes.len(), 1);
        assert_eq!(sel.ranges_for_node(&node), &[range(start, end)]);
        assert_eq!(sel.get_range_for_node(&node), Some(&range(start, end)));
    }
    #[test]
    fn autotest_build_text_selections_map_backward_range_reports_is_forward_false() {
        // A backward drag anchors at 9 and puts the focus at 2, so the emitted
        // selection must say so. `is_forward` used to be hard-coded `true`.
        let node = NodeId::new(6);
        let start = cursor(0, 9);
        let end = cursor(0, 2);
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(node)),
            vec![Selection::Range(range(start, end))],
            3,
        ));
        let map = m.build_text_selections_map();
        let sel = map.get(&DOM0).expect("keyed by the editing DomId");
        assert_eq!(sel.anchor.cursor, start);
        assert_eq!(sel.focus.cursor, end);
        assert!(!sel.is_forward, "anchor is logically AFTER the focus");
        assert!(!range_is_forward(&range(start, end)));
        assert!(
            range_is_forward(&range(end, start)),
            "the mirrored drag is forward"
        );
        assert!(
            range_is_forward(&range(start, start)),
            "a degenerate range counts as forward, like TextSelection::new_collapsed"
        );
    }
    #[test]
    fn autotest_build_text_selections_map_multi_range_endpoints_match_the_painted_range() {
        // The two halves of the emitted `TextSelection` must agree: the
        // `anchor`/`focus` endpoints describe the PRIMARY range, and that range
        // is one of the ranges `affected_nodes` paints. They used to disagree —
        // endpoints from the FIRST range, the map from the LAST (each insert
        // overwrote the same key, so a Ctrl+D session painted ONE occurrence).
        let node = NodeId::new(4);
        let first = range(cursor(0, 0), cursor(0, 1));
        let last = range(cursor(0, 5), cursor(0, 8));
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(node)),
            vec![
                Selection::Range(first),
                Selection::Cursor(cursor(0, 3)),
                Selection::Range(last),
            ],
            2,
        ));
        let map = m.build_text_selections_map();
        assert_eq!(map.len(), 1, "one entry per DomId, not per range");
        let sel = map.get(&DOM0).expect("keyed by the editing DomId");
        assert_eq!(
            sel.anchor.cursor, last.start,
            "endpoints from the PRIMARY range"
        );
        assert_eq!(sel.focus.cursor, last.end);
        assert_eq!(sel.affected_nodes.len(), 1, "one node key, several ranges");
        assert_eq!(
            sel.ranges_for_node(&node),
            &[first, last],
            "BOTH occurrences reach the painter, in document order"
        );
        assert!(
            sel.ranges_for_node(&node).contains(&last),
            "the range the endpoints describe is one of the painted ones"
        );
        // …and no range is lost on the way: the session reports both.
        let session = m.session_selection_ranges().expect("a session with ranges");
        assert_eq!(session.dom_id, DOM0);
        assert_eq!(session.node_id, node);
        assert_eq!(session.ranges, vec![first, last], "carets are not ranges");
        assert_eq!(session.primary, last);
    }
    #[test]
    fn autotest_session_selection_ranges_falls_back_to_the_first_range() {
        // The primary selection is a bare CARET here (the fixture makes the
        // last element primary), so the endpoints stand in from the first
        // range — never from a caret, which would emit a collapsed selection
        // and paint nothing.
        let node = NodeId::new(2);
        let only = range(cursor(0, 4), cursor(0, 7));
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM1, Some(node)),
            vec![Selection::Range(only), Selection::Cursor(cursor(0, 12))],
            9,
        ));
        let session = m
            .session_selection_ranges()
            .expect("one range is a session");
        assert_eq!(session.ranges, vec![only]);
        assert_eq!(session.primary, only);
        let map = m.build_text_selections_map();
        let sel = map.get(&DOM1).expect("keyed by the editing DomId");
        assert_eq!(sel.anchor.cursor, only.start);
        assert_eq!(sel.focus.cursor, only.end);
    }
    #[test]
    fn autotest_session_selection_ranges_is_none_without_ranges() {
        assert!(TextEditManager::new().session_selection_ranges().is_none());
        // Carets only — nothing to highlight.
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 3), DOM0, NodeId::new(1), 8);
        assert!(m.session_selection_ranges().is_none());
        // A range on a DETACHED node has no IFC root to express it against.
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, None),
            vec![Selection::Range(range(cursor(0, 0), cursor(0, 1)))],
            1,
        ));
        assert!(m.session_selection_ranges().is_none());
        assert!(m.build_text_selections_map().is_empty());
    }
    #[test]
    fn autotest_build_text_selections_map_degenerate_and_extreme_ranges() {
        let node = NodeId::new(MAX_ENCODABLE_NODE);
        // Zero-width range (start == end) at the top of the coordinate space.
        let point = cursor(u32::MAX, u32::MAX);
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM_MAX, Some(node)),
            vec![Selection::Range(range(point, point))],
            u64::MAX,
        ));
        let map = m.build_text_selections_map();
        let sel = map.get(&DOM_MAX).expect("keyed by the editing DomId");
        assert_eq!(sel.anchor.cursor, point);
        assert_eq!(sel.focus.cursor, point);
        assert_eq!(sel.ranges_for_node(&node), &[range(point, point)]);
    }
    // ------------------------------------------------------------------
    // TextEditManager — NodeIdRemap (DOM rebuild)
    // ------------------------------------------------------------------
    #[test]
    fn autotest_remap_without_session_is_a_noop() {
        let mut m = TextEditManager::new();
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::ZERO, NodeId::new(1))]),
        );
        assert!(!m.has_active_editing());
        assert!(
            !m.display_list_dirty,
            "nothing changed, so nothing to repaint"
        );
    }
    #[test]
    fn autotest_remap_rewrites_surviving_node() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 2), DOM0, NodeId::new(3), 55);
        m.set_preedit("ok".to_string(), 0, 2);
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(8))]),
        );
        assert!(m.has_active_editing());
        assert_eq!(m.get_editing_node_id(), Some(NodeId::new(8)));
        assert_eq!(m.get_editing_dom_id(), Some(DOM0));
        assert_eq!(m.get_primary_cursor(), Some(cursor(0, 2)));
        assert_eq!(
            m.preedit_text.as_deref(),
            Some("ok"),
            "a surviving node keeps its in-flight composition"
        );
        assert_eq!(
            m.multi_cursor.as_ref().map(|mc| mc.contenteditable_key),
            Some(55),
            "the stable key must survive the rebuild"
        );
    }
    #[test]
    fn autotest_remap_drops_session_when_node_unmounted() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 1), DOM0, NodeId::new(3), 55);
        m.set_preedit("gone".to_string(), 1, 4);
        m.display_list_dirty = false;
        // The rebuilt DOM matched some *other* node — 3 is unmounted.
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(4), NodeId::new(4))]),
        );
        assert!(!m.has_active_editing());
        assert!(m.multi_cursor.is_none());
        assert!(m.preedit_text.is_none());
        assert_eq!(m.preedit_cursor_begin, -1);
        assert_eq!(m.preedit_cursor_end, -1);
        assert!(m.display_list_dirty);
        assert!(m.build_cursor_locations().is_empty());
    }
    #[test]
    fn autotest_remap_with_empty_map_drops_session() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 0), DOM0, NodeId::ZERO, 1);
        m.remap_node_ids(DOM0, &NodeIdMap::default());
        assert!(
            !m.has_active_editing(),
            "an empty map means every node was unmounted"
        );
    }
    #[test]
    fn autotest_remap_leaves_other_doms_alone() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 0), DOM1, NodeId::new(3), 1);
        // A reconciliation of DOM0 says nothing about a cursor living in DOM1.
        m.remap_node_ids(DOM0, &NodeIdMap::default());
        assert!(m.has_active_editing());
        assert_eq!(m.get_editing_dom_id(), Some(DOM1));
        assert_eq!(m.get_editing_node_id(), Some(NodeId::new(3)));
    }
    #[test]
    fn autotest_remap_of_detached_node_drops_session() {
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, None),
            vec![Selection::Cursor(cursor(0, 0))],
            1,
        ));
        m.remap_node_ids(DOM0, &NodeIdMap::from_pairs([(NodeId::ZERO, NodeId::ZERO)]));
        assert!(
            !m.has_active_editing(),
            "a cursor with no IFC root is not an editing session"
        );
        assert!(m.display_list_dirty);
    }
    // ------------------------------------------------------------------
    // TextTweenState — the tween must follow (and die with) its node
    // ------------------------------------------------------------------
    fn rect(x: f32, y: f32) -> LogicalRect {
        LogicalRect::new(
            azul_core::geom::LogicalPosition { x, y },
            azul_core::geom::LogicalSize {
                width: 2.0,
                height: 16.0,
            },
        )
    }
    fn instant() -> Instant {
        Instant::Tick(SystemTick::new(0))
    }
    /// A manager editing `node` in `DOM0` with a caret tween and a selection
    /// tween both mid-flight, and both "last rendered" geometries recorded.
    fn manager_with_live_tween(node: NodeId) -> TextEditManager {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 0), DOM0, node, 7);
        m.tween.dom_id = Some(DOM0);
        m.tween.caret = Some(CaretTweenTrack {
            from: rect(10.0, 0.0),
            to: rect(40.0, 0.0),
            start: instant(),
            reveal: false,
        });
        m.tween.last_caret = Some(rect(25.0, 0.0));
        m.tween.selection = Some(SelectionTweenTrack {
            from: vec![rect(0.0, 0.0)],
            to: vec![rect(60.0, 0.0)],
            start: instant(),
        });
        m.tween.last_selection = vec![rect(30.0, 0.0)];
        m.tween.publish_active();
        m
    }
    #[test]
    fn autotest_remap_keeps_the_tween_anchored_to_a_moved_node() {
        let mut m = manager_with_live_tween(NodeId::new(3));
        assert_eq!(m.tween.node, Some(dom_node(DOM0, Some(NodeId::new(3)))));
        // A sibling was inserted ahead of it: same node, new index.
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(4))]),
        );
        assert_eq!(
            m.tween.node,
            Some(dom_node(DOM0, Some(NodeId::new(4)))),
            "the tween must follow the node it belongs to"
        );
        assert_eq!(m.get_editing_node_id(), Some(NodeId::new(4)));
        // The geometry is where the caret was actually RENDERED last frame, so
        // a move keeps it: that is what makes the glide continuous.
        assert_eq!(m.tween.last_caret, Some(rect(25.0, 0.0)));
        assert_eq!(m.tween.last_selection, vec![rect(30.0, 0.0)]);
        assert!(m.tween.caret.is_some());
        assert!(m.tween.selection.is_some());
        assert!(m.tween.is_active());
    }
    #[test]
    fn autotest_remap_clears_the_tween_when_the_edited_node_is_unmounted() {
        let mut m = manager_with_live_tween(NodeId::new(3));
        assert!(m.tween.tick_flag.load(AtomicOrdering::Acquire));
        // Node 3 is absent from the map => unmounted.
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(9), NodeId::new(9))]),
        );
        assert!(m.tween.node.is_none());
        assert!(
            m.tween.caret.is_none() && m.tween.last_caret.is_none(),
            "caret geometry belonging to a deleted node must not survive"
        );
        assert!(m.tween.selection.is_none());
        assert!(m.tween.last_selection.is_empty());
        assert!(!m.tween.is_active());
        assert!(
            !m.tween.tick_flag.load(AtomicOrdering::Acquire),
            "the timer flag must be republished, or the tween timer keeps ticking"
        );
    }
    #[test]
    fn autotest_remap_clears_the_tween_of_a_session_installed_without_the_anchor() {
        // `multi_cursor` is a public field and several call sites assign it
        // directly, which cannot set `tween.node`. The remap re-derives the
        // anchor from the session so that state is not orphaned.
        let mut m = TextEditManager::new();
        m.multi_cursor = Some(multi_cursor_with(
            dom_node(DOM0, Some(NodeId::new(2))),
            vec![Selection::Cursor(cursor(0, 0))],
            1,
        ));
        m.tween.last_caret = Some(rect(11.0, 0.0));
        assert!(m.tween.node.is_none());
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(5), NodeId::new(5))]),
        );
        assert!(m.tween.last_caret.is_none());
        assert!(m.tween.node.is_none());
    }
    #[test]
    fn autotest_remap_leaves_the_tween_of_another_dom_alone() {
        let mut m = TextEditManager::new();
        m.initialize_editing(cursor(0, 0), DOM1, NodeId::new(3), 7);
        m.tween.last_caret = Some(rect(12.0, 0.0));
        m.remap_node_ids(DOM0, &NodeIdMap::default());
        assert_eq!(m.tween.node, Some(dom_node(DOM1, Some(NodeId::new(3)))));
        assert_eq!(m.tween.last_caret, Some(rect(12.0, 0.0)));
    }
    #[test]
    fn autotest_text_tween_state_clone_copies_every_field() {
        let m = manager_with_live_tween(NodeId::new(3));
        let clone = m.tween.clone();
        assert_eq!(clone.dom_id, m.tween.dom_id);
        assert_eq!(clone.node, m.tween.node);
        assert_eq!(clone.last_caret, m.tween.last_caret);
        assert_eq!(clone.last_selection, m.tween.last_selection);
        let (a, b) = (
            clone
                .caret
                .as_ref()
                .expect("in-flight caret must be cloned"),
            m.tween.caret.as_ref().expect("original"),
        );
        assert_eq!(a.from, b.from);
        assert_eq!(a.to, b.to);
        let (a, b) = (
            clone
                .selection
                .as_ref()
                .expect("in-flight selection must be cloned"),
            m.tween.selection.as_ref().expect("original"),
        );
        assert_eq!(a.from, b.from);
        assert_eq!(a.to, b.to);
        assert!(clone.is_active(), "a clone of a running tween is running");
        assert!(clone.tick_flag.load(AtomicOrdering::Acquire));
    }
    #[test]
    fn autotest_text_tween_state_clone_does_not_share_the_timer_flag() {
        // Two managers sharing one flag would steer each other's tween timer.
        let m = manager_with_live_tween(NodeId::new(3));
        let mut clone = m.tween.clone();
        assert!(!Arc::ptr_eq(&clone.tick_flag, &m.tween.tick_flag));
        clone.reset();
        assert!(!clone.tick_flag.load(AtomicOrdering::Acquire));
        assert!(
            m.tween.tick_flag.load(AtomicOrdering::Acquire),
            "the original's timer must keep running"
        );
    }
    #[test]
    fn autotest_manager_clone_carries_the_tween() {
        let m = manager_with_live_tween(NodeId::new(3));
        let clone = m.clone();
        assert_eq!(clone.tween.node, m.tween.node);
        assert_eq!(clone.tween.last_caret, m.tween.last_caret);
        assert!(clone.tween.is_active());
    }
    // ------------------------------------------------------------------
    // Cross-block selection + queued edit notifications also carry NodeIds
    // ------------------------------------------------------------------
    fn cross_block_selection(anchor: NodeId, focus: NodeId) -> azul_core::selection::TextSelection {
        use azul_core::selection::{SelectionAnchor, SelectionFocus, TextSelection};
        let mut affected = alloc::collections::BTreeMap::new();
        affected.insert(anchor, vec![range(cursor(0, 0), cursor(0, 1))]);
        affected.insert(focus, vec![range(cursor(0, 0), cursor(0, 2))]);
        TextSelection {
            dom_id: DOM0,
            remote_ranges: alloc::collections::BTreeMap::new(),
            anchor: SelectionAnchor {
                ifc_root_node_id: anchor,
                cursor: cursor(0, 0),
                char_bounds: LogicalRect::zero(),
                mouse_position: azul_core::geom::LogicalPosition::zero(),
            },
            focus: SelectionFocus {
                ifc_root_node_id: focus,
                cursor: cursor(0, 2),
                mouse_position: azul_core::geom::LogicalPosition::zero(),
            },
            affected_nodes: affected,
            is_forward: true,
        }
    }
    #[test]
    fn autotest_remap_rewrites_the_cross_block_selection() {
        let mut m = TextEditManager::new();
        m.set_cross_block_selection(cross_block_selection(NodeId::new(2), NodeId::new(5)));
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([
                (NodeId::new(2), NodeId::new(3)),
                (NodeId::new(5), NodeId::new(6)),
            ]),
        );
        let cb = m.get_cross_block_selection().expect("both roots survived");
        assert_eq!(cb.anchor.ifc_root_node_id, NodeId::new(3));
        assert_eq!(cb.focus.ifc_root_node_id, NodeId::new(6));
        assert_eq!(cb.ranges_for_node(&NodeId::new(3)).len(), 1);
        assert_eq!(cb.ranges_for_node(&NodeId::new(6)).len(), 1);
        assert!(
            cb.ranges_for_node(&NodeId::new(2)).is_empty(),
            "the old index must not still paint"
        );
    }
    #[test]
    fn autotest_remap_drops_the_cross_block_selection_when_an_endpoint_is_gone() {
        let mut m = TextEditManager::new();
        m.set_cross_block_selection(cross_block_selection(NodeId::new(2), NodeId::new(5)));
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(2))]),
        );
        assert!(
            m.get_cross_block_selection().is_none(),
            "a band with no focus root has nothing to paint between"
        );
    }
    #[test]
    fn autotest_remap_leaves_a_cross_block_selection_of_another_dom_alone() {
        let mut m = TextEditManager::new();
        let mut sel = cross_block_selection(NodeId::new(2), NodeId::new(5));
        sel.dom_id = DOM1;
        m.set_cross_block_selection(sel);
        m.remap_node_ids(DOM0, &NodeIdMap::default());
        let cb = m
            .get_cross_block_selection()
            .expect("other DOM is untouched");
        assert_eq!(cb.anchor.ifc_root_node_id, NodeId::new(2));
        assert_eq!(cb.focus.ifc_root_node_id, NodeId::new(5));
    }
    #[test]
    fn autotest_remap_of_a_stable_cross_block_selection_owes_no_repaint() {
        let mut m = TextEditManager::new();
        m.set_cross_block_selection(cross_block_selection(NodeId::new(2), NodeId::new(5)));
        m.display_list_dirty = false;
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([
                (NodeId::new(2), NodeId::new(2)),
                (NodeId::new(5), NodeId::new(5)),
            ]),
        );
        assert!(m.get_cross_block_selection().is_some());
        assert!(
            !m.display_list_dirty,
            "a rebuild that renumbered nothing has no pixels to redraw"
        );
    }
    #[test]
    fn autotest_remap_rewrites_and_prunes_pending_edit_notifications() {
        let mut m = TextEditManager::new();
        m.pending_edit_notifications = vec![
            dom_node(DOM0, Some(NodeId::new(1))),
            dom_node(DOM0, Some(NodeId::new(4))),
            dom_node(DOM1, Some(NodeId::new(4))),
        ];
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(0))]),
        );
        assert_eq!(
            m.pending_edit_notifications,
            vec![
                dom_node(DOM0, Some(NodeId::new(0))),
                dom_node(DOM1, Some(NodeId::new(4))),
            ],
            "surviving hosts are rewritten, unmounted ones dropped, other DOMs untouched"
        );
    }
    #[test]
    fn autotest_remap_rewrites_and_prunes_pending_text_changed() {
        let mut m = TextEditManager::new();
        m.pending_text_changed = vec![
            dom_node(DOM0, Some(NodeId::new(2))),
            dom_node(DOM0, Some(NodeId::new(7))),
            dom_node(DOM1, Some(NodeId::new(7))),
        ];
        m.remap_node_ids(
            DOM0,
            &NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(5))]),
        );
        assert_eq!(
            m.pending_text_changed,
            vec![
                dom_node(DOM0, Some(NodeId::new(5))),
                dom_node(DOM1, Some(NodeId::new(7))),
            ],
            "the surviving text node is renamed, the unmounted one dropped, other DOMs untouched"
        );
    }
    // ==================================================================
    // Change semantics: value_at_focus (11a-i)
    // ==================================================================
    fn node(dom: DomId, n: usize) -> DomNodeId {
        DomNodeId {
            dom,
            node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
                NodeId::new(n),
            )),
        }
    }
    /// THE bug: focusing a field and tabbing straight back out emitted a
    /// `Change` on a field nobody typed into - enough to re-run validation,
    /// mark a form dirty, or fire a save.
    #[test]
    fn an_untouched_field_reports_no_change() {
        let mut m = TextEditManager::new();
        let n = node(DOM0, 3);
        m.snapshot_value_at_focus(n, "hello".to_string());
        assert_eq!(m.value_changed_since_focus(n, "hello"), Some(false));
    }
    /// ...and the other direction, or the fix would just suppress `Change`
    /// entirely, which is a worse bug than the one being fixed.
    #[test]
    fn an_edited_field_reports_a_change() {
        let mut m = TextEditManager::new();
        let n = node(DOM0, 3);
        m.snapshot_value_at_focus(n, "hello".to_string());
        assert_eq!(m.value_changed_since_focus(n, "hello!"), Some(true));
    }
    /// Emptying a field is a change. Trivial, but it is the case a
    /// `!current.is_empty()` shortcut would get wrong.
    #[test]
    fn clearing_a_field_is_a_change() {
        let mut m = TextEditManager::new();
        let n = node(DOM0, 3);
        m.snapshot_value_at_focus(n, "hello".to_string());
        assert_eq!(m.value_changed_since_focus(n, ""), Some(true));
    }
    /// The snapshot is keyed by node so it cannot be compared against a
    /// DIFFERENT field. Focus moving A -> B -> A must measure A against A's
    /// own starting value; an unkeyed snapshot would measure A against B's.
    #[test]
    fn a_snapshot_is_never_compared_against_another_node() {
        let mut m = TextEditManager::new();
        let a = node(DOM0, 3);
        let b = node(DOM0, 4);
        m.snapshot_value_at_focus(a, "a-value".to_string());
        // B's text happens to differ from A's snapshot - an unkeyed
        // implementation would call that a change to B.
        assert_eq!(m.value_changed_since_focus(b, "b-value"), None);
    }
    /// The same node index in a DIFFERENT dom is a different node.
    #[test]
    fn the_snapshot_key_includes_the_dom() {
        let mut m = TextEditManager::new();
        m.snapshot_value_at_focus(node(DOM0, 3), "v".to_string());
        assert_eq!(m.value_changed_since_focus(node(DOM1, 3), "other"), None);
    }
    /// With no snapshot the question is UNANSWERABLE, which is distinct from
    /// "no change" - the caller has to decide, and it must not be told `false`
    /// as though a comparison had happened. Reachable whenever focus is set
    /// programmatically before any snapshot exists.
    #[test]
    fn no_snapshot_means_unanswerable_not_unchanged() {
        let m = TextEditManager::new();
        assert_eq!(m.value_changed_since_focus(node(DOM0, 3), "anything"), None);
    }
    /// A re-focus REPLACES the baseline rather than accumulating: the second
    /// visit is measured against what the field held on the second visit.
    #[test]
    fn re_focusing_resets_the_baseline() {
        let mut m = TextEditManager::new();
        let n = node(DOM0, 3);
        m.snapshot_value_at_focus(n, "first".to_string());
        m.snapshot_value_at_focus(n, "second".to_string());
        assert_eq!(m.value_changed_since_focus(n, "second"), Some(false));
        assert_eq!(m.value_changed_since_focus(n, "first"), Some(true));
    }
    #[test]
    fn clearing_the_snapshot_makes_it_unanswerable_again() {
        let mut m = TextEditManager::new();
        let n = node(DOM0, 3);
        m.snapshot_value_at_focus(n, "v".to_string());
        m.clear_value_at_focus();
        assert_eq!(m.value_changed_since_focus(n, "v"), None);
    }
}
impl azul_core::events::EventProvider for TextEditManager {
    /// Yield `CompositionStart` / `CompositionUpdate` / `CompositionEnd` for a
    /// composition phase recorded since the last drain.
    ///
    /// Target is the focused node — a composition belongs to whatever is being
    /// typed into. Planning names both the Hover and Focus variants, so a
    /// listener on either family receives it.
    ///
    /// `get_pending_events` takes `&self`, so the phase is read here and
    /// cleared by the owner during the same pass (see `take_pending_composition`);
    /// re-emitting a stale phase would fire `CompositionStart` on every frame
    /// for the life of the composition.
50
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
        use azul_core::events::{
            CompositionEventData, EventData, EventSource, EventType, SyntheticEvent,
        };
50
        let event_type_of = |phase: CompositionPhase| match phase {
10
            CompositionPhase::Start => EventType::CompositionStart,
10
            CompositionPhase::Update => EventType::CompositionUpdate,
20
            CompositionPhase::End => EventType::CompositionEnd,
40
        };
50
        let mut out = Vec::new();
50
        if let Some(phase) = self.pending_composition {
            let begin = usize::try_from(self.preedit_cursor_begin).unwrap_or(0);
            let end = usize::try_from(self.preedit_cursor_end).unwrap_or(begin);
            out.push(SyntheticEvent::new(
                event_type_of(phase),
                EventSource::User,
                DomNodeId::ROOT,
                timestamp.clone(),
                EventData::Composition(CompositionEventData {
                    data: self.composition_text.clone(),
                    cursor_begin: begin,
                    cursor_end: end,
                    seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
                }),
            ));
50
        }
        // The other seats' phases (9b-ii-a-i-d-ii-c-i), stamped with the seat:
        // the Focus filter routes each to that seat's focused node.
90
        for (seat_id, pending) in &self.seat_pending_compositions {
40
            let begin = usize::try_from(pending.cursor_begin).unwrap_or(0);
40
            let end = usize::try_from(pending.cursor_end).unwrap_or(begin);
40
            out.push(SyntheticEvent::new(
40
                event_type_of(pending.phase),
40
                EventSource::User,
40
                DomNodeId::ROOT,
40
                timestamp.clone(),
40
                EventData::Composition(CompositionEventData {
40
                    data: pending.text.clone(),
40
                    cursor_begin: begin,
40
                    cursor_end: end,
40
                    seat_id: *seat_id,
40
                }),
40
            ));
40
        }
50
        out
50
    }
}
/// Rebase a byte range of the IME DOCUMENT - the committed text with the
/// preedit spliced in at `marked` (see `LayoutWindow::ime_document`) - onto
/// the COMMITTED text alone (10b-i-b-i-b).
///
/// This is what makes an explicit `replacementRange` during a composition
/// applicable: the offsets the input method sends index a string that
/// contains the marked text, and the selection seam the range is applied
/// through resolves against a layout that no longer does once the preedit
/// is un-shaped. So the caller ends (un-shapes) the composition FIRST and
/// then applies the range this returns - the reading `WebKit`'s
/// `WebPage::setCompositionAsync` / `insertTextAsync` imply, where the
/// replacement selection is set on the document and the composition is
/// then confirmed before the new text lands.
///
/// - `None` (`NSNotFound`) stays `None`: an implicit range is the caret or the composition, which
///   need no rebasing.
/// - No composition: the range is only ordered.
/// - A range wholly BEFORE the preedit is unchanged.
/// - A range wholly AFTER it slides back by the preedit's length.
/// - A range OVERLAPPING the preedit (partially or wholly, or containing it) resolves to the
///   preedit's own place in the committed text: the empty span at the composition's start, which is
///   where the caret sits once the preedit is gone. The caller's replacement rule reads an empty
///   range as "act at the caret", so the committed text around the composition is never deleted on
///   the strength of offsets that named composed glyphs - a partial overlap is not a shape any IME
///   documents, and this is the conservative reading of it.
/// - A zero-length range is a point and follows the same rules.
#[must_use]
17
pub fn rebase_ime_range_onto_committed(
17
    range: Option<(usize, usize)>,
17
    marked: Option<(usize, usize)>,
17
) -> Option<(usize, usize)> {
17
    let (start, end) = range?;
15
    let (start, end) = if start <= end {
13
        (start, end)
    } else {
2
        (end, start)
    };
15
    let Some((mark_start, mark_end)) = marked else {
1
        return Some((start, end));
    };
14
    let (mark_start, mark_end) = if mark_start <= mark_end {
14
        (mark_start, mark_end)
    } else {
        (mark_end, mark_start)
    };
14
    let preedit_len = mark_end - mark_start;
14
    if end <= mark_start {
4
        return Some((start, end));
10
    }
10
    if start >= mark_end {
4
        return Some((start - preedit_len, end - preedit_len));
6
    }
6
    Some((mark_start, mark_start))
17
}
#[cfg(test)]
mod ime_range_rebase_tests {
    use super::rebase_ime_range_onto_committed;
    // Document "ab" + preedit "にほん" (9 bytes) + "cd": marked = (2, 11).
    const MARKED: Option<(usize, usize)> = Some((2, 11));
    #[test]
1
    fn nsnotfound_is_untouched() {
1
        assert_eq!(rebase_ime_range_onto_committed(None, MARKED), None);
1
        assert_eq!(rebase_ime_range_onto_committed(None, None), None);
1
    }
    #[test]
1
    fn without_a_composition_the_range_is_only_ordered() {
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((5, 2)), None),
            Some((2, 5))
        );
1
    }
    #[test]
1
    fn a_range_before_the_preedit_is_unchanged() {
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((0, 2)), MARKED),
            Some((0, 2))
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((0, 1)), MARKED),
            Some((0, 1)),
            "ending short of the preedit is still before it"
        );
1
    }
    #[test]
1
    fn a_range_after_the_preedit_slides_back_by_its_length() {
        // "cd" is bytes 11..13 of the document and 2..4 of the committed text.
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((11, 13)), MARKED),
            Some((2, 4))
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((13, 11)), MARKED),
            Some((2, 4)),
            "a reversed range is ordered first"
        );
1
    }
    #[test]
1
    fn a_range_overlapping_the_preedit_resolves_to_its_own_place() {
1
        let at_composition = Some((2, 2));
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((2, 11)), MARKED),
            at_composition,
            "the preedit itself"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((0, 5)), MARKED),
            at_composition,
            "straddling its start"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((8, 13)), MARKED),
            at_composition,
            "straddling its end"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((0, 13)), MARKED),
            at_composition,
            "containing it"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((4, 6)), MARKED),
            at_composition,
            "inside it"
        );
1
    }
    #[test]
1
    fn a_zero_length_range_is_a_point_under_the_same_rules() {
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((1, 1)), MARKED),
            Some((1, 1))
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((2, 2)), MARKED),
            Some((2, 2)),
            "at the composition's start: before it"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((11, 11)), MARKED),
            Some((2, 2)),
            "at its end: after it, and the same point once it is gone"
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((13, 13)), MARKED),
            Some((4, 4))
        );
1
        assert_eq!(
1
            rebase_ime_range_onto_committed(Some((5, 5)), MARKED),
            Some((2, 2)),
            "inside it: the composition's place"
        );
1
    }
}
#[cfg(test)]
mod composition_end_tests {
    use super::{CompositionPhase, TextEditManager};
    /// A COMMIT and a CANCEL both end the composition, and the difference an
    /// app reads is the TEXT.
    ///
    /// X11 was the only backend that never called `commit_composition` — it
    /// has no separate commit event, since `Xutf8LookupString` returns the
    /// committed string directly and the preedit merely goes empty. So every
    /// X11 commit arrived as `CompositionEnd` with an empty payload, which is
    /// what a cancel means, and an app had to recover the text from the
    /// ordinary text input that followed.
    #[test]
1
    fn a_commit_carries_its_text_and_a_cancel_does_not() {
        // COMMIT.
1
        let mut m = TextEditManager::default();
1
        m.set_preedit("にほん".to_string(), 0, 0);
1
        assert_eq!(
1
            m.take_pending_composition(),
1
            Some((CompositionPhase::Start, "にほん".to_string())),
        );
1
        m.commit_composition("日本".to_string());
1
        assert_eq!(
1
            m.take_pending_composition(),
1
            Some((CompositionPhase::End, "日本".to_string())),
            "a commit must report WHAT was committed",
        );
        // CANCEL: the composition ends with nothing.
1
        let mut m = TextEditManager::default();
1
        m.set_preedit("にほん".to_string(), 0, 0);
1
        let _ = m.take_pending_composition();
1
        m.clear_preedit();
1
        assert_eq!(
1
            m.take_pending_composition(),
1
            Some((CompositionPhase::End, String::new())),
            "a cancel ends the composition with no text",
        );
1
    }
    /// Clearing an already-clear preedit is not an end.
    ///
    /// Otherwise every focus change would report a `CompositionEnd` for a
    /// composition that never started.
    #[test]
1
    fn clearing_nothing_reports_nothing() {
1
        let mut m = TextEditManager::default();
1
        m.clear_preedit();
1
        assert_eq!(m.take_pending_composition(), None);
1
    }
}