rust_widgets 1.1.3

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Android JNI bridge — native method implementations for creating
//! real Android native views (Button, TextView, EditText, etc.)
//! corresponding to rust_widgets logical widgets.
//!
//! # Architecture
//!
//! This module exports `#[no_mangle]` JNI native methods that are called
//! from Java/Kotlin code on the Android side. The Java class
//! `rust.widgets.RustWidgets` loads the native library and calls these
//! methods to create and manage Android native `View` objects.
//!
//! # Java-side usage
//!
//! ```java
//! package rust.widgets;
//!
//! public class RustWidgets {
//!     static { System.loadLibrary("rust_widgets"); }
//!
//!     public static native void nativeInit();
//!     public static native long nativeCreateButton(
//!         android.content.Context context, String text,
//!         int x, int y, int w, int h);
//!     // … more native methods …
//! }
//! ```
//!
//! # Thread safety
//!
//! The `JAVA_VM` static is set once during initialization and is then
//! immutable. The view registry is protected by a `Mutex`. All public
//! JNI entry points are safe to call from any thread.

use crate::core::ObjectId;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

// ---------------------------------------------------------------------------
// Android logcat logger
// ---------------------------------------------------------------------------

/// Install a `log` backend that forwards to Android's logcat.
///
/// Without this the bridge's `log::info!` / `log::error!` diagnostics go
/// nowhere on-device, because no global logger is set. `__android_log_write`
/// comes from liblog, which every Android process already links, so this adds
/// no dependency. Installed once from `nativeInit`; safe to call repeatedly.
pub fn init_logging() {
    static INSTALLED: std::sync::Once = std::sync::Once::new();
    INSTALLED.call_once(|| {
        // Ignore the error: if the host already installed a logger we keep it.
        let _ = log::set_logger(&LOGCAT_LOGGER);
        log::set_max_level(log::LevelFilter::Info);
    });
}

struct LogcatLogger;

static LOGCAT_LOGGER: LogcatLogger = LogcatLogger;

/// Map a `log` level to the logcat priority constants from `<android/log.h>`.
fn logcat_priority(level: log::Level) -> i32 {
    // ANDROID_LOG_VERBOSE=2, DEBUG=3, INFO=4, WARN=5, ERROR=6
    match level {
        log::Level::Trace => 2,
        log::Level::Debug => 3,
        log::Level::Info => 4,
        log::Level::Warn => 5,
        log::Level::Error => 6,
    }
}

impl log::Log for LogcatLogger {
    fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
        metadata.level() <= log::Level::Info
    }

    fn log(&self, record: &log::Record<'_>) {
        if !self.enabled(record.metadata()) {
            return;
        }
        let tag = std::ffi::CString::new("rust_widgets").unwrap_or_default();
        // `log::Record::args()` formatting allocates; acceptable for a
        // diagnostic path that only runs when logging is enabled.
        let message = std::ffi::CString::new(format!("{}", record.args()))
            .unwrap_or_else(|_| std::ffi::CString::new("(message contained NUL)").unwrap());
        unsafe {
            android_log_write(logcat_priority(record.level()), tag.as_ptr(), message.as_ptr());
        }
    }

    fn flush(&self) {}
}

// ---------------------------------------------------------------------------
// liblog FFI
// ---------------------------------------------------------------------------

extern "C" {
    /// `int __android_log_write(int prio, const char* tag, const char* text)`
    /// from `<android/log.h>`; provided by liblog on every Android device.
    #[link_name = "__android_log_write"]
    fn android_log_write(
        prio: i32,
        tag: *const std::os::raw::c_char,
        text: *const std::os::raw::c_char,
    ) -> i32;
}

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Global JavaVM reference, set once by the JNI_OnLoad / nativeInit entry.
static JAVA_VM: OnceLock<jni::JavaVM> = OnceLock::new();

/// Thread-safe registry mapping rust_widgets ObjectId → JNI GlobalRef.
///
/// GlobalRefs are created via `JNIEnv::new_global_ref()` and stored here
/// so the JNI object is not garbage-collected as long as the widget exists.
static VIEW_REGISTRY: OnceLock<Mutex<HashMap<ObjectId, jni::objects::GlobalRef>>> = OnceLock::new();

fn view_registry() -> &'static Mutex<HashMap<ObjectId, jni::objects::GlobalRef>> {
    VIEW_REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}

/// GlobalRef to the Android `Context` (usually the hosting `Activity`).
///
/// Set once from Java via [`set_activity_context`]. Without it the Rust-callable
/// view factory helpers cannot construct Android widgets, so
/// [`create_native_view`] returns `None` and the caller keeps the state-only
/// path.
static ACTIVITY_CONTEXT: OnceLock<Mutex<Option<jni::objects::GlobalRef>>> = OnceLock::new();

fn activity_context_slot() -> &'static Mutex<Option<jni::objects::GlobalRef>> {
    ACTIVITY_CONTEXT.get_or_init(|| Mutex::new(None))
}

/// Store the Android `Context` used by [`create_native_view`].
///
/// Called from the Java side (or `attach_to_native_view`) with a JNI local
/// reference; a `GlobalRef` is created internally so the Context outlives the
/// calling frame.
///
/// Returns `true` when the reference was stored.
pub fn set_activity_context(
    env: &mut jni::JNIEnv<'_>,
    context: &jni::objects::JObject<'_>,
) -> bool {
    let global = match env.new_global_ref(context) {
        Ok(g) => g,
        Err(e) => {
            log::error!("[android-jni] set_activity_context: failed to create GlobalRef: {e}");
            return false;
        }
    };
    let mut slot = activity_context_slot().lock().expect("activity context lock poisoned");
    *slot = Some(global);
    log::info!("[android-jni] activity Context stored");
    true
}

/// Returns `true` when a Context has been stored and native view creation can
/// proceed.
pub fn has_activity_context() -> bool {
    activity_context_slot().lock().map(|slot| slot.is_some()).unwrap_or(false)
}

/// Canonical readiness predicate for native view creation.
///
/// Native views require **both** the `JavaVM` (from `nativeInit`) and an
/// Activity `Context` (from [`set_activity_context`]). This is the single source
/// of truth used by `AndroidPlatform::jni_available` and the Rust-callable view
/// factory, so the two can never disagree about whether the bridge is usable.
pub fn native_view_creation_ready() -> bool {
    is_initialized() && has_activity_context()
}

/// Internal helper to generate fresh ObjectId values.
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

fn allocate_id() -> ObjectId {
    NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

// ---------------------------------------------------------------------------
// Public helpers (used by AndroidMobilePlatform when JNI is available)
// ---------------------------------------------------------------------------

/// Returns `true` when the JNI bridge has been initialized (JavaVM stored).
pub fn is_initialized() -> bool {
    JAVA_VM.get().is_some()
}

/// Integration status report for the Android JNI backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IntegrationStatus {
    /// Whether `JAVA_VM` has been initialized via `nativeInit`.
    pub jni_initialized: bool,
    /// Number of `#[no_mangle]` JNI native method implementations exported.
    pub native_methods_count: u32,
    /// Overall readiness: JNI initialized + methods available.
    pub ready: bool,
}

/// Returns the current integration readiness of the Android JNI backend.
pub fn android_integration_ready() -> IntegrationStatus {
    let jni_initialized = JAVA_VM.get().is_some();
    let native_methods_count = 13;
    IntegrationStatus {
        jni_initialized,
        native_methods_count,
        ready: jni_initialized && native_methods_count > 0,
    }
}

