nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
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
//! Tier-2 modular `nv_get_interface` `cdylib` hot-swap loader.
//!
//! Resolves the single `nv_get_interface` entry point once at load time, caches the small
//! `const` interface tables (`NvSurfaceApi`, plus optional `NvLayoutApi`, `NvComponentApi`,
//! `NvDevApi`), and exposes direct zero-cost calls + state-preserving generation reloads.

mod staging;

use std::path::{Path, PathBuf};

use nativeview_abi::{
    slab_ptr, DispatchResult, HostServiceId, NvAppHandle, NvBufferSlice, NvComponentApi, NvDevApi,
    NvDirectHostApi, NvDirectHostEnv, NvGestureDisposition, NvHostApi, NvHostCallbacks,
    NvIntrinsicSize, NvLayoutApi, NvMapEntry, NvPointerApi, NvSizeConstraints, NvSurfaceApi,
    SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT, NV_IFACE_DEV, NV_IFACE_DIRECT_HOST,
    NV_IFACE_HOST, NV_IFACE_LAYOUT, NV_IFACE_POINTER, NV_IFACE_SURFACE,
};

use crate::tracker::PointerCaptureRequest;

pub use staging::{
    MODULE_STAGE_DIR_ENV, STAGES_PRIVATE_COPY, StagedDylib, is_valid_nv_interface_symbol,
    resolve_in_process_symbol, staging_dir,
};

use crate::app_module::NvAppModule;

#[derive(Debug)]
pub enum LoaderError {
    /// The library could not be staged (missing / unreadable source, temp dir failure).
    Io(std::io::Error),
    /// The OS loader rejected the staged copy (`dlopen` / `LoadLibraryW`).
    Load(libloading::Error),
    /// The requested symbol does not match `nv_get_interface` or `nv_get_interface_[A-Za-z0-9_]+`.
    InvalidSymbol,
    /// The library loaded but exports no matching `nv_get_interface` entry point.
    MissingEntry(libloading::Error),
    /// The process image does not export the requested `nv_get_interface*` symbol.
    MissingSymbol,
    MissingSurfaceInterface,
    NullHandle,
    /// Loading in place (no staging root) a file whose bytes changed since this process already
    /// loaded that inode or canonical path in place: the OS loader would hand back the mapped
    /// image, silently running the old code.
    AlreadyLoadedInPlace(PathBuf),
}

impl std::fmt::Display for LoaderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl std::error::Error for LoaderError {}


/// Summary returned after a successful transactional [`HotAppInstance::reload`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReloadOutcome {
    pub previous_generation: u64,
    pub generation: u64,
    pub preserved_state_bytes: usize,
}

pub struct HotAppInstance {
    module: Option<NvAppModule>,
    surface: NvSurfaceApi,
    layout: Option<NvLayoutApi>,
    component: Option<NvComponentApi>,
    dev: Option<NvDevApi>,
    host: Option<NvHostApi>,
    direct_host: Option<NvDirectHostApi>,
    pointer: Option<NvPointerApi>,
    bound_host: Option<NvHostCallbacks>,
    bound_direct_host: Option<NvDirectHostEnv>,
    handle: NvAppHandle,
    surface_id: SurfaceId,
    generation: u64,
    /// `NV_DISPATCH_RESULT_CLOSE_REQUEST` of the last `dispatch_events`, until taken.
    close_request: bool,
    /// `NV_DISPATCH_RESULT_UNCONSUMED_KEY` of the last `dispatch_events`, until taken.
    unconsumed_key: bool,
}

impl HotAppInstance {
    /// Loads a compiled app `cdylib` via a unique staged filename so `dlopen` never returns
    /// a stale cached image (and Windows never hits DLL lock collisions during hot-swap),
    /// resolves `nv_get_interface`, and optionally restores state.
    pub fn load(
        dylib_path: &Path,
        surface_id: SurfaceId,
        generation: u64,
        prior_state: Option<&[u8]>,
    ) -> Result<Self, LoaderError> {
        let module = NvAppModule::load_generation(dylib_path, "nv-hotswap", generation)?;
        Self::from_module(&module, surface_id, prior_state)
    }

