cranpose 0.1.59

Cranpose runtime and UI facade
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
//! Android runtime for Compose applications.
//!
//! This module provides the Android event loop implementation with proper
//! lifecycle management, input handling, and rendering coordination.

use crate::{
    android_host_window,
    android_jni::{clear_pending_android_jni_exception, with_android_activity_env},
    android_keyboard::{self, is_system_key, AndroidKeyTranslator, AndroidSoftKeyboard},
    android_overlay_window,
    android_surface::{create_android_wgpu_surface, AndroidSurfaceError},
    android_text_input::{self, AndroidImeEvent},
    launcher::{AndroidOverlayWindowOptions, AppSettings},
    wgpu_surface::surface_present_required,
    wgpu_surface::{current_surface_texture, SurfaceFrame},
};
use cranpose_app_shell::{
    default_root_key, AppShell, KeyEvent, PlatformFrameDriver, PointerSource,
};
use cranpose_platform_android::AndroidPlatform;
use cranpose_render_wgpu::WgpuRenderer;
use cranpose_ui::{Point, Size};
use ndk::native_window::NativeWindow;
use std::time::{Duration, Instant};
use std::{
    cell::{Cell, RefCell},
    ffi::c_void,
    ptr::NonNull,
    rc::Rc,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

/// GPU resources for the current Android surface and its reusable WGPU device.
struct GpuResources {
    surface: wgpu::Surface<'static>,
    native_window_ptr: NonNull<c_void>,
    adapter: Arc<wgpu::Adapter>,
    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>,
    surface_format: wgpu::TextureFormat,
    backend: wgpu::Backend,
    config: wgpu::SurfaceConfiguration,
    _native_window: Option<NativeWindow>,
    /// Set when the surface is (re)created and cleared after a successful
    /// present, forcing the first frame to reach the screen even when `update()`
    /// reports no visual work (mirrors the desktop/web `surface_dirty` flag).
    surface_dirty: bool,
}

/// Pending input event to be processed outside poll_events callback.
/// This prevents blocking the main thread during input event acknowledgment.
///
/// Pointer variants carry the MotionEvent's own timestamp in milliseconds
/// (uptime clock). Android delivers touch input batched/frame-aligned, so
/// several samples are processed back-to-back in one loop iteration;
/// stamping them with the delivery time instead of the event time makes
/// gesture velocity computations wildly wrong (dt collapses to ~0).
enum PendingInput {
    PointerDown(f32, f32, Option<i64>, PointerSource),
    PointerUp(f32, f32, Option<i64>, PointerSource),
    PointerMove(f32, f32, Option<i64>, PointerSource),
    /// Translated key event (physical keyboard or soft-keyboard fallback
    /// input), routed to the focused text field via `AppShell::on_key_event`.
    Key(KeyEvent),
    /// Additional finger of a multi-touch gesture (pinch/zoom). The first
    /// field is the shell pointer id (never 0, which is the primary finger).
    SecondaryPointerDown(u64, f32, f32, Option<i64>),
    SecondaryPointerUp(u64, f32, f32, Option<i64>),
    SecondaryPointerMove(u64, f32, f32, Option<i64>),
}

/// Converts an Android event time (nanoseconds, `java.lang.System.nanoTime()`
/// base) into milliseconds for gesture velocity tracking.
fn android_event_time_ms(event_time_ns: i64) -> i64 {
    event_time_ns / 1_000_000
}

/// Maps an Android `MotionEvent` pointer onto the framework [`PointerSource`]
/// so text fields can show finger handles only for touch/stylus input.
///
/// The per-pointer tool type is the most specific signal, but many devices and
/// the Android emulator report `TOOL_TYPE_UNKNOWN` for genuine finger touches;
/// in that case the whole-event input source class (`getSource`) is consulted
/// so a touchscreen press is still stamped [`PointerSource::Touch`]. Without
/// this fallback the finger selection/cursor handles (touch-only) never appear.
fn android_pointer_source(
    pointer: &android_activity::input::Pointer<'_>,
    event_source: android_activity::input::Source,
) -> PointerSource {
    use crate::android_input::{resolve_pointer_source, AndroidSourceKind, AndroidToolKind};
    use android_activity::input::{Source, ToolType};

    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)
}

/// Translates one Android `KeyEvent` into a pending framework key event.
///
/// System keys (back, volume, media, ...) are reported as unhandled so the
/// platform keeps processing them. The back key is special: while the app has
/// back interception enabled (see [`cranpose_services::set_back_interception`])
/// it is consumed and forwarded to [`cranpose_services::push_back_request`],
/// mirroring Compose's `BackHandler`; otherwise it stays with the system so
/// the default leave-the-activity behavior keeps working. Returns `true` when
/// the event was consumed.
fn push_pending_input_from_android_key_event(
    key_event: &android_activity::input::KeyEvent<'_>,
    key_translator: &mut AndroidKeyTranslator,
    pending_inputs: &mut Vec<PendingInput>,
) -> bool {
    if key_event.key_code() == android_activity::input::Keycode::Back {
        if cranpose_services::back_interception_enabled() {
            // Act on key-up (Android convention) but consume the whole
            // down/up pair so the system never sees a half-handled back.
            if key_event.action() == android_activity::input::KeyAction::Up {
                cranpose_services::push_back_request();
            }
            return true;
        }
        return false;
    }
    if is_system_key(key_event.key_code()) {
        return false;
    }
    let Some(event) = key_translator.translate(key_event) else {
        return false;
    };
    pending_inputs.push(PendingInput::Key(event));
    true
}

thread_local! {
    /// Live platform environment (IME/safe-area insets in *logical* px, system
    /// theme) shared between the shell content wrapper — which provides the
    /// values to composition — and the event loop, which updates them from
    /// Java-forwarded keyboard heights, content-rect changes, and
    /// configuration changes.
    static ANDROID_PLATFORM_ENV: Rc<crate::platform_env::PlatformEnvironment> =
        crate::platform_env::PlatformEnvironment::new();
    /// Density used to convert Java's physical keyboard height to logical px.
    static ANDROID_IME_DENSITY: Cell<f32> = const { Cell::new(1.0) };
}

/// Shared handle to the live platform environment.
pub(crate) fn android_platform_env() -> Rc<crate::platform_env::PlatformEnvironment> {
    ANDROID_PLATFORM_ENV.with(Rc::clone)
}

/// Records the density used to convert the Java keyboard height to logical px.
fn set_android_ime_density(density: f32) {
    ANDROID_IME_DENSITY.with(|cell| cell.set(density.max(f32::EPSILON)));
}

/// Stores the keyboard's covered height (physical px, `0` when hidden) as
/// bottom IME insets in logical px. Returns whether the value changed.
fn set_android_ime_bottom_px(bottom_px: i32) -> bool {
    let density = ANDROID_IME_DENSITY.with(|cell| cell.get());
    let bottom = (bottom_px.max(0) as f32) / density;
    let insets = cranpose_ui::EdgeInsets {
        bottom,
        ..cranpose_ui::EdgeInsets::default()
    };
    android_platform_env().set_ime_insets(insets)
}

