1
//! Text selection and cursor positioning for inline content.
2
//!
3
//! This module provides data structures for managing text cursors and selection ranges
4
//! in a bidirectional (Bidi) and line-breaking aware manner. It handles:
5
//!
6
//! - **Grapheme cluster identification**: Unicode-aware character boundaries
7
//! - **Bidi support**: Cursor movement in mixed LTR/RTL text
8
//! - **Stable positions**: Selection anchors survive layout changes
9
//! - **Affinity tracking**: Cursor position at leading/trailing edges
10
//! - **Multi-node selection**: Browser-style selection spanning multiple DOM nodes
11
//!
12
//! # Architecture
13
//!
14
//! Text positions are represented as:
15
//! - `ContentIndex`: Logical position in the original inline content array
16
//! - `GraphemeClusterId`: Stable identifier for a grapheme cluster (survives reordering)
17
//! - `TextCursor`: Precise cursor location with leading/trailing affinity
18
//! - `SelectionRange`: Start and end cursors defining a selection
19
//!
20
//! Multi-node selection uses an Anchor/Focus model (W3C Selection API):
21
//! - `SelectionAnchor`: Fixed point where user started selection (mousedown)
22
//! - `SelectionFocus`: Movable point where selection currently ends (drag position)
23
//! - `TextSelection`: Complete selection state spanning potentially multiple IFC roots
24
//!
25
//! # Use Cases
26
//!
27
//! - Text editing: Insert/delete at cursor position
28
//! - Selection rendering: Highlight selected text across multiple nodes
29
//! - Keyboard navigation: Move cursor by grapheme/word/line
30
//! - Mouse selection: Convert pixel coordinates to text positions
31
//! - Drag selection: Extend selection across multiple DOM nodes
32
//!
33
//! # Examples
34
//!
35
//! ```rust,no_run
36
//! use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
37
//!
38
//! let cursor = TextCursor {
39
//!     cluster_id: GraphemeClusterId {
40
//!         source_run: 0,
41
//!         start_byte_in_run: 0,
42
//!     },
43
//!     affinity: CursorAffinity::Leading,
44
//! };
45
//! ```
46

            
47
use alloc::{collections::BTreeMap, vec::Vec};
48
use core::sync::atomic::{AtomicU64, Ordering};
49

            
50
use crate::{
51
    dom::{DomId, DomNodeId, NodeId},
52
    geom::{LogicalPosition, LogicalRect},
53
};
54

            
55
/// A stable, logical pointer to an item within the original `InlineContent` array.
56
///
57
/// This structure eliminates the need for string concatenation and byte-offset math
58
/// by tracking both the run index and the item index within that run.
59
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
60
pub struct ContentIndex {
61
    /// The index of the `InlineContent` run in the original input array.
62
    pub run_index: u32,
63
    /// The byte index of the character or item *within* that run's string.
64
    pub item_index: u32,
65
}
66

            
67
/// A stable, logical identifier for a grapheme cluster.
68
///
69
/// This survives Bidi reordering and line breaking, making it ideal for tracking
70
/// text positions for selection and cursor logic.
71
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
72
#[repr(C)]
73
pub struct GraphemeClusterId {
74
    /// The `run_index` from the source `ContentIndex`.
75
    pub source_run: u32,
76
    /// The byte index of the start of the cluster in its original `StyledRun`.
77
    pub start_byte_in_run: u32,
78
}
79

            
80
/// Represents the logical position of the cursor *between* two grapheme clusters
81
/// or at the start/end of the text.
82
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
83
#[repr(C)]
84
pub enum CursorAffinity {
85
    /// The cursor is at the leading edge of the character (left in LTR, right in RTL).
86
    Leading,
87
    /// The cursor is at the trailing edge of the character (right in LTR, left in RTL).
88
    Trailing,
89
}
90

            
91
/// Represents a precise cursor location in the logical text.
92
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
93
#[repr(C)]
94
pub struct TextCursor {
95
    /// The grapheme cluster the cursor is associated with.
96
    pub cluster_id: GraphemeClusterId,
97
    /// The edge of the cluster the cursor is on.
98
    pub affinity: CursorAffinity,
99
}
100

            
101
impl_option!(
102
    TextCursor,
103
    OptionTextCursor,
104
    [Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd]
105
);
106

            
107
/// Represents a range of selected text. The direction is implicit (start can be
108
/// logically after end if selecting backwards).
109
#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash)]
110
#[repr(C)]
111
pub struct SelectionRange {
112
    pub start: TextCursor,
113
    pub end: TextCursor,
114
}
115

            
116
impl_option!(
117
    SelectionRange,
118
    OptionSelectionRange,
119
    [Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd]
120
);
121

            
122
impl_vec!(
123
    SelectionRange,
124
    SelectionRangeVec,
125
    SelectionRangeVecDestructor,
126
    SelectionRangeVecDestructorType,
127
    SelectionRangeVecSlice,
128
    OptionSelectionRange
129
);
130
impl_vec_debug!(SelectionRange, SelectionRangeVec);
131
impl_vec_clone!(
132
    SelectionRange,
133
    SelectionRangeVec,
134
    SelectionRangeVecDestructor
135
);
136
impl_vec_partialeq!(SelectionRange, SelectionRangeVec);
137
impl_vec_partialord!(SelectionRange, SelectionRangeVec);
138

            
139
/// A single selection, which can be either a blinking cursor or a highlighted range.
140
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
141
#[repr(C, u8)]
142
pub enum Selection {
143
    Cursor(TextCursor),
144
    Range(SelectionRange),
145
}
146

            
147
impl_option!(
148
    Selection,
149
    OptionSelection,
150
    [Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord]
151
);
152

            
153
impl_vec!(
154
    Selection,
155
    SelectionVec,
156
    SelectionVecDestructor,
157
    SelectionVecDestructorType,
158
    SelectionVecSlice,
159
    OptionSelection
160
);
161
impl_vec_debug!(Selection, SelectionVec);
162
impl_vec_clone!(Selection, SelectionVec, SelectionVecDestructor);
163
impl_vec_partialeq!(Selection, SelectionVec);
164
impl_vec_partialord!(Selection, SelectionVec);
165

            
166
/// The complete selection state for a single text block, supporting multiple cursors/ranges.
167
#[derive(Debug, Clone, PartialEq)]
168
#[repr(C)]
169
pub struct SelectionState {
170
    /// A list of all active selections. This list is kept sorted and non-overlapping.
171
    pub selections: SelectionVec,
172
    /// The DOM node this selection state applies to.
173
    pub node_id: DomNodeId,
174
}
175

            
176
impl SelectionState {
177
    /// Adds a new selection, merging it with any existing selections it overlaps with.
178
111
    pub fn add(&mut self, new_selection: Selection) {
179
        // A full implementation would handle merging overlapping ranges.
180
        // For now, we simply add and sort for simplicity.
181
111
        let mut selections: Vec<Selection> = self.selections.as_ref().to_vec();
182
111
        selections.push(new_selection);
183
111
        selections.sort_unstable();
184
111
        selections.dedup(); // Removes duplicate cursors
185
111
        self.selections = selections.into();
186
111
    }
187
}
188

            
189
impl_option!(
190
    SelectionState,
191
    OptionSelectionState,
192
    copy = false,
193
    clone = false,
194
    [Debug, Clone, PartialEq]
195
);
196

            
197
// ============================================================================
198
// MULTI-CURSOR SUPPORT (Sublime Text style)
199
// ============================================================================
200

            
201
/// Stable identifier for a cursor/selection within a `MultiCursorState`.
202
///
203
/// Uses a monotonic u64 counter (not UUID) so it is `Copy` and C-API friendly.
204
/// Each `SelectionId` is unique within the lifetime of the process.
205
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
206
#[repr(C)]
207
pub struct SelectionId {
208
    pub inner: u64,
209
}
210

            
211
impl SelectionId {
212
    /// Generate a new unique `SelectionId`.
213
18210
    pub fn new() -> Self {
214
        static COUNTER: AtomicU64 = AtomicU64::new(1);
215
18210
        Self {
216
18210
            inner: COUNTER.fetch_add(1, Ordering::Relaxed),
217
18210
        }
218
18210
    }
219
}
220

            
221
/// Note: `Default` generates a new unique ID (increments global counter),
222
/// rather than returning a zero/sentinel value.
223
impl Default for SelectionId {
224
2
    fn default() -> Self {
225
2
        Self::new()
226
2
    }
227
}
228

            
229
impl_option!(
230
    SelectionId,
231
    OptionSelectionId,
232
    [Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord]
233
);
234

            
235
impl_vec!(
236
    SelectionId,
237
    SelectionIdVec,
238
    SelectionIdVecDestructor,
239
    SelectionIdVecDestructorType,
240
    SelectionIdVecSlice,
241
    OptionSelectionId
242
);
243
impl_vec_debug!(SelectionId, SelectionIdVec);
244
impl_vec_clone!(SelectionId, SelectionIdVec, SelectionIdVecDestructor);
245
impl_vec_partialeq!(SelectionId, SelectionIdVec);
246
impl_vec_partialord!(SelectionId, SelectionIdVec);
247

            
248
/// A selection (cursor or range) paired with a stable identity.
249
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
250
#[repr(C)]
251
pub struct IdentifiedSelection {
252
    pub id: SelectionId,
253
    pub selection: Selection,
254
    /// WHOSE selection this is (U1).
255
    ///
256
    /// [`SelectionOwner::LOCAL`] for the person at this machine, which is
257
    /// every selection the engine creates itself. An app running a shared
258
    /// editing session injects the other participants' cursors with their own
259
    /// owners, and the paint path colours by this rather than by the node's
260
    /// `caret-color` - one colour per participant is the whole point.
261
    pub owner: SelectionOwner,
262
}
263

            
264
impl_option!(
265
    IdentifiedSelection,
266
    OptionIdentifiedSelection,
267
    [Debug, Clone, Copy, PartialEq, Eq, Hash]
268
);
269

            
270
impl_vec!(
271
    IdentifiedSelection,
272
    IdentifiedSelectionVec,
273
    IdentifiedSelectionVecDestructor,
274
    IdentifiedSelectionVecDestructorType,
275
    IdentifiedSelectionVecSlice,
276
    OptionIdentifiedSelection
277
);
278
impl_vec_debug!(IdentifiedSelection, IdentifiedSelectionVec);
279
impl_vec_clone!(
280
    IdentifiedSelection,
281
    IdentifiedSelectionVec,
282
    IdentifiedSelectionVecDestructor
283
);
284
impl_vec_partialeq!(IdentifiedSelection, IdentifiedSelectionVec);
285

            
286
/// WHO a cursor or selection belongs to (U1).
287
///
288
/// A 128-bit id rather than an index, because it has to survive a NETWORK: in a
289
/// shared editing session the participants are decided elsewhere - a server, a
290
/// CRDT peer id, a user account - and an engine-allocated number could not be
291
/// agreed on by two machines. [`SelectionId`] is that engine-allocated number
292
/// and stays local; this is the app's, and the two are separate fields for
293
/// exactly that reason.
294
///
295
/// Split into two `u64`s rather than a `u128` because this crosses the C ABI,
296
/// where `u128` had no stable layout until recently and still surprises
297
/// bindings.
298
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
299
#[repr(C)]
300
pub struct SelectionOwner {
301
    pub high: u64,
302
    pub low: u64,
303
}
304

            
305
impl SelectionOwner {
306
    /// The person at this machine.
307
    ///
308
    /// All-zero, so a `Default` selection is a local one and every existing
309
    /// construction site keeps meaning what it meant.
310
    pub const LOCAL: Self = Self { high: 0, low: 0 };
311

            
312
    #[must_use]
313
21
    pub const fn new(high: u64, low: u64) -> Self {
314
21
        Self { high, low }
315
21
    }
316

            
317
    /// Is this the local participant?
318
    #[must_use]
319
53630
    pub const fn is_local(self) -> bool {
320
53630
        self.high == 0 && self.low == 0
321
53630
    }
322

            
323
    /// The `high` half every SEAT owner carries (9b-ii-a-i-d-ii-a). A random
324
    /// (v4) peer UUID never has this exact high half, and it is non-zero so a
325
    /// seat owner is never "local".
326
    pub const SEAT_HIGH: u64 = 0x5EA7_0000_0000_0001;
327

            
328
    /// The owner that stands for pointer / keyboard seat `seat_id`'s caret
329
    /// (9b-ii-a-i-d-ii-a): a second person at this machine, drawn like a
330
    /// peer caret in that seat's colour. Seat 0, the primary, is `LOCAL`.
331
    #[must_use]
332
743
    pub const fn seat(seat_id: u64) -> Self {
333
743
        if seat_id == 0 {
334
11
            return Self::LOCAL;
335
732
        }
336
732
        Self {
337
732
            high: Self::SEAT_HIGH,
338
732
            low: seat_id,
339
732
        }
340
743
    }
341

            
342
    /// Whether this owner is a (non-primary) seat at this machine.
343
    #[must_use]
344
2
    pub const fn is_seat(self) -> bool {
345
2
        self.high == Self::SEAT_HIGH
346
2
    }
347

            
348
    /// The seat this owner stands for, if it is one.
349
    #[must_use]
350
1
    pub const fn seat_id(self) -> Option<u64> {
351
1
        if self.is_seat() {
352
1
            Some(self.low)
353
        } else {
354
            None
355
        }
356
1
    }
357
}
358

            
359
/// Multi-cursor state for a contenteditable element (Sublime Text style).
360
///
361
/// Replaces the split `CursorManager` + `SelectionManager` pattern for text editing.
362
/// Supports multiple simultaneous cursors/selections, each with a stable ID.
363
///
364
/// ## Invariants
365
///
366
/// - `selections` is sorted by owner, then by position, and non-overlapping within one owner.
367
/// - The **primary** selection is identified by the stable `primary_id`, NOT by vector position:
368
///   `merge_overlapping()` re-sorts `selections` by position, so "last index" is not the
369
///   most-recently-added cursor.
370
/// - After any mutation, `merge_overlapping()` is called to maintain invariants.
371
///
372
/// ## Who a selection belongs to (U3)
373
///
374
/// A selection is identified by an OWNER-SCOPED id: `(owner, id)`. The engine
375
/// acts on the [`SelectionOwner::LOCAL`] set and on nothing else:
376
///
377
/// - the PRIMARY is always local - `get_primary` never answers with a peer's selection, and
378
///   `primary_id` is re-pointed only at a local one;
379
/// - the EDIT SET (`to_selections`, what typing / Backspace / paste apply to) is the local set, and
380
///   `update_from_edit_result` writes back to it alone, leaving every peer's entry untouched;
381
/// - a plain click (`set_single_cursor` / `set_single_range`) collapses the LOCAL set to one and
382
///   keeps the peers in view;
383
/// - cursor movement (`move_all_cursors*`) moves local carets only;
384
/// - the platform's idea of "the selection" (`selectedTextRange`, the IME's marked range, the
385
///   Android selection bridge) is the local primary.
386
///
387
/// Peers' selections are DISPLAY-ONLY SNAPSHOTS: they enter through
388
/// `set_owner_selections`, leave through `remove_owner`, and are painted in
389
/// their owner's colour. They are not shifted by a local edit either - the
390
/// sync layer that carried the snapshot here is the one that knows how the
391
/// edit moved the peer's caret, and it replaces the snapshot. Anything that
392
/// walks `selections` directly and means "what is the user doing" must go
393
/// through [`Self::local_selections`]; walking the whole list is right only
394
/// for painting.
395
#[derive(Debug, Clone, PartialEq, Eq)]
396
pub struct MultiCursorState {
397
    /// Sorted by position, non-overlapping. Primary is tracked via `primary_id`.
398
    pub selections: Vec<IdentifiedSelection>,
399
    /// Stable ID of the primary selection (most recently added/set). Survives the
400
    /// position sort in `merge_overlapping`, which would otherwise make the
401
    /// vector's last element (position-last) masquerade as the primary.
402
    pub primary_id: SelectionId,
403
    /// The DOM node this multi-cursor state applies to.
404
    pub node_id: DomNodeId,
405
    /// Stable key that survives DOM rebuilds (from `calculate_contenteditable_key`).
406
    pub contenteditable_key: u64,
407
}
408

            
409
impl MultiCursorState {
410
    /// Create a new `MultiCursorState` with a single cursor.
411
    #[must_use]
412
2525
    pub fn new_with_cursor(
413
2525
        cursor: TextCursor,
414
2525
        node_id: DomNodeId,
415
2525
        contenteditable_key: u64,
416
2525
    ) -> Self {
417
2525
        let id = SelectionId::new();
418
2525
        Self {
419
2525
            selections: vec![IdentifiedSelection {
420
2525
                id,
421
2525
                selection: Selection::Cursor(cursor),
422
2525
                owner: SelectionOwner::LOCAL,
423
2525
            }],
424
2525
            primary_id: id,
425
2525
            node_id,
426
2525
            contenteditable_key,
427
2525
        }
428
2525
    }
429

            
430
    /// Add a cursor, merging if it overlaps with existing selections.
431
    /// Returns the `SelectionId` of the new (or merged) cursor.
432
    #[must_use]
433
952
    pub fn add_cursor(&mut self, cursor: TextCursor) -> SelectionId {
434
952
        let id = SelectionId::new();
435
952
        self.selections.push(IdentifiedSelection {
436
952
            id,
437
952
            selection: Selection::Cursor(cursor),
438
952
            owner: SelectionOwner::LOCAL,
439
952
        });
440
952
        self.primary_id = id;
441
952
        self.merge_overlapping();
442
952
        id
443
952
    }
444

            
445
    /// Add a selection range, merging if it overlaps.
446
    /// Returns the `SelectionId` of the new (or merged) selection.
447
    #[must_use]
448
70
    pub fn add_selection(&mut self, range: SelectionRange) -> SelectionId {
449
70
        let id = SelectionId::new();
450
70
        self.selections.push(IdentifiedSelection {
451
70
            id,
452
70
            selection: Selection::Range(range),
453
70
            owner: SelectionOwner::LOCAL,
454
70
        });
455
70
        self.primary_id = id;
456
70
        self.merge_overlapping();
457
70
        id
458
70
    }
459

            
460
    /// Remove a selection by its stable ID. Returns true if found and removed.
461
    #[must_use]
462
9
    pub fn remove_selection(&mut self, id: SelectionId) -> bool {
463
9
        let len_before = self.selections.len();
464
17
        self.selections.retain(|s| s.id != id);
465
9
        let removed = self.selections.len() < len_before;
466
9
        if removed {
467
7
            // If we just removed the primary, re-point it at a surviving one.
468
7
            self.ensure_primary_valid();
469
7
        }
470
9
        removed
471
9
    }
472

            
473
    /// The LOCAL participant's selections - the ones the engine edits, moves
474
    /// and reports (U3). Peers' snapshots are excluded.
475
6633
    pub fn local_selections(&self) -> impl Iterator<Item = &IdentifiedSelection> {
476
7633
        self.selections.iter().filter(|s| s.owner.is_local())
477
6633
    }
478

            
479
    /// Mutable [`Self::local_selections`].
480
2
    pub fn local_selections_mut(&mut self) -> impl Iterator<Item = &mut IdentifiedSelection> {
481
2
        self.selections.iter_mut().filter(|s| s.owner.is_local())
482
2
    }
483

            
484
    /// How many carets the LOCAL user is typing into. This - not
485
    /// [`Self::len`] - is the count a "one line per cursor" paste or a
486
    /// "multi-cursor mode" decision wants; a peer's caret is not somewhere the
487
    /// local user types.
488
    #[must_use]
489
5
    pub fn local_len(&self) -> usize {
490
5
        self.local_selections().count()
491
5
    }
492

            
493
    /// Get the primary selection (the most recently added/set, tracked by
494
    /// `primary_id` — NOT the vector's last element, which position-sorting
495
    /// reorders). Falls back to the last LOCAL selection if `primary_id` was
496
    /// somehow lost - never to a peer's: the list is owner-sorted, so a plain
497
    /// `last()` was a peer's entry whenever one existed, and everything that
498
    /// reads "the selection" (IME, the platform selection, copy) would have
499
    /// been answering with someone else's.
500
    #[must_use]
501
21724
    pub fn get_primary(&self) -> Option<&IdentifiedSelection> {
502
21724
        let pid = self.primary_id;
503
21724
        self.selections
504
21724
            .iter()
505
22290
            .find(|s| s.id == pid && s.owner.is_local())
506
21724
            .or_else(|| self.local_selections().last())
507
21724
    }
508

            
509
    /// Get a mutable reference to the primary selection (see `get_primary`).
510
150
    pub fn get_primary_mut(&mut self) -> Option<&mut IdentifiedSelection> {
511
150
        let pid = self.primary_id;
512
150
        if let Some(pos) = self
513
150
            .selections
514
150
            .iter()
515
151
            .position(|s| s.id == pid && s.owner.is_local())
516
        {
517
148
            return self.selections.get_mut(pos);
518
2
        }
519
2
        self.local_selections_mut().last()
520
150
    }
521

            
522
    /// Ensure `primary_id` names a LOCAL selection that still exists; if not,
523
    /// adopt the last local one (best effort) so `get_primary` stays
524
    /// meaningful. With no local selection left, `primary_id` is left dangling
525
    /// on purpose and `get_primary` answers `None` - a peer's caret must not
526
    /// become "the selection" because the local one went away.
527
4333
    fn ensure_primary_valid(&mut self) {
528
4333
        let pid = self.primary_id;
529
4333
        if !self
530
4333
            .selections
531
4333
            .iter()
532
134814
            .any(|s| s.id == pid && s.owner.is_local())
533
        {
534
11
            if let Some(last) = self.local_selections().last() {
535
6
                self.primary_id = last.id;
536
6
            }
537
4322
        }
538
4333
    }
539

            
540
    /// Get the primary cursor position (for scroll-into-view, IME, etc.)
541
    #[must_use]
542
12019
    pub fn get_primary_cursor(&self) -> Option<TextCursor> {
543
12019
        self.get_primary().map(|s| match &s.selection {
544
11999
            Selection::Cursor(c) => *c,
545
4
            Selection::Range(r) => r.end,
546
12003
        })
547
12019
    }
548

            
549
    /// The EDIT SET: the LOCAL selections, as a `Vec<Selection>` for
550
    /// `edit_text()`. Peers' carets are excluded (U3) - with them included, a
551
    /// local keystroke was applied at every peer's caret as well, because
552
    /// multi-cursor editing inserts at every selection it is handed.
553
    #[must_use]
554
3310
    pub fn to_selections(&self) -> Vec<Selection> {
555
3310
        self.local_selections().map(|s| s.selection).collect()
556
3310
    }
557

            
558
    /// Update the LOCAL selections from the result of `edit_text()`.
559
    ///
560
    /// Preserves existing local IDs where possible (by index among the local
561
    /// entries), assigns new IDs for extras. Peers' entries are carried over
562
    /// UNTOUCHED, owner and id included: rebuilding the whole list as local
563
    /// used to absorb every peer into the local user after the first
564
    /// keystroke. Their POSITIONS are then moved across the edit by
565
    /// [`Self::shift_peers_across`] (U3-a), by the caller that knows the
566
    /// text delta.
567
3258
    pub fn update_from_edit_result(&mut self, new_selections: &[Selection]) {
568
3258
        let old_ids: Vec<SelectionId> = self.local_selections().map(|s| s.id).collect();
569
3258
        let peers: Vec<IdentifiedSelection> = self
570
3258
            .selections
571
3258
            .iter()
572
3263
            .filter(|s| !s.owner.is_local())
573
3258
            .copied()
574
3258
            .collect();
575
3258
        self.selections.clear();
576
4260
        for (i, sel) in new_selections.iter().enumerate() {
577
4260
            let id = old_ids.get(i).copied().unwrap_or_else(SelectionId::new);
578
4260
            self.selections.push(IdentifiedSelection {
579
4260
                id,
580
4260
                selection: *sel,
581
4260
                owner: SelectionOwner::LOCAL,
582
4260
            });
583
4260
        }
584
        // Owner-sorted order: LOCAL is all-zero and sorts first, so the peers
585
        // go back behind the rebuilt local set.
586
3258
        self.selections.extend(peers);
587
        // IDs are reassigned by index; make sure primary_id still resolves.
588
3258
        self.ensure_primary_valid();
589
        // Don't merge here — edit_text already returns correct positions
590
3258
    }
591

            
592
    /// Move the PEERS' selections across a change to the text (U3-a).
593
    ///
594
    /// `update_from_edit_result` carries peers over verbatim because the edit
595
    /// result knows nothing about them; the caller that knows what the edit
596
    /// did to the text - one `RunTextChange` per changed run, all relative to
597
    /// the OLD text - applies it here, and a peer's caret moves with the text
598
    /// it was anchored in, per the user's ruling (see
599
    /// [`RunTextChange::transform`]). Local selections are not touched: the
600
    /// edit result already placed them. A peer RANGE has both ends moved and
601
    /// may collapse when the change spans it.
602
    ///
603
    /// The sync layer still owns the semantics of CONCURRENT edits; this is
604
    /// only the local user's own change, which the peer will also receive.
605
9
    pub fn shift_peers_across(&mut self, changes: &[RunTextChange]) {
606
9
        self.shift_across(changes, false);
607
9
    }
608

            
609
    /// Move EVERY selection, the local ones included, across a change to the
610
    /// text that nobody's edit placed them for (U3-b): the app's new
611
    /// generation carried different text for the node - a remote
612
    /// participant's edit applied through the app's model, an app-side
613
    /// rewrite - and each caret keeps its logical anchor in it.
614
1
    pub fn shift_all_across(&mut self, changes: &[RunTextChange]) {
615
1
        self.shift_across(changes, true);
616
1
    }
617

            
618
    /// `shift_peers_across` for a diff that may also have changed the run
619
    /// count (U3-a-i).
620
3253
    pub fn shift_peers_across_diff(&mut self, diff: &RunTextDiff) {
621
3253
        self.shift_across_diff(diff, false);
622
3253
    }
623

            
624
    /// `shift_all_across` for a diff that may also have changed the run
625
    /// count (U3-a-i).
626
72
    pub fn shift_all_across_diff(&mut self, diff: &RunTextDiff) {
627
72
        self.shift_across_diff(diff, true);
628
72
    }
629

            
630
3325
    fn shift_across_diff(&mut self, diff: &RunTextDiff, include_local: bool) {
631
3325
        if diff.is_empty() {
632
            return;
633
3325
        }
634
3325
        for sel in self
635
3325
            .selections
636
3325
            .iter_mut()
637
3350
            .filter(|s| include_local || !s.owner.is_local())
638
        {
639
97
            sel.selection = match sel.selection {
640
97
                Selection::Cursor(c) => Selection::Cursor(diff.map_cursor(c)),
641
                Selection::Range(r) => {
642
                    let start = diff.map_cursor(r.start);
643
                    let end = diff.map_cursor(r.end);
644
                    if start == end {
645
                        Selection::Cursor(start)
646
                    } else {
647
                        Selection::Range(SelectionRange { start, end })
648
                    }
649
                }
650
            };
651
        }
652
3325
    }
653

            
654
10
    fn shift_across(&mut self, changes: &[RunTextChange], include_local: bool) {
655
10
        if changes.is_empty() {
656
            return;
657
10
        }
658
13
        let shift = |mut c: TextCursor| -> TextCursor {
659
26
            for change in changes {
660
13
                if change.run == c.cluster_id.source_run {
661
12
                    c.cluster_id.start_byte_in_run =
662
12
                        change.transform(c.cluster_id.start_byte_in_run);
663
12
                }
664
            }
665
13
            c
666
13
        };
667
11
        for sel in self
668
10
            .selections
669
10
            .iter_mut()
670
20
            .filter(|s| include_local || !s.owner.is_local())
671
        {
672
11
            sel.selection = match sel.selection {
673
9
                Selection::Cursor(c) => Selection::Cursor(shift(c)),
674
2
                Selection::Range(r) => Selection::Range(SelectionRange {
675
2
                    start: shift(r.start),
676
2
                    end: shift(r.end),
677
2
                }),
678
            };
679
        }
680
10
    }
681

            
682
    /// The id a collapsed local set keeps: the local primary's when there is
683
    /// one, so a caller tracking it sees the same selection continue.
684
167
    fn surviving_local_id(&self) -> SelectionId {
685
167
        self.get_primary()
686
167
            .map_or_else(SelectionId::new, |primary| primary.id)
687
167
    }
688

            
689
    /// Collapse the LOCAL selections to a single cursor (a plain click without
690
    /// Ctrl). Peers' selections stay: a click is not a message to them.
691
58
    pub fn set_single_cursor(&mut self, cursor: TextCursor) {
692
58
        let id = self.surviving_local_id();
693
62
        self.selections.retain(|s| !s.owner.is_local());
694
58
        self.selections.insert(
695
            0,
696
58
            IdentifiedSelection {
697
58
                id,
698
58
                selection: Selection::Cursor(cursor),
699
58
                owner: SelectionOwner::LOCAL,
700
58
            },
701
        );
702
58
        self.primary_id = id;
703
58
    }
704

            
705
    /// Collapse the LOCAL selections to a single range. Peers stay, as above.
706
109
    pub fn set_single_range(&mut self, range: SelectionRange) {
707
109
        let id = self.surviving_local_id();
708
109
        self.selections.retain(|s| !s.owner.is_local());
709
109
        self.selections.insert(
710
            0,
711
109
            IdentifiedSelection {
712
109
                id,
713
109
                selection: Selection::Range(range),
714
109
                owner: SelectionOwner::LOCAL,
715
109
            },
716
        );
717
109
        self.primary_id = id;
718
109
    }
719

            
720
    /// Number of selections of EVERY owner - what is painted. For how many
721
    /// carets the local user types into, see [`Self::local_len`].
722
    #[must_use]
723
53
    pub const fn len(&self) -> usize {
724
53
        self.selections.len()
725
53
    }
726

            
727
    /// Whether there are no selections (should not normally happen).
728
    #[must_use]
729
56
    pub const fn is_empty(&self) -> bool {
730
56
        self.selections.is_empty()
731
56
    }
732

            
733
    /// Sort selections by position and merge any that overlap.
734
1090
    pub fn merge_overlapping(&mut self) {
735
1090
        if self.selections.len() <= 1 {
736
97
            return;
737
993
        }
738

            
739
        // Capture the primary before sorting/merging reorders and rewrites IDs.
740
993
        let primary = self.primary_id;
741
993
        let mut new_primary = primary;
742

            
743
        // BY OWNER FIRST, then by position (U1). Two participants' cursors
744
        // must never merge: in a shared editing session that would silently
745
        // delete someone from the document - their caret absorbed into another
746
        // person's and repainted in that person's colour. Sorting by owner
747
        // groups each participant's selections so the adjacency check below
748
        // only ever compares two of the same owner's.
749
133177
        self.selections.sort_by(|a, b| {
750
133177
            a.owner.cmp(&b.owner).then_with(|| {
751
133167
                let pos_a = selection_start_pos(&a.selection);
752
133167
                let pos_b = selection_start_pos(&b.selection);
753
133167
                pos_a.cmp(&pos_b)
754
133167
            })
755
133177
        });
756

            
757
        // Merge overlapping: if selection[i+1] starts at or before selection[i] ends,
758
        // merge them into one range (keeping the later ID as it's more recent).
759
993
        let mut merged: Vec<IdentifiedSelection> = Vec::with_capacity(self.selections.len());
760
132116
        for sel in self.selections.drain(..) {
761
132116
            if let Some(last) = merged.last_mut() {
762
131123
                let last_end = selection_end_pos(&last.selection);
763
131123
                let cur_start = selection_start_pos(&sel.selection);
764
                // SAME OWNER ONLY - see the sort above.
765
131123
                if last.owner == sel.owner && cur_start <= last_end {
766
                    // Overlap — merge into one range covering both
767
616
                    let new_start = selection_start_pos(&last.selection);
768
616
                    let cur_end = selection_end_pos(&sel.selection);
769
616
                    let new_end = if cur_end > last_end {
770
14
                        cur_end
771
                    } else {
772
602
                        last_end
773
                    };
774
616
                    if new_start == new_end {
775
405
                        last.selection = Selection::Cursor(new_start);
776
405
                    } else {
777
211
                        last.selection = Selection::Range(SelectionRange {
778
211
                            start: new_start,
779
211
                            end: new_end,
780
211
                        });
781
211
                    }
782
                    // If either side of the merge — or the accumulator that has
783
                    // already absorbed the primary earlier in the chain — was the
784
                    // primary, the merged selection inherits primary status.
785
                    // `last.id == new_primary` carries the primary across a 3+-link
786
                    // chain: without it, `new_primary` would keep pointing at an
787
                    // intermediate id that the next merge overwrites, and
788
                    // `ensure_primary_valid` would then adopt an unrelated tail.
789
616
                    let inherits_primary =
790
616
                        last.id == primary || sel.id == primary || last.id == new_primary;
791
                    // Keep the newer ID (the one being merged in)
792
616
                    last.id = sel.id;
793
616
                    if inherits_primary {
794
469
                        new_primary = sel.id;
795
469
                    }
796
616
                    continue;
797
130507
                }
798
993
            }
799
131500
            merged.push(sel);
800
        }
801
993
        self.selections = merged;
802

            
803
        // Point primary at a surviving selection (fallback: last element).
804
993
        self.primary_id = new_primary;
805
993
        self.ensure_primary_valid();
806
1090
    }
807

            
808
    /// Replace everything ONE participant owns (U1).
809
    ///
810
    /// The injection point for a shared editing session: a peer's cursor
811
    /// arrives over the network, and this makes it the whole of what that peer
812
    /// has selected. Replacing rather than merging is deliberate - a remote
813
    /// participant's state is a SNAPSHOT, and adding to it would leave stale
814
    /// carets behind whenever a message was missed.
815
    ///
816
    /// Refuses to touch [`SelectionOwner::LOCAL`]: the local caret is the
817
    /// engine's, and letting an app overwrite it through this door would make
818
    /// every text-editing invariant the engine maintains someone else's
819
    /// problem. Returns `false` in that case.
820
71
    pub fn set_owner_selections(
821
71
        &mut self,
822
71
        owner: SelectionOwner,
823
71
        selections: &[Selection],
824
71
    ) -> bool {
825
71
        if owner.is_local() {
826
1
            return false;
827
70
        }
828
77
        self.selections.retain(|s| s.owner != owner);
829
142
        for selection in selections {
830
72
            self.selections.push(IdentifiedSelection {
831
72
                id: SelectionId::new(),
832
72
                selection: *selection,
833
72
                owner,
834
72
            });
835
72
        }
836
        // NOT `merge_overlapping` here: that call is about keeping the LOCAL
837
        // caret set sane after a movement, and a remote snapshot is already
838
        // whatever the peer says it is. Merging it would also renumber ids the
839
        // caller may be tracking.
840
70
        self.ensure_primary_valid();
841
70
        true
842
71
    }
843

            
844
    /// Forget a participant - they left, or their connection dropped.
845
    ///
846
    /// Returns how many selections went. `LOCAL` is refused for the same
847
    /// reason as above; removing it would leave the document with no caret.
848
2
    pub fn remove_owner(&mut self, owner: SelectionOwner) -> usize {
849
2
        if owner.is_local() {
850
1
            return 0;
851
1
        }
852
1
        let before = self.selections.len();
853
3
        self.selections.retain(|s| s.owner != owner);
854
1
        self.ensure_primary_valid();
855
1
        before - self.selections.len()
856
2
    }
857

            
858
    /// Every participant with a selection right now, `LOCAL` included.
859
    #[must_use]
860
6
    pub fn owners(&self) -> Vec<SelectionOwner> {
861
6
        let mut out: Vec<SelectionOwner> = self.selections.iter().map(|s| s.owner).collect();
862
6
        out.sort_unstable();
863
6
        out.dedup();
864
6
        out
865
6
    }
866

            
867
    /// Move all cursors using a movement function. Merges collisions afterward.
868
    ///
869
    /// `move_fn` takes a `TextCursor` and returns the new `TextCursor` after movement.
870
    /// If `extend_selection` is true, the anchor stays and only the focus moves,
871
    /// creating or extending a range.
872
    ///
873
    /// A bare (non-extending) move over an active range COLLAPSES to the range
874
    /// boundary — the arrow-key rule. Use [`Self::move_all_cursors_with`] for
875
    /// steps where that is wrong (Home/End, document jumps).
876
24
    pub fn move_all_cursors(
877
24
        &mut self,
878
24
        extend_selection: bool,
879
24
        move_fn: impl Fn(&TextCursor) -> TextCursor,
880
24
    ) {
881
24
        self.move_all_cursors_with(extend_selection, true, move_fn);
882
24
    }
883

            
884
    /// [`Self::move_all_cursors`], with control over what a bare move does to
885
    /// an active range.
886
    ///
887
    /// `collapse_range_to_boundary` is the arrow-key rule: Left/Right with a
888
    /// selection put the caret on the selection's edge and go no further.
889
    /// Every OTHER step — Home/End, Ctrl+Home/End, a visual line, a word — is a
890
    /// MOVEMENT and must be performed: collapsing them to the nearest edge is
891
    /// how pressing End with text selected used to leave the caret sitting at
892
    /// the end of the selection instead of the end of the line.
893
49
    pub fn move_all_cursors_with(
894
49
        &mut self,
895
49
        extend_selection: bool,
896
49
        collapse_range_to_boundary: bool,
897
49
        move_fn: impl Fn(&TextCursor) -> TextCursor,
898
49
    ) {
899
        // LOCAL carets only (U3): an arrow key is the local user's, and moving
900
        // a peer's caret with it would show the peer somewhere they are not.
901
207
        for sel in self.selections.iter_mut().filter(|s| s.owner.is_local()) {
902
206
            match &sel.selection {
903
178
                Selection::Cursor(c) => {
904
178
                    let new_cursor = move_fn(c);
905
178
                    if extend_selection {
906
2
                        if *c != new_cursor {
907
1
                            sel.selection = Selection::Range(SelectionRange {
908
1
                                start: *c,
909
1
                                end: new_cursor,
910
1
                            });
911
1
                        }
912
176
                    } else {
913
176
                        sel.selection = Selection::Cursor(new_cursor);
914
176
                    }
915
                }
916
28
                Selection::Range(r) => {
917
28
                    if extend_selection {
918
1
                        let new_end = move_fn(&r.end);
919
1
                        if r.start == new_end {
920
1
                            sel.selection = Selection::Cursor(r.start);
921
1
                        } else {
922
                            sel.selection = Selection::Range(SelectionRange {
923
                                start: r.start,
924
                                end: new_end,
925
                            });
926
                        }
927
27
                    } else if collapse_range_to_boundary {
928
                        // Bare arrow with an active selection collapses the caret
929
                        // to the selection boundary in the arrow's direction WITHOUT
930
                        // advancing a character (standard editor behavior). Running
931
                        // move_fn on the focus and using that as the caret would step
932
                        // one unit past the edge. We don't get the arrow direction
933
                        // here, so probe it: apply move_fn to the focus and compare —
934
                        // a forward move collapses to the max boundary, a backward
935
                        // move to the min boundary.
936
15
                        let (lo, hi) = if r.start <= r.end {
937
13
                            (r.start, r.end)
938
                        } else {
939
2
                            (r.end, r.start)
940
                        };
941
15
                        let probe = move_fn(&r.end);
942
15
                        let collapsed = if probe >= r.end { hi } else { lo };
943
15
                        sel.selection = Selection::Cursor(collapsed);
944
12
                    } else {
945
12
                        // Home / End / Ctrl+Home / Ctrl+End / a visual line step:
946
12
                        // the caret goes where the step points, measured from the
947
12
                        // focus. The boundary collapse above would strand it on
948
12
                        // the selection's edge instead.
949
12
                        sel.selection = Selection::Cursor(move_fn(&r.end));
950
12
                    }
951
                }
952
            }
953
        }
954
49
        self.merge_overlapping();
955
49
    }
956

            
957
    /// Remap the `NodeId` in `node_id` after DOM reconciliation.
958
    ///
959
    /// If the node was removed (not in the map), the multi-cursor state is cleared.
960
105
    pub fn remap_node_ids(&mut self, dom_id: DomId, node_id_map: &BTreeMap<NodeId, NodeId>) {
961
105
        if self.node_id.dom != dom_id {
962
1
            return;
963
104
        }
964
104
        if let Some(old_node_id) = self.node_id.node.into_crate_internal() {
965
103
            if let Some(&new_node_id) = node_id_map.get(&old_node_id) {
966
102
                self.node_id.node =
967
102
                    crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(new_node_id));
968
102
            } else {
969
1
                // Node removed — clear selections
970
1
                self.selections.clear();
971
1
            }
972
1
        }
973
105
    }