    /// Instantiates a surface handle backed by a shared [`NvAppModule`] without staging or
    /// `dlopen`ing the library again (`[INV:multi-surface-shared-dylib]`).
    pub fn from_module(
        module: &NvAppModule,
        surface_id: SurfaceId,
        prior_state: Option<&[u8]>,
    ) -> Result<Self, LoaderError> {
        let get_iface = module.get_interface();

        // SAFETY: `get_iface` returns static, properly aligned NV C-ABI vtable pointers (or null)
        // that remain valid while `module` keeps the dylib loaded; `surface.create` / `restore_state`
        // obey the NV surface/dev C ABI contract.
        let (surface, layout, component, dev, host, direct_host, handle) = unsafe {
            let surface_ptr = get_iface(NV_IFACE_SURFACE) as *const NvSurfaceApi;
            if surface_ptr.is_null() {
                return Err(LoaderError::MissingSurfaceInterface);
            }
            let surface = *surface_ptr;

            let layout_ptr = get_iface(NV_IFACE_LAYOUT) as *const NvLayoutApi;
            let layout = (!layout_ptr.is_null()).then(|| *layout_ptr);

            let component_ptr = get_iface(NV_IFACE_COMPONENT) as *const NvComponentApi;
            let component = (!component_ptr.is_null()).then(|| *component_ptr);

            let dev_ptr = get_iface(NV_IFACE_DEV) as *const NvDevApi;
            let dev = (!dev_ptr.is_null()).then(|| *dev_ptr);

            let host_ptr = get_iface(NV_IFACE_HOST) as *const NvHostApi;
            let host = (!host_ptr.is_null()).then(|| *host_ptr);

            let direct_host_ptr = get_iface(NV_IFACE_DIRECT_HOST) as *const NvDirectHostApi;
            let direct_host = (!direct_host_ptr.is_null()).then(|| *direct_host_ptr);

            let handle = (surface.create)(surface_id);
            if handle.is_null() {
                return Err(LoaderError::NullHandle);
            }
            if let (Some(dev_api), Some(state)) = (dev, prior_state)
                && !state.is_empty()
            {
                (dev_api.restore_state)(handle, NvBufferSlice::from_slice(state));
            }
            (surface, layout, component, dev, host, direct_host, handle)
        };
        // SAFETY: As above (a static `NvPointerApi` or NULL).
        let pointer = unsafe { (get_iface(NV_IFACE_POINTER) as *const NvPointerApi).as_ref().copied() };

        Ok(Self {
            module: Some(module.clone()),
            surface,
            layout,
            component,
            dev,
            host,
            direct_host,
            pointer,
            bound_host: None,
            bound_direct_host: None,
            handle,
            surface_id,
            generation: module.generation(),
            close_request: false,
            unconsumed_key: false,
        })
    }

    /// Borrows the shared [`NvAppModule`] backing this surface instance.
    #[inline]
    pub fn module(&self) -> Option<&NvAppModule> {
        self.module.as_ref()
    }

    pub fn surface_id(&self) -> SurfaceId {
        self.surface_id
    }

    pub fn generation(&self) -> u64 {
        self.generation
    }

    pub fn loaded_copy_path(&self) -> &Path {
        self.module
            .as_ref()
            .and_then(NvAppModule::loaded_copy_path)
            .unwrap_or_else(|| Path::new(""))
    }

    /// Renders a frame and borrows the binary `NV02` wire frame slice directly from the loaded
    /// app module's internal frame buffer (zero heap allocation / zero `.to_vec()` copy per frame).
    ///
    /// The borrowed slice remains valid until the next `&mut self` call on this [`HotAppInstance`].
    pub fn render(&mut self, frame_id: nativeview_abi::FrameId) -> &[u8] {
        // SAFETY: `self.handle` is live while `self` owns it; returned buffer stays valid until next `&mut self` call.
        unsafe { (self.surface.render)(self.handle, frame_id).as_slice() }
    }

    /// Forwards a validated zero-copy event batch directly across the C FFI boundary; returns
    /// `NV_DISPATCH_RESULT_DIRTY` and latches `NV_DISPATCH_RESULT_CLOSE_REQUEST` for
    /// [`Self::take_close_request`].
    pub fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool {
        // SAFETY: `self.handle` is live and `events` stays valid for the synchronous FFI call.
        let raw = unsafe { (self.surface.dispatch_events)(self.handle, events.as_raw_batch()) };
        let result = DispatchResult::from_bits_truncate(raw);
        self.close_request = result.is_close_request();
        self.unconsumed_key = result.is_unconsumed_key();
        result.is_dirty()
    }

