1mod frame;
10mod keyboard;
11mod pointer;
12
13use crate::arena::SmallVec;
14use crate::damage::DamageTracker;
15use crate::element::View;
16use crate::motion::{DrawOp, DrawOpSnapshot, MotionCache};
17use crate::pod::{
18 ActionScope, CoreTheme, DragEvent, FrameScope, Handle, ImePreedit, KeyModifiers, PodId,
19 PodPool, PointerKind, SafeAreaInsets,
20};
21use crate::renderers::software::precompute_occlusion_clips;
22use crate::solver::{HitRegion, InteractionState, LayoutNode, Region};
23
24pub const MAX_DRAW_OPS: usize = 128;
26
27pub const MAX_HIT_REGIONS: usize = 64;
29
30#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct GestureConfig {
33 pub drag_slop_px: i16,
35 pub swipe_threshold_px: i16,
37 pub edge_back_width_px: i16,
39 pub long_press_ms: u16,
41 pub repeat_delay_ms: u16,
43 pub repeat_interval_ms: u16,
45 pub mouse_drag_scroll: bool,
51}
52
53impl GestureConfig {
54 #[inline(always)]
56 pub const fn const_default() -> Self {
57 Self {
58 drag_slop_px: 8,
59 swipe_threshold_px: 16,
60 edge_back_width_px: 24,
61 long_press_ms: 500,
62 repeat_delay_ms: 400,
63 repeat_interval_ms: 100,
64 mouse_drag_scroll: false,
65 }
66 }
67}
68
69impl Default for GestureConfig {
70 #[inline(always)]
71 fn default() -> Self {
72 Self::const_default()
73 }
74}
75
76pub struct VeloxEngine {
78 pool: PodPool,
79 frame_scope: FrameScope,
80 async_rt: crate::async_rt::ForegroundExecutor,
81 motion: MotionCache,
82 damage: DamageTracker,
83 prev_snapshots: SmallVec<DrawOpSnapshot, MAX_DRAW_OPS>,
84 cached_ops_buf: std::vec::Vec<DrawOp<'static>>,
85 cached_hits_buf: std::vec::Vec<HitRegion<'static>>,
86 cached_ops_ptr: *const DrawOp<'static>,
87 cached_ops_len: u32,
88 cached_hits_ptr: *const HitRegion<'static>,
89 cached_hits_len: u32,
90 cached_layout_ptr: *mut LayoutNode<'static, 'static>,
91 tree_cursor_mark: u32,
92 tree_temp_mark: u32,
93 ops_cursor_mark: u32,
94 frame_cached: bool,
95 partial_relayout_count: u16,
96 solve_count: u32,
97 fast_paint_count: u32,
98 dropped_draw_ops: u32,
99 viewport: Region,
100 dpi_scale: i16,
101 scale_factor: f32,
102 gesture_config: GestureConfig,
103 root_pod: Option<PodId>,
104 interaction: InteractionState,
105 pressed_hit_id: u32,
106 press_start_x: i16,
107 press_start_y: i16,
108 press_hold_ms: u16,
109 repeat_accum_ms: u16,
110 last_drag_vy: i16,
111 last_arena_used_bytes: u32,
112 modifiers: KeyModifiers,
113 active_pointer_kind: PointerKind,
114 ime_preedit: ImePreedit,
115 ime_enabled: bool,
116 first_frame: bool,
117 interaction_dirty: bool,
118 has_pressed_hit: bool,
119 drag_fired_on_down: bool,
120 long_press_fired: bool,
121 long_press_handled: bool,
122}
123
124impl VeloxEngine {
125
126 pub fn new(width: i16, height: i16) -> Self {
128 Self {
129 pool: PodPool::new(),
130 frame_scope: FrameScope::new(),
131 async_rt: crate::async_rt::ForegroundExecutor::new(),
132 motion: MotionCache::new(),
133 damage: DamageTracker::new(),
134 prev_snapshots: SmallVec::new(),
135 cached_ops_buf: std::vec::Vec::new(),
136 cached_hits_buf: std::vec::Vec::new(),
137 cached_ops_ptr: core::ptr::null(),
138 cached_ops_len: 0,
139 cached_hits_ptr: core::ptr::null(),
140 cached_hits_len: 0,
141 cached_layout_ptr: core::ptr::null_mut(),
142 tree_cursor_mark: 0,
143 tree_temp_mark: 0,
144 ops_cursor_mark: 0,
145 frame_cached: false,
146 solve_count: 0,
147 partial_relayout_count: 0,
148 fast_paint_count: 0,
149 dropped_draw_ops: 0,
150 viewport: Region::new(0, 0, width, height),
151 dpi_scale: 1,
152 scale_factor: 1.0,
153 gesture_config: GestureConfig::const_default(),
154 root_pod: None,
155 interaction: InteractionState::const_default(),
156 pressed_hit_id: 0,
157 press_start_x: 0,
158 press_start_y: 0,
159 press_hold_ms: 0,
160 repeat_accum_ms: 0,
161 last_drag_vy: 0,
162 last_arena_used_bytes: 0,
163 modifiers: KeyModifiers::NONE,
164 active_pointer_kind: PointerKind::Touch,
165 ime_preedit: ImePreedit::empty(),
166 ime_enabled: false,
167 first_frame: true,
168 interaction_dirty: false,
169 has_pressed_hit: false,
170 drag_fired_on_down: false,
171 long_press_fired: false,
172 long_press_handled: false,
173 }
174 }
175
176 #[inline]
178 pub fn init_at(slot: &mut core::mem::MaybeUninit<Self>, width: i16, height: i16) -> &mut Self {
179 slot.write(Self::new(width, height))
180 }
181
182 #[inline]
184 pub fn try_insert_view<V: View>(&mut self, view: V) -> Option<Handle<V>> {
185 let handle = self.pool.try_insert(view)?;
186 self.invalidate_frame_cache();
187 Some(handle)
188 }
189
190 #[inline(always)]
191 pub(super) fn invalidate_frame_cache(&mut self) {
192 self.frame_cached = false;
193 self.cached_ops_ptr = core::ptr::null();
194 self.cached_ops_len = 0;
195 self.cached_hits_ptr = core::ptr::null();
196 self.cached_hits_len = 0;
197 {
198 self.cached_ops_buf.clear();
199 self.cached_hits_buf.clear();
200 }
201 }
202
203 #[inline(always)]
204 pub(super) fn resolve_hit_pod(root_id: PodId, hit_owner: u16) -> PodId {
205 if hit_owner == u16::MAX {
206 root_id
207 } else {
208 PodId(hit_owner)
209 }
210 }
211
212 #[inline]
213 pub(super) fn make_action_scope(
214 &mut self,
215 owner: PodId,
216 click_pos: (i16, i16),
217 drag_ev: DragEvent,
218 ) -> ActionScope<'_> {
219 let acx = ActionScope::new(
220 owner,
221 &mut self.pool,
222 click_pos,
223 drag_ev,
224 self.frame_scope.now_ms,
225 );
226 let acx = acx.with_async_app(self.async_rt.async_app());
227 acx
228 }
229
230 #[inline]
233 pub(super) fn flush_async_after_event(&mut self) {
234 if self.async_rt.has_work_to_poll() {
235 let _ = self.poll_async_tasks();
236 }
237 }
238
239 #[allow(clippy::too_many_arguments)]
240 pub(super) fn cache_ops_and_hits_into<'a>(
241 arena: &crate::arena::ScratchArena,
242 ops: &mut [DrawOp<'a>],
243 hits: &[HitRegion<'a>],
244 cached_ops_buf: &mut std::vec::Vec<DrawOp<'static>>,
245 cached_hits_buf: &mut std::vec::Vec<HitRegion<'static>>,
246 cached_ops_ptr: &mut *const DrawOp<'static>,
247 cached_ops_len: &mut u32,
248 cached_hits_ptr: &mut *const HitRegion<'static>,
249 cached_hits_len: &mut u32,
250 _dropped_draw_ops: &mut u32,
251 frame_cached: &mut bool,
252 last_arena_used_bytes: &mut u32,
253 ) {
254 precompute_occlusion_clips(ops);
255 {
256 cached_ops_buf.clear();
257 let static_ops: &[DrawOp<'static>] = unsafe {
261 core::slice::from_raw_parts(ops.as_ptr() as *const DrawOp<'static>, ops.len())
262 };
263 cached_ops_buf.extend_from_slice(static_ops);
264 *cached_ops_ptr = cached_ops_buf.as_ptr();
265 *cached_ops_len = cached_ops_buf.len() as u32;
266
267 cached_hits_buf.clear();
268 let static_hits: &[HitRegion<'static>] = unsafe {
269 core::slice::from_raw_parts(hits.as_ptr() as *const HitRegion<'static>, hits.len())
270 };
271 cached_hits_buf.extend_from_slice(static_hits);
272 *cached_hits_ptr = cached_hits_buf.as_ptr();
273 *cached_hits_len = cached_hits_buf.len() as u32;
274 *frame_cached = true;
275 *last_arena_used_bytes = arena.used_bytes() as u32;
276 }
277 }
278
279 #[inline(always)]
280 pub(super) fn invalidate_layout_cache(&mut self) {
281 self.invalidate_frame_cache();
282 self.cached_layout_ptr = core::ptr::null_mut();
283 self.tree_cursor_mark = 0;
284 self.tree_temp_mark = 0;
285 self.ops_cursor_mark = 0;
286 }
287
288 #[inline(always)]
290 pub const fn modifiers(&self) -> KeyModifiers {
291 self.modifiers
292 }
293
294 #[inline(always)]
296 pub fn set_modifiers(&mut self, modifiers: KeyModifiers) {
297 self.modifiers = modifiers;
298 }
299
300 #[inline(always)]
302 pub const fn gesture_config(&self) -> GestureConfig {
303 self.gesture_config
304 }
305
306 #[inline(always)]
308 pub fn set_gesture_config(&mut self, config: GestureConfig) {
309 self.gesture_config = config;
310 }
311
312 #[inline(always)]
314 pub const fn pointer_kind(&self) -> PointerKind {
315 self.active_pointer_kind
316 }
317
318 #[inline(always)]
320 pub fn set_pointer_kind(&mut self, kind: PointerKind) {
321 self.active_pointer_kind = kind;
322 }
323
324 #[inline(always)]
326 pub(super) const fn allows_drag_scroll(&self) -> bool {
327 matches!(self.active_pointer_kind, PointerKind::Touch)
328 || self.gesture_config.mouse_drag_scroll
329 }
330
331 #[inline(always)]
333 pub const fn dropped_draw_ops_count(&self) -> u32 {
334 self.dropped_draw_ops
335 }
336
337 #[inline(always)]
339 pub const fn layout_solve_count(&self) -> u32 {
340 self.solve_count
341 }
342
343 #[inline(always)]
345 pub const fn partial_relayout_count(&self) -> u32 {
346 self.partial_relayout_count as u32
347 }
348
349 #[inline(always)]
351 pub fn relayout_boundary_hits(&self) -> u32 {
352 self.pool.relayout_boundary_hits()
353 }
354
355 #[inline(always)]
357 pub const fn fast_paint_pass_count(&self) -> u32 {
358 self.fast_paint_count
359 }
360
361 #[inline(always)]
363 pub fn subview_cache_hits(&self) -> u32 {
364 self.pool.skipped_render_count()
365 }
366
367 #[inline(always)]
369 pub fn pod_render_count<V: View>(&self, handle: Handle<V>) -> u32 {
370 self.pool.render_count(handle.pod_id())
371 }
372
373 #[inline(always)]
376 pub fn set_dpi_scale(&mut self, scale: i16) {
377 let s = scale.max(1);
378 self.dpi_scale = s;
379 self.scale_factor = s as f32;
380 }
381
382 #[inline(always)]
384 pub fn set_scale_factor(&mut self, scale_factor: f32) {
385 let sf = scale_factor.clamp(0.5, 4.0);
386 self.scale_factor = sf;
387 self.dpi_scale = ((sf + 0.5) as i16).max(1);
388 }
389
390 #[inline(always)]
392 pub const fn dpi_scale(&self) -> i16 {
393 self.dpi_scale
394 }
395
396 #[inline(always)]
398 pub const fn scale_factor(&self) -> f32 {
399 self.scale_factor
400 }
401
402 #[inline(always)]
404 pub const fn viewport_region(&self) -> Region {
405 self.viewport
406 }
407
408 pub fn resize(&mut self, width: i16, height: i16) {
410 let new_vp = Region::new(0, 0, width, height);
411 if new_vp != self.viewport {
412 self.viewport = new_vp;
413 self.first_frame = true;
414 self.invalidate_layout_cache();
415 self.pool.mark_all_dirty();
416 }
417 }
418
419 #[inline(always)]
421 pub fn theme(&self) -> CoreTheme {
422 *self.frame_scope.theme()
423 }
424
425 pub fn set_theme(&mut self, theme: CoreTheme) {
427 self.frame_scope.set_theme(theme);
428 self.invalidate_layout_cache();
429 self.pool.mark_all_dirty();
430 }
431
432 #[inline(always)]
434 pub fn locale(&self) -> crate::i18n::Locale {
435 self.frame_scope.locale()
436 }
437
438 pub fn set_locale(&mut self, locale: crate::i18n::Locale) {
440 if self.frame_scope.locale() != locale {
441 self.frame_scope.set_locale(locale);
442 self.first_frame = true;
443 self.invalidate_layout_cache();
444 self.pool.mark_all_dirty();
445 }
446 }
447
448 pub fn set_i18n_catalog(&mut self, catalog: &'static crate::i18n::StaticCatalog) {
450 self.frame_scope.set_i18n_catalog(catalog);
451 self.first_frame = true;
452 self.invalidate_layout_cache();
453 self.pool.mark_all_dirty();
454 }
455
456 pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<crate::i18n::DynamicCatalog>) {
458 self.frame_scope.set_dynamic_catalog(catalog);
459 self.first_frame = true;
460 self.invalidate_layout_cache();
461 self.pool.mark_all_dirty();
462 }
463
464 #[inline(always)]
466 pub const fn safe_area(&self) -> SafeAreaInsets {
467 self.frame_scope.safe_area()
468 }
469
470 pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
472 if self.frame_scope.safe_area() != insets {
473 self.frame_scope.set_safe_area(insets);
474 self.first_frame = true;
475 self.invalidate_layout_cache();
476 self.pool.mark_all_dirty();
477 }
478 }
479
480 #[inline(always)]
482 pub const fn keyboard_inset(&self) -> i16 {
483 self.frame_scope.keyboard_inset()
484 }
485
486 pub fn set_keyboard_inset(&mut self, height: i16) {
488 let clamped = height.max(0);
489 if self.frame_scope.keyboard_inset() != clamped {
490 self.frame_scope.set_keyboard_inset(clamped);
491 self.first_frame = true;
492 self.invalidate_layout_cache();
493 self.pool.mark_all_dirty();
494 }
495 }
496
497 pub fn mount_root<V: View>(&mut self, view: V) -> Handle<V> {
499 let handle = self.pool.insert(view);
500 self.root_pod = Some(handle.pod_id());
501 self.pool.set_cached_bounds(handle.pod_id(), self.viewport);
502 self.first_frame = true;
503 self.invalidate_layout_cache();
504 handle
505 }
506
507 pub fn insert_view<V: View>(&mut self, view: V) -> Handle<V> {
509 self.pool.insert(view)
510 }
511
512 pub fn remove_view<V: View>(&mut self, handle: Handle<V>) -> bool {
514 let removed = self.pool.remove(handle);
515 if removed {
516 if self.root_pod == Some(handle.pod_id()) {
517 self.root_pod = None;
518 }
519 self.invalidate_layout_cache();
520 if let Some(root) = self.root_pod {
521 self.pool.mark_dirty(root);
522 }
523 }
524 removed
525 }
526
527 pub fn view_mut<V: View>(&mut self, handle: Handle<V>) -> Option<&mut V> {
529 self.pool.mark_dirty(handle.pod_id());
530 self.pool.get_mut(handle)
531 }
532
533 pub fn update_view<V: View, R>(&mut self, handle: Handle<V>, f: impl FnOnce(&mut V) -> R) -> Option<R> {
535 self.pool.update(handle, f)
536 }
537
538 pub fn view<V: View>(&self, handle: Handle<V>) -> Option<&V> {
540 self.pool.get(handle)
541 }
542
543 #[inline(always)]
545 pub fn motion_mut(&mut self) -> &mut MotionCache {
546 self.interaction_dirty = true;
547 &mut self.motion
548 }
549
550 #[inline(always)]
552 pub const fn last_arena_used_bytes(&self) -> usize {
553 self.last_arena_used_bytes as usize
554 }
555
556 #[inline(always)]
558 pub fn last_damage(&self) -> &[Region] {
559 self.damage.regions()
560 }
561
562 #[inline(always)]
564 pub const fn focused_index(&self) -> Option<u16> {
565 self.interaction.focused_index
566 }
567
568 #[inline(always)]
570 pub const fn is_focus_visible(&self) -> bool {
571 self.interaction.focus_visible
572 }
573
574 #[inline(always)]
576 pub fn set_focused_index(&mut self, idx: Option<u16>) {
577 if self.interaction.focused_index != idx {
578 self.interaction.focused_index = idx;
579 if idx.is_none() {
580 self.interaction.focus_visible = false;
581 }
582 self.interaction_dirty = true;
583 }
584 }
585
586 #[inline]
588 pub fn needs_redraw(&self) -> bool {
589 if self.async_rt.has_ready_work() {
590 return true;
591 }
592 self.first_frame
593 || self.interaction_dirty
594 || self.frame_scope.frame_requested.get()
595 || self.pool.has_dirty()
596 || crate::signal::has_pending_dirty_pods()
597 || self.motion.has_active_animations()
598 }
599
600 #[inline(always)]
602 pub const fn clock_ms(&self) -> u32 {
603 self.frame_scope.now_ms
604 }
605
606 pub fn with_scheduler(
608 self,
609 backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
610 ) -> Self {
611 self.async_rt.set_backend(backend);
612 self
613 }
614
615 pub fn set_scheduler(
617 &mut self,
618 backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
619 ) {
620 self.async_rt.set_backend(backend);
621 }
622
623 #[inline]
625 pub fn scheduler_name(&self) -> &'static str {
626 self.async_rt.scheduler_name()
627 }
628
629 #[inline]
631 pub fn scheduler_capabilities(&self) -> crate::async_rt::SchedulerCapabilities {
632 self.async_rt.scheduler_capabilities()
633 }
634
635 pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
637 self.async_rt.set_wake_ui(waker);
638 }
639
640 pub fn poll_async_tasks(&mut self) -> bool {
642 self.async_rt
643 .poll_ready(&mut self.pool, self.frame_scope.now_ms)
644 }
645
646 #[inline]
648 pub fn has_pending_async_tasks(&self) -> bool {
649 self.async_rt.has_ready_work()
650 }
651
652 #[inline]
654 pub fn active_async_task_count(&self) -> usize {
655 self.async_rt.active_task_count()
656 }
657
658 pub fn spawn<T, F, Fut>(&mut self, f: F) -> crate::async_rt::Task<T>
660 where
661 T: 'static,
662 F: FnOnce(crate::async_rt::AsyncApp) -> Fut,
663 Fut: core::future::Future<Output = T> + 'static,
664 {
665 self.async_rt.spawn(f)
666 }
667
668 pub fn spawn_for<V, T, F, Fut>(
670 &mut self,
671 handle: Handle<V>,
672 f: F,
673 ) -> crate::async_rt::Task<T>
674 where
675 V: View,
676 T: 'static,
677 F: FnOnce(Handle<V>, crate::async_rt::AsyncApp) -> Fut,
678 Fut: core::future::Future<Output = T> + 'static,
679 {
680 self.async_rt.async_app().spawn_for(handle, f)
681 }
682
683 #[inline]
685 pub fn background_spawn<T, Fut>(&self, fut: Fut) -> crate::async_rt::Task<T>
686 where
687 T: Send + 'static,
688 Fut: core::future::Future<Output = T> + Send + 'static,
689 {
690 self.background_executor().spawn(fut)
691 }
692
693 #[inline]
695 pub fn background_executor(&self) -> crate::async_rt::BackgroundExecutor {
696 self.async_rt.background_executor()
697 }
698
699 #[inline]
701 pub fn timer(&self, duration: core::time::Duration) -> crate::async_rt::Timer {
702 self.background_executor().timer(duration)
703 }
704
705 #[inline]
707 pub fn defer<F>(&mut self, f: F)
708 where
709 F: FnOnce(&mut ActionScope) + 'static,
710 {
711 self.async_rt.defer(f);
712 }
713
714 pub fn finish_animations(&mut self) {
716 self.motion.finish_all();
717 self.invalidate_frame_cache();
718 if let Some(root) = self.root_pod {
719 self.pool.mark_dirty(root);
720 }
721 }
722
723}
724
725impl HitRegion<'_> {
726 #[inline(always)]
727 const fn active_bg_or_focus(&self) -> bool {
728 self.has_active_bg || self.focus_index.is_some() || self.scroll_target.is_some()
729 }
730}