/// Attach the current thread to the Java VM and call `f` with a `JNIEnv`.
///
/// Returns the result of `f`, or `None` if the bridge was never initialized
/// or thread attachment fails.
pub fn with_jni_env<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&mut jni::JNIEnv<'_>) -> R,
{
    let vm = JAVA_VM.get()?;
    let mut guard = vm.attach_current_thread().ok()?;
    Some(f(&mut guard))
}

/// Store a JNI GlobalRef for a given widget ObjectId.
pub fn register_view(id: ObjectId, global_ref: jni::objects::GlobalRef) {
    view_registry().lock().expect("view registry lock poisoned").insert(id, global_ref);
}

/// Look up a stored GlobalRef by widget ObjectId.
pub fn lookup_view(id: ObjectId) -> Option<jni::objects::GlobalRef> {
    view_registry().lock().expect("view registry lock poisoned").get(&id).cloned()
}

/// Remove and drop a GlobalRef for a given widget ObjectId.
pub fn unregister_view(id: ObjectId) {
    view_registry().lock().expect("view registry lock poisoned").remove(&id);
}

// ---------------------------------------------------------------------------
// Rust-callable view factory (used by AndroidPlatform::create_* when the
// `android-jni` feature is on). The `#[no_mangle] Java_*` entry points below
// are the inverse direction (Java → Rust); these helpers are Rust → Java so
// `platform_impl` actually constructs native views instead of only recording
// logical state.
// ---------------------------------------------------------------------------

/// Android widget class selected by [`create_native_view`].
///
/// Mirrors the view types the `Java_*` entry points construct, so both
/// directions create the same widget for a given logical kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AndroidViewClass {
    /// `android.widget.Button`.
    Button,
    /// `android.widget.TextView` (labels and status text).
    TextView,
    /// `android.widget.EditText`.
    EditText,
    /// `android.widget.CheckBox`.
    CheckBox,
    /// `android.widget.RadioButton`.
    RadioButton,
    /// `android.widget.SeekBar`.
    SeekBar,
    /// `android.widget.ProgressBar`.
    ProgressBar,
    /// `android.widget.Spinner`.
    Spinner,
    /// `android.widget.ListView`.
    ListView,
    /// `android.widget.ScrollView`.
    ScrollView,
    /// `android.widget.NumberPicker`.
    NumberPicker,
    /// `android.widget.FrameLayout` (generic container / panel).
    FrameLayout,
}

/// Logical widget kind → native Android view class mapping.
///
/// This is the single source of truth for which logical kinds get a real
/// Android `View`. Kinds without a standalone View (menus, dialogs, toolbars)
/// deliberately return `None` so callers keep the logical handle instead of
/// pretending a native object exists. Kept here (rather than in the
/// `target_os = "android"` module) so the mapping is unit-testable on any host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AndroidLogicalKind {
    Window,
    Button,
    CheckBox,
    LineEdit,
    Label,
    RadioButton,
    Slider,
    ProgressBar,
    ComboBox,
    ListBox,
    Panel,
    MenuBar,
    Menu,
    MenuItem,
    ToolBar,
    StatusBar,
    MessageBox,
    FileDialog,
    ColorDialog,
    FontDialog,
    SpinBox,
    ListView,
    ScrollArea,
}

/// Resolve the native view class for a logical kind, or `None` when the kind
/// has no standalone Android View equivalent.
pub fn view_class_for(kind: AndroidLogicalKind) -> Option<AndroidViewClass> {
    use AndroidLogicalKind::*;
    Some(match kind {
        Button => AndroidViewClass::Button,
        Label | StatusBar => AndroidViewClass::TextView,
        LineEdit => AndroidViewClass::EditText,
        CheckBox => AndroidViewClass::CheckBox,
        RadioButton => AndroidViewClass::RadioButton,
        Slider => AndroidViewClass::SeekBar,
        ProgressBar => AndroidViewClass::ProgressBar,
        ComboBox => AndroidViewClass::Spinner,
        ListBox | ListView => AndroidViewClass::ListView,
        ScrollArea => AndroidViewClass::ScrollView,
        SpinBox => AndroidViewClass::NumberPicker,
        Panel | Window => AndroidViewClass::FrameLayout,
        MenuBar | Menu | MenuItem | ToolBar | MessageBox | FileDialog | ColorDialog
        | FontDialog => return None,
    })
}

impl AndroidViewClass {
    /// JNI class path passed to `JNIEnv::find_class`.
    fn jni_class_path(self) -> &'static str {
        match self {
            AndroidViewClass::Button => "android/widget/Button",
            AndroidViewClass::TextView => "android/widget/TextView",
            AndroidViewClass::EditText => "android/widget/EditText",
            AndroidViewClass::CheckBox => "android/widget/CheckBox",
            AndroidViewClass::RadioButton => "android/widget/RadioButton",
            AndroidViewClass::SeekBar => "android/widget/SeekBar",
            AndroidViewClass::ProgressBar => "android/widget/ProgressBar",
            AndroidViewClass::Spinner => "android/widget/Spinner",
            AndroidViewClass::ListView => "android/widget/ListView",
            AndroidViewClass::ScrollView => "android/widget/ScrollView",
            AndroidViewClass::NumberPicker => "android/widget/NumberPicker",
            AndroidViewClass::FrameLayout => "android/widget/FrameLayout",
        }
    }

    /// Whether the widget implements `setText(CharSequence)`.
    fn supports_text(self) -> bool {
        matches!(
            self,
            AndroidViewClass::Button
                | AndroidViewClass::TextView
                | AndroidViewClass::EditText
                | AndroidViewClass::CheckBox
                | AndroidViewClass::RadioButton
        )
    }
}

/// Create a native Android view, apply its layout, and register a GlobalRef.
///
/// Returns the JNI registry id (a fresh [`ObjectId`]) on success, or `None`
/// when the bridge is not initialized, no Activity Context has been stored, or
/// the JVM rejects the construction. `None` means the caller should keep the
/// logical state handle without a native counterpart.
pub fn create_native_view(
    class: AndroidViewClass,
    text: &str,
    x: i32,
    y: i32,
    width: u32,
    height: u32,
) -> Option<ObjectId> {
    if !is_initialized() {
        return None;
    }
    with_jni_env(|env| create_view_with_env(env, class, text, x, y, width, height)).flatten()
}

fn create_view_with_env(
    env: &mut jni::JNIEnv<'_>,
    class: AndroidViewClass,
    text: &str,
    x: i32,
    y: i32,
    width: u32,
    height: u32,
) -> Option<ObjectId> {
    // Hold the Context lock only while cloning the reference; the actual JNI
    // calls below must not run under the registry lock to avoid re-entrancy.
    let context = {
        let slot = activity_context_slot().lock().expect("activity context lock poisoned");
        slot.as_ref()?.clone()
    };
    let context_obj = context.as_obj();

    let class_path = class.jni_class_path();
    let view_class = env.find_class(class_path).ok()?;
    let view = env
        .new_object(
            &view_class,
            "(Landroid/content/Context;)V",
            &[jni::objects::JValue::Object(context_obj)],
        )
        .ok()?;

    if class.supports_text() && !text.is_empty() {
        if let Ok(java_text) = env.new_string(text) {
            if let Err(e) = env.call_method(
                &view,
                "setText",
                "(Ljava/lang/CharSequence;)V",
                &[jni::objects::JValue::Object(&java_text)],
            ) {
                log::warn!("[android-jni] create_native_view({class_path}): setText failed: {e}");
            }
        }
    }

    apply_view_layout(env, &view, x, y, width as i32, height as i32);

    let id = allocate_id();
    let global = env.new_global_ref(&view).ok()?;
    register_view(id, global);
    log::info!("[android-jni] create_native_view({class_path}) -> id={id}");
    Some(id)
}