/// Maps the Android night-mode configuration onto the framework system theme.
fn system_theme_from_android(
    night: ndk::configuration::UiModeNight,
) -> cranpose_services::SystemTheme {
    match night {
        ndk::configuration::UiModeNight::Yes => cranpose_services::SystemTheme::Dark,
        _ => cranpose_services::SystemTheme::Light,
    }
}

/// `EditorInfo.IME_ACTION_DONE`: the user tapped the keyboard's Done action.
const IME_ACTION_DONE: i32 = 6;

/// Applies one editing operation forwarded by the Java `InputConnection`
/// (see [`crate::android_text_input`]) to the focused text field.
fn dispatch_android_ime_event(shell: &mut AppShell<WgpuRenderer>, event: AndroidImeEvent) {
    match event {
        AndroidImeEvent::CommitText { text, .. } => {
            // commitText replaces the composing text (if any); clearing the
            // preedit first deletes it, then the final text is inserted.
            // `new_cursor_position` values other than 1 are not honored yet;
            // the editor-state sync restarts the IME session if the cursor
            // ends up somewhere the IME did not expect.
            let _ = shell.on_ime_preedit("", None);
            let _ = shell.on_paste(&text);
        }
        AndroidImeEvent::SetComposingText { text, cursor_bytes } => {
            let _ = shell.on_ime_preedit(&text, Some((cursor_bytes, cursor_bytes)));
        }
        AndroidImeEvent::SetComposingRegion {
            start_bytes,
            end_bytes,
        } => {
            let _ = shell.on_ime_set_composing_region(start_bytes, end_bytes);
        }
        AndroidImeEvent::SetSelection {
            start_bytes,
            end_bytes,
        } => {
            let _ = shell.on_ime_set_selection(start_bytes, end_bytes);
        }
        AndroidImeEvent::FinishComposing => {
            let _ = shell.on_ime_finish_composing();
        }
        AndroidImeEvent::DeleteSurrounding {
            before_bytes,
            after_bytes,
        } => {
            let _ = shell.on_ime_delete_surrounding(before_bytes, after_bytes);
        }
        AndroidImeEvent::Key {
            action,
            key_code,
            meta_state,
            unicode_char,
        } => {
            if let Some(event) =
                android_keyboard::ime_key_event(action, key_code, meta_state, unicode_char)
            {
                let _ = shell.on_key_event(&event);
            }
        }
        AndroidImeEvent::EditorAction { action } => {
            // Done follows the platform convention of dismissing the
            // keyboard (focus stays in the field). Other actions are
            // surfaced as an Enter key press: single-line fields ignore it
            // and apps can react through their key handlers. A dedicated
            // per-field ime-action callback (Compose `KeyboardActions`) is
            // not modeled yet.
            if action == IME_ACTION_DONE {
                let _ = shell.on_ime_finish_composing();
                shell.clear_text_field_focus();
            } else {
                for event_type in [
                    cranpose_app_shell::KeyEventType::KeyDown,
                    cranpose_app_shell::KeyEventType::KeyUp,
                ] {
                    let key = KeyEvent::new(
                        cranpose_app_shell::KeyCode::Enter,
                        "",
                        cranpose_app_shell::Modifiers::NONE,
                        event_type,
                    );
                    let _ = shell.on_key_event(&key);
                }
            }
        }
        AndroidImeEvent::ImeInsetsChanged { bottom_px } => {
            // Publish the keyboard height as IME insets and force a root render
            // so the content wrapper re-provides `local_ime_insets` (a plain
            // shared cell is not itself reactive).
            if set_android_ime_bottom_px(bottom_px) {
                shell.request_root_render();
            }
        }
    }
}

/// Maps an Android pointer id to the shell's pointer id space: the finger
/// that started the gesture (`ACTION_DOWN`) is the shell's primary pointer
/// `0`; every other finger gets a stable non-zero id.
fn shell_pointer_id(android_pointer_id: i32, primary_pointer_id: i32) -> u64 {
    if android_pointer_id == primary_pointer_id {
        0
    } else {
        android_pointer_id as u64 + 1
    }
}

/// Translates one Android input event into pending framework inputs.
///
/// The finger that started the gesture (`ACTION_DOWN`) is tracked in
/// `primary_pointer_id` and forwarded as the shell's primary pointer; its
/// Move events unpack the batched *historical* samples first (oldest to
/// newest, each with its own timestamp) and then the current sample, so the
/// velocity tracker sees every real touch sample instead of only the last
/// position of each batch. Additional fingers (`ACTION_POINTER_DOWN`) are
/// forwarded as secondary pointers with their ids so multi-touch gestures
/// (pinch/zoom) see them. Returns `true` when the event was consumed.
fn push_pending_inputs_from_android_event(
    event: &android_activity::input::InputEvent<'_>,
    android_platform: &AndroidPlatform,
    key_translator: &mut AndroidKeyTranslator,
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) -> bool {
    let motion_event = match event {
        android_activity::input::InputEvent::MotionEvent(motion_event) => motion_event,
        android_activity::input::InputEvent::KeyEvent(key_event) => {
            return push_pending_input_from_android_key_event(
                key_event,
                key_translator,
                pending_inputs,
            );
        }
        _ => return false,
    };

    let time_ms = Some(android_event_time_ms(motion_event.event_time()));
    // The whole-event input source class; used to recover a touch classification
    // when the per-pointer tool type is unreported (see `android_pointer_source`).
    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 as f32, logical.y as f32)
    };

    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 => {
            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 => {
                    // The gesture ends with a finger that is not the one that
                    // started it (the primary lifted earlier without ending
                    // the stream). Close the secondary, then the gesture.
                    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
        }
        android_activity::input::MotionAction::PointerUp => {
            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 {
                // The first finger lifted while others are still down. The
                // shell's gesture is anchored to the primary pointer, so end
                // the whole gesture: close the remaining secondaries, then
                // release the primary. New touches start a fresh gesture.
                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
        }
        android_activity::input::MotionAction::Move => {
            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
        }
        _ => false,
    }
}

fn drain_android_input_events(
    app: &android_activity::AndroidApp,
    android_platform: &AndroidPlatform,
    key_translator: &mut AndroidKeyTranslator,
    pending_inputs: &mut Vec<PendingInput>,
    primary_pointer_id: &mut Option<i32>,
) {
    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| {
            if push_pending_inputs_from_android_event(
                event,
                android_platform,
                key_translator,
                pending_inputs,
                primary_pointer_id,
            ) {
                android_activity::InputStatus::Handled
            } else {
                android_activity::InputStatus::Unhandled
            }
        });
        if !event_available {
            break;
        }
    }
}

const MAX_ANDROID_INPUT_EVENTS_PER_POLL: usize = 10;

#[derive(Clone, Copy)]
struct PendingHostWindowSizeRequest {
    state: Option<android_host_window::AndroidHostWindowState>,
    requested: Size,
    requested_at: Instant,
}

struct AndroidFrameDriver {
    need_frame: Arc<AtomicBool>,
    app_waker: android_activity::AndroidAppWaker,
    next_deadline: Cell<Option<web_time::Instant>>,
}

impl AndroidFrameDriver {
    fn new(app_waker: android_activity::AndroidAppWaker) -> Self {
        Self {
            need_frame: Arc::new(AtomicBool::new(false)),
            app_waker,
            next_deadline: Cell::new(None),
        }
    }

