1use core::any::TypeId;
4use core::cell::Cell;
5use core::marker::PhantomData;
6use core::ops::Deref;
7
8use crate::arena::{ScratchArena, StrRef};
9use crate::element::View;
10use crate::i18n::DynamicCatalog;
11use crate::i18n::{I18nArg, I18nContext, Locale, StaticCatalog, TextDirection};
12
13use super::events::{DragEvent, ImePreedit, SafeAreaInsets};
14use super::{CoreTheme, Handle, PodId, PodPool};
15
16#[inline(always)]
22pub const fn derive_scoped_id(parent_seed: u32, salt: u32, local_id: u32) -> u32 {
23 let mut h = parent_seed.wrapping_mul(0x9E37_79B9) ^ salt.wrapping_mul(0x85EB_CA6B);
24 h ^= local_id.wrapping_add(0xC2B2_AE35);
25 h ^= h >> 16;
26 h = h.wrapping_mul(0x7FEB_352D);
27 h ^= h >> 15;
28 h = h.wrapping_mul(0x846C_A68B);
29 h ^= h >> 16;
30 h | 0x8000_0000
31}
32
33pub struct FrameScope {
35 pub(crate) arena: ScratchArena,
36 pub(crate) theme: CoreTheme,
37 pub(crate) theme_override_ptr: Cell<*const CoreTheme>,
38 pub(crate) safe_area: SafeAreaInsets,
39 pub(crate) keyboard_inset: i16,
40 pub(crate) current_pod: PodId,
41 pub(crate) current_pod_gen: Option<u16>,
42 pub(crate) pool_ptr: *const PodPool,
43 pub(crate) now_ms: u32,
44 pub(crate) frame_requested: Cell<bool>,
45 pub(crate) id_stack: Cell<[u32; 8]>,
46 pub(crate) id_depth: Cell<u8>,
47 pub(crate) ime_preedit: ImePreedit,
48 pub(crate) i18n: I18nContext,
49 pub(crate) locale_override: Cell<Option<Locale>>,
50 pub(crate) catalog_override: Cell<Option<&'static StaticCatalog>>,
51}
52
53impl Default for FrameScope {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl FrameScope {
60
61 pub fn new() -> Self {
63 Self::with_theme(CoreTheme::dark())
64 }
65
66
67 pub fn with_theme(theme: CoreTheme) -> Self {
69 Self {
70 arena: ScratchArena::new(),
71 theme,
72 theme_override_ptr: Cell::new(core::ptr::null()),
73 safe_area: SafeAreaInsets::ZERO,
74 keyboard_inset: 0,
75 current_pod: PodId(0),
76 current_pod_gen: None,
77 pool_ptr: core::ptr::null(),
78 now_ms: 0,
79 frame_requested: Cell::new(false),
80 id_stack: Cell::new([0; 8]),
81 id_depth: Cell::new(0),
82 ime_preedit: ImePreedit::empty(),
83 i18n: I18nContext::new(Locale::EN_US),
84 locale_override: Cell::new(None),
85 catalog_override: Cell::new(None),
86 }
87 }
88
89 #[inline]
91 pub fn ime_preedit(&self) -> Option<&str> {
92 if self.ime_preedit.is_empty() {
93 None
94 } else {
95 Some(self.ime_preedit.as_str())
96 }
97 }
98
99 #[inline(always)]
101 pub const fn ime_preedit_state(&self) -> ImePreedit {
102 self.ime_preedit
103 }
104
105 #[inline(always)]
107 pub fn set_ime_preedit(&mut self, preedit: ImePreedit) {
108 self.ime_preedit = preedit;
109 }
110
111 #[inline(always)]
113 pub const fn safe_area(&self) -> SafeAreaInsets {
114 self.safe_area
115 }
116
117 #[inline(always)]
119 pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
120 self.safe_area = insets;
121 }
122
123 #[inline(always)]
125 pub const fn keyboard_inset(&self) -> i16 {
126 self.keyboard_inset
127 }
128
129 #[inline(always)]
131 pub fn set_keyboard_inset(&mut self, height: i16) {
132 self.keyboard_inset = height.max(0);
133 }
134
135 #[inline]
140 pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<super::PodReadGuard<'s, T>> {
141 if self.pool_ptr.is_null() || handle.id == self.current_pod {
142 return None;
143 }
144 unsafe {
145 let pool = &*self.pool_ptr;
146 let res = pool.read_guarded(handle);
147 if res.is_some() {
148 pool.record_cross_read(self.current_pod, handle.id);
149 }
150 res
151 }
152 }
153
154 #[inline]
156 pub fn read_with<T: View, R>(&self, handle: Handle<T>, f: impl FnOnce(&T) -> R) -> Option<R> {
157 let guard = self.read(handle)?;
158 Some(f(&*guard))
159 }
160
161 #[inline(always)]
163 pub fn arena(&self) -> &ScratchArena {
164 &self.arena
165 }
166
167 #[inline(always)]
169 pub fn arena_mut(&mut self) -> &mut ScratchArena {
170 self.theme_override_ptr.set(core::ptr::null());
171 self.locale_override.set(None);
172 self.catalog_override.set(None);
173 self.id_depth.set(0);
174 &mut self.arena
175 }
176
177 #[inline(always)]
179 pub fn locale(&self) -> Locale {
180 self.locale_override.get().unwrap_or(self.i18n.locale)
181 }
182
183 #[inline(always)]
185 pub fn text_direction(&self) -> TextDirection {
186 self.locale().text_direction()
187 }
188
189 #[inline(always)]
191 pub fn is_rtl(&self) -> bool {
192 self.locale().is_rtl()
193 }
194
195 #[inline(always)]
197 pub fn set_locale(&mut self, locale: Locale) {
198 self.i18n.locale = locale;
199 self.locale_override.set(None);
200 }
201
202 #[inline(always)]
204 pub fn override_locale(&self, locale: Locale) {
205 self.locale_override.set(Some(locale));
206 }
207
208 #[inline(always)]
210 pub fn set_i18n_catalog(&mut self, catalog: &'static StaticCatalog) {
211 self.i18n.static_catalog = Some(catalog);
212 self.catalog_override.set(None);
213 }
214
215 #[inline(always)]
217 pub fn override_i18n_catalog(&self, catalog: &'static StaticCatalog) {
218 self.catalog_override.set(Some(catalog));
219 }
220
221 #[inline]
223 pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<DynamicCatalog>) {
224 self.i18n.dynamic_catalog = Some(catalog);
225 }
226
227 #[inline]
228 fn resolve_i18n_template(&self, key: &str) -> Option<&str> {
229 let loc = self.locale();
230 if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
231 if let Some(v) = dyn_cat.lookup(loc, key) {
232 return Some(v);
233 }
234 }
235 if let Some(ov_cat) = self.catalog_override.get() {
236 if let Some(v) = ov_cat.lookup(loc, key) {
237 return Some(v);
238 }
239 }
240 if let Some(st_cat) = self.i18n.static_catalog {
241 if let Some(v) = st_cat.lookup(loc, key) {
242 return Some(v);
243 }
244 }
245 None
246 }
247
248 #[inline]
249 fn resolve_i18n_plural_template(&self, key: &str, count: i64) -> Option<&str> {
250 let loc = self.locale();
251 if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
252 if let Some(v) = dyn_cat.lookup_plural(loc, key, count) {
253 return Some(v);
254 }
255 }
256 if let Some(ov_cat) = self.catalog_override.get() {
257 if let Some(v) = ov_cat.lookup_plural(loc, key, count) {
258 return Some(v);
259 }
260 }
261 if let Some(st_cat) = self.i18n.static_catalog {
262 if let Some(v) = st_cat.lookup_plural(loc, key, count) {
263 return Some(v);
264 }
265 }
266 None
267 }
268
269 #[inline]
271 pub fn t<'a>(&'a self, key: &str) -> StrRef<'a> {
272 let loc = self.locale();
273 if let Some(dyn_cat) = &self.i18n.dynamic_catalog {
274 if let Some(v) = dyn_cat.lookup(loc, key) {
275 return self.arena.alloc_str(v);
276 }
277 }
278 if let Some(ov_cat) = self.catalog_override.get() {
279 if let Some(v) = ov_cat.lookup(loc, key) {
280 return StrRef::from(v);
281 }
282 }
283 if let Some(st_cat) = self.i18n.static_catalog {
284 if let Some(v) = st_cat.lookup(loc, key) {
285 return StrRef::from(v);
286 }
287 }
288 self.arena.alloc_str(key)
289 }
290
291 #[inline]
293 pub fn t_or<'a>(&'a self, key: &str, fallback: &'a str) -> StrRef<'a> {
294 if let Some(v) = self.resolve_i18n_template(key) {
295 self.arena.alloc_str(v)
296 } else {
297 StrRef::from(fallback)
298 }
299 }
300
301 #[inline]
303 pub fn t_args<'a>(&'a self, key: &str, args: &[(&str, I18nArg<'_>)]) -> StrRef<'a> {
304 let tmpl = self.resolve_i18n_template(key).unwrap_or(key);
305 crate::i18n::format_template(&self.arena, tmpl, args)
306 }
307
308 #[inline]
310 pub fn t_plural<'a>(&'a self, key: &str, count: i64) -> StrRef<'a> {
311 let tmpl = self.resolve_i18n_plural_template(key, count).unwrap_or(key);
312 crate::i18n::format_template(&self.arena, tmpl, &[("count", I18nArg::Int(count))])
313 }
314
315 #[inline]
319 pub fn push_id(&self, seed: u32) {
320 let depth = self.id_depth.get() as usize;
321 let mut stack = self.id_stack.get();
322 let parent = if depth == 0 {
323 self.current_pod.0 as u32
324 } else {
325 stack[(depth - 1).min(7)]
326 };
327 let combined = derive_scoped_id(parent, 0x5343_4F50, seed);
328 if depth < 8 {
329 stack[depth] = combined;
330 self.id_stack.set(stack);
331 self.id_depth.set((depth + 1) as u8);
332 }
333 }
334
335 #[inline]
337 pub fn pop_id(&self) {
338 let depth = self.id_depth.get();
339 if depth > 0 {
340 self.id_depth.set(depth - 1);
341 }
342 }
343
344 #[inline]
346 pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
347 self.push_id(seed);
348 let res = f(self);
349 self.pop_id();
350 res
351 }
352
353 #[inline]
355 pub fn scoped_id(&self, local_id: u32) -> u32 {
356 let depth = self.id_depth.get() as usize;
357 let seed = if depth == 0 {
358 self.current_pod.0 as u32
359 } else {
360 self.id_stack.get()[(depth - 1).min(7)]
361 };
362 derive_scoped_id(seed, 0x4C4F_434C, local_id)
363 }
364
365 #[inline(always)]
367 pub fn theme(&self) -> &CoreTheme {
368 let ptr = self.theme_override_ptr.get();
369 if !ptr.is_null() {
370 unsafe { &*ptr }
371 } else {
372 &self.theme
373 }
374 }
375
376 #[inline(always)]
378 pub fn set_theme(&mut self, theme: CoreTheme) {
379 self.theme = theme;
380 self.theme_override_ptr.set(core::ptr::null());
381 }
382
383 #[inline]
385 pub fn override_theme(&self, theme: CoreTheme) {
386 if self.arena.can_alloc_slice::<CoreTheme>(1) {
387 let alloc_ref: &CoreTheme = self.arena.alloc(theme);
388 self.theme_override_ptr.set(alloc_ref as *const CoreTheme);
389 }
390 }
391
392 #[inline(always)]
394 pub fn current_pod(&self) -> PodId {
395 self.current_pod
396 }
397
398 #[inline(always)]
402 pub const fn now_ms(&self) -> u32 {
403 self.now_ms
404 }
405
406 #[inline(always)]
408 pub fn set_now_ms(&mut self, now_ms: u32) {
409 self.now_ms = now_ms;
410 }
411
412 #[inline(always)]
414 pub fn request_frame(&self) {
415 self.frame_requested.set(true);
416 }
417
418 #[inline(always)]
420 pub fn keep_animating(&self, running: bool) -> bool {
421 if running {
422 self.frame_requested.set(true);
423 }
424 running
425 }
426
427 #[inline(always)]
429 pub fn is_frame_requested(&self) -> bool {
430 self.frame_requested.get()
431 }
432}
433
434#[repr(transparent)]
439pub struct Scope<V> {
440 pub(crate) frame: FrameScope,
441 _marker: PhantomData<V>,
442}
443
444impl<V> Default for Scope<V> {
445 fn default() -> Self {
446 Self::new()
447 }
448}
449
450impl<V> Scope<V> {
451 pub fn new() -> Self {
453 Self {
454 frame: FrameScope::new(),
455 _marker: PhantomData,
456 }
457 }
458
459 #[inline(always)]
461 pub fn set_current_pod(&mut self, id: PodId) {
462 self.frame.current_pod = id;
463 }
464
465 #[inline(always)]
467 pub fn theme(&self) -> &CoreTheme {
468 self.frame.theme()
469 }
470
471 #[inline(always)]
473 pub fn arena(&self) -> &ScratchArena {
474 self.frame.arena()
475 }
476
477 #[inline]
479 pub fn with_id<'a, R>(&'a self, seed: u32, f: impl FnOnce(&'a Self) -> R) -> R {
480 self.frame.push_id(seed);
481 let res = f(self);
482 self.frame.pop_id();
483 res
484 }
485}
486
487impl<V: View> Scope<V> {
488 pub fn listener<'a, E, F>(&'a self, handler: F) -> &'a dyn Fn(E, &mut ActionScope)
493 where
494 E: 'a,
495 F: Fn(&mut V, E, &mut ActionScope) + 'a,
496 {
497 let pod_id = self.frame.current_pod;
498 let pod_gen = self.frame.current_pod_gen;
499 self.frame.arena.alloc(move |event: E, acx: &mut ActionScope| {
500 let prev_pod = acx.active_pod;
501 let prev_skip = acx.notify_skipped;
502 acx.active_pod = pod_id;
503 acx.notify_skipped = false;
504 if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
505 let view_ref = unsafe { &mut *(view_ptr as *mut V) };
506 handler(view_ref, event, acx);
507 acx.release_view_borrow(pod_id);
508 if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
509 acx.notify();
510 }
511 }
512 acx.flush_signal_dirty_pods();
513 acx.notify_skipped = prev_skip;
514 acx.active_pod = prev_pod;
515 })
516 }
517
518 pub fn action<'a, F>(&'a self, handler: F) -> &'a dyn Fn(&mut ActionScope)
522 where
523 F: Fn(&mut V, &mut ActionScope) + 'a,
524 {
525 let pod_id = self.frame.current_pod;
526 let pod_gen = self.frame.current_pod_gen;
527 self.frame.arena.alloc(move |acx: &mut ActionScope| {
528 let prev_pod = acx.active_pod;
529 let prev_skip = acx.notify_skipped;
530 acx.active_pod = pod_id;
531 acx.notify_skipped = false;
532 if let Some(view_ptr) = acx.acquire_view_mut_ptr(pod_id, pod_gen, TypeId::of::<V>()) {
533 let view_ref = unsafe { &mut *(view_ptr as *mut V) };
534 handler(view_ref, acx);
535 acx.release_view_borrow(pod_id);
536 if core::mem::size_of::<V>() > 0 && !acx.notify_skipped {
537 acx.notify();
538 }
539 }
540 acx.flush_signal_dirty_pods();
541 acx.notify_skipped = prev_skip;
542 acx.active_pod = prev_pod;
543 })
544 }
545}
546
547impl<V> Deref for Scope<V> {
548 type Target = FrameScope;
549 #[inline(always)]
550 fn deref(&self) -> &Self::Target {
551 &self.frame
552 }
553}
554
555pub struct ActionScope<'p> {
557 pub(crate) active_pod: PodId,
558 pub(crate) pool: &'p mut PodPool,
559 pub(crate) click_pos: (i16, i16),
560 pub(crate) drag_event: DragEvent,
561 pub(crate) propagation_stopped: bool,
562 pub(crate) notify_skipped: bool,
563 pub(crate) now_ms: u32,
564 pub(crate) modifiers: super::events::KeyModifiers,
565 pub(crate) async_app: Option<crate::async_rt::AsyncApp>,
566}
567
568impl<'p> ActionScope<'p> {
569 #[inline(always)]
570 pub(crate) fn new(
571 active_pod: PodId,
572 pool: &'p mut PodPool,
573 click_pos: (i16, i16),
574 drag_event: DragEvent,
575 now_ms: u32,
576 ) -> Self {
577 Self {
578 active_pod,
579 pool,
580 click_pos,
581 drag_event,
582 propagation_stopped: false,
583 notify_skipped: false,
584 now_ms,
585 modifiers: super::events::KeyModifiers::NONE,
586 async_app: None,
587 }
588 }
589
590 #[inline(always)]
591 pub(crate) fn with_async_app(mut self, app: crate::async_rt::AsyncApp) -> Self {
592 self.async_app = Some(app);
593 self
594 }
595
596 #[inline(always)]
597 pub(crate) fn with_modifiers(mut self, modifiers: super::events::KeyModifiers) -> Self {
598 self.modifiers = modifiers;
599 self
600 }
601
602 #[inline]
604 pub fn handle<V: View>(&self) -> Option<Handle<V>> {
605 let generation = self
606 .pool
607 .current_generation_for_type(self.active_pod, TypeId::of::<V>())?;
608 Some(Handle::with_generation(self.active_pod, generation))
609 }
610
611 pub fn spawn<V, T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
615 where
616 V: View,
617 T: 'static,
618 F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
619 Fut: core::future::Future<Output = T> + 'static,
620 {
621 let handle = self
622 .handle::<V>()
623 .expect("ActionScope::spawn::<V> 类型与当前活跃视图不匹配");
624 let app = self
625 .async_app
626 .clone()
627 .expect("ActionScope 未绑定 ForegroundExecutor");
628 app.spawn_for(handle, f)
629 }
630
631 pub fn spawn_app<T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
633 where
634 T: 'static,
635 F: FnOnce(crate::async_rt::AsyncApp) -> Fut,
636 Fut: core::future::Future<Output = T> + 'static,
637 {
638 let app = self
639 .async_app
640 .clone()
641 .expect("ActionScope 未绑定 ForegroundExecutor");
642 app.spawn(f)
643 }
644
645 #[inline]
647 pub fn background_executor(&self) -> crate::async_rt::BackgroundExecutor {
648 self.async_app
649 .as_ref()
650 .map(|app| app.background_executor())
651 .unwrap_or_else(crate::async_rt::BackgroundExecutor::new)
652 }
653
654 #[inline]
656 pub fn background_spawn<T, Fut>(&self, fut: Fut) -> crate::async_rt::Task<T>
657 where
658 T: Send + 'static,
659 Fut: core::future::Future<Output = T> + Send + 'static,
660 {
661 self.background_executor().spawn(fut)
662 }
663
664 #[inline]
666 pub fn timer(&self, duration: core::time::Duration) -> crate::async_rt::Timer {
667 self.background_executor().timer(duration)
668 }
669
670 #[inline]
672 pub fn defer<F>(&mut self, f: F)
673 where
674 F: FnOnce(&mut ActionScope) + 'static,
675 {
676 if let Some(app) = &self.async_app {
677 app.defer(f);
678 }
679 }
680
681 pub fn defer_self<V, F>(&mut self, f: F)
683 where
684 V: View,
685 F: FnOnce(&mut V, &mut ActionScope) + 'static,
686 {
687 let Some(handle) = self.handle::<V>() else {
688 return;
689 };
690 if let Some(app) = &self.async_app {
691 app.defer(move |acx| {
692 let _ = acx.update(handle, f);
693 });
694 }
695 }
696
697 #[inline]
699 pub fn notify(&mut self) {
700 self.notify_skipped = false;
701 self.pool.mark_dirty(self.active_pod);
702 }
703
704 #[inline(always)]
706 pub fn skip_notify(&mut self) {
707 self.notify_skipped = true;
708 }
709
710 #[inline]
712 pub fn flush_signal_dirty_pods(&mut self) {
713 self.pool.flush_signal_dirty_pods();
714 }
715
716 #[inline(always)]
718 pub fn stop_propagation(&mut self) {
719 self.propagation_stopped = true;
720 }
721
722 #[inline(always)]
724 pub const fn is_propagation_stopped(&self) -> bool {
725 self.propagation_stopped
726 }
727
728 #[inline]
730 pub fn notify_handle<T: View>(&mut self, handle: Handle<T>) {
731 if self.pool.get(handle).is_some() {
732 self.pool.mark_dirty(handle.id);
733 }
734 }
735
736 #[inline]
738 pub fn read<'s, T: View>(&'s self, handle: Handle<T>) -> Option<&'s T> {
739 if handle.id == self.active_pod {
740 return None;
741 }
742 self.pool.get(handle)
743 }
744
745 pub fn update<T: View, R>(
748 &mut self,
749 handle: Handle<T>,
750 f: impl FnOnce(&mut T, &mut ActionScope) -> R,
751 ) -> Option<R> {
752 if handle.id == self.active_pod {
753 return None;
754 }
755 let target_ptr =
756 self.pool
757 .acquire_raw_mut(handle.id, Some(handle.generation), TypeId::of::<T>())?;
758 let prev_pod = self.active_pod;
759 let prev_skip = self.notify_skipped;
760 self.active_pod = handle.id;
761 self.notify_skipped = false;
762 let target_ref = unsafe { &mut *(target_ptr as *mut T) };
763 let res = f(target_ref, self);
764 let skipped = self.notify_skipped;
765 self.pool.release_borrow(handle.id);
766 if core::mem::size_of::<T>() > 0 && !skipped {
767 self.pool.mark_dirty(handle.id);
768 }
769 self.flush_signal_dirty_pods();
770 self.notify_skipped = prev_skip;
771 self.active_pod = prev_pod;
772 Some(res)
773 }
774
775 #[inline(always)]
777 pub const fn click_position(&self) -> (i16, i16) {
778 self.click_pos
779 }
780
781 #[inline(always)]
783 pub const fn drag_event(&self) -> DragEvent {
784 self.drag_event
785 }
786
787 #[inline(always)]
789 pub const fn now_ms(&self) -> u32 {
790 self.now_ms
791 }
792
793 #[inline(always)]
795 pub const fn modifiers(&self) -> super::events::KeyModifiers {
796 self.modifiers
797 }
798
799 pub(crate) fn acquire_view_mut_ptr(
800 &mut self,
801 id: PodId,
802 expected_gen: Option<u16>,
803 expected_type: TypeId,
804 ) -> Option<*mut u8> {
805 self.pool.acquire_raw_mut(id, expected_gen, expected_type)
806 }
807
808 pub(crate) fn release_view_borrow(&mut self, id: PodId) {
809 self.pool.release_borrow(id);
810 }
811}