/// Destroy a native view previously created by [`create_native_view`].
///
/// Returns `true` when a registered view was found and released.
pub fn destroy_native_view(id: ObjectId) -> bool {
    if lookup_view(id).is_none() {
        return false;
    }
    unregister_view(id);
    true
}

/// Set the text of a native view created by [`create_native_view`].
pub fn set_native_view_text(id: ObjectId, text: &str) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let java_text = match env.new_string(text) {
            Ok(t) => t,
            Err(e) => {
                log::error!("[android-jni] set_native_view_text({id}): new_string failed: {e}");
                return false;
            }
        };
        env.call_method(
            global.as_obj(),
            "setText",
            "(Ljava/lang/CharSequence;)V",
            &[jni::objects::JValue::Object(&java_text)],
        )
        .is_ok()
    })
    .unwrap_or(false)
}

/// Update the bounds of a native view created by [`create_native_view`].
pub fn set_native_view_bounds(id: ObjectId, x: i32, y: i32, width: u32, height: u32) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        apply_view_layout(env, global.as_obj(), x, y, width as i32, height as i32);
        true
    })
    .unwrap_or(false)
}

/// Set the visibility of a native view. `View.VISIBLE` = 0, `View.GONE` = 8.
pub fn set_native_view_visibility(id: ObjectId, visible: bool) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let visibility = if visible { 0 } else { 8 };
        env.call_method(
            global.as_obj(),
            "setVisibility",
            "(I)V",
            &[jni::objects::JValue::Int(visibility)],
        )
        .is_ok()
    })
    .unwrap_or(false)
}

/// Set the enabled state of a native view.
pub fn set_native_view_enabled(id: ObjectId, enabled: bool) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        env.call_method(
            global.as_obj(),
            "setEnabled",
            "(Z)V",
            &[jni::objects::JValue::Bool(if enabled {
                jni::sys::JNI_TRUE
            } else {
                jni::sys::JNI_FALSE
            })],
        )
        .is_ok()
    })
    .unwrap_or(false)
}

/// Append an item to a native `Spinner` adapter.
///
/// `Spinner` is backed by an `ArrayAdapter<String>`; the adapter is created on
/// the first item and reused afterwards so selecting an index keeps working.
/// `set_selection` is applied only for the first item so later appends do not
/// reset an existing user selection.
pub fn append_spinner_item(id: ObjectId, text: &str, set_selection: bool) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let spinner = global.as_obj();
        let java_text = match env.new_string(text) {
            Ok(t) => t,
            Err(e) => {
                log::error!("[android-jni] append_spinner_item({id}): new_string failed: {e}");
                return false;
            }
        };

        // Reuse the ArrayAdapter attached to the Spinner when one exists;
        // otherwise create a simple spinner-item layout adapter.
        let adapter = match env.call_method(spinner, "getAdapter", "()Landroid/widget/SpinnerAdapter;", &[])
        {
            Ok(v) => v.l().ok().filter(|o| !o.is_null()),
            Err(e) => {
                log::error!("[android-jni] append_spinner_item({id}): getAdapter failed: {e}");
                return false;
            }
        };

        let added = match adapter {
            Some(adapter_obj) => env
                .call_method(
                    &adapter_obj,
                    "add",
                    "(Ljava/lang/Object;)V",
                    &[jni::objects::JValue::Object(&java_text)],
                )
                .is_ok(),
            None => {
                // No adapter yet: build an ArrayAdapter<String> over the
                // standard Android spinner item layout.
                let array_adapter_class = match env.find_class("android/widget/ArrayAdapter") {
                    Ok(c) => c,
                    Err(e) => {
                        log::error!("[android-jni] append_spinner_item({id}): ArrayAdapter class missing: {e}");
                        return false;
                    }
                };
                let context = match spinner_context(env, spinner) {
                    Some(c) => c,
                    None => return false,
                };
                let layout = match env.get_static_field(
                    "android/R$layout",
                    "simple_spinner_item",
                    "I",
                ) {
                    Ok(v) => v.i().unwrap_or(0),
                    Err(_) => 0,
                };
                let adapter = match env.new_object(
                    &array_adapter_class,
                    "(Landroid/content/Context;I)V",
                    &[
                        jni::objects::JValue::Object(&context),
                        jni::objects::JValue::Int(layout),
                    ],
                ) {
                    Ok(a) => a,
                    Err(e) => {
                        log::error!("[android-jni] append_spinner_item({id}): ArrayAdapter creation failed: {e}");
                        return false;
                    }
                };
                if env
                    .call_method(
                        &adapter,
                        "add",
                        "(Ljava/lang/Object;)V",
                        &[jni::objects::JValue::Object(&java_text)],
                    )
                    .is_err()
                {
                    log::error!("[android-jni] append_spinner_item({id}): adapter.add failed");
                    return false;
                }
                env.call_method(
                    spinner,
                    "setAdapter",
                    "(Landroid/widget/SpinnerAdapter;)V",
                    &[jni::objects::JValue::Object(&adapter)],
                )
                .is_ok()
            }
        };
        if !added {
            return false;
        }
        if set_selection {
            let _ = env.call_method(
                spinner,
                "setSelection",
                "(I)V",
                &[jni::objects::JValue::Int(0)],
            );
        }
        true
    })
    .unwrap_or(false)
}

/// Fetch the `Context` a view was constructed with, for adapter creation.
fn spinner_context<'local>(
    env: &mut jni::JNIEnv<'local>,
    view: &jni::objects::JObject<'local>,
) -> Option<jni::objects::JObject<'local>> {
    env.call_method(view, "getContext", "()Landroid/content/Context;", &[])
        .ok()
        .and_then(|v| v.l().ok())
        .filter(|o| !o.is_null())
}

/// Append items to a native `ListView` adapter (or install a new adapter that
/// contains exactly `texts` when none is attached yet).
///
/// Uses the standard `android.R.layout.simple_list_item_1` row layout so the
/// list is usable without application-provided resources.
pub fn append_list_item(id: ObjectId, texts: &[&str]) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let list_view = global.as_obj();

        let existing = env
            .call_method(list_view, "getAdapter", "()Landroid/widget/ListAdapter;", &[])
            .ok()
            .and_then(|v| v.l().ok())
            .filter(|o| !o.is_null());

        if let Some(adapter) = existing {
            for text in texts {
                let java_text = match env.new_string(*text) {
                    Ok(t) => t,
                    Err(e) => {
                        log::error!("[android-jni] append_list_item({id}): new_string failed: {e}");
                        return false;
                    }
                };
                if let Err(e) = env.call_method(
                    &adapter,
                    "add",
                    "(Ljava/lang/Object;)V",
                    &[jni::objects::JValue::Object(&java_text)],
                ) {
                    log::error!("[android-jni] append_list_item({id}): adapter.add failed: {e}");
                    return false;
                }
            }
            return true;
        }

        // No adapter yet: build an ArrayAdapter<String> seeded with all items.
        let array_adapter_class = match env.find_class("android/widget/ArrayAdapter") {
            Ok(c) => c,
            Err(e) => {
                log::error!(
                    "[android-jni] append_list_item({id}): ArrayAdapter class missing: {e}"
                );
                return false;
            }
        };
        let context = match spinner_context(env, list_view) {
            Some(c) => c,
            None => return false,
        };
        let layout = env
            .get_static_field("android/R$layout", "simple_list_item_1", "I")
            .ok()
            .and_then(|v| v.i().ok())
            .unwrap_or(0);
        let adapter = match env.new_object(
            &array_adapter_class,
            "(Landroid/content/Context;I)V",
            &[jni::objects::JValue::Object(&context), jni::objects::JValue::Int(layout)],
        ) {
            Ok(a) => a,
            Err(e) => {
                log::error!(
                    "[android-jni] append_list_item({id}): ArrayAdapter creation failed: {e}"
                );
                return false;
            }
        };
        for text in texts {
            let java_text = match env.new_string(*text) {
                Ok(t) => t,
                Err(e) => {
                    log::error!("[android-jni] append_list_item({id}): new_string failed: {e}");
                    return false;
                }
            };
            if let Err(e) = env.call_method(
                &adapter,
                "add",
                "(Ljava/lang/Object;)V",
                &[jni::objects::JValue::Object(&java_text)],
            ) {
                log::error!("[android-jni] append_list_item({id}): adapter.add failed: {e}");
                return false;
            }
        }
        if let Err(e) = env.call_method(
            list_view,
            "setAdapter",
            "(Landroid/widget/ListAdapter;)V",
            &[jni::objects::JValue::Object(&adapter)],
        ) {
            log::error!("[android-jni] append_list_item({id}): setAdapter failed: {e}");
            return false;
        }
        true
    })
    .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// JNI entry points — called from Java side