    fn frame_waker(&self) -> impl Fn() + Send + Sync + 'static {
        let need_frame = self.need_frame.clone();
        let app_waker = self.app_waker.clone();
        move || {
            need_frame.store(true, Ordering::Relaxed);
            app_waker.wake();
        }
    }

    fn frame_requested(&self) -> bool {
        self.need_frame.load(Ordering::Relaxed)
    }

    fn take_frame_request(&self) -> bool {
        self.need_frame.swap(false, Ordering::Relaxed)
    }

    fn deadline_timeout(&self) -> Option<Duration> {
        self.next_deadline.get().map(duration_until_frame_deadline)
    }
}

impl PlatformFrameDriver for AndroidFrameDriver {
    fn request_frame(&self) {
        self.need_frame.store(true, Ordering::Relaxed);
        self.app_waker.wake();
    }

    fn request_wake_at(&self, deadline: web_time::Instant) {
        self.next_deadline.set(Some(deadline));
    }

    fn clear_wake(&self) {
        self.next_deadline.set(None);
    }
}

fn duration_until_frame_deadline(deadline: web_time::Instant) -> Duration {
    deadline
        .checked_duration_since(web_time::Instant::now())
        .unwrap_or(Duration::ZERO)
}

fn earliest_android_poll_timeout(
    first: Option<Duration>,
    second: Option<Duration>,
) -> Option<Duration> {
    match (first, second) {
        (Some(first), Some(second)) => Some(first.min(second)),
        (Some(duration), None) | (None, Some(duration)) => Some(duration),
        (None, None) => None,
    }
}

/// Get display density from Android NDK Configuration.
///
/// Uses the NDK's AConfiguration_getDensity which returns density constants
/// mapped to the standard Android density classes:
/// - mdpi: 1.0 (160 dpi baseline)
/// - hdpi: 1.5 (240 dpi)
/// - xhdpi: 2.0 (320 dpi) - most common modern phones
/// - xxhdpi: 3.0 (480 dpi)
/// - xxxhdpi: 4.0 (640 dpi)
///
/// The factor is calculated as DPI / 160 per Android NDK documentation.
fn get_display_density(app: &android_activity::AndroidApp) -> f32 {
    let config = app.config();
    let density_dpi = config.density(); // Returns Option<u32> with raw DPI value

    // Convert DPI to scale factor (baseline is 160 dpi = 1.0x)
    // e.g., 320 dpi / 160 = 2.0x (xhdpi)
    density_dpi.map(|dpi| dpi as f32 / 160.0).unwrap_or(2.0) // Fallback to xhdpi (2.0) if density unavailable
}

/// The freeform/DeX shadow-margin inset (in physical px) between the render
/// buffer and the on-screen frame. The native window buffer is enlarged by this
/// margin on every side; the renderer fills the buffer from (0,0) while pointer
/// events are frame-relative, so this is exactly the offset to add to pointers.
/// Returns `(0, 0)` when there is no margin (fullscreen: buffer == frame).
fn surface_inset_px(app: &android_activity::AndroidApp) -> (f64, f64) {
    let Some(window) = app.native_window() else {
        return (0.0, 0.0);
    };
    let buffer_w = window.width() as f64;
    let buffer_h = window.height() as f64;
    // `content_rect`'s right/bottom edges are the frame's size (the caption only
    // insets the top, so the content still reaches the frame's right and bottom).
    let content = app.content_rect();
    let frame_w = content.right as f64;
    let frame_h = content.bottom as f64;
    if frame_w <= 0.0 || frame_h <= 0.0 || frame_w > buffer_w || frame_h > buffer_h {
        return (0.0, 0.0);
    }
    (
        ((buffer_w - frame_w) / 2.0).max(0.0),
        ((buffer_h - frame_h) / 2.0).max(0.0),
    )
}

fn update_android_platform_geometry(
    app: &android_activity::AndroidApp,
    android_platform: &mut AndroidPlatform,
) -> f32 {
    let density = get_display_density(app);
    android_platform.set_scale_factor(density as f64);

    // A freeform/DeX window's render surface is LARGER than its on-screen frame:
    // the system adds a shadow/resize margin (the window `surfaceInsets`), so the
    // native buffer we draw into is e.g. 525x879 px while the visible frame is
    // only 447x801. The renderer fills the whole buffer starting at (0,0), which
    // lands at `frame_origin - inset` on screen — but pointer coordinates arrive
    // relative to the *frame*. Without correction every touch is off by that inset
    // (~39 px / 24 dp), so controls near the edges become unreachable. We recover
    // the inset as half the difference between the buffer and the frame, and add
    // it to incoming pointers so they map into the same surface space the renderer
    // draws in. Fullscreen (phone) has buffer == frame, so this is a no-op there.
    let (offset_x, offset_y) = surface_inset_px(app);
    android_platform.set_input_surface_offset_px(offset_x, offset_y);

    density
}

fn update_android_shell_geometry(
    shell: &mut AppShell<WgpuRenderer>,
    density: f32,
    host_window_registry: &android_host_window::AndroidHostWindowRegistry,
) -> Option<Size> {
    shell.renderer().set_root_scale(density);
    shell.set_density(density);

    let (width, height) = shell.buffer_size();
    if width > 0 && height > 0 {
        let width_dp = width as f32 / density;
        let height_dp = height as f32 / density;
        shell.set_viewport(width_dp, height_dp);
        let actual = Size::new(width_dp, height_dp);
        android_host_window::sync_android_host_window_actual_size(host_window_registry, actual);
        Some(actual)
    } else {
        None
    }
}

/// Renders a single frame. Returns true if out of memory (should exit).
fn render_once(resources: &mut GpuResources, shell: &mut AppShell<WgpuRenderer>) -> bool {
    match current_surface_texture(&resources.surface, "android") {
        SurfaceFrame::Ready(frame) => {
            let view = frame
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());
            let (width, height) = shell.buffer_size();

            if let Err(e) = shell.renderer().render(&view, width, height) {
                log::error!("Render error: {:?}", e);
            }

            frame.present();
            resources.surface_dirty = false;
            false
        }
        SurfaceFrame::Reconfigure => {
            let (width, height) = shell.buffer_size();
            resources.config.width = width;
            resources.config.height = height;
            resources
                .surface
                .configure(&resources.device, &resources.config);
            // The reconfigured surface has not presented yet. Unlike web/desktop,
            // the android render block is gated behind `shell.needs_update()`, so
            // marking the shell dirty is what both wakes the looper and re-enters
            // the present path on the next iteration to flush the new swapchain.
            resources.surface_dirty = true;
            shell.mark_dirty();
            false
        }
        // Surface unavailable this tick; retry the present on the next frame.
        SurfaceFrame::Skip => {
            resources.surface_dirty = true;
            false
        }
    }
}

struct AndroidGpuSetup {
    resources: GpuResources,
    renderer_needs_init: bool,
}

