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#[doc(hidden)]
42#[derive(Debug, Clone, PartialEq)]
44pub enum TextEvent {
45 Changed,
48 Selection(Range<usize>),
50 Composition(Option<String>),
52}
53
54#[derive(Debug, Clone, PartialEq, Default)]
58pub struct Completion {
59 pub range: Range<usize>,
61 pub items: Vec<String>,
63}
64
65type Completer = dyn Fn(&str, usize) -> Option<Completion>;
66
67const RETURN_MOVEMENT: isize = 0x10;
69const TAB_MOVEMENT: isize = 0x11;
70const OTHER_MOVEMENT: isize = 0;
71
72trait Data {
73 fn push(&self, event: TextEvent);
74 fn complete(&self) -> Option<(NSRange, Vec<String>)>;
76 fn has_completer(&self) -> bool;
77 fn quiet(&self) -> bool;
78 fn composing(&self) -> bool;
79 fn undo_manager(&self) -> Retained<NSUndoManager>;
80 fn offered(&self, items: &[String]);
82 fn highlight(&self, edited: Option<NSRange>) -> bool;
85 fn finish_highlight(&self);
86}
87
88struct ViewIvars {
89 data: RefCell<Option<Weak<dyn Data>>>,
90 composing: Cell<bool>,
91}
92
93define_class!(
94 #[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
96 #[thread_kind = MainThreadOnly]
97 #[name = "FerrokitCoreTextView"]
98 #[ivars = ViewIvars]
99 struct HostTextView;
100
101 impl HostTextView {
102 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
103 fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
104 crate::boundary::guarded("a text view (set_marked_text)", (), || {
105 let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
106 self.composition_changed();
107 })
108 }
109
110 #[unsafe(method(unmarkText))]
111 fn unmark_text(&self) {
112 crate::boundary::guarded("a text view (unmark_text)", (), || {
113 let () = unsafe { msg_send![super(self), unmarkText] };
114 self.composition_changed();
115 })
116 }
117
118 #[unsafe(method(insertText:replacementRange:))]
119 fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
120 crate::boundary::guarded("a text view (insert_text)", (), || {
121 let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
122 self.composition_changed();
123 let typed = string.downcast_ref::<NSString>().map(|s| s.to_string()).unwrap_or_default();
125 let mut chars = typed.chars();
126 if let (Some(c), None) = (chars.next(), chars.next())
127 && (c.is_alphanumeric() || c == '_' || c == '.')
128 && !self.hasMarkedText()
129 && self.data().is_some_and(|d| d.has_completer())
130 {
131 self.complete_soon();
132 }
133 })
134 }
135
136 #[unsafe(method(ferrokitCompleteNow:))]
139 fn complete_now(&self, _sender: Option<&AnyObject>) {
140 crate::boundary::guarded("a text view (complete_now)", (), || {
141 if self.hasMarkedText() || self.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
142 return;
143 }
144 objc2::rc::autoreleasepool(|_| unsafe { self.complete(None) });
146 })
147 }
148
149 #[unsafe(method(rangeForUserCompletion))]
151 fn range_for_user_completion(&self) -> NSRange {
152 crate::boundary::guarded("a text view (range_for_user_completion)", NSRange::new(0, 0), || {
153 if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
154 return range;
155 }
156 unsafe { msg_send![super(self), rangeForUserCompletion] }
157 })
158 }
159
160 #[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
164 fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
165 crate::boundary::guarded("a text view (insert_completion)", (), || {
166 if self.data().is_some_and(|d| d.has_completer()) {
167 let clicked = || {
168 let mtm = MainThreadMarker::from(self);
169 objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
170 use objc2_app_kit::NSEventType as T;
171 matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
172 })
173 };
174 let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
175 if !chosen {
176 return;
177 }
178 }
179 let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
180 })
181 }
182 }
183);
184
185impl HostTextView {
186 fn data(&self) -> Option<Rc<dyn Data>> {
187 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
188 }
189
190 fn complete_soon(&self) {
197 let sel = objc2::sel!(ferrokitCompleteNow:);
198 unsafe {
201 let () = msg_send![objc2::class!(NSObject), cancelPreviousPerformRequestsWithTarget: self, selector: sel, object: Option::<&AnyObject>::None];
202 let () = msg_send![self, performSelector: sel, withObject: Option::<&AnyObject>::None, afterDelay: 0.0f64];
203 }
204 }
205
206 fn composition_changed(&self) {
208 let composing = self.hasMarkedText();
209 let was = self.ivars().composing.replace(composing);
210 let Some(data) = self.data() else { return };
211 if composing {
212 let range = self.markedRange();
213 let marked = self.string().to_string();
214 let marked = utf16_slice(&marked, range.location, range.length);
215 data.push(TextEvent::Composition(Some(marked)));
216 } else if was {
217 data.push(TextEvent::Composition(None));
218 }
219 }
220}
221
222struct DelegateIvars {
223 data: RefCell<Option<Weak<dyn Data>>>,
224}
225
226define_class!(
227 #[unsafe(super(NSObject))]
228 #[thread_kind = MainThreadOnly]
229 #[name = "FerrokitCoreTextDelegate"]
230 #[ivars = DelegateIvars]
231 struct Delegate;
232
233 unsafe impl NSObjectProtocol for Delegate {}
234
235 unsafe impl NSTextDelegate for Delegate {
236 #[unsafe(method(textDidChange:))]
237 fn text_did_change(&self, _notification: &NSNotification) {
238 crate::boundary::guarded("a text view (text_did_change)", (), || {
239 let Some(data) = self.data() else { return };
240 data.finish_highlight();
244 if !data.quiet() {
245 data.push(TextEvent::Changed);
246 }
247 })
248 }
249 }
250
251 unsafe impl NSTextStorageDelegate for Delegate {
254 #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
260 fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
261 crate::boundary::guarded("a text view (will_process_editing)", (), || {
262 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
263 return;
264 }
265 let Some(data) = self.data().filter(|d| !d.composing()) else { return };
266 if data.highlight(Some(range)) {
267 let weak = self.ivars().data.borrow().clone();
270 let block = block2::RcBlock::new(move || {
271 if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
272 objc2::rc::autoreleasepool(|_| d.finish_highlight());
273 }
274 });
275 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
276 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
278 main.wake_up();
279 }
280 })
281 }
282
283 #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
284 fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
285 crate::boundary::guarded("a text view (did_process_editing)", (), || {
286 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
287 return;
288 }
289 let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
290 data.push(TextEvent::Changed);
291 })
292 }
293 }
294
295 unsafe impl NSTextViewDelegate for Delegate {
296 #[unsafe(method(textViewDidChangeSelection:))]
297 fn selection_did_change(&self, notification: &NSNotification) {
298 crate::boundary::guarded("a text view (selection_did_change)", (), || {
299 let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
300 let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
301 let text = view.string().to_string();
302 let r = view.selectedRange();
303 data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
304 })
305 }
306
307 #[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
309 fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
310 crate::boundary::guarded("a text view (completions)", None, || {
311 Some(self.completion_words(words, index))
312 })
313 }
314
315 #[unsafe(method_id(undoManagerForTextView:))]
318 fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
319 crate::boundary::guarded("a text view (undo_manager_for)", None, || {
320 self.data().map(|d| d.undo_manager())
321 })
322 }
323 }
324);
325
326impl Delegate {
327 fn data(&self) -> Option<Rc<dyn Data>> {
328 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
329 }
330
331 fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
332 let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
333 let items = data.complete().map(|(_, items)| items).unwrap_or_default();
334 if !index.is_null() {
335 unsafe { *index = if items.is_empty() { -1 } else { 0 } };
337 }
338 data.offered(&items);
339 let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
340 NSArray::from_retained_slice(&items)
341 }
342}
343
344pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
346 let (mut units, mut start, mut end) = (0usize, None, None);
347 for (byte, c) in text.char_indices() {
348 if start.is_none() && units >= location {
349 start = Some(byte);
350 }
351 if end.is_none() && units >= location + length {
352 end = Some(byte);
353 }
354 units += c.len_utf16();
355 }
356 let start = start.unwrap_or(text.len());
357 start..end.unwrap_or(text.len()).max(start)
358}
359
360pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
363 let to_units = |byte: usize| -> usize {
364 let byte = byte.min(text.len());
365 let mut b = byte;
366 while !text.is_char_boundary(b) {
367 b -= 1;
368 }
369 text[..b].encode_utf16().count()
370 };
371 let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
372 (s, e - s)
373}
374
375fn utf16_slice(text: &str, location: usize, length: usize) -> String {
376 text[utf16_to_bytes(text, location, length)].to_string()
377}
378
379struct Inner {
380 id: ViewId,
381 events: RefCell<VecDeque<TextEvent>>,
382 quiet: Cell<bool>,
383 mounted: Cell<bool>,
384 undo: RefCell<Retained<NSUndoManager>>,
385 shared: Cell<bool>,
387 scroll: Retained<NSScrollView>,
388 view: Retained<HostTextView>,
389 _delegate: Retained<Delegate>,
390 font: RefCell<Retained<NSFont>>,
392 highlighter: RefCell<Option<Rc<Highlighter>>>,
393 completer: RefCell<Option<Rc<Completer>>>,
394 offered: RefCell<Vec<String>>,
396 styling: Cell<bool>,
398 shown: RefCell<Option<(usize, Runs)>>,
401 deferred: Cell<Option<(usize, usize)>>,
403}
404
405type Highlighter = dyn Fn(&str) -> Runs;
406type Runs = Vec<(Range<usize>, TextStyle)>;
407
408#[derive(Debug, Clone, Copy, PartialEq)]
412#[non_exhaustive]
413pub enum Color {
414 Primary,
416 Secondary,
418 Tertiary,
420 Quaternary,
422 Fill,
425 SecondaryFill,
427 TertiaryFill,
429 QuaternaryFill,
432 Accent,
434 Link,
436 Red,
438 Orange,
440 Yellow,
442 Green,
444 Mint,
446 Teal,
448 Cyan,
450 Blue,
452 Indigo,
454 Purple,
456 Pink,
458 Brown,
460 Gray,
462 Background,
464 WindowBackground,
466 ControlBackground,
468 Separator,
470 Clear,
472 Rgb(f64, f64, f64),
474 Rgba(f64, f64, f64, f64),
476}
477
478impl Color {
479 const NAMED: [Color; 28] = [
480 Color::Primary,
481 Color::Secondary,
482 Color::Tertiary,
483 Color::Quaternary,
484 Color::Fill,
485 Color::SecondaryFill,
486 Color::TertiaryFill,
487 Color::QuaternaryFill,
488 Color::Accent,
489 Color::Link,
490 Color::Red,
491 Color::Orange,
492 Color::Yellow,
493 Color::Green,
494 Color::Mint,
495 Color::Teal,
496 Color::Cyan,
497 Color::Blue,
498 Color::Indigo,
499 Color::Purple,
500 Color::Pink,
501 Color::Brown,
502 Color::Gray,
503 Color::Background,
504 Color::WindowBackground,
505 Color::ControlBackground,
506 Color::Separator,
507 Color::Clear,
508 ];
509
510 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
512 Color::Rgb(r, g, b)
513 }
514
515 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
517 Color::Rgba(r, g, b, a)
518 }
519
520 pub fn hex(hex: &str) -> Color {
523 let h = hex.trim_start_matches('#');
524 let byte = |i: usize| h.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).map_or(0.0, |b| f64::from(b) / 255.0);
525 match h.len() {
526 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
527 6 => Color::Rgb(byte(0), byte(2), byte(4)),
528 _ => Color::Rgb(0.0, 0.0, 0.0),
529 }
530 }
531
532 pub fn opacity(self, opacity: f64) -> Color {
534 match self.components() {
535 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
536 None => self,
537 }
538 }
539
540 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
543 match self {
544 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
545 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
546 _ => {
547 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
548 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
549 }
550 }
551 }
552
553 pub fn ns(self) -> Retained<NSColor> {
555 match self {
556 Color::Primary => NSColor::textColor(),
557 Color::Secondary => NSColor::secondaryLabelColor(),
558 Color::Tertiary => NSColor::tertiaryLabelColor(),
559 Color::Quaternary => NSColor::quaternaryLabelColor(),
560 Color::Fill => NSColor::systemFillColor(),
561 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
562 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
563 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
564 Color::Accent => NSColor::controlAccentColor(),
565 Color::Link => NSColor::linkColor(),
566 Color::Red => NSColor::systemRedColor(),
567 Color::Orange => NSColor::systemOrangeColor(),
568 Color::Yellow => NSColor::systemYellowColor(),
569 Color::Green => NSColor::systemGreenColor(),
570 Color::Mint => NSColor::systemMintColor(),
571 Color::Teal => NSColor::systemTealColor(),
572 Color::Cyan => NSColor::systemCyanColor(),
573 Color::Blue => NSColor::systemBlueColor(),
574 Color::Indigo => NSColor::systemIndigoColor(),
575 Color::Purple => NSColor::systemPurpleColor(),
576 Color::Pink => NSColor::systemPinkColor(),
577 Color::Brown => NSColor::systemBrownColor(),
578 Color::Gray => NSColor::systemGrayColor(),
579 Color::Background => NSColor::textBackgroundColor(),
580 Color::WindowBackground => NSColor::windowBackgroundColor(),
581 Color::ControlBackground => NSColor::controlBackgroundColor(),
582 Color::Separator => NSColor::separatorColor(),
583 Color::Clear => NSColor::clearColor(),
584 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
585 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
586 }
587 }
588
589 pub fn from_ns(color: &NSColor) -> Option<Color> {
592 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
593 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
594 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
595 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
596 })
597 }
598}
599
600#[derive(Debug, Clone, Copy, Default, PartialEq)]
603pub struct TextStyle {
604 pub color: Option<Color>,
606 pub background: Option<Color>,
608 pub bold: bool,
610 pub italic: bool,
612 pub underline: bool,
614}
615
616impl TextStyle {
617 pub fn new() -> Self {
619 Self::default()
620 }
621
622 pub fn color(mut self, color: Color) -> Self {
624 self.color = Some(color);
625 self
626 }
627
628 pub fn background(mut self, color: Color) -> Self {
630 self.background = Some(color);
631 self
632 }
633
634 pub fn bold(mut self) -> Self {
636 self.bold = true;
637 self
638 }
639
640 pub fn italic(mut self) -> Self {
642 self.italic = true;
643 self
644 }
645
646 pub fn underline(mut self) -> Self {
648 self.underline = true;
649 self
650 }
651}
652
653fn utf16_map(text: &str) -> Vec<usize> {
656 let mut map = Vec::with_capacity(text.len() + 1);
657 let mut units = 0;
658 for c in text.chars() {
659 map.extend(std::iter::repeat_n(units, c.len_utf8()));
660 units += c.len_utf16();
661 }
662 map.push(units);
663 map
664}
665
666impl Inner {
667 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
675 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
677 let text = storage.string().to_string();
678 let map = utf16_map(&text);
679 let len16 = *map.last().unwrap_or(&0);
680 let shown = self.shown.borrow_mut().take();
681 let region = match (shown, edited) {
684 (Some((old_len, old)), Some(edited)) => {
685 let delta = text.len() as isize - old_len as isize;
686 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
687 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
688 let suffix = old[prefix..]
689 .iter()
690 .rev()
691 .zip(runs[prefix..].iter().rev())
692 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
693 .count();
694 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
695 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
696 let clamp = |i: isize| (i.max(0) as usize).min(text.len());
700 let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
701 let changed_old = old[prefix..old.len() - suffix].iter().flat_map(|(r, _)| [(clamp(r.start as isize), clamp(r.end as isize)), (clamp(r.start as isize + delta), clamp(r.end as isize + delta))]);
702 let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
703 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
704 lo..hi
705 }
706 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
707 };
708 let mut deferred = false;
714 let region = match edited {
715 Some(e) => {
716 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
717 if inside != region {
718 deferred = self.deferred.get().is_none();
719 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
720 }
721 inside.start..inside.end.max(inside.start)
722 }
723 None => region,
724 };
725 let font = self.font.borrow().clone();
726 self.styling.set(true);
727 unsafe {
730 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
731 if edited.is_none() {
732 storage.beginEditing();
733 }
734 let base = objc2_foundation::NSDictionary::from_retained_objects(
735 &[NSFontAttributeName, NSForegroundColorAttributeName],
736 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
737 );
738 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
739 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
740 for (range, style) in &runs {
741 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
742 if start >= end {
743 continue;
744 }
745 let r = NSRange::new(start, end - start);
746 if let Some(c) = style.color {
747 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
748 }
749 if let Some(c) = style.background {
750 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
751 }
752 if style.bold || style.italic {
753 let mut f = font.clone();
754 if style.bold {
755 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
756 }
757 if style.italic {
758 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
759 }
760 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
761 }
762 if style.underline {
763 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
764 }
765 }
766 if edited.is_none() {
767 storage.endEditing();
768 }
769 }
770 self.styling.set(false);
771 *self.shown.borrow_mut() = Some((text.len(), runs));
772 if edited.is_some() {
780 return deferred;
781 }
782 unsafe {
784 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
785 let typing = objc2_foundation::NSDictionary::from_retained_objects(
786 &[NSFontAttributeName, NSForegroundColorAttributeName],
787 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
788 );
789 self.view.setTypingAttributes(&typing);
790 }
791 false
792 }
793}
794
795impl Data for Inner {
796 fn push(&self, event: TextEvent) {
797 let mut events = self.events.borrow_mut();
798 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
801 return;
802 }
803 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
805 events.pop_back();
806 }
807 events.push_back(event);
808 drop(events);
809 crate::request_redraw();
810 }
811
812 fn quiet(&self) -> bool {
813 self.quiet.get()
814 }
815
816 fn complete(&self) -> Option<(NSRange, Vec<String>)> {
817 let f = self.completer.borrow().clone()?;
818 let text = self.view.string().to_string();
819 let sel = self.view.selectedRange();
820 let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
821 let c = f(&text, caret)?;
822 let start = c.range.start.min(caret);
823 let (location, length) = bytes_to_utf16(&text, start..caret);
824 Some((NSRange::new(location, length), c.items))
825 }
826
827 fn has_completer(&self) -> bool {
828 self.completer.borrow().is_some()
829 }
830
831 fn offered(&self, items: &[String]) {
832 *self.offered.borrow_mut() = items.to_vec();
833 }
834
835 fn composing(&self) -> bool {
836 self.view.hasMarkedText()
837 }
838
839 fn undo_manager(&self) -> Retained<NSUndoManager> {
840 self.undo.borrow().clone()
841 }
842
843 fn highlight(&self, edited: Option<NSRange>) -> bool {
844 if self.styling.get() {
845 return false;
846 }
847 let Some(f) = self.highlighter.borrow().clone() else { return false };
848 let runs = f(&self.view.string().to_string());
849 self.apply_styles(runs, edited, None)
850 }
851
852 fn finish_highlight(&self) {
853 let Some(span) = self.deferred.take() else { return };
854 if self.styling.get() || self.view.hasMarkedText() {
855 return;
856 }
857 let Some(f) = self.highlighter.borrow().clone() else { return };
858 let runs = f(&self.view.string().to_string());
859 self.apply_styles(runs, None, Some(span));
860 }
861}
862
863impl Drop for ViewIvars {
864 fn drop(&mut self) {
865 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
866 }
867}
868
869impl Drop for DelegateIvars {
870 fn drop(&mut self) {
871 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
872 }
873}
874
875impl Drop for Inner {
876 fn drop(&mut self) {
877 self.view.setDelegate(None);
879 if let Some(storage) = unsafe { self.view.textStorage() } {
880 storage.setDelegate(None);
881 }
882 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
883 crate::keys::set_accepts_tab(self.id, false);
884 if self.mounted.get() {
885 crate::unmount(self.id);
886 }
887 }
888}
889
890#[derive(Clone)]
892pub struct TextModel {
893 inner: Rc<Inner>,
894}
895
896impl std::fmt::Debug for TextModel {
897 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
898 write!(f, "TextModel({:?})", self.inner.id)
899 }
900}
901
902impl TextModel {
903 pub fn new(text: &str) -> Self {
907 Self::with_id(ViewId::next(), text)
908 }
909
910 fn with_id(id: ViewId, text: &str) -> Self {
911 let mtm = mtm();
912 let size = NSSize::new(400.0, 300.0);
913 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
914 scroll.setHasVerticalScroller(true);
915 scroll.setAutohidesScrollers(true);
916 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
917
918 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
921 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
922 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
923 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
924 view.setMinSize(NSSize::new(0.0, size.height));
925 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
926 view.setVerticallyResizable(true);
927 view.setHorizontallyResizable(false);
928 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
929 if let Some(container) = unsafe { view.textContainer() } {
931 container.setContainerSize(NSSize::new(size.width, f64::MAX));
932 container.setWidthTracksTextView(true);
933 }
934 view.setRichText(false);
935 view.setImportsGraphics(false);
936 view.setAllowsUndo(true);
937 view.setUsesFindBar(true);
938 view.setContinuousSpellCheckingEnabled(true);
939 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
940 view.setTextContainerInset(NSSize::new(4.0, 6.0));
941 view.setString(&NSString::from_str(text));
942 scroll.setDocumentView(Some(&view));
943
944 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
945 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
946
947 let inner = Rc::new(Inner {
948 id,
949 events: RefCell::new(VecDeque::new()),
950 quiet: Cell::new(false),
951 mounted: Cell::new(false),
952 undo: RefCell::new(NSUndoManager::new(mtm)),
953 shared: Cell::new(false),
954 scroll,
955 view: view.clone(),
956 _delegate: delegate.clone(),
957 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
958 highlighter: RefCell::new(None),
959 completer: RefCell::new(None),
960 offered: RefCell::new(Vec::new()),
961 styling: Cell::new(false),
962 shown: RefCell::new(None),
963 deferred: Cell::new(None),
964 });
965 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
966 *view.ivars().data.borrow_mut() = Some(weak.clone());
967 *delegate.ivars().data.borrow_mut() = Some(weak);
968 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
970 if let Some(storage) = unsafe { view.textStorage() } {
971 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
973 }
974 crate::keys::set_accepts_tab(id, true);
975 Self { inner }
976 }
977
978 pub fn id(&self) -> ViewId {
980 self.inner.id
981 }
982
983 #[doc(hidden)]
984 pub fn ensure_mounted(&self) {
987 if !self.inner.mounted.get() && crate::is_attached() {
988 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
989 self.inner.mounted.set(true);
990 }
991 }
992
993 pub fn text(&self) -> String {
995 self.inner.view.string().to_string()
996 }
997
998 pub fn set_text(&self, text: &str) {
1001 self.inner.quiet.set(true);
1002 self.inner.view.setString(&NSString::from_str(text));
1003 self.inner.quiet.set(false);
1004 self.clear_undo();
1005 }
1006
1007 fn clear_undo(&self) {
1010 let undo = self.inner.undo.borrow();
1011 if self.inner.shared.get() {
1012 unsafe {
1014 undo.removeAllActionsWithTarget(&self.inner.view);
1015 if let Some(storage) = self.inner.view.textStorage() {
1016 undo.removeAllActionsWithTarget(&storage);
1017 }
1018 }
1019 } else {
1020 undo.removeAllActions();
1021 }
1022 }
1023
1024 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
1029 self.clear_undo();
1030 let mtm = MainThreadMarker::from(&*self.inner.view);
1031 let next = match manager {
1032 Some(m) => m.retain(),
1033 None => NSUndoManager::new(mtm),
1034 };
1035 *self.inner.undo.borrow_mut() = next;
1036 self.inner.shared.set(manager.is_some());
1037 }
1038
1039 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
1041 self.inner.undo.borrow().clone()
1042 }
1043
1044 pub fn replace_selection(&self, text: &str) {
1046 let view = &self.inner.view;
1047 let range = view.selectedRange();
1048 let string = NSString::from_str(text);
1049 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1050 view.replaceCharactersInRange_withString(range, &string);
1051 view.didChangeText();
1052 }
1053 }
1054
1055 pub fn selection(&self) -> Range<usize> {
1057 let r = self.inner.view.selectedRange();
1058 utf16_to_bytes(&self.text(), r.location, r.length)
1059 }
1060
1061 pub fn set_selection(&self, range: Range<usize>) {
1063 let (location, length) = bytes_to_utf16(&self.text(), range);
1064 self.inner.quiet.set(true);
1065 self.inner.view.setSelectedRange(NSRange::new(location, length));
1066 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1067 self.inner.quiet.set(false);
1068 }
1069
1070 pub fn composition(&self) -> Option<String> {
1072 let view = &self.inner.view;
1073 view.hasMarkedText().then(|| {
1074 let r = view.markedRange();
1075 utf16_slice(&view.string().to_string(), r.location, r.length)
1076 })
1077 }
1078
1079 pub fn set_editable(&self, editable: bool) {
1081 self.inner.view.setEditable(editable);
1082 }
1083
1084 pub fn is_editable(&self) -> bool {
1086 self.inner.view.isEditable()
1087 }
1088
1089 pub fn set_font(&self, name: Option<&str>, size: f64) {
1091 let font = match name {
1092 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1093 None => Some(NSFont::systemFontOfSize(size)),
1094 };
1095 if let Some(font) = font {
1096 self.inner.view.setFont(Some(&font));
1097 *self.inner.font.borrow_mut() = font;
1098 self.inner.highlight(None);
1099 }
1100 }
1101
1102 pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1109 *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1110 }
1111
1112 pub fn complete(&self) {
1114 unsafe { self.inner.view.complete(None) };
1116 }
1117
1118 pub fn offered_completions(&self) -> Vec<String> {
1120 self.inner.offered.borrow().clone()
1121 }
1122
1123 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1129 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1130 self.restyle();
1131 }
1132
1133 pub fn restyle(&self) {
1136 if self.inner.highlighter.borrow().is_some() {
1137 self.inner.highlight(None);
1138 } else {
1139 self.inner.apply_styles(Vec::new(), None, None);
1140 }
1141 }
1142
1143 pub fn style_at(&self, offset: usize) -> TextStyle {
1145 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1147 let text = storage.string().to_string();
1148 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1149 let mut style = TextStyle::default();
1150 unsafe {
1152 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1153 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1154 style.color = at(NSForegroundColorAttributeName)
1155 .and_then(|c| c.downcast::<NSColor>().ok())
1156 .and_then(|c| Color::from_ns(&c))
1157 .filter(|c| *c != Color::Primary);
1158 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1159 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1160 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1161 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1162 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1163 }
1164 style.underline = at(NSUnderlineStyleAttributeName)
1165 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1166 .is_some_and(|n| n.integerValue() != 0);
1167 }
1168 style
1169 }
1170
1171 pub fn set_rich(&self, rich: bool) {
1178 let v = &self.inner.view;
1179 v.setRichText(rich);
1180 v.setImportsGraphics(rich);
1181 v.setUsesFontPanel(rich);
1182 v.setUsesRuler(rich);
1183 if !rich {
1184 v.setUsesInspectorBar(false);
1185 v.setRulerVisible(false);
1186 }
1187 }
1188
1189 pub fn is_rich(&self) -> bool {
1191 self.inner.view.isRichText()
1192 }
1193
1194 pub fn set_format_bar(&self, shown: bool) {
1197 self.inner.view.setUsesInspectorBar(shown);
1198 }
1199
1200 pub fn has_format_bar(&self) -> bool {
1202 self.inner.view.usesInspectorBar()
1203 }
1204
1205 pub fn set_ruler_visible(&self, shown: bool) {
1209 self.inner.view.setRulerVisible(shown);
1210 }
1211
1212 pub fn is_ruler_visible(&self) -> bool {
1214 self.inner.view.isRulerVisible()
1215 }
1216
1217 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1218 let storage = unsafe { self.inner.view.textStorage() }?;
1220 let len = storage.length();
1221 Some((storage, NSRange::new(0, len)))
1222 }
1223
1224 pub fn rtf(&self) -> Vec<u8> {
1227 let Some((storage, range)) = self.whole() else { return Vec::new() };
1228 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1229 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1231 data.map(|d| d.to_vec()).unwrap_or_default()
1232 }
1233
1234 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1238 let data = objc2_foundation::NSData::with_bytes(rtf);
1239 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1241 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1242 self.load(text)
1243 }
1244
1245 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1246 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1247 self.inner.quiet.set(true);
1248 storage.setAttributedString(&text);
1249 self.inner.quiet.set(false);
1250 self.clear_undo();
1251 true
1252 }
1253
1254 pub fn html(&self) -> String {
1257 let Some((storage, range)) = self.whole() else { return String::new() };
1258 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1261 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1262 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1263 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1264 };
1265 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1266 }
1267
1268 pub fn set_html(&self, html: &str) -> bool {
1272 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1273 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1275 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1276 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1278 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1279 &[kind, utf8.as_ref()],
1280 );
1281 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1282 };
1283 self.load(text)
1284 }
1285
1286 pub fn font_size(&self) -> Option<f64> {
1288 self.inner.view.font().map(|f| f.pointSize())
1289 }
1290
1291 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1293 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1294 }
1295
1296 pub fn set_spell_checking(&self, on: bool) {
1298 self.inner.view.setContinuousSpellCheckingEnabled(on);
1299 }
1300
1301 pub fn set_grammar_checking(&self, on: bool) {
1303 self.inner.view.setGrammarCheckingEnabled(on);
1304 }
1305
1306 pub fn set_code_input(&self, code: bool) {
1311 let view = &self.inner.view;
1312 view.setAutomaticQuoteSubstitutionEnabled(!code);
1313 view.setAutomaticDashSubstitutionEnabled(!code);
1314 view.setAutomaticTextReplacementEnabled(!code);
1315 view.setAutomaticSpellingCorrectionEnabled(!code);
1316 view.setContinuousSpellCheckingEnabled(!code);
1317 view.setSmartInsertDeleteEnabled(!code);
1318 }
1319
1320 pub fn set_accepts_tab(&self, accepts: bool) {
1322 crate::keys::set_accepts_tab(self.inner.id, accepts);
1323 }
1324
1325 pub fn show_find(&self) {
1328 let item = objc2_app_kit::NSMenuItem::new(mtm());
1330 item.setTag(1);
1331 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1332 }
1333
1334 pub fn set_wraps(&self, wraps: bool) {
1337 let (view, scroll) = (&self.inner.view, &self.inner.scroll);
1338 let Some(container) = (unsafe { view.textContainer() }) else { return };
1340 if container.widthTracksTextView() == wraps {
1341 return;
1342 }
1343 let width = scroll.contentSize().width;
1344 scroll.setHasHorizontalScroller(!wraps);
1345 view.setHorizontallyResizable(!wraps);
1346 container.setWidthTracksTextView(wraps);
1347 if wraps {
1348 let mut frame = view.frame();
1350 frame.size.width = width;
1351 view.setFrame(frame);
1352 container.setContainerSize(NSSize::new(width, f64::MAX));
1353 } else {
1354 container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
1356 view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
1357 }
1358 view.sizeToFit();
1359 view.setNeedsDisplay(true);
1360 }
1361
1362 pub fn wraps(&self) -> bool {
1364 unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
1366 }
1367
1368 pub fn is_find_visible(&self) -> bool {
1370 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1371 }
1372
1373 pub fn can_undo(&self) -> bool {
1375 self.inner.undo.borrow().canUndo()
1376 }
1377
1378 pub fn undo(&self) {
1380 let undo = self.undo_manager();
1381 if undo.canUndo() {
1382 undo.undo();
1383 }
1384 }
1385
1386 #[doc(hidden)]
1387 pub fn drain_events(&self) -> Vec<TextEvent> {
1389 self.inner.events.borrow_mut().drain(..).collect()
1390 }
1391
1392 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1395 self.inner.scroll.clone()
1396 }
1397
1398 pub fn text_view(&self) -> Retained<NSTextView> {
1400 Retained::into_super(self.inner.view.clone())
1401 }
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406 use super::{bytes_to_utf16, utf16_to_bytes};
1407
1408 #[test]
1409 fn offsets_round_trip() {
1410 let t = "a東京😀b";
1411 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1413 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1414 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1415 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1416 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1417 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1418 }
1419}