use super::*;
pub fn with_context<F, R>(ctx: Context, operation: F) -> R
where
F: FnOnce() -> R,
{
let previous: Option<Context> =
ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow_mut().replace(ctx));
let _guard: ContextGuard = ContextGuard::new(previous);
operation()
}
pub fn with_current_context<F, R>(operation: F) -> R
where
F: FnOnce(&Context) -> R,
{
ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
let borrowed: Ref<'_, Option<Context>> = slot.borrow();
if let Some(ctx) = borrowed.as_ref() {
operation(ctx)
} else {
drop(borrowed);
let fallback: Context = Context::new(SceneHandle::new_tree(), PlatformKind::Headless);
operation(&fallback)
}
})
}
#[must_use]
pub fn current_context() -> Context {
ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
slot.borrow()
.clone()
.unwrap_or_else(|| Context::new(SceneHandle::new_tree(), PlatformKind::Headless))
})
}
#[must_use]
pub fn has_context() -> bool {
ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow().is_some())
}
#[must_use]
pub fn current_platform() -> PlatformKind {
with_current_context(|ctx: &Context| ctx.get_platform())
}
pub fn mount_reactive_text<F>(style: Style, producer: F) -> NodeId
where
F: FnMut() -> String + 'static,
{
let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
let node_id: NodeId = handle.with_write(
|tree: &mut SceneTree| tree.create_text(String::new(), style),
NodeId::default(),
);
let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_text(node_id, producer));
handle.mutate(move |tree: &mut SceneTree| {
tree.attach_scope(node_id, scope);
});
node_id
}
pub fn bind_style_current<F>(node_id: NodeId, producer: F)
where
F: FnMut() -> Style + 'static,
{
let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_style(node_id, producer));
handle.mutate(move |tree: &mut SceneTree| {
tree.attach_scope(node_id, scope);
});
}
pub fn bind_children_current<F>(host: NodeId, builder: F)
where
F: FnMut() -> Vec<NodeId> + 'static,
{
let mut ctx: Context = current_context();
ctx.bind_children(host, builder);
}
#[must_use]
pub fn into_text<T>(value: T) -> String
where
T: Into<String>,
{
value.into()
}
pub fn register_frame_wakeup(hook: fn()) {
FRAME_WAKEUP_HOOK.store(hook as *mut (), Ordering::Release);
if FRAME_NEEDED.load(Ordering::Acquire) {
hook();
}
}
pub fn clear_frame_wakeup() {
FRAME_WAKEUP_HOOK.store(null_mut(), Ordering::Release);
}
#[inline(always)]
pub fn notify_frame_needed() {
if !FRAME_NEEDED.load(Ordering::Relaxed) && !FRAME_NEEDED.swap(true, Ordering::AcqRel) {
let raw: *mut () = FRAME_WAKEUP_HOOK.load(Ordering::Acquire);
if !raw.is_null() {
let hook: fn() = unsafe { transmute::<*mut (), fn()>(raw) };
hook();
}
}
}
#[must_use]
#[inline(always)]
pub fn take_frame_needed() -> bool {
FRAME_NEEDED.swap(false, Ordering::AcqRel)
}
#[must_use]
#[inline(always)]
pub fn is_frame_needed() -> bool {
FRAME_NEEDED.load(Ordering::Acquire)
}
#[must_use]
#[inline(always)]
pub(crate) fn is_scene_borrowed() -> bool {
SCENE_BORROW_DEPTH
.try_with(|depth: &Cell<u32>| depth.get() > 0)
.unwrap_or(false)
}
#[inline(always)]
pub(crate) fn defer_effect_flush_while_borrowed() {
let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
flag.set(true);
});
notify_frame_needed();
}
#[must_use]
#[inline(always)]
pub(crate) fn has_deferred_effect_flush() -> bool {
DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
}
#[must_use]
#[inline(always)]
pub(crate) fn take_deferred_effect_flush() -> bool {
DEFERRED_EFFECT_FLUSH
.try_with(|flag: &Cell<bool>| flag.replace(false))
.unwrap_or(false)
}
pub(crate) fn reset_scene_borrow_state() {
let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
depth.set(0);
});
let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
flag.set(false);
});
FRAME_NEEDED.store(false, Ordering::Release);
}
pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
let _: Result<(), _> =
NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
});
}
#[must_use]
pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
NETWORK_IMAGE_CACHE
.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
.ok()
.flatten()
}
pub fn clear_network_image_cache() {
let _: Result<(), _> =
NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
slot.borrow_mut().clear();
});
let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
|slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
slot.borrow_mut().clear();
},
);
}
pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
if let Some(buf) = result.as_ref() {
cache_network_image(url, buf.clone());
}
let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
.try_with(
|slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
slot.borrow_mut().remove(url).unwrap_or_default()
},
)
.unwrap_or_default();
for cb in waiters.into_iter() {
cb(result.clone());
}
notify_frame_needed();
}
pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
let trimmed: &str = url.trim();
if trimmed.is_empty() {
on_ready(None);
return;
}
if let Some(hit) = cached_network_image(trimmed) {
on_ready(Some(hit));
return;
}
#[cfg(target_arch = "wasm32")]
{
let should_fetch: bool = NETWORK_IMAGE_WAITERS
.try_with(
|slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
slot.borrow_mut();
if let Some(list) = map.get_mut(trimmed) {
list.push(on_ready.clone());
false
} else {
let _: Option<Vec<NetworkImageCallback>> =
map.insert(trimmed.to_string(), vec![on_ready.clone()]);
true
}
},
)
.unwrap_or(false);
if should_fetch {
web_load_network_image(trimmed);
}
}
#[cfg(not(target_arch = "wasm32"))]
{
on_ready(None);
}
}
#[inline(always)]
fn canon_f32_sig_bits(val: f32) -> u32 {
if val.is_nan() {
u32::MAX
} else if val == 0.0 {
0
} else {
val.to_bits()
}
}
#[inline(always)]
fn fnv_mix_u32(acc: u64, word: u32) -> u64 {
(acc ^ (word as u64)).wrapping_mul(0x0000_0100_0000_01B3)
}
#[must_use]
#[inline]
pub(crate) fn compute_style_sigs(style: &Style) -> (u64, u64) {
let lay: &LayoutStyle = style.layout_ref();
let vals: [f32; 7] = lay.get_length_vals();
let margin: Edges = lay.get_margin();
let padding: Edges = lay.get_padding();
let mut lh: u64 = 0xCBF2_9CE4_8422_2325;
lh = fnv_mix_u32(lh, lay.get_flags());
lh = fnv_mix_u32(lh, lay.get_length_tags());
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[0]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[1]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[2]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[3]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[4]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[5]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[6]));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_grow()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_shrink()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_top()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_right()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_bottom()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_left()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_top()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_right()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_bottom()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_left()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_row_gap()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_column_gap()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_top_val()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_right_val()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_bottom_val()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_left_val()));
lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_aspect_ratio_val()));
lh = fnv_mix_u32(lh, lay.get_z_index() as u32);
lh = fnv_mix_u32(lh, u32::from(lay.get_grid_columns()));
lh = fnv_mix_u32(
lh,
canon_f32_sig_bits(style.paint_ref().get_border().get_width()),
);
let txt: &TextStyle = style.text_ref();
let fam_tag: u32 = match txt.get_family() {
FontFamily::Sans => 0,
FontFamily::Monospace => 1,
FontFamily::Serif => 2,
};
let weight_tag: u32 = match txt.get_weight() {
FontWeight::Light => 0,
FontWeight::Normal => 1,
FontWeight::Medium => 2,
FontWeight::SemiBold => 3,
FontWeight::Bold => 4,
};
let align_tag: u32 = match txt.get_align() {
TextAlign::Left => 0,
TextAlign::Center => 1,
TextAlign::Right => 2,
};
let ov_tag: u32 = match txt.get_overflow() {
TextOverflow::Wrap => 0,
TextOverflow::Clip => 1,
TextOverflow::Ellipsis => 2,
};
let packed_enums: u32 = fam_tag
| (weight_tag << 3)
| (align_tag << 7)
| (ov_tag << 10)
| (u32::from(txt.get_italic()) << 13);
let mut th: u64 = 0xCBF2_9CE4_8422_2325;
th = fnv_mix_u32(th, packed_enums);
th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_font_size()));
th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_line_height()));
th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_letter_spacing()));
(lh, th)
}