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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! `@Observable` from Rust — a model SwiftUI re-renders on.
//!
//! The last thing on SwiftUI's surface this crate could not build, and the
//! reason it looked impossible was wrong. The obvious blockers are not blockers:
//! `Observation.Observable` is a **marker protocol** with zero requirements, and
//! `ObservationRegistrar` and `withObservationTracking` are fully exported. What
//! stood in the way was in the middle — an `@Observable` model is a *class*, and
//! this crate mints structs.
//!
//! It does not have to be a *Swift* class. `Observable` requires `AnyObject`, and
//! an `NSObject` subclass is one; [`crate::objc::ClassBuilder`] mints those. The
//! only piece missing was a conformance record whose type reference is a class
//! rather than a nominal descriptor — `IndirectObjCClass`, one of the four kinds
//! the format already has, which [`crate::conformance::Conformer`] now emits.
//!
//! ```no_run
//! # use swiftui_native::observable;
//! let model = observable::model(0);
//! let watched = model.clone();
//! // Whatever the block reads is what the handler is told about.
//! observable::track(move || { watched.get(); }, || println!("it changed"));
//! model.set(1);
//! ```
//!
//! # What an `@Observable` property actually is
//!
//! Three calls around ordinary storage, which the macro writes for you:
//!
//! ```text
//! get { registrar.access(self, keyPath: \.value); return storage }
//! set { registrar.willSet(self, keyPath: \.value)
//!       storage = newValue
//!       registrar.didSet(self, keyPath: \.value) }
//! ```
//!
//! [`Property::get`] and [`Property::set`] are that, with the storage on the Rust
//! side because a class minted through the Objective-C runtime has no ivars.
//!
//! # Several properties
//!
//! A model has as many named properties as it is asked for, each its own type:
//!
//! ```no_run
//! # use swiftui_native::observable;
//! let model = observable::model(0);
//! let name = model.property("name", "Ada".to_string());
//! let ratio = model.property("ratio", 0.5f64);
//! ```
//!
//! What makes them independent is that the key path is an *identity* — what
//! `access` records and `didSet` matches against — so each property needs one of
//! its own, and a view that read only `name` is not rebuilt when `ratio` changes.
//! Key paths are per *name*, not per model: `\.name` is one key path in Swift too,
//! and the registrar keys its observations by `(subject, keyPath)`, so two models
//! with a `name` property still change independently.

use crate::abi;
use crate::conformance::{synthesize_for, Conformance, Conformer, Protocol};
use crate::keypath;
use crate::objc;
use crate::resolve;
use crate::views::ViewHandle;
use core::ffi::c_void;
use std::sync::{Arc, Mutex, OnceLock};

/// The minted class and its `Observable` conformance.
struct Kind {
    class: usize,
    metadata: usize,
    observable_wt: usize,
}

// The three are immortal runtime objects; what makes this shareable is that
// nothing here is ever written after `OnceLock` publishes it.
unsafe impl Send for Kind {}
unsafe impl Sync for Kind {}

fn kind() -> &'static Kind {
    static K: OnceLock<Kind> = OnceLock::new();
    K.get_or_init(|| unsafe {
        let class = objc::ClassBuilder::new(c"NSObject", c"RustObservable")
            .expect("the class name `RustObservable` is already taken")
            .register();
        let metadata = swift_runtime_sys::MetadataIntrospection::swift_getObjCClassMetadata(class);
        assert!(!metadata.is_null(), "RustObservable metadata");

        // `Observable` has no requirements at all, so the witness table is the
        // conformance descriptor and nothing else. Registering it is the whole
        // point: SwiftUI and the registrar both find it by lookup.
        let protocol = Protocol::from_symbol(c"$s11Observation10ObservableMp");
        assert_eq!(
            protocol.requirement_count(),
            0,
            "Observable used to be a marker protocol with nothing to implement",
        );
        let conformance: &'static Conformance = Box::leak(Box::new(synthesize_for(
            &protocol,
            Conformer::ObjCClass(class),
            &[],
        )));

        Kind {
            class: class as usize,
            metadata: metadata as usize,
            observable_wt: conformance.witness_table() as usize,
        }
    })
}

/// One property *name*'s key path, and what reading through it produces.
struct Named {
    name: String,
    /// Which `T` the name was first declared with. A second model declaring the
    /// same name with a different type would silently share a key path whose
    /// value type is the first one's, so it is refused instead.
    value_type: core::any::TypeId,
    key_path: u64,
}