fn initialize_android_rendering<F>(
    instance: &wgpu::Instance,
    existing_resources: Option<GpuResources>,
    app_shell: &mut Option<AppShell<WgpuRenderer>>,
    content: &Rc<RefCell<F>>,
    settings: &AppSettings,
    frame_driver: &AndroidFrameDriver,
    host_window_registry: &android_host_window::AndroidHostWindowRegistry,
    native_window_ptr: NonNull<c_void>,
    native_window_owner: Option<NativeWindow>,
    width: u32,
    height: u32,
    density: f32,
) -> Result<(GpuResources, Option<Size>), AndroidSurfaceError>
where
    F: FnMut() + 'static,
{
    let setup = create_android_gpu_resources(
        instance,
        existing_resources,
        native_window_ptr,
        native_window_owner,
        width,
        height,
    )?;

    if app_shell.is_none() {
        let fonts: &[&[u8]] = settings.fonts.unwrap_or(&[]);
        let mut renderer = WgpuRenderer::new(fonts);
        renderer.init_gpu(
            setup.resources.device.clone(),
            setup.resources.queue.clone(),
            setup.resources.surface_format,
            setup.resources.backend,
        );

        let content_clone = content.clone();
        let density = density.max(f32::EPSILON);
        let platform_env = android_platform_env();
        let shell = AppShell::new_with_size_and_density(
            renderer,
            default_root_key(),
            move || {
                // Provide the live platform environment (IME/safe-area insets,
                // system theme) to composition. Read on every recomposition;
                // the event loop forces a root render when a value changes.
                platform_env.compose_root(|| content_clone.borrow_mut()());
            },
            (width, height),
            (width as f32 / density, height as f32 / density),
            density,
        );

        *app_shell = Some(shell);

        if let Some(shell) = app_shell {
            shell.set_frame_waker(frame_driver.frame_waker());
        }

        log::info!("App shell created");
    } else if setup.renderer_needs_init {
        if let Some(shell) = app_shell {
            shell.renderer().init_gpu(
                setup.resources.device.clone(),
                setup.resources.queue.clone(),
                setup.resources.surface_format,
                setup.resources.backend,
            );
            log::info!("Renderer reinitialized with new Android GPU pipeline resources");
        }
    } else {
        log::debug!("Reused Android WGPU device and renderer resources for surface update");
    }

    if let Some(shell) = app_shell {
        shell.renderer().set_root_scale(density);
        shell.set_density(density);
        set_android_ime_density(density);
    }

    let actual_size = app_shell.as_mut().and_then(|shell| {
        shell.set_buffer_size(width, height);
        update_android_shell_geometry(shell, density, host_window_registry)
    });

    Ok((setup.resources, actual_size))
}

fn create_android_gpu_resources(
    instance: &wgpu::Instance,
    existing_resources: Option<GpuResources>,
    native_window_ptr: NonNull<c_void>,
    native_window_owner: Option<NativeWindow>,
    width: u32,
    height: u32,
) -> Result<AndroidGpuSetup, AndroidSurfaceError> {
    if let Some(mut resources) = existing_resources {
        if resources.native_window_ptr == native_window_ptr {
            resources.config.width = width;
            resources.config.height = height;
            resources
                .surface
                .configure(&resources.device, &resources.config);
            if let Some(native_window_owner) = native_window_owner {
                resources._native_window = Some(native_window_owner);
            }
            return Ok(AndroidGpuSetup {
                resources,
                renderer_needs_init: false,
            });
        }

        return create_android_gpu_resources_for_existing_device(
            instance,
            &resources,
            native_window_ptr,
            native_window_owner,
            width,
            height,
        );
    }

    let surface = create_android_wgpu_surface(instance, native_window_ptr)?;

    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: wgpu::PowerPreference::HighPerformance,
        compatible_surface: Some(&surface),
        force_fallback_adapter: false,
    }))?;

    let adapter_info = adapter.get_info();
    log::info!("Found adapter: {:?}", adapter_info.backend);
    let adapter = Arc::new(adapter);

    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
        label: Some("Android Device"),
        required_features: wgpu::Features::empty(),
        required_limits: crate::gpu_limits::mobile_device_limits(adapter.limits()),
        experimental_features: wgpu::ExperimentalFeatures::disabled(),
        memory_hints: wgpu::MemoryHints::default(),
        trace: wgpu::Trace::Off,
    }))?;

    let device = Arc::new(device);
    let queue = Arc::new(queue);
    let config = create_android_surface_config(&surface, &adapter, width, height)?;
    surface.configure(&device, &config);

    Ok(AndroidGpuSetup {
        resources: GpuResources {
            surface,
            native_window_ptr,
            adapter,
            device,
            queue,
            surface_format: config.format,
            backend: adapter_info.backend,
            config,
            _native_window: native_window_owner,
            surface_dirty: true,
        },
        renderer_needs_init: true,
    })
}

fn create_android_gpu_resources_for_existing_device(
    instance: &wgpu::Instance,
    existing: &GpuResources,
    native_window_ptr: NonNull<c_void>,
    native_window_owner: Option<NativeWindow>,
    width: u32,
    height: u32,
) -> Result<AndroidGpuSetup, AndroidSurfaceError> {
    let surface = create_android_wgpu_surface(instance, native_window_ptr)?;
    let config = create_android_surface_config(&surface, &existing.adapter, width, height)?;
    surface.configure(&existing.device, &config);
    let renderer_needs_init = config.format != existing.surface_format;

    Ok(AndroidGpuSetup {
        resources: GpuResources {
            surface,
            native_window_ptr,
            adapter: existing.adapter.clone(),
            device: existing.device.clone(),
            queue: existing.queue.clone(),
            surface_format: config.format,
            backend: existing.backend,
            config,
            _native_window: native_window_owner,
            surface_dirty: true,
        },
        renderer_needs_init,
    })
}

fn create_android_surface_config(
    surface: &wgpu::Surface<'static>,
    adapter: &wgpu::Adapter,
    width: u32,
    height: u32,
) -> Result<wgpu::SurfaceConfiguration, AndroidSurfaceError> {
    let surface_caps = surface.get_capabilities(&adapter);
    let surface_format =
        crate::surface_format::select_display_surface_format(&surface_caps.formats)
            .ok_or(AndroidSurfaceError::NoSurfaceFormat)?;
    let alpha_mode = surface_caps
        .alpha_modes
        .first()
        .copied()
        .ok_or(AndroidSurfaceError::NoAlphaMode)?;
    let present_mode = crate::present_mode::select_present_mode(&surface_caps);
    Ok(wgpu::SurfaceConfiguration {
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        format: surface_format,
        width,
        height,
        present_mode,
        alpha_mode,
        view_formats: vec![],
        desired_maximum_frame_latency: 2,
    })
}

fn dispatch_android_surface_size_request(
    app: &android_activity::AndroidApp,
    requested: Size,
    position: Point,
    density: f32,
    overlay_options: Option<AndroidOverlayWindowOptions>,
) -> Result<(), String> {
    let requested =
        android_host_window::validate_logical_size(requested).map_err(|error| error.to_string())?;
    if overlay_options.is_some() {
        return android_overlay_window::update_android_overlay_window_bounds(
            app, position, requested, density,
        );
    }

    let (width_px, height_px) =
        android_host_window::logical_to_physical_window_size(requested, density);
    set_android_window_layout_px(app, width_px, height_px)
}

