cranpose 0.24.0

Build desktop, mobile and web apps with composable Rust functions
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use cranpose_app_shell::{AppShell, PointerSource};
use cranpose_platform_android::AndroidPlatform;
use cranpose_render_wgpu::WgpuRenderer;
use cranpose_ui::{PointerButton, PointerId};

use super::keyboard::AndroidKeyTranslator;

pub(super) enum PendingInput {
    PointerDown(f32, f32, Option<i64>, PointerSource),
    PointerUp(f32, f32, Option<i64>, PointerSource),
    PointerMove(f32, f32, Option<i64>, PointerSource),
    PointerCancel,
    HoverExit,
    SecondaryPointerDown(PointerId, f32, f32, Option<i64>),
    SecondaryPointerUp(PointerId, f32, f32, Option<i64>),
    SecondaryPointerMove(PointerId, f32, f32, Option<i64>),
    RotaryScroll(f32, u64),
    /// A mouse button other than the primary one went down (`true`) or up,
    /// with the pointer at a position.
    MouseButton(PointerButton, bool, f32, f32),
}

fn android_event_time_ms(event_time_ns: i64) -> i64 {
    event_time_ns / 1_000_000
}

fn android_pointer_source(
    pointer: &android_activity::input::Pointer<'_>,
    event_source: android_activity::input::Source,
) -> PointerSource {
    use android_activity::input::{Source, ToolType};

    use crate::android_input::{AndroidSourceKind, AndroidToolKind, resolve_pointer_source};

    let tool = match pointer.tool_type() {
        ToolType::Finger => AndroidToolKind::Finger,
        ToolType::Mouse => AndroidToolKind::Mouse,
        ToolType::Stylus | ToolType::Eraser => AndroidToolKind::Stylus,
        _ => AndroidToolKind::Indeterminate,
    };
    let source = match event_source {
        Source::Touchscreen => AndroidSourceKind::Touchscreen,
        Source::Stylus | Source::BluetoothStylus => AndroidSourceKind::Stylus,
        Source::Mouse | Source::MouseRelative => AndroidSourceKind::Mouse,
        _ => AndroidSourceKind::Other,
    };
    resolve_pointer_source(tool, source)
}

// Hands a key to `shell` at once, after the inputs queued before it, and
// answers whether Cranpose took it, as Compose's `dispatchKeyEvent` does:
// a key no handler took goes back to Android, which plays a media key in
// the media session, changes the volume or leaves the app. A Back that no
// handler took goes to the `BackHandler`s when one is composed.
fn dispatch_android_key_event(
    app: &android_activity::AndroidApp,
    key_event: &android_activity::input::KeyEvent<'_>,
    key_translator: &mut AndroidKeyTranslator,
    pending_inputs: &mut Vec<PendingInput>,
    shell: Option<&mut AppShell<WgpuRenderer>>,
) -> bool {
    let consumed = match (shell, key_translator.translate(key_event)) {
        (Some(shell), Some(event)) => {
            dispatch_pending_inputs(app, shell, pending_inputs);
            shell.on_key_event(&event)
        }
        _ => false,
    };
    consumed
        || (key_event.key_code() == android_activity::input::Keycode::Back
            && take_back_key(key_event))
}

fn take_back_key(key_event: &android_activity::input::KeyEvent<'_>) -> bool {
    if !cranpose_services::back_interception_enabled() {
        return false;
    }
    if key_event.action() == android_activity::input::KeyAction::Up {
        cranpose_services::push_back_request();
    }
    true
}

fn shell_pointer_id(android_pointer_id: i32, primary_pointer_id: i32) -> PointerId {
    if android_pointer_id == primary_pointer_id {
        PointerId::PRIMARY
    } else {
        PointerId(android_pointer_id as u64 + 1)
    }
}