fn names() -> &'static Mutex<Vec<Named>> {
    static N: OnceLock<Mutex<Vec<Named>>> = OnceLock::new();
    N.get_or_init(|| Mutex::new(Vec::new()))
}

/// Writes a `+1` copy of a property's declared value into a buffer.
type WriteInitial = Box<dyn Fn(*mut u8) + Send + Sync>;

/// What a read through slot `i`'s key path writes: a `+1` copy of the value the
/// property was declared with.
///
/// Indexed by key path slot, so [`identity_get`] — which knows only its slot —
/// can produce a valid value of whatever type the property holds.
fn initials() -> &'static Mutex<Vec<Option<WriteInitial>>> {
    static I: OnceLock<Mutex<Vec<Option<WriteInitial>>>> = OnceLock::new();
    I.get_or_init(|| Mutex::new((0..keypath::VALUE_SLOTS).map(|_| None).collect()))
}

/// The key path for a property called `name` holding a `T`, made once per name.
///
/// The root is named `So14RustObservableC`: an imported Objective-C class, which
/// the runtime resolves by asking the Objective-C runtime for the class by name,
/// and which therefore reaches a class minted at run time.
/// A mismatched type panics *after* the registry is unlocked: a panic while
/// holding it poisons a `static` mutex, which turns one caller's mistake into
/// every later model's failure — and in a test binary, into every other test's.
fn key_path_for<T: crate::views::KeyValue>(name: &str, initial: &T) -> u64 {
    let mut names = names().lock().expect("observable property names");
    if let Some(n) = names.iter().find(|n| n.name == name) {
        let (key_path, declared) = (n.key_path, n.value_type);
        drop(names);
        assert_eq!(
            declared,
            core::any::TypeId::of::<T>(),
            "the observable property `{name}` was already declared with a different \
             type; one name is one key path, so one name is one type",
        );
        return key_path;
    }

    let slot = keypath::next_value_slot();
    let initial = initial.clone();
    initials().lock().expect("observable property initials")[slot] =
        Some(Box::new(move |out| unsafe { initial.write(out) }));
    unsafe {
        let (get, set, get_target, set_target) = keypath::value_thunks(slot);
        *get_target = identity_get as *const c_void;
        *set_target = identity_set as *const c_void;
        let key_path = keypath::build_writable_computed(
            keypath::value_slot(slot),
            b"So14RustObservableC",
            T::mangled().as_bytes(),
            get,
            set,
        );
        swift_runtime_sys::RuntimeRaw::swift_retain(key_path as *mut c_void);
        names.push(Named {
            name: name.to_string(),
            value_type: core::any::TypeId::of::<T>(),
            key_path,
        });
        key_path
    }
}

/// The key path's getter, which nothing in this crate reads through.
///
/// A key path has to have one, and this one exists to be *compared*: `access`,
/// `willSet` and `didSet` use the key path as a dictionary key and never call it.
/// So what it writes is the value the property was declared with — which is a
/// valid `T`, and the only value available to a function that knows the property
/// but not which object the read is for. Live values come from [`Property::get`],
/// whose storage is per object.
///
/// Writing a zeroed word regardless of type is what this did while a model held
/// one `Int`, and it stopped being safe the moment a property could hold a
/// `String`: all-zero is not a valid `String`, and destroying one is a crash.
///
/// # Safety
/// Reached through [`keypath::value_thunks`].
unsafe extern "C" fn identity_get(out: *mut u8, _root: *const c_void, slot: u64) {
    let initials = initials().lock().expect("observable property initials");
    if let Some(write) = initials[slot as usize].as_ref() {
        write(out);
    }
}

/// The key path's setter, which nothing reads through either — a write here would
/// have to find the object's storage, and the object is not what a computed
/// component's root reliably is.
///
/// # Safety
/// As [`identity_get`].
unsafe extern "C" fn identity_set(_value: *const u8, _root: *mut c_void, _slot: u64) {}

/// One property's storage, with its type forgotten so one map can hold them all.
type ErasedStorage = Arc<dyn core::any::Any + Send + Sync>;

