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