1use super::*;
2
3pub fn with_context<CallbackFn, ReturnValue>(ctx: Context, operation: CallbackFn) -> ReturnValue
14where
15 CallbackFn: FnOnce() -> ReturnValue,
16{
17 let previous: Option<Context> =
18 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow_mut().replace(ctx));
19 let _guard: ContextGuard = ContextGuard::new(previous);
20 operation()
21}
22
23pub fn with_current_context<CallbackFn, ReturnValue>(operation: CallbackFn) -> ReturnValue
33where
34 CallbackFn: FnOnce(&Context) -> ReturnValue,
35{
36 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
37 let borrowed: Ref<'_, Option<Context>> = slot.borrow();
38 if let Some(ctx) = borrowed.as_ref() {
39 operation(ctx)
40 } else {
41 drop(borrowed);
42 let fallback: Context = Context::new(SceneHandle::new_tree(), PlatformKind::Headless);
43 operation(&fallback)
44 }
45 })
46}
47
48#[must_use]
54pub fn current_context() -> Context {
55 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
56 slot.borrow()
57 .clone()
58 .unwrap_or_else(|| Context::new(SceneHandle::new_tree(), PlatformKind::Headless))
59 })
60}
61
62#[must_use]
68pub fn has_context() -> bool {
69 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow().is_some())
70}
71
72#[must_use]
78pub fn current_platform() -> PlatformKind {
79 with_current_context(|ctx: &Context| ctx.get_platform())
80}
81
82pub fn mount_reactive_text<CallbackFn>(style: Style, producer: CallbackFn) -> NodeId
93where
94 CallbackFn: FnMut() -> String + 'static,
95{
96 let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
97 let node_id: NodeId = handle.with_write(
98 |tree: &mut SceneTree| tree.create_text(String::new(), style),
99 NodeId::default(),
100 );
101 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_text(node_id, producer));
102 handle.mutate(move |tree: &mut SceneTree| {
103 tree.attach_scope(node_id, scope);
104 });
105 node_id
106}
107
108pub fn bind_style_current<CallbackFn>(node_id: NodeId, producer: CallbackFn)
115where
116 CallbackFn: FnMut() -> Style + 'static,
117{
118 let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
119 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_style(node_id, producer));
120 handle.mutate(move |tree: &mut SceneTree| {
121 tree.attach_scope(node_id, scope);
122 });
123}
124
125pub fn bind_children_current<CallbackFn>(host: NodeId, builder: CallbackFn)
132where
133 CallbackFn: FnMut() -> Vec<NodeId> + 'static,
134{
135 let mut ctx: Context = current_context();
136 ctx.bind_children(host, builder);
137}
138
139#[must_use]
149pub fn into_text<ValueType>(value: ValueType) -> String
150where
151 ValueType: Into<String>,
152{
153 value.into()
154}
155
156pub fn register_frame_wakeup(hook: fn()) {
162 FRAME_WAKEUP_HOOK.store(hook as *mut (), Ordering::Release);
163 if FRAME_NEEDED.load(Ordering::Acquire) {
164 hook();
165 }
166}
167
168pub fn clear_frame_wakeup() {
170 FRAME_WAKEUP_HOOK.store(null_mut(), Ordering::Release);
171}
172
173#[inline(always)]
175pub fn notify_frame_needed() {
176 if !FRAME_NEEDED.load(Ordering::Relaxed) && !FRAME_NEEDED.swap(true, Ordering::AcqRel) {
177 let raw: *mut () = FRAME_WAKEUP_HOOK.load(Ordering::Acquire);
178 if !raw.is_null() {
179 let hook: fn() = unsafe { transmute::<*mut (), fn()>(raw) };
181 hook();
182 }
183 }
184}
185
186#[must_use]
192#[inline(always)]
193pub fn take_frame_needed() -> bool {
194 FRAME_NEEDED.swap(false, Ordering::AcqRel)
195}
196
197#[must_use]
203#[inline(always)]
204pub fn is_frame_needed() -> bool {
205 FRAME_NEEDED.load(Ordering::Acquire)
206}
207
208pub fn request_cancel_scroll_inertia() {
210 let _: bool = SCROLL_INERTIA_CANCEL_REQUESTED
211 .try_with(|flag: &Cell<bool>| {
212 flag.set(true);
213 true
214 })
215 .unwrap_or(false);
216}
217
218#[must_use]
224pub fn take_cancel_scroll_inertia_request() -> bool {
225 SCROLL_INERTIA_CANCEL_REQUESTED
226 .try_with(|flag: &Cell<bool>| flag.replace(false))
227 .unwrap_or(false)
228}
229
230#[must_use]
236#[inline(always)]
237pub(crate) fn is_scene_borrowed() -> bool {
238 SCENE_BORROW_DEPTH
239 .try_with(|depth: &Cell<u32>| depth.get() > 0)
240 .unwrap_or(false)
241}
242
243#[inline(always)]
245pub(crate) fn defer_effect_flush_while_borrowed() {
246 let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
247 flag.set(true);
248 });
249 notify_frame_needed();
250}
251
252#[must_use]
258#[inline(always)]
259pub(crate) fn has_deferred_effect_flush() -> bool {
260 DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
261}
262
263#[must_use]
269#[inline(always)]
270pub(crate) fn take_deferred_effect_flush() -> bool {
271 DEFERRED_EFFECT_FLUSH
272 .try_with(|flag: &Cell<bool>| flag.replace(false))
273 .unwrap_or(false)
274}
275
276pub(crate) fn reset_scene_borrow_state() {
278 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
279 depth.set(0);
280 });
281 let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
282 flag.set(false);
283 });
284 FRAME_NEEDED.store(false, Ordering::Release);
285}
286
287pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
294 let _: Result<(), _> =
295 NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
296 let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
297 });
298}
299
300#[must_use]
310pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
311 NETWORK_IMAGE_CACHE
312 .try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
313 .ok()
314 .flatten()
315}
316
317pub fn clear_network_image_cache() {
319 let _: Result<(), _> =
320 NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
321 slot.borrow_mut().clear();
322 });
323 let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
324 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
325 slot.borrow_mut().clear();
326 },
327 );
328}
329
330pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
337 if let Some(buf) = result.as_ref() {
338 cache_network_image(url, buf.clone());
339 }
340 let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
341 .try_with(
342 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
343 slot.borrow_mut().remove(url).unwrap_or_default()
344 },
345 )
346 .unwrap_or_default();
347 for callback_fn in waiters.into_iter() {
348 callback_fn(result.clone());
349 }
350 notify_frame_needed();
351}
352
353pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
360 let trimmed: &str = url.trim();
361 if trimmed.is_empty() {
362 on_ready(None);
363 return;
364 }
365 if let Some(hit) = cached_network_image(trimmed) {
366 on_ready(Some(hit));
367 return;
368 }
369 #[cfg(target_arch = "wasm32")]
370 {
371 let should_fetch: bool = NETWORK_IMAGE_WAITERS
372 .try_with(
373 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
374 let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
375 slot.borrow_mut();
376 if let Some(list) = map.get_mut(trimmed) {
377 list.push(on_ready.clone());
378 false
379 } else {
380 let _: Option<Vec<NetworkImageCallback>> =
381 map.insert(trimmed.to_string(), vec![on_ready.clone()]);
382 true
383 }
384 },
385 )
386 .unwrap_or(false);
387 if should_fetch {
388 web_load_network_image(trimmed);
389 }
390 }
391 #[cfg(not(target_arch = "wasm32"))]
392 {
393 on_ready(None);
394 }
395}
396
397#[inline(always)]
407fn canon_f32_sig_bits(val: f32) -> u32 {
408 if val.is_nan() {
409 u32::MAX
410 } else if val == 0.0 {
411 0
412 } else {
413 val.to_bits()
414 }
415}
416
417#[inline(always)]
428fn fnv_mix_u32(acc: u64, word: u32) -> u64 {
429 (acc ^ (word as u64)).wrapping_mul(0x0000_0100_0000_01B3)
430}
431
432#[must_use]
447#[inline]
448pub(crate) fn compute_style_sigs(style: &Style) -> (u64, u64) {
449 let lay: &LayoutStyle = style.layout_ref();
450 let vals: [f32; 7] = lay.get_length_vals();
451 let margin: Edges = lay.get_margin();
452 let padding: Edges = lay.get_padding();
453 let mut lh: u64 = 0xCBF2_9CE4_8422_2325;
454 lh = fnv_mix_u32(lh, lay.get_flags());
455 lh = fnv_mix_u32(lh, lay.get_length_tags());
456 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[0]));
457 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[1]));
458 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[2]));
459 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[3]));
460 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[4]));
461 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[5]));
462 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[6]));
463 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_grow()));
464 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_shrink()));
465 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_top()));
466 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_right()));
467 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_bottom()));
468 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_left()));
469 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_top()));
470 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_right()));
471 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_bottom()));
472 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_left()));
473 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_row_gap()));
474 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_column_gap()));
475 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_top_val()));
476 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_right_val()));
477 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_bottom_val()));
478 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_left_val()));
479 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_aspect_ratio_val()));
480 lh = fnv_mix_u32(lh, lay.get_z_index() as u32);
481 lh = fnv_mix_u32(lh, u32::from(lay.get_grid_columns()));
482 lh = fnv_mix_u32(
483 lh,
484 canon_f32_sig_bits(style.paint_ref().get_border().get_width()),
485 );
486 let txt: &TextStyle = style.text_ref();
487 let fam_tag: u32 = match txt.get_family() {
488 FontFamily::Sans => 0,
489 FontFamily::Monospace => 1,
490 FontFamily::Serif => 2,
491 };
492 let weight_tag: u32 = match txt.get_weight() {
493 FontWeight::Light => 0,
494 FontWeight::Normal => 1,
495 FontWeight::Medium => 2,
496 FontWeight::SemiBold => 3,
497 FontWeight::Bold => 4,
498 };
499 let align_tag: u32 = match txt.get_align() {
500 TextAlign::Left => 0,
501 TextAlign::Center => 1,
502 TextAlign::Right => 2,
503 };
504 let ov_tag: u32 = match txt.get_overflow() {
505 TextOverflow::Wrap => 0,
506 TextOverflow::Clip => 1,
507 TextOverflow::Ellipsis => 2,
508 };
509 let packed_enums: u32 = fam_tag
510 | (weight_tag << 3)
511 | (align_tag << 7)
512 | (ov_tag << 10)
513 | (u32::from(txt.get_italic()) << 13);
514 let mut th: u64 = 0xCBF2_9CE4_8422_2325;
515 th = fnv_mix_u32(th, packed_enums);
516 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_font_size()));
517 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_line_height()));
518 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_letter_spacing()));
519 (lh, th)
520}