fn dispatch_registered_android_surface_size_request(
    app: &android_activity::AndroidApp,
    host_window_registry: &android_host_window::AndroidHostWindowRegistry,
    density: f32,
    overlay_options: Option<AndroidOverlayWindowOptions>,
    last_dispatched: &mut Option<(android_host_window::AndroidHostWindowState, u64, u64)>,
    pending_confirmation: &mut Option<PendingHostWindowSizeRequest>,
) {
    let Some(request) =
        android_host_window::latest_android_host_window_request(host_window_registry)
    else {
        return;
    };
    let dispatch_key = (
        request.state,
        request.size_revision,
        if overlay_options.is_some() {
            request.position_revision
        } else {
            0
        },
    );
    if *last_dispatched == Some(dispatch_key) {
        return;
    }

    let position = overlay_options
        .filter(|_| request.position_revision == 0)
        .map(|options| Point::new(options.x as f32, options.y as f32))
        .unwrap_or(request.position);
    request.state.mark_pending(request.size);
    match dispatch_android_surface_size_request(
        app,
        request.size,
        position,
        density,
        overlay_options,
    ) {
        Ok(()) => {
            *last_dispatched = Some(dispatch_key);
            *pending_confirmation = Some(PendingHostWindowSizeRequest {
                state: Some(request.state),
                requested: request.size,
                requested_at: Instant::now(),
            });
            let target = if overlay_options.is_some() {
                "Android overlay surface"
            } else {
                "Android host-window"
            };
            if overlay_options.is_some() {
                log::info!(
                    "Requested {target} bounds {:.1}x{:.1} dp at {:.1},{:.1} dp",
                    request.size.width,
                    request.size.height,
                    position.x,
                    position.y
                );
            } else {
                log::info!(
                    "Requested {target} size {:.1}x{:.1} dp",
                    request.size.width,
                    request.size.height
                );
            }
        }
        Err(message) => {
            *last_dispatched = Some(dispatch_key);
            request.state.mark_dispatch_failed(request.size, message);
        }
    }
}

fn confirm_android_host_window_request(
    pending_confirmation: &mut Option<PendingHostWindowSizeRequest>,
    actual_size: Size,
) {
    let Some(pending) = *pending_confirmation else {
        return;
    };

    if android_host_window::sizes_match(pending.requested, actual_size) {
        if let Some(state) = pending.state {
            state.mark_applied(pending.requested, actual_size);
        }
        *pending_confirmation = None;
        return;
    }

    if pending.requested_at.elapsed() >= android_host_window::HOST_WINDOW_CONFIRMATION_TIMEOUT {
        if let Some(state) = pending.state {
            state.mark_unsupported(pending.requested, actual_size);
        }
        log::info!(
            "Android surface size request {:.1}x{:.1} dp was not honored; actual is {:.1}x{:.1} dp",
            pending.requested.width,
            pending.requested.height,
            actual_size.width,
            actual_size.height
        );
        *pending_confirmation = None;
    }
}

/// Whether the activity is currently in multi-window mode (split-screen,
/// freeform, or desktop windowing such as Samsung DeX).
///
/// A fullscreen phone activity's window is laid out edge-to-edge across the
/// whole display (`PhoneWindow.generateLayout` sets `FLAG_LAYOUT_IN_SCREEN |
/// FLAG_LAYOUT_INSET_DECOR` and clears `fitInsetsTypes` for every non-floating
/// window), so its `ANativeWindow` buffer already covers the areas behind the
/// status and navigation bars. Calling `Window.setLayout` with a fixed pixel
/// size on that window replaces `MATCH_PARENT`; devices that honor it shrink
/// and center the surface, leaving uncovered strips of raw display that show
/// as black bands at the top and bottom. Host-window sizing is therefore only
/// meaningful in multi-window modes, where the window is genuinely resizable.
///
/// Returns `false` when the query fails (including API < 24, where
/// `isInMultiWindowMode` does not exist and multi-window is unavailable).
fn android_activity_in_multi_window_mode(app: &android_activity::AndroidApp) -> bool {
    use jni::{jni_sig, jni_str};

    with_android_activity_env(app, |env, activity| {
        env.call_method(
            &activity,
            jni_str!("isInMultiWindowMode"),
            jni_sig!("()Z"),
            &[],
        )
        .and_then(|value| value.z())
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to query Android multi-window mode: {error}")
        })
    })
    .unwrap_or_else(|error| {
        log::warn!("{error}");
        false
    })
}

fn set_android_window_layout_px(
    app: &android_activity::AndroidApp,
    width_px: i32,
    height_px: i32,
) -> Result<(), String> {
    use jni::{jni_sig, jni_str, objects::JValue};

    with_android_activity_env(app, |env, activity| {
        let class = android_overlay_window::find_android_overlay_class(env, &activity)?;
        let result = env
            .call_static_method(
                class,
                jni_str!("setActivityWindowLayout"),
                jni_sig!("(Landroid/app/Activity;II)I"),
                &[
                    JValue::Object(&activity),
                    JValue::Int(width_px),
                    JValue::Int(height_px),
                ],
            )
            .and_then(|value| value.i())
            .map_err(|error| {
                clear_pending_android_jni_exception(env);
                format!("failed to request Android window layout: {error}")
            })?;

        match result {
            0 => Ok(()),
            code => Err(format!(
                "Android window layout request failed with code {code}"
            )),
        }
    })
}

