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)]
411#[non_exhaustive]
412pub enum Color {
413 Primary,
415 Secondary,
417 Tertiary,
419 Quaternary,
421 Fill,
424 SecondaryFill,
426 TertiaryFill,
428 QuaternaryFill,
431 Accent,
433 Link,
435 Red,
437 Orange,
439 Yellow,
441 Green,
443 Mint,
445 Teal,
447 Cyan,
449 Blue,
451 Indigo,
453 Purple,
455 Pink,
457 Brown,
459 Gray,
461 Background,
463 WindowBackground,
465 ControlBackground,
467 Separator,
469 Clear,
471 Rgb(f64, f64, f64),
473 Rgba(f64, f64, f64, f64),
475}
476
477impl Color {
478 const NAMED: [Color; 28] = [
479 Color::Primary,
480 Color::Secondary,
481 Color::Tertiary,
482 Color::Quaternary,
483 Color::Fill,
484 Color::SecondaryFill,
485 Color::TertiaryFill,
486 Color::QuaternaryFill,
487 Color::Accent,
488 Color::Link,
489 Color::Red,
490 Color::Orange,
491 Color::Yellow,
492 Color::Green,
493 Color::Mint,
494 Color::Teal,
495 Color::Cyan,
496 Color::Blue,
497 Color::Indigo,
498 Color::Purple,
499 Color::Pink,
500 Color::Brown,
501 Color::Gray,
502 Color::Background,
503 Color::WindowBackground,
504 Color::ControlBackground,
505 Color::Separator,
506 Color::Clear,
507 ];
508
509 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
511 Color::Rgb(r, g, b)
512 }
513
514 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
516 Color::Rgba(r, g, b, a)
517 }
518
519 pub fn hex(hex: &str) -> Color {
522 let h = hex.trim_start_matches('#');
523 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);
524 match h.len() {
525 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
526 6 => Color::Rgb(byte(0), byte(2), byte(4)),
527 _ => Color::Rgb(0.0, 0.0, 0.0),
528 }
529 }
530
531 pub fn opacity(self, opacity: f64) -> Color {
533 match self.components() {
534 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
535 None => self,
536 }
537 }
538
539 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
542 match self {
543 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
544 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
545 _ => {
546 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
547 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
548 }
549 }
550 }
551
552 pub fn ns(self) -> Retained<NSColor> {
554 match self {
555 Color::Primary => NSColor::textColor(),
556 Color::Secondary => NSColor::secondaryLabelColor(),
557 Color::Tertiary => NSColor::tertiaryLabelColor(),
558 Color::Quaternary => NSColor::quaternaryLabelColor(),
559 Color::Fill => NSColor::systemFillColor(),
560 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
561 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
562 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
563 Color::Accent => NSColor::controlAccentColor(),
564 Color::Link => NSColor::linkColor(),
565 Color::Red => NSColor::systemRedColor(),
566 Color::Orange => NSColor::systemOrangeColor(),
567 Color::Yellow => NSColor::systemYellowColor(),
568 Color::Green => NSColor::systemGreenColor(),
569 Color::Mint => NSColor::systemMintColor(),
570 Color::Teal => NSColor::systemTealColor(),
571 Color::Cyan => NSColor::systemCyanColor(),
572 Color::Blue => NSColor::systemBlueColor(),
573 Color::Indigo => NSColor::systemIndigoColor(),
574 Color::Purple => NSColor::systemPurpleColor(),
575 Color::Pink => NSColor::systemPinkColor(),
576 Color::Brown => NSColor::systemBrownColor(),
577 Color::Gray => NSColor::systemGrayColor(),
578 Color::Background => NSColor::textBackgroundColor(),
579 Color::WindowBackground => NSColor::windowBackgroundColor(),
580 Color::ControlBackground => NSColor::controlBackgroundColor(),
581 Color::Separator => NSColor::separatorColor(),
582 Color::Clear => NSColor::clearColor(),
583 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
584 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
585 }
586 }
587
588 pub fn from_ns(color: &NSColor) -> Option<Color> {
591 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
592 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
593 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
594 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
595 })
596 }
597}
598
599#[derive(Debug, Clone, Copy, Default, PartialEq)]
602pub struct TextStyle {
603 pub color: Option<Color>,
605 pub background: Option<Color>,
607 pub bold: bool,
609 pub italic: bool,
611 pub underline: bool,
613}
614
615impl TextStyle {
616 pub fn new() -> Self {
618 Self::default()
619 }
620
621 pub fn color(mut self, color: Color) -> Self {
623 self.color = Some(color);
624 self
625 }
626
627 pub fn background(mut self, color: Color) -> Self {
629 self.background = Some(color);
630 self
631 }
632
633 pub fn bold(mut self) -> Self {
635 self.bold = true;
636 self
637 }
638
639 pub fn italic(mut self) -> Self {
641 self.italic = true;
642 self
643 }
644
645 pub fn underline(mut self) -> Self {
647 self.underline = true;
648 self
649 }
650}
651
652fn utf16_map(text: &str) -> Vec<usize> {
655 let mut map = Vec::with_capacity(text.len() + 1);
656 let mut units = 0;
657 for c in text.chars() {
658 map.extend(std::iter::repeat_n(units, c.len_utf8()));
659 units += c.len_utf16();
660 }
661 map.push(units);
662 map
663}
664
665impl Inner {
666 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
674 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
676 let text = storage.string().to_string();
677 let map = utf16_map(&text);
678 let len16 = *map.last().unwrap_or(&0);
679 let shown = self.shown.borrow_mut().take();
680 let region = match (shown, edited) {
683 (Some((old_len, old)), Some(edited)) => {
684 let delta = text.len() as isize - old_len as isize;
685 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
686 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
687 let suffix = old[prefix..]
688 .iter()
689 .rev()
690 .zip(runs[prefix..].iter().rev())
691 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
692 .count();
693 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
694 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
695 let clamp = |i: isize| (i.max(0) as usize).min(text.len());
699 let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
700 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))]);
701 let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
702 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
703 lo..hi
704 }
705 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
706 };
707 let mut deferred = false;
713 let region = match edited {
714 Some(e) => {
715 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
716 if inside != region {
717 deferred = self.deferred.get().is_none();
718 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
719 }
720 inside.start..inside.end.max(inside.start)
721 }
722 None => region,
723 };
724 let font = self.font.borrow().clone();
725 self.styling.set(true);
726 unsafe {
729 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
730 if edited.is_none() {
731 storage.beginEditing();
732 }
733 let base = objc2_foundation::NSDictionary::from_retained_objects(
734 &[NSFontAttributeName, NSForegroundColorAttributeName],
735 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
736 );
737 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
738 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
739 for (range, style) in &runs {
740 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
741 if start >= end {
742 continue;
743 }
744 let r = NSRange::new(start, end - start);
745 if let Some(c) = style.color {
746 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
747 }
748 if let Some(c) = style.background {
749 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
750 }
751 if style.bold || style.italic {
752 let mut f = font.clone();
753 if style.bold {
754 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
755 }
756 if style.italic {
757 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
758 }
759 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
760 }
761 if style.underline {
762 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
763 }
764 }
765 if edited.is_none() {
766 storage.endEditing();
767 }
768 }
769 self.styling.set(false);
770 *self.shown.borrow_mut() = Some((text.len(), runs));
771 if edited.is_some() {
779 return deferred;
780 }
781 unsafe {
783 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
784 let typing = objc2_foundation::NSDictionary::from_retained_objects(
785 &[NSFontAttributeName, NSForegroundColorAttributeName],
786 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
787 );
788 self.view.setTypingAttributes(&typing);
789 }
790 false
791 }
792}
793
794impl Data for Inner {
795 fn push(&self, event: TextEvent) {
796 let mut events = self.events.borrow_mut();
797 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
800 return;
801 }
802 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
804 events.pop_back();
805 }
806 events.push_back(event);
807 drop(events);
808 crate::request_redraw();
809 }
810
811 fn quiet(&self) -> bool {
812 self.quiet.get()
813 }
814
815 fn complete(&self) -> Option<(NSRange, Vec<String>)> {
816 let f = self.completer.borrow().clone()?;
817 let text = self.view.string().to_string();
818 let sel = self.view.selectedRange();
819 let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
820 let c = f(&text, caret)?;
821 let start = c.range.start.min(caret);
822 let (location, length) = bytes_to_utf16(&text, start..caret);
823 Some((NSRange::new(location, length), c.items))
824 }
825
826 fn has_completer(&self) -> bool {
827 self.completer.borrow().is_some()
828 }
829
830 fn offered(&self, items: &[String]) {
831 *self.offered.borrow_mut() = items.to_vec();
832 }
833
834 fn composing(&self) -> bool {
835 self.view.hasMarkedText()
836 }
837
838 fn undo_manager(&self) -> Retained<NSUndoManager> {
839 self.undo.borrow().clone()
840 }
841
842 fn highlight(&self, edited: Option<NSRange>) -> bool {
843 if self.styling.get() {
844 return false;
845 }
846 let Some(f) = self.highlighter.borrow().clone() else { return false };
847 let runs = f(&self.view.string().to_string());
848 self.apply_styles(runs, edited, None)
849 }
850
851 fn finish_highlight(&self) {
852 let Some(span) = self.deferred.take() else { return };
853 if self.styling.get() || self.view.hasMarkedText() {
854 return;
855 }
856 let Some(f) = self.highlighter.borrow().clone() else { return };
857 let runs = f(&self.view.string().to_string());
858 self.apply_styles(runs, None, Some(span));
859 }
860}
861
862impl Drop for ViewIvars {
863 fn drop(&mut self) {
864 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
865 }
866}
867
868impl Drop for DelegateIvars {
869 fn drop(&mut self) {
870 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
871 }
872}
873
874impl Drop for Inner {
875 fn drop(&mut self) {
876 self.view.setDelegate(None);
878 if let Some(storage) = unsafe { self.view.textStorage() } {
879 storage.setDelegate(None);
880 }
881 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
882 crate::keys::set_accepts_tab(self.id, false);
883 if self.mounted.get() {
884 crate::unmount(self.id);
885 }
886 }
887}
888
889#[derive(Clone)]
891pub struct TextModel {
892 inner: Rc<Inner>,
893}
894
895impl std::fmt::Debug for TextModel {
896 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
897 write!(f, "TextModel({:?})", self.inner.id)
898 }
899}
900
901impl TextModel {
902 pub fn new(text: &str) -> Self {
906 #[allow(deprecated)]
907 Self::with_id(ViewId::next(), text)
908 }
909
910 #[deprecated(since = "0.13.0", note = "use `TextModel::new(text)`: the id is chosen for you")]
913 pub fn with_id(id: ViewId, text: &str) -> Self {
914 let mtm = mtm();
915 let size = NSSize::new(400.0, 300.0);
916 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
917 scroll.setHasVerticalScroller(true);
918 scroll.setAutohidesScrollers(true);
919 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
920
921 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
924 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
925 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
926 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
927 view.setMinSize(NSSize::new(0.0, size.height));
928 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
929 view.setVerticallyResizable(true);
930 view.setHorizontallyResizable(false);
931 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
932 if let Some(container) = unsafe { view.textContainer() } {
934 container.setContainerSize(NSSize::new(size.width, f64::MAX));
935 container.setWidthTracksTextView(true);
936 }
937 view.setRichText(false);
938 view.setImportsGraphics(false);
939 view.setAllowsUndo(true);
940 view.setUsesFindBar(true);
941 view.setContinuousSpellCheckingEnabled(true);
942 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
943 view.setTextContainerInset(NSSize::new(4.0, 6.0));
944 view.setString(&NSString::from_str(text));
945 scroll.setDocumentView(Some(&view));
946
947 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
948 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
949
950 let inner = Rc::new(Inner {
951 id,
952 events: RefCell::new(VecDeque::new()),
953 quiet: Cell::new(false),
954 mounted: Cell::new(false),
955 undo: RefCell::new(NSUndoManager::new(mtm)),
956 shared: Cell::new(false),
957 scroll,
958 view: view.clone(),
959 _delegate: delegate.clone(),
960 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
961 highlighter: RefCell::new(None),
962 completer: RefCell::new(None),
963 offered: RefCell::new(Vec::new()),
964 styling: Cell::new(false),
965 shown: RefCell::new(None),
966 deferred: Cell::new(None),
967 });
968 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
969 *view.ivars().data.borrow_mut() = Some(weak.clone());
970 *delegate.ivars().data.borrow_mut() = Some(weak);
971 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
973 if let Some(storage) = unsafe { view.textStorage() } {
974 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
976 }
977 crate::keys::set_accepts_tab(id, true);
978 Self { inner }
979 }
980
981 pub fn id(&self) -> ViewId {
983 self.inner.id
984 }
985
986 pub fn ensure_mounted(&self) {
989 if !self.inner.mounted.get() && crate::is_attached() {
990 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
991 self.inner.mounted.set(true);
992 }
993 }
994
995 pub fn text(&self) -> String {
997 self.inner.view.string().to_string()
998 }
999
1000 pub fn set_text(&self, text: &str) {
1003 self.inner.quiet.set(true);
1004 self.inner.view.setString(&NSString::from_str(text));
1005 self.inner.quiet.set(false);
1006 self.clear_undo();
1007 }
1008
1009 fn clear_undo(&self) {
1012 let undo = self.inner.undo.borrow();
1013 if self.inner.shared.get() {
1014 unsafe {
1016 undo.removeAllActionsWithTarget(&self.inner.view);
1017 if let Some(storage) = self.inner.view.textStorage() {
1018 undo.removeAllActionsWithTarget(&storage);
1019 }
1020 }
1021 } else {
1022 undo.removeAllActions();
1023 }
1024 }
1025
1026 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
1031 self.clear_undo();
1032 let mtm = MainThreadMarker::from(&*self.inner.view);
1033 let next = match manager {
1034 Some(m) => m.retain(),
1035 None => NSUndoManager::new(mtm),
1036 };
1037 *self.inner.undo.borrow_mut() = next;
1038 self.inner.shared.set(manager.is_some());
1039 }
1040
1041 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
1043 self.inner.undo.borrow().clone()
1044 }
1045
1046 pub fn replace_selection(&self, text: &str) {
1048 let view = &self.inner.view;
1049 let range = view.selectedRange();
1050 let string = NSString::from_str(text);
1051 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
1052 view.replaceCharactersInRange_withString(range, &string);
1053 view.didChangeText();
1054 }
1055 }
1056
1057 pub fn selection(&self) -> Range<usize> {
1059 let r = self.inner.view.selectedRange();
1060 utf16_to_bytes(&self.text(), r.location, r.length)
1061 }
1062
1063 pub fn set_selection(&self, range: Range<usize>) {
1065 let (location, length) = bytes_to_utf16(&self.text(), range);
1066 self.inner.quiet.set(true);
1067 self.inner.view.setSelectedRange(NSRange::new(location, length));
1068 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
1069 self.inner.quiet.set(false);
1070 }
1071
1072 pub fn composition(&self) -> Option<String> {
1074 let view = &self.inner.view;
1075 view.hasMarkedText().then(|| {
1076 let r = view.markedRange();
1077 utf16_slice(&view.string().to_string(), r.location, r.length)
1078 })
1079 }
1080
1081 pub fn set_editable(&self, editable: bool) {
1083 self.inner.view.setEditable(editable);
1084 }
1085
1086 pub fn is_editable(&self) -> bool {
1088 self.inner.view.isEditable()
1089 }
1090
1091 pub fn set_font(&self, name: Option<&str>, size: f64) {
1093 let font = match name {
1094 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
1095 None => Some(NSFont::systemFontOfSize(size)),
1096 };
1097 if let Some(font) = font {
1098 self.inner.view.setFont(Some(&font));
1099 *self.inner.font.borrow_mut() = font;
1100 self.inner.highlight(None);
1101 }
1102 }
1103
1104 pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
1111 *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
1112 }
1113
1114 pub fn complete(&self) {
1116 unsafe { self.inner.view.complete(None) };
1118 }
1119
1120 pub fn offered_completions(&self) -> Vec<String> {
1122 self.inner.offered.borrow().clone()
1123 }
1124
1125 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
1131 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
1132 self.restyle();
1133 }
1134
1135 pub fn restyle(&self) {
1138 if self.inner.highlighter.borrow().is_some() {
1139 self.inner.highlight(None);
1140 } else {
1141 self.inner.apply_styles(Vec::new(), None, None);
1142 }
1143 }
1144
1145 pub fn style_at(&self, offset: usize) -> TextStyle {
1147 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
1149 let text = storage.string().to_string();
1150 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
1151 let mut style = TextStyle::default();
1152 unsafe {
1154 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
1155 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
1156 style.color = at(NSForegroundColorAttributeName)
1157 .and_then(|c| c.downcast::<NSColor>().ok())
1158 .and_then(|c| Color::from_ns(&c))
1159 .filter(|c| *c != Color::Primary);
1160 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
1161 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
1162 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
1163 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
1164 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
1165 }
1166 style.underline = at(NSUnderlineStyleAttributeName)
1167 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
1168 .is_some_and(|n| n.integerValue() != 0);
1169 }
1170 style
1171 }
1172
1173 pub fn set_rich(&self, rich: bool) {
1180 let v = &self.inner.view;
1181 v.setRichText(rich);
1182 v.setImportsGraphics(rich);
1183 v.setUsesFontPanel(rich);
1184 v.setUsesRuler(rich);
1185 if !rich {
1186 v.setUsesInspectorBar(false);
1187 v.setRulerVisible(false);
1188 }
1189 }
1190
1191 pub fn is_rich(&self) -> bool {
1193 self.inner.view.isRichText()
1194 }
1195
1196 pub fn set_format_bar(&self, shown: bool) {
1199 self.inner.view.setUsesInspectorBar(shown);
1200 }
1201
1202 pub fn has_format_bar(&self) -> bool {
1204 self.inner.view.usesInspectorBar()
1205 }
1206
1207 pub fn set_ruler_visible(&self, shown: bool) {
1211 self.inner.view.setRulerVisible(shown);
1212 }
1213
1214 pub fn is_ruler_visible(&self) -> bool {
1216 self.inner.view.isRulerVisible()
1217 }
1218
1219 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1220 let storage = unsafe { self.inner.view.textStorage() }?;
1222 let len = storage.length();
1223 Some((storage, NSRange::new(0, len)))
1224 }
1225
1226 pub fn rtf(&self) -> Vec<u8> {
1229 let Some((storage, range)) = self.whole() else { return Vec::new() };
1230 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1231 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1233 data.map(|d| d.to_vec()).unwrap_or_default()
1234 }
1235
1236 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1240 let data = objc2_foundation::NSData::with_bytes(rtf);
1241 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1243 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1244 self.load(text)
1245 }
1246
1247 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1248 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1249 self.inner.quiet.set(true);
1250 storage.setAttributedString(&text);
1251 self.inner.quiet.set(false);
1252 self.clear_undo();
1253 true
1254 }
1255
1256 pub fn html(&self) -> String {
1259 let Some((storage, range)) = self.whole() else { return String::new() };
1260 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1263 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1264 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1265 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1266 };
1267 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1268 }
1269
1270 pub fn set_html(&self, html: &str) -> bool {
1274 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1275 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1277 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1278 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1280 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1281 &[kind, utf8.as_ref()],
1282 );
1283 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1284 };
1285 self.load(text)
1286 }
1287
1288 pub fn font_size(&self) -> Option<f64> {
1290 self.inner.view.font().map(|f| f.pointSize())
1291 }
1292
1293 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1295 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1296 }
1297
1298 pub fn set_spell_checking(&self, on: bool) {
1300 self.inner.view.setContinuousSpellCheckingEnabled(on);
1301 }
1302
1303 pub fn set_grammar_checking(&self, on: bool) {
1305 self.inner.view.setGrammarCheckingEnabled(on);
1306 }
1307
1308 pub fn set_code_input(&self, code: bool) {
1313 let view = &self.inner.view;
1314 view.setAutomaticQuoteSubstitutionEnabled(!code);
1315 view.setAutomaticDashSubstitutionEnabled(!code);
1316 view.setAutomaticTextReplacementEnabled(!code);
1317 view.setAutomaticSpellingCorrectionEnabled(!code);
1318 view.setContinuousSpellCheckingEnabled(!code);
1319 view.setSmartInsertDeleteEnabled(!code);
1320 }
1321
1322 pub fn set_accepts_tab(&self, accepts: bool) {
1324 crate::keys::set_accepts_tab(self.inner.id, accepts);
1325 }
1326
1327 pub fn show_find(&self) {
1330 let item = objc2_app_kit::NSMenuItem::new(mtm());
1332 item.setTag(1);
1333 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1334 }
1335
1336 pub fn set_wraps(&self, wraps: bool) {
1339 let (view, scroll) = (&self.inner.view, &self.inner.scroll);
1340 let Some(container) = (unsafe { view.textContainer() }) else { return };
1342 if container.widthTracksTextView() == wraps {
1343 return;
1344 }
1345 let width = scroll.contentSize().width;
1346 scroll.setHasHorizontalScroller(!wraps);
1347 view.setHorizontallyResizable(!wraps);
1348 container.setWidthTracksTextView(wraps);
1349 if wraps {
1350 let mut frame = view.frame();
1352 frame.size.width = width;
1353 view.setFrame(frame);
1354 container.setContainerSize(NSSize::new(width, f64::MAX));
1355 } else {
1356 container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
1358 view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
1359 }
1360 view.sizeToFit();
1361 view.setNeedsDisplay(true);
1362 }
1363
1364 pub fn wraps(&self) -> bool {
1366 unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
1368 }
1369
1370 pub fn is_find_visible(&self) -> bool {
1372 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1373 }
1374
1375 pub fn can_undo(&self) -> bool {
1377 self.inner.undo.borrow().canUndo()
1378 }
1379
1380 pub fn undo(&self) {
1382 let undo = self.undo_manager();
1383 if undo.canUndo() {
1384 undo.undo();
1385 }
1386 }
1387
1388 pub fn drain_events(&self) -> Vec<TextEvent> {
1390 self.inner.events.borrow_mut().drain(..).collect()
1391 }
1392
1393 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1396 self.inner.scroll.clone()
1397 }
1398
1399 pub fn text_view(&self) -> Retained<NSTextView> {
1401 Retained::into_super(self.inner.view.clone())
1402 }
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407 use super::{bytes_to_utf16, utf16_to_bytes};
1408
1409 #[test]
1410 fn offsets_round_trip() {
1411 let t = "a東京😀b";
1412 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1414 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1415 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1416 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1417 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1418 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1419 }
1420}