1use 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#[derive(Debug, Clone, PartialEq)]
43pub enum TextEvent {
44 Changed,
47 Selection(Range<usize>),
49 Composition(Option<String>),
51}
52
53#[derive(Debug, Clone, PartialEq, Default)]
57pub struct Completion {
58 pub range: Range<usize>,
60 pub items: Vec<String>,
62}
63
64type Completer = dyn Fn(&str, usize) -> Option<Completion>;
65
66const RETURN_MOVEMENT: isize = 0x10;
68const TAB_MOVEMENT: isize = 0x11;
69const OTHER_MOVEMENT: isize = 0;
70
71trait Data {
72 fn push(&self, event: TextEvent);
73 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 fn offered(&self, items: &[String]);
81 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 #[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
95 #[thread_kind = MainThreadOnly]
96 #[name = "FerrokitCoreTextView"]
97 #[ivars = ViewIvars]
98 struct HostTextView;
99
100 impl HostTextView {
101 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
102 fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
103 let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
104 self.composition_changed();
105 }
106
107 #[unsafe(method(unmarkText))]
108 fn unmark_text(&self) {
109 let () = unsafe { msg_send![super(self), unmarkText] };
110 self.composition_changed();
111 }
112
113 #[unsafe(method(insertText:replacementRange:))]
114 fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
115 let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
116 self.composition_changed();
117 let typed = string.downcast_ref::<NSString>().map(|s| s.to_string()).unwrap_or_default();
119 let mut chars = typed.chars();
120 if let (Some(c), None) = (chars.next(), chars.next())
121 && (c.is_alphanumeric() || c == '_' || c == '.')
122 && !self.hasMarkedText()
123 && self.data().is_some_and(|d| d.has_completer())
124 {
125 self.complete_soon();
126 }
127 }
128
129 #[unsafe(method(rangeForUserCompletion))]
131 fn range_for_user_completion(&self) -> NSRange {
132 if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
133 return range;
134 }
135 unsafe { msg_send![super(self), rangeForUserCompletion] }
136 }
137
138 #[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
142 fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
143 if self.data().is_some_and(|d| d.has_completer()) {
144 let clicked = || {
145 let mtm = MainThreadMarker::from(self);
146 objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
147 use objc2_app_kit::NSEventType as T;
148 matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
149 })
150 };
151 let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
152 if !chosen {
153 return;
154 }
155 }
156 let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
157 }
158 }
159);
160
161impl HostTextView {
162 fn data(&self) -> Option<Rc<dyn Data>> {
163 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
164 }
165
166 fn complete_soon(&self) {
169 let view = objc2::rc::Weak::from(self);
170 let block = block2::RcBlock::new(move || {
171 let Some(v) = view.load() else { return };
172 if v.hasMarkedText() || v.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
173 return;
174 }
175 objc2::rc::autoreleasepool(|_| unsafe { v.complete(None) });
177 });
178 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
179 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopDefaultMode.map(|m| m.as_ref()), Some(&block)) };
181 main.wake_up();
182 }
183
184 fn composition_changed(&self) {
186 let composing = self.hasMarkedText();
187 let was = self.ivars().composing.replace(composing);
188 let Some(data) = self.data() else { return };
189 if composing {
190 let range = self.markedRange();
191 let marked = self.string().to_string();
192 let marked = utf16_slice(&marked, range.location, range.length);
193 data.push(TextEvent::Composition(Some(marked)));
194 } else if was {
195 data.push(TextEvent::Composition(None));
196 }
197 }
198}
199
200struct DelegateIvars {
201 data: RefCell<Option<Weak<dyn Data>>>,
202}
203
204define_class!(
205 #[unsafe(super(NSObject))]
206 #[thread_kind = MainThreadOnly]
207 #[name = "FerrokitCoreTextDelegate"]
208 #[ivars = DelegateIvars]
209 struct Delegate;
210
211 unsafe impl NSObjectProtocol for Delegate {}
212
213 unsafe impl NSTextDelegate for Delegate {
214 #[unsafe(method(textDidChange:))]
215 fn text_did_change(&self, _notification: &NSNotification) {
216 let Some(data) = self.data() else { return };
217 data.finish_highlight();
221 if !data.quiet() {
222 data.push(TextEvent::Changed);
223 }
224 }
225 }
226
227 unsafe impl NSTextStorageDelegate for Delegate {
230 #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
236 fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
237 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
238 return;
239 }
240 let Some(data) = self.data().filter(|d| !d.composing()) else { return };
241 if data.highlight(Some(range)) {
242 let weak = self.ivars().data.borrow().clone();
245 let block = block2::RcBlock::new(move || {
246 if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
247 objc2::rc::autoreleasepool(|_| d.finish_highlight());
248 }
249 });
250 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
251 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
253 main.wake_up();
254 }
255 }
256
257 #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
258 fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
259 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
260 return;
261 }
262 let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
263 data.push(TextEvent::Changed);
264 }
265 }
266
267 unsafe impl NSTextViewDelegate for Delegate {
268 #[unsafe(method(textViewDidChangeSelection:))]
269 fn selection_did_change(&self, notification: &NSNotification) {
270 let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
271 let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
272 let text = view.string().to_string();
273 let r = view.selectedRange();
274 data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
275 }
276
277 #[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
279 fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
280 Some(self.completion_words(words, index))
281 }
282
283 #[unsafe(method_id(undoManagerForTextView:))]
286 fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
287 self.data().map(|d| d.undo_manager())
288 }
289 }
290);
291
292impl Delegate {
293 fn data(&self) -> Option<Rc<dyn Data>> {
294 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
295 }
296
297 fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
298 let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
299 let items = data.complete().map(|(_, items)| items).unwrap_or_default();
300 if !index.is_null() {
301 unsafe { *index = if items.is_empty() { -1 } else { 0 } };
303 }
304 data.offered(&items);
305 let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
306 NSArray::from_retained_slice(&items)
307 }
308}
309
310pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
312 let (mut units, mut start, mut end) = (0usize, None, None);
313 for (byte, c) in text.char_indices() {
314 if start.is_none() && units >= location {
315 start = Some(byte);
316 }
317 if end.is_none() && units >= location + length {
318 end = Some(byte);
319 }
320 units += c.len_utf16();
321 }
322 let start = start.unwrap_or(text.len());
323 start..end.unwrap_or(text.len()).max(start)
324}
325
326pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
329 let to_units = |byte: usize| -> usize {
330 let byte = byte.min(text.len());
331 let mut b = byte;
332 while !text.is_char_boundary(b) {
333 b -= 1;
334 }
335 text[..b].encode_utf16().count()
336 };
337 let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
338 (s, e - s)
339}
340
341fn utf16_slice(text: &str, location: usize, length: usize) -> String {
342 text[utf16_to_bytes(text, location, length)].to_string()
343}
344
345struct Inner {
346 id: ViewId,
347 events: RefCell<VecDeque<TextEvent>>,
348 quiet: Cell<bool>,
349 mounted: Cell<bool>,
350 undo: RefCell<Retained<NSUndoManager>>,
351 shared: Cell<bool>,
353 scroll: Retained<NSScrollView>,
354 view: Retained<HostTextView>,
355 _delegate: Retained<Delegate>,
356 font: RefCell<Retained<NSFont>>,
358 highlighter: RefCell<Option<Rc<Highlighter>>>,
359 completer: RefCell<Option<Rc<Completer>>>,
360 offered: RefCell<Vec<String>>,
362 styling: Cell<bool>,
364 shown: RefCell<Option<(usize, Runs)>>,
367 deferred: Cell<Option<(usize, usize)>>,
369}
370
371type Highlighter = dyn Fn(&str) -> Runs;
372type Runs = Vec<(Range<usize>, TextStyle)>;
373
374#[derive(Debug, Clone, Copy, PartialEq)]
378pub enum Color {
379 Primary,
381 Secondary,
383 Tertiary,
385 Quaternary,
387 Fill,
390 SecondaryFill,
392 TertiaryFill,
394 QuaternaryFill,
397 Accent,
399 Link,
401 Red,
403 Orange,
405 Yellow,
407 Green,
409 Mint,
411 Teal,
413 Cyan,
415 Blue,
417 Indigo,
419 Purple,
421 Pink,
423 Brown,
425 Gray,
427 Background,
429 WindowBackground,
431 ControlBackground,
433 Separator,
435 Clear,
437 Rgb(f64, f64, f64),
439 Rgba(f64, f64, f64, f64),
441}
442
443impl Color {
444 const NAMED: [Color; 28] = [
445 Color::Primary,
446 Color::Secondary,
447 Color::Tertiary,
448 Color::Quaternary,
449 Color::Fill,
450 Color::SecondaryFill,
451 Color::TertiaryFill,
452 Color::QuaternaryFill,
453 Color::Accent,
454 Color::Link,
455 Color::Red,
456 Color::Orange,
457 Color::Yellow,
458 Color::Green,
459 Color::Mint,
460 Color::Teal,
461 Color::Cyan,
462 Color::Blue,
463 Color::Indigo,
464 Color::Purple,
465 Color::Pink,
466 Color::Brown,
467 Color::Gray,
468 Color::Background,
469 Color::WindowBackground,
470 Color::ControlBackground,
471 Color::Separator,
472 Color::Clear,
473 ];
474
475 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
477 Color::Rgb(r, g, b)
478 }
479
480 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
482 Color::Rgba(r, g, b, a)
483 }
484
485 pub fn hex(hex: &str) -> Color {
488 let h = hex.trim_start_matches('#');
489 let byte = |i: usize| h.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).map_or(0.0, |b| f64::from(b) / 255.0);
490 match h.len() {
491 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
492 6 => Color::Rgb(byte(0), byte(2), byte(4)),
493 _ => Color::Rgb(0.0, 0.0, 0.0),
494 }
495 }
496
497 pub fn opacity(self, opacity: f64) -> Color {
499 match self.components() {
500 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
501 None => self,
502 }
503 }
504
505 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
508 match self {
509 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
510 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
511 _ => {
512 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
513 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
514 }
515 }
516 }
517
518 pub fn ns(self) -> Retained<NSColor> {
520 match self {
521 Color::Primary => NSColor::textColor(),
522 Color::Secondary => NSColor::secondaryLabelColor(),
523 Color::Tertiary => NSColor::tertiaryLabelColor(),
524 Color::Quaternary => NSColor::quaternaryLabelColor(),
525 Color::Fill => NSColor::systemFillColor(),
526 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
527 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
528 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
529 Color::Accent => NSColor::controlAccentColor(),
530 Color::Link => NSColor::linkColor(),
531 Color::Red => NSColor::systemRedColor(),
532 Color::Orange => NSColor::systemOrangeColor(),
533 Color::Yellow => NSColor::systemYellowColor(),
534 Color::Green => NSColor::systemGreenColor(),
535 Color::Mint => NSColor::systemMintColor(),
536 Color::Teal => NSColor::systemTealColor(),
537 Color::Cyan => NSColor::systemCyanColor(),
538 Color::Blue => NSColor::systemBlueColor(),
539 Color::Indigo => NSColor::systemIndigoColor(),
540 Color::Purple => NSColor::systemPurpleColor(),
541 Color::Pink => NSColor::systemPinkColor(),
542 Color::Brown => NSColor::systemBrownColor(),
543 Color::Gray => NSColor::systemGrayColor(),
544 Color::Background => NSColor::textBackgroundColor(),
545 Color::WindowBackground => NSColor::windowBackgroundColor(),
546 Color::ControlBackground => NSColor::controlBackgroundColor(),
547 Color::Separator => NSColor::separatorColor(),
548 Color::Clear => NSColor::clearColor(),
549 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
550 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
551 }
552 }
553
554 pub fn from_ns(color: &NSColor) -> Option<Color> {
557 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
558 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
559 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
560 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
561 })
562 }
563}
564
565#[derive(Debug, Clone, Copy, Default, PartialEq)]
568pub struct TextStyle {
569 pub color: Option<Color>,
571 pub background: Option<Color>,
573 pub bold: bool,
575 pub italic: bool,
577 pub underline: bool,
579}
580
581impl TextStyle {
582 pub fn new() -> Self {
584 Self::default()
585 }
586
587 pub fn color(mut self, color: Color) -> Self {
589 self.color = Some(color);
590 self
591 }
592
593 pub fn background(mut self, color: Color) -> Self {
595 self.background = Some(color);
596 self
597 }
598
599 pub fn bold(mut self) -> Self {
601 self.bold = true;
602 self
603 }
604
605 pub fn italic(mut self) -> Self {
607 self.italic = true;
608 self
609 }
610
611 pub fn underline(mut self) -> Self {
613 self.underline = true;
614 self
615 }
616}
617
618fn utf16_map(text: &str) -> Vec<usize> {
621 let mut map = Vec::with_capacity(text.len() + 1);
622 let mut units = 0;
623 for c in text.chars() {
624 map.extend(std::iter::repeat_n(units, c.len_utf8()));
625 units += c.len_utf16();
626 }
627 map.push(units);
628 map
629}
630
631impl Inner {
632 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
640 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
642 let text = storage.string().to_string();
643 let map = utf16_map(&text);
644 let len16 = *map.last().unwrap_or(&0);
645 let shown = self.shown.borrow_mut().take();
646 let region = match (shown, edited) {
649 (Some((old_len, old)), Some(edited)) => {
650 let delta = text.len() as isize - old_len as isize;
651 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
652 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
653 let suffix = old[prefix..]
654 .iter()
655 .rev()
656 .zip(runs[prefix..].iter().rev())
657 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
658 .count();
659 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
660 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
661 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
662 lo..hi
663 }
664 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
665 };
666 let mut deferred = false;
672 let region = match edited {
673 Some(e) => {
674 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
675 if inside != region {
676 deferred = self.deferred.get().is_none();
677 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
678 }
679 inside.start..inside.end.max(inside.start)
680 }
681 None => region,
682 };
683 let font = self.font.borrow().clone();
684 self.styling.set(true);
685 unsafe {
688 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
689 if edited.is_none() {
690 storage.beginEditing();
691 }
692 let base = objc2_foundation::NSDictionary::from_retained_objects(
693 &[NSFontAttributeName, NSForegroundColorAttributeName],
694 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
695 );
696 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
697 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
698 for (range, style) in &runs {
699 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
700 if start >= end {
701 continue;
702 }
703 let r = NSRange::new(start, end - start);
704 if let Some(c) = style.color {
705 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
706 }
707 if let Some(c) = style.background {
708 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
709 }
710 if style.bold || style.italic {
711 let mut f = font.clone();
712 if style.bold {
713 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
714 }
715 if style.italic {
716 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
717 }
718 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
719 }
720 if style.underline {
721 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
722 }
723 }
724 if edited.is_none() {
725 storage.endEditing();
726 }
727 }
728 self.styling.set(false);
729 *self.shown.borrow_mut() = Some((text.len(), runs));
730 if edited.is_some() {
738 return deferred;
739 }
740 unsafe {
742 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
743 let typing = objc2_foundation::NSDictionary::from_retained_objects(
744 &[NSFontAttributeName, NSForegroundColorAttributeName],
745 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
746 );
747 self.view.setTypingAttributes(&typing);
748 }
749 false
750 }
751}
752
753impl Data for Inner {
754 fn push(&self, event: TextEvent) {
755 let mut events = self.events.borrow_mut();
756 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
759 return;
760 }
761 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
763 events.pop_back();
764 }
765 events.push_back(event);
766 drop(events);
767 crate::request_redraw();
768 }
769
770 fn quiet(&self) -> bool {
771 self.quiet.get()
772 }
773
774 fn complete(&self) -> Option<(NSRange, Vec<String>)> {
775 let f = self.completer.borrow().clone()?;
776 let text = self.view.string().to_string();
777 let sel = self.view.selectedRange();
778 let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
779 let c = f(&text, caret)?;
780 let start = c.range.start.min(caret);
781 let (location, length) = bytes_to_utf16(&text, start..caret);
782 Some((NSRange::new(location, length), c.items))
783 }
784
785 fn has_completer(&self) -> bool {
786 self.completer.borrow().is_some()
787 }
788
789 fn offered(&self, items: &[String]) {
790 *self.offered.borrow_mut() = items.to_vec();
791 }
792
793 fn composing(&self) -> bool {
794 self.view.hasMarkedText()
795 }
796
797 fn undo_manager(&self) -> Retained<NSUndoManager> {
798 self.undo.borrow().clone()
799 }
800
801 fn highlight(&self, edited: Option<NSRange>) -> bool {
802 if self.styling.get() {
803 return false;
804 }
805 let Some(f) = self.highlighter.borrow().clone() else { return false };
806 let runs = f(&self.view.string().to_string());
807 self.apply_styles(runs, edited, None)
808 }
809
810 fn finish_highlight(&self) {
811 let Some(span) = self.deferred.take() else { return };
812 if self.styling.get() || self.view.hasMarkedText() {
813 return;
814 }
815 let Some(f) = self.highlighter.borrow().clone() else { return };
816 let runs = f(&self.view.string().to_string());
817 self.apply_styles(runs, None, Some(span));
818 }
819}
820
821impl Drop for ViewIvars {
822 fn drop(&mut self) {
823 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
824 }
825}
826
827impl Drop for DelegateIvars {
828 fn drop(&mut self) {
829 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
830 }
831}
832
833impl Drop for Inner {
834 fn drop(&mut self) {
835 self.view.setDelegate(None);
837 if let Some(storage) = unsafe { self.view.textStorage() } {
838 storage.setDelegate(None);
839 }
840 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
841 crate::keys::set_accepts_tab(self.id, false);
842 if self.mounted.get() {
843 crate::unmount(self.id);
844 }
845 }
846}
847
848#[derive(Clone)]
850pub struct TextModel {
851 inner: Rc<Inner>,
852}
853
854impl std::fmt::Debug for TextModel {
855 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
856 write!(f, "TextModel({:?})", self.inner.id)
857 }
858}
859
860impl TextModel {
861 pub fn new(id: ViewId, text: &str) -> Self {
865 let mtm = mtm();
866 let size = NSSize::new(400.0, 300.0);
867 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
868 scroll.setHasVerticalScroller(true);
869 scroll.setAutohidesScrollers(true);
870 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
871
872 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
875 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
876 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
877 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
878 view.setMinSize(NSSize::new(0.0, size.height));
879 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
880 view.setVerticallyResizable(true);
881 view.setHorizontallyResizable(false);
882 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
883 if let Some(container) = unsafe { view.textContainer() } {
885 container.setContainerSize(NSSize::new(size.width, f64::MAX));
886 container.setWidthTracksTextView(true);
887 }
888 view.setRichText(false);
889 view.setImportsGraphics(false);
890 view.setAllowsUndo(true);
891 view.setUsesFindBar(true);
892 view.setContinuousSpellCheckingEnabled(true);
893 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
894 view.setTextContainerInset(NSSize::new(4.0, 6.0));
895 view.setString(&NSString::from_str(text));
896 scroll.setDocumentView(Some(&view));
897
898 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
899 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
900
901 let inner = Rc::new(Inner {
902 id,
903 events: RefCell::new(VecDeque::new()),
904 quiet: Cell::new(false),
905 mounted: Cell::new(false),
906 undo: RefCell::new(NSUndoManager::new(mtm)),
907 shared: Cell::new(false),
908 scroll,
909 view: view.clone(),
910 _delegate: delegate.clone(),
911 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
912 highlighter: RefCell::new(None),
913 completer: RefCell::new(None),
914 offered: RefCell::new(Vec::new()),
915 styling: Cell::new(false),
916 shown: RefCell::new(None),
917 deferred: Cell::new(None),
918 });
919 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
920 *view.ivars().data.borrow_mut() = Some(weak.clone());
921 *delegate.ivars().data.borrow_mut() = Some(weak);
922 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
924 if let Some(storage) = unsafe { view.textStorage() } {
925 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
927 }
928 crate::keys::set_accepts_tab(id, true);
929 Self { inner }
930 }
931
932 pub fn id(&self) -> ViewId {
934 self.inner.id
935 }
936
937 pub fn ensure_mounted(&self) {
940 if !self.inner.mounted.get() && crate::is_attached() {
941 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
942 self.inner.mounted.set(true);
943 }
944 }
945
946 pub fn text(&self) -> String {
948 self.inner.view.string().to_string()
949 }
950
951 pub fn set_text(&self, text: &str) {
954 self.inner.quiet.set(true);
955 self.inner.view.setString(&NSString::from_str(text));
956 self.inner.quiet.set(false);
957 self.clear_undo();
958 }
959
960 fn clear_undo(&self) {
963 let undo = self.inner.undo.borrow();
964 if self.inner.shared.get() {
965 unsafe {
967 undo.removeAllActionsWithTarget(&self.inner.view);
968 if let Some(storage) = self.inner.view.textStorage() {
969 undo.removeAllActionsWithTarget(&storage);
970 }
971 }
972 } else {
973 undo.removeAllActions();
974 }
975 }
976
977 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
982 self.clear_undo();
983 let mtm = MainThreadMarker::from(&*self.inner.view);
984 let next = match manager {
985 Some(m) => m.retain(),
986 None => NSUndoManager::new(mtm),
987 };
988 *self.inner.undo.borrow_mut() = next;
989 self.inner.shared.set(manager.is_some());
990 }
991
992 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
994 self.inner.undo.borrow().clone()
995 }
996
997 pub fn replace_selection(&self, text: &str) {
999 let view = &self.inner.view;
1000 let range = view.selectedRange();
1001 let string = NSString::from_str(text);
1002 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1003 view.replaceCharactersInRange_withString(range, &string);
1004 view.didChangeText();
1005 }
1006 }
1007
1008 pub fn selection(&self) -> Range<usize> {
1010 let r = self.inner.view.selectedRange();
1011 utf16_to_bytes(&self.text(), r.location, r.length)
1012 }
1013
1014 pub fn set_selection(&self, range: Range<usize>) {
1016 let (location, length) = bytes_to_utf16(&self.text(), range);
1017 self.inner.quiet.set(true);
1018 self.inner.view.setSelectedRange(NSRange::new(location, length));
1019 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1020 self.inner.quiet.set(false);
1021 }
1022
1023 pub fn composition(&self) -> Option<String> {
1025 let view = &self.inner.view;
1026 view.hasMarkedText().then(|| {
1027 let r = view.markedRange();
1028 utf16_slice(&view.string().to_string(), r.location, r.length)
1029 })
1030 }
1031
1032 pub fn set_editable(&self, editable: bool) {
1034 self.inner.view.setEditable(editable);
1035 }
1036
1037 pub fn is_editable(&self) -> bool {
1039 self.inner.view.isEditable()
1040 }
1041
1042 pub fn set_font(&self, name: Option<&str>, size: f64) {
1044 let font = match name {
1045 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1046 None => Some(NSFont::systemFontOfSize(size)),
1047 };
1048 if let Some(font) = font {
1049 self.inner.view.setFont(Some(&font));
1050 *self.inner.font.borrow_mut() = font;
1051 self.inner.highlight(None);
1052 }
1053 }
1054
1055 pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1062 *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1063 }
1064
1065 pub fn complete(&self) {
1067 unsafe { self.inner.view.complete(None) };
1069 }
1070
1071 pub fn offered_completions(&self) -> Vec<String> {
1073 self.inner.offered.borrow().clone()
1074 }
1075
1076 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1082 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1083 self.restyle();
1084 }
1085
1086 pub fn restyle(&self) {
1089 if self.inner.highlighter.borrow().is_some() {
1090 self.inner.highlight(None);
1091 } else {
1092 self.inner.apply_styles(Vec::new(), None, None);
1093 }
1094 }
1095
1096 pub fn style_at(&self, offset: usize) -> TextStyle {
1098 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1100 let text = storage.string().to_string();
1101 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1102 let mut style = TextStyle::default();
1103 unsafe {
1105 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1106 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1107 style.color = at(NSForegroundColorAttributeName)
1108 .and_then(|c| c.downcast::<NSColor>().ok())
1109 .and_then(|c| Color::from_ns(&c))
1110 .filter(|c| *c != Color::Primary);
1111 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1112 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1113 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1114 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1115 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1116 }
1117 style.underline = at(NSUnderlineStyleAttributeName)
1118 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1119 .is_some_and(|n| n.integerValue() != 0);
1120 }
1121 style
1122 }
1123
1124 pub fn set_rich(&self, rich: bool) {
1131 let v = &self.inner.view;
1132 v.setRichText(rich);
1133 v.setImportsGraphics(rich);
1134 v.setUsesFontPanel(rich);
1135 v.setUsesRuler(rich);
1136 if !rich {
1137 v.setUsesInspectorBar(false);
1138 v.setRulerVisible(false);
1139 }
1140 }
1141
1142 pub fn is_rich(&self) -> bool {
1144 self.inner.view.isRichText()
1145 }
1146
1147 pub fn set_format_bar(&self, shown: bool) {
1150 self.inner.view.setUsesInspectorBar(shown);
1151 }
1152
1153 pub fn has_format_bar(&self) -> bool {
1155 self.inner.view.usesInspectorBar()
1156 }
1157
1158 pub fn set_ruler_visible(&self, shown: bool) {
1162 self.inner.view.setRulerVisible(shown);
1163 }
1164
1165 pub fn is_ruler_visible(&self) -> bool {
1167 self.inner.view.isRulerVisible()
1168 }
1169
1170 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1171 let storage = unsafe { self.inner.view.textStorage() }?;
1173 let len = storage.length();
1174 Some((storage, NSRange::new(0, len)))
1175 }
1176
1177 pub fn rtf(&self) -> Vec<u8> {
1180 let Some((storage, range)) = self.whole() else { return Vec::new() };
1181 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1182 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1184 data.map(|d| d.to_vec()).unwrap_or_default()
1185 }
1186
1187 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1191 let data = objc2_foundation::NSData::with_bytes(rtf);
1192 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1194 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1195 self.load(text)
1196 }
1197
1198 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1199 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1200 self.inner.quiet.set(true);
1201 storage.setAttributedString(&text);
1202 self.inner.quiet.set(false);
1203 self.clear_undo();
1204 true
1205 }
1206
1207 pub fn html(&self) -> String {
1210 let Some((storage, range)) = self.whole() else { return String::new() };
1211 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1214 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1215 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1216 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1217 };
1218 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1219 }
1220
1221 pub fn set_html(&self, html: &str) -> bool {
1225 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1226 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1228 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1229 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1231 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1232 &[kind, utf8.as_ref()],
1233 );
1234 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1235 };
1236 self.load(text)
1237 }
1238
1239 pub fn font_size(&self) -> Option<f64> {
1241 self.inner.view.font().map(|f| f.pointSize())
1242 }
1243
1244 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1246 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1247 }
1248
1249 pub fn set_spell_checking(&self, on: bool) {
1251 self.inner.view.setContinuousSpellCheckingEnabled(on);
1252 }
1253
1254 pub fn set_grammar_checking(&self, on: bool) {
1256 self.inner.view.setGrammarCheckingEnabled(on);
1257 }
1258
1259 pub fn set_code_input(&self, code: bool) {
1264 let view = &self.inner.view;
1265 view.setAutomaticQuoteSubstitutionEnabled(!code);
1266 view.setAutomaticDashSubstitutionEnabled(!code);
1267 view.setAutomaticTextReplacementEnabled(!code);
1268 view.setAutomaticSpellingCorrectionEnabled(!code);
1269 view.setContinuousSpellCheckingEnabled(!code);
1270 view.setSmartInsertDeleteEnabled(!code);
1271 }
1272
1273 pub fn set_accepts_tab(&self, accepts: bool) {
1275 crate::keys::set_accepts_tab(self.inner.id, accepts);
1276 }
1277
1278 pub fn show_find(&self) {
1280 let item = objc2_app_kit::NSMenuItem::new(mtm());
1282 item.setTag(1);
1283 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1284 }
1285
1286 pub fn is_find_visible(&self) -> bool {
1288 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1289 }
1290
1291 pub fn can_undo(&self) -> bool {
1293 self.inner.undo.borrow().canUndo()
1294 }
1295
1296 pub fn undo(&self) {
1298 let undo = self.undo_manager();
1299 if undo.canUndo() {
1300 undo.undo();
1301 }
1302 }
1303
1304 pub fn drain_events(&self) -> Vec<TextEvent> {
1306 self.inner.events.borrow_mut().drain(..).collect()
1307 }
1308
1309 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1312 self.inner.scroll.clone()
1313 }
1314
1315 pub fn text_view(&self) -> Retained<NSTextView> {
1317 Retained::into_super(self.inner.view.clone())
1318 }
1319}
1320
1321#[cfg(test)]
1322mod tests {
1323 use super::{bytes_to_utf16, utf16_to_bytes};
1324
1325 #[test]
1326 fn offsets_round_trip() {
1327 let t = "a東京😀b";
1328 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1330 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1331 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1332 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1333 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1334 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1335 }
1336}