fn push_pending_inputs_from_android_event(
    event: &android_activity::input::InputEvent<'_>,
    android_platform: &AndroidPlatform,
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) -> bool {
    let android_activity::input::InputEvent::MotionEvent(motion_event) = event else {
        return false;
    };

    let time_ms = Some(android_event_time_ms(motion_event.event_time()));
    let event_source = motion_event.source();
    let logical_of = |x: f32, y: f32| {
        let logical = android_platform.pointer_position(x as f64, y as f64);
        (logical.x, logical.y)
    };

    match motion_event.action() {
        android_activity::input::MotionAction::Down => {
            let pointer = motion_event.pointer_at_index(0);
            *primary_pointer_id = Some(pointer.pointer_id());
            let (x, y) = logical_of(pointer.x(), pointer.y());
            pending_inputs.push(PendingInput::PointerDown(
                x,
                y,
                time_ms,
                android_pointer_source(&pointer, event_source),
            ));
            true
        }
        android_activity::input::MotionAction::PointerDown => {
            let pointer = motion_event.pointer_at_index(motion_event.pointer_index());
            let Some(primary) = *primary_pointer_id else {
                return true;
            };
            let (x, y) = logical_of(pointer.x(), pointer.y());
            pending_inputs.push(PendingInput::SecondaryPointerDown(
                shell_pointer_id(pointer.pointer_id(), primary),
                x,
                y,
                time_ms,
            ));
            true
        }
        android_activity::input::MotionAction::Up => push_final_release(
            motion_event,
            event_source,
            time_ms,
            logical_of,
            pending_inputs,
            primary_pointer_id,
        ),
        android_activity::input::MotionAction::PointerUp => push_pointer_release(
            motion_event,
            event_source,
            time_ms,
            logical_of,
            pending_inputs,
            primary_pointer_id,
        ),
        android_activity::input::MotionAction::Move => push_pointer_move(
            motion_event,
            event_source,
            time_ms,
            logical_of,
            pending_inputs,
            primary_pointer_id,
        ),
        android_activity::input::MotionAction::Cancel => {
            pending_inputs.push(PendingInput::PointerCancel);
            *primary_pointer_id = None;
            true
        }
        _ => push_hover_or_scroll(motion_event, android_platform, time_ms, pending_inputs),
    }
}

fn push_hover_or_scroll(
    event: &android_activity::input::MotionEvent<'_>,
    platform: &AndroidPlatform,
    time_ms: Option<i64>,
    pending: &mut Vec<PendingInput>,
) -> bool {
    use android_activity::input::MotionAction;
    match event.action() {
        MotionAction::HoverEnter | MotionAction::HoverMove => {
            if let Some(pointer) = event.pointers().next() {
                let position =
                    platform.pointer_position(f64::from(pointer.x()), f64::from(pointer.y()));
                pending.push(PendingInput::PointerMove(
                    position.x,
                    position.y,
                    time_ms,
                    android_pointer_source(&pointer, event.source()),
                ));
            }
            true
        }
        MotionAction::HoverExit => {
            pending.push(PendingInput::HoverExit);
            true
        }
        MotionAction::Scroll => push_rotary_pending_input(event, event.source(), time_ms, pending),
        _ => false,
    }
}

fn push_final_release(
    motion_event: &android_activity::input::MotionEvent<'_>,
    event_source: android_activity::input::Source,
    time_ms: Option<i64>,
    logical_of: impl Fn(f32, f32) -> (f32, f32),
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) -> bool {
    let pointer = motion_event.pointer_at_index(motion_event.pointer_index());
    let (x, y) = logical_of(pointer.x(), pointer.y());
    match *primary_pointer_id {
        Some(primary) if pointer.pointer_id() != primary => {
            pending_inputs.push(PendingInput::SecondaryPointerUp(
                shell_pointer_id(pointer.pointer_id(), primary),
                x,
                y,
                time_ms,
            ));
        }
        _ => {}
    }
    pending_inputs.push(PendingInput::PointerUp(
        x,
        y,
        time_ms,
        android_pointer_source(&pointer, event_source),
    ));
    *primary_pointer_id = None;
    true
}

