ragnarok 0.1.0

UI Events processor. Originally made for Freya but works for other libraries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#![allow(dead_code)]

use std::collections::{
    HashMap,
    HashSet,
};

use ragnarok::{
    Area,
    CursorPoint,
    EmmitableEvent,
    EventsExecutor,
    EventsMeasurer,
    NameOfEvent,
    NodesState,
    SourceEvent,
};

#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
enum EventName {
    MouseEnter,
    MouseMove,
    MouseLeave,
    MouseDown,
    MouseUp,

    KeyboardDown,
}

impl NameOfEvent for EventName {
    fn is_moved(&self) -> bool {
        matches!(self, Self::MouseMove)
    }

    fn is_enter(&self) -> bool {
        matches!(self, Self::MouseEnter)
    }

    fn is_pressed(&self) -> bool {
        matches!(self, Self::MouseDown)
    }

    fn is_released(&self) -> bool {
        matches!(self, Self::MouseUp)
    }

    fn is_global(&self) -> bool {
        false
    }

    fn does_bubble(&self) -> bool {
        !matches!(self, Self::MouseLeave)
    }

    fn does_go_through_solid(&self) -> bool {
        true
    }

    fn new_leave() -> Self {
        Self::MouseLeave
    }

    fn get_derived_events(&self) -> Vec<Self> {
        let mut events = vec![*self];
        #[allow(clippy::single_match)]
        match self {
            Self::MouseMove => events.push(Self::MouseEnter),
            _ => {}
        }

        events
    }
}

#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, PartialEq, Debug)]
enum TestSourceEvent {
    MouseDown { cursor: CursorPoint },
    MouseMove { cursor: CursorPoint },
    MouseUp { cursor: CursorPoint },
}

impl SourceEvent for TestSourceEvent {
    type Name = EventName;

    fn is_pressed(&self) -> bool {
        matches!(self, Self::MouseDown { .. })
    }

    fn is_moved(&self) -> bool {
        matches!(self, Self::MouseMove { .. })
    }

    fn try_cursor(&self) -> Option<ragnarok::CursorPoint> {
        match self {
            Self::MouseDown { cursor } => Some(*cursor),
            Self::MouseMove { cursor } => Some(*cursor),
            Self::MouseUp { cursor } => Some(*cursor),
        }
    }

