1use super::*;
2
3pub fn with_context<F, R>(ctx: Context, operation: F) -> R
14where
15 F: FnOnce() -> R,
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<F, R>(operation: F) -> R
33where
34 F: FnOnce(&Context) -> R,
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<F>(style: Style, producer: F) -> NodeId
93where
94 F: 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<F>(node_id: NodeId, producer: F)
115where
116 F: 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<F>(host: NodeId, builder: F)
132where
133 F: 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<T>(value: T) -> String
150where
151 T: 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
208#[must_use]
214#[inline(always)]
215pub(crate) fn is_scene_borrowed() -> bool {
216 SCENE_BORROW_DEPTH
217 .try_with(|depth: &Cell<u32>| depth.get() > 0)
218 .unwrap_or(false)
219}
220
221#[inline(always)]
223pub(crate) fn defer_effect_flush_while_borrowed() {
224 let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
225 flag.set(true);
226 });
227 notify_frame_needed();
228}
229
230#[must_use]
236#[inline(always)]
237pub(crate) fn has_deferred_effect_flush() -> bool {
238 DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
239}
240
241#[must_use]
247#[inline(always)]
248pub(crate) fn take_deferred_effect_flush() -> bool {
249 DEFERRED_EFFECT_FLUSH
250 .try_with(|flag: &Cell<bool>| flag.replace(false))
251 .unwrap_or(false)
252}
253
254pub(crate) fn reset_scene_borrow_state() {
256 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
257 depth.set(0);
258 });
259 let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
260 flag.set(false);
261 });
262 FRAME_NEEDED.store(false, Ordering::Release);
263}
264
265pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
272 let _: Result<(), _> =
273 NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
274 let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
275 });
276}
277
278#[must_use]
288pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
289 NETWORK_IMAGE_CACHE
290 .try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
291 .ok()
292 .flatten()
293}
294
295pub fn clear_network_image_cache() {
297 let _: Result<(), _> =
298 NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
299 slot.borrow_mut().clear();
300 });
301 let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
302 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
303 slot.borrow_mut().clear();
304 },
305 );
306}
307
308pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
315 if let Some(buf) = result.as_ref() {
316 cache_network_image(url, buf.clone());
317 }
318 let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
319 .try_with(
320 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
321 slot.borrow_mut().remove(url).unwrap_or_default()
322 },
323 )
324 .unwrap_or_default();
325 for cb in waiters.into_iter() {
326 cb(result.clone());
327 }
328 notify_frame_needed();
329}
330
331pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
338 let trimmed: &str = url.trim();
339 if trimmed.is_empty() {
340 on_ready(None);
341 return;
342 }
343 if let Some(hit) = cached_network_image(trimmed) {
344 on_ready(Some(hit));
345 return;
346 }
347 #[cfg(target_arch = "wasm32")]
348 {
349 let should_fetch: bool = NETWORK_IMAGE_WAITERS
350 .try_with(
351 |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
352 let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
353 slot.borrow_mut();
354 if let Some(list) = map.get_mut(trimmed) {
355 list.push(on_ready.clone());
356 false
357 } else {
358 let _: Option<Vec<NetworkImageCallback>> =
359 map.insert(trimmed.to_string(), vec![on_ready.clone()]);
360 true
361 }
362 },
363 )
364 .unwrap_or(false);
365 if should_fetch {
366 web_load_network_image(trimmed);
367 }
368 }
369 #[cfg(not(target_arch = "wasm32"))]
370 {
371 on_ready(None);
372 }
373}
374
375#[inline(always)]
385fn canon_f32_sig_bits(val: f32) -> u32 {
386 if val.is_nan() {
387 u32::MAX
388 } else if val == 0.0 {
389 0
390 } else {
391 val.to_bits()
392 }
393}
394
395#[inline(always)]
406fn fnv_mix_u32(acc: u64, word: u32) -> u64 {
407 (acc ^ (word as u64)).wrapping_mul(0x0000_0100_0000_01B3)
408}
409
410#[must_use]
425#[inline]
426pub(crate) fn compute_style_sigs(style: &Style) -> (u64, u64) {
427 let lay: &LayoutStyle = style.layout_ref();
428 let vals: [f32; 7] = lay.get_length_vals();
429 let margin: Edges = lay.get_margin();
430 let padding: Edges = lay.get_padding();
431 let mut lh: u64 = 0xCBF2_9CE4_8422_2325;
432 lh = fnv_mix_u32(lh, lay.get_flags());
433 lh = fnv_mix_u32(lh, lay.get_length_tags());
434 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[0]));
435 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[1]));
436 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[2]));
437 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[3]));
438 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[4]));
439 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[5]));
440 lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[6]));
441 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_grow()));
442 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_shrink()));
443 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_top()));
444 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_right()));
445 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_bottom()));
446 lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_left()));
447 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_top()));
448 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_right()));
449 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_bottom()));
450 lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_left()));
451 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_row_gap()));
452 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_column_gap()));
453 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_top_val()));
454 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_right_val()));
455 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_bottom_val()));
456 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_left_val()));
457 lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_aspect_ratio_val()));
458 lh = fnv_mix_u32(lh, lay.get_z_index() as u32);
459 lh = fnv_mix_u32(lh, u32::from(lay.get_grid_columns()));
460 lh = fnv_mix_u32(
461 lh,
462 canon_f32_sig_bits(style.paint_ref().get_border().get_width()),
463 );
464 let txt: &TextStyle = style.text_ref();
465 let fam_tag: u32 = match txt.get_family() {
466 FontFamily::Sans => 0,
467 FontFamily::Monospace => 1,
468 FontFamily::Serif => 2,
469 };
470 let weight_tag: u32 = match txt.get_weight() {
471 FontWeight::Light => 0,
472 FontWeight::Normal => 1,
473 FontWeight::Medium => 2,
474 FontWeight::SemiBold => 3,
475 FontWeight::Bold => 4,
476 };
477 let align_tag: u32 = match txt.get_align() {
478 TextAlign::Left => 0,
479 TextAlign::Center => 1,
480 TextAlign::Right => 2,
481 };
482 let ov_tag: u32 = match txt.get_overflow() {
483 TextOverflow::Wrap => 0,
484 TextOverflow::Clip => 1,
485 TextOverflow::Ellipsis => 2,
486 };
487 let packed_enums: u32 = fam_tag
488 | (weight_tag << 3)
489 | (align_tag << 7)
490 | (ov_tag << 10)
491 | (u32::from(txt.get_italic()) << 13);
492 let mut th: u64 = 0xCBF2_9CE4_8422_2325;
493 th = fnv_mix_u32(th, packed_enums);
494 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_font_size()));
495 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_line_height()));
496 th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_letter_spacing()));
497 (lh, th)
498}