跳到正文
开发版

手势识别与事件回调 ​

本文介绍如何声明强类型事件载荷、绑定回调以及配置有界的通知与命令存储。关于控件自身的输入钩子与文本编辑通知,请参阅控件初始化、输入与通知;关于文档编辑与输入法会话,请参阅文本编辑与输入法;关于选区快照与系统剪贴板读写,请参阅跨平台剪贴板。

Tap, Double-Tap & Drag
2352#[model]
2353#[derive(Default)]
2354pub struct GestureLab {
2355 #[observe]
2356 pub single_taps: u32,
2357 #[observe]
2358 pub double_taps: u32,
2359 #[observe]
2360 pub drag_dx: i32,
2361 #[observe]
2362 pub bubble_hits: u32,
2363 #[observe]
2364 pub allow_bubble: bool,
2365}
2366
2367#[model]
2368impl GestureLab {
2369 pub fn on_single(&mut self) {
2370 self.single_taps += 1;
2371 }
2372
2373 pub fn on_double(&mut self) {
2374 self.double_taps += 1;
2375 }
2376
2377 pub fn on_drag(&mut self, dx: i32) {
2378 self.drag_dx = (self.drag_dx + dx).clamp(-40, 40);
2379 }
2380
2381 pub fn on_parent_bubble(&mut self) {
2382 self.bubble_hits += 1;
2383 }
2384
2385 pub fn toggle_bubble(&mut self) {
2386 self.allow_bubble = !self.allow_bubble;
2387 }
2388}
2389
2390#[event]
2391fn drag_puck(event: event!(DragMove), lab: model!(GestureLab)) {
2392 lab.on_drag(event.dx.to_int());
2393}
2394
2395#[compose]
2396fn events_playground_scene(lab: model!(GestureLab)) {
2397 ui! {
2398 Column (
2399 grow: 1.0,
2400 padding: Padding::all(16),
2401 justify: JustifyContent::SpaceBetween,
2402 text_color: ColorToken::OnSurface
2403 ) {
2404 Row (height: 30, column_gap: 8, align: AlignItems::Center) {
2405 Button (
2406 text: ${ if lab.allow_bubble() { "Bubble: Allow" } else { "Bubble: Stop" } },
2407 width: 118,
2408 height: 28,
2409 font_size: 12,
2410 border_radius: 7,
2411 normal_color: ColorToken::SurfaceVariant,
2412 pressed_color: ColorToken::Outline,
2413 text_color: ColorToken::OnSurface
2414 ) on Tap { lab.toggle_bubble(); }
2415 Text (
2416 text: ${ format_args!("Row hits: {}", lab.bubble_hits()) },
2417 capacity: 24,
2418 grow: 1.0,
2419 height: 20,
2420 font_size: 12,
2421 text_color: ColorToken::OnSurfaceVariant
2422 )
2423 }
2424 Row (
2425 height: 76,
2426 padding: Padding::all(10),
2427 column_gap: 8,
2428 align: AlignItems::Center,
2429 bg_color: ColorToken::SurfaceVariant,
2430 border_radius: 10
2431 ) on Tap { lab.on_parent_bubble(); } {
2432 Button (
2433 "Tap / 2×Tap",
2434 width: 104,
2435 height: 52,
2436 font_size: 12,
2437 border_radius: 8,
2438 normal_color: ColorToken::Primary,
2439 pressed_color: ColorToken::Secondary,
2440 text_color: ColorToken::OnPrimary
2441 ) on Tap {
2442 lab.on_single();
2443 !lab.allow_bubble()
2444 } on Tap(2) { lab.on_double(); }
2445 View (
2446 grow: 1.0,
2447 height: 52,
2448 padding: Padding::all(10),
2449 bg_color: ColorToken::Secondary,
2450 border_radius: 8,
2451 clip_children: true
2452 ) {
2453 View (
2454 position: Position::Absolute,
2455 left: ${ 12 + lab.drag_dx() },
2456 top: 16,
2457 width: 96,
2458 height: 20
2459 ) {
2460 Text (
2461 "Drag ↔",
2462 height: 20,
2463 font_size: 12,
2464 text_color: ColorToken::OnSecondary
2465 )
2466 }
2467 } on DragMove(drag_puck::callback(lab))
2468 }
2469 Text (
2470 text: ${ format_args!("Tap(1): {} · Tap(2): {} · dx: {}px", lab.single_taps(), lab.double_taps(), lab.drag_dx()) },
2471 capacity: 56,
2472 height: 18,
2473 font_size: 12,
2474 text_color: ColorToken::OnSurfaceVariant
2475 )
2476 }
2477 };
2478}
正在加载预览…