fn push_pointer_release(
    motion_event: &android_activity::input::MotionEvent<'_>,
    event_source: android_activity::input::Source,
    time_ms: Option<i64>,
    logical_of: impl Fn(f32, f32) -> (f32, f32),
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) -> bool {
    let pointer = motion_event.pointer_at_index(motion_event.pointer_index());
    let Some(primary) = *primary_pointer_id else {
        return true;
    };
    let (x, y) = logical_of(pointer.x(), pointer.y());
    if pointer.pointer_id() == primary {
        for other in motion_event.pointers() {
            if other.pointer_id() == primary {
                continue;
            }
            let (ox, oy) = logical_of(other.x(), other.y());
            pending_inputs.push(PendingInput::SecondaryPointerUp(
                shell_pointer_id(other.pointer_id(), primary),
                ox,
                oy,
                time_ms,
            ));
        }
        pending_inputs.push(PendingInput::PointerUp(
            x,
            y,
            time_ms,
            android_pointer_source(&pointer, event_source),
        ));
        *primary_pointer_id = None;
    } else {
        pending_inputs.push(PendingInput::SecondaryPointerUp(
            shell_pointer_id(pointer.pointer_id(), primary),
            x,
            y,
            time_ms,
        ));
    }
    true
}

fn push_pointer_move(
    motion_event: &android_activity::input::MotionEvent<'_>,
    event_source: android_activity::input::Source,
    time_ms: Option<i64>,
    logical_of: impl Fn(f32, f32) -> (f32, f32),
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) -> bool {
    let primary = *primary_pointer_id;
    for pointer in motion_event.pointers() {
        let is_primary = primary == Some(pointer.pointer_id());
        let source = android_pointer_source(&pointer, event_source);
        if is_primary {
            for historical in pointer.history() {
                let (hx, hy) = logical_of(historical.x(), historical.y());
                pending_inputs.push(PendingInput::PointerMove(
                    hx,
                    hy,
                    Some(android_event_time_ms(historical.event_time())),
                    source,
                ));
            }
        }
        let (x, y) = logical_of(pointer.x(), pointer.y());
        match (is_primary, primary) {
            (true, _) => {
                pending_inputs.push(PendingInput::PointerMove(x, y, time_ms, source));
            }
            (false, Some(primary)) => {
                pending_inputs.push(PendingInput::SecondaryPointerMove(
                    shell_pointer_id(pointer.pointer_id(), primary),
                    x,
                    y,
                    time_ms,
                ));
            }
            (false, None) => {}
        }
    }
    true
}

fn push_rotary_pending_input(
    motion_event: &android_activity::input::MotionEvent<'_>,
    event_source: android_activity::input::Source,
    time_ms: Option<i64>,
    pending_inputs: &mut Vec<PendingInput>,
) -> bool {
    use crate::android_input::is_rotary_encoder_source;

    if !is_rotary_encoder_source(u32::from(event_source)) {
        return false;
    }

    let Some(pointer) = motion_event.pointers().next() else {
        return true;
    };
    let detents = pointer.axis_value(android_activity::input::Axis::Scroll);
    if !detents.is_finite() || detents == 0.0 {
        return true;
    }

    pending_inputs.push(PendingInput::RotaryScroll(
        detents,
        time_ms.unwrap_or(0).max(0) as u64,
    ));
    true
}

// What the loop keeps of Android's input between frames: the pointer input
// waiting for the frame, and the state that reads key and pointer events.
pub(super) struct AndroidInput {
    pub(super) pending: Vec<PendingInput>,
    key_translator: AndroidKeyTranslator,
    primary_pointer_id: Option<i32>,
    mouse_buttons: android_activity::input::ButtonState,
}

impl AndroidInput {
    pub(super) fn new(app: android_activity::AndroidApp) -> Self {
        Self {
            pending: Vec::new(),
            key_translator: AndroidKeyTranslator::new(app),
            primary_pointer_id: None,
            mouse_buttons: android_activity::input::ButtonState(0),
        }
    }

