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)]
411#[non_exhaustive]
412pub enum Color {
413    /// The text colour (what unstyled text uses).
414    Primary,
415    /// Less prominent text.
416    Secondary,
417    /// Even less prominent text (comments, placeholders).
418    Tertiary,
419    /// The least prominent text and fills.
420    Quaternary,
421    /// The system's fill for thin shapes (a slider's track, a progress
422    /// ring's track): the strongest of the fills, a translucent grey.
423    Fill,
424    /// A fill for medium shapes (a switch's background).
425    SecondaryFill,
426    /// A fill for large shapes (an input field, a search bar).
427    TertiaryFill,
428    /// A fill for large areas with content on them: grouped cards, as
429    /// SwiftUI's `GroupBox` and grouped forms draw them.
430    QuaternaryFill,
431    /// The user's accent colour (System Settings › Appearance).
432    Accent,
433    /// Links.
434    Link,
435    /// System red.
436    Red,
437    /// System orange.
438    Orange,
439    /// System yellow.
440    Yellow,
441    /// System green.
442    Green,
443    /// System mint.
444    Mint,
445    /// System teal.
446    Teal,
447    /// System cyan.
448    Cyan,
449    /// System blue.
450    Blue,
451    /// System indigo.
452    Indigo,
453    /// System purple.
454    Purple,
455    /// System pink.
456    Pink,
457    /// System brown.
458    Brown,
459    /// System gray.
460    Gray,
461    /// The background of content (text, tables): white, or dark in Dark Mode.
462    Background,
463    /// The window's background (behind content).
464    WindowBackground,
465    /// The background of controls and grouped content: cards, panels.
466    ControlBackground,
467    /// Separator lines and grids.
468    Separator,
469    /// Fully transparent.
470    Clear,
471    /// A fixed sRGB colour (components 0–1; the same in light and dark).
472    Rgb(f64, f64, f64),
473    /// A fixed sRGB colour with opacity (components 0–1).
474    Rgba(f64, f64, f64, f64),
475}
476
477impl Color {
478    const NAMED: [Color; 28] = [
479        Color::Primary,
480        Color::Secondary,
481        Color::Tertiary,
482        Color::Quaternary,
483        Color::Fill,
484        Color::SecondaryFill,
485        Color::TertiaryFill,
486        Color::QuaternaryFill,
487        Color::Accent,
488        Color::Link,
489        Color::Red,
490        Color::Orange,
491        Color::Yellow,
492        Color::Green,
493        Color::Mint,
494        Color::Teal,
495        Color::Cyan,
496        Color::Blue,
497        Color::Indigo,
498        Color::Purple,
499        Color::Pink,
500        Color::Brown,
501        Color::Gray,
502        Color::Background,
503        Color::WindowBackground,
504        Color::ControlBackground,
505        Color::Separator,
506        Color::Clear,
507    ];
508
509    /// An opaque sRGB colour (components 0–1).
510    pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
511        Color::Rgb(r, g, b)
512    }
513
514    /// An sRGB colour with opacity (components 0–1).
515    pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
516        Color::Rgba(r, g, b, a)
517    }
518
519    /// A colour from a hex string: `"#3a7bd5"`, `"3a7bd5"`, or with opacity
520    /// `"#3a7bd580"`. Black for anything else.
521    pub fn hex(hex: &str) -> Color {
522        let h = hex.trim_start_matches('#');
523        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);
524        match h.len() {
525            8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
526            6 => Color::Rgb(byte(0), byte(2), byte(4)),
527            _ => Color::Rgb(0.0, 0.0, 0.0),
528        }
529    }
530
531    /// The same colour at `opacity` (0–1), on top of its own.
532    pub fn opacity(self, opacity: f64) -> Color {
533        match self.components() {
534            Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
535            None => self,
536        }
537    }
538
539    /// Its sRGB components (red, green, blue, opacity), resolved for the
540    /// current appearance for the named colours.
541    pub fn components(self) -> Option<(f64, f64, f64, f64)> {
542        match self {
543            Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
544            Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
545            _ => {
546                let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
547                Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
548            }
549        }
550    }
551
552    /// The `NSColor` (dynamic for the named colours).
553    pub fn ns(self) -> Retained<NSColor> {
554        match self {
555            Color::Primary => NSColor::textColor(),
556            Color::Secondary => NSColor::secondaryLabelColor(),
557            Color::Tertiary => NSColor::tertiaryLabelColor(),
558            Color::Quaternary => NSColor::quaternaryLabelColor(),
559            Color::Fill => NSColor::systemFillColor(),
560            Color::SecondaryFill => NSColor::secondarySystemFillColor(),
561            Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
562            Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
563            Color::Accent => NSColor::controlAccentColor(),
564            Color::Link => NSColor::linkColor(),
565            Color::Red => NSColor::systemRedColor(),
566            Color::Orange => NSColor::systemOrangeColor(),
567            Color::Yellow => NSColor::systemYellowColor(),
568            Color::Green => NSColor::systemGreenColor(),
569            Color::Mint => NSColor::systemMintColor(),
570            Color::Teal => NSColor::systemTealColor(),
571            Color::Cyan => NSColor::systemCyanColor(),
572            Color::Blue => NSColor::systemBlueColor(),
573            Color::Indigo => NSColor::systemIndigoColor(),
574            Color::Purple => NSColor::systemPurpleColor(),
575            Color::Pink => NSColor::systemPinkColor(),
576            Color::Brown => NSColor::systemBrownColor(),
577            Color::Gray => NSColor::systemGrayColor(),
578            Color::Background => NSColor::textBackgroundColor(),
579            Color::WindowBackground => NSColor::windowBackgroundColor(),
580            Color::ControlBackground => NSColor::controlBackgroundColor(),
581            Color::Separator => NSColor::separatorColor(),
582            Color::Clear => NSColor::clearColor(),
583            Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
584            Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
585        }
586    }
587
588    /// The colour an `NSColor` is: a named one if it's one of those, else
589    /// its sRGB components.
590    pub fn from_ns(color: &NSColor) -> Option<Color> {
591        Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
592            let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
593            let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
594            Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
595        })
596    }
597}
598
599/// How a run of text looks. What it leaves unset stays as the editor's own
600/// (its font and text colour).
601#[derive(Debug, Clone, Copy, Default, PartialEq)]
602pub struct TextStyle {
603    /// The text colour.
604    pub color: Option<Color>,
605    /// A background behind the run.
606    pub background: Option<Color>,
607    /// Bold (the font's bold face).
608    pub bold: bool,
609    /// Italic (the font's italic face, where it has one).
610    pub italic: bool,
611    /// Underlined.
612    pub underline: bool,
613}
614
615impl TextStyle {
616    /// A style that changes nothing.
617    pub fn new() -> Self {
618        Self::default()
619    }
620
621    /// With this text colour.
622    pub fn color(mut self, color: Color) -> Self {
623        self.color = Some(color);
624        self
625    }
626
627    /// With this background.
628    pub fn background(mut self, color: Color) -> Self {
629        self.background = Some(color);
630        self
631    }
632
633    /// Bold.
634    pub fn bold(mut self) -> Self {
635        self.bold = true;
636        self
637    }
638
639    /// Italic.
640    pub fn italic(mut self) -> Self {
641        self.italic = true;
642        self
643    }
644
645    /// Underlined.
646    pub fn underline(mut self) -> Self {
647        self.underline = true;
648        self
649    }
650}
651
652/// UTF-16 offsets of every byte offset of `text` (inside a character: that
653/// character's start), plus the end.
654fn utf16_map(text: &str) -> Vec<usize> {
655    let mut map = Vec::with_capacity(text.len() + 1);
656    let mut units = 0;
657    for c in text.chars() {
658        map.extend(std::iter::repeat_n(units, c.len_utf8()));
659        units += c.len_utf16();
660    }
661    map.push(units);
662    map
663}
664
665impl Inner {
666    /// Styles the text with `runs`: what differs from the runs shown before
667    /// (and the `edited` UTF-16 range) is reset to the editor's font and
668    /// colour, then given its runs' styles. `None` restyles everything.
669    /// With an `edited` range it runs inside the storage's own edit
670    /// (willProcessEditing), so it opens no edit of its own; `only` limits
671    /// a restyle outside an edit to a UTF-16 span. True when part of an
672    /// edit's span was newly left for just after it.
673    fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
674        // SAFETY: the text view's own storage, on the main thread.
675        let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
676        let text = storage.string().to_string();
677        let map = utf16_map(&text);
678        let len16 = *map.last().unwrap_or(&0);
679        let shown = self.shown.borrow_mut().take();
680        // The span whose runs changed: runs equal before it (a prefix) and,
681        // shifted by the edit, after it (a suffix) keep their styles.
682        let region = match (shown, edited) {
683            (Some((old_len, old)), Some(edited)) => {
684                let delta = text.len() as isize - old_len as isize;
685                let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
686                let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
687                let suffix = old[prefix..]
688                    .iter()
689                    .rev()
690                    .zip(runs[prefix..].iter().rev())
691                    .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
692                    .count();
693                let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
694                let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
695                // Runs may overlap or come unsorted (a search match over a
696                // keyword): the span also covers every changed run itself,
697                // old and new, wherever it sits among the others.
698                let clamp = |i: isize| (i.max(0) as usize).min(text.len());
699                let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
700                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))]);
701                let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
702                let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
703                lo..hi
704            }
705            _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
706        };
707        // Inside an edit only the edited characters are styled: attributes
708        // changed past them widen the storage's edited range, and the text
709        // view puts the caret at its end (typing mid-line jumped to the next
710        // run). The rest of the span is restyled just after the edit (all
711        // of the text if an earlier edit's span is still waiting).
712        let mut deferred = false;
713        let region = match edited {
714            Some(e) => {
715                let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
716                if inside != region {
717                    deferred = self.deferred.get().is_none();
718                    self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
719                }
720                inside.start..inside.end.max(inside.start)
721            }
722            None => region,
723        };
724        let font = self.font.borrow().clone();
725        self.styling.set(true);
726        // SAFETY: attribute keys and values of the documented types (fonts,
727        // colours, an NSNumber for the underline style), in range.
728        unsafe {
729            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
730            if edited.is_none() {
731                storage.beginEditing();
732            }
733            let base = objc2_foundation::NSDictionary::from_retained_objects(
734                &[NSFontAttributeName, NSForegroundColorAttributeName],
735                &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
736            );
737            storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
738            let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
739            for (range, style) in &runs {
740                let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
741                if start >= end {
742                    continue;
743                }
744                let r = NSRange::new(start, end - start);
745                if let Some(c) = style.color {
746                    storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
747                }
748                if let Some(c) = style.background {
749                    storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
750                }
751                if style.bold || style.italic {
752                    let mut f = font.clone();
753                    if style.bold {
754                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
755                    }
756                    if style.italic {
757                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
758                    }
759                    storage.addAttribute_value_range(NSFontAttributeName, &f, r);
760                }
761                if style.underline {
762                    storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
763                }
764            }
765            if edited.is_none() {
766                storage.endEditing();
767            }
768        }
769        self.styling.set(false);
770        *self.shown.borrow_mut() = Some((text.len(), runs));
771        // What's typed next starts plain (the highlighter restyles it).
772        // Not during an edit: the text view still has the selection from
773        // before it, and setting typing attributes reads the attributes
774        // there, past the end of shorter text (an NSRangeException that
775        // stopped the edit halfway and left TextKit 2's layout behind the
776        // text). After an edit the text view takes them from the text
777        // around the caret, which is already styled.
778        if edited.is_some() {
779            return deferred;
780        }
781        // SAFETY: a dictionary of standard attributes.
782        unsafe {
783            use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
784            let typing = objc2_foundation::NSDictionary::from_retained_objects(
785                &[NSFontAttributeName, NSForegroundColorAttributeName],
786                &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
787            );
788            self.view.setTypingAttributes(&typing);
789        }
790        false
791    }
792}
793
794impl Data for Inner {
795    fn push(&self, event: TextEvent) {
796        let mut events = self.events.borrow_mut();
797        // `Changed` means "read the text again": one queued is enough (an
798        // edit is reported by both the text storage and textDidChange:).
799        if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
800            return;
801        }
802        // Keep only the latest of a run of selection moves.
803        if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
804            events.pop_back();
805        }
806        events.push_back(event);
807        drop(events);
808        crate::request_redraw();
809    }
810
811    fn quiet(&self) -> bool {
812        self.quiet.get()
813    }
814
815    fn complete(&self) -> Option<(NSRange, Vec<String>)> {
816        let f = self.completer.borrow().clone()?;
817        let text = self.view.string().to_string();
818        let sel = self.view.selectedRange();
819        let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
820        let c = f(&text, caret)?;
821        let start = c.range.start.min(caret);
822        let (location, length) = bytes_to_utf16(&text, start..caret);
823        Some((NSRange::new(location, length), c.items))
824    }
825
826    fn has_completer(&self) -> bool {
827        self.completer.borrow().is_some()
828    }
829
830    fn offered(&self, items: &[String]) {
831        *self.offered.borrow_mut() = items.to_vec();
832    }
833
834    fn composing(&self) -> bool {
835        self.view.hasMarkedText()
836    }
837
838    fn undo_manager(&self) -> Retained<NSUndoManager> {
839        self.undo.borrow().clone()
840    }
841
842    fn highlight(&self, edited: Option<NSRange>) -> bool {
843        if self.styling.get() {
844            return false;
845        }
846        let Some(f) = self.highlighter.borrow().clone() else { return false };
847        let runs = f(&self.view.string().to_string());
848        self.apply_styles(runs, edited, None)
849    }
850
851    fn finish_highlight(&self) {
852        let Some(span) = self.deferred.take() else { return };
853        if self.styling.get() || self.view.hasMarkedText() {
854            return;
855        }
856        let Some(f) = self.highlighter.borrow().clone() else { return };
857        let runs = f(&self.view.string().to_string());
858        self.apply_styles(runs, None, Some(span));
859    }
860}
861
862impl Drop for ViewIvars {
863    fn drop(&mut self) {
864        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
865    }
866}
867
868impl Drop for DelegateIvars {
869    fn drop(&mut self) {
870        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
871    }
872}
873
874impl Drop for Inner {
875    fn drop(&mut self) {
876        // The text view and its storage hold the delegate weakly: detach it first.
877        self.view.setDelegate(None);
878        if let Some(storage) = unsafe { self.view.textStorage() } {
879            storage.setDelegate(None);
880        }
881        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
882        crate::keys::set_accepts_tab(self.id, false);
883        if self.mounted.get() {
884            crate::unmount(self.id);
885        }
886    }
887}
888
889/// A native plain-text editor. Cheap to clone (a handle); main thread only.
890#[derive(Clone)]
891pub struct TextModel {
892    inner: Rc<Inner>,
893}
894
895impl std::fmt::Debug for TextModel {
896    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
897        write!(f, "TextModel({:?})", self.inner.id)
898    }
899}
900
901impl TextModel {
902    /// Creates the editor (added to the window the first time the host draws
903    /// it). Defaults: plain text, system font 13 pt, continuous spell
904    /// checking, find bar, undo, Tab inserts a tab (Ctrl-Tab moves focus on).
905    pub fn new(text: &str) -> Self {
906        #[allow(deprecated)]
907        Self::with_id(ViewId::next(), text)
908    }
909
910    /// [`new`](Self::new) with an id the caller chose (before 0.13, every
911    /// model took one).
912    #[deprecated(since = "0.13.0", note = "use `TextModel::new(text)`: the id is chosen for you")]
913    pub fn with_id(id: ViewId, text: &str) -> Self {
914        let mtm = mtm();
915        let size = NSSize::new(400.0, 300.0);
916        let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
917        scroll.setHasVerticalScroller(true);
918        scroll.setAutohidesScrollers(true);
919        scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
920
921        // The standard recipe for a text view in a scroll view: width tracks
922        // the scroll view, height grows with the text.
923        crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
924        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
925        let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
926        let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
927        view.setMinSize(NSSize::new(0.0, size.height));
928        view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
929        view.setVerticallyResizable(true);
930        view.setHorizontallyResizable(false);
931        view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
932        // SAFETY: the text view's own container.
933        if let Some(container) = unsafe { view.textContainer() } {
934            container.setContainerSize(NSSize::new(size.width, f64::MAX));
935            container.setWidthTracksTextView(true);
936        }
937        view.setRichText(false);
938        view.setImportsGraphics(false);
939        view.setAllowsUndo(true);
940        view.setUsesFindBar(true);
941        view.setContinuousSpellCheckingEnabled(true);
942        view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
943        view.setTextContainerInset(NSSize::new(4.0, 6.0));
944        view.setString(&NSString::from_str(text));
945        scroll.setDocumentView(Some(&view));
946
947        let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
948        let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
949
950        let inner = Rc::new(Inner {
951            id,
952            events: RefCell::new(VecDeque::new()),
953            quiet: Cell::new(false),
954            mounted: Cell::new(false),
955            undo: RefCell::new(NSUndoManager::new(mtm)),
956            shared: Cell::new(false),
957            scroll,
958            view: view.clone(),
959            _delegate: delegate.clone(),
960            font: RefCell::new(NSFont::systemFontOfSize(13.0)),
961            highlighter: RefCell::new(None),
962            completer: RefCell::new(None),
963            offered: RefCell::new(Vec::new()),
964            styling: Cell::new(false),
965            shown: RefCell::new(None),
966            deferred: Cell::new(None),
967        });
968        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
969        *view.ivars().data.borrow_mut() = Some(weak.clone());
970        *delegate.ivars().data.borrow_mut() = Some(weak);
971        // SAFETY: the delegate lives as long as the model, which removes the view.
972        view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
973        if let Some(storage) = unsafe { view.textStorage() } {
974            // Weak in AppKit, like the view's delegate; detached in Drop.
975            storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
976        }
977        crate::keys::set_accepts_tab(id, true);
978        Self { inner }
979    }
980
981    /// The view id the editor was created with.
982    pub fn id(&self) -> ViewId {
983        self.inner.id
984    }
985
986    /// Adds the editor to the attached window if it isn't yet (the host
987    /// widget calls this before placing it).
988    pub fn ensure_mounted(&self) {
989        if !self.inner.mounted.get() && crate::is_attached() {
990            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
991            self.inner.mounted.set(true);
992        }
993    }
994
995    /// The whole text.
996    pub fn text(&self) -> String {
997        self.inner.view.string().to_string()
998    }
999
1000    /// Replaces the whole text (e.g. loading a document). Clears the undo
1001    /// history and emits no event.
1002    pub fn set_text(&self, text: &str) {
1003        self.inner.quiet.set(true);
1004        self.inner.view.setString(&NSString::from_str(text));
1005        self.inner.quiet.set(false);
1006        self.clear_undo();
1007    }
1008
1009    /// Removes this editor's edits from its undo history (only this
1010    /// editor's, when the history is shared).
1011    fn clear_undo(&self) {
1012        let undo = self.inner.undo.borrow();
1013        if self.inner.shared.get() {
1014            // AppKit registers typing with the text storage as the target.
1015            unsafe {
1016                undo.removeAllActionsWithTarget(&self.inner.view);
1017                if let Some(storage) = self.inner.view.textStorage() {
1018                    undo.removeAllActionsWithTarget(&storage);
1019                }
1020            }
1021        } else {
1022            undo.removeAllActions();
1023        }
1024    }
1025
1026    /// Records edits in `manager` (e.g. the window's, shared with other
1027    /// views and app-level changes) instead of the editor's own history, or
1028    /// in a fresh history of its own again with `None`. Edits recorded so
1029    /// far are dropped.
1030    pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
1031        self.clear_undo();
1032        let mtm = MainThreadMarker::from(&*self.inner.view);
1033        let next = match manager {
1034            Some(m) => m.retain(),
1035            None => NSUndoManager::new(mtm),
1036        };
1037        *self.inner.undo.borrow_mut() = next;
1038        self.inner.shared.set(manager.is_some());
1039    }
1040
1041    /// The undo history the editor records in.
1042    pub fn undo_manager(&self) -> Retained<NSUndoManager> {
1043        self.inner.undo.borrow().clone()
1044    }
1045
1046    /// Replaces the selection as if typed: undoable, emits `Changed`.
1047    pub fn replace_selection(&self, text: &str) {
1048        let view = &self.inner.view;
1049        let range = view.selectedRange();
1050        let string = NSString::from_str(text);
1051        if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1052            view.replaceCharactersInRange_withString(range, &string);
1053            view.didChangeText();
1054        }
1055    }
1056
1057    /// Selected byte range (empty: the caret).
1058    pub fn selection(&self) -> Range<usize> {
1059        let r = self.inner.view.selectedRange();
1060        utf16_to_bytes(&self.text(), r.location, r.length)
1061    }
1062
1063    /// Selects a byte range (emits no event).
1064    pub fn set_selection(&self, range: Range<usize>) {
1065        let (location, length) = bytes_to_utf16(&self.text(), range);
1066        self.inner.quiet.set(true);
1067        self.inner.view.setSelectedRange(NSRange::new(location, length));
1068        self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1069        self.inner.quiet.set(false);
1070    }
1071
1072    /// Whether an input method is composing, and its marked text.
1073    pub fn composition(&self) -> Option<String> {
1074        let view = &self.inner.view;
1075        view.hasMarkedText().then(|| {
1076            let r = view.markedRange();
1077            utf16_slice(&view.string().to_string(), r.location, r.length)
1078        })
1079    }
1080
1081    /// Read-only (`false`) or editable. Read-only text can still be selected and copied.
1082    pub fn set_editable(&self, editable: bool) {
1083        self.inner.view.setEditable(editable);
1084    }
1085
1086    /// Whether the user can edit the text.
1087    pub fn is_editable(&self) -> bool {
1088        self.inner.view.isEditable()
1089    }
1090
1091    /// Font: `None` for the system font, else a family or PostScript name.
1092    pub fn set_font(&self, name: Option<&str>, size: f64) {
1093        let font = match name {
1094            Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1095            None => Some(NSFont::systemFontOfSize(size)),
1096        };
1097        if let Some(font) = font {
1098            self.inner.view.setFont(Some(&font));
1099            *self.inner.font.borrow_mut() = font;
1100            self.inner.highlight(None);
1101        }
1102    }
1103
1104    /// Completes as the user types, in AppKit's completion list: `f` gets
1105    /// the text and the caret (a byte offset) and says what it completes
1106    /// there and with which words ([`Completion`]), or `None`. Typing a
1107    /// word character or a dot opens the list (⌥⎋ or F5 open it too);
1108    /// typing on filters it (`f` is asked again), ↑ and ↓ move, Return or
1109    /// Tab or a click puts the word in, and Escape closes it.
1110    pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1111        *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1112    }
1113
1114    /// Opens the completion list at the caret now (as ⌥⎋ does).
1115    pub fn complete(&self) {
1116        // SAFETY: AppKit's completion, on the main thread.
1117        unsafe { self.inner.view.complete(None) };
1118    }
1119
1120    /// The words the completion list showed last (for checks).
1121    pub fn offered_completions(&self) -> Vec<String> {
1122        self.inner.offered.borrow().clone()
1123    }
1124
1125    /// Styles the text with `f`: given the text, it returns runs (UTF-8
1126    /// byte ranges) and their styles; the rest is plain. It runs now and
1127    /// after every edit (typing, paste, undo, `set_text`), before the edit
1128    /// is drawn, so keep it fast: it sees the whole text each time. `None`
1129    /// makes the text plain again.
1130    pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1131        *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1132        self.restyle();
1133    }
1134
1135    /// Runs the highlighter again, for when what it depends on changed
1136    /// other than the text (a search term, a theme).
1137    pub fn restyle(&self) {
1138        if self.inner.highlighter.borrow().is_some() {
1139            self.inner.highlight(None);
1140        } else {
1141            self.inner.apply_styles(Vec::new(), None, None);
1142        }
1143    }
1144
1145    /// The style of the character at byte `offset`, as shown (for checks).
1146    pub fn style_at(&self, offset: usize) -> TextStyle {
1147        // SAFETY: the text view's own storage, on the main thread.
1148        let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1149        let text = storage.string().to_string();
1150        let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1151        let mut style = TextStyle::default();
1152        // SAFETY: reading standard attributes at an index inside the text.
1153        unsafe {
1154            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1155            let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1156            style.color = at(NSForegroundColorAttributeName)
1157                .and_then(|c| c.downcast::<NSColor>().ok())
1158                .and_then(|c| Color::from_ns(&c))
1159                .filter(|c| *c != Color::Primary);
1160            style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1161            if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1162                let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1163                style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1164                style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1165            }
1166            style.underline = at(NSUnderlineStyleAttributeName)
1167                .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1168                .is_some_and(|n| n.integerValue() != 0);
1169        }
1170        style
1171    }
1172
1173    /// Rich text (`true`) or plain (`false`, the default). Rich, the user
1174    /// styles the text: fonts and sizes (the font panel, ⌘T), bold, italic
1175    /// and underline (⌘B, ⌘I, ⌘U), colours, alignment, spacing and lists
1176    /// (the ruler and the format bar); pasted text keeps its styles, and
1177    /// pictures can be pasted or dropped in. Don't combine it with a
1178    /// highlighter, which restyles the text itself.
1179    pub fn set_rich(&self, rich: bool) {
1180        let v = &self.inner.view;
1181        v.setRichText(rich);
1182        v.setImportsGraphics(rich);
1183        v.setUsesFontPanel(rich);
1184        v.setUsesRuler(rich);
1185        if !rich {
1186            v.setUsesInspectorBar(false);
1187            v.setRulerVisible(false);
1188        }
1189    }
1190
1191    /// Whether the text is rich (see [`set_rich`](Self::set_rich)).
1192    pub fn is_rich(&self) -> bool {
1193        self.inner.view.isRichText()
1194    }
1195
1196    /// TextEdit's format bar above the text (rich text): font, size,
1197    /// colours, bold, italic, underline, alignment, line spacing and lists.
1198    pub fn set_format_bar(&self, shown: bool) {
1199        self.inner.view.setUsesInspectorBar(shown);
1200    }
1201
1202    /// Whether the format bar is shown.
1203    pub fn has_format_bar(&self) -> bool {
1204        self.inner.view.usesInspectorBar()
1205    }
1206
1207    /// The ruler above the text (rich text): margins, tab stops,
1208    /// alignment, spacing and lists. Format ▸ Text ▸ Show Ruler (⌃⌘R)
1209    /// toggles it too.
1210    pub fn set_ruler_visible(&self, shown: bool) {
1211        self.inner.view.setRulerVisible(shown);
1212    }
1213
1214    /// Whether the ruler is shown.
1215    pub fn is_ruler_visible(&self) -> bool {
1216        self.inner.view.isRulerVisible()
1217    }
1218
1219    fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1220        // SAFETY: the text view's own storage, on the main thread.
1221        let storage = unsafe { self.inner.view.textStorage() }?;
1222        let len = storage.length();
1223        Some((storage, NSRange::new(0, len)))
1224    }
1225
1226    /// The text with its styles, as RTF (what TextEdit saves). Pictures
1227    /// aren't included.
1228    pub fn rtf(&self) -> Vec<u8> {
1229        let Some((storage, range)) = self.whole() else { return Vec::new() };
1230        let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1231        // SAFETY: NSAttributedString's AppKit addition, with no document attributes.
1232        let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1233        data.map(|d| d.to_vec()).unwrap_or_default()
1234    }
1235
1236    /// Replaces the text with RTF's (from [`rtf`](Self::rtf), TextEdit or
1237    /// Word), styles and all. Clears the undo history and emits no event.
1238    /// False (and nothing changes) if `rtf` isn't RTF.
1239    pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1240        let data = objc2_foundation::NSData::with_bytes(rtf);
1241        // SAFETY: NSAttributedString's AppKit initialiser; nil if it isn't RTF.
1242        let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1243            unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1244        self.load(text)
1245    }
1246
1247    fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1248        let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1249        self.inner.quiet.set(true);
1250        storage.setAttributedString(&text);
1251        self.inner.quiet.set(false);
1252        self.clear_undo();
1253        true
1254    }
1255
1256    /// The text with its styles as an HTML document (for the web, mail or
1257    /// the clipboard).
1258    pub fn html(&self) -> String {
1259        let Some((storage, range)) = self.whole() else { return String::new() };
1260        // SAFETY: AppKit's document type constants and NSAttributedString's
1261        // AppKit addition; nil on failure.
1262        let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1263            let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1264            let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1265            msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1266        };
1267        data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1268    }
1269
1270    /// Replaces the text with HTML's, styles and all (headings, bold,
1271    /// links, lists). Clears the undo history and emits no event. False
1272    /// if AppKit can't read it.
1273    pub fn set_html(&self, html: &str) -> bool {
1274        let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1275        // SAFETY: as in `html`; the reader runs on the main thread, as it must.
1276        let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1277            let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1278            let utf8 = objc2_foundation::NSNumber::new_usize(4); // NSUTF8StringEncoding
1279            let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1280                &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1281                &[kind, utf8.as_ref()],
1282            );
1283            msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1284        };
1285        self.load(text)
1286    }
1287
1288    /// The current font size in points.
1289    pub fn font_size(&self) -> Option<f64> {
1290        self.inner.view.font().map(|f| f.pointSize())
1291    }
1292
1293    /// Space between the text and the view's edges, in points.
1294    pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1295        self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1296    }
1297
1298    /// Continuous spell checking (on by default).
1299    pub fn set_spell_checking(&self, on: bool) {
1300        self.inner.view.setContinuousSpellCheckingEnabled(on);
1301    }
1302
1303    /// Grammar checking (off by default).
1304    pub fn set_grammar_checking(&self, on: bool) {
1305        self.inner.view.setGrammarCheckingEnabled(on);
1306    }
1307
1308    /// Input for code (`true`) or prose (`false`, the default): code turns
1309    /// off what helps prose and breaks code: smart quotes and dashes (`"`
1310    /// becoming `“`), text replacement, spelling correction, spell checking
1311    /// and the spaces smart paste adds.
1312    pub fn set_code_input(&self, code: bool) {
1313        let view = &self.inner.view;
1314        view.setAutomaticQuoteSubstitutionEnabled(!code);
1315        view.setAutomaticDashSubstitutionEnabled(!code);
1316        view.setAutomaticTextReplacementEnabled(!code);
1317        view.setAutomaticSpellingCorrectionEnabled(!code);
1318        view.setContinuousSpellCheckingEnabled(!code);
1319        view.setSmartInsertDeleteEnabled(!code);
1320    }
1321
1322    /// Whether plain Tab inserts a tab (default) or moves focus on.
1323    pub fn set_accepts_tab(&self, accepts: bool) {
1324        crate::keys::set_accepts_tab(self.inner.id, accepts);
1325    }
1326
1327    /// Shows the find bar, as Edit ▸ Find ▸ Find… (⌘F) does in a Ferrokit
1328    /// app while the focus is in the editor.
1329    pub fn show_find(&self) {
1330        // NSTextFinderActionShowFindInterface = 1, passed as the sender's tag.
1331        let item = objc2_app_kit::NSMenuItem::new(mtm());
1332        item.setTag(1);
1333        let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1334    }
1335
1336    /// Whether long lines wrap at the editor's width (the default), or run
1337    /// on with a horizontal scroller (code, logs, tables of text).
1338    pub fn set_wraps(&self, wraps: bool) {
1339        let (view, scroll) = (&self.inner.view, &self.inner.scroll);
1340        // SAFETY: the text view's own container.
1341        let Some(container) = (unsafe { view.textContainer() }) else { return };
1342        if container.widthTracksTextView() == wraps {
1343            return;
1344        }
1345        let width = scroll.contentSize().width;
1346        scroll.setHasHorizontalScroller(!wraps);
1347        view.setHorizontallyResizable(!wraps);
1348        container.setWidthTracksTextView(wraps);
1349        if wraps {
1350            // Back to the scroll view's width, which the container follows.
1351            let mut frame = view.frame();
1352            frame.size.width = width;
1353            view.setFrame(frame);
1354            container.setContainerSize(NSSize::new(width, f64::MAX));
1355        } else {
1356            // (Wide enough for any line; the largest number breaks layout.)
1357            container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
1358            view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
1359        }
1360        view.sizeToFit();
1361        view.setNeedsDisplay(true);
1362    }
1363
1364    /// Whether long lines wrap (see [`set_wraps`](Self::set_wraps)).
1365    pub fn wraps(&self) -> bool {
1366        // SAFETY: the text view's own container.
1367        unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
1368    }
1369
1370    /// Whether the find bar is showing.
1371    pub fn is_find_visible(&self) -> bool {
1372        unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1373    }
1374
1375    /// Whether there is something to undo.
1376    pub fn can_undo(&self) -> bool {
1377        self.inner.undo.borrow().canUndo()
1378    }
1379
1380    /// Undoes the last edit (as ⌘Z does).
1381    pub fn undo(&self) {
1382        let undo = self.undo_manager();
1383        if undo.canUndo() {
1384            undo.undo();
1385        }
1386    }
1387
1388    /// Takes the queued user events (for the host widget).
1389    pub fn drain_events(&self) -> Vec<TextEvent> {
1390        self.inner.events.borrow_mut().drain(..).collect()
1391    }
1392
1393    /// The `NSScrollView` holding the text view, for hosts that place it
1394    /// themselves (no [`crate::attach`]ed window).
1395    pub fn scroll_view(&self) -> Retained<NSScrollView> {
1396        self.inner.scroll.clone()
1397    }
1398
1399    /// The underlying `NSTextView` (escape hatch).
1400    pub fn text_view(&self) -> Retained<NSTextView> {
1401        Retained::into_super(self.inner.view.clone())
1402    }
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407    use super::{bytes_to_utf16, utf16_to_bytes};
1408
1409    #[test]
1410    fn offsets_round_trip() {
1411        let t = "a東京😀b";
1412        // a=1 unit/1 byte, 東,京=1 unit/3 bytes, 😀=2 units/4 bytes.
1413        assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1414        assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1415        assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1416        assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1417        assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1418        assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1419    }
1420}