    /// Takes the close request of the last [`Self::dispatch_events`].
    pub fn take_close_request(&mut self) -> bool {
        std::mem::take(&mut self.close_request)
    }

    /// Takes whether the last [`Self::dispatch_events`] left a `KeyDown` unconsumed.
    pub fn take_unconsumed_key(&mut self) -> bool {
        std::mem::take(&mut self.unconsumed_key)
    }

    /// Drains the pointer-capture requests of the last [`Self::dispatch_events`] (`NvPointerApi`).
    pub fn drain_pointer_capture_requests(&mut self, sink: &mut dyn FnMut(PointerCaptureRequest)) {
        if let Some(api) = self.pointer {
            // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
            unsafe { crate::app::pointer::drain_capture_requests(api, self.handle, sink) };
        }
    }

    pub fn measure(&mut self, constraints: NvSizeConstraints) -> Option<NvIntrinsicSize> {
        self.layout.map(|api| {
            // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
            unsafe { (api.measure)(self.handle, constraints) }
        })
    }

    pub fn hit_test(&mut self, x: f32, y: f32, pointer_phase: u8) -> NvGestureDisposition {
        match self.layout {
            Some(api) => {
                // SAFETY: `self.handle` is live and `api` was resolved from the same loaded dylib.
                NvGestureDisposition::from_u8(unsafe {
                    (api.hit_test)(self.handle, x, y, pointer_phase)
                })
            }
            None => NvGestureDisposition::PassThrough,
        }
    }

    pub fn set_props(&mut self, entries: &[NvMapEntry]) -> bool {
        match self.component {
            // SAFETY: `self.handle` is live and `entries` stays valid for the synchronous FFI call.
            Some(api) => unsafe {
                (api.set_props)(
                    self.handle,
                    entries.as_ptr(),
                    entries.len().min(u32::MAX as usize) as u32,
                ) != 0
            },
            None => false,
        }
    }