/// An observable model: a class instance, a registrar, and its named properties.
///
/// Cloning shares all three, as a class reference does in Swift — two handles to
/// one model, not two models.
#[derive(Clone)]
pub struct Model {
    object: usize,
    /// `ObservationRegistrar`, one per model, held by address because it is
    /// resilient.
    registrar: Arc<Mutex<Vec<u8>>>,
    /// The properties declared on this model, by name. Type-erased so one map
    /// can hold storage of every type; [`Model::property`] casts it back and
    /// refuses a name reused with a different type.
    properties: Arc<Mutex<Vec<(String, ErasedStorage)>>>,
}

// The object is immortal for the model's lifetime and the rest is behind locks.
unsafe impl Send for Model {}
unsafe impl Sync for Model {}

/// A new observable model with no properties yet.
///
/// What [`crate::observable!`] builds on: the class instance and the registrar,
/// with [`Model::property`] called once per declared property. [`model`] is this
/// plus one `Int` property, which is the short form for a model that holds one
/// number.
pub fn object() -> Model {
    model_of(None)
}

/// A new observable model, with one `Int` property holding `initial`.
///
/// That property is what [`Model::get`] and [`Model::set`] mean; anything else
/// the model should hold is [`Model::property`], named and of whatever type — or
/// [`crate::observable!`], which declares them all at once.
pub fn model(initial: i64) -> Model {
    model_of(Some(initial))
}

/// The two constructors: a bare object, or one with the default `Int` property.
fn model_of(initial: Option<i64>) -> Model {
    let kind = kind();
    unsafe {
        let object = objc::send(
            objc::send(kind.class as *mut c_void, objc::sel(c"alloc")),
            objc::sel(c"init"),
        );
        assert!(!object.is_null(), "RustObservable init");

        let meta = abi::metadata0(resolve::observation_registrar_ma());
        assert!(!meta.is_null(), "ObservationRegistrar metadata");
        let mut registrar = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::observation_registrar_init(),
            in("x8") registrar.as_mut_ptr(),
            lateout("x0") _, 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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );

        let model = Model {
            object: object as usize,
            registrar: Arc::new(Mutex::new(registrar)),
            properties: Arc::new(Mutex::new(Vec::new())),
        };
        // `Model::get`/`set`/`peek` are this property, so when it is asked for it
        // exists from the start and `model(0)` reads as it always did. A model
        // built by `observable!` has its own names and never wants it, and
        // declaring it anyway would spend a key path slot on nothing.
        if let Some(initial) = initial {
            let _ = model.property(DEFAULT_PROPERTY, initial);
        }
        model
    }
}

/// The property [`Model::get`] and [`Model::set`] mean.
///
/// A model made by [`model`] has one `Int` property, and the two-line form that
/// reads and writes it stays the shortest thing that works. Naming it here rather
/// than in both methods is what keeps them from drifting apart.
const DEFAULT_PROPERTY: &str = "value";

impl Model {
    /// The object itself, for handing to SwiftUI.
    ///
    /// What `.environment(_ object:)` and `focusedSceneValue(_ object:)` take:
    /// an `AnyObject` that conforms to `Observable`, which this is.
    pub fn as_object(&self) -> *mut c_void {
        self.object as *mut c_void
    }

    /// The model's Swift metadata and its `Observable` conformance.
    pub fn conformance(&self) -> (*const c_void, *const c_void) {
        let k = kind();
        (k.metadata as *const c_void, k.observable_wt as *const c_void)
    }

    /// A named property of this model, declared with `initial` if it is new.
    ///
    /// Calling this twice with the same name returns two handles to *one*
    /// property — the second `initial` is ignored, as a stored property's
    /// initialiser is after the object exists. That is what lets a view and the
    /// code that updates it each ask for the property they mean without either
    /// having to own it.
    ///
    /// # Panics
    /// If `name` was declared with a different type, here or on another model: a
    /// property name is one key path, and a key path has one value type.
    pub fn property<T: crate::views::KeyValue>(
        &self,
        name: &str,
        initial: impl crate::views::IntoKeyValue<T>,
    ) -> Property<T> {
        let initial = initial.into_key_value();
        let key_path = key_path_for(name, &initial);
        let mut properties = self.properties.lock().expect("model properties");
        let existing = properties.iter().find(|(n, _)| n == name).map(|(_, s)| s.clone());
        let storage = match existing {
            Some(erased) => {
                // Unlocked before the cast, for the reason `key_path_for` is.
                drop(properties);
                erased.downcast::<Mutex<T>>().unwrap_or_else(|_| {
                    panic!("the property `{name}` on this model does not hold this type")
                })
            }
            None => {
                let storage = Arc::new(Mutex::new(initial));
                properties.push((name.to_string(), storage.clone()));
                storage
            }
        };
        Property {
            object: self.object,
            registrar: self.registrar.clone(),
            key_path,
            value: storage,
        }
    }