点击 Tap or Double-Tap 按钮体验单击 on Tap 与双击 on Tap(2) 回调,切换顶部的 Bubble: Allow (false) / Stop (true) 观察父容器 Row 是否收到冒泡点击,并左右拖动右侧滑块观察 DragMove 实时增量。

TYPED EVENT DISPATCH手势冒泡、双缓冲通知队列与延迟命令时序

在对空间指针事件做命中测试前,`App` 先刷新过期的布局与变换几何,确保坐标永远命中最新位置。

InputEvent::PointerUp { x, y, .. } -> Gesture::Tap { count: 2 }Route: EntityBubble (target -> ancestors -> root)

事件类型契约 (Event 与 EventKey) ​

路由类型典型事件载荷派发路径返回值与冒泡控制契约
EntityBubbleTap、LongPress、DragStart/Move/End、Pinch、Rotate命中节点 → Parent 祖先链 → 根节点返回 false / BubbleControl::Allow 继续冒泡;返回 () / true / Stop 消费并停止
EntityNotificationSlider::ValueChanged、Switch::Toggled、ClipboardFinished直接送达发出通知的实体监听器(双缓冲 FIFO)固定返回 ()(不可消费,扇出广播)
EntityRequest<R>SelectAll、InspectSelection、Copy/Cut/PasteSelection在目标实体上同步调用唯一提供者返回强类型 R(如 Result<..., RequestError>)
InputFallbackKey、TextCommitted、Wheel、Rotary焦点 / 滚动目标 → 祖先链 → App::on_event被焦点编辑器或滚动容器消费的输入不会落入全局快捷键
AppNotificationStarted、Suspended、Resumed、MemoryWarning、Quit生命周期钩子完成后直接送达 App::on_event固定返回 ()

选区请求与 Event 特征 ​

选区请求使用 ui::selection::SelectAll 并返回 Result<(), RequestError>。调用 commands.selection().select_all(entity) 会在目标节点上调用唯一的提供者(不冒泡、不走 App 回退、也不占用通知队列存储)。TextEditing 默认注册了该提供者;自定义组件也可以在 View 的 input 元组中注册 #[event] 回调,或在具体节点上用 on SelectAll 覆盖默认实现。请求类绑定不会给节点增加指针高亮反馈或命中测试目标。

input::event::contract::Event 声明事件载荷的路由(Route)、事件源约束(Source)与配置选项(Options)。EventKey<E> 仅存储配置选项并保留载荷类型标记(当 Options = () 时为零大小类型)。

自定义控件通知使用 EntityNotification 路由与 WidgetSource<W> 事件源约束:

rust
use mirui::input::event::contract::{EntityNotification, Event, WidgetSource};

#[mirui::component]
struct Pad;

struct Hit {
    strength: u8,
}

impl Event for Hit {
    type Route = EntityNotification;
    type Source = WidgetSource<Pad>;
    type Options = ();
}

WidgetSource<Pad> 编译器级约束确保该通知只能安装在挂载了 Pad 的控件上,而不能误挂到其他控件或 App 监听器上。四类核心路由分工明确:

  • EntityBubble:从命中目标向祖先节点冒泡的手势与按键事件(支持返回 ()、bool 或 BubbleControl 控制是否继续冒泡);
  • EntityNotification:控件向自身监听器派发的业务通知(返回值固定为 ());
  • InputFallback:经焦点或滚动处理后未被消费、最终送达 App 监听器的回退输入;
  • AppNotification:不可消费的应用生命周期通知(Started、Suspended、Resumed、MemoryWarning、HostInteraction、Quit)。

内置控件通知位于各自的模块下:slider::ValueChanged、slider::DragStarted、slider::DragEnded、slider::DragCancelled、switch::Toggled、checkbox::Toggled、progress_bar::ValueChanged、tabbar::SelectionChanged 与 text_editing::Changed(可通过 Slider::ValueChanged 等类型常量直接引用)。

常用手势导出在 prelude 中:Tap、LongPress、DragStart、DragMove、DragEnd、DragCancel、Pinch 与 Rotate。其中默认 on Tap 匹配任意点击次数;若传入显式连击次数 on Tap(2),则只匹配对应的连击重数(有效范围为 1..=255)。

ui! 中的 on 绑定统一支持四种写法:内联代码块(通过 event 变量读取载荷)、单参数闭包、普通 Rust 函数以及 #[event] 具名回调工厂(支持注入 event!(E)、entity!()、model!(T)、res!(...)、query!(...) 与 commands!()):

rust
Button(text: "DROP") on Tap { game.drop_ball(); }

