swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Drag, drop, and the item providers they carry.
//!
//! `NSItemProvider` is an Objective-C class, so these are the bindings where the
//! two runtimes meet: SwiftUI hands over providers built by AppKit, and what
//! goes back is built here through the Objective-C runtime.

use super::*;
use super::closures::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::{self, swift_type};

/// Apply `.onDragSessionUpdated(_:)`.
pub fn on_drag_session_updated(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_drag_session_updated_fn(),
            resolve::on_drag_session_updated_oret(),
            view,
            &ignoring_value_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onDropSessionUpdated(_:)`.
pub fn on_drop_session_updated(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_drop_session_updated_fn(),
            resolve::on_drop_session_updated_oret(),
            view,
            &ignoring_value_words(action),
            [0.0; 4],
        )
    }
}

/// A Swift `Array<UTType>`, as the one word it travels in.
pub(crate) unsafe fn content_types(kinds: &[ContentType]) -> u64 {
    unsafe {
        let meta = crate::type_by_name!(swift_type!(UniformTypeIdentifiers.UTType).as_bytes());
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * kinds.len()];
        for (i, k) in kinds.iter().enumerate() {
            // `UTType` is a resilient struct, so its getter writes through x8
            // even though the value it holds is a single reference.
            let v = resilient_static(meta, k.getter());
            bytes[i * stride..i * stride + v.len()].copy_from_slice(&v);
        }
        abi::swift_array(meta, kinds.len(), &bytes)
    }
}

/// An `NSItemProvider` SwiftUI handed to a callback, or one built to hand back.
///
/// Reading what a provider *carries* is asynchronous — that is the whole point
/// of the class — so what a synchronous Rust callback can see is which type
/// identifiers it offers, which is a plain property.
#[derive(Clone, Copy, Debug)]
pub struct ItemProvider(pub(crate) *mut c_void);

impl ItemProvider {
    /// The underlying `NSItemProvider`.
    pub fn as_ptr(&self) -> *mut c_void {
        self.0
    }

    /// The uniform type identifiers this provider can produce.
    pub fn type_identifiers(&self) -> Vec<String> {
        unsafe {
            type Send0 = unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void;
            let send: Send0 = core::mem::transmute(crate::objc::msg_send_addr());
            let array = send(self.0, crate::objc::sel(c"registeredTypeIdentifiers"));
            if array.is_null() {
                return Vec::new();
            }
            type Count = unsafe extern "C" fn(*mut c_void, *const c_void) -> usize;
            let count: Count = core::mem::transmute(crate::objc::msg_send_addr());
            let n = count(array, crate::objc::sel(c"count"));
            type At = unsafe extern "C" fn(*mut c_void, *const c_void, usize) -> *mut c_void;
            let at: At = core::mem::transmute(crate::objc::msg_send_addr());
            type Utf8 = unsafe extern "C" fn(*mut c_void, *const c_void) -> *const i8;
            let utf8: Utf8 = core::mem::transmute(crate::objc::msg_send_addr());
            (0..n)
                .map(|i| {
                    let s = at(array, crate::objc::sel(c"objectAtIndex:"), i);
                    let p = utf8(s, crate::objc::sel(c"UTF8String"));
                    if p.is_null() {
                        String::new()
                    } else {
                        core::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
                    }
                })
                .collect()
        }
    }

    /// Ask for the item's text. The answer arrives **later**, on the main queue.
    ///
    /// A drop handler could see how many items were dropped and what type
    /// identifiers they carried, and nothing about what they actually were —
    /// which is most of the way to not having a drop handler.
    ///
    /// Asynchronous because it has to be, not as a matter of taste: measured
    /// with a probe that waited a full second without turning the run loop, the
    /// completion never came, and the same load with the loop running returned
    /// immediately. `NSItemProvider` delivers on the main queue, so a
    /// synchronous read from a drop handler — which is already running on the
    /// main thread inside AppKit's own dispatch — would wait for a block that
    /// cannot run until it returns. Swift's `loadItem` is `async` for the same
    /// reason.
    ///
    /// ```no_run
    /// # use swiftui_native::prelude::*;
    /// # use swiftui_native::views::ContentType;
    /// let drop = text("drop here").on_drop(&[ContentType::PlainText], |providers| {
    ///     for p in providers {
    ///         p.load_plain_text(|text| println!("dropped {text:?}"));
    ///     }
    ///     true
    /// });
    /// ```
    pub fn load_plain_text(&self, then: impl FnOnce(Option<String>) + 'static) {
        unsafe {
            let boxed: Box<dyn FnOnce(Option<String>)> = Box::new(then);
            let capture = Box::into_raw(Box::new(boxed)) as *mut c_void;
            // Leaked: the receiver may copy the block and call the copy, and
            // either way it outlives this call. It is five words.
            let block = Box::leak(Box::new(crate::objc::CapturingBlock::new(
                loaded_item as *const c_void,
                capture,
            ))) as *const crate::objc::CapturingBlock;
            let kind = crate::objc::nsstring("public.plain-text");
            type Load = unsafe extern "C" fn(
                *mut c_void, *const c_void, *mut c_void, *mut c_void,
                *const crate::objc::CapturingBlock,
            ) -> *mut c_void;
            let load: Load = core::mem::transmute(crate::objc::msg_send_addr());
            load(
                self.0,
                crate::objc::sel(c"loadItemForTypeIdentifier:options:completionHandler:"),
                kind,
                core::ptr::null_mut(),
                block,
            );
        }
    }

    /// Build a provider carrying `text` as plain text.
    pub fn plain_text(text: &str) -> Self {
        unsafe {
            let cls = crate::objc::class_named(c"NSItemProvider");
            type Alloc = unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void;
            let alloc: Alloc = core::mem::transmute(crate::objc::msg_send_addr());
            let obj = alloc(cls, crate::objc::sel(c"alloc"));
            let ns_string = crate::objc::class_named(c"NSString");
            type With = unsafe extern "C" fn(*mut c_void, *const c_void, *const i8) -> *mut c_void;
            let with: With = core::mem::transmute(crate::objc::msg_send_addr());
            let c = std::ffi::CString::new(text).expect("text");
            let value = with(ns_string, crate::objc::sel(c"stringWithUTF8String:"), c.as_ptr());
            let kind = with(
                ns_string,
                crate::objc::sel(c"stringWithUTF8String:"),
                c"public.plain-text".as_ptr(),
            );
            type Init = unsafe extern "C" fn(
                *mut c_void, *const c_void, *mut c_void, *mut c_void,
            ) -> *mut c_void;
            let init: Init = core::mem::transmute(crate::objc::msg_send_addr());
            let p = init(obj, crate::objc::sel(c"initWithItem:typeIdentifier:"), value, kind);
            assert!(!p.is_null(), "NSItemProvider for {text:?}");
            Self(p)
        }
    }
}