    // Takes Android's queued input: keys go to `shell` at once, so Android
    // hears which ones Cranpose took, and pointer input waits in `pending`
    // for the frame. A key that reached the shell raises the frame rate as
    // pointer input does.
    pub(super) fn drain(
        &mut self,
        app: &android_activity::AndroidApp,
        android_platform: &AndroidPlatform,
        mut shell: Option<&mut AppShell<WgpuRenderer>>,
        frame_rate_boost: &mut cranpose_app_shell::FrameRateBoost,
    ) {
        let Ok(mut iter) = app.input_events_iter() else {
            return;
        };
        for _ in 0..MAX_ANDROID_INPUT_EVENTS_PER_POLL {
            let event_available = iter.next(|event| {
                let handled = match event {
                    android_activity::input::InputEvent::KeyEvent(key_event) => {
                        if shell.is_some() {
                            frame_rate_boost.note_input(std::time::Instant::now());
                        }
                        dispatch_android_key_event(
                            app,
                            key_event,
                            &mut self.key_translator,
                            &mut self.pending,
                            shell.as_deref_mut(),
                        )
                    }
                    _ => {
                        push_mouse_button_inputs(
                            event,
                            android_platform,
                            &mut self.pending,
                            &mut self.primary_pointer_id,
                            &mut self.mouse_buttons,
                        ) || push_pending_inputs_from_android_event(
                            event,
                            android_platform,
                            &mut self.pending,
                            &mut self.primary_pointer_id,
                        )
                    }
                };
                if handled {
                    android_activity::InputStatus::Handled
                } else {
                    android_activity::InputStatus::Unhandled
                }
            });
            if !event_available {
                break;
            }
        }
    }
}

const MAX_ANDROID_INPUT_EVENTS_PER_POLL: usize = 10;

/// Takes a mouse's events that the path for fingers would read wrongly.
/// Android sends a press of the right or middle button alone as `Down`, the
/// moves of a drag with no primary button as `Move`, and every button's
/// change as `ButtonPress` or `ButtonRelease`. The primary button presses at
/// `Down`, or at its `ButtonPress` after another button; it releases at its
/// `ButtonRelease`, or at `Up` on a device that sends none. The other buttons
/// press and release as the shell's other mouse buttons. Returns whether it
/// took the event.
///
/// The button a press or release changed is the one `mouse_buttons`, the
/// buttons the last mouse event held, gains or loses: Android's
/// `AMotionEvent_getActionButton` arrived in API 33, and a library that
/// calls it does not load on an older device.
fn push_mouse_button_inputs(
    event: &android_activity::input::InputEvent<'_>,
    android_platform: &AndroidPlatform,
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
    mouse_buttons: &mut android_activity::input::ButtonState,
) -> bool {
    use android_activity::input::{Button, InputEvent, MotionAction, ToolType};

    let InputEvent::MotionEvent(motion_event) = event else {
        return false;
    };
    let Some(pointer) = motion_event.pointers().next() else {
        return false;
    };
    if pointer.tool_type() != ToolType::Mouse {
        return false;
    }
    let at = android_platform.pointer_position(f64::from(pointer.x()), f64::from(pointer.y()));
    let time_ms = Some(android_event_time_ms(motion_event.event_time()));
    let held = motion_event.button_state();
    let before = std::mem::replace(mouse_buttons, held);
    match motion_event.action() {
        MotionAction::Down => held.0 != 0 && !held.primary(),
        MotionAction::Move if primary_pointer_id.is_none() => {
            pending_inputs.push(PendingInput::PointerMove(
                at.x,
                at.y,
                time_ms,
                PointerSource::Mouse,
            ));
            true
        }
        MotionAction::Up => primary_pointer_id.is_none(),
        action @ (MotionAction::ButtonPress | MotionAction::ButtonRelease) => {
            let pressed = action == MotionAction::ButtonPress;
            let mut changed = if pressed {
                held.0 & !before.0
            } else {
                before.0 & !held.0
            };
            while changed != 0 {
                let bit = 1 << changed.trailing_zeros();
                changed &= !bit;
                match shell_mouse_button(Button::from(bit)) {
                    Some(PointerButton::Primary) => match (pressed, *primary_pointer_id) {
                        (true, None) => {
                            *primary_pointer_id = Some(pointer.pointer_id());
                            pending_inputs.push(PendingInput::PointerDown(
                                at.x,
                                at.y,
                                time_ms,
                                PointerSource::Mouse,
                            ));
                        }
                        (false, Some(_)) => {
                            *primary_pointer_id = None;
                            pending_inputs.push(PendingInput::PointerUp(
                                at.x,
                                at.y,
                                time_ms,
                                PointerSource::Mouse,
                            ));
                        }
                        _ => {}
                    },
                    Some(button) => {
                        pending_inputs.push(PendingInput::MouseButton(button, pressed, at.x, at.y));
                    }
                    None => {}
                }
            }
            true
        }
        _ => false,
    }
}