// ---------------------------------------------------------------------------

/// Initialize the JNI bridge. Called from Java when native lib is loaded.
///
/// Java equivalent:
/// ```java
/// public static native void nativeInit();
/// ```
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeInit(
    env: jni::JNIEnv,
    _class: jni::objects::JClass,
) {
    // Install the logcat backend first so the messages below are visible.
    init_logging();
    match env.get_java_vm() {
        Ok(vm) => {
            if JAVA_VM.set(vm).is_ok() {
                log::info!("[android-jni] JavaVM stored, native library initialized");
            } else {
                log::info!("[android-jni] JavaVM already initialized (duplicate call)");
            }
        }
        Err(e) => {
            log::error!("[android-jni] failed to get JavaVM: {e}");
        }
    }
}

/// Create an Android `android.widget.Button`.
///
/// Returns a `jlong` representing the rust_widgets ObjectId, or `0` on failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateButton<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    text: jni::objects::JString<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeCreateButton: failed to get text string: {e}");
            return 0;
        }
    };

    log::info!("[android-jni] nativeCreateButton: text={text_str}, pos=({x},{y}), size=({w},{h})");

    // Find the android.widget.Button class
    let button_class = match env.find_class("android/widget/Button") {
        Ok(c) => c,
        Err(e) => {
            log::error!("[android-jni] nativeCreateButton: cannot find android/widget/Button: {e}");
            return 0;
        }
    };

    // Create a new Button(context)
    let button = match env.new_object(
        &button_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(b) => b,
        Err(e) => {
            log::error!("[android-jni] nativeCreateButton: failed to create Button: {e}");
            return 0;
        }
    };

    // Set text
    if let Err(e) = env.call_method(
        &button,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeCreateButton: setText failed: {e}");
    }

    // Create LayoutParams for positioning
    apply_view_layout(&mut env, &button, x, y, w, h);

    // Store as global ref
    let id = allocate_id();
    match env.new_global_ref(&button) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateButton: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.TextView` (used for Label).
///
/// Returns a `jlong` representing the rust_widgets ObjectId, or `0` on failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateTextView<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    text: jni::objects::JString<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeCreateTextView: failed to get text string: {e}");
            return 0;
        }
    };

    log::info!(
        "[android-jni] nativeCreateTextView: text={text_str}, pos=({x},{y}), size=({w},{h})"
    );

    let text_view_class = match env.find_class("android/widget/TextView") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateTextView: cannot find android/widget/TextView: {e}"
            );
            return 0;
        }
    };

    let text_view = match env.new_object(
        &text_view_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(tv) => tv,
        Err(e) => {
            log::error!("[android-jni] nativeCreateTextView: failed to create TextView: {e}");
            return 0;
        }
    };

    // Set text
    if let Err(e) = env.call_method(
        &text_view,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeCreateTextView: setText failed: {e}");
    }

    apply_view_layout(&mut env, &text_view, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&text_view) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateTextView: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.EditText` (used for LineEdit).