    /// The default `Int` property — see [`Property::get`].
    pub fn get(&self) -> i64 {
        self.property(DEFAULT_PROPERTY, 0).get()
    }

    /// The default `Int` property — see [`Property::set`].
    pub fn set(&self, value: i64) {
        self.property(DEFAULT_PROPERTY, 0).set(value);
    }

    /// The default `Int` property — see [`Property::peek`].
    pub fn peek(&self) -> i64 {
        self.property(DEFAULT_PROPERTY, 0).peek()
    }
}

/// One named property of a [`Model`]: storage, and the key path that names it.
///
/// Cloning shares the storage, so two handles to `"count"` are two views of one
/// property.
#[derive(Clone)]
pub struct Property<T> {
    object: usize,
    registrar: Arc<Mutex<Vec<u8>>>,
    key_path: u64,
    value: Arc<Mutex<T>>,
}

impl<T: Clone> Property<T> {
    /// Read the value, telling the registrar that it was read.
    ///
    /// The `access` half of what an `@Observable` property's getter does. Inside
    /// a [`track`] block — or inside SwiftUI's own tracking, which is how a view
    /// body works — this is what subscribes the reader to the next change *of this
    /// property*: a body that read only this one is not re-run when another
    /// changes, because the registrar recorded this key path and no other.
    pub fn get(&self) -> T {
        unsafe { self.registrar_call(resolve::registrar_access()) };
        self.value.lock().expect("property value").clone()
    }

    /// Write the value, telling the registrar before and after.
    ///
    /// The `willSet` / `didSet` half. `didSet` is what fires every handler that
    /// read this property since it last changed.
    pub fn set(&self, value: T) {
        unsafe {
            self.registrar_call(resolve::registrar_will_set());
            *self.value.lock().expect("property value") = value;
            self.registrar_call(resolve::registrar_did_set());
        }
    }

    /// Read without telling anyone, for assertions that must not subscribe.
    pub fn peek(&self) -> T {
        self.value.lock().expect("property value").clone()
    }

    /// One of `access`, `willSet` and `didSet`, which take the same arguments.
    ///
    /// # Safety
    /// `f` must be one of those three.
    unsafe fn registrar_call(&self, f: *const c_void) {
        let k = kind();
        // `Subject` is `@in`, so what is passed is a pointer *to* the class
        // reference rather than the reference.
        let mut subject = self.object;
        let mut registrar = self.registrar.lock().expect("registrar");
        unsafe {
            core::arch::asm!("blr {f}", f = in(reg) f,
                in("x0") &mut subject as *mut usize,
                in("x1") self.key_path,
                in("x2") k.observable_wt,
                in("x20") registrar.as_mut_ptr(),
                lateout("x3") _, lateout("x4") _, lateout("x5") _, lateout("x6") _,
                lateout("x7") _, lateout("x8") _,
                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"),
            );
        }
    }
}

// ── withObservationTracking ──

/// What the `apply` closure runs.
struct Reading<'a> {
    read: &'a mut dyn FnMut(),
}

