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