/// Runs an Android Compose application with wgpu rendering.
///
/// Called by `AppLauncher::run_android()`. This is the framework-level
/// entrypoint that manages the Android lifecycle and event loop.
///
/// **Note:** Applications should use `AppLauncher` instead of calling this directly.
pub fn run(
    app: android_activity::AndroidApp,
    settings: AppSettings,
    content: impl FnMut() + 'static,
) {
    use android_activity::{MainEvent, PollEvent};

    // Register the SAF document picker as the platform file picker. Requires the
    // app's activity to be `dev.cranpose.android.CranposeActivity`.
    crate::android_file_picker::register(app.clone());
    // Register the SAF writable-folder backend (write-side complement, used for
    // cross-device sync into a user-granted folder).
    crate::android_writable_folder::register(app.clone());
    // Haptics, share sheet, notifier, network status (JNI backends of the
    // CranposeActivity capability hooks).
    crate::android_services::register(app.clone());

    // Seed the system theme from the boot configuration; live switches arrive
    // as `MainEvent::ConfigChanged`.
    android_platform_env()
        .set_system_theme(system_theme_from_android(app.config().ui_mode_night()));

    // Install panic hook for better crash logging in Logcat
    std::panic::set_hook(Box::new(|panic_info| {
        let location = panic_info
            .location()
            .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
            .unwrap_or_else(|| "unknown location".to_string());
        let message = panic_info
            .payload()
            .downcast_ref::<&str>()
            .map(|s| *s)
            .or_else(|| {
                panic_info
                    .payload()
                    .downcast_ref::<String>()
                    .map(|s| s.as_str())
            })
            .unwrap_or("Box<dyn Any>");
        log::error!("PANIC at {}: {}", location, message);
    }));

    // Wrap content in Rc<RefCell> for reuse across window recreations
    let content = std::rc::Rc::new(std::cell::RefCell::new(content));

    // App shell (created once, persists across window recreations)
    let mut app_shell: Option<AppShell<WgpuRenderer>> = None;

    // Initialize logging
    android_logger::init_once(
        android_logger::Config::default()
            .with_max_level(log::LevelFilter::Info)
            .with_tag("ComposeRS")
            .with_filter(
                android_logger::FilterBuilder::new()
                    .filter_level(log::LevelFilter::Info)
                    .filter_module("wgpu_core", log::LevelFilter::Warn)
                    .filter_module("wgpu_hal", log::LevelFilter::Warn)
                    .filter_module("naga", log::LevelFilter::Warn)
                    .build(),
            ),
    );

    log::info!("Starting Compose Android Application");

    let android_frame_driver = AndroidFrameDriver::new(app.create_waker());
    let host_window_registry = Rc::new(android_host_window::AndroidHostWindowRegistry::default());
    let overlay_event_queue = Arc::new(android_overlay_window::AndroidOverlayEventQueue::default());

    // IME editor bridge (InputConnection-backed text input). The queue crosses
    // the JNI/UI-thread boundary; the session state stays on this thread.
    let ime_event_queue = Arc::new(android_text_input::AndroidImeEventQueue::new());
    ime_event_queue.set_waker(app.create_waker());
    let ime_session =
        android_keyboard::AndroidImeSession::new(app.clone(), Arc::clone(&ime_event_queue));

    // Exit flag for Destroy event (can't break from inside poll_events closure)
    let should_exit = Arc::new(AtomicBool::new(false));

    // Initialize wgpu instance with GL and Vulkan backends
    // Use DISCARD_HAL_LABELS to prevent crash in emulator's Vulkan debug utils
    // (vk_common_SetDebugUtilsObjectNameEXT crashes on null labels)
    let backends = wgpu::Backends::GL | wgpu::Backends::VULKAN;

    let mut instance_descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
    instance_descriptor.backends = backends;
    // No debug/validation: emulator Vulkan debug utils can crash on null labels.
    instance_descriptor.flags = wgpu::InstanceFlags::empty();
    let instance = wgpu::Instance::new(instance_descriptor);

    // Platform abstraction for density/pointer conversion
    let mut android_platform = AndroidPlatform::new();
    let mut current_host_window_size = Size::ZERO;
    let mut initial_host_window_size = settings.initial_size_explicit.then(|| {
        Size::new(
            settings.initial_width as f32,
            settings.initial_height as f32,
        )
    });
    let mut last_dispatched_host_window_request =
        None::<(android_host_window::AndroidHostWindowState, u64, u64)>;
    let mut pending_host_window_confirmation = None::<PendingHostWindowSizeRequest>;
    let mut overlay_window_options = settings.android_overlay_window;
    let mut overlay_window_requested = false;

    // GPU resources (recreated when window is destroyed/created)
    let mut gpu_resources: Option<GpuResources> = None;

    // Queue for input events (processed outside poll_events to prevent ANR)
    let mut pending_inputs: Vec<PendingInput> = Vec::new();
    // Android pointer id of the finger that started the current gesture
    // (the shell's primary pointer). None while no gesture is in progress.
    let mut primary_pointer_id: Option<i32> = None;

    // Key-event translation (KeyCharacterMap lookups, dead-key state)
    let mut key_translator = AndroidKeyTranslator::new(app.clone());
    // The soft-keyboard handler is installed once the app shell exists
    let mut soft_keyboard_installed = false;

    // Main event loop
    loop {
        let pending_confirmation_timeout = pending_host_window_confirmation.map(|pending| {
            android_host_window::HOST_WINDOW_CONFIRMATION_TIMEOUT
                .checked_sub(pending.requested_at.elapsed())
                .unwrap_or(Duration::ZERO)
        });

        if let Some(shell) = app_shell.as_ref() {
            shell.schedule_platform_frame(&android_frame_driver);
        } else {
            android_frame_driver.clear_wake();
        }
        let frame_deadline_timeout = android_frame_driver.deadline_timeout();
        let idle_timeout =
            earliest_android_poll_timeout(pending_confirmation_timeout, frame_deadline_timeout);

        let poll_duration = if !pending_inputs.is_empty() {
            Some(Duration::ZERO)
        } else if android_frame_driver.frame_requested() {
            Some(Duration::ZERO)
        } else {
            idle_timeout
        };

        app.poll_events(poll_duration, |event| {
            match event {
                PollEvent::Main(main_event) => match main_event {
                    MainEvent::InitWindow { .. } => {
                        log::info!("Window initialized, setting up rendering");

                        if let Some(options) = overlay_window_options {
                            let density =
                                update_android_platform_geometry(&app, &mut android_platform);
                            android_platform.set_input_surface_offset_px(0.0, 0.0);
                            if !overlay_window_requested {
                                match android_overlay_window::show_android_overlay_window(
                                    &app,
                                    options,
                                    density,
                                    &overlay_event_queue,
                                ) {
                                    Ok(()) => {
                                        overlay_window_requested = true;
                                        log::info!(
                                            "Requested Android overlay surface {}x{} dp at ({}, {})",
                                            options.width,
                                            options.height,
                                            options.x,
                                            options.y
                                        );
                                    }
                                    Err(error) => {
                                        overlay_window_options = None;
                                        log::warn!(
                                            "Android overlay surface unavailable; waiting for activity surface fallback: {error}"
                                        );
                                    }
                                }
                            }
                        }

                        if overlay_window_options.is_none() {
                            if let Some(native_window) = app.native_window() {
                                let width = native_window.width() as u32;
                                let height = native_window.height() as u32;
                                let density =
                                    update_android_platform_geometry(&app, &mut android_platform);
                                let (input_offset_x, input_offset_y) =
                                    android_platform.input_surface_offset_px();
                                log::info!(
                                    "Display density: {:.2}x, input surface offset: ({:.1}, {:.1}) px",
                                    density,
                                    input_offset_x,
                                    input_offset_y
                                );

                                match initialize_android_rendering(
                                    &instance,
                                    gpu_resources.take(),
                                    &mut app_shell,
                                    &content,
                                    &settings,
                                    &android_frame_driver,
                                    &host_window_registry,
                                    native_window.ptr().cast(),
                                    None,
                                    width,
                                    height,
                                    density,
                                ) {
                                    Ok((resources, actual_size)) => {
                                        if let Some(actual_size) = actual_size {
                                            current_host_window_size = actual_size;
                                        }
                                        let width_dp = current_host_window_size.width;
                                        let height_dp = current_host_window_size.height;
                                        log::info!(
                                            "Set viewport to {:.1}x{:.1} dp ({}x{} px at {:.2}x density)",
                                            width_dp,
                                            height_dp,
                                            width,
                                            height,
                                            density
                                        );

                                        // Only forward the launcher's initial size to the host
                                        // window in multi-window/freeform modes. A fullscreen
                                        // activity's window already spans the entire display
                                        // (edge-to-edge, including behind the system bars);
                                        // shrinking it with `Window.setLayout` pulls the native
                                        // surface away from the display edges and the uncovered
                                        // strips render as black bands.
                                        if let Some(requested) = initial_host_window_size.take() {
                                            if !android_activity_in_multi_window_mode(&app) {
                                                log::info!(
                                                    "Ignoring initial window size {:.1}x{:.1} dp: fullscreen Android activities keep the display-sized edge-to-edge surface; size requests apply in multi-window/freeform modes",
                                                    requested.width,
                                                    requested.height
                                                );
                                            } else {
                                                match dispatch_android_surface_size_request(
                                                    &app,
                                                    requested,
                                                    Point::ZERO,
                                                    density,
                                                    None,
                                                ) {
                                                    Ok(()) => {
                                                        pending_host_window_confirmation =
                                                            Some(PendingHostWindowSizeRequest {
                                                                state: None,
                                                                requested,
                                                                requested_at: Instant::now(),
                                                            });
                                                        log::info!(
                                                            "Requested initial Android host-window size {:.1}x{:.1} dp",
                                                            requested.width,
                                                            requested.height
                                                        );
                                                    }
                                                    Err(error) => {
                                                        log::warn!(
                                                            "Initial Android host-window size request failed: {error}"
                                                        );
                                                    }
                                                }
                                            }
                                        }

                                        gpu_resources = Some(resources);
                                        log::info!("Rendering initialized successfully");
                                    }
                                    Err(error) => {
                                        log::error!("Android rendering initialization failed: {error}");
                                    }
                                }
                            }
                        }
                    }
                    MainEvent::TerminateWindow { .. } => {
                        log::info!("Window terminated");
                        if overlay_window_options.is_none() {
                            gpu_resources = None;
                        }
                    }
                    MainEvent::WindowResized { .. } => {
                        if overlay_window_options.is_none() {
                            if let Some(native_window) = app.native_window() {
                                let width = native_window.width() as u32;
                                let height = native_window.height() as u32;

                                let density =
                                    update_android_platform_geometry(&app, &mut android_platform);
                                let (input_offset_x, input_offset_y) =
                                    android_platform.input_surface_offset_px();
                                log::info!(
                                    "Window resized to {}x{} at {:.2}x density with input surface offset ({:.1}, {:.1}) px",
                                    width,
                                    height,
                                    density,
                                    input_offset_x,
                                    input_offset_y
                                );

                                if let (Some(resources), Some(shell)) =
                                    (&mut gpu_resources, &mut app_shell)
                                {
                                    if width > 0 && height > 0 {
                                        resources.config.width = width;
                                        resources.config.height = height;
                                        resources
                                            .surface
                                            .configure(&resources.device, &resources.config);

                                        // Set buffer_size to physical pixels
                                        shell.set_buffer_size(width, height);

                                        if let Some(actual_size) =
                                            update_android_shell_geometry(
                                                shell,
                                                density,
                                                &host_window_registry,
                                            )
                                        {
                                            current_host_window_size = actual_size;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    MainEvent::ContentRectChanged { .. } => {
                        let density = update_android_platform_geometry(&app, &mut android_platform);
                        if overlay_window_options.is_some() {
                            android_platform.set_input_surface_offset_px(0.0, 0.0);
                        }
                        let (input_offset_x, input_offset_y) =
                            android_platform.input_surface_offset_px();
                        log::info!(
                            "Content rect changed; input surface offset: ({:.1}, {:.1}) px at {:.2}x density",
                            input_offset_x,
                            input_offset_y,
                            density
                        );

                        if let Some(shell) = &mut app_shell {
                            if let Some(actual_size) =
                                update_android_shell_geometry(shell, density, &host_window_registry)
                            {
                                current_host_window_size = actual_size;
                            }
                        }
                    }
                    MainEvent::RedrawNeeded { .. } => {
                        if let Some(shell) = &mut app_shell {
                            shell.mark_dirty();
                        }
                    }
                    MainEvent::Pause => {
                        log::info!("App paused");
                        // Withdraw any outstanding soft-keyboard request and
                        // close the IME editor session so the OS cannot restore
                        // the keyboard on resume for an editor view the
                        // framework no longer considers focused.
                        if let Some(shell) = &mut app_shell {
                            shell.notify_app_paused();
                        }
                        ime_session.ensure_hidden();
                    }
                    MainEvent::Resume { .. } => {
                        log::info!("App resumed");
                        // Never auto-reopen the soft keyboard on resume, even if a
                        // field is still focused: a warm resume keeps the field's
                        // caret/focus but must not resurrect the keyboard (the OS
                        // InputMethodManager would otherwise pop it back). The user
                        // taps the field to bring it back. `notify_app_resumed`
                        // always returns false, so we force the keyboard hidden.
                        let reopened = app_shell
                            .as_mut()
                            .map(|shell| shell.notify_app_resumed())
                            .unwrap_or(false);
                        if !reopened {
                            ime_session.ensure_hidden();
                        }
                    }
                    MainEvent::Start => {
                        log::info!("App started");
                    }
                    MainEvent::Stop => {
                        log::info!("App stopped");
                    }
                    MainEvent::SaveState { .. } => {
                        log::info!("Save state requested");
                    }
                    MainEvent::Destroy => {
                        log::info!("App destroy requested, will exit after this event");
                        if overlay_window_options.is_some() {
                            android_overlay_window::hide_android_overlay_window(&app);
                        }
                        should_exit.store(true, Ordering::Relaxed);
                    }
                    MainEvent::InputAvailable => {
                        drain_android_input_events(
                            &app,
                            &android_platform,
                            &mut key_translator,
                            &mut pending_inputs,
                            &mut primary_pointer_id,
                        );
                    }
                    MainEvent::ConfigChanged { .. } => {
                        // Follow OS light/dark switches live (uiMode arrives as
                        // a configuration change).
                        let theme = system_theme_from_android(app.config().ui_mode_night());
                        if android_platform_env().set_system_theme(theme) {
                            if let Some(shell) = &mut app_shell {
                                shell.request_root_render();
                            }
                        }
                    }
                    _ => {}
                },
                _ => {
                    // Non-main poll events do not own Android NativeActivity
                    // input. Native input is delivered as MainEvent::InputAvailable.
                }
            }
        });

        for event in
            android_overlay_window::drain_android_overlay_window_events(&overlay_event_queue)
        {
            match event {
                android_overlay_window::AndroidOverlayWindowEvent::CreateFailed(message) => {
                    log::warn!("Android overlay surface failed: {message}");
                    overlay_window_options = None;

                    if let Some(native_window) = app.native_window() {
                        let width = native_window.width() as u32;
                        let height = native_window.height() as u32;
                        if width > 0 && height > 0 {
                            let density =
                                update_android_platform_geometry(&app, &mut android_platform);
                            match initialize_android_rendering(
                                &instance,
                                gpu_resources.take(),
                                &mut app_shell,
                                &content,
                                &settings,
                                &android_frame_driver,
                                &host_window_registry,
                                native_window.ptr().cast(),
                                None,
                                width,
                                height,
                                density,
                            ) {
                                Ok((resources, actual_size)) => {
                                    if let Some(actual_size) = actual_size {
                                        current_host_window_size = actual_size;
                                    }
                                    gpu_resources = Some(resources);
                                }
                                Err(error) => {
                                    log::error!(
                                        "Android activity surface fallback initialization failed: {error}"
                                    );
                                }
                            }
                        }
                    }
                }
                android_overlay_window::AndroidOverlayWindowEvent::SurfaceChanged {
                    native_window,
                    width,
                    height,
                } => {
                    if width > 0 && height > 0 {
                        let density = get_display_density(&app);
                        android_platform.set_scale_factor(density as f64);
                        android_platform.set_input_surface_offset_px(0.0, 0.0);
                        if let Some(shell) = app_shell.as_mut() {
                            shell.set_density(density);
                        }

                        let native_window_ptr = native_window.ptr().cast();
                        match initialize_android_rendering(
                            &instance,
                            gpu_resources.take(),
                            &mut app_shell,
                            &content,
                            &settings,
                            &android_frame_driver,
                            &host_window_registry,
                            native_window_ptr,
                            Some(native_window),
                            width,
                            height,
                            density,
                        ) {
                            Ok((resources, actual_size)) => {
                                if let Some(actual_size) = actual_size {
                                    current_host_window_size = actual_size;
                                }
                                gpu_resources = Some(resources);
                                log::info!(
                                    "Android overlay surface ready at {}x{} px ({:.2}x density)",
                                    width,
                                    height,
                                    density
                                );
                            }
                            Err(error) => {
                                log::error!(
                                    "Android overlay surface initialization failed: {error}"
                                );
                            }
                        }
                    }
                }
                android_overlay_window::AndroidOverlayWindowEvent::SurfaceDestroyed => {
                    if overlay_window_options.is_some() {
                        gpu_resources = None;
                    }
                }
                android_overlay_window::AndroidOverlayWindowEvent::Pointer { action, x, y } => {
                    let logical = android_platform.pointer_position(x as f64, y as f64);
                    // Overlay pointer events cross a JNI bridge that does not
                    // forward MotionEvent timestamps; velocity tracking falls
                    // back to delivery-time stamping for them.
                    match action {
                        android_overlay_window::AndroidOverlayPointerAction::Down => {
                            pending_inputs.push(PendingInput::PointerDown(
                                logical.x as f32,
                                logical.y as f32,
                                None,
                                // The overlay JNI bridge does not forward tool
                                // type; overlay surfaces are touch in practice.
                                PointerSource::Touch,
                            ));
                        }
                        android_overlay_window::AndroidOverlayPointerAction::Up
                        | android_overlay_window::AndroidOverlayPointerAction::Cancel => {
                            pending_inputs.push(PendingInput::PointerUp(
                                logical.x as f32,
                                logical.y as f32,
                                None,
                                PointerSource::Touch,
                            ));
                        }
                        android_overlay_window::AndroidOverlayPointerAction::Move => {
                            pending_inputs.push(PendingInput::PointerMove(
                                logical.x as f32,
                                logical.y as f32,
                                None,
                                PointerSource::Touch,
                            ));
                        }
                    }
                }
            }
        }

        // Install the soft-keyboard focus hook as soon as the shell exists so
        // the first tap on a text field already opens the keyboard.
        if !soft_keyboard_installed {
            if let Some(shell) = &mut app_shell {
                shell.set_platform_text_input(Rc::new(AndroidSoftKeyboard::new(Rc::clone(
                    &ime_session,
                ))));
                soft_keyboard_installed = true;
                log::info!("Android soft keyboard focus hook installed");

                // The system clipboard is per-AppContext (it backs the text
                // selection menu), so it registers once the shell exists.
                let clipboard_app = app.clone();
                shell.app_context().enter(move || {
                    cranpose_ui::clipboard_session::set_platform_clipboard(Rc::new(
                        crate::android_services::AndroidClipboard { app: clipboard_app },
                    ));
                });

                // Cold-start guard (bug 5): on a fresh launch the OS can restore
                // the soft keyboard left over from the previous process — even on
                // a screen with no text field. Re-request it only if a field is
                // genuinely focused this launch; otherwise force it hidden so the
                // keyboard does not resurrect on relaunch. `notify_app_resumed`
                // returns whether a focused field re-opened it.
                if !shell.notify_app_resumed() {
                    ime_session.ensure_hidden();
                    log::info!("No focused field at launch; ensured soft keyboard hidden");
                }
            }
        }

        // Apply editing operations forwarded by the IME InputConnection
        // (commit/compose/delete/key/editor-action), in arrival order.
        if let Some(shell) = &mut app_shell {
            for event in ime_event_queue.drain() {
                dispatch_android_ime_event(shell, event);
            }
        }

        // Apply capability signals parked by the Java UI thread (window
        // insets → safe area).
        crate::android_services::apply_pending_platform_signals(
            get_display_density(&app),
            &mut app_shell,
        );

        // Process pending input events outside poll_events to prevent ANR
        if !pending_inputs.is_empty() {
            if let Some(shell) = &mut app_shell {
                for input in pending_inputs.drain(..) {
                    match input {
                        PendingInput::PointerDown(x, y, time_ms, source) => {
                            shell.set_pointer_source(source);
                            shell.set_cursor_at_time(x, y, time_ms);
                            shell.pointer_pressed_at_time(time_ms);
                        }
                        PendingInput::PointerUp(x, y, time_ms, source) => {
                            // ACTION_UP coordinates carry lift-off roll-back
                            // jitter; they must NOT become a velocity sample
                            // (a synthesized Move here can flip the fling
                            // direction), so release without a Move dispatch.
                            shell.set_pointer_source(source);
                            shell.pointer_released_at_position_time(x, y, time_ms);
                        }
                        PendingInput::PointerMove(x, y, time_ms, source) => {
                            shell.set_pointer_source(source);
                            shell.set_cursor_at_time(x, y, time_ms);
                        }
                        PendingInput::Key(event) => {
                            shell.on_key_event(&event);
                        }
                        PendingInput::SecondaryPointerDown(id, x, y, time_ms) => {
                            // Additional fingers of a multi-touch gesture: touch.
                            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);
                        }
                    }
                }
            }
        }

        // Mirror the editor state back to the Java InputConnection after
        // input handling: refreshes the IME's selection view and restarts
        // the input session when the field content diverged from the mirror
        // (e.g. the app transformed or rejected input).
        if ime_session.is_active() {
            if let Some(shell) = &mut app_shell {
                ime_session.sync_editor_state(shell.ime_editor_state());
            }
        }

        // Check if app side requested a frame (animations, state changes)
        if android_frame_driver.take_frame_request() {
            if let Some(shell) = &mut app_shell {
                shell.mark_dirty();
            }
        }

        confirm_android_host_window_request(
            &mut pending_host_window_confirmation,
            current_host_window_size,
        );

        // Check if Destroy event requested exit
        if should_exit.load(Ordering::Relaxed) {
            log::info!("Exiting cleanly after Destroy event");
            break;
        }

        // Render outside event callback if needed
        if let (Some(resources), Some(shell)) = (&mut gpu_resources, &mut app_shell) {
            if shell.needs_update() {
                let update_result = android_host_window::with_android_host_window_registry(
                    &host_window_registry,
                    || shell.update(),
                );
                dispatch_registered_android_surface_size_request(
                    &app,
                    &host_window_registry,
                    android_platform.scale_factor(),
                    overlay_window_options,
                    &mut last_dispatched_host_window_request,
                    &mut pending_host_window_confirmation,
                );
                if surface_present_required(
                    resources.surface_dirty,
                    update_result.visual_changed,
                    shell.needs_redraw(),
                ) && render_once(resources, shell)
                {
                    break; // Out of memory, exit
                }
            }
        }
    }
}