/// The `() -> T` block, with `T == ()` so there is nothing to write out.
///
/// # Safety
/// Reached through [`abi::swift_closure_thunk`]; `payload` must be a [`Reading`].
unsafe extern "C" fn run_reading(_out: *mut u8, payload: *mut c_void) {
    let r = unsafe { &mut *(payload as *mut Reading<'_>) };
    (r.read)();
}

// `onChange` is an *autoclosure*: what Swift passes is a closure returning the
// handler, so the thunk hands back two words — the handler's function and its
// context. A thick function is returned in x0/x1, and the closure's own context
// arrives in x20, so the one shuffle is x20 into the first argument register.
core::arch::global_asm!(
    ".p2align 2",
    ".globl _rswift_obs_onchange_thunk",
    "_rswift_obs_onchange_thunk:",
    "mov x0, x20",
    "b _rswift_obs_onchange",
);

unsafe extern "C" {
    #[link_name = "rswift_obs_onchange_thunk"]
    fn onchange_thunk();
}

/// A thick Swift function: its code and its context.
#[repr(C)]
struct Thick {
    function: u64,
    context: u64,
}

/// The handler the autoclosure returns, kept where the thunk can find it.
#[repr(C)]
struct OnChange {
    isa: *const c_void,
    refcount: u64,
    handler: Thick,
}

/// Branch target of the autoclosure thunk: hand back the handler.
///
/// # Safety
/// `ctx` must be an [`OnChange`] this module leaked.
#[unsafe(no_mangle)]
unsafe extern "C" fn rswift_obs_onchange(ctx: *mut c_void) -> Thick {
    let c = unsafe { &*(ctx as *const OnChange) };
    Thick { function: c.handler.function, context: c.handler.context }
}

/// Run `read`, remembering every observable property it touches, and call
/// `on_change` once when any of them next changes.
///
/// `withObservationTracking`, which is what SwiftUI itself uses to decide that a
/// view needs rebuilding. **Once**: the handler fires for the first change and
/// then the subscription is over, which is Swift's behaviour too — a view
/// re-reads on the next render and so re-subscribes.
pub fn track(read: impl FnMut(), on_change: impl Fn() + Send + Sync + 'static) {
    let mut read = read;
    let mut reading = Reading { read: &mut read };
    unsafe {
        let mut ctx = abi::ClosureCtx::new(
            run_reading,
            &mut reading as *mut Reading<'_> as *mut c_void,
        );
        let handler = crate::views::action_words(on_change);
        let onchange = Box::leak(Box::new(OnChange {
            isa: abi::immortal_isa(),
            refcount: abi::IMMORTAL_REFCOUNT,
            handler: Thick { function: handler[0], context: handler[1] },
        })) as *mut OnChange;

        // `T` is `()`: the result slot is never written, but the runtime is
        // given somewhere real to point at rather than a null.
        let unit = abi::resolve_type_by_mangled_name(b"yt");
        assert!(!unit.is_null(), "() metadata");
        let mut out = [0u8; 8];
        core::arch::asm!("blr {f}", f = in(reg) resolve::with_observation_tracking(),
            in("x0") abi::swift_closure_thunk as *const c_void,
            in("x1") &mut ctx as *mut abi::ClosureCtx,
            in("x2") onchange_thunk as *const c_void,
            in("x3") onchange,
            in("x4") unit,
            in("x8") out.as_mut_ptr(),
            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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
    }
}

// ── Handing the model to SwiftUI ──
//
// The two modifiers that take an `Observable` *object* rather than a key path.
// Both were unreachable until there was an object to pass: the crate had the
// symbols and a synthesised `Observable` conformance, but the conformance was
// for a borrowed `Foundation.JSONDecoder` — a stand-in that proved the binding
// worked and was of no use to an app.

/// `.environment(model)` — put the model where every view below can read it.
///
/// The `Observable` overload. A body that reads a property of the model through
/// [`Model::get`] while SwiftUI is tracking it is re-run when that property
/// changes; one that reads a *different* property is not.
pub fn environment_model(view: &ViewHandle, model: &Model) -> ViewHandle {
    unsafe { publish(view, model, resolve::environment_observable_fn(), resolve::environment_observable_oret()) }
}

/// `.focusedValue(model)` — publish the model for the commands above it.
///
/// The object form of what [`crate::views::focused_scene_value`] does with a key
/// path, and the one Apple now recommends: a key is a type, and an `@Observable`
/// object already is one.
pub fn focused_value_model(view: &ViewHandle, model: &Model) -> ViewHandle {
    unsafe { publish(view, model, resolve::focused_value_fn(), resolve::focused_value_oret()) }
}

/// `.environment(_:)` and `.focusedValue(_:)` take the same arguments.
///
/// `T?` where `T` is a class is one word and `nil` is a null one, so the object
/// goes in a register rather than by address.
///
/// # Safety
/// `f`/`oret` must be a matching `Observable`-object modifier and descriptor.
unsafe fn publish(
    view: &ViewHandle,
    model: &Model,
    f: *const c_void,
    oret: *const c_void,
) -> ViewHandle {
    let (meta, wt) = model.conformance();
    unsafe {
        crate::views::generic1_modifier_ints(
            f,
            oret,
            view,
            meta,
            wt,
            &[model.as_object() as u64],
            [0.0; 4],
        )
    }
}