    /// Drains outbound component events as an ingress-validated zero-copy [`ValidatedEvents`].
    pub fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
        match self.component {
            // SAFETY: `self.handle` is live; returned batch borrows from the module's buffer until next `&mut self` call.
            Some(api) => unsafe {
                ValidatedEvents::from_raw((api.drain_emitted_events)(self.handle))
            },
            None => ValidatedEvents::EMPTY,
        }
    }

    /// Forwards one binary `NV_HOT_PATCH` frame (as received from `nv dev`) to the module.
    pub fn apply_hot_patch(&mut self, patch: &[u8]) -> bool {
        match self.dev {
            // SAFETY: `self.handle` is live and `patch` stays valid for the synchronous FFI call.
            Some(api) => unsafe {
                (api.apply_hot_patch)(self.handle, NvBufferSlice::from_slice(patch)) != 0
            },
            None => false,
        }
    }

    /// Captures serialized app state and borrows the slice directly from the loaded app module's
    /// internal snapshot buffer without copying.
    pub fn snapshot_state(&mut self) -> &[u8] {
        match self.dev {
            // SAFETY: `self.handle` is live; returned slice stays valid until the next `&mut self` call.
            Some(api) => unsafe { (api.snapshot_state)(self.handle).as_slice() },
            None => &[],
        }
    }

    pub fn has_host_interface(&self) -> bool {
        self.host.is_some()
    }

    /// Binds (or unbinds when `None`) host capability callbacks via `NV_IFACE_HOST = 5`.
    /// Returns `true` if the loaded module exposes `NvHostApi`.
    pub fn bind_host(&mut self, callbacks: Option<NvHostCallbacks>) -> bool {
        self.bound_host = callbacks;
        match self.host {
            Some(api) => {
                let ptr = callbacks
                    .as_ref()
                    .map_or(std::ptr::null(), |cb| cb as *const NvHostCallbacks);
                // SAFETY: `self.handle` is live and `ptr` is null or points to the valid `NvHostCallbacks` copy.
                unsafe { (api.bind_host)(self.handle, ptr) };
                true
            }
            None => false,
        }
    }

    /// Dispatches a host-event payload buffer via `NvHostApi::dispatch_host_events`.
    pub fn dispatch_host_events(&mut self, batch: &[u8]) -> bool {
        match self.host {
            // SAFETY: `self.handle` is live and `batch` stays valid for the synchronous FFI call.
            Some(api) => unsafe {
                (api.dispatch_host_events)(self.handle, NvBufferSlice::from_slice(batch)) != 0
            },
            None => false,
        }
    }

    /// Returns `true` if the loaded module exports `NV_IFACE_DIRECT_HOST = 6`.
    pub fn has_direct_host_interface(&self) -> bool {
        self.direct_host.is_some()
    }

    /// Binds (or unbinds when `None`) the non-reloaded Direct-First host environment via
    /// `NV_IFACE_DIRECT_HOST = 6`. Returns `true` if the loaded module exposes `NvDirectHostApi`.
    pub fn bind_direct_host(&mut self, env: Option<NvDirectHostEnv>) -> bool {
        self.bound_direct_host = env;
        match self.direct_host {
            Some(api) => {
                let ptr = env
                    .as_ref()
                    .map_or(std::ptr::null(), |e| e as *const NvDirectHostEnv);
                // SAFETY: `self.handle` is live and `ptr` is null or points to the valid `NvDirectHostEnv`.
                unsafe { (api.bind_direct_host)(self.handle, ptr) };
                true
            }
            None => false,
        }
    }

    /// Dispatches one completed direct-FFI async reply on the owner thread via
    /// `NvDirectHostApi::dispatch_direct_completion`.
    pub fn dispatch_direct_completion(
        &mut self,
        local_req_id: u64,
        status: i32,
        payload: &[u8],
    ) -> bool {
        match self.direct_host {
            // SAFETY: `self.handle` is live and `payload` stays borrowed for this synchronous FFI call.
            Some(api) => unsafe {
                (api.dispatch_direct_completion)(
                    self.handle,
                    local_req_id,
                    status,
                    slab_ptr(payload),
                    payload.len(),
                ) != 0
            },
            None => false,
        }
    }

    /// Dispatches one direct-FFI push event on the owner thread via
    /// `NvDirectHostApi::dispatch_direct_event`.
    pub fn dispatch_direct_event(
        &mut self,
        service_id: HostServiceId,
        event_id: u32,
        flags: u32,
        payload: &[u8],
    ) -> bool {
        match self.direct_host {
            // SAFETY: `self.handle` is live and `payload` stays borrowed for this synchronous FFI call.
            Some(api) => unsafe {
                (api.dispatch_direct_event)(
                    self.handle,
                    service_id,
                    event_id,
                    flags,
                    slab_ptr(payload),
                    payload.len(),
                ) != 0
            },
            None => false,
        }
    }

    /// Transactionally hot-swaps this live instance to a freshly compiled dylib while preserving
    /// app state.
    ///
    /// Snapshots state from the live app, then stages (under a unique filename to avoid Windows
    /// DLL lock collisions), loads, validates (`nv_get_interface` + `NV_IFACE_SURFACE`),
    /// instantiates, and restores state on the candidate dylib BEFORE swapping out and unloading
    /// the existing instance. If any step fails, `self` stays 100% alive and untouched.
    pub fn reload(&mut self, new_dylib_path: &Path) -> Result<ReloadOutcome, LoaderError> {
        let bound_host = self.bound_host;
        let bound_direct = self.bound_direct_host;
        self.reload_with_hosts(new_dylib_path, bound_host, bound_direct)
    }

    /// Transactional reload binding `next_host` onto the candidate dylib **once** before swapping
    /// out and unbinding the previous generation (so a failed reload leaves generation N untouched,
    /// generation N is unbound BEFORE `destroy`, and generation N+1 is never double-bound).
    pub fn reload_with_host(
        &mut self,
        new_dylib_path: &Path,
        next_host: Option<NvHostCallbacks>,
    ) -> Result<ReloadOutcome, LoaderError> {
        let bound_direct = self.bound_direct_host;
        self.reload_with_hosts(new_dylib_path, next_host, bound_direct)
    }

    /// Transactional reload binding both `next_host` (`NV_IFACE_HOST = 5`) and `next_direct`
    /// (`NV_IFACE_DIRECT_HOST = 6`) onto the candidate dylib once before swapping out old gen.
    pub fn reload_with_hosts(
        &mut self,
        new_dylib_path: &Path,
        next_host: Option<NvHostCallbacks>,
        next_direct: Option<NvDirectHostEnv>,
    ) -> Result<ReloadOutcome, LoaderError> {
        let surface_id = self.surface_id;
        let next_gen = self.generation + 1;
        let (candidate, preserved_state_bytes) = {
            let saved = self.snapshot_state();
            let len = saved.len();
            let prior = (!saved.is_empty()).then_some(saved);
            (Self::load(new_dylib_path, surface_id, next_gen, prior)?, len)
        };
        Ok(self.commit_reloaded_candidate(
            candidate,
            next_host,
            next_direct,
            preserved_state_bytes,
            || {},
            || {},
        ))
    }

    /// Transactional reload using caller-captured `prior_state` (avoiding redundant double
    /// `snapshot_state()` calls) and invoking `on_old_unbound` strictly AFTER `old.bind_host(None)`
    /// and BEFORE `old`'s `destroy` runs.
    pub fn reload_with_host_and_state(
        &mut self,
        new_dylib_path: &Path,
        next_host: Option<NvHostCallbacks>,
        prior_state: Option<&[u8]>,
        on_old_unbound: impl FnOnce(),
    ) -> Result<ReloadOutcome, LoaderError> {
        let next_direct = self.bound_direct_host;
        self.reload_with_hosts_and_state(
            new_dylib_path,
            next_host,
            next_direct,
            prior_state,
            || {},
            on_old_unbound,
        )
    }

    /// Full transactional reload binding both lean `next_host` and `next_direct` onto the candidate
    /// dylib once, invoking `on_old_direct_deactivate` (deactivating old `DirectSurfaceBinding` and
    /// cancelling in-flight direct async calls) strictly BEFORE `old.bind_direct_host(None)`,
    /// invoking `on_old_unbound` strictly AFTER unbinding and BEFORE `old`'s `destroy` + `dlclose`.
    pub fn reload_with_hosts_and_state(
        &mut self,
        new_dylib_path: &Path,
        next_host: Option<NvHostCallbacks>,
        next_direct: Option<NvDirectHostEnv>,
        prior_state: Option<&[u8]>,
        on_old_direct_deactivate: impl FnOnce(),
        on_old_unbound: impl FnOnce(),
    ) -> Result<ReloadOutcome, LoaderError> {
        let len = prior_state.map_or(0, <[u8]>::len);
        let candidate =
            Self::load(new_dylib_path, self.surface_id, self.generation + 1, prior_state)?;
        Ok(self.commit_reloaded_candidate(
            candidate,
            next_host,
            next_direct,
            len,
            on_old_direct_deactivate,
            on_old_unbound,
        ))
    }

    fn commit_reloaded_candidate(
        &mut self,
        mut candidate: Self,
        next_host: Option<NvHostCallbacks>,
        next_direct: Option<NvDirectHostEnv>,
        preserved_state_bytes: usize,
        on_old_direct_deactivate: impl FnOnce(),
        on_old_unbound: impl FnOnce(),
    ) -> ReloadOutcome {
        let previous_generation = self.generation;
        let next_gen = candidate.generation;
        if let Some(cb) = next_host {
            candidate.bind_host(Some(cb));
        }
        if let Some(env) = next_direct {
            candidate.bind_direct_host(Some(env));
        }
        let mut old = std::mem::replace(self, candidate);
        on_old_direct_deactivate();
        if old.bound_direct_host.is_some() {
            let _ = old.bind_direct_host(None);
        }
        if old.bound_host.is_some() {
            let _ = old.bind_host(None);
        }
        on_old_unbound();
        drop(old);
        ReloadOutcome {
            previous_generation,
            generation: next_gen,
            preserved_state_bytes,
        }
    }
}

impl Drop for HotAppInstance {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            if self.bound_direct_host.is_some() {
                let _ = self.bind_direct_host(None);
            }
            if self.bound_host.is_some() {
                let _ = self.bind_host(None);
            }
            // SAFETY: `self.handle` was created by `self.surface.create` and is destroyed once before unloading `module`.
            unsafe { (self.surface.destroy)(self.handle) };
            self.handle = std::ptr::null_mut();
        }
        drop(self.module.take());
    }
}