View () on Tap(|input| { game.select_at(input.x, input.y); })

View () on DragMove(|input: event!(DragMove), node: entity!(), items: query!(mut Draggable)| {
    if let Some(item) = items.get(node) {
        item.move_by(input.dx, input.dy);
    }
})

View () on DragMove(moved::callback(game, step))

View () on Tap(handle_tap)

同一个节点上的不计次 Tap 与计次 Tap(n) 按声明顺序依次执行,并在第一个消费事件的处理器处停止。返回 false(或 BubbleControl::Allow)表示允许后续处理器继续运行;返回 () 或 true 则消费并终止:

rust
View ()
    on Tap { game.record_tap(); false }
    on Tap(2) { game.record_double_tap(); }

Key 事件同时携带与输入法布局无关的物理键位 physical: Option<PhysicalKey>(如美式键盘位置上的 PhysicalKey::KeyW)以及逻辑键码 code。Wheel 与 Rotary 仅支持安装在 App 级回退监听器上。

布局尺寸变更事件 (SizeChanged) ​

SizeChanged 在节点首次算出有效逻辑尺寸以及后续宽度或高度发生变化时触发。首次投递时 event.old 为 None,event.new 为包含 width 与 height 的 LayoutSize。单纯的位置平移、滚动偏移、输出缩放比或视觉变换不会触发尺寸事件;隐藏或未挂载节点不参与测量。

Container Size & @width
2167#[compose]
2168fn state_at_scene() {
2169 ui! {
2170 Column (
2171 container: true,
2172 grow: 1.0,
2173 padding: Padding::all(18),
2174 justify: JustifyContent::SpaceBetween,
2175 text_color: ColorToken::OnSurface
2176 ) {
2177 Text (
2178 "Drag the bottom-right grip to cross 320 px",
2179 height: 28,
2180 font_size: @width {
2181 if width < Fixed::from_int(320) { 13_u16 } else { 18_u16 }
2182 },
2183 text_color: ColorToken::Primary
2184 )
2185 View (
2186 id: "stage",
2187 width: Dimension::percent(100),
2188 height: 44,
2189 padding: Padding::all(12),
2190 bg_color: ColorToken::Secondary,
2191 border_radius: 8
2192 ) {
2193 Text ("#stage (100% width)", height: 20, font_size: 13, text_color: ColorToken::OnSecondary)
2194 }
2195 View (
2196 width: @id(stage).width { stage.width / 2 },
2197 height: 36,
2198 padding: Padding::all(8),
2199 bg_color: ColorToken::SurfaceVariant,
2200 border_radius: 8
2201 ) {
2202 Text ("@id(stage).width / 2", height: 20, font_size: 12)
2203 }
2204 }
2205 };
2206}
正在加载预览…

拖动预览画布右下角的尺寸调节手柄跨过 320 px 宽度阈值,观察容器几何变化如何实时驱动字号与子视图宽度更新。

rust
View(width: Dimension::percent(100), height: 360) on SizeChanged {
    model.set_stage_size(event.new.width, event.new.height);
}

View() on SizeChanged(|change: event!(SizeChanged)| {
    model.set_stage_size(change.new.width, change.new.height);
})

#[event]
fn resized(model: model!(PanelModel), change: event!(SizeChanged)) {
    model.set_stage_size(change.new.width, change.new.height);
}

View() on SizeChanged(resized::callback(model.clone()))

SizeChanged 由布局阶段直接产生,不冒泡、不增加命中测试目标,且其引起的响应式状态更新会直接参与同一帧的收敛结算。若只需跨节点引用布局几何,请优先使用零分配的 @ 几何响应式属性;若需要将容器宽高同步进业务 Model(例如根据画布尺寸重算贝塞尔路径范围),则使用 SizeChanged。

应用级回调与事件容量预算 (EventCapacity) ​

App::on_event(E::EVENT, callback) 用于安装应用生命周期通知或全局按键/滚轮回退监听器:

rust
use mirui::prelude::*;

#[model]
struct Shortcuts {
    enabled: bool,
}

#[model]
impl Shortcuts {
    fn toggle(&mut self) {
        self.enabled = !self.enabled;
    }
}

#[event]
fn handle_key(input: event!(Key), shortcuts: model!(Shortcuts)) -> bool {
    if input.pressed && input.code == mirui::input::event::input::KEY_RETURN {
        shortcuts.toggle();
        true
    } else {
        false
    }
}

let mut app = App::headless(320, 240);
let shortcuts = app.add_model(Shortcuts { enabled: false }).finish();
app.on_event(Key::EVENT, handle_key::callback(shortcuts));

