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(ferrokitCompleteNow:))]
138 fn complete_now(&self, _sender: Option<&AnyObject>) {
139 crate::boundary::guarded("a text view (complete_now)", (), || {
140 if self.hasMarkedText() || self.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
141 return;
142 }
143 objc2::rc::autoreleasepool(|_| unsafe { self.complete(None) });
145 })
146 }
147
148 #[unsafe(method(rangeForUserCompletion))]
150 fn range_for_user_completion(&self) -> NSRange {
151 crate::boundary::guarded("a text view (range_for_user_completion)", NSRange::new(0, 0), || {
152 if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
153 return range;
154 }
155 unsafe { msg_send![super(self), rangeForUserCompletion] }
156 })
157 }
158
159 #[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
163 fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
164 crate::boundary::guarded("a text view (insert_completion)", (), || {
165 if self.data().is_some_and(|d| d.has_completer()) {
166 let clicked = || {
167 let mtm = MainThreadMarker::from(self);
168 objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
169 use objc2_app_kit::NSEventType as T;
170 matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
171 })
172 };
173 let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
174 if !chosen {
175 return;
176 }
177 }
178 let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
179 })
180 }
181 }
182);
183
184impl HostTextView {
185 fn data(&self) -> Option<Rc<dyn Data>> {
186 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
187 }
188
189 fn complete_soon(&self) {
196 let sel = objc2::sel!(ferrokitCompleteNow:);
197 unsafe {
200 let () = msg_send![objc2::class!(NSObject), cancelPreviousPerformRequestsWithTarget: self, selector: sel, object: Option::<&AnyObject>::None];
201 let () = msg_send![self, performSelector: sel, withObject: Option::<&AnyObject>::None, afterDelay: 0.0f64];
202 }
203 }
204
205 fn composition_changed(&self) {
207 let composing = self.hasMarkedText();
208 let was = self.ivars().composing.replace(composing);
209 let Some(data) = self.data() else { return };
210 if composing {
211 let range = self.markedRange();
212 let marked = self.string().to_string();
213 let marked = utf16_slice(&marked, range.location, range.length);
214 data.push(TextEvent::Composition(Some(marked)));
215 } else if was {
216 data.push(TextEvent::Composition(None));
217 }
218 }
219}
220
221struct DelegateIvars {
222 data: RefCell<Option<Weak<dyn Data>>>,
223}
224
225define_class!(
226 #[unsafe(super(NSObject))]
227 #[thread_kind = MainThreadOnly]
228 #[name = "FerrokitCoreTextDelegate"]
229 #[ivars = DelegateIvars]
230 struct Delegate;
231
232 unsafe impl NSObjectProtocol for Delegate {}
233
234 unsafe impl NSTextDelegate for Delegate {
235 #[unsafe(method(textDidChange:))]
236 fn text_did_change(&self, _notification: &NSNotification) {
237 crate::boundary::guarded("a text view (text_did_change)", (), || {
238 let Some(data) = self.data() else { return };
239 data.finish_highlight();
243 if !data.quiet() {
244 data.push(TextEvent::Changed);
245 }
246 })
247 }
248 }
249
250 unsafe impl NSTextStorageDelegate for Delegate {
253 #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
259 fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
260 crate::boundary::guarded("a text view (will_process_editing)", (), || {
261 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
262 return;
263 }
264 let Some(data) = self.data().filter(|d| !d.composing()) else { return };
265 if data.highlight(Some(range)) {
266 let weak = self.ivars().data.borrow().clone();
269 let block = block2::RcBlock::new(move || {
270 if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
271 objc2::rc::autoreleasepool(|_| d.finish_highlight());
272 }
273 });
274 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
275 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
277 main.wake_up();
278 }
279 })
280 }
281
282 #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
283 fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
284 crate::boundary::guarded("a text view (did_process_editing)", (), || {
285 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
286 return;
287 }
288 let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
289 data.push(TextEvent::Changed);
290 })
291 }
292 }
293
294 unsafe impl NSTextViewDelegate for Delegate {
295 #[unsafe(method(textViewDidChangeSelection:))]
296 fn selection_did_change(&self, notification: &NSNotification) {
297 crate::boundary::guarded("a text view (selection_did_change)", (), || {
298 let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
299 let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
300 let text = view.string().to_string();
301 let r = view.selectedRange();
302 data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
303 })
304 }
305
306 #[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
308 fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
309 crate::boundary::guarded("a text view (completions)", None, || {
310 Some(self.completion_words(words, index))
311 })
312 }
313
314 #[unsafe(method_id(undoManagerForTextView:))]
317 fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
318 crate::boundary::guarded("a text view (undo_manager_for)", None, || {
319 self.data().map(|d| d.undo_manager())
320 })
321 }
322 }
323);
324
325impl Delegate {
326 fn data(&self) -> Option<Rc<dyn Data>> {
327 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
328 }
329
330 fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
331 let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
332 let items = data.complete().map(|(_, items)| items).unwrap_or_default();
333 if !index.is_null() {
334 unsafe { *index = if items.is_empty() { -1 } else { 0 } };
336 }
337 data.offered(&items);
338 let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
339 NSArray::from_retained_slice(&items)
340 }
341}
342
343pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
345 let (mut units, mut start, mut end) = (0usize, None, None);
346 for (byte, c) in text.char_indices() {
347 if start.is_none() && units >= location {
348 start = Some(byte);
349 }
350 if end.is_none() && units >= location + length {
351 end = Some(byte);
352 }
353 units += c.len_utf16();
354 }
355 let start = start.unwrap_or(text.len());
356 start..end.unwrap_or(text.len()).max(start)
357}
358
359pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
362 let to_units = |byte: usize| -> usize {
363 let byte = byte.min(text.len());
364 let mut b = byte;
365 while !text.is_char_boundary(b) {
366 b -= 1;
367 }
368 text[..b].encode_utf16().count()
369 };
370 let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
371 (s, e - s)
372}
373
374fn utf16_slice(text: &str, location: usize, length: usize) -> String {
375 text[utf16_to_bytes(text, location, length)].to_string()
376}
377
378struct Inner {
379 id: ViewId,
380 events: RefCell<VecDeque<TextEvent>>,
381 quiet: Cell<bool>,
382 mounted: Cell<bool>,
383 undo: RefCell<Retained<NSUndoManager>>,
384 shared: Cell<bool>,
386 scroll: Retained<NSScrollView>,
387 view: Retained<HostTextView>,
388 _delegate: Retained<Delegate>,
389 font: RefCell<Retained<NSFont>>,
391 highlighter: RefCell<Option<Rc<Highlighter>>>,
392 completer: RefCell<Option<Rc<Completer>>>,
393 offered: RefCell<Vec<String>>,
395 styling: Cell<bool>,
397 shown: RefCell<Option<(usize, Runs)>>,
400 deferred: Cell<Option<(usize, usize)>>,
402}
403
404type Highlighter = dyn Fn(&str) -> Runs;
405type Runs = Vec<(Range<usize>, TextStyle)>;
406
407#[derive(Debug, Clone, Copy, PartialEq)]
411pub enum Color {
412 Primary,
414 Secondary,
416 Tertiary,
418 Quaternary,
420 Fill,
423 SecondaryFill,
425 TertiaryFill,
427 QuaternaryFill,
430 Accent,
432 Link,
434 Red,
436 Orange,
438 Yellow,
440 Green,
442 Mint,
444 Teal,
446 Cyan,
448 Blue,
450 Indigo,
452 Purple,
454 Pink,
456 Brown,
458 Gray,
460 Background,
462 WindowBackground,
464 ControlBackground,
466 Separator,
468 Clear,
470 Rgb(f64, f64, f64),
472 Rgba(f64, f64, f64, f64),
474}
475
476impl Color {
477 const NAMED: [Color; 28] = [
478 Color::Primary,
479 Color::Secondary,
480 Color::Tertiary,
481 Color::Quaternary,
482 Color::Fill,
483 Color::SecondaryFill,
484 Color::TertiaryFill,
485 Color::QuaternaryFill,
486 Color::Accent,
487 Color::Link,
488 Color::Red,
489 Color::Orange,
490 Color::Yellow,
491 Color::Green,
492 Color::Mint,
493 Color::Teal,
494 Color::Cyan,
495 Color::Blue,
496 Color::Indigo,
497 Color::Purple,
498 Color::Pink,
499 Color::Brown,
500 Color::Gray,
501 Color::Background,
502 Color::WindowBackground,
503 Color::ControlBackground,
504 Color::Separator,
505 Color::Clear,
506 ];
507
508 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
510 Color::Rgb(r, g, b)
511 }
512
513 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
515 Color::Rgba(r, g, b, a)
516 }
517
518 pub fn hex(hex: &str) -> Color {
521 let h = hex.trim_start_matches('#');
522 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);
523 match h.len() {
524 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
525 6 => Color::Rgb(byte(0), byte(2), byte(4)),
526 _ => Color::Rgb(0.0, 0.0, 0.0),
527 }
528 }
529
530 pub fn opacity(self, opacity: f64) -> Color {
532 match self.components() {
533 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
534 None => self,
535 }
536 }
537
538 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
541 match self {
542 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
543 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
544 _ => {
545 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
546 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
547 }
548 }
549 }
550
551 pub fn ns(self) -> Retained<NSColor> {
553 match self {
554 Color::Primary => NSColor::textColor(),
555 Color::Secondary => NSColor::secondaryLabelColor(),
556 Color::Tertiary => NSColor::tertiaryLabelColor(),
557 Color::Quaternary => NSColor::quaternaryLabelColor(),
558 Color::Fill => NSColor::systemFillColor(),
559 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
560 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
561 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
562 Color::Accent => NSColor::controlAccentColor(),
563 Color::Link => NSColor::linkColor(),
564 Color::Red => NSColor::systemRedColor(),
565 Color::Orange => NSColor::systemOrangeColor(),
566 Color::Yellow => NSColor::systemYellowColor(),
567 Color::Green => NSColor::systemGreenColor(),
568 Color::Mint => NSColor::systemMintColor(),
569 Color::Teal => NSColor::systemTealColor(),
570 Color::Cyan => NSColor::systemCyanColor(),
571 Color::Blue => NSColor::systemBlueColor(),
572 Color::Indigo => NSColor::systemIndigoColor(),
573 Color::Purple => NSColor::systemPurpleColor(),
574 Color::Pink => NSColor::systemPinkColor(),
575 Color::Brown => NSColor::systemBrownColor(),
576 Color::Gray => NSColor::systemGrayColor(),
577 Color::Background => NSColor::textBackgroundColor(),
578 Color::WindowBackground => NSColor::windowBackgroundColor(),
579 Color::ControlBackground => NSColor::controlBackgroundColor(),
580 Color::Separator => NSColor::separatorColor(),
581 Color::Clear => NSColor::clearColor(),
582 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
583 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
584 }
585 }
586
587 pub fn from_ns(color: &NSColor) -> Option<Color> {
590 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
591 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
592 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
593 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
594 })
595 }
596}
597
598#[derive(Debug, Clone, Copy, Default, PartialEq)]
601pub struct TextStyle {
602 pub color: Option<Color>,
604 pub background: Option<Color>,
606 pub bold: bool,
608 pub italic: bool,
610 pub underline: bool,
612}
613
614impl TextStyle {
615 pub fn new() -> Self {
617 Self::default()
618 }
619
620 pub fn color(mut self, color: Color) -> Self {
622 self.color = Some(color);
623 self
624 }
625
626 pub fn background(mut self, color: Color) -> Self {
628 self.background = Some(color);
629 self
630 }
631
632 pub fn bold(mut self) -> Self {
634 self.bold = true;
635 self
636 }
637
638 pub fn italic(mut self) -> Self {
640 self.italic = true;
641 self
642 }
643
644 pub fn underline(mut self) -> Self {
646 self.underline = true;
647 self
648 }
649}
650
651fn utf16_map(text: &str) -> Vec<usize> {
654 let mut map = Vec::with_capacity(text.len() + 1);
655 let mut units = 0;
656 for c in text.chars() {
657 map.extend(std::iter::repeat_n(units, c.len_utf8()));
658 units += c.len_utf16();
659 }
660 map.push(units);
661 map
662}
663
664impl Inner {
665 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
673 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
675 let text = storage.string().to_string();
676 let map = utf16_map(&text);
677 let len16 = *map.last().unwrap_or(&0);
678 let shown = self.shown.borrow_mut().take();
679 let region = match (shown, edited) {
682 (Some((old_len, old)), Some(edited)) => {
683 let delta = text.len() as isize - old_len as isize;
684 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
685 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
686 let suffix = old[prefix..]
687 .iter()
688 .rev()
689 .zip(runs[prefix..].iter().rev())
690 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
691 .count();
692 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
693 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
694 let clamp = |i: isize| (i.max(0) as usize).min(text.len());
698 let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
699 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))]);
700 let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
701 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
702 lo..hi
703 }
704 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
705 };
706 let mut deferred = false;
712 let region = match edited {
713 Some(e) => {
714 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
715 if inside != region {
716 deferred = self.deferred.get().is_none();
717 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
718 }
719 inside.start..inside.end.max(inside.start)
720 }
721 None => region,
722 };
723 let font = self.font.borrow().clone();
724 self.styling.set(true);
725 unsafe {
728 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
729 if edited.is_none() {
730 storage.beginEditing();
731 }
732 let base = objc2_foundation::NSDictionary::from_retained_objects(
733 &[NSFontAttributeName, NSForegroundColorAttributeName],
734 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
735 );
736 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
737 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
738 for (range, style) in &runs {
739 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
740 if start >= end {
741 continue;
742 }
743 let r = NSRange::new(start, end - start);
744 if let Some(c) = style.color {
745 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
746 }
747 if let Some(c) = style.background {
748 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
749 }
750 if style.bold || style.italic {
751 let mut f = font.clone();
752 if style.bold {
753 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
754 }
755 if style.italic {
756 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
757 }
758 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
759 }
760 if style.underline {
761 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
762 }
763 }
764 if edited.is_none() {
765 storage.endEditing();
766 }
767 }
768 self.styling.set(false);
769 *self.shown.borrow_mut() = Some((text.len(), runs));
770 if edited.is_some() {
778 return deferred;
779 }
780 unsafe {
782 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
783 let typing = objc2_foundation::NSDictionary::from_retained_objects(
784 &[NSFontAttributeName, NSForegroundColorAttributeName],
785 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
786 );
787 self.view.setTypingAttributes(&typing);
788 }
789 false
790 }
791}
792
793impl Data for Inner {
794 fn push(&self, event: TextEvent) {
795 let mut events = self.events.borrow_mut();
796 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
799 return;
800 }
801 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
803 events.pop_back();
804 }
805 events.push_back(event);
806 drop(events);
807 crate::request_redraw();
808 }
809
810 fn quiet(&self) -> bool {
811 self.quiet.get()
812 }
813
814 fn complete(&self) -> Option<(NSRange, Vec<String>)> {
815 let f = self.completer.borrow().clone()?;
816 let text = self.view.string().to_string();
817 let sel = self.view.selectedRange();
818 let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
819 let c = f(&text, caret)?;
820 let start = c.range.start.min(caret);
821 let (location, length) = bytes_to_utf16(&text, start..caret);
822 Some((NSRange::new(location, length), c.items))
823 }
824
825 fn has_completer(&self) -> bool {
826 self.completer.borrow().is_some()
827 }
828
829 fn offered(&self, items: &[String]) {
830 *self.offered.borrow_mut() = items.to_vec();
831 }
832
833 fn composing(&self) -> bool {
834 self.view.hasMarkedText()
835 }
836
837 fn undo_manager(&self) -> Retained<NSUndoManager> {
838 self.undo.borrow().clone()
839 }
840
841 fn highlight(&self, edited: Option<NSRange>) -> bool {
842 if self.styling.get() {
843 return false;
844 }
845 let Some(f) = self.highlighter.borrow().clone() else { return false };
846 let runs = f(&self.view.string().to_string());
847 self.apply_styles(runs, edited, None)
848 }
849
850 fn finish_highlight(&self) {
851 let Some(span) = self.deferred.take() else { return };
852 if self.styling.get() || self.view.hasMarkedText() {
853 return;
854 }
855 let Some(f) = self.highlighter.borrow().clone() else { return };
856 let runs = f(&self.view.string().to_string());
857 self.apply_styles(runs, None, Some(span));
858 }
859}
860
861impl Drop for ViewIvars {
862 fn drop(&mut self) {
863 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
864 }
865}
866
867impl Drop for DelegateIvars {
868 fn drop(&mut self) {
869 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
870 }
871}
872
873impl Drop for Inner {
874 fn drop(&mut self) {
875 self.view.setDelegate(None);
877 if let Some(storage) = unsafe { self.view.textStorage() } {
878 storage.setDelegate(None);
879 }
880 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
881 crate::keys::set_accepts_tab(self.id, false);
882 if self.mounted.get() {
883 crate::unmount(self.id);
884 }
885 }
886}
887
888#[derive(Clone)]
890pub struct TextModel {
891 inner: Rc<Inner>,
892}
893
894impl std::fmt::Debug for TextModel {
895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
896 write!(f, "TextModel({:?})", self.inner.id)
897 }
898}
899
900impl TextModel {
901 pub fn new(id: ViewId, text: &str) -> Self {
905 let mtm = mtm();
906 let size = NSSize::new(400.0, 300.0);
907 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
908 scroll.setHasVerticalScroller(true);
909 scroll.setAutohidesScrollers(true);
910 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
911
912 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
915 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
916 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
917 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
918 view.setMinSize(NSSize::new(0.0, size.height));
919 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
920 view.setVerticallyResizable(true);
921 view.setHorizontallyResizable(false);
922 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
923 if let Some(container) = unsafe { view.textContainer() } {
925 container.setContainerSize(NSSize::new(size.width, f64::MAX));
926 container.setWidthTracksTextView(true);
927 }
928 view.setRichText(false);
929 view.setImportsGraphics(false);
930 view.setAllowsUndo(true);
931 view.setUsesFindBar(true);
932 view.setContinuousSpellCheckingEnabled(true);
933 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
934 view.setTextContainerInset(NSSize::new(4.0, 6.0));
935 view.setString(&NSString::from_str(text));
936 scroll.setDocumentView(Some(&view));
937
938 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
939 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
940
941 let inner = Rc::new(Inner {
942 id,
943 events: RefCell::new(VecDeque::new()),
944 quiet: Cell::new(false),
945 mounted: Cell::new(false),
946 undo: RefCell::new(NSUndoManager::new(mtm)),
947 shared: Cell::new(false),
948 scroll,
949 view: view.clone(),
950 _delegate: delegate.clone(),
951 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
952 highlighter: RefCell::new(None),
953 completer: RefCell::new(None),
954 offered: RefCell::new(Vec::new()),
955 styling: Cell::new(false),
956 shown: RefCell::new(None),
957 deferred: Cell::new(None),
958 });
959 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
960 *view.ivars().data.borrow_mut() = Some(weak.clone());
961 *delegate.ivars().data.borrow_mut() = Some(weak);
962 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
964 if let Some(storage) = unsafe { view.textStorage() } {
965 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
967 }
968 crate::keys::set_accepts_tab(id, true);
969 Self { inner }
970 }
971
972 pub fn id(&self) -> ViewId {
974 self.inner.id
975 }
976
977 pub fn ensure_mounted(&self) {
980 if !self.inner.mounted.get() && crate::is_attached() {
981 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
982 self.inner.mounted.set(true);
983 }
984 }
985
986 pub fn text(&self) -> String {
988 self.inner.view.string().to_string()
989 }
990
991 pub fn set_text(&self, text: &str) {
994 self.inner.quiet.set(true);
995 self.inner.view.setString(&NSString::from_str(text));
996 self.inner.quiet.set(false);
997 self.clear_undo();
998 }
999
1000 fn clear_undo(&self) {
1003 let undo = self.inner.undo.borrow();
1004 if self.inner.shared.get() {
1005 unsafe {
1007 undo.removeAllActionsWithTarget(&self.inner.view);
1008 if let Some(storage) = self.inner.view.textStorage() {
1009 undo.removeAllActionsWithTarget(&storage);
1010 }
1011 }
1012 } else {
1013 undo.removeAllActions();
1014 }
1015 }
1016
1017 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
1022 self.clear_undo();
1023 let mtm = MainThreadMarker::from(&*self.inner.view);
1024 let next = match manager {
1025 Some(m) => m.retain(),
1026 None => NSUndoManager::new(mtm),
1027 };
1028 *self.inner.undo.borrow_mut() = next;
1029 self.inner.shared.set(manager.is_some());
1030 }
1031
1032 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
1034 self.inner.undo.borrow().clone()
1035 }
1036
1037 pub fn replace_selection(&self, text: &str) {
1039 let view = &self.inner.view;
1040 let range = view.selectedRange();
1041 let string = NSString::from_str(text);
1042 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1043 view.replaceCharactersInRange_withString(range, &string);
1044 view.didChangeText();
1045 }
1046 }
1047
1048 pub fn selection(&self) -> Range<usize> {
1050 let r = self.inner.view.selectedRange();
1051 utf16_to_bytes(&self.text(), r.location, r.length)
1052 }
1053
1054 pub fn set_selection(&self, range: Range<usize>) {
1056 let (location, length) = bytes_to_utf16(&self.text(), range);
1057 self.inner.quiet.set(true);
1058 self.inner.view.setSelectedRange(NSRange::new(location, length));
1059 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1060 self.inner.quiet.set(false);
1061 }
1062
1063 pub fn composition(&self) -> Option<String> {
1065 let view = &self.inner.view;
1066 view.hasMarkedText().then(|| {
1067 let r = view.markedRange();
1068 utf16_slice(&view.string().to_string(), r.location, r.length)
1069 })
1070 }
1071
1072 pub fn set_editable(&self, editable: bool) {
1074 self.inner.view.setEditable(editable);
1075 }
1076
1077 pub fn is_editable(&self) -> bool {
1079 self.inner.view.isEditable()
1080 }
1081
1082 pub fn set_font(&self, name: Option<&str>, size: f64) {
1084 let font = match name {
1085 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1086 None => Some(NSFont::systemFontOfSize(size)),
1087 };
1088 if let Some(font) = font {
1089 self.inner.view.setFont(Some(&font));
1090 *self.inner.font.borrow_mut() = font;
1091 self.inner.highlight(None);
1092 }
1093 }
1094
1095 pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1102 *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1103 }
1104
1105 pub fn complete(&self) {
1107 unsafe { self.inner.view.complete(None) };
1109 }
1110
1111 pub fn offered_completions(&self) -> Vec<String> {
1113 self.inner.offered.borrow().clone()
1114 }
1115
1116 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1122 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1123 self.restyle();
1124 }
1125
1126 pub fn restyle(&self) {
1129 if self.inner.highlighter.borrow().is_some() {
1130 self.inner.highlight(None);
1131 } else {
1132 self.inner.apply_styles(Vec::new(), None, None);
1133 }
1134 }
1135
1136 pub fn style_at(&self, offset: usize) -> TextStyle {
1138 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1140 let text = storage.string().to_string();
1141 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1142 let mut style = TextStyle::default();
1143 unsafe {
1145 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1146 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1147 style.color = at(NSForegroundColorAttributeName)
1148 .and_then(|c| c.downcast::<NSColor>().ok())
1149 .and_then(|c| Color::from_ns(&c))
1150 .filter(|c| *c != Color::Primary);
1151 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1152 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1153 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1154 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1155 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1156 }
1157 style.underline = at(NSUnderlineStyleAttributeName)
1158 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1159 .is_some_and(|n| n.integerValue() != 0);
1160 }
1161 style
1162 }
1163
1164 pub fn set_rich(&self, rich: bool) {
1171 let v = &self.inner.view;
1172 v.setRichText(rich);
1173 v.setImportsGraphics(rich);
1174 v.setUsesFontPanel(rich);
1175 v.setUsesRuler(rich);
1176 if !rich {
1177 v.setUsesInspectorBar(false);
1178 v.setRulerVisible(false);
1179 }
1180 }
1181
1182 pub fn is_rich(&self) -> bool {
1184 self.inner.view.isRichText()
1185 }
1186
1187 pub fn set_format_bar(&self, shown: bool) {
1190 self.inner.view.setUsesInspectorBar(shown);
1191 }
1192
1193 pub fn has_format_bar(&self) -> bool {
1195 self.inner.view.usesInspectorBar()
1196 }
1197
1198 pub fn set_ruler_visible(&self, shown: bool) {
1202 self.inner.view.setRulerVisible(shown);
1203 }
1204
1205 pub fn is_ruler_visible(&self) -> bool {
1207 self.inner.view.isRulerVisible()
1208 }
1209
1210 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1211 let storage = unsafe { self.inner.view.textStorage() }?;
1213 let len = storage.length();
1214 Some((storage, NSRange::new(0, len)))
1215 }
1216
1217 pub fn rtf(&self) -> Vec<u8> {
1220 let Some((storage, range)) = self.whole() else { return Vec::new() };
1221 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1222 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1224 data.map(|d| d.to_vec()).unwrap_or_default()
1225 }
1226
1227 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1231 let data = objc2_foundation::NSData::with_bytes(rtf);
1232 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1234 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1235 self.load(text)
1236 }
1237
1238 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1239 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1240 self.inner.quiet.set(true);
1241 storage.setAttributedString(&text);
1242 self.inner.quiet.set(false);
1243 self.clear_undo();
1244 true
1245 }
1246
1247 pub fn html(&self) -> String {
1250 let Some((storage, range)) = self.whole() else { return String::new() };
1251 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1254 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1255 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1256 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1257 };
1258 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1259 }
1260
1261 pub fn set_html(&self, html: &str) -> bool {
1265 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1266 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1268 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1269 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1271 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1272 &[kind, utf8.as_ref()],
1273 );
1274 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1275 };
1276 self.load(text)
1277 }
1278
1279 pub fn font_size(&self) -> Option<f64> {
1281 self.inner.view.font().map(|f| f.pointSize())
1282 }
1283
1284 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1286 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1287 }
1288
1289 pub fn set_spell_checking(&self, on: bool) {
1291 self.inner.view.setContinuousSpellCheckingEnabled(on);
1292 }
1293
1294 pub fn set_grammar_checking(&self, on: bool) {
1296 self.inner.view.setGrammarCheckingEnabled(on);
1297 }
1298
1299 pub fn set_code_input(&self, code: bool) {
1304 let view = &self.inner.view;
1305 view.setAutomaticQuoteSubstitutionEnabled(!code);
1306 view.setAutomaticDashSubstitutionEnabled(!code);
1307 view.setAutomaticTextReplacementEnabled(!code);
1308 view.setAutomaticSpellingCorrectionEnabled(!code);
1309 view.setContinuousSpellCheckingEnabled(!code);
1310 view.setSmartInsertDeleteEnabled(!code);
1311 }
1312
1313 pub fn set_accepts_tab(&self, accepts: bool) {
1315 crate::keys::set_accepts_tab(self.inner.id, accepts);
1316 }
1317
1318 pub fn show_find(&self) {
1321 let item = objc2_app_kit::NSMenuItem::new(mtm());
1323 item.setTag(1);
1324 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1325 }
1326
1327 pub fn set_wraps(&self, wraps: bool) {
1330 let (view, scroll) = (&self.inner.view, &self.inner.scroll);
1331 let Some(container) = (unsafe { view.textContainer() }) else { return };
1333 if container.widthTracksTextView() == wraps {
1334 return;
1335 }
1336 let width = scroll.contentSize().width;
1337 scroll.setHasHorizontalScroller(!wraps);
1338 view.setHorizontallyResizable(!wraps);
1339 container.setWidthTracksTextView(wraps);
1340 if wraps {
1341 let mut frame = view.frame();
1343 frame.size.width = width;
1344 view.setFrame(frame);
1345 container.setContainerSize(NSSize::new(width, f64::MAX));
1346 } else {
1347 container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
1349 view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
1350 }
1351 view.sizeToFit();
1352 view.setNeedsDisplay(true);
1353 }
1354
1355 pub fn wraps(&self) -> bool {
1357 unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
1359 }
1360
1361 pub fn is_find_visible(&self) -> bool {
1363 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1364 }
1365
1366 pub fn can_undo(&self) -> bool {
1368 self.inner.undo.borrow().canUndo()
1369 }
1370
1371 pub fn undo(&self) {
1373 let undo = self.undo_manager();
1374 if undo.canUndo() {
1375 undo.undo();
1376 }
1377 }
1378
1379 pub fn drain_events(&self) -> Vec<TextEvent> {
1381 self.inner.events.borrow_mut().drain(..).collect()
1382 }
1383
1384 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1387 self.inner.scroll.clone()
1388 }
1389
1390 pub fn text_view(&self) -> Retained<NSTextView> {
1392 Retained::into_super(self.inner.view.clone())
1393 }
1394}
1395
1396#[cfg(test)]
1397mod tests {
1398 use super::{bytes_to_utf16, utf16_to_bytes};
1399
1400 #[test]
1401 fn offsets_round_trip() {
1402 let t = "a東京😀b";
1403 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1405 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1406 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1407 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1408 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1409 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1410 }
1411}