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 crate::boundary::guarded("a text view (set_marked_text)", (), || {
104 let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
105 self.composition_changed();
106 })
107 }
108
109 #[unsafe(method(unmarkText))]
110 fn unmark_text(&self) {
111 crate::boundary::guarded("a text view (unmark_text)", (), || {
112 let () = unsafe { msg_send![super(self), unmarkText] };
113 self.composition_changed();
114 })
115 }
116
117 #[unsafe(method(insertText:replacementRange:))]
118 fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
119 crate::boundary::guarded("a text view (insert_text)", (), || {
120 let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
121 self.composition_changed();
122 let typed = string.downcast_ref::<NSString>().map(|s| s.to_string()).unwrap_or_default();
124 let mut chars = typed.chars();
125 if let (Some(c), None) = (chars.next(), chars.next())
126 && (c.is_alphanumeric() || c == '_' || c == '.')
127 && !self.hasMarkedText()
128 && self.data().is_some_and(|d| d.has_completer())
129 {
130 self.complete_soon();
131 }
132 })
133 }
134
135 #[unsafe(method(rangeForUserCompletion))]
137 fn range_for_user_completion(&self) -> NSRange {
138 crate::boundary::guarded("a text view (range_for_user_completion)", NSRange::new(0, 0), || {
139 if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
140 return range;
141 }
142 unsafe { msg_send![super(self), rangeForUserCompletion] }
143 })
144 }
145
146 #[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
150 fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
151 crate::boundary::guarded("a text view (insert_completion)", (), || {
152 if self.data().is_some_and(|d| d.has_completer()) {
153 let clicked = || {
154 let mtm = MainThreadMarker::from(self);
155 objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
156 use objc2_app_kit::NSEventType as T;
157 matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
158 })
159 };
160 let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
161 if !chosen {
162 return;
163 }
164 }
165 let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
166 })
167 }
168 }
169);
170
171impl HostTextView {
172 fn data(&self) -> Option<Rc<dyn Data>> {
173 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
174 }
175
176 fn complete_soon(&self) {
179 let view = objc2::rc::Weak::from(self);
180 let block = block2::RcBlock::new(move || {
181 let Some(v) = view.load() else { return };
182 if v.hasMarkedText() || v.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
183 return;
184 }
185 objc2::rc::autoreleasepool(|_| unsafe { v.complete(None) });
187 });
188 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
189 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopDefaultMode.map(|m| m.as_ref()), Some(&block)) };
191 main.wake_up();
192 }
193
194 fn composition_changed(&self) {
196 let composing = self.hasMarkedText();
197 let was = self.ivars().composing.replace(composing);
198 let Some(data) = self.data() else { return };
199 if composing {
200 let range = self.markedRange();
201 let marked = self.string().to_string();
202 let marked = utf16_slice(&marked, range.location, range.length);
203 data.push(TextEvent::Composition(Some(marked)));
204 } else if was {
205 data.push(TextEvent::Composition(None));
206 }
207 }
208}
209
210struct DelegateIvars {
211 data: RefCell<Option<Weak<dyn Data>>>,
212}
213
214define_class!(
215 #[unsafe(super(NSObject))]
216 #[thread_kind = MainThreadOnly]
217 #[name = "FerrokitCoreTextDelegate"]
218 #[ivars = DelegateIvars]
219 struct Delegate;
220
221 unsafe impl NSObjectProtocol for Delegate {}
222
223 unsafe impl NSTextDelegate for Delegate {
224 #[unsafe(method(textDidChange:))]
225 fn text_did_change(&self, _notification: &NSNotification) {
226 crate::boundary::guarded("a text view (text_did_change)", (), || {
227 let Some(data) = self.data() else { return };
228 data.finish_highlight();
232 if !data.quiet() {
233 data.push(TextEvent::Changed);
234 }
235 })
236 }
237 }
238
239 unsafe impl NSTextStorageDelegate for Delegate {
242 #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
248 fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
249 crate::boundary::guarded("a text view (will_process_editing)", (), || {
250 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
251 return;
252 }
253 let Some(data) = self.data().filter(|d| !d.composing()) else { return };
254 if data.highlight(Some(range)) {
255 let weak = self.ivars().data.borrow().clone();
258 let block = block2::RcBlock::new(move || {
259 if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
260 objc2::rc::autoreleasepool(|_| d.finish_highlight());
261 }
262 });
263 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
264 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
266 main.wake_up();
267 }
268 })
269 }
270
271 #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
272 fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
273 crate::boundary::guarded("a text view (did_process_editing)", (), || {
274 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
275 return;
276 }
277 let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
278 data.push(TextEvent::Changed);
279 })
280 }
281 }
282
283 unsafe impl NSTextViewDelegate for Delegate {
284 #[unsafe(method(textViewDidChangeSelection:))]
285 fn selection_did_change(&self, notification: &NSNotification) {
286 crate::boundary::guarded("a text view (selection_did_change)", (), || {
287 let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
288 let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
289 let text = view.string().to_string();
290 let r = view.selectedRange();
291 data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
292 })
293 }
294
295 #[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
297 fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
298 crate::boundary::guarded("a text view (completions)", None, || {
299 Some(self.completion_words(words, index))
300 })
301 }
302
303 #[unsafe(method_id(undoManagerForTextView:))]
306 fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
307 crate::boundary::guarded("a text view (undo_manager_for)", None, || {
308 self.data().map(|d| d.undo_manager())
309 })
310 }
311 }
312);
313
314impl Delegate {
315 fn data(&self) -> Option<Rc<dyn Data>> {
316 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
317 }
318
319 fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
320 let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
321 let items = data.complete().map(|(_, items)| items).unwrap_or_default();
322 if !index.is_null() {
323 unsafe { *index = if items.is_empty() { -1 } else { 0 } };
325 }
326 data.offered(&items);
327 let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
328 NSArray::from_retained_slice(&items)
329 }
330}
331
332pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
334 let (mut units, mut start, mut end) = (0usize, None, None);
335 for (byte, c) in text.char_indices() {
336 if start.is_none() && units >= location {
337 start = Some(byte);
338 }
339 if end.is_none() && units >= location + length {
340 end = Some(byte);
341 }
342 units += c.len_utf16();
343 }
344 let start = start.unwrap_or(text.len());
345 start..end.unwrap_or(text.len()).max(start)
346}
347
348pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
351 let to_units = |byte: usize| -> usize {
352 let byte = byte.min(text.len());
353 let mut b = byte;
354 while !text.is_char_boundary(b) {
355 b -= 1;
356 }
357 text[..b].encode_utf16().count()
358 };
359 let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
360 (s, e - s)
361}
362
363fn utf16_slice(text: &str, location: usize, length: usize) -> String {
364 text[utf16_to_bytes(text, location, length)].to_string()
365}
366
367struct Inner {
368 id: ViewId,
369 events: RefCell<VecDeque<TextEvent>>,
370 quiet: Cell<bool>,
371 mounted: Cell<bool>,
372 undo: RefCell<Retained<NSUndoManager>>,
373 shared: Cell<bool>,
375 scroll: Retained<NSScrollView>,
376 view: Retained<HostTextView>,
377 _delegate: Retained<Delegate>,
378 font: RefCell<Retained<NSFont>>,
380 highlighter: RefCell<Option<Rc<Highlighter>>>,
381 completer: RefCell<Option<Rc<Completer>>>,
382 offered: RefCell<Vec<String>>,
384 styling: Cell<bool>,
386 shown: RefCell<Option<(usize, Runs)>>,
389 deferred: Cell<Option<(usize, usize)>>,
391}
392
393type Highlighter = dyn Fn(&str) -> Runs;
394type Runs = Vec<(Range<usize>, TextStyle)>;
395
396#[derive(Debug, Clone, Copy, PartialEq)]
400pub enum Color {
401 Primary,
403 Secondary,
405 Tertiary,
407 Quaternary,
409 Fill,
412 SecondaryFill,
414 TertiaryFill,
416 QuaternaryFill,
419 Accent,
421 Link,
423 Red,
425 Orange,
427 Yellow,
429 Green,
431 Mint,
433 Teal,
435 Cyan,
437 Blue,
439 Indigo,
441 Purple,
443 Pink,
445 Brown,
447 Gray,
449 Background,
451 WindowBackground,
453 ControlBackground,
455 Separator,
457 Clear,
459 Rgb(f64, f64, f64),
461 Rgba(f64, f64, f64, f64),
463}
464
465impl Color {
466 const NAMED: [Color; 28] = [
467 Color::Primary,
468 Color::Secondary,
469 Color::Tertiary,
470 Color::Quaternary,
471 Color::Fill,
472 Color::SecondaryFill,
473 Color::TertiaryFill,
474 Color::QuaternaryFill,
475 Color::Accent,
476 Color::Link,
477 Color::Red,
478 Color::Orange,
479 Color::Yellow,
480 Color::Green,
481 Color::Mint,
482 Color::Teal,
483 Color::Cyan,
484 Color::Blue,
485 Color::Indigo,
486 Color::Purple,
487 Color::Pink,
488 Color::Brown,
489 Color::Gray,
490 Color::Background,
491 Color::WindowBackground,
492 Color::ControlBackground,
493 Color::Separator,
494 Color::Clear,
495 ];
496
497 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
499 Color::Rgb(r, g, b)
500 }
501
502 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
504 Color::Rgba(r, g, b, a)
505 }
506
507 pub fn hex(hex: &str) -> Color {
510 let h = hex.trim_start_matches('#');
511 let byte = |i: usize| h.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).map_or(0.0, |b| f64::from(b) / 255.0);
512 match h.len() {
513 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
514 6 => Color::Rgb(byte(0), byte(2), byte(4)),
515 _ => Color::Rgb(0.0, 0.0, 0.0),
516 }
517 }
518
519 pub fn opacity(self, opacity: f64) -> Color {
521 match self.components() {
522 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
523 None => self,
524 }
525 }
526
527 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
530 match self {
531 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
532 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
533 _ => {
534 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
535 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
536 }
537 }
538 }
539
540 pub fn ns(self) -> Retained<NSColor> {
542 match self {
543 Color::Primary => NSColor::textColor(),
544 Color::Secondary => NSColor::secondaryLabelColor(),
545 Color::Tertiary => NSColor::tertiaryLabelColor(),
546 Color::Quaternary => NSColor::quaternaryLabelColor(),
547 Color::Fill => NSColor::systemFillColor(),
548 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
549 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
550 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
551 Color::Accent => NSColor::controlAccentColor(),
552 Color::Link => NSColor::linkColor(),
553 Color::Red => NSColor::systemRedColor(),
554 Color::Orange => NSColor::systemOrangeColor(),
555 Color::Yellow => NSColor::systemYellowColor(),
556 Color::Green => NSColor::systemGreenColor(),
557 Color::Mint => NSColor::systemMintColor(),
558 Color::Teal => NSColor::systemTealColor(),
559 Color::Cyan => NSColor::systemCyanColor(),
560 Color::Blue => NSColor::systemBlueColor(),
561 Color::Indigo => NSColor::systemIndigoColor(),
562 Color::Purple => NSColor::systemPurpleColor(),
563 Color::Pink => NSColor::systemPinkColor(),
564 Color::Brown => NSColor::systemBrownColor(),
565 Color::Gray => NSColor::systemGrayColor(),
566 Color::Background => NSColor::textBackgroundColor(),
567 Color::WindowBackground => NSColor::windowBackgroundColor(),
568 Color::ControlBackground => NSColor::controlBackgroundColor(),
569 Color::Separator => NSColor::separatorColor(),
570 Color::Clear => NSColor::clearColor(),
571 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
572 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
573 }
574 }
575
576 pub fn from_ns(color: &NSColor) -> Option<Color> {
579 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
580 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
581 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
582 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
583 })
584 }
585}
586
587#[derive(Debug, Clone, Copy, Default, PartialEq)]
590pub struct TextStyle {
591 pub color: Option<Color>,
593 pub background: Option<Color>,
595 pub bold: bool,
597 pub italic: bool,
599 pub underline: bool,
601}
602
603impl TextStyle {
604 pub fn new() -> Self {
606 Self::default()
607 }
608
609 pub fn color(mut self, color: Color) -> Self {
611 self.color = Some(color);
612 self
613 }
614
615 pub fn background(mut self, color: Color) -> Self {
617 self.background = Some(color);
618 self
619 }
620
621 pub fn bold(mut self) -> Self {
623 self.bold = true;
624 self
625 }
626
627 pub fn italic(mut self) -> Self {
629 self.italic = true;
630 self
631 }
632
633 pub fn underline(mut self) -> Self {
635 self.underline = true;
636 self
637 }
638}
639
640fn utf16_map(text: &str) -> Vec<usize> {
643 let mut map = Vec::with_capacity(text.len() + 1);
644 let mut units = 0;
645 for c in text.chars() {
646 map.extend(std::iter::repeat_n(units, c.len_utf8()));
647 units += c.len_utf16();
648 }
649 map.push(units);
650 map
651}
652
653impl Inner {
654 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
662 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
664 let text = storage.string().to_string();
665 let map = utf16_map(&text);
666 let len16 = *map.last().unwrap_or(&0);
667 let shown = self.shown.borrow_mut().take();
668 let region = match (shown, edited) {
671 (Some((old_len, old)), Some(edited)) => {
672 let delta = text.len() as isize - old_len as isize;
673 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
674 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
675 let suffix = old[prefix..]
676 .iter()
677 .rev()
678 .zip(runs[prefix..].iter().rev())
679 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
680 .count();
681 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
682 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
683 let clamp = |i: isize| (i.max(0) as usize).min(text.len());
687 let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
688 let changed_old = old[prefix..old.len() - suffix].iter().flat_map(|(r, _)| [(clamp(r.start as isize), clamp(r.end as isize)), (clamp(r.start as isize + delta), clamp(r.end as isize + delta))]);
689 let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
690 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
691 lo..hi
692 }
693 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
694 };
695 let mut deferred = false;
701 let region = match edited {
702 Some(e) => {
703 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
704 if inside != region {
705 deferred = self.deferred.get().is_none();
706 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
707 }
708 inside.start..inside.end.max(inside.start)
709 }
710 None => region,
711 };
712 let font = self.font.borrow().clone();
713 self.styling.set(true);
714 unsafe {
717 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
718 if edited.is_none() {
719 storage.beginEditing();
720 }
721 let base = objc2_foundation::NSDictionary::from_retained_objects(
722 &[NSFontAttributeName, NSForegroundColorAttributeName],
723 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
724 );
725 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
726 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
727 for (range, style) in &runs {
728 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
729 if start >= end {
730 continue;
731 }
732 let r = NSRange::new(start, end - start);
733 if let Some(c) = style.color {
734 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
735 }
736 if let Some(c) = style.background {
737 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
738 }
739 if style.bold || style.italic {
740 let mut f = font.clone();
741 if style.bold {
742 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
743 }
744 if style.italic {
745 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
746 }
747 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
748 }
749 if style.underline {
750 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
751 }
752 }
753 if edited.is_none() {
754 storage.endEditing();
755 }
756 }
757 self.styling.set(false);
758 *self.shown.borrow_mut() = Some((text.len(), runs));
759 if edited.is_some() {
767 return deferred;
768 }
769 unsafe {
771 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
772 let typing = objc2_foundation::NSDictionary::from_retained_objects(
773 &[NSFontAttributeName, NSForegroundColorAttributeName],
774 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
775 );
776 self.view.setTypingAttributes(&typing);
777 }
778 false
779 }
780}
781
782impl Data for Inner {
783 fn push(&self, event: TextEvent) {
784 let mut events = self.events.borrow_mut();
785 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
788 return;
789 }
790 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
792 events.pop_back();
793 }
794 events.push_back(event);
795 drop(events);
796 crate::request_redraw();
797 }
798
799 fn quiet(&self) -> bool {
800 self.quiet.get()
801 }
802
803 fn complete(&self) -> Option<(NSRange, Vec<String>)> {
804 let f = self.completer.borrow().clone()?;
805 let text = self.view.string().to_string();
806 let sel = self.view.selectedRange();
807 let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
808 let c = f(&text, caret)?;
809 let start = c.range.start.min(caret);
810 let (location, length) = bytes_to_utf16(&text, start..caret);
811 Some((NSRange::new(location, length), c.items))
812 }
813
814 fn has_completer(&self) -> bool {
815 self.completer.borrow().is_some()
816 }
817
818 fn offered(&self, items: &[String]) {
819 *self.offered.borrow_mut() = items.to_vec();
820 }
821
822 fn composing(&self) -> bool {
823 self.view.hasMarkedText()
824 }
825
826 fn undo_manager(&self) -> Retained<NSUndoManager> {
827 self.undo.borrow().clone()
828 }
829
830 fn highlight(&self, edited: Option<NSRange>) -> bool {
831 if self.styling.get() {
832 return false;
833 }
834 let Some(f) = self.highlighter.borrow().clone() else { return false };
835 let runs = f(&self.view.string().to_string());
836 self.apply_styles(runs, edited, None)
837 }
838
839 fn finish_highlight(&self) {
840 let Some(span) = self.deferred.take() else { return };
841 if self.styling.get() || self.view.hasMarkedText() {
842 return;
843 }
844 let Some(f) = self.highlighter.borrow().clone() else { return };
845 let runs = f(&self.view.string().to_string());
846 self.apply_styles(runs, None, Some(span));
847 }
848}
849
850impl Drop for ViewIvars {
851 fn drop(&mut self) {
852 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
853 }
854}
855
856impl Drop for DelegateIvars {
857 fn drop(&mut self) {
858 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
859 }
860}
861
862impl Drop for Inner {
863 fn drop(&mut self) {
864 self.view.setDelegate(None);
866 if let Some(storage) = unsafe { self.view.textStorage() } {
867 storage.setDelegate(None);
868 }
869 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
870 crate::keys::set_accepts_tab(self.id, false);
871 if self.mounted.get() {
872 crate::unmount(self.id);
873 }
874 }
875}
876
877#[derive(Clone)]
879pub struct TextModel {
880 inner: Rc<Inner>,
881}
882
883impl std::fmt::Debug for TextModel {
884 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
885 write!(f, "TextModel({:?})", self.inner.id)
886 }
887}
888
889impl TextModel {
890 pub fn new(id: ViewId, text: &str) -> Self {
894 let mtm = mtm();
895 let size = NSSize::new(400.0, 300.0);
896 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
897 scroll.setHasVerticalScroller(true);
898 scroll.setAutohidesScrollers(true);
899 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
900
901 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
904 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
905 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
906 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
907 view.setMinSize(NSSize::new(0.0, size.height));
908 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
909 view.setVerticallyResizable(true);
910 view.setHorizontallyResizable(false);
911 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
912 if let Some(container) = unsafe { view.textContainer() } {
914 container.setContainerSize(NSSize::new(size.width, f64::MAX));
915 container.setWidthTracksTextView(true);
916 }
917 view.setRichText(false);
918 view.setImportsGraphics(false);
919 view.setAllowsUndo(true);
920 view.setUsesFindBar(true);
921 view.setContinuousSpellCheckingEnabled(true);
922 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
923 view.setTextContainerInset(NSSize::new(4.0, 6.0));
924 view.setString(&NSString::from_str(text));
925 scroll.setDocumentView(Some(&view));
926
927 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
928 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
929
930 let inner = Rc::new(Inner {
931 id,
932 events: RefCell::new(VecDeque::new()),
933 quiet: Cell::new(false),
934 mounted: Cell::new(false),
935 undo: RefCell::new(NSUndoManager::new(mtm)),
936 shared: Cell::new(false),
937 scroll,
938 view: view.clone(),
939 _delegate: delegate.clone(),
940 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
941 highlighter: RefCell::new(None),
942 completer: RefCell::new(None),
943 offered: RefCell::new(Vec::new()),
944 styling: Cell::new(false),
945 shown: RefCell::new(None),
946 deferred: Cell::new(None),
947 });
948 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
949 *view.ivars().data.borrow_mut() = Some(weak.clone());
950 *delegate.ivars().data.borrow_mut() = Some(weak);
951 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
953 if let Some(storage) = unsafe { view.textStorage() } {
954 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
956 }
957 crate::keys::set_accepts_tab(id, true);
958 Self { inner }
959 }
960
961 pub fn id(&self) -> ViewId {
963 self.inner.id
964 }
965
966 pub fn ensure_mounted(&self) {
969 if !self.inner.mounted.get() && crate::is_attached() {
970 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
971 self.inner.mounted.set(true);
972 }
973 }
974
975 pub fn text(&self) -> String {
977 self.inner.view.string().to_string()
978 }
979
980 pub fn set_text(&self, text: &str) {
983 self.inner.quiet.set(true);
984 self.inner.view.setString(&NSString::from_str(text));
985 self.inner.quiet.set(false);
986 self.clear_undo();
987 }
988
989 fn clear_undo(&self) {
992 let undo = self.inner.undo.borrow();
993 if self.inner.shared.get() {
994 unsafe {
996 undo.removeAllActionsWithTarget(&self.inner.view);
997 if let Some(storage) = self.inner.view.textStorage() {
998 undo.removeAllActionsWithTarget(&storage);
999 }
1000 }
1001 } else {
1002 undo.removeAllActions();
1003 }
1004 }
1005
1006 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
1011 self.clear_undo();
1012 let mtm = MainThreadMarker::from(&*self.inner.view);
1013 let next = match manager {
1014 Some(m) => m.retain(),
1015 None => NSUndoManager::new(mtm),
1016 };
1017 *self.inner.undo.borrow_mut() = next;
1018 self.inner.shared.set(manager.is_some());
1019 }
1020
1021 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
1023 self.inner.undo.borrow().clone()
1024 }
1025
1026 pub fn replace_selection(&self, text: &str) {
1028 let view = &self.inner.view;
1029 let range = view.selectedRange();
1030 let string = NSString::from_str(text);
1031 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1032 view.replaceCharactersInRange_withString(range, &string);
1033 view.didChangeText();
1034 }
1035 }
1036
1037 pub fn selection(&self) -> Range<usize> {
1039 let r = self.inner.view.selectedRange();
1040 utf16_to_bytes(&self.text(), r.location, r.length)
1041 }
1042
1043 pub fn set_selection(&self, range: Range<usize>) {
1045 let (location, length) = bytes_to_utf16(&self.text(), range);
1046 self.inner.quiet.set(true);
1047 self.inner.view.setSelectedRange(NSRange::new(location, length));
1048 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1049 self.inner.quiet.set(false);
1050 }
1051
1052 pub fn composition(&self) -> Option<String> {
1054 let view = &self.inner.view;
1055 view.hasMarkedText().then(|| {
1056 let r = view.markedRange();
1057 utf16_slice(&view.string().to_string(), r.location, r.length)
1058 })
1059 }
1060
1061 pub fn set_editable(&self, editable: bool) {
1063 self.inner.view.setEditable(editable);
1064 }
1065
1066 pub fn is_editable(&self) -> bool {
1068 self.inner.view.isEditable()
1069 }
1070
1071 pub fn set_font(&self, name: Option<&str>, size: f64) {
1073 let font = match name {
1074 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1075 None => Some(NSFont::systemFontOfSize(size)),
1076 };
1077 if let Some(font) = font {
1078 self.inner.view.setFont(Some(&font));
1079 *self.inner.font.borrow_mut() = font;
1080 self.inner.highlight(None);
1081 }
1082 }
1083
1084 pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1091 *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1092 }
1093
1094 pub fn complete(&self) {
1096 unsafe { self.inner.view.complete(None) };
1098 }
1099
1100 pub fn offered_completions(&self) -> Vec<String> {
1102 self.inner.offered.borrow().clone()
1103 }
1104
1105 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1111 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1112 self.restyle();
1113 }
1114
1115 pub fn restyle(&self) {
1118 if self.inner.highlighter.borrow().is_some() {
1119 self.inner.highlight(None);
1120 } else {
1121 self.inner.apply_styles(Vec::new(), None, None);
1122 }
1123 }
1124
1125 pub fn style_at(&self, offset: usize) -> TextStyle {
1127 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1129 let text = storage.string().to_string();
1130 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1131 let mut style = TextStyle::default();
1132 unsafe {
1134 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1135 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1136 style.color = at(NSForegroundColorAttributeName)
1137 .and_then(|c| c.downcast::<NSColor>().ok())
1138 .and_then(|c| Color::from_ns(&c))
1139 .filter(|c| *c != Color::Primary);
1140 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1141 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1142 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1143 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1144 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1145 }
1146 style.underline = at(NSUnderlineStyleAttributeName)
1147 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1148 .is_some_and(|n| n.integerValue() != 0);
1149 }
1150 style
1151 }
1152
1153 pub fn set_rich(&self, rich: bool) {
1160 let v = &self.inner.view;
1161 v.setRichText(rich);
1162 v.setImportsGraphics(rich);
1163 v.setUsesFontPanel(rich);
1164 v.setUsesRuler(rich);
1165 if !rich {
1166 v.setUsesInspectorBar(false);
1167 v.setRulerVisible(false);
1168 }
1169 }
1170
1171 pub fn is_rich(&self) -> bool {
1173 self.inner.view.isRichText()
1174 }
1175
1176 pub fn set_format_bar(&self, shown: bool) {
1179 self.inner.view.setUsesInspectorBar(shown);
1180 }
1181
1182 pub fn has_format_bar(&self) -> bool {
1184 self.inner.view.usesInspectorBar()
1185 }
1186
1187 pub fn set_ruler_visible(&self, shown: bool) {
1191 self.inner.view.setRulerVisible(shown);
1192 }
1193
1194 pub fn is_ruler_visible(&self) -> bool {
1196 self.inner.view.isRulerVisible()
1197 }
1198
1199 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1200 let storage = unsafe { self.inner.view.textStorage() }?;
1202 let len = storage.length();
1203 Some((storage, NSRange::new(0, len)))
1204 }
1205
1206 pub fn rtf(&self) -> Vec<u8> {
1209 let Some((storage, range)) = self.whole() else { return Vec::new() };
1210 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1211 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1213 data.map(|d| d.to_vec()).unwrap_or_default()
1214 }
1215
1216 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1220 let data = objc2_foundation::NSData::with_bytes(rtf);
1221 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1223 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1224 self.load(text)
1225 }
1226
1227 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1228 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1229 self.inner.quiet.set(true);
1230 storage.setAttributedString(&text);
1231 self.inner.quiet.set(false);
1232 self.clear_undo();
1233 true
1234 }
1235
1236 pub fn html(&self) -> String {
1239 let Some((storage, range)) = self.whole() else { return String::new() };
1240 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1243 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1244 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1245 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1246 };
1247 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1248 }
1249
1250 pub fn set_html(&self, html: &str) -> bool {
1254 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1255 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1257 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1258 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1260 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1261 &[kind, utf8.as_ref()],
1262 );
1263 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1264 };
1265 self.load(text)
1266 }
1267
1268 pub fn font_size(&self) -> Option<f64> {
1270 self.inner.view.font().map(|f| f.pointSize())
1271 }
1272
1273 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1275 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1276 }
1277
1278 pub fn set_spell_checking(&self, on: bool) {
1280 self.inner.view.setContinuousSpellCheckingEnabled(on);
1281 }
1282
1283 pub fn set_grammar_checking(&self, on: bool) {
1285 self.inner.view.setGrammarCheckingEnabled(on);
1286 }
1287
1288 pub fn set_code_input(&self, code: bool) {
1293 let view = &self.inner.view;
1294 view.setAutomaticQuoteSubstitutionEnabled(!code);
1295 view.setAutomaticDashSubstitutionEnabled(!code);
1296 view.setAutomaticTextReplacementEnabled(!code);
1297 view.setAutomaticSpellingCorrectionEnabled(!code);
1298 view.setContinuousSpellCheckingEnabled(!code);
1299 view.setSmartInsertDeleteEnabled(!code);
1300 }
1301
1302 pub fn set_accepts_tab(&self, accepts: bool) {
1304 crate::keys::set_accepts_tab(self.inner.id, accepts);
1305 }
1306
1307 pub fn show_find(&self) {
1310 let item = objc2_app_kit::NSMenuItem::new(mtm());
1312 item.setTag(1);
1313 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1314 }
1315
1316 pub fn set_wraps(&self, wraps: bool) {
1319 let (view, scroll) = (&self.inner.view, &self.inner.scroll);
1320 let Some(container) = (unsafe { view.textContainer() }) else { return };
1322 if container.widthTracksTextView() == wraps {
1323 return;
1324 }
1325 let width = scroll.contentSize().width;
1326 scroll.setHasHorizontalScroller(!wraps);
1327 view.setHorizontallyResizable(!wraps);
1328 container.setWidthTracksTextView(wraps);
1329 if wraps {
1330 let mut frame = view.frame();
1332 frame.size.width = width;
1333 view.setFrame(frame);
1334 container.setContainerSize(NSSize::new(width, f64::MAX));
1335 } else {
1336 container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
1338 view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
1339 }
1340 view.sizeToFit();
1341 view.setNeedsDisplay(true);
1342 }
1343
1344 pub fn wraps(&self) -> bool {
1346 unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
1348 }
1349
1350 pub fn is_find_visible(&self) -> bool {
1352 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1353 }
1354
1355 pub fn can_undo(&self) -> bool {
1357 self.inner.undo.borrow().canUndo()
1358 }
1359
1360 pub fn undo(&self) {
1362 let undo = self.undo_manager();
1363 if undo.canUndo() {
1364 undo.undo();
1365 }
1366 }
1367
1368 pub fn drain_events(&self) -> Vec<TextEvent> {
1370 self.inner.events.borrow_mut().drain(..).collect()
1371 }
1372
1373 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1376 self.inner.scroll.clone()
1377 }
1378
1379 pub fn text_view(&self) -> Retained<NSTextView> {
1381 Retained::into_super(self.inner.view.clone())
1382 }
1383}
1384
1385#[cfg(test)]
1386mod tests {
1387 use super::{bytes_to_utf16, utf16_to_bytes};
1388
1389 #[test]
1390 fn offsets_round_trip() {
1391 let t = "a東京😀b";
1392 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1394 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1395 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1396 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1397 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1398 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1399 }
1400}