当存在聚焦的编辑器时,节点按键回调与默认文本编辑优先于 App 全局按键回退执行;滚轮与旋钮事件同样优先尝试滚动路由,只有在未被滚动容器消费时才会落入 App 监听器。

App 默认自带一套按需分配的有界事件容量预设(双缓冲各 8 条业务通知记录、每次回调最多 5 条延迟命令记录、单次外层刷新最多投递 16 条通知)。如果应用需要更大的自定义通知载荷或更长的命令批次,可在安装第一个回调前通过 App::with_event_capacity 显式配置:

rust
app.with_event_capacity(
    EventCapacity::new()
        .notifications::<PadHit>(MAX_PENDING_HITS)
        .commands(CommandCapacity::new().emit::<PadHit>(MAX_HITS_PER_CALLBACK))
        .flush_limit(MAX_DELIVERIES),
);

第一个回调成功安装后,容量配置即被冻结;派发期间绝不会在后台隐式扩容已准备好的缓冲区。

通知载荷双缓冲存储 ​

内部通知服务使用两块显式预留的缓冲区(双缓冲乒乓切换):当回调正在稳定读取当前批次的只读载荷窗口时,回调内部新发出的通知会追加到另一块写入缓冲区中,并在当前批次剩余记录全部执行完毕后按 FIFO 顺序继续排空,从而在不发生递归重入的前提下保证严格的先进先出顺序。在预留容量上限内的写入与排空全程零堆分配。

已识别的手势批次与状态机 ​

手势识别器在同一输入批次中统一维护指针状态:

  • 点击与长按(Tap / LongPress):手指按下后在移动阈值内抬起触发 Tap(快速连点递增连击计数 count);按住超过长按阈值且未发生拖拽时触发 LongPress;
  • 拖拽(DragStart / DragMove / DragEnd / DragCancel):位移越过阈值后锁定手势目标并持续派发 DragMove,直至松手(DragEnd)或被窗口失焦/挂起打断(DragCancel);
  • 双指缩放与旋转(Pinch / Rotate):根据多点触控距离比与角度增量派发。

回调参数校验与延迟命令执行 ​

#[event]、#[system] 与 #[timer] 共用同一套编译期与安装期访问计划校验器:若参数中存在组件/资源可变借用冲突,或混入了属于其他 App 的模型句柄,安装阶段即会拦截并输出结构化错误日志。

在回调执行期间,commands!() 先将操作记录在当前回调专属的定长命令缓冲中;待回调函数体返回、所有参数借用全部释放后,执行器再按源码顺序依次提交命令。

监听器选择与路由快照 ​

派发手势或键盘事件前,监听器池会先冻结当前的 Parent 祖先链与有效监听器快照,并在每一步执行前核对实体代数(generation):

  • 若回调中途移动了节点父子关系、增删了监听器或移除了过滤组件,当前正在冒泡的这一轮路由快照不会被篡改;
  • 隐藏或禁用(disabled)的节点及其祖先在路由选择阶段即被跳过,不会触发手势或焦点按键,但业务通知(EntityNotification)仍然可以送达存活的隐藏/禁用控件。

延迟发送自定义控件通知 (commands.emit) ​

在自定义控件的输入回调中,使用 commands.emit(entity, payload) 向该节点发送业务通知:

  • commands.emit 仅在命令提交时刻该实体确实安装了对应类型的监听器时才将载荷移入通知队列;若无人监听则直接丢弃,不消耗通知缓冲区配额;
  • commands.emit_always 则无论当前是否有监听器都会校验实体、事件源与容量配额。两者均需在自定义容量配置中通过 CommandCapacity::emit::<E>(count) 预留额度。

具名事件回调声明 (#[event]) ​

#[event] 生成一个带有 callback(...) 工厂函数的同名模块。工厂函数按参数声明顺序接收已注册的 Model 实例以及普通的 Copy + 'static 值;而资源(res!)、查询(query!)、事件载荷(event!)、当前实体(entity!)与延迟命令(commands!)则在事件触发调用时由框架注入,无需传给工厂函数:

rust
#[event]
fn moved(
    game: model!(Game),
    step: u16,
    input: event!(DragMove),
    node: entity!(),
    positions: query!(mut Position),
) -> bool {
    let Some(position) = positions.get(node) else {
        return false;
    };
    game.move_to(position, input.x, input.y, step);
    true
}

调用 moved::callback(game, step) 即可构造回调描述符,无需暴露 World 或生成的句柄类型。通知类回调返回 ();可消费的冒泡或回退路由还支持返回 bool 或 BubbleControl。