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