1use std::cell::{Cell, RefCell};
24use std::collections::VecDeque;
25use std::ops::Range;
26use std::rc::{Rc, Weak};
27
28use objc2::rc::Retained;
29use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
30use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send};
31use objc2_app_kit::{
32 NSColor, NSFont, NSResponder, NSScrollView, NSText, NSTextDelegate, NSTextInputClient, NSTextStorage, NSTextStorageDelegate,
33 NSTextStorageEditActions, NSTextView, NSTextViewDelegate, NSAutoresizingMaskOptions, NSView,
34};
35use objc2_foundation::{NSNotification, NSPoint, NSRange, NSRect, NSSize, NSString, NSUndoManager};
36
37use crate::ViewId;
38use crate::host::mtm;
39
40#[derive(Debug, Clone, PartialEq)]
42pub enum TextEvent {
43 Changed,
46 Selection(Range<usize>),
48 Composition(Option<String>),
50}
51
52trait Data {
53 fn push(&self, event: TextEvent);
54 fn quiet(&self) -> bool;
55 fn composing(&self) -> bool;
56 fn undo_manager(&self) -> Retained<NSUndoManager>;
57 fn highlight(&self, edited: Option<NSRange>) -> bool;
60 fn finish_highlight(&self);
61}
62
63struct ViewIvars {
64 data: RefCell<Option<Weak<dyn Data>>>,
65 composing: Cell<bool>,
66}
67
68define_class!(
69 #[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
71 #[thread_kind = MainThreadOnly]
72 #[name = "FerrokitCoreTextView"]
73 #[ivars = ViewIvars]
74 struct HostTextView;
75
76 impl HostTextView {
77 #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
78 fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
79 let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
80 self.composition_changed();
81 }
82
83 #[unsafe(method(unmarkText))]
84 fn unmark_text(&self) {
85 let () = unsafe { msg_send![super(self), unmarkText] };
86 self.composition_changed();
87 }
88
89 #[unsafe(method(insertText:replacementRange:))]
90 fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
91 let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
92 self.composition_changed();
93 }
94 }
95);
96
97impl HostTextView {
98 fn data(&self) -> Option<Rc<dyn Data>> {
99 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
100 }
101
102 fn composition_changed(&self) {
104 let composing = self.hasMarkedText();
105 let was = self.ivars().composing.replace(composing);
106 let Some(data) = self.data() else { return };
107 if composing {
108 let range = self.markedRange();
109 let marked = self.string().to_string();
110 let marked = utf16_slice(&marked, range.location, range.length);
111 data.push(TextEvent::Composition(Some(marked)));
112 } else if was {
113 data.push(TextEvent::Composition(None));
114 }
115 }
116}
117
118struct DelegateIvars {
119 data: RefCell<Option<Weak<dyn Data>>>,
120}
121
122define_class!(
123 #[unsafe(super(NSObject))]
124 #[thread_kind = MainThreadOnly]
125 #[name = "FerrokitCoreTextDelegate"]
126 #[ivars = DelegateIvars]
127 struct Delegate;
128
129 unsafe impl NSObjectProtocol for Delegate {}
130
131 unsafe impl NSTextDelegate for Delegate {
132 #[unsafe(method(textDidChange:))]
133 fn text_did_change(&self, _notification: &NSNotification) {
134 let Some(data) = self.data() else { return };
135 data.finish_highlight();
139 if !data.quiet() {
140 data.push(TextEvent::Changed);
141 }
142 }
143 }
144
145 unsafe impl NSTextStorageDelegate for Delegate {
148 #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
154 fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
155 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
156 return;
157 }
158 let Some(data) = self.data().filter(|d| !d.composing()) else { return };
159 if data.highlight(Some(range)) {
160 let weak = self.ivars().data.borrow().clone();
163 let block = block2::RcBlock::new(move || {
164 if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
165 objc2::rc::autoreleasepool(|_| d.finish_highlight());
166 }
167 });
168 let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
169 unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
171 main.wake_up();
172 }
173 }
174
175 #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
176 fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
177 if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
178 return;
179 }
180 let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
181 data.push(TextEvent::Changed);
182 }
183 }
184
185 unsafe impl NSTextViewDelegate for Delegate {
186 #[unsafe(method(textViewDidChangeSelection:))]
187 fn selection_did_change(&self, notification: &NSNotification) {
188 let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
189 let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
190 let text = view.string().to_string();
191 let r = view.selectedRange();
192 data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
193 }
194
195 #[unsafe(method_id(undoManagerForTextView:))]
198 fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
199 self.data().map(|d| d.undo_manager())
200 }
201 }
202);
203
204impl Delegate {
205 fn data(&self) -> Option<Rc<dyn Data>> {
206 self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
207 }
208}
209
210pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
212 let (mut units, mut start, mut end) = (0usize, None, None);
213 for (byte, c) in text.char_indices() {
214 if start.is_none() && units >= location {
215 start = Some(byte);
216 }
217 if end.is_none() && units >= location + length {
218 end = Some(byte);
219 }
220 units += c.len_utf16();
221 }
222 let start = start.unwrap_or(text.len());
223 start..end.unwrap_or(text.len()).max(start)
224}
225
226pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
229 let to_units = |byte: usize| -> usize {
230 let byte = byte.min(text.len());
231 let mut b = byte;
232 while !text.is_char_boundary(b) {
233 b -= 1;
234 }
235 text[..b].encode_utf16().count()
236 };
237 let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
238 (s, e - s)
239}
240
241fn utf16_slice(text: &str, location: usize, length: usize) -> String {
242 text[utf16_to_bytes(text, location, length)].to_string()
243}
244
245struct Inner {
246 id: ViewId,
247 events: RefCell<VecDeque<TextEvent>>,
248 quiet: Cell<bool>,
249 mounted: Cell<bool>,
250 undo: RefCell<Retained<NSUndoManager>>,
251 shared: Cell<bool>,
253 scroll: Retained<NSScrollView>,
254 view: Retained<HostTextView>,
255 _delegate: Retained<Delegate>,
256 font: RefCell<Retained<NSFont>>,
258 highlighter: RefCell<Option<Rc<Highlighter>>>,
259 styling: Cell<bool>,
261 shown: RefCell<Option<(usize, Runs)>>,
264 deferred: Cell<Option<(usize, usize)>>,
266}
267
268type Highlighter = dyn Fn(&str) -> Runs;
269type Runs = Vec<(Range<usize>, TextStyle)>;
270
271#[derive(Debug, Clone, Copy, PartialEq)]
275pub enum Color {
276 Primary,
278 Secondary,
280 Tertiary,
282 Quaternary,
284 Fill,
287 SecondaryFill,
289 TertiaryFill,
291 QuaternaryFill,
294 Accent,
296 Link,
298 Red,
300 Orange,
302 Yellow,
304 Green,
306 Mint,
308 Teal,
310 Cyan,
312 Blue,
314 Indigo,
316 Purple,
318 Pink,
320 Brown,
322 Gray,
324 Background,
326 WindowBackground,
328 ControlBackground,
330 Separator,
332 Clear,
334 Rgb(f64, f64, f64),
336 Rgba(f64, f64, f64, f64),
338}
339
340impl Color {
341 const NAMED: [Color; 28] = [
342 Color::Primary,
343 Color::Secondary,
344 Color::Tertiary,
345 Color::Quaternary,
346 Color::Fill,
347 Color::SecondaryFill,
348 Color::TertiaryFill,
349 Color::QuaternaryFill,
350 Color::Accent,
351 Color::Link,
352 Color::Red,
353 Color::Orange,
354 Color::Yellow,
355 Color::Green,
356 Color::Mint,
357 Color::Teal,
358 Color::Cyan,
359 Color::Blue,
360 Color::Indigo,
361 Color::Purple,
362 Color::Pink,
363 Color::Brown,
364 Color::Gray,
365 Color::Background,
366 Color::WindowBackground,
367 Color::ControlBackground,
368 Color::Separator,
369 Color::Clear,
370 ];
371
372 pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
374 Color::Rgb(r, g, b)
375 }
376
377 pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
379 Color::Rgba(r, g, b, a)
380 }
381
382 pub fn hex(hex: &str) -> Color {
385 let h = hex.trim_start_matches('#');
386 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);
387 match h.len() {
388 8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
389 6 => Color::Rgb(byte(0), byte(2), byte(4)),
390 _ => Color::Rgb(0.0, 0.0, 0.0),
391 }
392 }
393
394 pub fn opacity(self, opacity: f64) -> Color {
396 match self.components() {
397 Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
398 None => self,
399 }
400 }
401
402 pub fn components(self) -> Option<(f64, f64, f64, f64)> {
405 match self {
406 Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
407 Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
408 _ => {
409 let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
410 Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
411 }
412 }
413 }
414
415 pub fn ns(self) -> Retained<NSColor> {
417 match self {
418 Color::Primary => NSColor::textColor(),
419 Color::Secondary => NSColor::secondaryLabelColor(),
420 Color::Tertiary => NSColor::tertiaryLabelColor(),
421 Color::Quaternary => NSColor::quaternaryLabelColor(),
422 Color::Fill => NSColor::systemFillColor(),
423 Color::SecondaryFill => NSColor::secondarySystemFillColor(),
424 Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
425 Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
426 Color::Accent => NSColor::controlAccentColor(),
427 Color::Link => NSColor::linkColor(),
428 Color::Red => NSColor::systemRedColor(),
429 Color::Orange => NSColor::systemOrangeColor(),
430 Color::Yellow => NSColor::systemYellowColor(),
431 Color::Green => NSColor::systemGreenColor(),
432 Color::Mint => NSColor::systemMintColor(),
433 Color::Teal => NSColor::systemTealColor(),
434 Color::Cyan => NSColor::systemCyanColor(),
435 Color::Blue => NSColor::systemBlueColor(),
436 Color::Indigo => NSColor::systemIndigoColor(),
437 Color::Purple => NSColor::systemPurpleColor(),
438 Color::Pink => NSColor::systemPinkColor(),
439 Color::Brown => NSColor::systemBrownColor(),
440 Color::Gray => NSColor::systemGrayColor(),
441 Color::Background => NSColor::textBackgroundColor(),
442 Color::WindowBackground => NSColor::windowBackgroundColor(),
443 Color::ControlBackground => NSColor::controlBackgroundColor(),
444 Color::Separator => NSColor::separatorColor(),
445 Color::Clear => NSColor::clearColor(),
446 Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
447 Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
448 }
449 }
450
451 pub fn from_ns(color: &NSColor) -> Option<Color> {
454 Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
455 let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
456 let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
457 Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
458 })
459 }
460}
461
462#[derive(Debug, Clone, Copy, Default, PartialEq)]
465pub struct TextStyle {
466 pub color: Option<Color>,
468 pub background: Option<Color>,
470 pub bold: bool,
472 pub italic: bool,
474 pub underline: bool,
476}
477
478impl TextStyle {
479 pub fn new() -> Self {
481 Self::default()
482 }
483
484 pub fn color(mut self, color: Color) -> Self {
486 self.color = Some(color);
487 self
488 }
489
490 pub fn background(mut self, color: Color) -> Self {
492 self.background = Some(color);
493 self
494 }
495
496 pub fn bold(mut self) -> Self {
498 self.bold = true;
499 self
500 }
501
502 pub fn italic(mut self) -> Self {
504 self.italic = true;
505 self
506 }
507
508 pub fn underline(mut self) -> Self {
510 self.underline = true;
511 self
512 }
513}
514
515fn utf16_map(text: &str) -> Vec<usize> {
518 let mut map = Vec::with_capacity(text.len() + 1);
519 let mut units = 0;
520 for c in text.chars() {
521 map.extend(std::iter::repeat_n(units, c.len_utf8()));
522 units += c.len_utf16();
523 }
524 map.push(units);
525 map
526}
527
528impl Inner {
529 fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
537 let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
539 let text = storage.string().to_string();
540 let map = utf16_map(&text);
541 let len16 = *map.last().unwrap_or(&0);
542 let shown = self.shown.borrow_mut().take();
543 let region = match (shown, edited) {
546 (Some((old_len, old)), Some(edited)) => {
547 let delta = text.len() as isize - old_len as isize;
548 let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
549 let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
550 let suffix = old[prefix..]
551 .iter()
552 .rev()
553 .zip(runs[prefix..].iter().rev())
554 .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
555 .count();
556 let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
557 let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
558 let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
559 lo..hi
560 }
561 _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
562 };
563 let mut deferred = false;
569 let region = match edited {
570 Some(e) => {
571 let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
572 if inside != region {
573 deferred = self.deferred.get().is_none();
574 self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
575 }
576 inside.start..inside.end.max(inside.start)
577 }
578 None => region,
579 };
580 let font = self.font.borrow().clone();
581 self.styling.set(true);
582 unsafe {
585 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
586 if edited.is_none() {
587 storage.beginEditing();
588 }
589 let base = objc2_foundation::NSDictionary::from_retained_objects(
590 &[NSFontAttributeName, NSForegroundColorAttributeName],
591 &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
592 );
593 storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
594 let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
595 for (range, style) in &runs {
596 let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
597 if start >= end {
598 continue;
599 }
600 let r = NSRange::new(start, end - start);
601 if let Some(c) = style.color {
602 storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
603 }
604 if let Some(c) = style.background {
605 storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
606 }
607 if style.bold || style.italic {
608 let mut f = font.clone();
609 if style.bold {
610 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
611 }
612 if style.italic {
613 f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
614 }
615 storage.addAttribute_value_range(NSFontAttributeName, &f, r);
616 }
617 if style.underline {
618 storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
619 }
620 }
621 if edited.is_none() {
622 storage.endEditing();
623 }
624 }
625 self.styling.set(false);
626 *self.shown.borrow_mut() = Some((text.len(), runs));
627 if edited.is_some() {
635 return deferred;
636 }
637 unsafe {
639 use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
640 let typing = objc2_foundation::NSDictionary::from_retained_objects(
641 &[NSFontAttributeName, NSForegroundColorAttributeName],
642 &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
643 );
644 self.view.setTypingAttributes(&typing);
645 }
646 false
647 }
648}
649
650impl Data for Inner {
651 fn push(&self, event: TextEvent) {
652 let mut events = self.events.borrow_mut();
653 if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
656 return;
657 }
658 if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
660 events.pop_back();
661 }
662 events.push_back(event);
663 drop(events);
664 crate::request_redraw();
665 }
666
667 fn quiet(&self) -> bool {
668 self.quiet.get()
669 }
670
671 fn composing(&self) -> bool {
672 self.view.hasMarkedText()
673 }
674
675 fn undo_manager(&self) -> Retained<NSUndoManager> {
676 self.undo.borrow().clone()
677 }
678
679 fn highlight(&self, edited: Option<NSRange>) -> bool {
680 if self.styling.get() {
681 return false;
682 }
683 let Some(f) = self.highlighter.borrow().clone() else { return false };
684 let runs = f(&self.view.string().to_string());
685 self.apply_styles(runs, edited, None)
686 }
687
688 fn finish_highlight(&self) {
689 let Some(span) = self.deferred.take() else { return };
690 if self.styling.get() || self.view.hasMarkedText() {
691 return;
692 }
693 let Some(f) = self.highlighter.borrow().clone() else { return };
694 let runs = f(&self.view.string().to_string());
695 self.apply_styles(runs, None, Some(span));
696 }
697}
698
699impl Drop for ViewIvars {
700 fn drop(&mut self) {
701 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
702 }
703}
704
705impl Drop for DelegateIvars {
706 fn drop(&mut self) {
707 crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
708 }
709}
710
711impl Drop for Inner {
712 fn drop(&mut self) {
713 self.view.setDelegate(None);
715 if let Some(storage) = unsafe { self.view.textStorage() } {
716 storage.setDelegate(None);
717 }
718 crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
719 crate::keys::set_accepts_tab(self.id, false);
720 if self.mounted.get() {
721 crate::unmount(self.id);
722 }
723 }
724}
725
726#[derive(Clone)]
728pub struct TextModel {
729 inner: Rc<Inner>,
730}
731
732impl std::fmt::Debug for TextModel {
733 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
734 write!(f, "TextModel({:?})", self.inner.id)
735 }
736}
737
738impl TextModel {
739 pub fn new(id: ViewId, text: &str) -> Self {
743 let mtm = mtm();
744 let size = NSSize::new(400.0, 300.0);
745 let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
746 scroll.setHasVerticalScroller(true);
747 scroll.setAutohidesScrollers(true);
748 scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
749
750 crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
753 crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
754 let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
755 let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
756 view.setMinSize(NSSize::new(0.0, size.height));
757 view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
758 view.setVerticallyResizable(true);
759 view.setHorizontallyResizable(false);
760 view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
761 if let Some(container) = unsafe { view.textContainer() } {
763 container.setContainerSize(NSSize::new(size.width, f64::MAX));
764 container.setWidthTracksTextView(true);
765 }
766 view.setRichText(false);
767 view.setImportsGraphics(false);
768 view.setAllowsUndo(true);
769 view.setUsesFindBar(true);
770 view.setContinuousSpellCheckingEnabled(true);
771 view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
772 view.setTextContainerInset(NSSize::new(4.0, 6.0));
773 view.setString(&NSString::from_str(text));
774 scroll.setDocumentView(Some(&view));
775
776 let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
777 let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
778
779 let inner = Rc::new(Inner {
780 id,
781 events: RefCell::new(VecDeque::new()),
782 quiet: Cell::new(false),
783 mounted: Cell::new(false),
784 undo: RefCell::new(NSUndoManager::new(mtm)),
785 shared: Cell::new(false),
786 scroll,
787 view: view.clone(),
788 _delegate: delegate.clone(),
789 font: RefCell::new(NSFont::systemFontOfSize(13.0)),
790 highlighter: RefCell::new(None),
791 styling: Cell::new(false),
792 shown: RefCell::new(None),
793 deferred: Cell::new(None),
794 });
795 let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
796 *view.ivars().data.borrow_mut() = Some(weak.clone());
797 *delegate.ivars().data.borrow_mut() = Some(weak);
798 view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
800 if let Some(storage) = unsafe { view.textStorage() } {
801 storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
803 }
804 crate::keys::set_accepts_tab(id, true);
805 Self { inner }
806 }
807
808 pub fn id(&self) -> ViewId {
810 self.inner.id
811 }
812
813 pub fn ensure_mounted(&self) {
816 if !self.inner.mounted.get() && crate::is_attached() {
817 crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
818 self.inner.mounted.set(true);
819 }
820 }
821
822 pub fn text(&self) -> String {
824 self.inner.view.string().to_string()
825 }
826
827 pub fn set_text(&self, text: &str) {
830 self.inner.quiet.set(true);
831 self.inner.view.setString(&NSString::from_str(text));
832 self.inner.quiet.set(false);
833 self.clear_undo();
834 }
835
836 fn clear_undo(&self) {
839 let undo = self.inner.undo.borrow();
840 if self.inner.shared.get() {
841 unsafe {
843 undo.removeAllActionsWithTarget(&self.inner.view);
844 if let Some(storage) = self.inner.view.textStorage() {
845 undo.removeAllActionsWithTarget(&storage);
846 }
847 }
848 } else {
849 undo.removeAllActions();
850 }
851 }
852
853 pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
858 self.clear_undo();
859 let mtm = MainThreadMarker::from(&*self.inner.view);
860 let next = match manager {
861 Some(m) => m.retain(),
862 None => NSUndoManager::new(mtm),
863 };
864 *self.inner.undo.borrow_mut() = next;
865 self.inner.shared.set(manager.is_some());
866 }
867
868 pub fn undo_manager(&self) -> Retained<NSUndoManager> {
870 self.inner.undo.borrow().clone()
871 }
872
873 pub fn replace_selection(&self, text: &str) {
875 let view = &self.inner.view;
876 let range = view.selectedRange();
877 let string = NSString::from_str(text);
878 if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
879 view.replaceCharactersInRange_withString(range, &string);
880 view.didChangeText();
881 }
882 }
883
884 pub fn selection(&self) -> Range<usize> {
886 let r = self.inner.view.selectedRange();
887 utf16_to_bytes(&self.text(), r.location, r.length)
888 }
889
890 pub fn set_selection(&self, range: Range<usize>) {
892 let (location, length) = bytes_to_utf16(&self.text(), range);
893 self.inner.quiet.set(true);
894 self.inner.view.setSelectedRange(NSRange::new(location, length));
895 self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
896 self.inner.quiet.set(false);
897 }
898
899 pub fn composition(&self) -> Option<String> {
901 let view = &self.inner.view;
902 view.hasMarkedText().then(|| {
903 let r = view.markedRange();
904 utf16_slice(&view.string().to_string(), r.location, r.length)
905 })
906 }
907
908 pub fn set_editable(&self, editable: bool) {
910 self.inner.view.setEditable(editable);
911 }
912
913 pub fn is_editable(&self) -> bool {
915 self.inner.view.isEditable()
916 }
917
918 pub fn set_font(&self, name: Option<&str>, size: f64) {
920 let font = match name {
921 Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
922 None => Some(NSFont::systemFontOfSize(size)),
923 };
924 if let Some(font) = font {
925 self.inner.view.setFont(Some(&font));
926 *self.inner.font.borrow_mut() = font;
927 self.inner.highlight(None);
928 }
929 }
930
931 pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
937 *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
938 self.restyle();
939 }
940
941 pub fn restyle(&self) {
944 if self.inner.highlighter.borrow().is_some() {
945 self.inner.highlight(None);
946 } else {
947 self.inner.apply_styles(Vec::new(), None, None);
948 }
949 }
950
951 pub fn style_at(&self, offset: usize) -> TextStyle {
953 let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
955 let text = storage.string().to_string();
956 let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
957 let mut style = TextStyle::default();
958 unsafe {
960 use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
961 let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
962 style.color = at(NSForegroundColorAttributeName)
963 .and_then(|c| c.downcast::<NSColor>().ok())
964 .and_then(|c| Color::from_ns(&c))
965 .filter(|c| *c != Color::Primary);
966 style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
967 if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
968 let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
969 style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
970 style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
971 }
972 style.underline = at(NSUnderlineStyleAttributeName)
973 .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
974 .is_some_and(|n| n.integerValue() != 0);
975 }
976 style
977 }
978
979 pub fn set_rich(&self, rich: bool) {
986 let v = &self.inner.view;
987 v.setRichText(rich);
988 v.setImportsGraphics(rich);
989 v.setUsesFontPanel(rich);
990 v.setUsesRuler(rich);
991 if !rich {
992 v.setUsesInspectorBar(false);
993 v.setRulerVisible(false);
994 }
995 }
996
997 pub fn is_rich(&self) -> bool {
999 self.inner.view.isRichText()
1000 }
1001
1002 pub fn set_format_bar(&self, shown: bool) {
1005 self.inner.view.setUsesInspectorBar(shown);
1006 }
1007
1008 pub fn has_format_bar(&self) -> bool {
1010 self.inner.view.usesInspectorBar()
1011 }
1012
1013 pub fn set_ruler_visible(&self, shown: bool) {
1017 self.inner.view.setRulerVisible(shown);
1018 }
1019
1020 pub fn is_ruler_visible(&self) -> bool {
1022 self.inner.view.isRulerVisible()
1023 }
1024
1025 fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
1026 let storage = unsafe { self.inner.view.textStorage() }?;
1028 let len = storage.length();
1029 Some((storage, NSRange::new(0, len)))
1030 }
1031
1032 pub fn rtf(&self) -> Vec<u8> {
1035 let Some((storage, range)) = self.whole() else { return Vec::new() };
1036 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
1037 let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
1039 data.map(|d| d.to_vec()).unwrap_or_default()
1040 }
1041
1042 pub fn set_rtf(&self, rtf: &[u8]) -> bool {
1046 let data = objc2_foundation::NSData::with_bytes(rtf);
1047 let text: Option<Retained<objc2_foundation::NSAttributedString>> =
1049 unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
1050 self.load(text)
1051 }
1052
1053 fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
1054 let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
1055 self.inner.quiet.set(true);
1056 storage.setAttributedString(&text);
1057 self.inner.quiet.set(false);
1058 self.clear_undo();
1059 true
1060 }
1061
1062 pub fn html(&self) -> String {
1065 let Some((storage, range)) = self.whole() else { return String::new() };
1066 let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
1069 let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1070 let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
1071 msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
1072 };
1073 data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
1074 }
1075
1076 pub fn set_html(&self, html: &str) -> bool {
1080 let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
1081 let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
1083 let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
1084 let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
1086 &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
1087 &[kind, utf8.as_ref()],
1088 );
1089 msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
1090 };
1091 self.load(text)
1092 }
1093
1094 pub fn font_size(&self) -> Option<f64> {
1096 self.inner.view.font().map(|f| f.pointSize())
1097 }
1098
1099 pub fn set_insets(&self, horizontal: f64, vertical: f64) {
1101 self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
1102 }
1103
1104 pub fn set_spell_checking(&self, on: bool) {
1106 self.inner.view.setContinuousSpellCheckingEnabled(on);
1107 }
1108
1109 pub fn set_grammar_checking(&self, on: bool) {
1111 self.inner.view.setGrammarCheckingEnabled(on);
1112 }
1113
1114 pub fn set_code_input(&self, code: bool) {
1119 let view = &self.inner.view;
1120 view.setAutomaticQuoteSubstitutionEnabled(!code);
1121 view.setAutomaticDashSubstitutionEnabled(!code);
1122 view.setAutomaticTextReplacementEnabled(!code);
1123 view.setAutomaticSpellingCorrectionEnabled(!code);
1124 view.setContinuousSpellCheckingEnabled(!code);
1125 view.setSmartInsertDeleteEnabled(!code);
1126 }
1127
1128 pub fn set_accepts_tab(&self, accepts: bool) {
1130 crate::keys::set_accepts_tab(self.inner.id, accepts);
1131 }
1132
1133 pub fn show_find(&self) {
1135 let item = objc2_app_kit::NSMenuItem::new(mtm());
1137 item.setTag(1);
1138 let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
1139 }
1140
1141 pub fn is_find_visible(&self) -> bool {
1143 unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
1144 }
1145
1146 pub fn can_undo(&self) -> bool {
1148 self.inner.undo.borrow().canUndo()
1149 }
1150
1151 pub fn undo(&self) {
1153 let undo = self.undo_manager();
1154 if undo.canUndo() {
1155 undo.undo();
1156 }
1157 }
1158
1159 pub fn drain_events(&self) -> Vec<TextEvent> {
1161 self.inner.events.borrow_mut().drain(..).collect()
1162 }
1163
1164 pub fn scroll_view(&self) -> Retained<NSScrollView> {
1167 self.inner.scroll.clone()
1168 }
1169
1170 pub fn text_view(&self) -> Retained<NSTextView> {
1172 Retained::into_super(self.inner.view.clone())
1173 }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178 use super::{bytes_to_utf16, utf16_to_bytes};
1179
1180 #[test]
1181 fn offsets_round_trip() {
1182 let t = "a東京😀b";
1183 assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
1185 assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
1186 assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
1187 assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
1188 assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
1189 assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
1190 }
1191}