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