Skip to main content

ferrokit_core/
text.rs

1//! A real `NSTextView` (in its `NSScrollView`) as a text editor, plain or rich.
2//!
3//! What AppKit brings: IME with the candidate window at the caret, spell and
4//! grammar checking with the suggestion menu, the find bar, undo, text
5//! services (Look Up, Translate, Writing Tools), Dark Mode and VoiceOver.
6//!
7//! Offsets in this API are UTF-8 byte offsets into the text, as Rust strings
8//! use; they're converted from AppKit's UTF-16 ranges at the boundary.
9//! Like [`crate::table::TableModel`], user actions are queued on the model
10//! and announced with [`crate::request_redraw`].
11//!
12//! Styled text: [`TextModel::set_highlighter`] colours and emphasises runs
13//! of the text (syntax highlighting, search matches), re-run on every edit
14//! before it's drawn. The text stays plain: styles aren't typed, pasted,
15//! copied or undone.
16//!
17//! Rich text: [`TextModel::set_rich`] lets the user style the text
18//! themselves (fonts, bold, colours, alignment, lists, pictures), with the
19//! font panel, the ruler and the format bar; [`TextModel::rtf`] and
20//! [`TextModel::html`] read it out, [`TextModel::set_rtf`] and
21//! [`TextModel::set_html`] load it.
22
23use std::cell::{Cell, RefCell};
24use std::collections::VecDeque;
25use std::ops::Range;
26use std::rc::{Rc, Weak};
27
28use objc2::rc::Retained;
29use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
30use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send};
31use objc2_app_kit::{
32    NSColor, NSFont, NSResponder, NSScrollView, NSText, NSTextDelegate, NSTextInputClient, NSTextStorage, NSTextStorageDelegate,
33    NSTextStorageEditActions, NSTextView, NSTextViewDelegate, NSAutoresizingMaskOptions, NSView,
34};
35use objc2_foundation::{NSNotification, NSPoint, NSRange, NSRect, NSSize, NSString, NSUndoManager};
36
37use crate::ViewId;
38use crate::host::mtm;
39
40/// Something the user did in the editor.
41#[derive(Debug, Clone, PartialEq)]
42pub enum TextEvent {
43    /// The text changed (typing, paste, undo, a committed IME composition…).
44    /// Read it with [`TextModel::text`]. Not sent while composing.
45    Changed,
46    /// The selection or caret moved (byte range).
47    Selection(Range<usize>),
48    /// An input method is composing (`Some(marked text)`), or stopped (`None`).
49    Composition(Option<String>),
50}
51
52trait Data {
53    fn push(&self, event: TextEvent);
54    fn quiet(&self) -> bool;
55    fn composing(&self) -> bool;
56    fn undo_manager(&self) -> Retained<NSUndoManager>;
57    /// Restyles; inside an edit (`edited`), true when the rest of the
58    /// region is left for [`Data::finish_highlight`] just after it.
59    fn highlight(&self, edited: Option<NSRange>) -> bool;
60    fn finish_highlight(&self);
61}
62
63struct ViewIvars {
64    data: RefCell<Option<Weak<dyn Data>>>,
65    composing: Cell<bool>,
66}
67
68define_class!(
69    // NSTextView that reports input-method composition.
70    #[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
71    #[thread_kind = MainThreadOnly]
72    #[name = "FerrokitCoreTextView"]
73    #[ivars = ViewIvars]
74    struct HostTextView;
75
76    impl HostTextView {
77        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
78        fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
79            let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
80            self.composition_changed();
81        }
82
83        #[unsafe(method(unmarkText))]
84        fn unmark_text(&self) {
85            let () = unsafe { msg_send![super(self), unmarkText] };
86            self.composition_changed();
87        }
88
89        #[unsafe(method(insertText:replacementRange:))]
90        fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
91            let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
92            self.composition_changed();
93        }
94    }
95);
96
97impl HostTextView {
98    fn data(&self) -> Option<Rc<dyn Data>> {
99        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
100    }
101
102    /// Emits `Composition` when marked text appears, changes or goes away.
103    fn composition_changed(&self) {
104        let composing = self.hasMarkedText();
105        let was = self.ivars().composing.replace(composing);
106        let Some(data) = self.data() else { return };
107        if composing {
108            let range = self.markedRange();
109            let marked = self.string().to_string();
110            let marked = utf16_slice(&marked, range.location, range.length);
111            data.push(TextEvent::Composition(Some(marked)));
112        } else if was {
113            data.push(TextEvent::Composition(None));
114        }
115    }
116}
117
118struct DelegateIvars {
119    data: RefCell<Option<Weak<dyn Data>>>,
120}
121
122define_class!(
123    #[unsafe(super(NSObject))]
124    #[thread_kind = MainThreadOnly]
125    #[name = "FerrokitCoreTextDelegate"]
126    #[ivars = DelegateIvars]
127    struct Delegate;
128
129    unsafe impl NSObjectProtocol for Delegate {}
130
131    unsafe impl NSTextDelegate for Delegate {
132        #[unsafe(method(textDidChange:))]
133        fn text_did_change(&self, _notification: &NSNotification) {
134            let Some(data) = self.data() else { return };
135            // The edit is done and the caret placed: style the rest of what
136            // it changed now (edits without this message, such as undo, get
137            // it from the run loop).
138            data.finish_highlight();
139            if !data.quiet() {
140                data.push(TextEvent::Changed);
141            }
142        }
143    }
144
145    // Every character edit, including undo and redo (for which AppKit sends
146    // no textDidChange:), reaches the text storage.
147    unsafe impl NSTextStorageDelegate for Delegate {
148        // Restyling happens here, inside the edit, so new text never shows
149        // in the previous run's style. Changing attributes after the edit
150        // (in didProcessEditing, in an edit of its own) left TextKit 2's
151        // layout behind the text: typed text didn't show, and the next
152        // redraw read past the end of the string and aborted.
153        #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
154        fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
155            if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
156                return;
157            }
158            let Some(data) = self.data().filter(|d| !d.composing()) else { return };
159            if data.highlight(Some(range)) {
160                // Just after the edit, before the run loop draws, unless
161                // textDidChange: comes first.
162                let weak = self.ivars().data.borrow().clone();
163                let block = block2::RcBlock::new(move || {
164                    if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
165                        objc2::rc::autoreleasepool(|_| d.finish_highlight());
166                    }
167                });
168                let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
169                // SAFETY: the main run loop; the block touches main-thread state only.
170                unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
171                main.wake_up();
172            }
173        }
174
175        #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
176        fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
177            if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
178                return;
179            }
180            let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
181            data.push(TextEvent::Changed);
182        }
183    }
184
185    unsafe impl NSTextViewDelegate for Delegate {
186        #[unsafe(method(textViewDidChangeSelection:))]
187        fn selection_did_change(&self, notification: &NSNotification) {
188            let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
189            let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
190            let text = view.string().to_string();
191            let r = view.selectedRange();
192            data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
193        }
194
195        // Each editor keeps its own undo history, instead of sharing the
196        // window's (where ⌘Z in one view could undo another view's edit).
197        #[unsafe(method_id(undoManagerForTextView:))]
198        fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
199            self.data().map(|d| d.undo_manager())
200        }
201    }
202);
203
204impl Delegate {
205    fn data(&self) -> Option<Rc<dyn Data>> {
206        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
207    }
208}
209
210/// UTF-16 range → UTF-8 byte range in `text` (clamped).
211pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
212    let (mut units, mut start, mut end) = (0usize, None, None);
213    for (byte, c) in text.char_indices() {
214        if start.is_none() && units >= location {
215            start = Some(byte);
216        }
217        if end.is_none() && units >= location + length {
218            end = Some(byte);
219        }
220        units += c.len_utf16();
221    }
222    let start = start.unwrap_or(text.len());
223    start..end.unwrap_or(text.len()).max(start)
224}
225
226/// UTF-8 byte range → UTF-16 range (location, length). Bytes inside a
227/// character round down to its start.
228pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
229    let to_units = |byte: usize| -> usize {
230        let byte = byte.min(text.len());
231        let mut b = byte;
232        while !text.is_char_boundary(b) {
233            b -= 1;
234        }
235        text[..b].encode_utf16().count()
236    };
237    let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
238    (s, e - s)
239}
240
241fn utf16_slice(text: &str, location: usize, length: usize) -> String {
242    text[utf16_to_bytes(text, location, length)].to_string()
243}
244
245struct Inner {
246    id: ViewId,
247    events: RefCell<VecDeque<TextEvent>>,
248    quiet: Cell<bool>,
249    mounted: Cell<bool>,
250    undo: RefCell<Retained<NSUndoManager>>,
251    /// Whether `undo` is someone else's (shared with other views).
252    shared: Cell<bool>,
253    scroll: Retained<NSScrollView>,
254    view: Retained<HostTextView>,
255    _delegate: Retained<Delegate>,
256    /// The font unstyled text uses (`set_font`).
257    font: RefCell<Retained<NSFont>>,
258    highlighter: RefCell<Option<Rc<Highlighter>>>,
259    /// Set while styles are applied (they re-enter the storage delegate).
260    styling: Cell<bool>,
261    /// The runs last applied and the text's length then, to restyle only
262    /// what an edit changed.
263    shown: RefCell<Option<(usize, Runs)>>,
264    /// The UTF-16 span an edit left to restyle just after it.
265    deferred: Cell<Option<(usize, usize)>>,
266}
267
268type Highlighter = dyn Fn(&str) -> Runs;
269type Runs = Vec<(Range<usize>, TextStyle)>;
270
271/// A colour: for text, backgrounds, borders, drawing. The named ones are the
272/// system's colours: they follow Dark Mode, Increase Contrast and the user's
273/// accent colour.
274#[derive(Debug, Clone, Copy, PartialEq)]
275pub enum Color {
276    /// The text colour (what unstyled text uses).
277    Primary,
278    /// Less prominent text.
279    Secondary,
280    /// Even less prominent text (comments, placeholders).
281    Tertiary,
282    /// The least prominent text and fills.
283    Quaternary,
284    /// The system's fill for thin shapes (a slider's track, a progress
285    /// ring's track): the strongest of the fills, a translucent grey.
286    Fill,
287    /// A fill for medium shapes (a switch's background).
288    SecondaryFill,
289    /// A fill for large shapes (an input field, a search bar).
290    TertiaryFill,
291    /// A fill for large areas with content on them: grouped cards, as
292    /// SwiftUI's `GroupBox` and grouped forms draw them.
293    QuaternaryFill,
294    /// The user's accent colour (System Settings › Appearance).
295    Accent,
296    /// Links.
297    Link,
298    /// System red.
299    Red,
300    /// System orange.
301    Orange,
302    /// System yellow.
303    Yellow,
304    /// System green.
305    Green,
306    /// System mint.
307    Mint,
308    /// System teal.
309    Teal,
310    /// System cyan.
311    Cyan,
312    /// System blue.
313    Blue,
314    /// System indigo.
315    Indigo,
316    /// System purple.
317    Purple,
318    /// System pink.
319    Pink,
320    /// System brown.
321    Brown,
322    /// System gray.
323    Gray,
324    /// The background of content (text, tables): white, or dark in Dark Mode.
325    Background,
326    /// The window's background (behind content).
327    WindowBackground,
328    /// The background of controls and grouped content: cards, panels.
329    ControlBackground,
330    /// Separator lines and grids.
331    Separator,
332    /// Fully transparent.
333    Clear,
334    /// A fixed sRGB colour (components 0–1; the same in light and dark).
335    Rgb(f64, f64, f64),
336    /// A fixed sRGB colour with opacity (components 0–1).
337    Rgba(f64, f64, f64, f64),
338}
339
340impl Color {
341    const NAMED: [Color; 28] = [
342        Color::Primary,
343        Color::Secondary,
344        Color::Tertiary,
345        Color::Quaternary,
346        Color::Fill,
347        Color::SecondaryFill,
348        Color::TertiaryFill,
349        Color::QuaternaryFill,
350        Color::Accent,
351        Color::Link,
352        Color::Red,
353        Color::Orange,
354        Color::Yellow,
355        Color::Green,
356        Color::Mint,
357        Color::Teal,
358        Color::Cyan,
359        Color::Blue,
360        Color::Indigo,
361        Color::Purple,
362        Color::Pink,
363        Color::Brown,
364        Color::Gray,
365        Color::Background,
366        Color::WindowBackground,
367        Color::ControlBackground,
368        Color::Separator,
369        Color::Clear,
370    ];
371
372    /// An opaque sRGB colour (components 0–1).
373    pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
374        Color::Rgb(r, g, b)
375    }
376
377    /// An sRGB colour with opacity (components 0–1).
378    pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
379        Color::Rgba(r, g, b, a)
380    }
381
382    /// A colour from a hex string: `"#3a7bd5"`, `"3a7bd5"`, or with opacity
383    /// `"#3a7bd580"`. Black for anything else.
384    pub fn hex(hex: &str) -> Color {
385        let h = hex.trim_start_matches('#');
386        let byte = |i: usize| h.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).map_or(0.0, |b| f64::from(b) / 255.0);
387        match h.len() {
388            8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
389            6 => Color::Rgb(byte(0), byte(2), byte(4)),
390            _ => Color::Rgb(0.0, 0.0, 0.0),
391        }
392    }
393
394    /// The same colour at `opacity` (0–1), on top of its own.
395    pub fn opacity(self, opacity: f64) -> Color {
396        match self.components() {
397            Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
398            None => self,
399        }
400    }
401
402    /// Its sRGB components (red, green, blue, opacity), resolved for the
403    /// current appearance for the named colours.
404    pub fn components(self) -> Option<(f64, f64, f64, f64)> {
405        match self {
406            Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
407            Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
408            _ => {
409                let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
410                Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
411            }
412        }
413    }
414
415    /// The `NSColor` (dynamic for the named colours).
416    pub fn ns(self) -> Retained<NSColor> {
417        match self {
418            Color::Primary => NSColor::textColor(),
419            Color::Secondary => NSColor::secondaryLabelColor(),
420            Color::Tertiary => NSColor::tertiaryLabelColor(),
421            Color::Quaternary => NSColor::quaternaryLabelColor(),
422            Color::Fill => NSColor::systemFillColor(),
423            Color::SecondaryFill => NSColor::secondarySystemFillColor(),
424            Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
425            Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
426            Color::Accent => NSColor::controlAccentColor(),
427            Color::Link => NSColor::linkColor(),
428            Color::Red => NSColor::systemRedColor(),
429            Color::Orange => NSColor::systemOrangeColor(),
430            Color::Yellow => NSColor::systemYellowColor(),
431            Color::Green => NSColor::systemGreenColor(),
432            Color::Mint => NSColor::systemMintColor(),
433            Color::Teal => NSColor::systemTealColor(),
434            Color::Cyan => NSColor::systemCyanColor(),
435            Color::Blue => NSColor::systemBlueColor(),
436            Color::Indigo => NSColor::systemIndigoColor(),
437            Color::Purple => NSColor::systemPurpleColor(),
438            Color::Pink => NSColor::systemPinkColor(),
439            Color::Brown => NSColor::systemBrownColor(),
440            Color::Gray => NSColor::systemGrayColor(),
441            Color::Background => NSColor::textBackgroundColor(),
442            Color::WindowBackground => NSColor::windowBackgroundColor(),
443            Color::ControlBackground => NSColor::controlBackgroundColor(),
444            Color::Separator => NSColor::separatorColor(),
445            Color::Clear => NSColor::clearColor(),
446            Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
447            Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
448        }
449    }
450
451    /// The colour an `NSColor` is: a named one if it's one of those, else
452    /// its sRGB components.
453    pub fn from_ns(color: &NSColor) -> Option<Color> {
454        Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
455            let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
456            let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
457            Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
458        })
459    }
460}
461
462/// How a run of text looks. What it leaves unset stays as the editor's own
463/// (its font and text colour).
464#[derive(Debug, Clone, Copy, Default, PartialEq)]
465pub struct TextStyle {
466    /// The text colour.
467    pub color: Option<Color>,
468    /// A background behind the run.
469    pub background: Option<Color>,
470    /// Bold (the font's bold face).
471    pub bold: bool,
472    /// Italic (the font's italic face, where it has one).
473    pub italic: bool,
474    /// Underlined.
475    pub underline: bool,
476}
477
478impl TextStyle {
479    /// A style that changes nothing.
480    pub fn new() -> Self {
481        Self::default()
482    }
483
484    /// With this text colour.
485    pub fn color(mut self, color: Color) -> Self {
486        self.color = Some(color);
487        self
488    }
489
490    /// With this background.
491    pub fn background(mut self, color: Color) -> Self {
492        self.background = Some(color);
493        self
494    }
495
496    /// Bold.
497    pub fn bold(mut self) -> Self {
498        self.bold = true;
499        self
500    }
501
502    /// Italic.
503    pub fn italic(mut self) -> Self {
504        self.italic = true;
505        self
506    }
507
508    /// Underlined.
509    pub fn underline(mut self) -> Self {
510        self.underline = true;
511        self
512    }
513}
514
515/// UTF-16 offsets of every byte offset of `text` (inside a character: that
516/// character's start), plus the end.
517fn utf16_map(text: &str) -> Vec<usize> {
518    let mut map = Vec::with_capacity(text.len() + 1);
519    let mut units = 0;
520    for c in text.chars() {
521        map.extend(std::iter::repeat_n(units, c.len_utf8()));
522        units += c.len_utf16();
523    }
524    map.push(units);
525    map
526}
527
528impl Inner {
529    /// Styles the text with `runs`: what differs from the runs shown before
530    /// (and the `edited` UTF-16 range) is reset to the editor's font and
531    /// colour, then given its runs' styles. `None` restyles everything.
532    /// With an `edited` range it runs inside the storage's own edit
533    /// (willProcessEditing), so it opens no edit of its own; `only` limits
534    /// a restyle outside an edit to a UTF-16 span. True when part of an
535    /// edit's span was newly left for just after it.
536    fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
537        // SAFETY: the text view's own storage, on the main thread.
538        let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
539        let text = storage.string().to_string();
540        let map = utf16_map(&text);
541        let len16 = *map.last().unwrap_or(&0);
542        let shown = self.shown.borrow_mut().take();
543        // The span whose runs changed: runs equal before it (a prefix) and,
544        // shifted by the edit, after it (a suffix) keep their styles.
545        let region = match (shown, edited) {
546            (Some((old_len, old)), Some(edited)) => {
547                let delta = text.len() as isize - old_len as isize;
548                let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
549                let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
550                let suffix = old[prefix..]
551                    .iter()
552                    .rev()
553                    .zip(runs[prefix..].iter().rev())
554                    .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
555                    .count();
556                let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
557                let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
558                let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
559                lo..hi
560            }
561            _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
562        };
563        // Inside an edit only the edited characters are styled: attributes
564        // changed past them widen the storage's edited range, and the text
565        // view puts the caret at its end (typing mid-line jumped to the next
566        // run). The rest of the span is restyled just after the edit (all
567        // of the text if an earlier edit's span is still waiting).
568        let mut deferred = false;
569        let region = match edited {
570            Some(e) => {
571                let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
572                if inside != region {
573                    deferred = self.deferred.get().is_none();
574                    self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
575                }
576                inside.start..inside.end.max(inside.start)
577            }
578            None => region,
579        };
580        let font = self.font.borrow().clone();
581        self.styling.set(true);
582        // SAFETY: attribute keys and values of the documented types (fonts,
583        // colours, an NSNumber for the underline style), in range.
584        unsafe {
585            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
586            if edited.is_none() {
587                storage.beginEditing();
588            }
589            let base = objc2_foundation::NSDictionary::from_retained_objects(
590                &[NSFontAttributeName, NSForegroundColorAttributeName],
591                &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
592            );
593            storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
594            let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
595            for (range, style) in &runs {
596                let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
597                if start >= end {
598                    continue;
599                }
600                let r = NSRange::new(start, end - start);
601                if let Some(c) = style.color {
602                    storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
603                }
604                if let Some(c) = style.background {
605                    storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
606                }
607                if style.bold || style.italic {
608                    let mut f = font.clone();
609                    if style.bold {
610                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
611                    }
612                    if style.italic {
613                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
614                    }
615                    storage.addAttribute_value_range(NSFontAttributeName, &f, r);
616                }
617                if style.underline {
618                    storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
619                }
620            }
621            if edited.is_none() {
622                storage.endEditing();
623            }
624        }
625        self.styling.set(false);
626        *self.shown.borrow_mut() = Some((text.len(), runs));
627        // What's typed next starts plain (the highlighter restyles it).
628        // Not during an edit: the text view still has the selection from
629        // before it, and setting typing attributes reads the attributes
630        // there, past the end of shorter text (an NSRangeException that
631        // stopped the edit halfway and left TextKit 2's layout behind the
632        // text). After an edit the text view takes them from the text
633        // around the caret, which is already styled.
634        if edited.is_some() {
635            return deferred;
636        }
637        // SAFETY: a dictionary of standard attributes.
638        unsafe {
639            use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
640            let typing = objc2_foundation::NSDictionary::from_retained_objects(
641                &[NSFontAttributeName, NSForegroundColorAttributeName],
642                &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
643            );
644            self.view.setTypingAttributes(&typing);
645        }
646        false
647    }
648}
649
650impl Data for Inner {
651    fn push(&self, event: TextEvent) {
652        let mut events = self.events.borrow_mut();
653        // `Changed` means "read the text again": one queued is enough (an
654        // edit is reported by both the text storage and textDidChange:).
655        if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
656            return;
657        }
658        // Keep only the latest of a run of selection moves.
659        if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
660            events.pop_back();
661        }
662        events.push_back(event);
663        drop(events);
664        crate::request_redraw();
665    }
666
667    fn quiet(&self) -> bool {
668        self.quiet.get()
669    }
670
671    fn composing(&self) -> bool {
672        self.view.hasMarkedText()
673    }
674
675    fn undo_manager(&self) -> Retained<NSUndoManager> {
676        self.undo.borrow().clone()
677    }
678
679    fn highlight(&self, edited: Option<NSRange>) -> bool {
680        if self.styling.get() {
681            return false;
682        }
683        let Some(f) = self.highlighter.borrow().clone() else { return false };
684        let runs = f(&self.view.string().to_string());
685        self.apply_styles(runs, edited, None)
686    }
687
688    fn finish_highlight(&self) {
689        let Some(span) = self.deferred.take() else { return };
690        if self.styling.get() || self.view.hasMarkedText() {
691            return;
692        }
693        let Some(f) = self.highlighter.borrow().clone() else { return };
694        let runs = f(&self.view.string().to_string());
695        self.apply_styles(runs, None, Some(span));
696    }
697}
698
699impl Drop for ViewIvars {
700    fn drop(&mut self) {
701        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
702    }
703}
704
705impl Drop for DelegateIvars {
706    fn drop(&mut self) {
707        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
708    }
709}
710
711impl Drop for Inner {
712    fn drop(&mut self) {
713        // The text view and its storage hold the delegate weakly: detach it first.
714        self.view.setDelegate(None);
715        if let Some(storage) = unsafe { self.view.textStorage() } {
716            storage.setDelegate(None);
717        }
718        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
719        crate::keys::set_accepts_tab(self.id, false);
720        if self.mounted.get() {
721            crate::unmount(self.id);
722        }
723    }
724}
725
726/// A native plain-text editor. Cheap to clone (a handle); main thread only.
727#[derive(Clone)]
728pub struct TextModel {
729    inner: Rc<Inner>,
730}
731
732impl std::fmt::Debug for TextModel {
733    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
734        write!(f, "TextModel({:?})", self.inner.id)
735    }
736}
737
738impl TextModel {
739    /// Creates the editor (added to the window the first time the host draws
740    /// it). Defaults: plain text, system font 13 pt, continuous spell
741    /// checking, find bar, undo, Tab inserts a tab (Ctrl-Tab moves focus on).
742    pub fn new(id: ViewId, text: &str) -> Self {
743        let mtm = mtm();
744        let size = NSSize::new(400.0, 300.0);
745        let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
746        scroll.setHasVerticalScroller(true);
747        scroll.setAutohidesScrollers(true);
748        scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
749
750        // The standard recipe for a text view in a scroll view: width tracks
751        // the scroll view, height grows with the text.
752        crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
753        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
754        let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
755        let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
756        view.setMinSize(NSSize::new(0.0, size.height));
757        view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
758        view.setVerticallyResizable(true);
759        view.setHorizontallyResizable(false);
760        view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
761        // SAFETY: the text view's own container.
762        if let Some(container) = unsafe { view.textContainer() } {
763            container.setContainerSize(NSSize::new(size.width, f64::MAX));
764            container.setWidthTracksTextView(true);
765        }
766        view.setRichText(false);
767        view.setImportsGraphics(false);
768        view.setAllowsUndo(true);
769        view.setUsesFindBar(true);
770        view.setContinuousSpellCheckingEnabled(true);
771        view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
772        view.setTextContainerInset(NSSize::new(4.0, 6.0));
773        view.setString(&NSString::from_str(text));
774        scroll.setDocumentView(Some(&view));
775
776        let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
777        let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
778
779        let inner = Rc::new(Inner {
780            id,
781            events: RefCell::new(VecDeque::new()),
782            quiet: Cell::new(false),
783            mounted: Cell::new(false),
784            undo: RefCell::new(NSUndoManager::new(mtm)),
785            shared: Cell::new(false),
786            scroll,
787            view: view.clone(),
788            _delegate: delegate.clone(),
789            font: RefCell::new(NSFont::systemFontOfSize(13.0)),
790            highlighter: RefCell::new(None),
791            styling: Cell::new(false),
792            shown: RefCell::new(None),
793            deferred: Cell::new(None),
794        });
795        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
796        *view.ivars().data.borrow_mut() = Some(weak.clone());
797        *delegate.ivars().data.borrow_mut() = Some(weak);
798        // SAFETY: the delegate lives as long as the model, which removes the view.
799        view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
800        if let Some(storage) = unsafe { view.textStorage() } {
801            // Weak in AppKit, like the view's delegate; detached in Drop.
802            storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
803        }
804        crate::keys::set_accepts_tab(id, true);
805        Self { inner }
806    }
807
808    /// The view id the editor was created with.
809    pub fn id(&self) -> ViewId {
810        self.inner.id
811    }
812
813    /// Adds the editor to the attached window if it isn't yet (the host
814    /// widget calls this before placing it).
815    pub fn ensure_mounted(&self) {
816        if !self.inner.mounted.get() && crate::is_attached() {
817            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
818            self.inner.mounted.set(true);
819        }
820    }
821
822    /// The whole text.
823    pub fn text(&self) -> String {
824        self.inner.view.string().to_string()
825    }
826
827    /// Replaces the whole text (e.g. loading a document). Clears the undo
828    /// history and emits no event.
829    pub fn set_text(&self, text: &str) {
830        self.inner.quiet.set(true);
831        self.inner.view.setString(&NSString::from_str(text));
832        self.inner.quiet.set(false);
833        self.clear_undo();
834    }
835
836    /// Removes this editor's edits from its undo history (only this
837    /// editor's, when the history is shared).
838    fn clear_undo(&self) {
839        let undo = self.inner.undo.borrow();
840        if self.inner.shared.get() {
841            // AppKit registers typing with the text storage as the target.
842            unsafe {
843                undo.removeAllActionsWithTarget(&self.inner.view);
844                if let Some(storage) = self.inner.view.textStorage() {
845                    undo.removeAllActionsWithTarget(&storage);
846                }
847            }
848        } else {
849            undo.removeAllActions();
850        }
851    }
852
853    /// Records edits in `manager` (e.g. the window's, shared with other
854    /// views and app-level changes) instead of the editor's own history, or
855    /// in a fresh history of its own again with `None`. Edits recorded so
856    /// far are dropped.
857    pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
858        self.clear_undo();
859        let mtm = MainThreadMarker::from(&*self.inner.view);
860        let next = match manager {
861            Some(m) => m.retain(),
862            None => NSUndoManager::new(mtm),
863        };
864        *self.inner.undo.borrow_mut() = next;
865        self.inner.shared.set(manager.is_some());
866    }
867
868    /// The undo history the editor records in.
869    pub fn undo_manager(&self) -> Retained<NSUndoManager> {
870        self.inner.undo.borrow().clone()
871    }
872
873    /// Replaces the selection as if typed: undoable, emits `Changed`.
874    pub fn replace_selection(&self, text: &str) {
875        let view = &self.inner.view;
876        let range = view.selectedRange();
877        let string = NSString::from_str(text);
878        if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
879            view.replaceCharactersInRange_withString(range, &string);
880            view.didChangeText();
881        }
882    }
883
884    /// Selected byte range (empty: the caret).
885    pub fn selection(&self) -> Range<usize> {
886        let r = self.inner.view.selectedRange();
887        utf16_to_bytes(&self.text(), r.location, r.length)
888    }
889
890    /// Selects a byte range (emits no event).
891    pub fn set_selection(&self, range: Range<usize>) {
892        let (location, length) = bytes_to_utf16(&self.text(), range);
893        self.inner.quiet.set(true);
894        self.inner.view.setSelectedRange(NSRange::new(location, length));
895        self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
896        self.inner.quiet.set(false);
897    }
898
899    /// Whether an input method is composing, and its marked text.
900    pub fn composition(&self) -> Option<String> {
901        let view = &self.inner.view;
902        view.hasMarkedText().then(|| {
903            let r = view.markedRange();
904            utf16_slice(&view.string().to_string(), r.location, r.length)
905        })
906    }
907
908    /// Read-only (`false`) or editable. Read-only text can still be selected and copied.
909    pub fn set_editable(&self, editable: bool) {
910        self.inner.view.setEditable(editable);
911    }
912
913    /// Whether the user can edit the text.
914    pub fn is_editable(&self) -> bool {
915        self.inner.view.isEditable()
916    }
917
918    /// Font: `None` for the system font, else a family or PostScript name.
919    pub fn set_font(&self, name: Option<&str>, size: f64) {
920        let font = match name {
921            Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
922            None => Some(NSFont::systemFontOfSize(size)),
923        };
924        if let Some(font) = font {
925            self.inner.view.setFont(Some(&font));
926            *self.inner.font.borrow_mut() = font;
927            self.inner.highlight(None);
928        }
929    }
930
931    /// Styles the text with `f`: given the text, it returns runs (UTF-8
932    /// byte ranges) and their styles; the rest is plain. It runs now and
933    /// after every edit (typing, paste, undo, `set_text`), before the edit
934    /// is drawn, so keep it fast: it sees the whole text each time. `None`
935    /// makes the text plain again.
936    pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
937        *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
938        self.restyle();
939    }
940
941    /// Runs the highlighter again, for when what it depends on changed
942    /// other than the text (a search term, a theme).
943    pub fn restyle(&self) {
944        if self.inner.highlighter.borrow().is_some() {
945            self.inner.highlight(None);
946        } else {
947            self.inner.apply_styles(Vec::new(), None, None);
948        }
949    }
950
951    /// The style of the character at byte `offset`, as shown (for checks).
952    pub fn style_at(&self, offset: usize) -> TextStyle {
953        // SAFETY: the text view's own storage, on the main thread.
954        let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
955        let text = storage.string().to_string();
956        let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
957        let mut style = TextStyle::default();
958        // SAFETY: reading standard attributes at an index inside the text.
959        unsafe {
960            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
961            let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
962            style.color = at(NSForegroundColorAttributeName)
963                .and_then(|c| c.downcast::<NSColor>().ok())
964                .and_then(|c| Color::from_ns(&c))
965                .filter(|c| *c != Color::Primary);
966            style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
967            if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
968                let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
969                style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
970                style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
971            }
972            style.underline = at(NSUnderlineStyleAttributeName)
973                .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
974                .is_some_and(|n| n.integerValue() != 0);
975        }
976        style
977    }
978
979    /// Rich text (`true`) or plain (`false`, the default). Rich, the user
980    /// styles the text: fonts and sizes (the font panel, ⌘T), bold, italic
981    /// and underline (⌘B, ⌘I, ⌘U), colours, alignment, spacing and lists
982    /// (the ruler and the format bar); pasted text keeps its styles, and
983    /// pictures can be pasted or dropped in. Don't combine it with a
984    /// highlighter, which restyles the text itself.
985    pub fn set_rich(&self, rich: bool) {
986        let v = &self.inner.view;
987        v.setRichText(rich);
988        v.setImportsGraphics(rich);
989        v.setUsesFontPanel(rich);
990        v.setUsesRuler(rich);
991        if !rich {
992            v.setUsesInspectorBar(false);
993            v.setRulerVisible(false);
994        }
995    }
996
997    /// Whether the text is rich (see [`set_rich`](Self::set_rich)).
998    pub fn is_rich(&self) -> bool {
999        self.inner.view.isRichText()
1000    }
1001
1002    /// TextEdit's format bar above the text (rich text): font, size,
1003    /// colours, bold, italic, underline, alignment, line spacing and lists.
1004    pub fn set_format_bar(&self, shown: bool) {
1005        self.inner.view.setUsesInspectorBar(shown);
1006    }
1007
1008    /// Whether the format bar is shown.
1009    pub fn has_format_bar(&self) -> bool {
1010        self.inner.view.usesInspectorBar()
1011    }
1012
1013    /// The ruler above the text (rich text): margins, tab stops,
1014    /// alignment, spacing and lists. Format ▸ Text ▸ Show Ruler (⌃⌘R)
1015    /// toggles it too.
1016    pub fn set_ruler_visible(&self, shown: bool) {
1017        self.inner.view.setRulerVisible(shown);
1018    }
1019
1020    /// Whether the ruler is shown.
1021    pub fn is_ruler_visible(&self) -> bool {
1022        self.inner.view.isRulerVisible()
1023    }
1024
1025    fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1026        // SAFETY: the text view's own storage, on the main thread.
1027        let storage = unsafe { self.inner.view.textStorage() }?;
1028        let len = storage.length();
1029        Some((storage, NSRange::new(0, len)))
1030    }
1031
1032    /// The text with its styles, as RTF (what TextEdit saves). Pictures
1033    /// aren't included.
1034    pub fn rtf(&self) -> Vec<u8> {
1035        let Some((storage, range)) = self.whole() else { return Vec::new() };
1036        let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1037        // SAFETY: NSAttributedString's AppKit addition, with no document attributes.
1038        let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1039        data.map(|d| d.to_vec()).unwrap_or_default()
1040    }
1041
1042    /// Replaces the text with RTF's (from [`rtf`](Self::rtf), TextEdit or
1043    /// Word), styles and all. Clears the undo history and emits no event.
1044    /// False (and nothing changes) if `rtf` isn't RTF.
1045    pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1046        let data = objc2_foundation::NSData::with_bytes(rtf);
1047        // SAFETY: NSAttributedString's AppKit initialiser; nil if it isn't RTF.
1048        let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1049            unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1050        self.load(text)
1051    }
1052
1053    fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1054        let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1055        self.inner.quiet.set(true);
1056        storage.setAttributedString(&text);
1057        self.inner.quiet.set(false);
1058        self.clear_undo();
1059        true
1060    }
1061
1062    /// The text with its styles as an HTML document (for the web, mail or
1063    /// the clipboard).
1064    pub fn html(&self) -> String {
1065        let Some((storage, range)) = self.whole() else { return String::new() };
1066        // SAFETY: AppKit's document type constants and NSAttributedString's
1067        // AppKit addition; nil on failure.
1068        let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1069            let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1070            let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1071            msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1072        };
1073        data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1074    }
1075
1076    /// Replaces the text with HTML's, styles and all (headings, bold,
1077    /// links, lists). Clears the undo history and emits no event. False
1078    /// if AppKit can't read it.
1079    pub fn set_html(&self, html: &str) -> bool {
1080        let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1081        // SAFETY: as in `html`; the reader runs on the main thread, as it must.
1082        let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1083            let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1084            let utf8 = objc2_foundation::NSNumber::new_usize(4); // NSUTF8StringEncoding
1085            let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1086                &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1087                &[kind, utf8.as_ref()],
1088            );
1089            msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1090        };
1091        self.load(text)
1092    }
1093
1094    /// The current font size in points.
1095    pub fn font_size(&self) -> Option<f64> {
1096        self.inner.view.font().map(|f| f.pointSize())
1097    }
1098
1099    /// Space between the text and the view's edges, in points.
1100    pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1101        self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1102    }
1103
1104    /// Continuous spell checking (on by default).
1105    pub fn set_spell_checking(&self, on: bool) {
1106        self.inner.view.setContinuousSpellCheckingEnabled(on);
1107    }
1108
1109    /// Grammar checking (off by default).
1110    pub fn set_grammar_checking(&self, on: bool) {
1111        self.inner.view.setGrammarCheckingEnabled(on);
1112    }
1113
1114    /// Input for code (`true`) or prose (`false`, the default): code turns
1115    /// off what helps prose and breaks code: smart quotes and dashes (`"`
1116    /// becoming `“`), text replacement, spelling correction, spell checking
1117    /// and the spaces smart paste adds.
1118    pub fn set_code_input(&self, code: bool) {
1119        let view = &self.inner.view;
1120        view.setAutomaticQuoteSubstitutionEnabled(!code);
1121        view.setAutomaticDashSubstitutionEnabled(!code);
1122        view.setAutomaticTextReplacementEnabled(!code);
1123        view.setAutomaticSpellingCorrectionEnabled(!code);
1124        view.setContinuousSpellCheckingEnabled(!code);
1125        view.setSmartInsertDeleteEnabled(!code);
1126    }
1127
1128    /// Whether plain Tab inserts a tab (default) or moves focus on.
1129    pub fn set_accepts_tab(&self, accepts: bool) {
1130        crate::keys::set_accepts_tab(self.inner.id, accepts);
1131    }
1132
1133    /// Shows the find bar (as ⌘F does).
1134    pub fn show_find(&self) {
1135        // NSTextFinderActionShowFindInterface = 1, passed as the sender's tag.
1136        let item = objc2_app_kit::NSMenuItem::new(mtm());
1137        item.setTag(1);
1138        let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1139    }
1140
1141    /// Whether the find bar is showing.
1142    pub fn is_find_visible(&self) -> bool {
1143        unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1144    }
1145
1146    /// Whether there is something to undo.
1147    pub fn can_undo(&self) -> bool {
1148        self.inner.undo.borrow().canUndo()
1149    }
1150
1151    /// Undoes the last edit (as ⌘Z does).
1152    pub fn undo(&self) {
1153        let undo = self.undo_manager();
1154        if undo.canUndo() {
1155            undo.undo();
1156        }
1157    }
1158
1159    /// Takes the queued user events (for the host widget).
1160    pub fn drain_events(&self) -> Vec<TextEvent> {
1161        self.inner.events.borrow_mut().drain(..).collect()
1162    }
1163
1164    /// The `NSScrollView` holding the text view, for hosts that place it
1165    /// themselves (no [`crate::attach`]ed window).
1166    pub fn scroll_view(&self) -> Retained<NSScrollView> {
1167        self.inner.scroll.clone()
1168    }
1169
1170    /// The underlying `NSTextView` (escape hatch).
1171    pub fn text_view(&self) -> Retained<NSTextView> {
1172        Retained::into_super(self.inner.view.clone())
1173    }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178    use super::{bytes_to_utf16, utf16_to_bytes};
1179
1180    #[test]
1181    fn offsets_round_trip() {
1182        let t = "a東京😀b";
1183        // a=1 unit/1 byte, 東,京=1 unit/3 bytes, 😀=2 units/4 bytes.
1184        assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1185        assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1186        assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1187        assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1188        assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1189        assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1190    }
1191}