use objc2_foundation::NSArray;
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::ops::Range;
use std::rc::{Rc, Weak};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send};
use objc2_app_kit::{
NSColor, NSFont, NSResponder, NSScrollView, NSText, NSTextDelegate, NSTextInputClient, NSTextStorage, NSTextStorageDelegate,
NSTextStorageEditActions, NSTextView, NSTextViewDelegate, NSAutoresizingMaskOptions, NSView,
};
use objc2_foundation::{NSNotification, NSPoint, NSRange, NSRect, NSSize, NSString, NSUndoManager};
use crate::ViewId;
use crate::host::mtm;
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
pub enum TextEvent {
Changed,
Selection(Range<usize>),
Composition(Option<String>),
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Completion {
pub range: Range<usize>,
pub items: Vec<String>,
}
type Completer = dyn Fn(&str, usize) -> Option<Completion>;
const RETURN_MOVEMENT: isize = 0x10;
const TAB_MOVEMENT: isize = 0x11;
const OTHER_MOVEMENT: isize = 0;
trait Data {
fn push(&self, event: TextEvent);
fn complete(&self) -> Option<(NSRange, Vec<String>)>;
fn has_completer(&self) -> bool;
fn quiet(&self) -> bool;
fn composing(&self) -> bool;
fn undo_manager(&self) -> Retained<NSUndoManager>;
fn offered(&self, items: &[String]);
fn highlight(&self, edited: Option<NSRange>) -> bool;
fn finish_highlight(&self);
}
struct ViewIvars {
data: RefCell<Option<Weak<dyn Data>>>,
composing: Cell<bool>,
}
define_class!(
#[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreTextView"]
#[ivars = ViewIvars]
struct HostTextView;
impl HostTextView {
#[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
crate::boundary::guarded("a text view (set_marked_text)", (), || {
let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
self.composition_changed();
})
}
#[unsafe(method(unmarkText))]
fn unmark_text(&self) {
crate::boundary::guarded("a text view (unmark_text)", (), || {
let () = unsafe { msg_send![super(self), unmarkText] };
self.composition_changed();
})
}
#[unsafe(method(insertText:replacementRange:))]
fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
crate::boundary::guarded("a text view (insert_text)", (), || {
let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
self.composition_changed();
let typed = string.downcast_ref::<NSString>().map(|s| s.to_string()).unwrap_or_default();
let mut chars = typed.chars();
if let (Some(c), None) = (chars.next(), chars.next())
&& (c.is_alphanumeric() || c == '_' || c == '.')
&& !self.hasMarkedText()
&& self.data().is_some_and(|d| d.has_completer())
{
self.complete_soon();
}
})
}
#[unsafe(method(ferrokitCompleteNow:))]
fn complete_now(&self, _sender: Option<&AnyObject>) {
crate::boundary::guarded("a text view (complete_now)", (), || {
if self.hasMarkedText() || self.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
return;
}
objc2::rc::autoreleasepool(|_| unsafe { self.complete(None) });
})
}
#[unsafe(method(rangeForUserCompletion))]
fn range_for_user_completion(&self) -> NSRange {
crate::boundary::guarded("a text view (range_for_user_completion)", NSRange::new(0, 0), || {
if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
return range;
}
unsafe { msg_send![super(self), rangeForUserCompletion] }
})
}
#[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
crate::boundary::guarded("a text view (insert_completion)", (), || {
if self.data().is_some_and(|d| d.has_completer()) {
let clicked = || {
let mtm = MainThreadMarker::from(self);
objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
use objc2_app_kit::NSEventType as T;
matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
})
};
let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
if !chosen {
return;
}
}
let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
})
}
}
);
impl HostTextView {
fn data(&self) -> Option<Rc<dyn Data>> {
self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
}
fn complete_soon(&self) {
let sel = objc2::sel!(ferrokitCompleteNow:);
unsafe {
let () = msg_send![objc2::class!(NSObject), cancelPreviousPerformRequestsWithTarget: self, selector: sel, object: Option::<&AnyObject>::None];
let () = msg_send![self, performSelector: sel, withObject: Option::<&AnyObject>::None, afterDelay: 0.0f64];
}
}
fn composition_changed(&self) {
let composing = self.hasMarkedText();
let was = self.ivars().composing.replace(composing);
let Some(data) = self.data() else { return };
if composing {
let range = self.markedRange();
let marked = self.string().to_string();
let marked = utf16_slice(&marked, range.location, range.length);
data.push(TextEvent::Composition(Some(marked)));
} else if was {
data.push(TextEvent::Composition(None));
}
}
}
struct DelegateIvars {
data: RefCell<Option<Weak<dyn Data>>>,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreTextDelegate"]
#[ivars = DelegateIvars]
struct Delegate;
unsafe impl NSObjectProtocol for Delegate {}
unsafe impl NSTextDelegate for Delegate {
#[unsafe(method(textDidChange:))]
fn text_did_change(&self, _notification: &NSNotification) {
crate::boundary::guarded("a text view (text_did_change)", (), || {
let Some(data) = self.data() else { return };
data.finish_highlight();
if !data.quiet() {
data.push(TextEvent::Changed);
}
})
}
}
unsafe impl NSTextStorageDelegate for Delegate {
#[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
crate::boundary::guarded("a text view (will_process_editing)", (), || {
if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
return;
}
let Some(data) = self.data().filter(|d| !d.composing()) else { return };
if data.highlight(Some(range)) {
let weak = self.ivars().data.borrow().clone();
let block = block2::RcBlock::new(move || {
if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
objc2::rc::autoreleasepool(|_| d.finish_highlight());
}
});
let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
main.wake_up();
}
})
}
#[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
crate::boundary::guarded("a text view (did_process_editing)", (), || {
if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
return;
}
let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
data.push(TextEvent::Changed);
})
}
}
unsafe impl NSTextViewDelegate for Delegate {
#[unsafe(method(textViewDidChangeSelection:))]
fn selection_did_change(&self, notification: &NSNotification) {
crate::boundary::guarded("a text view (selection_did_change)", (), || {
let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
let text = view.string().to_string();
let r = view.selectedRange();
data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
})
}
#[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
crate::boundary::guarded("a text view (completions)", None, || {
Some(self.completion_words(words, index))
})
}
#[unsafe(method_id(undoManagerForTextView:))]
fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
crate::boundary::guarded("a text view (undo_manager_for)", None, || {
self.data().map(|d| d.undo_manager())
})
}
}
);
impl Delegate {
fn data(&self) -> Option<Rc<dyn Data>> {
self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
}
fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
let items = data.complete().map(|(_, items)| items).unwrap_or_default();
if !index.is_null() {
unsafe { *index = if items.is_empty() { -1 } else { 0 } };
}
data.offered(&items);
let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
NSArray::from_retained_slice(&items)
}
}
pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
let (mut units, mut start, mut end) = (0usize, None, None);
for (byte, c) in text.char_indices() {
if start.is_none() && units >= location {
start = Some(byte);
}
if end.is_none() && units >= location + length {
end = Some(byte);
}
units += c.len_utf16();
}
let start = start.unwrap_or(text.len());
start..end.unwrap_or(text.len()).max(start)
}
pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
let to_units = |byte: usize| -> usize {
let byte = byte.min(text.len());
let mut b = byte;
while !text.is_char_boundary(b) {
b -= 1;
}
text[..b].encode_utf16().count()
};
let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
(s, e - s)
}
fn utf16_slice(text: &str, location: usize, length: usize) -> String {
text[utf16_to_bytes(text, location, length)].to_string()
}
struct Inner {
id: ViewId,
events: RefCell<VecDeque<TextEvent>>,
quiet: Cell<bool>,
mounted: Cell<bool>,
undo: RefCell<Retained<NSUndoManager>>,
shared: Cell<bool>,
scroll: Retained<NSScrollView>,
view: Retained<HostTextView>,
_delegate: Retained<Delegate>,
font: RefCell<Retained<NSFont>>,
highlighter: RefCell<Option<Rc<Highlighter>>>,
completer: RefCell<Option<Rc<Completer>>>,
offered: RefCell<Vec<String>>,
styling: Cell<bool>,
shown: RefCell<Option<(usize, Runs)>>,
deferred: Cell<Option<(usize, usize)>>,
}
type Highlighter = dyn Fn(&str) -> Runs;
type Runs = Vec<(Range<usize>, TextStyle)>;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Color {
Primary,
Secondary,
Tertiary,
Quaternary,
Fill,
SecondaryFill,
TertiaryFill,
QuaternaryFill,
Accent,
Link,
Red,
Orange,
Yellow,
Green,
Mint,
Teal,
Cyan,
Blue,
Indigo,
Purple,
Pink,
Brown,
Gray,
Background,
WindowBackground,
ControlBackground,
Separator,
Clear,
Rgb(f64, f64, f64),
Rgba(f64, f64, f64, f64),
}
impl Color {
const NAMED: [Color; 28] = [
Color::Primary,
Color::Secondary,
Color::Tertiary,
Color::Quaternary,
Color::Fill,
Color::SecondaryFill,
Color::TertiaryFill,
Color::QuaternaryFill,
Color::Accent,
Color::Link,
Color::Red,
Color::Orange,
Color::Yellow,
Color::Green,
Color::Mint,
Color::Teal,
Color::Cyan,
Color::Blue,
Color::Indigo,
Color::Purple,
Color::Pink,
Color::Brown,
Color::Gray,
Color::Background,
Color::WindowBackground,
Color::ControlBackground,
Color::Separator,
Color::Clear,
];
pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
Color::Rgb(r, g, b)
}
pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
Color::Rgba(r, g, b, a)
}
pub fn hex(hex: &str) -> Color {
let h = hex.trim_start_matches('#');
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);
match h.len() {
8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
6 => Color::Rgb(byte(0), byte(2), byte(4)),
_ => Color::Rgb(0.0, 0.0, 0.0),
}
}
pub fn opacity(self, opacity: f64) -> Color {
match self.components() {
Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
None => self,
}
}
pub fn components(self) -> Option<(f64, f64, f64, f64)> {
match self {
Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
_ => {
let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
}
}
}
pub fn ns(self) -> Retained<NSColor> {
match self {
Color::Primary => NSColor::textColor(),
Color::Secondary => NSColor::secondaryLabelColor(),
Color::Tertiary => NSColor::tertiaryLabelColor(),
Color::Quaternary => NSColor::quaternaryLabelColor(),
Color::Fill => NSColor::systemFillColor(),
Color::SecondaryFill => NSColor::secondarySystemFillColor(),
Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
Color::Accent => NSColor::controlAccentColor(),
Color::Link => NSColor::linkColor(),
Color::Red => NSColor::systemRedColor(),
Color::Orange => NSColor::systemOrangeColor(),
Color::Yellow => NSColor::systemYellowColor(),
Color::Green => NSColor::systemGreenColor(),
Color::Mint => NSColor::systemMintColor(),
Color::Teal => NSColor::systemTealColor(),
Color::Cyan => NSColor::systemCyanColor(),
Color::Blue => NSColor::systemBlueColor(),
Color::Indigo => NSColor::systemIndigoColor(),
Color::Purple => NSColor::systemPurpleColor(),
Color::Pink => NSColor::systemPinkColor(),
Color::Brown => NSColor::systemBrownColor(),
Color::Gray => NSColor::systemGrayColor(),
Color::Background => NSColor::textBackgroundColor(),
Color::WindowBackground => NSColor::windowBackgroundColor(),
Color::ControlBackground => NSColor::controlBackgroundColor(),
Color::Separator => NSColor::separatorColor(),
Color::Clear => NSColor::clearColor(),
Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
}
}
pub fn from_ns(color: &NSColor) -> Option<Color> {
Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TextStyle {
pub color: Option<Color>,
pub background: Option<Color>,
pub bold: bool,
pub italic: bool,
pub underline: bool,
}
impl TextStyle {
pub fn new() -> Self {
Self::default()
}
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
pub fn bold(mut self) -> Self {
self.bold = true;
self
}
pub fn italic(mut self) -> Self {
self.italic = true;
self
}
pub fn underline(mut self) -> Self {
self.underline = true;
self
}
}
fn utf16_map(text: &str) -> Vec<usize> {
let mut map = Vec::with_capacity(text.len() + 1);
let mut units = 0;
for c in text.chars() {
map.extend(std::iter::repeat_n(units, c.len_utf8()));
units += c.len_utf16();
}
map.push(units);
map
}
impl Inner {
fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
let text = storage.string().to_string();
let map = utf16_map(&text);
let len16 = *map.last().unwrap_or(&0);
let shown = self.shown.borrow_mut().take();
let region = match (shown, edited) {
(Some((old_len, old)), Some(edited)) => {
let delta = text.len() as isize - old_len as isize;
let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
let suffix = old[prefix..]
.iter()
.rev()
.zip(runs[prefix..].iter().rev())
.take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
.count();
let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
let clamp = |i: isize| (i.max(0) as usize).min(text.len());
let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
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))]);
let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
lo..hi
}
_ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
};
let mut deferred = false;
let region = match edited {
Some(e) => {
let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
if inside != region {
deferred = self.deferred.get().is_none();
self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
}
inside.start..inside.end.max(inside.start)
}
None => region,
};
let font = self.font.borrow().clone();
self.styling.set(true);
unsafe {
use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
if edited.is_none() {
storage.beginEditing();
}
let base = objc2_foundation::NSDictionary::from_retained_objects(
&[NSFontAttributeName, NSForegroundColorAttributeName],
&[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
);
storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
for (range, style) in &runs {
let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
if start >= end {
continue;
}
let r = NSRange::new(start, end - start);
if let Some(c) = style.color {
storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
}
if let Some(c) = style.background {
storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
}
if style.bold || style.italic {
let mut f = font.clone();
if style.bold {
f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
}
if style.italic {
f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
}
storage.addAttribute_value_range(NSFontAttributeName, &f, r);
}
if style.underline {
storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
}
}
if edited.is_none() {
storage.endEditing();
}
}
self.styling.set(false);
*self.shown.borrow_mut() = Some((text.len(), runs));
if edited.is_some() {
return deferred;
}
unsafe {
use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
let typing = objc2_foundation::NSDictionary::from_retained_objects(
&[NSFontAttributeName, NSForegroundColorAttributeName],
&[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
);
self.view.setTypingAttributes(&typing);
}
false
}
}
impl Data for Inner {
fn push(&self, event: TextEvent) {
let mut events = self.events.borrow_mut();
if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
return;
}
if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
events.pop_back();
}
events.push_back(event);
drop(events);
crate::request_redraw();
}
fn quiet(&self) -> bool {
self.quiet.get()
}
fn complete(&self) -> Option<(NSRange, Vec<String>)> {
let f = self.completer.borrow().clone()?;
let text = self.view.string().to_string();
let sel = self.view.selectedRange();
let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
let c = f(&text, caret)?;
let start = c.range.start.min(caret);
let (location, length) = bytes_to_utf16(&text, start..caret);
Some((NSRange::new(location, length), c.items))
}
fn has_completer(&self) -> bool {
self.completer.borrow().is_some()
}
fn offered(&self, items: &[String]) {
*self.offered.borrow_mut() = items.to_vec();
}
fn composing(&self) -> bool {
self.view.hasMarkedText()
}
fn undo_manager(&self) -> Retained<NSUndoManager> {
self.undo.borrow().clone()
}
fn highlight(&self, edited: Option<NSRange>) -> bool {
if self.styling.get() {
return false;
}
let Some(f) = self.highlighter.borrow().clone() else { return false };
let runs = f(&self.view.string().to_string());
self.apply_styles(runs, edited, None)
}
fn finish_highlight(&self) {
let Some(span) = self.deferred.take() else { return };
if self.styling.get() || self.view.hasMarkedText() {
return;
}
let Some(f) = self.highlighter.borrow().clone() else { return };
let runs = f(&self.view.string().to_string());
self.apply_styles(runs, None, Some(span));
}
}
impl Drop for ViewIvars {
fn drop(&mut self) {
crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
impl Drop for DelegateIvars {
fn drop(&mut self) {
crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
impl Drop for Inner {
fn drop(&mut self) {
self.view.setDelegate(None);
if let Some(storage) = unsafe { self.view.textStorage() } {
storage.setDelegate(None);
}
crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
crate::keys::set_accepts_tab(self.id, false);
if self.mounted.get() {
crate::unmount(self.id);
}
}
}
#[derive(Clone)]
pub struct TextModel {
inner: Rc<Inner>,
}
impl std::fmt::Debug for TextModel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TextModel({:?})", self.inner.id)
}
}
impl TextModel {
pub fn new(text: &str) -> Self {
Self::with_id(ViewId::next(), text)
}
fn with_id(id: ViewId, text: &str) -> Self {
let mtm = mtm();
let size = NSSize::new(400.0, 300.0);
let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
scroll.setHasVerticalScroller(true);
scroll.setAutohidesScrollers(true);
scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);
crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
view.setMinSize(NSSize::new(0.0, size.height));
view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
view.setVerticallyResizable(true);
view.setHorizontallyResizable(false);
view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
if let Some(container) = unsafe { view.textContainer() } {
container.setContainerSize(NSSize::new(size.width, f64::MAX));
container.setWidthTracksTextView(true);
}
view.setRichText(false);
view.setImportsGraphics(false);
view.setAllowsUndo(true);
view.setUsesFindBar(true);
view.setContinuousSpellCheckingEnabled(true);
view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
view.setTextContainerInset(NSSize::new(4.0, 6.0));
view.setString(&NSString::from_str(text));
scroll.setDocumentView(Some(&view));
let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };
let inner = Rc::new(Inner {
id,
events: RefCell::new(VecDeque::new()),
quiet: Cell::new(false),
mounted: Cell::new(false),
undo: RefCell::new(NSUndoManager::new(mtm)),
shared: Cell::new(false),
scroll,
view: view.clone(),
_delegate: delegate.clone(),
font: RefCell::new(NSFont::systemFontOfSize(13.0)),
highlighter: RefCell::new(None),
completer: RefCell::new(None),
offered: RefCell::new(Vec::new()),
styling: Cell::new(false),
shown: RefCell::new(None),
deferred: Cell::new(None),
});
let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
*view.ivars().data.borrow_mut() = Some(weak.clone());
*delegate.ivars().data.borrow_mut() = Some(weak);
view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
if let Some(storage) = unsafe { view.textStorage() } {
storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
}
crate::keys::set_accepts_tab(id, true);
Self { inner }
}
pub fn id(&self) -> ViewId {
self.inner.id
}
#[doc(hidden)]
pub fn ensure_mounted(&self) {
if !self.inner.mounted.get() && crate::is_attached() {
crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
self.inner.mounted.set(true);
}
}
pub fn text(&self) -> String {
self.inner.view.string().to_string()
}
pub fn set_text(&self, text: &str) {
self.inner.quiet.set(true);
self.inner.view.setString(&NSString::from_str(text));
self.inner.quiet.set(false);
self.clear_undo();
}
fn clear_undo(&self) {
let undo = self.inner.undo.borrow();
if self.inner.shared.get() {
unsafe {
undo.removeAllActionsWithTarget(&self.inner.view);
if let Some(storage) = self.inner.view.textStorage() {
undo.removeAllActionsWithTarget(&storage);
}
}
} else {
undo.removeAllActions();
}
}
pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
self.clear_undo();
let mtm = MainThreadMarker::from(&*self.inner.view);
let next = match manager {
Some(m) => m.retain(),
None => NSUndoManager::new(mtm),
};
*self.inner.undo.borrow_mut() = next;
self.inner.shared.set(manager.is_some());
}
pub fn undo_manager(&self) -> Retained<NSUndoManager> {
self.inner.undo.borrow().clone()
}
pub fn replace_selection(&self, text: &str) {
let view = &self.inner.view;
let range = view.selectedRange();
let string = NSString::from_str(text);
if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
view.replaceCharactersInRange_withString(range, &string);
view.didChangeText();
}
}
pub fn selection(&self) -> Range<usize> {
let r = self.inner.view.selectedRange();
utf16_to_bytes(&self.text(), r.location, r.length)
}
pub fn set_selection(&self, range: Range<usize>) {
let (location, length) = bytes_to_utf16(&self.text(), range);
self.inner.quiet.set(true);
self.inner.view.setSelectedRange(NSRange::new(location, length));
self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
self.inner.quiet.set(false);
}
pub fn composition(&self) -> Option<String> {
let view = &self.inner.view;
view.hasMarkedText().then(|| {
let r = view.markedRange();
utf16_slice(&view.string().to_string(), r.location, r.length)
})
}
pub fn set_editable(&self, editable: bool) {
self.inner.view.setEditable(editable);
}
pub fn is_editable(&self) -> bool {
self.inner.view.isEditable()
}
pub fn set_font(&self, name: Option<&str>, size: f64) {
let font = match name {
Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
None => Some(NSFont::systemFontOfSize(size)),
};
if let Some(font) = font {
self.inner.view.setFont(Some(&font));
*self.inner.font.borrow_mut() = font;
self.inner.highlight(None);
}
}
pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
*self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
}
pub fn complete(&self) {
unsafe { self.inner.view.complete(None) };
}
pub fn offered_completions(&self) -> Vec<String> {
self.inner.offered.borrow().clone()
}
pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
*self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
self.restyle();
}
pub fn restyle(&self) {
if self.inner.highlighter.borrow().is_some() {
self.inner.highlight(None);
} else {
self.inner.apply_styles(Vec::new(), None, None);
}
}
pub fn style_at(&self, offset: usize) -> TextStyle {
let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
let text = storage.string().to_string();
let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
let mut style = TextStyle::default();
unsafe {
use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
style.color = at(NSForegroundColorAttributeName)
.and_then(|c| c.downcast::<NSColor>().ok())
.and_then(|c| Color::from_ns(&c))
.filter(|c| *c != Color::Primary);
style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
}
style.underline = at(NSUnderlineStyleAttributeName)
.and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
.is_some_and(|n| n.integerValue() != 0);
}
style
}
pub fn set_rich(&self, rich: bool) {
let v = &self.inner.view;
v.setRichText(rich);
v.setImportsGraphics(rich);
v.setUsesFontPanel(rich);
v.setUsesRuler(rich);
if !rich {
v.setUsesInspectorBar(false);
v.setRulerVisible(false);
}
}
pub fn is_rich(&self) -> bool {
self.inner.view.isRichText()
}
pub fn set_format_bar(&self, shown: bool) {
self.inner.view.setUsesInspectorBar(shown);
}
pub fn has_format_bar(&self) -> bool {
self.inner.view.usesInspectorBar()
}
pub fn set_ruler_visible(&self, shown: bool) {
self.inner.view.setRulerVisible(shown);
}
pub fn is_ruler_visible(&self) -> bool {
self.inner.view.isRulerVisible()
}
fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
let storage = unsafe { self.inner.view.textStorage() }?;
let len = storage.length();
Some((storage, NSRange::new(0, len)))
}
pub fn rtf(&self) -> Vec<u8> {
let Some((storage, range)) = self.whole() else { return Vec::new() };
let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
data.map(|d| d.to_vec()).unwrap_or_default()
}
pub fn set_rtf(&self, rtf: &[u8]) -> bool {
let data = objc2_foundation::NSData::with_bytes(rtf);
let text: Option<Retained<objc2_foundation::NSAttributedString>> =
unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
self.load(text)
}
fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
self.inner.quiet.set(true);
storage.setAttributedString(&text);
self.inner.quiet.set(false);
self.clear_undo();
true
}
pub fn html(&self) -> String {
let Some((storage, range)) = self.whole() else { return String::new() };
let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
};
data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
}
pub fn set_html(&self, html: &str) -> bool {
let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
let utf8 = objc2_foundation::NSNumber::new_usize(4); let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
&[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
&[kind, utf8.as_ref()],
);
msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
};
self.load(text)
}
pub fn font_size(&self) -> Option<f64> {
self.inner.view.font().map(|f| f.pointSize())
}
pub fn set_insets(&self, horizontal: f64, vertical: f64) {
self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
}
pub fn set_spell_checking(&self, on: bool) {
self.inner.view.setContinuousSpellCheckingEnabled(on);
}
pub fn set_grammar_checking(&self, on: bool) {
self.inner.view.setGrammarCheckingEnabled(on);
}
pub fn set_code_input(&self, code: bool) {
let view = &self.inner.view;
view.setAutomaticQuoteSubstitutionEnabled(!code);
view.setAutomaticDashSubstitutionEnabled(!code);
view.setAutomaticTextReplacementEnabled(!code);
view.setAutomaticSpellingCorrectionEnabled(!code);
view.setContinuousSpellCheckingEnabled(!code);
view.setSmartInsertDeleteEnabled(!code);
}
pub fn set_accepts_tab(&self, accepts: bool) {
crate::keys::set_accepts_tab(self.inner.id, accepts);
}
pub fn show_find(&self) {
let item = objc2_app_kit::NSMenuItem::new(mtm());
item.setTag(1);
let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
}
pub fn set_wraps(&self, wraps: bool) {
let (view, scroll) = (&self.inner.view, &self.inner.scroll);
let Some(container) = (unsafe { view.textContainer() }) else { return };
if container.widthTracksTextView() == wraps {
return;
}
let width = scroll.contentSize().width;
scroll.setHasHorizontalScroller(!wraps);
view.setHorizontallyResizable(!wraps);
container.setWidthTracksTextView(wraps);
if wraps {
let mut frame = view.frame();
frame.size.width = width;
view.setFrame(frame);
container.setContainerSize(NSSize::new(width, f64::MAX));
} else {
container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
}
view.sizeToFit();
view.setNeedsDisplay(true);
}
pub fn wraps(&self) -> bool {
unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
}
pub fn is_find_visible(&self) -> bool {
unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
}
pub fn can_undo(&self) -> bool {
self.inner.undo.borrow().canUndo()
}
pub fn undo(&self) {
let undo = self.undo_manager();
if undo.canUndo() {
undo.undo();
}
}
#[doc(hidden)]
pub fn drain_events(&self) -> Vec<TextEvent> {
self.inner.events.borrow_mut().drain(..).collect()
}
pub fn scroll_view(&self) -> Retained<NSScrollView> {
self.inner.scroll.clone()
}
pub fn text_view(&self) -> Retained<NSTextView> {
Retained::into_super(self.inner.view.clone())
}
}
#[cfg(test)]
mod tests {
use super::{bytes_to_utf16, utf16_to_bytes};
#[test]
fn offsets_round_trip() {
let t = "a東京😀b";
assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
}
}