///
/// Returns a `jlong` representing the rust_widgets ObjectId, or `0` on failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateEditText<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    text: jni::objects::JString<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeCreateEditText: failed to get text string: {e}");
            return 0;
        }
    };

    log::info!(
        "[android-jni] nativeCreateEditText: text={text_str}, pos=({x},{y}), size=({w},{h})"
    );

    let edit_text_class = match env.find_class("android/widget/EditText") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateEditText: cannot find android/widget/EditText: {e}"
            );
            return 0;
        }
    };

    let edit_text = match env.new_object(
        &edit_text_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(et) => et,
        Err(e) => {
            log::error!("[android-jni] nativeCreateEditText: failed to create EditText: {e}");
            return 0;
        }
    };

    // Set text
    if let Err(e) = env.call_method(
        &edit_text,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeCreateEditText: setText failed: {e}");
    }

    apply_view_layout(&mut env, &edit_text, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&edit_text) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateEditText: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.CheckBox`.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateCheckBox<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    text: jni::objects::JString<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeCreateCheckBox: failed to get text string: {e}");
            return 0;
        }
    };

    log::info!(
        "[android-jni] nativeCreateCheckBox: text={text_str}, pos=({x},{y}), size=({w},{h})"
    );

    let check_box_class = match env.find_class("android/widget/CheckBox") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateCheckBox: cannot find android/widget/CheckBox: {e}"
            );
            return 0;
        }
    };

    let check_box = match env.new_object(
        &check_box_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(cb) => cb,
        Err(e) => {
            log::error!("[android-jni] nativeCreateCheckBox: failed to create CheckBox: {e}");
            return 0;
        }
    };

    if let Err(e) = env.call_method(
        &check_box,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeCreateCheckBox: setText failed: {e}");
    }

    apply_view_layout(&mut env, &check_box, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&check_box) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateCheckBox: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.RadioButton`.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateRadioButton<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    text: jni::objects::JString<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeCreateRadioButton: failed to get text string: {e}");
            return 0;
        }
    };

    log::info!(
        "[android-jni] nativeCreateRadioButton: text={text_str}, pos=({x},{y}), size=({w},{h})"
    );

    let radio_button_class = match env.find_class("android/widget/RadioButton") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateRadioButton: cannot find android/widget/RadioButton: {e}"
            );
            return 0;
        }
    };

    let radio_button = match env.new_object(
        &radio_button_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(rb) => rb,
        Err(e) => {
            log::error!("[android-jni] nativeCreateRadioButton: failed to create RadioButton: {e}");
            return 0;
        }
    };

    if let Err(e) = env.call_method(
        &radio_button,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeCreateRadioButton: setText failed: {e}");
    }

    apply_view_layout(&mut env, &radio_button, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&radio_button) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateRadioButton: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.ProgressBar`.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateProgressBar<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    log::info!("[android-jni] nativeCreateProgressBar: pos=({x},{y}), size=({w},{h})");

    let progress_bar_class = match env.find_class("android/widget/ProgressBar") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateProgressBar: cannot find android/widget/ProgressBar: {e}"
            );
            return 0;
        }
    };

    let progress_bar = match env.new_object(
        &progress_bar_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(pb) => pb,
        Err(e) => {
            log::error!("[android-jni] nativeCreateProgressBar: failed to create ProgressBar: {e}");
            return 0;
        }
    };

    apply_view_layout(&mut env, &progress_bar, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&progress_bar) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateProgressBar: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

/// Create an Android `android.widget.SeekBar` (used for Slider).
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeCreateSeekBar<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    context: jni::objects::JObject<'local>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) -> jni::sys::jlong {
    log::info!("[android-jni] nativeCreateSeekBar: pos=({x},{y}), size=({w},{h})");

    let seek_bar_class = match env.find_class("android/widget/SeekBar") {
        Ok(c) => c,
        Err(e) => {
            log::error!(
                "[android-jni] nativeCreateSeekBar: cannot find android/widget/SeekBar: {e}"
            );
            return 0;
        }
    };

    let seek_bar = match env.new_object(
        &seek_bar_class,
        "(Landroid/content/Context;)V",
        &[jni::objects::JValue::Object(&context)],
    ) {
        Ok(sb) => sb,
        Err(e) => {
            log::error!("[android-jni] nativeCreateSeekBar: failed to create SeekBar: {e}");
            return 0;
        }
    };

    apply_view_layout(&mut env, &seek_bar, x, y, w, h);

    let id = allocate_id();
    match env.new_global_ref(&seek_bar) {
        Ok(global_ref) => {
            register_view(id, global_ref);
        }
        Err(e) => {
            log::error!("[android-jni] nativeCreateSeekBar: failed to create global ref: {e}");
            return 0;
        }
    }

    id as jni::sys::jlong
}

// ---------------------------------------------------------------------------
// View manipulation helpers & JNI methods
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Dialog factory (AlertDialog)
// ---------------------------------------------------------------------------

/// Register a dialog object in the same registry as views.
///
/// Dialogs and views share the `ObjectId` space so `lookup_view` resolves both;
/// a dialog is simply an object that implements `show()` / `dismiss()` rather
/// than a `View`.
fn register_dialog(
    id: ObjectId,
    env: &mut jni::JNIEnv<'_>,
    dialog: &jni::objects::JObject<'_>,
) -> bool {
    match env.new_global_ref(dialog) {
        Ok(global) => {
            register_view(id, global);
            true
        }
        Err(e) => {
            log::error!("[android-jni] register_dialog: failed to create GlobalRef: {e}");
            false
        }
    }
}

/// Build an `AlertDialog` on the stored Activity Context.
///
/// Returns the registry id on success. Requires the Activity Context
/// ([`set_activity_context`]) because `AlertDialog.Builder` needs a Context, and
/// `show()` needs an Activity-backed window. `title`/`message` are optional in
/// the sense that an empty string simply yields an empty field.
pub fn create_native_dialog(title: &str, message: &str) -> Option<ObjectId> {
    if !is_initialized() {
        return None;
    }
    with_jni_env(|env| create_dialog_with_env(env, title, message)).flatten()
}

fn create_dialog_with_env(
    env: &mut jni::JNIEnv<'_>,
    title: &str,
    message: &str,
) -> Option<ObjectId> {
    let context = {
        let slot = activity_context_slot().lock().expect("activity context lock poisoned");
        slot.as_ref()?.clone()
    };
    let context_obj = context.as_obj();

    let builder_class = env.find_class("android/app/AlertDialog$Builder").ok()?;
    let builder = env
        .new_object(
            &builder_class,
            "(Landroid/content/Context;)V",
            &[jni::objects::JValue::Object(context_obj)],
        )
        .ok()?;

    if !title.is_empty() {
        let java_title = env.new_string(title).ok()?;
        if let Err(e) = env.call_method(
            &builder,
            "setTitle",
            "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;",
            &[jni::objects::JValue::Object(&java_title)],
        ) {
            log::warn!("[android-jni] create_native_dialog: setTitle failed: {e}");
        }
    }
    if !message.is_empty() {
        let java_message = env.new_string(message).ok()?;
        if let Err(e) = env.call_method(
            &builder,
            "setMessage",
            "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;",
            &[jni::objects::JValue::Object(&java_message)],
        ) {
            log::warn!("[android-jni] create_native_dialog: setMessage failed: {e}");
        }
    }

    let dialog = env
        .call_method(&builder, "create", "()Landroid/app/AlertDialog;", &[])
        .ok()
        .and_then(|v| v.l().ok())?;

    // Show it. `AlertDialog.show()` must run on a thread with a Looper; the
    // Java-side entry points are called from the UI thread, and the Rust-driven
    // path is documented to require the same.
    if let Err(e) = env.call_method(&dialog, "show", "()V", &[]) {
        log::warn!("[android-jni] create_native_dialog: show() failed: {e}");
    }

    let id = allocate_id();
    if !register_dialog(id, env, &dialog) {
        return None;
    }
    log::info!("[android-jni] create_native_dialog -> id={id}");
    Some(id)
}

/// Request code used for the `ACTION_OPEN_DOCUMENT` result.
///
/// The host Activity receives this in `onActivityResult` / its result
/// launcher; it is chosen to be unlikely to collide with app-defined codes.
pub const FILE_DIALOG_REQUEST_CODE: i32 = 0x5257; // "RW"

/// Launch the system document picker (`ACTION_OPEN_DOCUMENT`) for a file dialog.
///
/// Android has no `FileDialog` View: file selection is an *Activity* operation.
/// The bridge stores only a `Context` `GlobalRef`, so the Activity is recovered
/// by reflection: the stored object is first checked with `instanceof Activity`,
/// then `Activity.startActivityForResult(Intent, int)` is invoked on it. This is
/// the same mechanism (and the same constraint) documented for the backend — a
/// non-Activity Context cannot service a result launcher, and in that case this
/// returns `false` after logging an explicit diagnostic rather than silently
/// doing nothing.
///
/// Verified on a physical device (Xiaomi M2102J2SC, Android 13): the stored
/// Context is the Activity, the method resolves reflectively, and the picker
/// launches.
///
/// The result is delivered to the host Activity's own callback; the bridge does
/// not intercept it. Returns `true` when the picker was launched.
pub fn launch_file_dialog(mime_type: &str) -> bool {
    if !is_initialized() {
        log::info!("[android-jni] launch_file_dialog: bridge not initialized");
        return false;
    }
    with_jni_env(|env| launch_file_dialog_with_env(env, mime_type)).flatten().unwrap_or(false)
}

fn launch_file_dialog_with_env(env: &mut jni::JNIEnv<'_>, mime_type: &str) -> Option<bool> {
    let context = {
        let slot = activity_context_slot().lock().expect("activity context lock poisoned");
        slot.as_ref()?.clone()
    };
    let context_obj = context.as_obj();

    // A Context that is not an Activity cannot start a result launcher. Report
    // this precisely instead of pretending the request was serviced.
    let activity_class = match env.find_class("android/app/Activity") {
        Ok(c) => c,
        Err(e) => {
            log::error!("[android-jni] launch_file_dialog: Activity class missing: {e}");
            return Some(false);
        }
    };
    match env.is_instance_of(context_obj, &activity_class) {
        Ok(true) => {}
        Ok(false) => {
            log::warn!(
                "[android-jni] launch_file_dialog: stored Context is not an Activity, \
                 cannot launch a result launcher; pass the Activity to nativeAttachContext"
            );
            return Some(false);
        }
        Err(e) => {
            log::error!("[android-jni] launch_file_dialog: is_instance_of failed: {e}");
            return Some(false);
        }
    }

    // Intent(ACTION_OPEN_DOCUMENT) + CATEGORY_OPENABLE + setType(mime).
    let intent_class = match env.find_class("android/content/Intent") {
        Ok(c) => c,
        Err(e) => {
            log::error!("[android-jni] launch_file_dialog: Intent class missing: {e}");
            return Some(false);
        }
    };
    let action = env.new_string("android.intent.action.OPEN_DOCUMENT").ok()?;
    let intent = match env.new_object(
        &intent_class,
        "(Ljava/lang/String;)V",
        &[jni::objects::JValue::Object(&action)],
    ) {
        Ok(i) => i,
        Err(e) => {
            log::error!("[android-jni] launch_file_dialog: new Intent failed: {e}");
            return Some(false);
        }
    };

    let category = env.new_string("android.intent.category.OPENABLE").ok()?;
    if let Err(e) = env.call_method(
        &intent,
        "addCategory",
        "(Ljava/lang/String;)Landroid/content/Intent;",
        &[jni::objects::JValue::Object(&category)],
    ) {
        log::warn!("[android-jni] launch_file_dialog: addCategory failed: {e}");
    }

    // Default to any content when the caller gives no MIME type.
    let mime = if mime_type.is_empty() { "*/*" } else { mime_type };
    let mime_str = env.new_string(mime).ok()?;
    if let Err(e) = env.call_method(
        &intent,
        "setType",
        "(Ljava/lang/String;)Landroid/content/Intent;",
        &[jni::objects::JValue::Object(&mime_str)],
    ) {
        log::warn!("[android-jni] launch_file_dialog: setType failed: {e}");
    }

    // startActivityForResult(Intent, int) — resolved reflectively on the stored
    // object, which the instanceof check above proved is an Activity.
    if let Err(e) = env.call_method(
        context_obj,
        "startActivityForResult",
        "(Landroid/content/Intent;I)V",
        &[
            jni::objects::JValue::Object(&intent),
            jni::objects::JValue::Int(FILE_DIALOG_REQUEST_CODE),
        ],
    ) {
        log::error!("[android-jni] launch_file_dialog: startActivityForResult failed: {e}");
        return Some(false);
    }

    log::info!(
        "[android-jni] launch_file_dialog: ACTION_OPEN_DOCUMENT launched (mime={mime}, \
         requestCode={FILE_DIALOG_REQUEST_CODE})"
    );
    Some(true)
}

/// Update the message of a dialog created by [`create_native_dialog`].
pub fn set_native_dialog_message(id: ObjectId, message: &str) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let dialog = global.as_obj();
        let java_message = match env.new_string(message) {
            Ok(t) => t,
            Err(e) => {
                log::error!(
                    "[android-jni] set_native_dialog_message({id}): new_string failed: {e}"
                );
                return false;
            }
        };
        env.call_method(
            dialog,
            "setMessage",
            "(Ljava/lang/CharSequence;)V",
            &[jni::objects::JValue::Object(&java_message)],
        )
        .is_ok()
    })
    .unwrap_or(false)
}

/// Show or dismiss a dialog created by [`create_native_dialog`].
pub fn set_native_dialog_visible(id: ObjectId, visible: bool) -> bool {
    with_jni_env(|env| {
        let global = match lookup_view(id) {
            Some(g) => g,
            None => return false,
        };
        let dialog = global.as_obj();
        let method = if visible { "show" } else { "dismiss" };
        env.call_method(dialog, method, "()V", &[]).is_ok()
    })
    .unwrap_or(false)
}

/// Dismiss and release a dialog created by [`create_native_dialog`].
pub fn destroy_native_dialog(id: ObjectId) -> bool {
    if lookup_view(id).is_none() {
        return false;
    }
    let _ = set_native_dialog_visible(id, false);
    unregister_view(id);
    true
}

/// Apply layout params (position + size) to an Android View.
///
/// This creates a `ViewGroup.MarginLayoutParams` (or `LayoutParams` with
/// absolute coordinates) so the view appears at (x, y) with size (w, h).
fn apply_view_layout(
    env: &mut jni::JNIEnv<'_>,
    view: &jni::objects::JObject<'_>,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) {
    // Get the ViewGroup.LayoutParams class
    let lp_class = match env.find_class("android/view/ViewGroup$LayoutParams") {
        Ok(c) => c,
        Err(e) => {
            log::error!("[android-jni] apply_view_layout: cannot find LayoutParams class: {e}");
            return;
        }
    };

    // Create new LayoutParams(width, height)
    let lp = match env.new_object(
        &lp_class,
        "(II)V",
        &[jni::objects::JValue::Int(w), jni::objects::JValue::Int(h)],
    ) {
        Ok(lp) => lp,
        Err(e) => {
            log::error!("[android-jni] apply_view_layout: failed to create LayoutParams: {e}");
            return;
        }
    };

    // Store the original x/y in the LayoutParams's leftMargin/topMargin.
    // We directly set margins; if the parent doesn't support MarginLayoutParams,
    // the margin values are simply ignored by the layout system.
    if let Err(e) = env.call_method(view, "setLeft", "(I)V", &[jni::objects::JValue::Int(x)]) {
        log::error!("[android-jni] apply_view_layout: setLeft failed: {e}");
    }
    if let Err(e) = env.call_method(view, "setTop", "(I)V", &[jni::objects::JValue::Int(y)]) {
        log::error!("[android-jni] apply_view_layout: setTop failed: {e}");
    }

    // Set the layout params on the view
    if let Err(e) = env.call_method(
        view,
        "setLayoutParams",
        "(Landroid/view/ViewGroup$LayoutParams;)V",
        &[jni::objects::JValue::Object(&lp)],
    ) {
        log::error!("[android-jni] apply_view_layout: setLayoutParams failed: {e}");
    }
}

/// Set the text content of a View that has `setText(CharSequence)`.
///
/// Java equivalent:
/// ```java
/// public static native void nativeSetViewText(long nativePtr, String text);
/// ```
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSetViewText<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    native_ptr: jni::sys::jlong,
    text: jni::objects::JString<'local>,
) {
    let id = native_ptr as ObjectId;
    let text_str: String = match env.get_string(&text) {
        Ok(s) => s.into(),
        Err(e) => {
            log::error!("[android-jni] nativeSetViewText({id}): failed to get text string: {e}");
            return;
        }
    };

    let global_ref = match lookup_view(id) {
        Some(r) => r,
        None => {
            log::warn!("[android-jni] nativeSetViewText({id}): view not found in registry");
            return;
        }
    };

    let view_obj = global_ref.as_obj();
    if let Err(e) = env.call_method(
        view_obj,
        "setText",
        "(Ljava/lang/CharSequence;)V",
        &[jni::objects::JValue::Object(&text)],
    ) {
        log::error!("[android-jni] nativeSetViewText({id}): setText failed: {e}");
    }

    log::info!("[android-jni] nativeSetViewText({id}): text={text_str}");
}