    fn as_event_name(&self) -> Self::Name {
        match self {
            Self::MouseMove { .. } => EventName::MouseMove,
            Self::MouseDown { .. } => EventName::MouseDown,
            Self::MouseUp { .. } => EventName::MouseUp,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
struct TestEmmitableEvent {
    key: usize,
    name: EventName,
    source: EventName,
}

impl Eq for TestEmmitableEvent {}

impl PartialOrd for TestEmmitableEvent {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for TestEmmitableEvent {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

impl EmmitableEvent for TestEmmitableEvent {
    type Key = usize;
    type Name = EventName;

    fn name(&self) -> Self::Name {
        self.name
    }

    fn source(&self) -> Self::Name {
        self.source
    }

    fn key(&self) -> Self::Key {
        self.key
    }
}

#[derive(Default)]
struct TestMeasurer {
    layers: HashMap<i16, Vec<usize>>,
    children: HashMap<usize, HashSet<usize>>,
    listeners: HashMap<EventName, Vec<usize>>,
    areas: HashMap<usize, Area>,
}

impl TestMeasurer {
    fn add(&mut self, id: usize, parent: Option<usize>, layer: i16, area: Area) {
        self.layers.entry(layer).or_default().push(id);
        if let Some(parent) = parent {
            self.children.entry(parent).or_default().insert(parent);
        }
        self.areas.insert(id, area);
    }

    fn listen_to(&mut self, id: usize, event: EventName) {
        self.listeners.entry(event).or_default().push(id);
    }
}

impl EventsMeasurer for TestMeasurer {
    type Name = EventName;

    type Key = usize;

    type Emmitable = TestEmmitableEvent;

    type Source = TestSourceEvent;

    fn get_layers(&self) -> std::collections::hash_map::Iter<'_, i16, Vec<Self::Key>> {
        self.layers.iter()
    }

    fn get_listeners_of(&self, name: &Self::Name) -> Vec<Self::Key> {
        self.listeners.get(name).unwrap().clone()
    }

    fn is_point_inside(&self, key: Self::Key, cursor: ragnarok::CursorPoint) -> bool {
        self.areas.get(&key).unwrap().contains(cursor.to_f32())
    }

    fn is_node_parent_of(&self, key: Self::Key, parent: Self::Key) -> bool {
        self.children.get(&parent).unwrap().contains(&key)
    }

    fn is_listening_to(&self, key: Self::Key, name: &Self::Name) -> bool {
        let Some(listeners) = self.listeners.get(name) else {
            return false;
        };
        listeners.contains(&key)
    }

    fn is_node_transparent(&self, _key: Self::Key) -> bool {
        false
    }

    fn try_area_of(&self, key: Self::Key) -> Option<ragnarok::Area> {
        self.areas.get(&key).cloned()
    }

    fn new_emmitable_event(
        &self,
        key: Self::Key,
        name: Self::Name,
        source: Self::Source,
        _area: Option<ragnarok::Area>,
    ) -> Self::Emmitable {
        TestEmmitableEvent {
            key,
            name,
            source: source.as_event_name(),
        }
    }
}

#[derive(Default)]
struct TestExecutor;

impl EventsExecutor for TestExecutor {
    type Emmitable = TestEmmitableEvent;
    type Key = usize;
    type Name = EventName;
    type Source = TestSourceEvent;

    fn emit_event(&self, _event: Self::Emmitable) -> bool {
        true
    }
}

#[test]
fn enter_leave_events() {
    let mut test_measurer = TestMeasurer::default();
    let mut nodes_state = NodesState::default();

    test_measurer.add(0, None, 0, Area::new((0., 0.).into(), (100., 100.).into()));
    test_measurer.listen_to(0, EventName::MouseEnter);
    test_measurer.listen_to(0, EventName::MouseLeave);

    // Move the mouse over the node a few times
    for i in 0..25 {
        let processed_events = test_measurer.measure(
            &mut vec![TestSourceEvent::MouseMove {
                cursor: (5. + i as f64, 5. + i as f64).into(),
            }],
            &mut nodes_state,
            None,
        );
        match i {
            0 => {
                // Assert an enter event is to be emitted
                assert_eq!(
                    processed_events.emmitable_events.first(),
                    Some(&TestEmmitableEvent {
                        key: 0,
                        name: EventName::MouseEnter,
                        source: EventName::MouseMove
                    })
                );
            }
            _ => {
                // No more enter events will be emitted as long as the mouse does not leave and enter again
                assert!(processed_events.emmitable_events.is_empty())
            }
        }
        // Apply the processed events
        TestExecutor.run(&mut nodes_state, processed_events);
        // Assert that the node is indeed being hovered
        assert!(nodes_state.is_hovered(0));
    }

    // Put the mouse outside the node
    let processed_events = test_measurer.measure(
        &mut vec![TestSourceEvent::MouseMove {
            cursor: (600., 700.).into(),
        }],
        &mut nodes_state,
        None,
    );

    // Assert a leave event is to be emitted
    assert_eq!(
        processed_events.emmitable_events.first(),
        Some(&TestEmmitableEvent {
            key: 0,
            name: EventName::MouseLeave,
            source: EventName::MouseMove
        })
    );
    // Apply the processed events
    TestExecutor.run(&mut nodes_state, processed_events);
    // Assert that the node is indeed not being hovered anymore
    assert!(!nodes_state.is_hovered(0));
}

#[test]
fn accurate_down_up_event() {
    let mut test_measurer = TestMeasurer::default();
    let mut nodes_state = NodesState::default();

    test_measurer.add(0, None, 0, Area::new((0., 0.).into(), (100., 100.).into()));
    test_measurer.listen_to(0, EventName::MouseDown);
    test_measurer.listen_to(0, EventName::MouseUp);

    let processed_events = test_measurer.measure(
        &mut vec![TestSourceEvent::MouseDown {
            cursor: (25., 25.).into(),
        }],
        &mut nodes_state,
        None,
    );

    // Assert an enter event is to be emitted
    assert_eq!(
        processed_events.emmitable_events.first(),
        Some(&TestEmmitableEvent {
            key: 0,
            name: EventName::MouseDown,
            source: EventName::MouseDown
        })
    );
    // Apply the processed events
    TestExecutor.run(&mut nodes_state, processed_events);
    // Assert that the node is indeed being pressed
    assert!(nodes_state.is_pressed(0));

    // Click outside the node
    let processed_events = test_measurer.measure(
        &mut vec![TestSourceEvent::MouseUp {
            cursor: (25., 25.).into(),
        }],
        &mut nodes_state,
        None,
    );

    // Assert a leave event is to be emitted
    assert_eq!(
        processed_events.emmitable_events.first(),
        Some(&TestEmmitableEvent {
            key: 0,
            name: EventName::MouseUp,
            source: EventName::MouseUp
        })
    );
    // Apply the processed events
    TestExecutor.run(&mut nodes_state, processed_events);
    // Assert that the node is indeed not being pressed anymore
    assert!(nodes_state.is_pressed(0));
}

#[test]
fn missed_up_event() {
    let mut test_measurer = TestMeasurer::default();
    let mut nodes_state = NodesState::default();

    test_measurer.add(0, None, 0, Area::new((0., 0.).into(), (100., 100.).into()));
    test_measurer.listen_to(0, EventName::MouseDown);
    test_measurer.listen_to(0, EventName::MouseUp);

    let processed_events = test_measurer.measure(
        &mut vec![TestSourceEvent::MouseDown {
            cursor: (25., 25.).into(),
        }],
        &mut nodes_state,
        None,
    );

    // Assert an enter event is to be emitted
    assert_eq!(
        processed_events.emmitable_events.first(),
        Some(&TestEmmitableEvent {
            key: 0,
            name: EventName::MouseDown,
            source: EventName::MouseDown
        })
    );
    // Apply the processed events
    TestExecutor.run(&mut nodes_state, processed_events);
    // Assert that the node is indeed being pressed
    assert!(nodes_state.is_pressed(0));

    // Click outside the node
    let processed_events = test_measurer.measure(
        &mut vec![TestSourceEvent::MouseUp {
            cursor: (600., 700.).into(),
        }],
        &mut nodes_state,
        None,
    );
    // Apply the processed events
    TestExecutor.run(&mut nodes_state, processed_events);
    // Assert that the node is indeed not being pressed anymore
    assert!(nodes_state.is_pressed(0));
}