/// Read a Swift `[NSItemProvider]` back into Rust handles.
pub(crate) unsafe fn read_provider_array(array: u64) -> Vec<ItemProvider> {
    unsafe {
        if array == 0 {
            return Vec::new();
        }
        let stride = abi::type_bytes(crate::type_by_name!(swift_type!(objc NSItemProvider).as_bytes()));
        let (base, count) = abi::array_parts(array);
        (0..count)
            .map(|i| ItemProvider(*(base.add(i * stride) as *const *mut c_void)))
            .collect()
    }
}

/// Apply `.onCopyCommand(perform:)`, offering the given plain-text items.
pub fn on_copy_command(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let c = word_closure(emit_providers, provider_payload(provider_array(items), None, None));
        opaque_modifier(
            resolve::on_copy_command_fn(),
            resolve::on_copy_command_oret(),
            view,
            &c,
            [0.0; 4],
        )
    }
}

/// Apply `.onCutCommand(perform:)`, offering the given plain-text items.
pub fn on_cut_command(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let c = word_closure(emit_providers, provider_payload(provider_array(items), None, None));
        opaque_modifier(
            resolve::on_cut_command_fn(),
            resolve::on_cut_command_oret(),
            view,
            &c,
            [0.0; 4],
        )
    }
}

/// Apply `.itemProvider(_:)` with a provider carrying `item`.
pub fn item_provider(view: &ViewHandle, item: Option<&str>) -> ViewHandle {
    unsafe {
        let array = provider_array(&item.map_or(Vec::new(), |t| vec![t]));
        let c = word_closure(emit_first_provider, provider_payload(array, None, None));
        opaque_modifier(
            resolve::item_provider_fn(),
            resolve::item_provider_oret(),
            view,
            &c,
            [0.0; 4],
        )
    }
}