/// Update the bounds (position + size) of a View by applying new LayoutParams.
///
/// Java equivalent:
/// ```java
/// public static native void nativeSetViewBounds(long nativePtr, int x, int y, int w, int h);
/// ```
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSetViewBounds<'local>(
    mut env: jni::JNIEnv<'local>,
    _class: jni::objects::JClass<'local>,
    native_ptr: jni::sys::jlong,
    x: jni::sys::jint,
    y: jni::sys::jint,
    w: jni::sys::jint,
    h: jni::sys::jint,
) {
    let id = native_ptr as ObjectId;
    log::info!("[android-jni] nativeSetViewBounds({id}): pos=({x},{y}), size=({w},{h})");

    let global_ref = match lookup_view(id) {
        Some(r) => r,
        None => {
            log::warn!("[android-jni] nativeSetViewBounds({id}): view not found in registry");
            return;
        }
    };

    let view_obj = global_ref.as_obj();
    apply_view_layout(&mut env, view_obj, x, y, w, h);
}

/// Set the visibility of a View.
///
/// `visible`: `JNI_TRUE` (1) for `View.VISIBLE`, `JNI_FALSE` (0) for `View.GONE`.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSetViewVisibility(
    mut env: jni::JNIEnv,
    _class: jni::objects::JClass,
    native_ptr: jni::sys::jlong,
    visible: jni::sys::jboolean,
) {
    let id = native_ptr as ObjectId;
    let visibility = if visible != 0 { 0 } else { 8 }; // View.VISIBLE = 0, View.GONE = 8

    let global_ref = match lookup_view(id) {
        Some(r) => r,
        None => {
            log::warn!("[android-jni] nativeSetViewVisibility({id}): view not found in registry");
            return;
        }
    };

    let view_obj = global_ref.as_obj();
    if let Err(e) =
        env.call_method(view_obj, "setVisibility", "(I)V", &[jni::objects::JValue::Int(visibility)])
    {
        log::error!("[android-jni] nativeSetViewVisibility({id}): setVisibility failed: {e}");
    }
}

