use core::any::TypeId;
use core::cell::Cell;
use core::marker::PhantomData;
use core::ops::Deref;
use crate::arena::{ScratchArena, StrRef};
use crate::element::View;
use crate::i18n::DynamicCatalog;
use crate::i18n::{I18nArg, I18nContext, Locale, StaticCatalog, TextDirection};
use super::events::{DragEvent, ImePreedit, SafeAreaInsets};
use super::{CoreTheme, Handle, PodId, PodPool};
#[inline(always)]
pub const fn derive_scoped_id(parent_seed: u32, salt: u32, local_id: u32) -> u32 {
let mut h = parent_seed.wrapping_mul(0x9E37_79B9) ^ salt.wrapping_mul(0x85EB_CA6B);
h ^= local_id.wrapping_add(0xC2B2_AE35);
h ^= h >> 16;
h = h.wrapping_mul(0x7FEB_352D);
h ^= h >> 15;
h = h.wrapping_mul(0x846C_A68B);
h ^= h >> 16;
h | 0x8000_0000
}
pub struct FrameScope {
pub(crate) arena: ScratchArena,
pub(crate) theme: CoreTheme,
pub(crate) theme_override_ptr: Cell<*const CoreTheme>,
pub(crate) safe_area: SafeAreaInsets,
pub(crate) keyboard_inset: i16,
pub(crate) current_pod: PodId,
pub(crate) current_pod_gen: Option<u16>,
pub(crate) pool_ptr: *const PodPool,
pub(crate) now_ms: u32,
pub(crate) frame_requested: Cell<bool>,
pub(crate) id_stack: Cell<[u32; 8]>,
pub(crate) id_depth: Cell<u8>,
pub(crate) ime_preedit: ImePreedit,
pub(crate) i18n: I18nContext,
pub(crate) locale_override: Cell<Option<Locale>>,
pub(crate) catalog_override: Cell<Option<&'static StaticCatalog>>,
}
impl Default for FrameScope {
fn default() -> Self {
Self::new()
}
}
impl FrameScope {
pub fn new() -> Self {
Self::with_theme(CoreTheme::dark())
}
pub fn with_theme(theme: CoreTheme) -> Self {
Self {
arena: ScratchArena::new(),
theme,
theme_override_ptr: Cell::new(core::ptr::null()),
safe_area: SafeAreaInsets::ZERO,
keyboard_inset: 0,
current_pod: PodId(0),
current_pod_gen: None,
pool_ptr: core::ptr::null(),
now_ms: 0,
frame_requested: Cell::new(false),
id_stack: Cell::new([0; 8]),
id_depth: Cell::new(0),
ime_preedit: ImePreedit::empty(),
i18n: I18nContext::new(Locale::EN_US),
locale_override: Cell::new(None),
catalog_override: Cell::new(None),
}
}
#[inline]
pub fn ime_preedit(&self) -> Option<&str> {
if self.ime_preedit.is_empty() {
None
} else {
Some(self.ime_preedit.as_str())
}
}
#[inline(always)]
pub const fn ime_preedit_state(&self) -> ImePreedit {
self.ime_preedit
}
#[inline(always)]
pub fn set_ime_preedit(&mut self, preedit: ImePreedit) {
self.ime_preedit = preedit;
}
#[inline(always)]
pub const fn safe_area(&self) -> SafeAreaInsets {
self.safe_area
}
#[inline(always)]
pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
self.safe_area = insets;
}
#[inline(always)]
pub const fn keyboard_inset(&self) -> i16 {
self.keyboard_inset
}
#[inline(always)]
pub fn set_keyboard_inset(&mut self, height: i16) {
self.keyboard_inset = height.max(0);
}
#[inline]
pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<super::PodReadGuard<'s, T>> {
if self.pool_ptr.is_null() || handle.id == self.current_pod {
return None;
}
unsafe {
let pool = &*self.pool_ptr;
let res = pool.read_guarded(handle);
if res.is_some() {
pool.record_cross_read(self.current_pod, handle.id);
}
res
}
}
#[inline]
pub fn read_with<T: View, R>(&self, handle: Handle<T>, f: impl FnOnce(&T) -> R) -> Option<R> {
let guard = self.read(handle)?;
Some(f(&*guard))
}
#[inline(always)]
pub fn arena(&self) -> &ScratchArena {
&self.arena
}
#[inline(always)]
pub fn arena_mut(&mut self) -> &mut ScratchArena {
self.theme_override_ptr.set(core::ptr::null());
self.locale_override.set(None);
self.catalog_override.set(None);
self.id_depth.set(0);
&mut self.arena
}
#[inline(always)]
pub fn locale(&self) -> Locale {
self.locale_override.get().unwrap_or(self.i18n.locale)
}
#[inline(always)]
pub fn text_direction(&self) -> TextDirection {
self.locale().text_direction()
}
#[inline(always)]
pub fn is_rtl(&self) -> bool {
self.locale().is_rtl()
}
#[inline(always)]
pub fn set_locale(&mut self, locale: Locale) {
self.i18n.locale = locale;
self.locale_override.set(None);
}
#[inline(always)]
pub fn override_locale(&self, locale: Locale) {
self.locale_override.set(Some(locale));
}
#[inline(always)]
pub fn set_i18n_catalog(&mut self, catalog: &'static StaticCatalog) {
self.i18n.static_catalog = Some(catalog);
self.catalog_override.set(None);
}
#[inline(always)]
pub fn override_i18n_catalog(&self, catalog: &'static StaticCatalog) {
self.catalog_override.set(Some(catalog));
}
#[inline]
pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<DynamicCatalog>) {
self.i18n.dynamic_catalog = Some(catalog);
}
#[inline]
fn resolve_i18n_template(&self, key: &str) -> Option<&str> {
let loc = self.locale();
if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
if let Some(v) = dyn_cat.lookup(loc, key) {
return Some(v);
}
}
if let Some(ov_cat) = self.catalog_override.get() {
if let Some(v) = ov_cat.lookup(loc, key) {
return Some(v);
}
}
if let Some(st_cat) = self.i18n.static_catalog {
if let Some(v) = st_cat.lookup(loc, key) {
return Some(v);
}
}
None
}
#[inline]
fn resolve_i18n_plural_template(&self, key: &str, count: i64) -> Option<&str> {
let loc = self.locale();
if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
if let Some(v) = dyn_cat.lookup_plural(loc, key, count) {
return Some(v);
}
}
if let Some(ov_cat) = self.catalog_override.get() {
if let Some(v) = ov_cat.lookup_plural(loc, key, count) {
return Some(v);
}
}
if let Some(st_cat) = self.i18n.static_catalog {
if let Some(v) = st_cat.lookup_plural(loc, key, count) {
return Some(v);
}
}
None
}
#[inline]
pub fn t<'a>(&'a self, key: &str) -> StrRef<'a> {
let loc = self.locale();
if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
if let Some(v) = dyn_cat.lookup(loc, key) {
return self.arena.alloc_str(v);
}
}
if let Some(ov_cat) = self.catalog_override.get() {
if let Some(v) = ov_cat.lookup(loc, key) {
return StrRef::from(v);
}
}
if let Some(st_cat) = self.i18n.static_catalog {
if let Some(v) = st_cat.lookup(loc, key) {
return StrRef::from(v);
}
}
self.arena.alloc_str(key)
}
#[inline]
pub fn t_or<'a>(&'a self, key: &str, fallback: &'a str) -> StrRef<'a> {
if let Some(v) = self.resolve_i18n_template(key) {
self.arena.alloc_str(v)
} else {
StrRef::from(fallback)
}
}
#[inline]
pub fn t_args<'a>(&'a self, key: &str, args: &[(&str, I18nArg<'_>)]) -> StrRef<'a> {
let tmpl = self.resolve_i18n_template(key).unwrap_or(key);
crate::i18n::format_template(&self.arena, tmpl, args)
}
#[inline]
pub fn t_plural<'a>(&'a self, key: &str, count: i64) -> StrRef<'a> {
let tmpl = self.resolve_i18n_plural_template(key, count).unwrap_or(key);
crate::i18n::format_template(&self.arena, tmpl, &[("count", I18nArg::Int(count))])
}
#[inline]
pub fn push_id(&self, seed: u32) {
let depth = self.id_depth.get() as usize;
let mut stack = self.id_stack.get();
let parent = if depth == 0 {
self.current_pod.0 as u32
} else {
stack[(depth - 1).min(7)]
};
let combined = derive_scoped_id(parent, 0x5343_4F50, seed);
if depth < 8 {
stack[depth] = combined;
self.id_stack.set(stack);
self.id_depth.set((depth + 1) as u8);
}
}
#[inline]
pub fn pop_id(&self) {
let depth = self.id_depth.get();
if depth > 0 {
self.id_depth.set(depth - 1);
}
}
#[inline]
pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
self.push_id(seed);
let res = f(self);
self.pop_id();
res
}
#[inline]
pub fn scoped_id(&self, local_id: u32) -> u32 {
let depth = self.id_depth.get() as usize;
let seed = if depth == 0 {
self.current_pod.0 as u32
} else {
self.id_stack.get()[(depth - 1).min(7)]
};
derive_scoped_id(seed, 0x4C4F_434C, local_id)
}
#[inline(always)]
pub fn theme(&self) -> &CoreTheme {
let ptr = self.theme_override_ptr.get();
if !ptr.is_null() {
unsafe { &*ptr }
} else {
&self.theme
}
}
#[inline(always)]
pub fn set_theme(&mut self, theme: CoreTheme) {
self.theme = theme;
self.theme_override_ptr.set(core::ptr::null());
}
#[inline]
pub fn override_theme(&self, theme: CoreTheme) {
if self.arena.can_alloc_slice::<CoreTheme>(1) {
let alloc_ref: &CoreTheme = self.arena.alloc(theme);
self.theme_override_ptr.set(alloc_ref as *const CoreTheme);
}
}
#[inline(always)]
pub fn current_pod(&self) -> PodId {
self.current_pod
}
#[inline(always)]
pub const fn now_ms(&self) -> u32 {
self.now_ms
}
#[inline(always)]
pub fn set_now_ms(&mut self, now_ms: u32) {
self.now_ms = now_ms;
}
#[inline(always)]
pub fn request_frame(&self) {
self.frame_requested.set(true);
}
#[inline(always)]
pub fn keep_animating(&self, running: bool) -> bool {
if running {
self.frame_requested.set(true);
}
running
}
#[inline(always)]
pub fn is_frame_requested(&self) -> bool {
self.frame_requested.get()
}
}
#[repr(transparent)]
pub struct Scope<V> {
pub(crate) frame: FrameScope,
_marker: PhantomData<V>,
}
impl<V> Default for Scope<V> {
fn default() -> Self {
Self::new()
}
}
impl<V> Scope<V> {
pub fn new() -> Self {
Self {
frame: FrameScope::new(),
_marker: PhantomData,
}
}
#[inline(always)]
pub fn set_current_pod(&mut self, id: PodId) {
self.frame.current_pod = id;
}
#[inline(always)]
pub fn theme(&self) -> &CoreTheme {
self.frame.theme()
}
#[inline(always)]
pub fn arena(&self) -> &ScratchArena {
self.frame.arena()
}
#[inline]
pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
self.frame.push_id(seed);
let res = f(self);
self.frame.pop_id();
res
}
}
impl<V: View> Scope<V> {
pub fn listener<'a, E, F>(&'a self, handler: F) -> &'a dyn Fn(E, &mut ActionScope)
where
E: 'a,
F: Fn(&mut V, E, &mut ActionScope) + 'a,
{
let pod_id = self.frame.current_pod;
let pod_gen = self.frame.current_pod_gen;
self.frame.arena.alloc(move |event: E, acx: &mut ActionScope| {
let prev_pod = acx.active_pod;
let prev_skip = acx.notify_skipped;
acx.active_pod = pod_id;
acx.notify_skipped = false;
if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
let view_ref = unsafe { &mut *(view_ptr as *mut V) };
handler(view_ref, event, acx);
acx.release_view_borrow(pod_id);
if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
acx.notify();
}
}
acx.flush_signal_dirty_pods();
acx.notify_skipped = prev_skip;
acx.active_pod = prev_pod;
})
}
pub fn action<'a, F>(&'a self, handler: F) -> &'a dyn Fn(&mut ActionScope)
where
F: Fn(&mut V, &mut ActionScope) + 'a,
{
let pod_id = self.frame.current_pod;
let pod_gen = self.frame.current_pod_gen;
self.frame.arena.alloc(move |acx: &mut ActionScope| {
let prev_pod = acx.active_pod;
let prev_skip = acx.notify_skipped;
acx.active_pod = pod_id;
acx.notify_skipped = false;
if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
let view_ref = unsafe { &mut *(view_ptr as *mut V) };
handler(view_ref, acx);
acx.release_view_borrow(pod_id);
if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
acx.notify();
}
}
acx.flush_signal_dirty_pods();
acx.notify_skipped = prev_skip;
acx.active_pod = prev_pod;
})
}
}
impl<V> Deref for Scope<V> {
type Target = FrameScope;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.frame
}
}
pub struct ActionScope<'p> {
pub(crate) active_pod: PodId,
pub(crate) pool: &'p mut PodPool,
pub(crate) click_pos: (i16, i16),
pub(crate) drag_event: DragEvent,
pub(crate) propagation_stopped: bool,
pub(crate) notify_skipped: bool,
pub(crate) now_ms: u32,
pub(crate) modifiers: super::events::KeyModifiers,
pub(crate) async_app: Option<crate::async_rt::AsyncApp>,
}
impl<'p> ActionScope<'p> {
#[inline(always)]
pub(crate) fn new(
active_pod: PodId,
pool: &'p mut PodPool,
click_pos: (i16, i16),
drag_event: DragEvent,
now_ms: u32,
) -> Self {
Self {
active_pod,
pool,
click_pos,
drag_event,
propagation_stopped: false,
notify_skipped: false,
now_ms,
modifiers: super::events::KeyModifiers::NONE,
async_app: None,
}
}
#[inline(always)]
pub(crate) fn with_async_app(mut self, app: crate::async_rt::AsyncApp) -> Self {
self.async_app = Some(app);
self
}
#[inline(always)]
pub(crate) fn with_modifiers(mut self, modifiers: super::events::KeyModifiers) -> Self {
self.modifiers = modifiers;
self
}
#[inline]
pub fn handle<V: View>(&self) -> Option<Handle<V>> {
let generation = self
.pool
.current_generation_for_type(self.active_pod, TypeId::of::<V>())?;
Some(Handle::with_generation(self.active_pod, generation))
}
pub fn spawn<V, T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
where
V: View,
T: 'static,
F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
Fut: core::future::Future<Output = T> + 'static,
{
let handle = self
.handle::<V>()
.expect("ActionScope::spawn::<V> 类型与当前活跃视图不匹配");
let app = self
.async_app
.clone()
.expect("ActionScope 未绑定 ForegroundExecutor");
app.spawn_for(handle, f)
}
pub fn spawn_app<T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
where
T: 'static,
F: FnOnce(crate::async_rt::AsyncApp) -> Fut,
Fut: core::future::Future<Output = T> + 'static,
{
let app = self
.async_app
.clone()
.expect("ActionScope 未绑定 ForegroundExecutor");
app.spawn(f)
}
#[inline]
pub fn background_executor(&self) -> crate::async_rt::BackgroundExecutor {
self.async_app
.as_ref()
.map(|app| app.background_executor())
.unwrap_or_else(crate::async_rt::BackgroundExecutor::new)
}
#[inline]
pub fn background_spawn<T, Fut>(&self, fut: Fut) -> crate::async_rt::Task<T>
where
T: Send + 'static,
Fut: core::future::Future<Output = T> + Send + 'static,
{
self.background_executor().spawn(fut)
}
#[inline]
pub fn timer(&self, duration: core::time::Duration) -> crate::async_rt::Timer {
self.background_executor().timer(duration)
}
#[inline]
pub fn defer<F>(&mut self, f: F)
where
F: FnOnce(&mut ActionScope) + 'static,
{
if let Some(app) = &self.async_app {
app.defer(f);
}
}
pub fn defer_self<V, F>(&mut self, f: F)
where
V: View,
F: FnOnce(&mut V, &mut ActionScope) + 'static,
{
let Some(handle) = self.handle::<V>() else {
return;
};
if let Some(app) = &self.async_app {
app.defer(move |acx| {
let _ = acx.update(handle, f);
});
}
}
#[inline]
pub fn notify(&mut self) {
self.notify_skipped = false;
self.pool.mark_dirty(self.active_pod);
}
#[inline(always)]
pub fn skip_notify(&mut self) {
self.notify_skipped = true;
}
#[inline]
pub fn flush_signal_dirty_pods(&mut self) {
self.pool.flush_signal_dirty_pods();
}
#[inline(always)]
pub fn stop_propagation(&mut self) {
self.propagation_stopped = true;
}
#[inline(always)]
pub const fn is_propagation_stopped(&self) -> bool {
self.propagation_stopped
}
#[inline]
pub fn notify_handle<T: View>(&mut self, handle: Handle<T>) {
if self.pool.get(handle).is_some() {
self.pool.mark_dirty(handle.id);
}
}
#[inline]
pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<&'s T> {
if handle.id == self.active_pod {
return None;
}
self.pool.get(handle)
}
pub fn update<T: View, R>(
&mut self,
handle: Handle<T>,
f: impl FnOnce(&mut T, &mut ActionScope) -> R,
) -> Option<R> {
if handle.id == self.active_pod {
return None;
}
let target_ptr =
self.pool
.acquire_raw_mut(handle.id, Some(handle.generation), TypeId::of::<T>())?;
let prev_pod = self.active_pod;
let prev_skip = self.notify_skipped;
self.active_pod = handle.id;
self.notify_skipped = false;
let target_ref = unsafe { &mut *(target_ptr as *mut T) };
let res = f(target_ref, self);
let skipped = self.notify_skipped;
self.pool.release_borrow(handle.id);
if core::mem::size_of::<T>() > 0 && !skipped {
self.pool.mark_dirty(handle.id);
}
self.flush_signal_dirty_pods();
self.notify_skipped = prev_skip;
self.active_pod = prev_pod;
Some(res)
}
#[inline(always)]
pub const fn click_position(&self) -> (i16, i16) {
self.click_pos
}
#[inline(always)]
pub const fn drag_event(&self) -> DragEvent {
self.drag_event
}
#[inline(always)]
pub const fn now_ms(&self) -> u32 {
self.now_ms
}
#[inline(always)]
pub const fn modifiers(&self) -> super::events::KeyModifiers {
self.modifiers
}
pub(crate) fn acquire_view_mut_ptr(
&mut self,
id: PodId,
expected_gen: Option<u16>,
expected_type: TypeId,
) -> Option<*mut u8> {
self.pool.acquire_raw_mut(id, expected_gen, expected_type)
}
pub(crate) fn release_view_borrow(&mut self, id: PodId) {
self.pool.release_borrow(id);
}
}