fn shell_mouse_button(button: android_activity::input::Button) -> Option<PointerButton> {
    use android_activity::input::Button;

    match button {
        Button::Primary => Some(PointerButton::Primary),
        Button::Secondary => Some(PointerButton::Secondary),
        Button::Tertiary => Some(PointerButton::Middle),
        Button::Back => Some(PointerButton::Back),
        Button::Forward => Some(PointerButton::Forward),
        _ => None,
    }
}

/// Sends one input taken from Android's queue to `shell`.
fn dispatch_pending_input(shell: &mut AppShell<WgpuRenderer>, input: PendingInput) {
    match input {
        PendingInput::PointerDown(x, y, time_ms, source) => {
            shell.set_pointer_source(source);
            let event_time = shell.realtime_pointer_event_time(time_ms);
            shell.set_cursor_at_event_time(x, y, event_time);
            shell.pointer_pressed_at_event_time(event_time);
        }
        PendingInput::PointerUp(x, y, time_ms, source) => {
            shell.set_pointer_source(source);
            let event_time = shell.realtime_pointer_event_time(time_ms);
            shell.pointer_released_at_position_event_time(x, y, event_time);
        }
        PendingInput::PointerMove(x, y, time_ms, source) => {
            shell.set_pointer_source(source);
            let event_time = shell.realtime_pointer_event_time(time_ms);
            shell.set_cursor_at_event_time(x, y, event_time);
        }
        PendingInput::PointerCancel => {
            shell.cancel_gesture();
        }
        PendingInput::HoverExit => {
            shell.cancel_gesture_unless_pressed();
        }
        PendingInput::SecondaryPointerDown(id, x, y, time_ms) => {
            shell.set_pointer_source(PointerSource::Touch);
            shell.secondary_pointer_pressed(id, x, y, time_ms);
        }
        PendingInput::SecondaryPointerUp(id, x, y, time_ms) => {
            shell.set_pointer_source(PointerSource::Touch);
            shell.secondary_pointer_released(id, x, y, time_ms);
        }
        PendingInput::SecondaryPointerMove(id, x, y, time_ms) => {
            shell.set_pointer_source(PointerSource::Touch);
            shell.secondary_pointer_moved(id, x, y, time_ms);
        }
        PendingInput::RotaryScroll(detents, uptime_ms) => {
            shell.rotary_scrolled_by_detents(detents, uptime_ms);
        }
        PendingInput::MouseButton(button, pressed, x, y) => {
            shell.set_pointer_source(PointerSource::Mouse);
            shell.set_cursor(x, y);
            let mut surface = shell.primary();
            if pressed {
                surface.mouse_button_pressed(button);
            } else {
                surface.mouse_button_released(button);
            }
        }
    }
}

pub(super) fn dispatch_pending_inputs(
    app: &android_activity::AndroidApp,
    shell: &mut AppShell<WgpuRenderer>,
    pending: &mut Vec<PendingInput>,
) {
    for input in pending.drain(..) {
        dispatch_pending_input(shell, input);
    }
    if let Some(icon) = shell.take_pointer_icon_change() {
        super::pointer_icon::apply(app, &icon);
    }
}