974
}
975

            
976
/// Helper: get the start position of a Selection for sorting.
977
398879
fn selection_start_pos(sel: &Selection) -> TextCursor {
978
398879
    match sel {
979
396663
        Selection::Cursor(c) => *c,
980
2216
        Selection::Range(r) => {
981
2216
            if r.start <= r.end {
982
1598
                r.start
983
            } else {
984
618
                r.end
985
            }
986
        }
987
    }
988
398879
}
989

            
990
/// Helper: get the end position of a Selection for merging.
991
132545
fn selection_end_pos(sel: &Selection) -> TextCursor {
992
132545
    match sel {
993
131983
        Selection::Cursor(c) => *c,
994
562
        Selection::Range(r) => {
995
562
            if r.end >= r.start {
996
427
                r.end
997
            } else {
998
135
                r.start
999
            }
        }
    }
132545
}
// ============================================================================
// MULTI-NODE SELECTION (Browser-style Anchor/Focus model)
// ============================================================================
/// The anchor point of a text selection - where the user started selecting.
///
/// This is the fixed point during a drag operation. It records:
/// - The IFC root node (where the `UnifiedLayout` lives)
/// - The exact cursor position within that layout
/// - The visual bounds of the anchor character (for logical rectangle calculations)
///
/// The anchor remains constant during a drag; only the focus moves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectionAnchor {
    /// The IFC root node ID where selection started.
    /// This is the node that has `inline_layout_result` (e.g., `<p>`, `<div>`).
    pub ifc_root_node_id: NodeId,
    /// The exact cursor position within the IFC's `UnifiedLayout`.
    pub cursor: TextCursor,
    /// Visual bounds of the anchor character in viewport coordinates.
    /// Used for computing the logical selection rectangle during multi-line/multi-node selection.
    pub char_bounds: LogicalRect,
    /// The mouse position when the selection started (viewport coordinates).
    pub mouse_position: LogicalPosition,
}
/// The focus point of a text selection - where the selection currently ends.
///
/// This is the movable point during a drag operation. It updates on every mouse move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectionFocus {
    /// The IFC root node ID where selection currently ends.
    /// May differ from anchor's IFC root during cross-node selection.
    pub ifc_root_node_id: NodeId,
    /// The exact cursor position within the IFC's `UnifiedLayout`.
    pub cursor: TextCursor,
    /// Current mouse position in viewport coordinates.
    pub mouse_position: LogicalPosition,
}
/// Complete selection state spanning potentially multiple DOM nodes.
///
/// This implements the W3C Selection API model with anchor/focus endpoints.
/// The selection can span multiple IFC roots (e.g., multiple `<p>` elements).
///
/// ## Storage Model
///
/// Uses `BTreeMap<NodeId, Vec<SelectionRange>>` for O(log N) lookup during rendering.
/// The key is the **IFC root `NodeId`**, and the value is every `SelectionRange`
/// that IFC contributes.
///
/// ## Example
///
/// ```text
/// <p id="1">Hello [World</p>     <- Anchor in IFC 1, partial selection
/// <p id="2">Complete line</p>    <- InBetween, fully selected
/// <p id="3">Partial] end</p>     <- Focus in IFC 3, partial selection
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextSelection {
    /// The DOM this selection belongs to.
    pub dom_id: DomId,
    /// The anchor point - where the selection started (fixed during drag).
    pub anchor: SelectionAnchor,
    /// The focus point - where the selection currently ends (moves during drag).
    pub focus: SelectionFocus,
    /// Map from IFC root `NodeId` to the `SelectionRange`s for that IFC.
    /// This allows O(log N) lookup during rendering.
    ///
    /// Each `SelectionRange` contains the actual `TextCursor` positions for that IFC,
    /// ready to be passed to `UnifiedLayout::get_selection_rects()`.
    ///
    /// A node carries SEVERAL ranges when a multi-cursor session selects several
    /// occurrences in it (Ctrl+D); the ranges are disjoint and in document order.
    pub affected_nodes: BTreeMap<NodeId, Vec<SelectionRange>>,
    /// OTHER PARTICIPANTS' ranges on the same nodes, with whose they are
    /// (U1-a).
    ///
    /// Separate from `affected_nodes` rather than mixed into it, because the
    /// two are painted differently and mean different things: that one is the
    /// LOCAL user's selection and takes the node's `::selection` colour, while
    /// these take their owner's. Mixing them made a remote participant's range
    /// look like the local user's own, which is worse than not showing it.
    ///
    /// Empty for a single-user app, which is every app until one injects a
    /// remote owner.
    pub remote_ranges: BTreeMap<NodeId, Vec<(SelectionOwner, SelectionRange)>>,
    /// Indicates whether anchor comes before focus in document order.
    /// True = forward selection (left-to-right), False = backward selection.
    pub is_forward: bool,
}
/// An edit that changed the RUN COUNT of a node's inline content (U3-a-i):
/// a delete spanning two styled runs merged them, a styled paste split one.
///
/// The runs before `first` and the runs after the changed middle are the
/// same in both generations (aligned by common prefix and suffix); a caret
/// in the middle is mapped through the concatenated middle text, a caret
/// after it keeps its byte and moves its run index by the count delta.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunRemap {
    /// The first old run index that differs.
    pub first: u32,
    /// Text lengths of the old middle runs `first ..`.
    pub old_lens: Vec<u32>,
    /// Text lengths of the new middle runs `first ..`.
    pub new_lens: Vec<u32>,
    /// The byte change between the concatenated old and new middle texts,
    /// if they differ (`run` is meaningless here).
    pub middle: Option<RunTextChange>,
    /// Length of the unchanged run just before the middle, when there is
    /// one: where a caret lands when the whole middle vanished.
    pub prev_len: Option<u32>,
}
impl RunRemap {
    /// Where a caret of the old generation sits in the new one.
    #[must_use]
    // Run counts come from `old_lens`/`new_lens`, whose elements and indices are
    // already u32; a run count past u32::MAX cannot be built in the first place.
    #[allow(clippy::cast_possible_truncation)]
94
    pub fn map_cursor(&self, c: TextCursor) -> TextCursor {
94
        let run = c.cluster_id.source_run;
94
        let first = self.first;
94
        let old_end = first + self.old_lens.len() as u32;
94
        let new_end = first + self.new_lens.len() as u32;
94
        if run < first {
12
            return c;
82
        }
82
        if run >= old_end {
27
            return TextCursor {
27
                cluster_id: GraphemeClusterId {
27
                    source_run: run - old_end + new_end,
27
                    start_byte_in_run: c.cluster_id.start_byte_in_run,
27
                },
27
                affinity: c.affinity,
27
            };
55
        }
        // In the middle: through the concatenated text.
55
        let mut global: u32 = self.old_lens[..(run - first) as usize].iter().sum();
55
        global = global.saturating_add(c.cluster_id.start_byte_in_run);
55
        if let Some(m) = &self.middle {
27
            global = m.transform(global);
28
        }
55
        let total_new: u32 = self.new_lens.iter().sum();
55
        global = global.min(total_new);
55
        if self.new_lens.is_empty() {
            // The middle vanished: the end of the run before it, or the
            // start of what follows.
1
            return match (first.checked_sub(1), self.prev_len) {
1
                (Some(prev), Some(len)) => TextCursor {
1
                    cluster_id: GraphemeClusterId {
1
                        source_run: prev,
1
                        start_byte_in_run: len,
1
                    },
1
                    affinity: c.affinity,
1
                },
                _ => TextCursor {
                    cluster_id: GraphemeClusterId {
                        source_run: first,
                        start_byte_in_run: 0,
                    },
                    affinity: c.affinity,
                },
            };
54
        }
54
        let mut offset = global;
54
        let mut target = first;
67
        for (i, len) in self.new_lens.iter().enumerate() {
67
            let last = i + 1 == self.new_lens.len();
67
            if offset <= *len || last {
54
                target = first + i as u32;
54
                break;
13
            }
13
            offset -= len;
        }
54
        TextCursor {
54
            cluster_id: GraphemeClusterId {
54
                source_run: target,
54
                start_byte_in_run: offset,
54
            },
54
            affinity: c.affinity,
54
        }
94
    }
}
/// What an edit did to a node's text, for moving carets across it (U3-a,
/// U3-a-i): a run remap when the run count changed, then byte changes
/// within runs.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RunTextDiff {
    pub remap: Option<RunRemap>,
    pub changes: Vec<RunTextChange>,
}
impl RunTextDiff {
    #[must_use]
7204
    pub const fn is_empty(&self) -> bool {
7204
        self.remap.is_none() && self.changes.is_empty()
7204
    }
    /// A caret of the old generation in the new one: the remap first, then
    /// the byte changes of its (new) run.
    #[must_use]
217
    pub fn map_cursor(&self, c: TextCursor) -> TextCursor {
217
        let mut c = self.remap.as_ref().map_or(c, |remap| remap.map_cursor(c));
349
        for change in &self.changes {
132
            if change.run == c.cluster_id.source_run {
132
                c.cluster_id.start_byte_in_run = change.transform(c.cluster_id.start_byte_in_run);
132
            }
        }
217
        c
217
    }
}
/// One contiguous change to a run's text (U3-a): bytes `start..end` of the
/// OLD text were replaced by `inserted` bytes.
///
/// The shape every caret shift is computed from, whoever made the change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RunTextChange {
    /// The run (`GraphemeClusterId::source_run`) whose text changed.
    pub run: u32,
    /// First changed byte of the old text.
    pub start: u32,
    /// One past the last changed byte of the old text (`== start` for a pure
    /// insert).
    pub end: u32,
    /// How many bytes replaced `start..end`.
    pub inserted: u32,
}
impl RunTextChange {
    /// The smallest change between two versions of one run's text: the common
    /// prefix and the common suffix are unchanged, what lies between was
    /// replaced. `None` when the texts are identical.
    ///
    /// Byte-level, then backed off to char boundaries on BOTH sides so a
    /// change never starts or ends inside a multi-byte character. When the
    /// inserted text repeats its neighbour (`aa` -> `aaa`) the position is
    /// ambiguous by nature; the prefix wins, which puts the change AFTER the
    /// existing copy - the only carets that can tell the difference sit
    /// between identical characters.
    #[must_use]
    #[allow(clippy::cast_possible_truncation)] // run text is bounded far below u32
4226
    pub fn between(run: u32, old: &str, new: &str) -> Option<Self> {
4226
        if old == new {
760
            return None;
3466
        }
3466
        let ob = old.as_bytes();
3466
        let nb = new.as_bytes();
3466
        let shorter = ob.len().min(nb.len());
3466
        let mut prefix = 0;
318597
        while prefix < shorter && ob[prefix] == nb[prefix] {
315131
            prefix += 1;
315131
        }
3467
        while prefix > 0 && !(old.is_char_boundary(prefix) && new.is_char_boundary(prefix)) {
1
            prefix -= 1;
1
        }
3466
        let mut suffix = 0;
61471
        while suffix < shorter - prefix && ob[ob.len() - 1 - suffix] == nb[nb.len() - 1 - suffix] {
58005
            suffix += 1;
58005
        }
3466
        while suffix > 0
2692
            && !(old.is_char_boundary(ob.len() - suffix) && new.is_char_boundary(nb.len() - suffix))
        {
            suffix -= 1;
        }
3466
        Some(Self {
3466
            run,
3466
            start: prefix as u32,
3466
            end: (ob.len() - suffix) as u32,
3466
            inserted: (nb.len() - prefix - suffix) as u32,
3466
        })
4226
    }
    /// Where a caret that sat at `byte` of the OLD text sits in the new one.
    ///
    /// The user's rule (2026-09-03): a caret is anchored at a LOGICAL
    /// position, so a change entirely before it shifts it by the delta, a
    /// change entirely after it leaves it alone, and a change that spans it
    /// collapses it to the change's start - the only position that still
    /// exists. A caret AT a pure insert's position counts as after it: it is
    /// attached to the character that follows, and that character moved.
    #[must_use]
171
    pub const fn transform(&self, byte: u32) -> u32 {
171
        if byte < self.start {
37
            byte
134
        } else if byte >= self.end {
93
            byte - (self.end - self.start) + self.inserted
        } else {
41
            self.start
        }
171
    }
}
impl TextSelection {
    /// Create a new collapsed selection (cursor) at the given position.
    #[must_use]
80
    pub fn new_collapsed(
80
        dom_id: DomId,
80
        ifc_root_node_id: NodeId,
80
        cursor: TextCursor,
80
        char_bounds: LogicalRect,
80
        mouse_position: LogicalPosition,
80
    ) -> Self {
80
        let anchor = SelectionAnchor {
80
            ifc_root_node_id,
80
            cursor,
80
            char_bounds,
80
            mouse_position,
80
        };
80
        let focus = SelectionFocus {
80
            ifc_root_node_id,
80
            cursor,
80
            mouse_position,
80
        };
        // For a collapsed selection, the anchor node has a zero-width range
80
        let mut affected_nodes = BTreeMap::new();
80
        affected_nodes.insert(
80
            ifc_root_node_id,
80
            vec![SelectionRange {
80
                start: cursor,
80
                end: cursor,
80
            }],
        );
80
        Self {
80
            remote_ranges: BTreeMap::new(),
80
            dom_id,
80
            anchor,
80
            focus,
80
            affected_nodes,
80
            is_forward: true, // Direction doesn't matter for collapsed selection
80
        }
80
    }
    /// Check if this is a collapsed selection (cursor with no range).
    #[must_use]
3454
    pub fn is_collapsed(&self) -> bool {
3454
        self.anchor.ifc_root_node_id == self.focus.ifc_root_node_id
659
            && self.anchor.cursor == self.focus.cursor
3454
    }
    /// Get the FIRST selection range for a specific IFC root node.
    /// Returns `None` if this node is not part of the selection.
    ///
    /// A multi-range node has more; [`Self::ranges_for_node`] returns all of them.
    #[must_use]
80
    pub fn get_range_for_node(&self, ifc_root_node_id: &NodeId) -> Option<&SelectionRange> {
80
        self.affected_nodes
80
            .get(ifc_root_node_id)
80
            .and_then(|r| r.first())
80
    }
    /// Every range this IFC root contributes (empty slice when unaffected).
    #[must_use]
111
    pub fn ranges_for_node(&self, ifc_root_node_id: &NodeId) -> &[SelectionRange] {
111
        self.affected_nodes
111
            .get(ifc_root_node_id)
111
            .map_or(&[], Vec::as_slice)
111
    }
}
impl_option!(
    TextSelection,
    OptionTextSelection,
    copy = false,
    clone = false,
    [Debug, Clone, PartialEq, Eq]
);
// ============================================================================
// App-facing document coordinates (the CallbackInfo selection/sync API)
// ============================================================================
/// A position in a node's TEXT CONTENT, app-facing: `text_byte` indexes the
/// flattened text of `node`.
///
/// It is the exact string `CallbackInfo::get_node_text_content(node)` returns
/// (overlay-first, so it sees uncommitted typing). The engine resolves cluster
/// ids and affinity
/// BEFORE handing this out: the byte always lies on a grapheme-cluster
/// boundary of that string (a ZWJ emoji family or a decomposed `é` is never
/// split), and is in LOGICAL order — bidi visual reordering does not affect
/// it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct DocumentPosition {
    pub node: DomNodeId,
    pub text_byte: u32,
}
impl_option!(
    DocumentPosition,
    OptionDocumentPosition,
    [Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord]
);
/// A selected byte span `[start_byte, end_byte)` of `node`'s text content,
/// in the coordinates of [`DocumentPosition`].
///
/// Always LOGICAL and NORMALIZED: `start_byte <= end_byte` regardless of drag
/// direction or
/// script direction (an RTL selection is still a forward byte span). A
/// cross-block selection yields one span per affected node, in document
/// order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct DocumentSelectionSpan {
    pub node: DomNodeId,
    pub start_byte: u32,
    pub end_byte: u32,
}
impl_option!(
    DocumentSelectionSpan,
    OptionDocumentSelectionSpan,
    [Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord]
);
impl_vec!(
    DocumentSelectionSpan,
    DocumentSelectionSpanVec,
    DocumentSelectionSpanVecDestructor,
    DocumentSelectionSpanVecDestructorType,
    DocumentSelectionSpanVecSlice,
    OptionDocumentSelectionSpan
);
impl_vec_debug!(DocumentSelectionSpan, DocumentSelectionSpanVec);
impl_vec_clone!(
    DocumentSelectionSpan,
    DocumentSelectionSpanVec,
    DocumentSelectionSpanVecDestructor
);
impl_vec_partialeq!(DocumentSelectionSpan, DocumentSelectionSpanVec);
impl_vec_partialord!(DocumentSelectionSpan, DocumentSelectionSpanVec);
/// One un-synced character-level edit: `node`'s effective text is now
/// `text` (revision-stamped).
///
/// The app folds it into its model and acks the highest revision it saw via
/// `CallbackInfo::mark_text_revision_synced` — the character-path counterpart
/// of the structural `DocumentEdit` loop.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct DocumentTextEdit {
    pub node: DomNodeId,
    pub text: azul_css::corety::AzString,
    pub revision: u64,
}
impl_option!(
    DocumentTextEdit,
    OptionDocumentTextEdit,
    copy = false,
    [Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord]
);
impl_vec!(
    DocumentTextEdit,
    DocumentTextEditVec,
    DocumentTextEditVecDestructor,
    DocumentTextEditVecDestructorType,
    DocumentTextEditVecSlice,
    OptionDocumentTextEdit
);
impl_vec_debug!(DocumentTextEdit, DocumentTextEditVec);
impl_vec_clone!(
    DocumentTextEdit,
    DocumentTextEditVec,
    DocumentTextEditVecDestructor
);
impl_vec_partialeq!(DocumentTextEdit, DocumentTextEditVec);
impl_vec_partialord!(DocumentTextEdit, DocumentTextEditVec);
#[cfg(test)]
#[path = "selection_test.rs"]
mod selection_test;