mod frame;
mod keyboard;
mod pointer;
use crate::arena::SmallVec;
use crate::damage::DamageTracker;
use crate::element::View;
use crate::motion::{DrawOp, DrawOpSnapshot, MotionCache};
use crate::pod::{
ActionScope, CoreTheme, DragEvent, FrameScope, Handle, ImePreedit, KeyModifiers, PodId,
PodPool, PointerKind, SafeAreaInsets,
};
use crate::renderers::software::precompute_occlusion_clips;
use crate::solver::{HitRegion, InteractionState, LayoutNode, Region};
pub const MAX_DRAW_OPS: usize = 128;
pub const MAX_HIT_REGIONS: usize = 64;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct GestureConfig {
pub drag_slop_px: i16,
pub swipe_threshold_px: i16,
pub edge_back_width_px: i16,
pub long_press_ms: u16,
pub repeat_delay_ms: u16,
pub repeat_interval_ms: u16,
pub mouse_drag_scroll: bool,
}
impl GestureConfig {
#[inline(always)]
pub const fn const_default() -> Self {
Self {
drag_slop_px: 8,
swipe_threshold_px: 16,
edge_back_width_px: 24,
long_press_ms: 500,
repeat_delay_ms: 400,
repeat_interval_ms: 100,
mouse_drag_scroll: false,
}
}
}
impl Default for GestureConfig {
#[inline(always)]
fn default() -> Self {
Self::const_default()
}
}
pub struct VeloxEngine {
pool: PodPool,
frame_scope: FrameScope,
async_rt: crate::async_rt::ForegroundExecutor,
motion: MotionCache,
damage: DamageTracker,
prev_snapshots: SmallVec<DrawOpSnapshot, MAX_DRAW_OPS>,
cached_ops_buf: std::vec::Vec<DrawOp<'static>>,
cached_hits_buf: std::vec::Vec<HitRegion<'static>>,
cached_ops_ptr: *const DrawOp<'static>,
cached_ops_len: u32,
cached_hits_ptr: *const HitRegion<'static>,
cached_hits_len: u32,
cached_layout_ptr: *mut LayoutNode<'static, 'static>,
tree_cursor_mark: u32,
tree_temp_mark: u32,
ops_cursor_mark: u32,
frame_cached: bool,
partial_relayout_count: u16,
solve_count: u32,
fast_paint_count: u32,
dropped_draw_ops: u32,
viewport: Region,
dpi_scale: i16,
scale_factor: f32,
gesture_config: GestureConfig,
root_pod: Option<PodId>,
interaction: InteractionState,
pressed_hit_id: u32,
press_start_x: i16,
press_start_y: i16,
press_hold_ms: u16,
repeat_accum_ms: u16,
last_drag_vy: i16,
last_arena_used_bytes: u32,
modifiers: KeyModifiers,
active_pointer_kind: PointerKind,
ime_preedit: ImePreedit,
ime_enabled: bool,
first_frame: bool,
interaction_dirty: bool,
has_pressed_hit: bool,
drag_fired_on_down: bool,
long_press_fired: bool,
long_press_handled: bool,
}
impl VeloxEngine {
pub fn new(width: i16, height: i16) -> Self {
Self {
pool: PodPool::new(),
frame_scope: FrameScope::new(),
async_rt: crate::async_rt::ForegroundExecutor::new(),
motion: MotionCache::new(),
damage: DamageTracker::new(),
prev_snapshots: SmallVec::new(),
cached_ops_buf: std::vec::Vec::new(),
cached_hits_buf: std::vec::Vec::new(),
cached_ops_ptr: core::ptr::null(),
cached_ops_len: 0,
cached_hits_ptr: core::ptr::null(),
cached_hits_len: 0,
cached_layout_ptr: core::ptr::null_mut(),
tree_cursor_mark: 0,
tree_temp_mark: 0,
ops_cursor_mark: 0,
frame_cached: false,
solve_count: 0,
partial_relayout_count: 0,
fast_paint_count: 0,
dropped_draw_ops: 0,
viewport: Region::new(0, 0, width, height),
dpi_scale: 1,
scale_factor: 1.0,
gesture_config: GestureConfig::const_default(),
root_pod: None,
interaction: InteractionState::const_default(),
pressed_hit_id: 0,
press_start_x: 0,
press_start_y: 0,
press_hold_ms: 0,
repeat_accum_ms: 0,
last_drag_vy: 0,
last_arena_used_bytes: 0,
modifiers: KeyModifiers::NONE,
active_pointer_kind: PointerKind::Touch,
ime_preedit: ImePreedit::empty(),
ime_enabled: false,
first_frame: true,
interaction_dirty: false,
has_pressed_hit: false,
drag_fired_on_down: false,
long_press_fired: false,
long_press_handled: false,
}
}
#[inline]
pub fn init_at(slot: &mut core::mem::MaybeUninit<Self>, width: i16, height: i16) -> &mut Self {
slot.write(Self::new(width, height))
}
#[inline]
pub fn try_insert_view<V: View>(&mut self, view: V) -> Option<Handle<V>> {
let handle = self.pool.try_insert(view)?;
self.invalidate_frame_cache();
Some(handle)
}
#[inline(always)]
pub(super) fn invalidate_frame_cache(&mut self) {
self.frame_cached = false;
self.cached_ops_ptr = core::ptr::null();
self.cached_ops_len = 0;
self.cached_hits_ptr = core::ptr::null();
self.cached_hits_len = 0;
{
self.cached_ops_buf.clear();
self.cached_hits_buf.clear();
}
}
#[inline(always)]
pub(super) fn resolve_hit_pod(root_id: PodId, hit_owner: u16) -> PodId {
if hit_owner == u16::MAX {
root_id
} else {
PodId(hit_owner)
}
}
#[inline]
pub(super) fn make_action_scope(
&mut self,
owner: PodId,
click_pos: (i16, i16),
drag_ev: DragEvent,
) -> ActionScope<'_> {
let acx = ActionScope::new(
owner,
&mut self.pool,
click_pos,
drag_ev,
self.frame_scope.now_ms,
);
let acx = acx.with_async_app(self.async_rt.async_app());
acx
}
#[inline]
pub(super) fn flush_async_after_event(&mut self) {
if self.async_rt.has_work_to_poll() {
let _ = self.poll_async_tasks();
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn cache_ops_and_hits_into<'a>(
arena: &crate::arena::ScratchArena,
ops: &mut [DrawOp<'a>],
hits: &[HitRegion<'a>],
cached_ops_buf: &mut std::vec::Vec<DrawOp<'static>>,
cached_hits_buf: &mut std::vec::Vec<HitRegion<'static>>,
cached_ops_ptr: &mut *const DrawOp<'static>,
cached_ops_len: &mut u32,
cached_hits_ptr: &mut *const HitRegion<'static>,
cached_hits_len: &mut u32,
_dropped_draw_ops: &mut u32,
frame_cached: &mut bool,
last_arena_used_bytes: &mut u32,
) {
precompute_occlusion_clips(ops);
{
cached_ops_buf.clear();
let static_ops: &[DrawOp<'static>] = unsafe {
core::slice::from_raw_parts(ops.as_ptr() as *const DrawOp<'static>, ops.len())
};
cached_ops_buf.extend_from_slice(static_ops);
*cached_ops_ptr = cached_ops_buf.as_ptr();
*cached_ops_len = cached_ops_buf.len() as u32;
cached_hits_buf.clear();
let static_hits: &[HitRegion<'static>] = unsafe {
core::slice::from_raw_parts(hits.as_ptr() as *const HitRegion<'static>, hits.len())
};
cached_hits_buf.extend_from_slice(static_hits);
*cached_hits_ptr = cached_hits_buf.as_ptr();
*cached_hits_len = cached_hits_buf.len() as u32;
*frame_cached = true;
*last_arena_used_bytes = arena.used_bytes() as u32;
}
}
#[inline(always)]
pub(super) fn invalidate_layout_cache(&mut self) {
self.invalidate_frame_cache();
self.cached_layout_ptr = core::ptr::null_mut();
self.tree_cursor_mark = 0;
self.tree_temp_mark = 0;
self.ops_cursor_mark = 0;
}
#[inline(always)]
pub const fn modifiers(&self) -> KeyModifiers {
self.modifiers
}
#[inline(always)]
pub fn set_modifiers(&mut self, modifiers: KeyModifiers) {
self.modifiers = modifiers;
}
#[inline(always)]
pub const fn gesture_config(&self) -> GestureConfig {
self.gesture_config
}
#[inline(always)]
pub fn set_gesture_config(&mut self, config: GestureConfig) {
self.gesture_config = config;
}
#[inline(always)]
pub const fn pointer_kind(&self) -> PointerKind {
self.active_pointer_kind
}
#[inline(always)]
pub fn set_pointer_kind(&mut self, kind: PointerKind) {
self.active_pointer_kind = kind;
}
#[inline(always)]
pub(super) const fn allows_drag_scroll(&self) -> bool {
matches!(self.active_pointer_kind, PointerKind::Touch)
|| self.gesture_config.mouse_drag_scroll
}
#[inline(always)]
pub const fn dropped_draw_ops_count(&self) -> u32 {
self.dropped_draw_ops
}
#[inline(always)]
pub const fn layout_solve_count(&self) -> u32 {
self.solve_count
}
#[inline(always)]
pub const fn partial_relayout_count(&self) -> u32 {
self.partial_relayout_count as u32
}
#[inline(always)]
pub fn relayout_boundary_hits(&self) -> u32 {
self.pool.relayout_boundary_hits()
}
#[inline(always)]
pub const fn fast_paint_pass_count(&self) -> u32 {
self.fast_paint_count
}
#[inline(always)]
pub fn subview_cache_hits(&self) -> u32 {
self.pool.skipped_render_count()
}
#[inline(always)]
pub fn pod_render_count<V: View>(&self, handle: Handle<V>) -> u32 {
self.pool.render_count(handle.pod_id())
}
#[inline(always)]
pub fn set_dpi_scale(&mut self, scale: i16) {
let s = scale.max(1);
self.dpi_scale = s;
self.scale_factor = s as f32;
}
#[inline(always)]
pub fn set_scale_factor(&mut self, scale_factor: f32) {
let sf = scale_factor.clamp(0.5, 4.0);
self.scale_factor = sf;
self.dpi_scale = ((sf + 0.5) as i16).max(1);
}
#[inline(always)]
pub const fn dpi_scale(&self) -> i16 {
self.dpi_scale
}
#[inline(always)]
pub const fn scale_factor(&self) -> f32 {
self.scale_factor
}
#[inline(always)]
pub const fn viewport_region(&self) -> Region {
self.viewport
}
pub fn resize(&mut self, width: i16, height: i16) {
let new_vp = Region::new(0, 0, width, height);
if new_vp != self.viewport {
self.viewport = new_vp;
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
}
#[inline(always)]
pub fn theme(&self) -> CoreTheme {
*self.frame_scope.theme()
}
pub fn set_theme(&mut self, theme: CoreTheme) {
self.frame_scope.set_theme(theme);
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
#[inline(always)]
pub fn locale(&self) -> crate::i18n::Locale {
self.frame_scope.locale()
}
pub fn set_locale(&mut self, locale: crate::i18n::Locale) {
if self.frame_scope.locale() != locale {
self.frame_scope.set_locale(locale);
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
}
pub fn set_i18n_catalog(&mut self, catalog: &'static crate::i18n::StaticCatalog) {
self.frame_scope.set_i18n_catalog(catalog);
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
pub fn set_dynamic_catalog(&mut self, catalog: std::sync::Arc<crate::i18n::DynamicCatalog>) {
self.frame_scope.set_dynamic_catalog(catalog);
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
#[inline(always)]
pub const fn safe_area(&self) -> SafeAreaInsets {
self.frame_scope.safe_area()
}
pub fn set_safe_area(&mut self, insets: SafeAreaInsets) {
if self.frame_scope.safe_area() != insets {
self.frame_scope.set_safe_area(insets);
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
}
#[inline(always)]
pub const fn keyboard_inset(&self) -> i16 {
self.frame_scope.keyboard_inset()
}
pub fn set_keyboard_inset(&mut self, height: i16) {
let clamped = height.max(0);
if self.frame_scope.keyboard_inset() != clamped {
self.frame_scope.set_keyboard_inset(clamped);
self.first_frame = true;
self.invalidate_layout_cache();
self.pool.mark_all_dirty();
}
}
pub fn mount_root<V: View>(&mut self, view: V) -> Handle<V> {
let handle = self.pool.insert(view);
self.root_pod = Some(handle.pod_id());
self.pool.set_cached_bounds(handle.pod_id(), self.viewport);
self.first_frame = true;
self.invalidate_layout_cache();
handle
}
pub fn insert_view<V: View>(&mut self, view: V) -> Handle<V> {
self.pool.insert(view)
}
pub fn remove_view<V: View>(&mut self, handle: Handle<V>) -> bool {
let removed = self.pool.remove(handle);
if removed {
if self.root_pod == Some(handle.pod_id()) {
self.root_pod = None;
}
self.invalidate_layout_cache();
if let Some(root) = self.root_pod {
self.pool.mark_dirty(root);
}
}
removed
}
pub fn view_mut<V: View>(&mut self, handle: Handle<V>) -> Option<&mut V> {
self.pool.mark_dirty(handle.pod_id());
self.pool.get_mut(handle)
}
pub fn update_view<V: View, R>(&mut self, handle: Handle<V>, f: impl FnOnce(&mut V) -> R) -> Option<R> {
self.pool.update(handle, f)
}
pub fn view<V: View>(&self, handle: Handle<V>) -> Option<&V> {
self.pool.get(handle)
}
#[inline(always)]
pub fn motion_mut(&mut self) -> &mut MotionCache {
self.interaction_dirty = true;
&mut self.motion
}
#[inline(always)]
pub const fn last_arena_used_bytes(&self) -> usize {
self.last_arena_used_bytes as usize
}
#[inline(always)]
pub fn last_damage(&self) -> &[Region] {
self.damage.regions()
}
#[inline(always)]
pub const fn focused_index(&self) -> Option<u16> {
self.interaction.focused_index
}
#[inline(always)]
pub const fn is_focus_visible(&self) -> bool {
self.interaction.focus_visible
}
#[inline(always)]
pub fn set_focused_index(&mut self, idx: Option<u16>) {
if self.interaction.focused_index != idx {
self.interaction.focused_index = idx;
if idx.is_none() {
self.interaction.focus_visible = false;
}
self.interaction_dirty = true;
}
}
#[inline]
pub fn needs_redraw(&self) -> bool {
if self.async_rt.has_ready_work() {
return true;
}
self.first_frame
|| self.interaction_dirty
|| self.frame_scope.frame_requested.get()
|| self.pool.has_dirty()
|| crate::signal::has_pending_dirty_pods()
|| self.motion.has_active_animations()
}
#[inline(always)]
pub const fn clock_ms(&self) -> u32 {
self.frame_scope.now_ms
}
pub fn with_scheduler(
self,
backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
) -> Self {
self.async_rt.set_backend(backend);
self
}
pub fn set_scheduler(
&mut self,
backend: std::sync::Arc<dyn crate::async_rt::SchedulerBackend>,
) {
self.async_rt.set_backend(backend);
}
#[inline]
pub fn scheduler_name(&self) -> &'static str {
self.async_rt.scheduler_name()
}
#[inline]
pub fn scheduler_capabilities(&self) -> crate::async_rt::SchedulerCapabilities {
self.async_rt.scheduler_capabilities()
}
pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
self.async_rt.set_wake_ui(waker);
}
pub fn poll_async_tasks(&mut self) -> bool {
self.async_rt
.poll_ready(&mut self.pool, self.frame_scope.now_ms)
}
#[inline]
pub fn has_pending_async_tasks(&self) -> bool {
self.async_rt.has_ready_work()
}
#[inline]
pub fn active_async_task_count(&self) -> usize {
self.async_rt.active_task_count()
}
pub fn spawn<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,
{
self.async_rt.spawn(f)
}
pub fn spawn_for<V, T, F, Fut>(
&mut self,
handle: Handle<V>,
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,
{
self.async_rt.async_app().spawn_for(handle, f)
}
#[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 background_executor(&self) -> crate::async_rt::BackgroundExecutor {
self.async_rt.background_executor()
}
#[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,
{
self.async_rt.defer(f);
}
pub fn finish_animations(&mut self) {
self.motion.finish_all();
self.invalidate_frame_cache();
if let Some(root) = self.root_pod {
self.pool.mark_dirty(root);
}
}
}
impl HitRegion<'_> {
#[inline(always)]
const fn active_bg_or_focus(&self) -> bool {
self.has_active_bg || self.focus_index.is_some() || self.scroll_target.is_some()
}
}