/// Apply `.importsItemProviders(_:onImport:)`.
pub fn imports_item_providers(
    view: &ViewHandle,
    kinds: &[ContentType],
    accept: impl Fn(&[ItemProvider]) -> bool + 'static,
) -> ViewHandle {
    unsafe {
        let types = content_types(kinds);
        let c = word_closure(decide_on_providers, provider_payload(0, Some(Box::new(accept)), None));
        opaque_modifier(
            resolve::imports_item_providers_fn(),
            resolve::imports_item_providers_oret(),
            view,
            &[types, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.onPasteCommand(of:perform:)`.
pub fn on_paste_command(
    view: &ViewHandle,
    kinds: &[ContentType],
    paste: impl Fn(&[ItemProvider]) + 'static,
) -> ViewHandle {
    unsafe {
        let types = content_types(kinds);
        let c = wide_words(observe_providers, provider_payload(0, None, Some(Box::new(paste))));
        opaque_modifier(
            resolve::on_paste_command_fn(),
            resolve::on_paste_command_oret(),
            view,
            &[types, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.exportsItemProviders(_:onExport:onEdit:)`.
///
/// `items` are offered as plain text; `edit` is asked whether an edit was
/// accepted.
pub fn exports_item_providers(
    view: &ViewHandle,
    kinds: &[ContentType],
    items: &[&str],
    edit: impl Fn(&[ItemProvider]) -> bool + 'static,
) -> ViewHandle {
    unsafe {
        let types = content_types(kinds);
        let export =
            word_closure(emit_providers, provider_payload(provider_array(items), None, None));
        // `onEdit: ([NSItemProvider]) -> Bool` — one argument in x0, the answer
        // back in x0. A dump cannot tell a wrong closure shape from a right one
        // (both print `(Function)`), so this one is taken from the SDK rather
        // than from the mangled name, which does not distinguish them either.
        let on_edit = word_closure(decide_on_providers, provider_payload(0, Some(Box::new(edit)), None));
        opaque_modifier(
            resolve::exports_item_providers_fn(),
            resolve::exports_item_providers_oret(),
            view,
            &[types, export[0], export[1], on_edit[0], on_edit[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.onDrop(of:isTargeted:perform:)`.
///
/// `accept` sees the dropped providers and answers whether it took them.
pub fn on_drop(
    view: &ViewHandle,
    kinds: &[ContentType],
    accept: impl Fn(&[ItemProvider]) -> bool + 'static,
) -> ViewHandle {
    unsafe {
        let types = content_types(kinds);
        // `Binding<Bool>?` is a `Binding` with a null location, so it is still
        // three registers rather than an address.
        let payload = abi::resolve_type_by_mangled_name(mangle::bound("7SwiftUI7BindingV", &[mangle::BOOL]).as_bytes());
        let opt = abi::resolve_type_by_mangled_name(mangle::optional(&mangle::bound("7SwiftUI7BindingV", &[mangle::BOOL])).as_bytes());
        let mut nil = vec![0u8; abi::type_bytes(opt).max(24)];
        abi::store_optional_tag(&mut nil, payload, false);
        let b = binding_words(&mut nil);
        let perform = word_closure(decide_on_providers, provider_payload(0, Some(Box::new(accept)), None));
        opaque_modifier(
            resolve::on_drop_fn(),
            resolve::on_drop_oret(),
            view,
            &[types, b[0], b[1], b[2], perform[0], perform[1]],
            [0.0; 4],
        )
    }
}

/// What a drop does with what it is given.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DropOperation {
    Cancel = 0,
    Forbidden = 1,
    Copy = 2,
    Move = 3,
}

/// `(DropSession) -> DropConfiguration` — build a fresh configuration.
///
/// `DropConfiguration` is resilient, so it comes back through x8; the session in
/// x0 is not read, since deciding from it would mean reading a type that only
/// exists while a drag is in flight.
pub(crate) unsafe extern "C" fn emit_drop_configuration(out: *mut u8, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn() -> DropOperation>(payload);
        let op = abi::enum_argument(abi::metadata0(resolve::drop_operation_ma()), f() as u32);
        let meta = abi::metadata0(resolve::drop_configuration_ma());
        core::arch::asm!("blr {f}", f = in(reg) resolve::drop_configuration_init(),
            in("x0") op, in("x8") out, in("x20") meta,
            lateout("x1") _, lateout("x2") _, lateout("x3") _, lateout("x4") _,
            lateout("x5") _, lateout("x6") _, lateout("x7") _, lateout("x9") _,
            lateout("x10") _, lateout("x11") _, lateout("x12") _, lateout("x13") _,
            lateout("x14") _, lateout("x15") _, lateout("x16") _, lateout("x17") _,
            lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );
    }
}

/// Apply `.dropConfiguration(_:)`.
pub fn drop_configuration(view: &ViewHandle, decide: impl Fn() -> DropOperation + 'static) -> ViewHandle {
    unsafe {
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_drop_configuration,
            boxed_ctx(Box::new(decide) as Box<dyn Fn() -> DropOperation>),
        ))) as *mut abi::ClosureCtx;
        opaque_modifier(
            resolve::drop_configuration_fn(),
            resolve::drop_configuration_oret(),
            view,
            &[abi::swift_closure_thunk as *const () as u64, ctx as u64],
            [0.0; 4],
        )
    }
}

/// Which drag operations a view permits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DragOperations {
    pub copy: bool,
    pub move_: bool,
    pub delete: bool,
}

/// Build one of the two `DragConfiguration.Operations*` values.
///
/// Both have the same three-`Bool` initialiser and both are resilient, so each
/// comes back through x8 with its own metatype in x20.
unsafe fn drag_operations(ma: *const c_void, init: *const c_void, ops: DragOperations) -> Vec<u8> {
    unsafe {
        let meta = abi::metadata0(ma);
        let mut out = vec![0u8; abi::type_bytes(meta)];
        abi::call_out(
            init,
            abi::ints(&[u64::from(ops.copy), u64::from(ops.move_), u64::from(ops.delete)]),
            [0.0; 4],
            meta as u64,
            out.as_mut_ptr(),
        );
        out
    }
}

/// Apply `.dragConfiguration(_:)`.
///
/// Three nested resilient values, each built by its own initialiser: the two
/// `Operations` sets go in by address, and the configuration they make comes
/// back by address to be handed to the modifier the same way.
pub fn drag_configuration(
    view: &ViewHandle,
    within_app: DragOperations,
    outside_app: DragOperations,
) -> ViewHandle {
    unsafe {
        let within = drag_operations(
            resolve::drag_ops_within_ma(), resolve::drag_ops_within_init(), within_app);
        let outside = drag_operations(
            resolve::drag_ops_outside_ma(), resolve::drag_ops_outside_init(), outside_app);
        let meta = abi::metadata0(resolve::drag_configuration_ma());
        let mut config = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::drag_configuration_init(),
            in("x0") within.as_ptr(), in("x1") outside.as_ptr(),
            in("x8") config.as_mut_ptr(), in("x20") meta,
            lateout("x2") _, lateout("x3") _, lateout("x4") _, lateout("x5") _,
            lateout("x6") _, lateout("x7") _, lateout("x9") _, lateout("x10") _,
            lateout("x11") _, lateout("x12") _, lateout("x13") _, lateout("x14") _,
            lateout("x15") _, lateout("x16") _, lateout("x17") _, lateout("lr") _,
            lateout("x21") _, clobber_abi("C"),
        );
        opaque_modifier(
            resolve::drag_configuration_fn(),
            resolve::drag_configuration_oret(),
            view,
            &[config.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// `() -> NSItemProvider` — hand back a provider built from a Rust string.
pub(crate) unsafe extern "C" fn emit_provider(payload: *mut c_void, _arg: u64) -> u64 {
    unsafe {
        let text = &*(payload as *const String);
        ItemProvider::plain_text(text).0 as u64
    }
}

/// Apply `.onDrag(_:preview:)`.
///
/// The public spelling has two arguments; the symbol has six, because Swift
/// fills the rest in from defaults at every call site. So the defaults are
/// written out here: enabled, no local context, and neither session callback.
///
/// `Any?` is four words — three of inline existential buffer and one of type
/// metadata — which is what pushes this past eight argument registers and makes
/// it the widest modifier bound here.
pub fn on_drag(view: &ViewHandle, item: &str, preview: &ViewHandle) -> ViewHandle {
    unsafe {
        let text = Box::leak(Box::new(item.to_string())) as *mut String;
        let data = word_closure(emit_provider, text as *mut c_void);
        // `Optional<Any>` holding `.none`. An existential is address-only —
        // it holds an arbitrary value, so nothing can copy it without its
        // witness table — which makes it one pointer here rather than the four
        // words its thirty-two-byte layout would suggest. An all-zero container
        // is `.none`, because the discriminator is the null metadata word.
        let none_any = [0u64; 4];
        let mut ints = vec![1u64, none_any.as_ptr() as u64];
        ints.extend_from_slice(&data);
        // Both session callbacks nil — a null function pointer is `.none` for
        // an optional closure, so the context word beside it is never read.
        ints.extend_from_slice(&[0, 0, 0, 0]);
        ints.extend_from_slice(&view_words(preview));
        generic1_modifier_ints(
            resolve::on_drag_fn(),
            resolve::on_drag_oret(),
            view,
            preview.meta,
            preview.wt,
            &ints,
            [0.0; 4],
        )
    }
}


/// `void (^)(id item, NSError *error)` — turn the item into a Rust string and
/// hand it to the waiting closure.
///
/// The item is whatever the provider registered: an `NSString` for text put
/// there by [`ItemProvider::plain_text`], an `NSData` for most things dragged
/// in from elsewhere. Both are handled, since a drop handler does not get to
/// choose which it receives.
unsafe extern "C" fn loaded_item(block: *mut c_void, item: *mut c_void, error: *mut c_void) {
    unsafe {
        let capture = (*(block as *const crate::objc::CapturingBlock)).capture;
        if capture.is_null() {
            return;
        }
        let then = Box::from_raw(capture as *mut Box<dyn FnOnce(Option<String>)>);
        let text = (error.is_null() && !item.is_null())
            .then(|| item_text(item))
            .flatten();
        then(text);
    }
}

/// Read an `NSString` or an `NSData` as UTF-8.
///
/// # Safety
/// `item` must be a live object.
unsafe fn item_text(item: *mut c_void) -> Option<String> {
    unsafe {
        let _pool = crate::objc::AutoreleasePool::new();
        // `UTF8String` first: an `NSString` answers it and an `NSData` does not,
        // which is a cheaper question than asking each class by name.
        if crate::objc::responds(item, crate::objc::sel(c"UTF8String")) {
            let p = crate::objc::send(item, crate::objc::sel(c"UTF8String")) as *const i8;
            if p.is_null() {
                return None;
            }
            return Some(core::ffi::CStr::from_ptr(p).to_string_lossy().into_owned());
        }
        if crate::objc::responds(item, crate::objc::sel(c"bytes")) {
            let bytes = crate::objc::send(item, crate::objc::sel(c"bytes")) as *const u8;
            let len = crate::objc::send(item, crate::objc::sel(c"length")) as usize;
            if bytes.is_null() || len == 0 {
                return None;
            }
            return Some(String::from_utf8_lossy(core::slice::from_raw_parts(bytes, len)).into_owned());
        }
        None
    }
}