/// Set the enabled state of a View.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSetViewEnabled(
    mut env: jni::JNIEnv,
    _class: jni::objects::JClass,
    native_ptr: jni::sys::jlong,
    enabled: jni::sys::jboolean,
) {
    let id = native_ptr as ObjectId;

    let global_ref = match lookup_view(id) {
        Some(r) => r,
        None => {
            log::warn!("[android-jni] nativeSetViewEnabled({id}): view not found in registry");
            return;
        }
    };

    let view_obj = global_ref.as_obj();
    if let Err(e) = env.call_method(
        view_obj,
        "setEnabled",
        "(Z)V",
        &[jni::objects::JValue::Bool(if enabled != 0 {
            jni::sys::JNI_TRUE
        } else {
            jni::sys::JNI_FALSE
        })],
    ) {
        log::error!("[android-jni] nativeSetViewEnabled({id}): setEnabled failed: {e}");
    }
}

/// Destroy (remove global ref for) a previously created View.
///
/// Called from Java when the widget is no longer needed.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeDestroyView(
    _env: jni::JNIEnv,
    _class: jni::objects::JClass,
    native_ptr: jni::sys::jlong,
) {
    let id = native_ptr as ObjectId;
    log::info!("[android-jni] nativeDestroyView({id})");
    unregister_view(id);
}

/// Hand the host Activity `Context` to the Rust-side view factory.
///
/// This enables the Rust→Java direction: once the Context is stored,
/// `AndroidPlatform::jni_available()` becomes true and `platform_impl`'s
/// `create_*` methods construct real Android views through
/// [`create_native_view`].
///
/// Returns `true` when the Context was stored.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeAttachContext(
    mut env: jni::JNIEnv,
    _class: jni::objects::JClass,
    context: jni::objects::JObject,
) -> jni::sys::jboolean {
    init_logging();
    if set_activity_context(&mut env, &context) {
        jni::sys::JNI_TRUE
    } else {
        jni::sys::JNI_FALSE
    }
}

/// Run the Rust-side `AndroidPlatform` create path for every native kind.
///
/// This exercises `platform_impl` → `attach_native_view` → JNI, i.e. the
/// direction that does not go through a per-call Java entry point. Returns the
/// number of widgets created, or a negative value on the first failure so the
/// caller can distinguish "not ready" (`-1`) from a partial failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSelfTestKinds(
    _env: jni::JNIEnv,
    _class: jni::objects::JClass,
) -> jni::sys::jint {
    init_logging();
    if !native_view_creation_ready() {
        log::error!("[android-jni] nativeSelfTestKinds: bridge not ready");
        return -1;
    }

    // The `AndroidPlatform` backend only exists on Android; on other hosts the
    // bridge is compiled for unit testing only, where there is no platform to
    // drive. Report "unsupported" rather than pretending to have run.
    #[cfg(not(target_os = "android"))]
    {
        log::warn!("[android-jni] nativeSelfTestKinds: not an Android target");
        -1
    }

    #[cfg(target_os = "android")]
    {
        use crate::platform::android::AndroidPlatform;
        use crate::platform::Platform;

        /// One `(name, constructor)` pair in the kind sweep below.
        type KindCreator = (&'static str, fn(&AndroidPlatform, u64) -> u64);

        let platform = AndroidPlatform::new();
        platform.init();

        let window = platform.create_window("selftest", 0, 0, 320, 640);
        if window == 0 {
            return -2;
        }

        // (name, constructor)
        let creators: [KindCreator; 7] = [
            ("Button", |p, w| p.create_button(w, "b", 0, 0, 100, 40)),
            ("Label", |p, w| p.create_label(w, "l", 0, 50, 100, 40)),
            ("LineEdit", |p, w| p.create_line_edit(w, "e", 0, 100, 100, 40)),
            ("CheckBox", |p, w| p.create_checkbox(w, "c", 0, 150, 100, 40)),
            ("RadioButton", |p, w| p.create_radio_button(w, "r", 0, 200, 100, 40)),
            ("ProgressBar", |p, w| p.create_progress_bar(w, 0, 250, 100, 40)),
            ("Slider", |p, w| p.create_slider(w, 0, 300, 100, 40)),
        ];

        let mut created = 0i32;
        for (name, create) in creators {
            let id = create(&platform, window);
            if id == 0 {
                log::error!("[android-jni] nativeSelfTestKinds: create {name} failed");
                return -3;
            }
            // A native view must actually back the logical handle.
            if platform.native_view_of(id).is_none() {
                log::error!("[android-jni] nativeSelfTestKinds: {name} has no native view");
                return -4;
            }
            created += 1;
            log::info!("[android-jni] nativeSelfTestKinds: {name} -> logical={id} ok");
        }
        created
    }
}

/// Exercise the Rust-side dialog path: create an `AlertDialog` through
/// `AndroidPlatform::create_message_box`, then update/dismiss/show it.
///
/// Returns `1` on success, or a negative value on the first failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSelfTestDialog(
    _env: jni::JNIEnv,
    _class: jni::objects::JClass,
) -> jni::sys::jint {
    init_logging();
    if !native_view_creation_ready() {
        log::error!("[android-jni] nativeSelfTestDialog: bridge not ready");
        return -1;
    }

    #[cfg(not(target_os = "android"))]
    {
        log::warn!("[android-jni] nativeSelfTestDialog: not an Android target");
        -1
    }

    #[cfg(target_os = "android")]
    {
        use crate::platform::android::AndroidPlatform;
        use crate::platform::Platform;

        let platform = AndroidPlatform::new();
        platform.init();

        let window = platform.create_window("dialog-test", 0, 0, 320, 640);
        if window == 0 {
            return -2;
        }
        let message_box =
            platform.create_message_box(window, "Self Test", "Hello from Rust", 0, 0, 240, 160);
        if message_box == 0 {
            return -3;
        }
        // The dialog must be a real native object, not just a logical handle.
        if platform.native_view_of(message_box).is_none() {
            log::error!("[android-jni] nativeSelfTestDialog: no native dialog");
            return -4;
        }
        // Body update must reach the AlertDialog setMessage().
        platform.set_widget_text(message_box, "Updated by Rust");
        // Hide/show must reach dismiss()/show().
        platform.hide_widget(message_box);
        platform.show_widget(message_box);
        log::info!("[android-jni] nativeSelfTestDialog: ok");
        1
    }
}

