1mod staging;
8
9use std::path::{Path, PathBuf};
10
11use nativeview_abi::{
12 slab_ptr, DispatchResult, HostServiceId, NvAppHandle, NvBufferSlice, NvComponentApi, NvDevApi,
13 NvDirectHostApi, NvDirectHostEnv, NvGestureDisposition, NvHostApi, NvHostCallbacks,
14 NvIntrinsicSize, NvLayoutApi, NvMapEntry, NvPointerApi, NvSizeConstraints, NvSurfaceApi,
15 SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT, NV_IFACE_DEV, NV_IFACE_DIRECT_HOST,
16 NV_IFACE_HOST, NV_IFACE_LAYOUT, NV_IFACE_POINTER, NV_IFACE_SURFACE,
17};
18
19use crate::tracker::PointerCaptureRequest;
20
21pub use staging::{
22 MODULE_STAGE_DIR_ENV, STAGES_PRIVATE_COPY, StagedDylib, is_valid_nv_interface_symbol,
23 resolve_in_process_symbol, staging_dir,
24};
25
26use crate::app_module::NvAppModule;
27
28#[derive(Debug)]
29pub enum LoaderError {
30 Io(std::io::Error),
32 Load(libloading::Error),
34 InvalidSymbol,
36 MissingEntry(libloading::Error),
38 MissingSymbol,
40 MissingSurfaceInterface,
41 NullHandle,
42 AlreadyLoadedInPlace(PathBuf),
46}
47
48impl std::fmt::Display for LoaderError {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 write!(f, "{self:?}")
51 }
52}
53
54impl std::error::Error for LoaderError {}
55
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ReloadOutcome {
60 pub previous_generation: u64,
61 pub generation: u64,
62 pub preserved_state_bytes: usize,
63}
64
65pub struct HotAppInstance {
66 module: Option<NvAppModule>,
67 surface: NvSurfaceApi,
68 layout: Option<NvLayoutApi>,
69 component: Option<NvComponentApi>,
70 dev: Option<NvDevApi>,
71 host: Option<NvHostApi>,
72 direct_host: Option<NvDirectHostApi>,
73 pointer: Option<NvPointerApi>,
74 bound_host: Option<NvHostCallbacks>,
75 bound_direct_host: Option<NvDirectHostEnv>,
76 handle: NvAppHandle,
77 surface_id: SurfaceId,
78 generation: u64,
79 close_request: bool,
81 unconsumed_key: bool,
83}
84
85impl HotAppInstance {
86 pub fn load(
90 dylib_path: &Path,
91 surface_id: SurfaceId,
92 generation: u64,
93 prior_state: Option<&[u8]>,
94 ) -> Result<Self, LoaderError> {
95 let module = NvAppModule::load_generation(dylib_path, "nv-hotswap", generation)?;
96 Self::from_module(&module, surface_id, prior_state)
97 }
98
99 pub fn from_module(
102 module: &NvAppModule,
103 surface_id: SurfaceId,
104 prior_state: Option<&[u8]>,
105 ) -> Result<Self, LoaderError> {
106 let get_iface = module.get_interface();
107
108 let (surface, layout, component, dev, host, direct_host, handle) = unsafe {
112 let surface_ptr = get_iface(NV_IFACE_SURFACE) as *const NvSurfaceApi;
113 if surface_ptr.is_null() {
114 return Err(LoaderError::MissingSurfaceInterface);
115 }
116 let surface = *surface_ptr;
117
118 let layout_ptr = get_iface(NV_IFACE_LAYOUT) as *const NvLayoutApi;
119 let layout = (!layout_ptr.is_null()).then(|| *layout_ptr);
120
121 let component_ptr = get_iface(NV_IFACE_COMPONENT) as *const NvComponentApi;
122 let component = (!component_ptr.is_null()).then(|| *component_ptr);
123
124 let dev_ptr = get_iface(NV_IFACE_DEV) as *const NvDevApi;
125 let dev = (!dev_ptr.is_null()).then(|| *dev_ptr);
126
127 let host_ptr = get_iface(NV_IFACE_HOST) as *const NvHostApi;
128 let host = (!host_ptr.is_null()).then(|| *host_ptr);
129
130 let direct_host_ptr = get_iface(NV_IFACE_DIRECT_HOST) as *const NvDirectHostApi;
131 let direct_host = (!direct_host_ptr.is_null()).then(|| *direct_host_ptr);
132
133 let handle = (surface.create)(surface_id);
134 if handle.is_null() {
135 return Err(LoaderError::NullHandle);
136 }
137 if let (Some(dev_api), Some(state)) = (dev, prior_state)
138 && !state.is_empty()
139 {
140 (dev_api.restore_state)(handle, NvBufferSlice::from_slice(state));
141 }
142 (surface, layout, component, dev, host, direct_host, handle)
143 };
144 let pointer = unsafe { (get_iface(NV_IFACE_POINTER) as *const NvPointerApi).as_ref().copied() };
146
147 Ok(Self {
148 module: Some(module.clone()),
149 surface,
150 layout,
151 component,
152 dev,
153 host,
154 direct_host,
155 pointer,
156 bound_host: None,
157 bound_direct_host: None,
158 handle,
159 surface_id,
160 generation: module.generation(),
161 close_request: false,
162 unconsumed_key: false,
163 })
164 }
165
166 #[inline]
168 pub fn module(&self) -> Option<&NvAppModule> {
169 self.module.as_ref()
170 }
171
172 pub fn surface_id(&self) -> SurfaceId {
173 self.surface_id
174 }
175
176 pub fn generation(&self) -> u64 {
177 self.generation
178 }
179
180 pub fn loaded_copy_path(&self) -> &Path {
181 self.module
182 .as_ref()
183 .and_then(NvAppModule::loaded_copy_path)
184 .unwrap_or_else(|| Path::new(""))
185 }
186
187 pub fn render(&mut self, frame_id: nativeview_abi::FrameId) -> &[u8] {
192 unsafe { (self.surface.render)(self.handle, frame_id).as_slice() }
194 }
195
196 pub fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool {
200 let raw = unsafe { (self.surface.dispatch_events)(self.handle, events.as_raw_batch()) };
202 let result = DispatchResult::from_bits_truncate(raw);
203 self.close_request = result.is_close_request();
204 self.unconsumed_key = result.is_unconsumed_key();
205 result.is_dirty()
206 }
207
208 pub fn take_close_request(&mut self) -> bool {
210 std::mem::take(&mut self.close_request)
211 }
212
213 pub fn take_unconsumed_key(&mut self) -> bool {
215 std::mem::take(&mut self.unconsumed_key)
216 }
217
218 pub fn drain_pointer_capture_requests(&mut self, sink: &mut dyn FnMut(PointerCaptureRequest)) {
220 if let Some(api) = self.pointer {
221 unsafe { crate::app::pointer::drain_capture_requests(api, self.handle, sink) };
223 }
224 }
225
226 pub fn measure(&mut self, constraints: NvSizeConstraints) -> Option<NvIntrinsicSize> {
227 self.layout.map(|api| {
228 unsafe { (api.measure)(self.handle, constraints) }
230 })
231 }
232
233 pub fn hit_test(&mut self, x: f32, y: f32, pointer_phase: u8) -> NvGestureDisposition {
234 match self.layout {
235 Some(api) => {
236 NvGestureDisposition::from_u8(unsafe {
238 (api.hit_test)(self.handle, x, y, pointer_phase)
239 })
240 }
241 None => NvGestureDisposition::PassThrough,
242 }
243 }
244
245 pub fn set_props(&mut self, entries: &[NvMapEntry]) -> bool {
246 match self.component {
247 Some(api) => unsafe {
249 (api.set_props)(
250 self.handle,
251 entries.as_ptr(),
252 entries.len().min(u32::MAX as usize) as u32,
253 ) != 0
254 },
255 None => false,
256 }
257 }
258
259 pub fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
261 match self.component {
262 Some(api) => unsafe {
264 ValidatedEvents::from_raw((api.drain_emitted_events)(self.handle))
265 },
266 None => ValidatedEvents::EMPTY,
267 }
268 }
269
270 pub fn apply_hot_patch(&mut self, patch: &[u8]) -> bool {
272 match self.dev {
273 Some(api) => unsafe {
275 (api.apply_hot_patch)(self.handle, NvBufferSlice::from_slice(patch)) != 0
276 },
277 None => false,
278 }
279 }
280
281 pub fn snapshot_state(&mut self) -> &[u8] {
284 match self.dev {
285 Some(api) => unsafe { (api.snapshot_state)(self.handle).as_slice() },
287 None => &[],
288 }
289 }
290
291 pub fn has_host_interface(&self) -> bool {
292 self.host.is_some()
293 }
294
295 pub fn bind_host(&mut self, callbacks: Option<NvHostCallbacks>) -> bool {
298 self.bound_host = callbacks;
299 match self.host {
300 Some(api) => {
301 let ptr = callbacks
302 .as_ref()
303 .map_or(std::ptr::null(), |cb| cb as *const NvHostCallbacks);
304 unsafe { (api.bind_host)(self.handle, ptr) };
306 true
307 }
308 None => false,
309 }
310 }
311
312 pub fn dispatch_host_events(&mut self, batch: &[u8]) -> bool {
314 match self.host {
315 Some(api) => unsafe {
317 (api.dispatch_host_events)(self.handle, NvBufferSlice::from_slice(batch)) != 0
318 },
319 None => false,
320 }
321 }
322
323 pub fn has_direct_host_interface(&self) -> bool {
325 self.direct_host.is_some()
326 }
327
328 pub fn bind_direct_host(&mut self, env: Option<NvDirectHostEnv>) -> bool {
331 self.bound_direct_host = env;
332 match self.direct_host {
333 Some(api) => {
334 let ptr = env
335 .as_ref()
336 .map_or(std::ptr::null(), |e| e as *const NvDirectHostEnv);
337 unsafe { (api.bind_direct_host)(self.handle, ptr) };
339 true
340 }
341 None => false,
342 }
343 }
344
345 pub fn dispatch_direct_completion(
348 &mut self,
349 local_req_id: u64,
350 status: i32,
351 payload: &[u8],
352 ) -> bool {
353 match self.direct_host {
354 Some(api) => unsafe {
356 (api.dispatch_direct_completion)(
357 self.handle,
358 local_req_id,
359 status,
360 slab_ptr(payload),
361 payload.len(),
362 ) != 0
363 },
364 None => false,
365 }
366 }
367
368 pub fn dispatch_direct_event(
371 &mut self,
372 service_id: HostServiceId,
373 event_id: u32,
374 flags: u32,
375 payload: &[u8],
376 ) -> bool {
377 match self.direct_host {
378 Some(api) => unsafe {
380 (api.dispatch_direct_event)(
381 self.handle,
382 service_id,
383 event_id,
384 flags,
385 slab_ptr(payload),
386 payload.len(),
387 ) != 0
388 },
389 None => false,
390 }
391 }
392
393 pub fn reload(&mut self, new_dylib_path: &Path) -> Result<ReloadOutcome, LoaderError> {
401 let bound_host = self.bound_host;
402 let bound_direct = self.bound_direct_host;
403 self.reload_with_hosts(new_dylib_path, bound_host, bound_direct)
404 }
405
406 pub fn reload_with_host(
410 &mut self,
411 new_dylib_path: &Path,
412 next_host: Option<NvHostCallbacks>,
413 ) -> Result<ReloadOutcome, LoaderError> {
414 let bound_direct = self.bound_direct_host;
415 self.reload_with_hosts(new_dylib_path, next_host, bound_direct)
416 }
417
418 pub fn reload_with_hosts(
421 &mut self,
422 new_dylib_path: &Path,
423 next_host: Option<NvHostCallbacks>,
424 next_direct: Option<NvDirectHostEnv>,
425 ) -> Result<ReloadOutcome, LoaderError> {
426 let surface_id = self.surface_id;
427 let next_gen = self.generation + 1;
428 let (candidate, preserved_state_bytes) = {
429 let saved = self.snapshot_state();
430 let len = saved.len();
431 let prior = (!saved.is_empty()).then_some(saved);
432 (Self::load(new_dylib_path, surface_id, next_gen, prior)?, len)
433 };
434 Ok(self.commit_reloaded_candidate(
435 candidate,
436 next_host,
437 next_direct,
438 preserved_state_bytes,
439 || {},
440 || {},
441 ))
442 }
443
444 pub fn reload_with_host_and_state(
448 &mut self,
449 new_dylib_path: &Path,
450 next_host: Option<NvHostCallbacks>,
451 prior_state: Option<&[u8]>,
452 on_old_unbound: impl FnOnce(),
453 ) -> Result<ReloadOutcome, LoaderError> {
454 let next_direct = self.bound_direct_host;
455 self.reload_with_hosts_and_state(
456 new_dylib_path,
457 next_host,
458 next_direct,
459 prior_state,
460 || {},
461 on_old_unbound,
462 )
463 }
464
465 pub fn reload_with_hosts_and_state(
470 &mut self,
471 new_dylib_path: &Path,
472 next_host: Option<NvHostCallbacks>,
473 next_direct: Option<NvDirectHostEnv>,
474 prior_state: Option<&[u8]>,
475 on_old_direct_deactivate: impl FnOnce(),
476 on_old_unbound: impl FnOnce(),
477 ) -> Result<ReloadOutcome, LoaderError> {
478 let len = prior_state.map_or(0, <[u8]>::len);
479 let candidate =
480 Self::load(new_dylib_path, self.surface_id, self.generation + 1, prior_state)?;
481 Ok(self.commit_reloaded_candidate(
482 candidate,
483 next_host,
484 next_direct,
485 len,
486 on_old_direct_deactivate,
487 on_old_unbound,
488 ))
489 }
490
491 fn commit_reloaded_candidate(
492 &mut self,
493 mut candidate: Self,
494 next_host: Option<NvHostCallbacks>,
495 next_direct: Option<NvDirectHostEnv>,
496 preserved_state_bytes: usize,
497 on_old_direct_deactivate: impl FnOnce(),
498 on_old_unbound: impl FnOnce(),
499 ) -> ReloadOutcome {
500 let previous_generation = self.generation;
501 let next_gen = candidate.generation;
502 if let Some(cb) = next_host {
503 candidate.bind_host(Some(cb));
504 }
505 if let Some(env) = next_direct {
506 candidate.bind_direct_host(Some(env));
507 }
508 let mut old = std::mem::replace(self, candidate);
509 on_old_direct_deactivate();
510 if old.bound_direct_host.is_some() {
511 let _ = old.bind_direct_host(None);
512 }
513 if old.bound_host.is_some() {
514 let _ = old.bind_host(None);
515 }
516 on_old_unbound();
517 drop(old);
518 ReloadOutcome {
519 previous_generation,
520 generation: next_gen,
521 preserved_state_bytes,
522 }
523 }
524}
525
526impl Drop for HotAppInstance {
527 fn drop(&mut self) {
528 if !self.handle.is_null() {
529 if self.bound_direct_host.is_some() {
530 let _ = self.bind_direct_host(None);
531 }
532 if self.bound_host.is_some() {
533 let _ = self.bind_host(None);
534 }
535 unsafe { (self.surface.destroy)(self.handle) };
537 self.handle = std::ptr::null_mut();
538 }
539 drop(self.module.take());
540 }
541}
542