Skip to main content

aureole_core/
event.rs

1//! 交给处理器的事件对象:指针、点击、按键、拖动、手势、拖入文件、改值、表单级的改值汇总,以及控制传播的方法。
2//!
3//! 一次输入走一条管线:命中(或指针捕获)得到路径,
4//! 先从外往里走一遍(捕获阶段,`on_*_capture`),到目标元素(目标阶段),再从里往外走一遍(冒泡阶段,`on_*`),
5//! 最后执行没被取消的内置行为。处理器拿到的是事件对象的引用,用它上面的方法控制传播:
6//!
7//! - [`PointerEvent::stop_propagation`]:外面(冒泡)或里面(捕获)的元素不再收到;这个元素上剩下的处理器照样调用;
8//! - [`PointerEvent::prevent_builtin`]:取消内置行为(拿焦点、选字、拖动、滚动、激活……见 [`Builtin`]);
9//! - [`PointerEvent::capture_pointer`]:按下时调用,之后的移动、松开都交给这个元素,指针移出它、移出窗口也一样。
10//!
11//! 处理器可以写成收事件对象的闭包,也可以写成不带参数的闭包([`IntoHandler`]):
12//! `.on_click(|| save())` 和 `.on_click(|e: &ClickEvent| ..)` 收到的是同一个事件。
13
14use std::cell::Cell;
15use std::path::PathBuf;
16use std::rc::Rc;
17use std::time::Duration;
18
19use reactive::Scope;
20use scene::Angle;
21
22use crate::image::RgbaImage;
23use crate::rich_text::SpanInfo;
24use crate::input::{Buttons, GesturePhase, Key, Modifiers, MouseButton, PhysicalKey, PointerId, PointerKind, WheelDelta};
25use crate::interaction::{Chord, FocusHandle};
26
27/// 事件传到了哪一段
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum PropagationPhase {
30    /// 从外往里,还没到目标(`on_*_capture` 的处理器)
31    Capture,
32    /// 在目标元素上
33    #[default]
34    Target,
35    /// 从目标往外
36    Bubble,
37}
38
39bitflags::bitflags! {
40    /// 事件之后的内置行为,处理器用 `prevent_builtin(..)` 取消
41    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42    pub struct Builtin: u16 {
43        /// 按下时让元素获得焦点
44        const FOCUS = 1;
45        /// 在文字上按下、拖动时放插入点、选字
46        const TEXT_SELECT = 1 << 1;
47        /// 按下后移动时开始拖动(`on_drag`、拖放、拖到应用外面)
48        const DRAG = 1 << 2;
49        /// 滚轮、方向键、翻页键滚动视口;手指拖动滚动视口(在 `on_pointer_down` 里取消)
50        const SCROLL = 1 << 3;
51        /// 点击:松开时合成点击;回车、空格激活有焦点的元素
52        const ACTIVATE = 1 << 4;
53        /// 在浮层外面按下、按 Esc 时请求关闭浮层
54        const DISMISS = 1 << 5;
55        /// Tab、Shift+Tab 切换焦点
56        const TAB = 1 << 6;
57        /// `focus_arrows` 的方向键在子孙之间移动焦点;输入框里的方向键移动插入点
58        const ARROWS = 1 << 7;
59        /// 右键按下、手指长按、菜单键和 Shift+F10 时的右键点击(`on_secondary_click`)
60        const CONTEXT_MENU = 1 << 8;
61        /// 有焦点的输入框处理按键:打字、删除、移动插入点、剪贴板、撤销
62        const EDIT = 1 << 9;
63        /// 关窗口(窗口的 `on_close_request`)
64        const CLOSE = 1 << 10;
65        /// 按在窗口的拖动区域(`window_drag_area`)上拖动窗口、双击缩放窗口
66        const WINDOW_DRAG = 1 << 11;
67        /// 全部
68        const ALL = (1 << 12) - 1;
69    }
70}
71
72/// 传播的状态:处理器拿到的是事件的引用,用格子记下它们的要求
73#[derive(Clone, Debug, Default)]
74pub(crate) struct Flow {
75    stopped: Cell<bool>,
76    prevented: Cell<Builtin>,
77    capture: Cell<bool>,
78    phase: Cell<PropagationPhase>,
79    /// 手势开始时,这个元素的处理器要不要这个手势
80    claim: Cell<Claim>,
81}
82
83/// 手势开始时一个元素的处理器的表态(见 [`DragEvent::claim_gesture`])
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub(crate) enum Claim {
86    /// 没表态:目标和冒泡阶段第一个有处理器的元素按默认拿到
87    #[default]
88    Undecided,
89    /// 要
90    Claimed,
91    /// 不要,交给外面的元素
92    Declined,
93}
94
95/// 传播的状态只在分发的那一刻有意义:比较事件时不算它
96impl PartialEq for Flow {
97    fn eq(&self, _: &Self) -> bool {
98        true
99    }
100}
101
102impl Flow {
103    pub fn stopped(&self) -> bool {
104        self.stopped.get()
105    }
106
107    /// 停止传播(分发器替元素做的,比如手势有了主人)
108    pub fn stop(&self) {
109        self.stopped.set(true);
110    }
111
112    /// 取走这个元素的表态(每个元素的处理器之后取一次)
113    pub fn take_claim(&self) -> Claim {
114        self.claim.replace(Claim::Undecided)
115    }
116
117    pub fn prevented(&self) -> Builtin {
118        self.prevented.get()
119    }
120
121    pub fn prevent(&self, builtin: Builtin) {
122        self.prevented.set(self.prevented.get() | builtin);
123    }
124
125    pub fn set_phase(&self, phase: PropagationPhase) {
126        self.phase.set(phase);
127    }
128
129    /// 处理器要求捕获指针了(取走要求)
130    pub fn take_capture(&self) -> bool {
131        self.capture.replace(false)
132    }
133}
134
135/// 控制传播的几个方法,每种会传播的事件都有
136macro_rules! propagation {
137    ($($ty:ident),*) => {
138        $(
139            impl $ty {
140                /// 停止传播:冒泡阶段外面的元素、捕获阶段里面的元素不再收到;这个元素上剩下的处理器照样调用
141                pub fn stop_propagation(&self) {
142                    self.flow.stopped.set(true);
143                }
144
145                /// 已经有处理器停止了传播
146                pub fn is_propagation_stopped(&self) -> bool {
147                    self.flow.stopped.get()
148                }
149
150                /// 取消内置行为,见 [`Builtin`]
151                pub fn prevent_builtin(&self, builtin: Builtin) {
152                    self.flow.prevent(builtin);
153                }
154
155                /// 这些内置行为是不是已经被取消了(都取消了才是 `true`)
156                pub fn is_builtin_prevented(&self, builtin: Builtin) -> bool {
157                    self.flow.prevented.get().contains(builtin)
158                }
159
160                /// 事件传到了哪一段
161                pub fn phase(&self) -> PropagationPhase {
162                    self.flow.phase.get()
163                }
164
165                pub(crate) fn flow(&self) -> &Flow {
166                    &self.flow
167                }
168            }
169        )*
170    };
171}
172
173propagation!(PointerEvent, ClickEvent, KeyEvent, WheelEvent);
174
175/// 手势事件(拖动、捏合、旋转)控制传播、争手势的方法
176macro_rules! gesture {
177    ($($ty:ident),*) => {
178        $(
179            impl $ty {
180                /// 停止传播:冒泡阶段外面的元素、捕获阶段里面的元素不再收到这次 `Start`;这个元素上剩下的处理器照样调用。
181                /// 停止了又没有元素拿到手势时,这个手势不开始(收到过 `Start` 的元素收到 `Cancel`)
182                pub fn stop_propagation(&self) {
183                    self.flow.stopped.set(true);
184                }
185
186                /// 已经有处理器停止了传播
187                pub fn is_propagation_stopped(&self) -> bool {
188                    self.flow.stopped.get()
189                }
190
191                /// 事件传到了哪一段。`Start` 按捕获 → 目标 → 冒泡走;之后的 `Move`、`End`、`Cancel` 只交给拿到手势的元素,
192                /// 是它拿到时的那一段(在捕获阶段抢到的是捕获阶段)
193                pub fn phase(&self) -> PropagationPhase {
194                    self.flow.phase.get()
195                }
196
197                /// 这个手势我要(只在 `Start` 时有效):这个元素拿到手势,传播停止,之后的 `Move`、`End` 只交给它;
198                /// 收到过 `Start` 的别的元素收到 `Cancel`。父元素在捕获阶段(`on_*_capture`)调用就是抢在里面的元素之前拿走;
199                /// 子元素在目标阶段调用是明说要它(不调用也是它的,见 [`Self::decline_gesture`])
200                pub fn claim_gesture(&self) {
201                    self.flow.claim.set(Claim::Claimed);
202                }
203
204                /// 这个手势我不要(只在 `Start` 时有效):目标和冒泡阶段第一个有处理器的元素默认拿到手势,
205                /// 调用了这个就接着往外传,交给外面的元素(比如横着拖的卡片把竖着的拖动让给外面的视口)。
206                /// 之后收到 `Cancel`
207                pub fn decline_gesture(&self) {
208                    self.flow.claim.set(Claim::Declined);
209                }
210
211                pub(crate) fn flow(&self) -> &Flow {
212                    &self.flow
213                }
214            }
215        )*
216    };
217}
218
219gesture!(DragEvent, PinchEvent, RotateEvent);
220
221impl FieldChangeEvent {
222    pub(crate) fn new(name: Option<String>, focus_handle: Option<FocusHandle>, value: FieldValue, source: ChangeSource) -> Self {
223        Self { name, focus_handle, value, source, flow: Flow::default() }
224    }
225
226    /// 停止传播:外面(冒泡)或里面(捕获)的元素不再收到;这个元素上剩下的处理器照样调用
227    pub fn stop_propagation(&self) {
228        self.flow.stopped.set(true);
229    }
230
231    /// 已经有处理器停止了传播
232    pub fn is_propagation_stopped(&self) -> bool {
233        self.flow.stopped.get()
234    }
235
236    /// 事件传到了哪一段:控件自己是目标阶段,外面的容器是冒泡阶段
237    pub fn phase(&self) -> PropagationPhase {
238        self.flow.phase.get()
239    }
240
241    pub(crate) fn flow(&self) -> &Flow {
242        &self.flow
243    }
244}
245
246/// 指针事件是哪一种
247#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
248#[non_exhaustive]
249pub enum PointerEventKind {
250    /// 按下一个键
251    Down,
252    /// 松开一个键
253    Up,
254    /// 移动
255    #[default]
256    Move,
257    /// 进入元素(不传播)
258    Enter,
259    /// 离开元素(不传播)
260    Leave,
261    /// 进行中的按下被打断(窗口失去焦点、拖动交给了系统)
262    Cancel,
263}
264
265/// 指针事件:按下、松开、移动、进入、离开、取消共用。位置有两份,元素自己的坐标(左上角是 (0, 0),
266/// 已经去掉了元素和祖先的变换,传播时每一层都换算成那一层元素的坐标)和窗口坐标
267#[derive(Clone, Debug)]
268pub struct PointerEvent {
269    /// 哪一种
270    pub kind: PointerEventKind,
271    /// 元素自己的坐标,逻辑像素
272    pub position: [f32; 2],
273    /// 窗口坐标,逻辑像素
274    pub window_position: [f32; 2],
275    /// 按下、松开的键;移动、进入、离开时是 `None`
276    pub button: Option<MouseButton>,
277    /// 此刻按着的键
278    pub buttons: Buttons,
279    /// 此刻按着的修饰键
280    pub modifiers: Modifiers,
281    /// 连续点击的次数:1 是单击,2 是双击……(按下、松开时有,别的是 0)
282    pub clicks: u32,
283    /// 什么设备
284    pub device: PointerKind,
285    /// 这种设备上的哪一个指针:触摸屏上每根手指一个(一根手指从按下到抬起不变),鼠标是 [`PointerId::MOUSE`]
286    pub pointer_id: PointerId,
287    /// 时间戳(和定时器同一个时钟,测试工具里是虚拟时间)
288    pub time: Duration,
289    pub(crate) flow: Flow,
290}
291
292impl PointerEvent {
293    pub(crate) fn new(kind: PointerEventKind, window_position: [f32; 2], button: Option<MouseButton>, modifiers: Modifiers, clicks: u32) -> Self {
294        Self {
295            kind,
296            position: window_position,
297            window_position,
298            button,
299            buttons: Buttons::empty(),
300            modifiers,
301            clicks,
302            device: PointerKind::Mouse,
303            pointer_id: PointerId::MOUSE,
304            time: crate::timer::now_duration(),
305            flow: Flow::default(),
306        }
307    }
308
309    /// 捕获指针(只在按下时有效):这次按下之后的移动、松开都交给这个元素,指针移出它、移出窗口也一样
310    pub fn capture_pointer(&self) {
311        self.flow.capture.set(true);
312    }
313}
314
315/// 点击是怎么来的
316#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
317#[non_exhaustive]
318pub enum ClickSource {
319    /// 指针:按下和松开都在元素上
320    #[default]
321    Pointer,
322    /// 键盘:有焦点时按回车、空格
323    Keyboard,
324    /// 辅助技术请求点击
325    Accessibility,
326    /// 点了它的标签(`controls::Label`)
327    Label,
328}
329
330/// 点击:左键(`on_click`)、右键(`on_secondary_click`)、中键(`on_middle_click`)、双击(`on_double_click`)。
331/// 不是指针来的点击(键盘、辅助技术、标签)位置是元素的正中
332#[derive(Clone, Debug)]
333pub struct ClickEvent {
334    /// 怎么来的
335    pub source: ClickSource,
336    /// 哪个键;不是指针来的是左键
337    pub button: MouseButton,
338    /// 元素自己的坐标,逻辑像素
339    pub position: [f32; 2],
340    /// 窗口坐标,逻辑像素
341    pub window_position: [f32; 2],
342    /// 此刻按着的修饰键
343    pub modifiers: Modifiers,
344    /// 连续点击的次数:1 是单击,2 是双击……
345    pub clicks: u32,
346    /// 时间戳,秒
347    pub time: Duration,
348    pub(crate) flow: Flow,
349}
350
351impl ClickEvent {
352    pub(crate) fn new(source: ClickSource, button: MouseButton, window_position: [f32; 2], modifiers: Modifiers, clicks: u32) -> Self {
353        Self {
354            source,
355            button,
356            position: window_position,
357            window_position,
358            modifiers,
359            clicks,
360            time: crate::timer::now_duration(),
361            flow: Flow::default(),
362        }
363    }
364}
365
366/// 按键事件,见 [`crate::Element::on_key_down`]
367#[derive(Clone, Debug)]
368pub struct KeyEvent {
369    /// 逻辑按键(按当前键盘布局和修饰键)
370    pub key: Key,
371    /// 不算修饰键时的按键(Shift+/ 的这里是 `/`),平台不提供时等于 `key`
372    pub base: Key,
373    /// 物理键(键位);平台不提供时为 `None`
374    pub physical: Option<PhysicalKey>,
375    /// 这个键输入的文字
376    pub text: Option<String>,
377    /// 按下时按住的修饰键
378    pub modifiers: Modifiers,
379    /// 按住不放时系统发的重复
380    pub repeated: bool,
381    /// 焦点上的元素正在输入法组字:这个键是给输入法的,输入框这类的内置编辑不处理它
382    pub composing: bool,
383    /// 时间戳,秒
384    pub time: Duration,
385    /// Windows、Linux 上的 AltGr(报成 Ctrl+Alt):打出来的是字,不是组合键
386    altgr: bool,
387    pub(crate) flow: Flow,
388}
389
390impl KeyEvent {
391    pub(crate) fn new(key: Key, base: Key, physical: Option<PhysicalKey>, text: Option<String>, modifiers: Modifiers, repeated: bool) -> Self {
392        // 主修饰键是 Command 的平台(macOS)没有 AltGr 这回事;别的平台上 Ctrl+Alt(不带 Win 键)是 AltGr
393        let altgr = modifiers.has_control()
394            && modifiers.has_alt()
395            && !modifiers.has_super()
396            && crate::system::conventions().primary_modifier == Modifiers::CONTROL;
397        Self { key, base, physical, text, modifiers, repeated, composing: false, time: crate::timer::now_duration(), altgr, flow: Flow::default() }
398    }
399
400    /// 是否是这个组合键,写法同 [`crate::shortcut`]:`e.is("Escape")`、`e.is("CmdOrCtrl+Enter")`
401    pub fn is(&self, chord: &str) -> bool {
402        Chord::parse(chord).is_some_and(|c| c.matches(&self.key, &self.base, self.modifiers))
403    }
404
405    /// 按着平台的主修饰键(macOS 是 Command,别的平台是 Ctrl;AltGr 不算):快捷键,⌘C、⌘V 这类
406    pub fn has_primary_modifier(&self) -> bool {
407        self.modifiers.intersects(crate::system::conventions().primary_modifier) && !self.altgr
408    }
409
410    /// 是组合键(按着 Command,或者按着不是 AltGr 的 Ctrl):不打字,留给快捷键和处理器。
411    /// 所有输入目标共用这一条规则(见 [`KeyEvent::typed_text`])
412    pub fn is_chord(&self) -> bool {
413        self.modifiers.has_super() || (self.modifiers.has_control() && !self.altgr)
414    }
415
416    /// 这个键打出的字:不是组合键、不在组字、不是控制字符(退格、回车、Esc 这类另外处理)时才有。
417    /// 输入框、字符网格、自己定义的编辑器都按它决定打不打字
418    pub fn typed_text(&self) -> Option<&str> {
419        let text = self.text.as_deref().filter(|t| !t.is_empty() && !t.chars().any(char::is_control))?;
420        (!self.is_chord() && !self.composing).then_some(text)
421    }
422}
423
424/// 滚轮、触控板滚动,见 [`crate::Element::on_wheel`]。交给指针下最内层的元素往外冒泡,之后滚动视口才滚
425/// (取消 [`Builtin::SCROLL`] 就不滚)
426#[derive(Clone, Debug)]
427pub struct WheelEvent {
428    /// 滚动量:鼠标滚轮按格(行),触控板按逻辑像素;正数让偏移变大(向下、向右滚,内容往上、往左走)
429    pub delta: WheelDelta,
430    /// 触控板手势进行到哪一步(鼠标滚轮总是 `Move`)
431    pub phase: GesturePhase,
432    /// 是系统在手指抬起后接着发的惯性
433    pub inertial: bool,
434    /// 元素自己的坐标,逻辑像素
435    pub position: [f32; 2],
436    /// 窗口坐标,逻辑像素
437    pub window_position: [f32; 2],
438    /// 此刻按着的修饰键(按住 Ctrl、Command 滚动常用来缩放)
439    pub modifiers: Modifiers,
440    /// 时间戳,秒
441    pub time: Duration,
442    pub(crate) flow: Flow,
443}
444
445impl WheelEvent {
446    pub(crate) fn new(delta: WheelDelta, phase: GesturePhase, inertial: bool, window_position: [f32; 2], modifiers: Modifiers) -> Self {
447        Self {
448            delta,
449            phase,
450            inertial,
451            position: window_position,
452            window_position,
453            modifiers,
454            time: crate::timer::now_duration(),
455            flow: Flow::default(),
456        }
457    }
458}
459
460/// 滚动视口的偏移变了,见 [`crate::Element::on_scroll`]:一帧最多一次,合并了这一帧里所有的变化
461#[derive(Clone, Copy, Debug, PartialEq)]
462pub struct ScrollEvent {
463    /// 现在的偏移(内容往上、往左滚过的距离),逻辑像素
464    pub offset: [f32; 2],
465    /// 和上一次的偏移(第一次是 0)差多少
466    pub delta: [f32; 2],
467}
468
469/// 拖动事件,见 [`crate::Element::on_drag`]。位移、速度都是窗口坐标(逻辑像素),不受元素自己缩放的影响。
470///
471/// `Start` 沿按下处的路径走捕获 → 目标 → 冒泡,决定谁拿到这个拖动([`DragEvent::claim_gesture`]、
472/// [`DragEvent::decline_gesture`]);之后只交给拿到的元素
473#[derive(Clone, Debug, PartialEq)]
474pub struct DragEvent {
475    /// 进行到哪一步
476    pub phase: GesturePhase,
477    /// 元素自己的坐标
478    pub position: [f32; 2],
479    /// 窗口坐标;拖出窗口后可以是负数或超过窗口大小
480    pub window_position: [f32; 2],
481    /// 按下的位置,窗口坐标
482    pub start_position: [f32; 2],
483    /// 和上一个事件之间的位移。`Start` 的位移是从按下到现在(包括越过阈值的那一小段),所以各次位移加起来就是总位移
484    pub delta: [f32; 2],
485    /// 从按下到现在的总位移
486    pub translation: [f32; 2],
487    /// 最近约 0.1 秒的平均速度,逻辑像素每秒;松手前停了一会儿时 `End` 的速度是 0
488    pub velocity: [f32; 2],
489    /// 拖动用的鼠标键
490    pub button: MouseButton,
491    /// 此刻按住的修饰键
492    pub modifiers: Modifiers,
493    pub(crate) flow: Flow,
494}
495
496/// 捏合(触控板、触摸屏上两根手指),见 [`crate::Element::on_pinch`]。`Start` 的传播和争手势同 [`DragEvent`]
497#[derive(Clone, Debug, PartialEq)]
498pub struct PinchEvent {
499    /// 进行到哪一步
500    pub phase: GesturePhase,
501    /// 从手势开始到现在的缩放倍数(开始时是 1)
502    pub scale: f32,
503    /// 这一次的倍数:乘到自己的缩放上就是跟手的缩放
504    pub delta: f32,
505    /// 元素自己的坐标(双指中心:触控板是指针的位置,触摸屏是两根手指的中点)
506    pub position: [f32; 2],
507    /// 同一位置的窗口坐标,逻辑像素
508    pub window_position: [f32; 2],
509    pub(crate) flow: Flow,
510}
511
512/// 旋转(触控板、触摸屏上两根手指),见 [`crate::Element::on_rotate`]。正值顺时针(和 [`crate::Element::rotation`] 一致)。
513/// `Start` 的传播和争手势同 [`DragEvent`]
514#[derive(Clone, Debug, PartialEq)]
515pub struct RotateEvent {
516    /// 进行到哪一步
517    pub phase: GesturePhase,
518    /// 从手势开始到现在转过的角度
519    pub rotation: Angle,
520    /// 这一次转过的角度
521    pub delta: Angle,
522    /// 元素自己的坐标(双指中心:触控板是指针的位置,触摸屏是两根手指的中点)
523    pub position: [f32; 2],
524    /// 同一位置的窗口坐标,逻辑像素
525    pub window_position: [f32; 2],
526    pub(crate) flow: Flow,
527}
528
529impl PinchEvent {
530    pub(crate) fn new(phase: GesturePhase, scale: f32, delta: f32, window_position: [f32; 2]) -> Self {
531        Self { phase, scale, delta, position: window_position, window_position, flow: Flow::default() }
532    }
533}
534
535impl RotateEvent {
536    pub(crate) fn new(phase: GesturePhase, rotation: Angle, delta: Angle, window_position: [f32; 2]) -> Self {
537        Self { phase, rotation, delta, position: window_position, window_position, flow: Flow::default() }
538    }
539}
540
541/// 从系统拖进来的文件放下,见 [`crate::Element::on_file_drop`]
542#[derive(Clone, Debug, PartialEq)]
543pub struct FileDropEvent {
544    /// 放下的文件
545    pub paths: Vec<PathBuf>,
546    /// 元素自己的坐标
547    pub position: [f32; 2],
548    /// 窗口坐标,逻辑像素
549    pub window_position: [f32; 2],
550}
551
552bitflags::bitflags! {
553    /// 别的应用拖来的内容有哪几种,见 [`crate::Element::on_external_drag_over`]。有文件时只算文件(访达拖文件时也带着文件名的文字)
554    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
555    pub struct ExternalDataKinds: u8 {
556        /// 文字
557        const TEXT = 1;
558        /// 链接
559        const LINK = 1 << 1;
560        /// 图片
561        const IMAGE = 1 << 2;
562        /// 文件
563        const FILES = 1 << 3;
564        /// 带格式的文字
565        const RICH_TEXT = 1 << 4;
566        /// 应用登记过的自己定的格式(`accept_drop_format`)里至少有一种
567        const CUSTOM = 1 << 5;
568    }
569}
570
571/// 接受拖来的内容算什么操作:系统按它显示光标,也告诉拖动的来源。来源不许这种操作时换一种它许的
572#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
573#[non_exhaustive]
574pub enum ExternalDropEffect {
575    /// 拷贝(默认)
576    #[default]
577    Copy,
578    /// 移动:来源可能删掉原来的
579    Move,
580    /// 建链接
581    Link,
582}
583
584/// 别的应用拖来的内容经过元素、离开元素,见 [`crate::Element::on_external_drag_over`]
585#[derive(Clone, Debug, PartialEq)]
586pub struct ExternalDragEvent {
587    /// 内容有哪几种。放下之前读不到内容本身
588    pub kinds: ExternalDataKinds,
589    /// 元素自己的坐标
590    pub position: [f32; 2],
591    /// 窗口坐标,逻辑像素
592    pub window_position: [f32; 2],
593    pub(crate) effect: Cell<Option<ExternalDropEffect>>,
594}
595
596impl ExternalDragEvent {
597    pub(crate) fn new(kinds: ExternalDataKinds, position: [f32; 2], window_position: [f32; 2]) -> Self {
598        Self { kinds, position, window_position, effect: Cell::new(None) }
599    }
600
601    /// 接受(算拷贝):系统显示能放下的光标,放下时这个元素收到 [`crate::Element::on_external_drop`]。
602    /// 不调用就是不接受,接着问外面一层的元素
603    pub fn accept(&self) {
604        self.effect.set(Some(ExternalDropEffect::Copy));
605    }
606
607    /// 接受,并且说明算什么操作(光标不一样)
608    pub fn accept_with(&self, effect: ExternalDropEffect) {
609        self.effect.set(Some(effect));
610    }
611
612    /// 已经接受了
613    pub fn is_accepted(&self) -> bool {
614        self.effect.get().is_some()
615    }
616}
617
618/// 别的应用拖来、放下的内容,从哪里来都一样:系统的拖放(见 [`crate::Element::on_external_drop`]),测试工具也用它模拟
619#[derive(Clone, Debug, Default, PartialEq)]
620pub struct ExternalDropData {
621    /// 文字
622    pub text: Option<String>,
623    /// 链接(网址)
624    pub link: Option<String>,
625    /// 图片,能直接给 [`crate::image()`]
626    pub image: Option<RgbaImage>,
627    /// 文件
628    pub files: Vec<PathBuf>,
629    /// 带格式的文字;空的是没有
630    pub rich_text: Vec<SpanInfo>,
631    /// 应用登记过的自己定的格式里拖来了的:格式名和原样的字节,见 [`ExternalDropData::custom`]
632    pub custom: Vec<(String, Vec<u8>)>,
633}
634
635impl ExternalDropData {
636    /// 里面有哪几种内容
637    pub fn kinds(&self) -> ExternalDataKinds {
638        let mut kinds = ExternalDataKinds::empty();
639        kinds.set(ExternalDataKinds::TEXT, self.text.is_some());
640        kinds.set(ExternalDataKinds::LINK, self.link.is_some());
641        kinds.set(ExternalDataKinds::IMAGE, self.image.is_some());
642        kinds.set(ExternalDataKinds::FILES, !self.files.is_empty());
643        kinds.set(ExternalDataKinds::RICH_TEXT, !self.rich_text.is_empty());
644        kinds.set(ExternalDataKinds::CUSTOM, !self.custom.is_empty());
645        kinds
646    }
647
648    /// 应用自己定的格式 `format` 的字节;没拖来这种格式(或者没登记过)时是 `None`
649    pub fn custom(&self, format: &str) -> Option<&[u8]> {
650        custom_of(&self.custom, format)
651    }
652}
653
654fn custom_of<'a>(custom: &'a [(String, Vec<u8>)], format: &str) -> Option<&'a [u8]> {
655    custom.iter().find(|(name, _)| name == format).map(|(_, bytes)| bytes.as_slice())
656}
657
658/// 别的应用拖来的内容放下了,见 [`crate::Element::on_external_drop`]
659#[derive(Clone, Debug, PartialEq)]
660pub struct ExternalDropEvent {
661    /// 文字
662    pub text: Option<String>,
663    /// 链接(网址)
664    pub link: Option<String>,
665    /// 图片,能直接给 [`crate::image()`]
666    pub image: Option<RgbaImage>,
667    /// 文件
668    pub files: Vec<PathBuf>,
669    /// 带格式的文字;空的是没有
670    pub rich_text: Vec<SpanInfo>,
671    /// 应用登记过的自己定的格式里拖来了的,见 [`ExternalDropEvent::custom`]
672    pub custom: Vec<(String, Vec<u8>)>,
673    /// 元素自己的坐标
674    pub position: [f32; 2],
675    /// 窗口坐标,逻辑像素
676    pub window_position: [f32; 2],
677}
678
679impl ExternalDropEvent {
680    /// 应用自己定的格式 `format` 的字节(要先用 `aureole::accept_drop_format` 登记);没拖来这种格式时是 `None`
681    pub fn custom(&self, format: &str) -> Option<&[u8]> {
682        custom_of(&self.custom, format)
683    }
684}
685
686// ---- 改值 ----
687
688/// 值是怎么被用户改的(改值事件只在用户改动时发,代码里改绑定的信号不发)
689#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
690#[non_exhaustive]
691pub enum ChangeSource {
692    /// 指针:点、拖
693    #[default]
694    Pointer,
695    /// 键盘:打字、删除、粘贴、撤销、输入法提交,方向键、回车、空格
696    Keyboard,
697    /// 辅助技术要求改值
698    Accessibility,
699    /// 点了它的标签
700    Label,
701}
702
703impl From<ClickSource> for ChangeSource {
704    fn from(activation: ClickSource) -> Self {
705        match activation {
706            ClickSource::Pointer => Self::Pointer,
707            ClickSource::Keyboard => Self::Keyboard,
708            ClickSource::Accessibility => Self::Accessibility,
709            ClickSource::Label => Self::Label,
710        }
711    }
712}
713
714/// 改值事件:输入框和有值的基础控件的 `on_change`(用户每改一次)、`on_commit`(改完了)。只发给控件自己,不冒泡。
715/// 处理器可以只收值(`|v| ..`),也可以收整个事件(`|e: &ChangeEvent<bool>| ..`,带着是怎么改的),见 [`IntoChangeHandler`]
716#[derive(Clone, Debug, PartialEq)]
717pub struct ChangeEvent<T> {
718    /// 新的值
719    pub value: T,
720    /// 怎么改的
721    pub source: ChangeSource,
722}
723
724/// 表单级的改值事件里新值的描述([`FieldChangeEvent::value`]):各种控件的值的类型不一样,这里统一成几种。
725/// 显示出来(`{}`)是值本身的文字:`true`、`0.6`、输入框的内容、选项的文字
726#[derive(Clone, Debug, PartialEq)]
727#[non_exhaustive]
728pub enum FieldValue {
729    /// 开关量:复选框、开关
730    Bool(bool),
731    /// 数:滑块、数字输入
732    Number(f64),
733    /// 文字:输入框、多行输入框
734    Text(String),
735    /// 密码框:不带内容(要内容用它自己的 `on_change`),免得汇总到表单的日志里
736    Secret,
737    /// 选项:单选组、下拉选择。第几项(从 0 开始)和它显示的文字
738    Choice {
739        /// 第几项
740        index: usize,
741        /// 显示的文字
742        text: String,
743    },
744}
745
746impl std::fmt::Display for FieldValue {
747    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748        match self {
749            Self::Bool(v) => write!(f, "{v}"),
750            Self::Number(v) => write!(f, "{v}"),
751            Self::Text(v) => f.write_str(v),
752            Self::Secret => f.write_str("••••"),
753            Self::Choice { text, .. } => f.write_str(text),
754        }
755    }
756}
757
758/// 表单级的改值事件([`crate::Element::on_field_change`]):一个控件的值被用户改了,从控件往外冒泡
759/// (沿逻辑父元素,模态浮层是边界),容器上能收到里面任何控件的改动。代码里改绑定的信号时不发。
760///
761/// 控件自己的 `on_change`、`on_commit` 照旧只发给控件自己;这一个是给表单用的
762#[derive(Clone, Debug)]
763pub struct FieldChangeEvent {
764    /// 控件的名字(`.name(..)`);没起名字时是 `None`
765    pub name: Option<String>,
766    /// 控件的焦点句柄(交给控件、或者控件里面的输入框的那个);没给时是 `None`
767    pub focus_handle: Option<FocusHandle>,
768    /// 新的值
769    pub value: FieldValue,
770    /// 怎么改的
771    pub source: ChangeSource,
772    pub(crate) flow: Flow,
773}
774
775/// 改值事件的处理器:只收值(`Fn(T)`)或者收整个事件(`Fn(&ChangeEvent<T>)`),返回值丢掉。
776///
777/// 只收值的闭包,参数的用法定下了类型时(传给收这个类型的函数、写进同类型的信号)不用写类型;
778/// 只拿去打印、格式化时要写出来:`|v: f32| println!("{v}")`
779pub trait IntoChangeHandler<T, Marker> {
780    /// 转成收事件引用的处理器,在创建控件时的作用域里执行
781    #[allow(clippy::type_complexity, reason = "处理器的类型就是这样,起个别名反而要多找一处")]
782    fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)>;
783}
784
785impl<T: Clone + 'static, R, F: Fn(T) -> R + 'static> IntoChangeHandler<T, fn(T) -> R> for F {
786    fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)> {
787        IntoHandler::<ChangeEvent<T>, fn(&ChangeEvent<T>)>::into_handler(move |e: &ChangeEvent<T>| {
788            self(e.value.clone());
789        })
790    }
791}
792
793impl<T: 'static, R, F: Fn(&ChangeEvent<T>) -> R + 'static> IntoChangeHandler<T, fn(&ChangeEvent<T>) -> R> for F {
794    fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)> {
795        IntoHandler::<ChangeEvent<T>, fn(&ChangeEvent<T>)>::into_handler(move |e: &ChangeEvent<T>| {
796            self(e);
797        })
798    }
799}
800
801// ---- 处理器的两种写法 ----
802
803/// 处理器:收事件对象(`|e: &ClickEvent| ..`)或者不带参数(`|| ..`)的闭包,返回值丢掉。
804///
805/// 收事件对象的闭包要写出参数的类型:同一个方法接受两种闭包,编译器不能从方法上推断出参数的类型
806pub trait IntoHandler<E, Marker> {
807    /// 转成收事件对象引用的处理器,在创建元素时的作用域里执行
808    fn into_handler(self) -> Rc<dyn Fn(&E)>;
809}
810
811impl<E: 'static, R, F: Fn() -> R + 'static> IntoHandler<E, fn() -> R> for F {
812    fn into_handler(self) -> Rc<dyn Fn(&E)> {
813        match Scope::current() {
814            Some(scope) => Rc::new(move |_: &E| {
815                scope.run(|| {
816                    self();
817                })
818            }),
819            None => Rc::new(move |_: &E| {
820                self();
821            }),
822        }
823    }
824}
825
826impl<E: 'static, R, F: Fn(&E) -> R + 'static> IntoHandler<E, fn(&E) -> R> for F {
827    fn into_handler(self) -> Rc<dyn Fn(&E)> {
828        match Scope::current() {
829            Some(scope) => Rc::new(move |e: &E| {
830                scope.run(|| {
831                    self(e);
832                })
833            }),
834            None => Rc::new(move |e: &E| {
835                self(e);
836            }),
837        }
838    }
839}