/// Exercise the Rust-side file-dialog path: create a file dialog through
/// `AndroidPlatform::create_file_dialog`, which must launch
/// `ACTION_OPEN_DOCUMENT` on the stored Activity.
///
/// Returns `1` on success, or a negative value on the first failure.
#[no_mangle]
pub extern "system" fn Java_rust_1widgets_RustWidgets_nativeSelfTestFileDialog(
    _env: jni::JNIEnv,
    _class: jni::objects::JClass,
) -> jni::sys::jint {
    init_logging();
    if !native_view_creation_ready() {
        log::error!("[android-jni] nativeSelfTestFileDialog: bridge not ready");
        return -1;
    }

    #[cfg(not(target_os = "android"))]
    {
        log::warn!("[android-jni] nativeSelfTestFileDialog: not an Android target");
        -1
    }

    #[cfg(target_os = "android")]
    {
        use crate::platform::android::AndroidPlatform;
        use crate::platform::Platform;

        let platform = AndroidPlatform::new();
        platform.init();

        let window = platform.create_window("file-dialog-test", 0, 0, 320, 640);
        if window == 0 {
            return -2;
        }
        // Creation requests the system picker; the result is delivered to the
        // host Activity's own callback.
        let file_dialog = platform.create_file_dialog(window, 0, 0, 240, 160);
        if file_dialog == 0 {
            log::error!("[android-jni] nativeSelfTestFileDialog: logical handle not created");
            return -3;
        }
        // Exercise the launch path directly so the return value is observable
        // (create_file_dialog only logs on failure).
        if !launch_file_dialog("*/*") {
            log::error!("[android-jni] nativeSelfTestFileDialog: picker not launched");
            return -4;
        }
        log::info!("[android-jni] nativeSelfTestFileDialog: ok");
        1
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_allocate_id_is_monotonic() {
        let id1 = allocate_id();
        let id2 = allocate_id();
        assert!(id2 > id1);
    }

    #[test]
    fn test_register_and_lookup_view() {
        // Create a mock ObjectId and a mock registry entry is not
        // possible without a real JVM. Verify the registry API doesn't panic.
        let id = 42;
        assert!(lookup_view(id).is_none());
        unregister_view(id); // should not panic
        assert!(lookup_view(id).is_none());
    }

    #[test]
    fn test_unregister_nonexistent_view() {
        unregister_view(999); // should not panic
    }

    #[test]
    fn test_view_class_paths_are_android_widgets() {
        // Every mapped class must live in the `android/widget` package, which is
        // what `JNIEnv::find_class` expects (slash-separated, no `.class`).
        let classes = [
            AndroidViewClass::Button,
            AndroidViewClass::TextView,
            AndroidViewClass::EditText,
            AndroidViewClass::CheckBox,
            AndroidViewClass::RadioButton,
            AndroidViewClass::SeekBar,
            AndroidViewClass::ProgressBar,
            AndroidViewClass::Spinner,
            AndroidViewClass::ListView,
            AndroidViewClass::ScrollView,
            AndroidViewClass::NumberPicker,
            AndroidViewClass::FrameLayout,
        ];
        for class in classes {
            assert!(
                class.jni_class_path().starts_with("android/widget/"),
                "unexpected class path {}",
                class.jni_class_path()
            );
        }
    }

    #[test]
    fn test_supports_text_matches_settext_capable_views() {
        assert!(AndroidViewClass::Button.supports_text());
        assert!(AndroidViewClass::TextView.supports_text());
        assert!(AndroidViewClass::EditText.supports_text());
        assert!(AndroidViewClass::CheckBox.supports_text());
        assert!(AndroidViewClass::RadioButton.supports_text());
        assert!(!AndroidViewClass::SeekBar.supports_text());
        assert!(!AndroidViewClass::ProgressBar.supports_text());
        assert!(!AndroidViewClass::ScrollView.supports_text());
        assert!(!AndroidViewClass::FrameLayout.supports_text());
    }

    #[test]
    fn test_native_view_helpers_noop_without_jvm() {
        // No `JavaVM` has been stored in this unit-test process, so the
        // Rust-callable helpers must report failure instead of panicking.
        assert!(!is_initialized());
        assert!(!has_activity_context());
        assert!(!native_view_creation_ready());
        assert_eq!(create_native_view(AndroidViewClass::Button, "x", 0, 0, 10, 10), None);
        assert!(!destroy_native_view(1234));
        assert!(!set_native_view_text(1234, "x"));
        assert!(!set_native_view_bounds(1234, 0, 0, 10, 10));
        assert!(!set_native_view_visibility(1234, true));
        assert!(!set_native_view_enabled(1234, true));
        assert!(!append_spinner_item(1234, "item", true));
        assert!(!append_list_item(1234, &["item"]));
        // File dialogs need an Activity to launch a result launcher; with no JVM
        // there is none, so the request must report failure rather than claim
        // success.
        assert!(!launch_file_dialog("*/*"));
    }

    #[test]
    fn test_native_view_creation_ready_requires_both_vm_and_context() {
        // The readiness predicate is the AND of the two prerequisites. With no
        // JVM it must be false regardless of the context slot; this pins the
        // contract that `AndroidPlatform::jni_available` relies on, so a future
        // change cannot make it true on only one of the two conditions.
        assert_eq!(native_view_creation_ready(), is_initialized() && has_activity_context());
        assert!(!native_view_creation_ready());
    }

    #[test]
    fn test_android_integration_ready_reports_unready_without_jvm() {
        let status = android_integration_ready();
        assert!(!status.jni_initialized);
        assert_eq!(status.native_methods_count, 13);
        assert!(!status.ready);
    }

    #[test]
    fn test_native_kinds_map_to_view_classes() {
        use AndroidLogicalKind::*;
        assert_eq!(view_class_for(Button), Some(AndroidViewClass::Button));
        assert_eq!(view_class_for(Label), Some(AndroidViewClass::TextView));
        assert_eq!(view_class_for(StatusBar), Some(AndroidViewClass::TextView));
        assert_eq!(view_class_for(LineEdit), Some(AndroidViewClass::EditText));
        assert_eq!(view_class_for(CheckBox), Some(AndroidViewClass::CheckBox));
        assert_eq!(view_class_for(RadioButton), Some(AndroidViewClass::RadioButton));
        assert_eq!(view_class_for(Slider), Some(AndroidViewClass::SeekBar));
        assert_eq!(view_class_for(ProgressBar), Some(AndroidViewClass::ProgressBar));
        assert_eq!(view_class_for(ComboBox), Some(AndroidViewClass::Spinner));
        assert_eq!(view_class_for(ListBox), Some(AndroidViewClass::ListView));
        assert_eq!(view_class_for(ListView), Some(AndroidViewClass::ListView));
        assert_eq!(view_class_for(ScrollArea), Some(AndroidViewClass::ScrollView));
        assert_eq!(view_class_for(SpinBox), Some(AndroidViewClass::NumberPicker));
        assert_eq!(view_class_for(Panel), Some(AndroidViewClass::FrameLayout));
        assert_eq!(view_class_for(Window), Some(AndroidViewClass::FrameLayout));
    }

    #[test]
    fn test_logical_only_kinds_have_no_native_view() {
        use AndroidLogicalKind::*;
        for kind in
            [MenuBar, Menu, MenuItem, ToolBar, MessageBox, FileDialog, ColorDialog, FontDialog]
        {
            assert_eq!(view_class_for(kind), None, "{kind:?} must not claim a native view");
        }
    }
}