rust_widgets 2.1.0

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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Stable C ABI for foreign language bindings.
use crate::compat::HashMap;
use crate::compat::Mutex;
use crate::compat::OnceLock;
use crate::control_backend::get_control_backend;
use crate::{c_try, c_try_void};
use alloc::boxed::Box;
use alloc::ffi::CString;
use core::ffi::{c_char, c_float, c_int, c_uint, CStr};
type CBool = bool;
/// Global node-handle registry used by Harmony native bridge callbacks.
fn harmony_node_registry() -> &'static Mutex<HashMap<u64, u64>> {
    static REGISTRY: OnceLock<Mutex<HashMap<u64, u64>>> = OnceLock::new();
    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
fn harmony_lookup_widget(node_handle: u64) -> Option<u64> {
    if node_handle == 0 {
        return None;
    }
    harmony_node_registry().lock().unwrap_or_else(|e| e.into_inner()).get(&node_handle).copied()
}
/// Convert stable C ABI trigger code to internal typed trigger enum.
fn trigger_kind_from_code(code: c_uint) -> crate::platform::WidgetTriggerKind {
    match code {
        1 => crate::platform::WidgetTriggerKind::Clicked,
        2 => crate::platform::WidgetTriggerKind::ValueChanged,
        3 => crate::platform::WidgetTriggerKind::SelectionChanged,
        4 => crate::platform::WidgetTriggerKind::Closed,
        _ => crate::platform::WidgetTriggerKind::Unknown,
    }
}
fn capability_contract_mask(contract: crate::platform::CapabilityContract) -> c_uint {
    match contract {
        crate::platform::CapabilityContract::Native(native) => {
            let mut mask: c_uint = 0;
            mask |= 1 << 0;
            if native.dpi_scaling {
                mask |= 1 << 1;
            }
            if native.ime {
                mask |= 1 << 2;
            }
            if native.accessibility {
                mask |= 1 << 3;
            }
            if native.native_menu {
                mask |= 1 << 4;
            }
            if native.typed_widget_trigger {
                mask |= 1 << 5;
            }
            mask
        }
        crate::platform::CapabilityContract::Embedded(embedded) => {
            let mut mask: c_uint = 0;
            if embedded.fixed_dpi {
                mask |= 1 << 1;
            }
            if embedded.low_memory_mode {
                mask |= 1 << 2;
            }
            if embedded.typed_widget_trigger {
                mask |= 1 << 3;
            }
            mask
        }
    }
}
/// Convert nullable C string pointer to owned Rust `String`.
/// Logs a warning when a null pointer is received.
fn c_str_or_default(ptr: *const c_char) -> String {
    if ptr.is_null() {
        log::warn!("[bindings] c_str_or_default: received null C string pointer");
        return String::new();
    }
    unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() }
}

/// Convert a Rust string to a C string pointer, returning an empty C string on failure.
/// Never panics — all interior-NUL errors are caught.
fn to_c_string_or_empty(s: impl Into<String>) -> *const c_char {
    let owned: String = s.into();
    match CString::new(owned) {
        Ok(cs) => cs.into_raw(),
        Err(nul_err) => {
            let pos = nul_err.nul_position();
            log::warn!(
                "[bindings] CString::new failed (interior NUL at position {pos}), truncating"
            );
            // Truncate — return an empty C string.
            CString::new("").unwrap().into_raw()
        }
    }
}
#[no_mangle]
/// Initializes the widget toolkit's global subsystems.
///
/// C ABI entry point for [`crate::init`]. Call this before creating any window or
/// widget. Returns nothing and cannot report failure; if initialization panics,
/// the panic is contained and the state is simply left uninitialized.
pub extern "C" fn rw_init() {
    c_try_void!({
        crate::init();
    })
}
#[no_mangle]
/// Runs the platform main event loop.
///
/// C ABI entry point for [`crate::run`]. Blocks until the loop exits (typically
/// when a quit is requested), so call it from the thread that owns the UI.
/// Returns nothing and cannot report failure.
pub extern "C" fn rw_run() {
    c_try_void!({
        crate::run();
    })
}
#[no_mangle]
/// Requests that the platform event loop shut down.
///
/// C ABI entry point for [`crate::quit`]. The request is asynchronous: the loop
/// stops on its next iteration, so control may not return to the caller's next
/// statement until the loop actually drains. Returns nothing and cannot fail.
pub extern "C" fn rw_quit() {
    c_try_void!({
        crate::quit();
    })
}

/// Destroy a widget created by any `rw_create_*` call.
///
/// Returns `CBool::TRUE` when the widget existed and was torn down. Releases the
/// backend's state record and every registry entry it holds for the widget, so a
/// long-running application can rebuild its UI without accumulating registrations.
///
/// Passing an unknown or already-destroyed id is safe and returns `false`.
#[no_mangle]
pub extern "C" fn rw_destroy_widget(widget_id: u64) -> CBool {
    c_try!({ get_control_backend().destroy_widget(widget_id) })
}
#[no_mangle]
/// Creates a top-level window at a framework-assigned identity.
///
/// `title` may be null, in which case the title is empty. Returns the new
/// window's id, or `0` on failure. `x`/`y` are the position and `width`/`height`
/// the size, in logical pixels.
pub extern "C" fn rw_create_window(
    title: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_window(&c_str_or_default(title), x, y, width, height) })
}
#[no_mangle]
/// Creates a push button as a child of `parent`.
///
/// `text` is the button label and may be null, which yields an empty label.
/// Returns the new widget's id, or `0` if `parent` is unknown or the backend
/// refuses the request.
pub extern "C" fn rw_create_button(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_button(parent, &c_str_or_default(text), x, y, width, height)
    })
}
#[no_mangle]
/// Creates a checkbox as a child of `parent`, initially unchecked and labelled
/// `text` (null gives an empty label). Returns the new widget's id, or `0` on
/// failure.
pub extern "C" fn rw_create_checkbox(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_checkbox(parent, &c_str_or_default(text), x, y, width, height)
    })
}
#[no_mangle]
/// Creates a single-line text field as a child of `parent`, pre-filled with
/// `text` (null gives an empty field). Returns the new widget's id, or `0` on
/// failure.
pub extern "C" fn rw_create_line_edit(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_line_edit(parent, &c_str_or_default(text), x, y, width, height)
    })
}
#[no_mangle]
/// Creates a non-interactive text label as a child of `parent`.
///
/// `text` may be null, which yields an empty label. Returns the new widget's id,
/// or `0` on failure.
pub extern "C" fn rw_create_label(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_label(parent, &c_str_or_default(text), x, y, width, height)
    })
}
#[no_mangle]
/// Creates a radio button as a child of `parent`, labelled `text` (null gives an
/// empty label).
///
/// Grouping against sibling radio buttons is the backend's concern; this call
/// only creates the control. Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_radio_button(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_radio_button(
            parent,
            &c_str_or_default(text),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Creates a horizontal value slider as a child of `parent`.
///
/// Returns the new widget's id, or `0` on failure. The range and initial value
/// come from the backend's defaults; use the platform API to change them.
pub extern "C" fn rw_create_slider(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_slider(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a progress bar as a child of `parent`.
///
/// Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_progress_bar(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_progress_bar(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a drop-down combo box as a child of `parent`, with no items.
///
/// Add entries with `rw_combo_box_add_item`. Returns the new widget's id, or `0`
/// on failure.
pub extern "C" fn rw_create_combo_box(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_combo_box(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a list box as a child of `parent`, with no items.
///
/// Add entries with `rw_list_box_add_item`. Returns the new widget's id, or `0`
/// on failure.
pub extern "C" fn rw_create_list_box(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_list_box(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates an empty container panel as a child of `parent`.
///
/// Panels hold other controls but have no presentation of their own. Returns the
/// new widget's id, or `0` on failure.
pub extern "C" fn rw_create_panel(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_panel(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a message box, a transient dialog rather than a persistent child.
///
/// `title` and `text` may each be null, which supplies an empty string for that
/// part. The `x`/`y`/`width`/`height` geometry is a hint that the window manager
/// may override. Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_message_box(
    parent: u64,
    title: *const c_char,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_message_box(
            parent,
            &c_str_or_default(title),
            &c_str_or_default(text),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Creates a file chooser dialog, scoped to `parent` if that id is valid.
///
/// `title` may be null for an empty caption. Returns the dialog's id, or `0` on
/// failure. Showing it and reading back the chosen path are separate calls.
pub extern "C" fn rw_create_file_dialog(
    parent: u64,
    title: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_file_dialog(
            parent,
            &c_str_or_default(title),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Creates a colour chooser dialog, scoped to `parent` if that id is valid.
///
/// `title` may be null for an empty caption. Returns the dialog's id, or `0` on
/// failure.
pub extern "C" fn rw_create_color_dialog(
    parent: u64,
    title: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_color_dialog(
            parent,
            &c_str_or_default(title),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Creates a font chooser dialog, scoped to `parent` if that id is valid.
///
/// `title` may be null for an empty caption. Returns the dialog's id, or `0` on
/// failure.
pub extern "C" fn rw_create_font_dialog(
    parent: u64,
    title: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_font_dialog(
            parent,
            &c_str_or_default(title),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Creates a numeric spin box as a child of `parent`.
///
/// Returns the new widget's id, or `0` on failure. The range, step and initial
/// value come from the backend's defaults.
pub extern "C" fn rw_create_spin_box(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_spin_box(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a list view as a child of `parent`, with no rows.
///
/// A list view is the multi-column counterpart of `rw_create_list_box`. Returns
/// the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_list_view(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_list_view(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a scrollable container as a child of `parent`.
///
/// Child widgets are clipped to the container and reachable through its
/// scrollbars. Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_scroll_area(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_scroll_area(parent, x, y, width, height) })
}
#[no_mangle]
/// Moves and resizes a widget in one call.
///
/// `x`/`y` are the new position and `width`/`height` the new size, in logical
/// pixels. An unknown `widget_id` is ignored. Returns nothing; there is no way
/// for the caller to learn whether the geometry was applied.
pub extern "C" fn rw_set_widget_geometry(
    widget_id: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) {
    c_try_void!({
        get_control_backend().set_widget_geometry(widget_id, x, y, width, height);
    })
}
#[no_mangle]
/// Retrieves the geometry of a widget identified by `widget_id`.
///
/// # Safety
///
/// All output pointer arguments must be either null or point to valid,
/// properly aligned memory regions suitable for writing the respective
/// geometry values (`c_int` for x/y, `c_uint` for width/height).
pub unsafe extern "C" fn rw_get_widget_geometry(
    widget_id: u64,
    x_out: *mut c_int,
    y_out: *mut c_int,
    width_out: *mut c_uint,
    height_out: *mut c_uint,
) -> CBool {
    c_try!({
        let geo = get_control_backend().get_widget_geometry(widget_id);
        if let Some((x, y, w, h)) = geo {
            unsafe {
                if !x_out.is_null() {
                    *x_out = x;
                }
                if !y_out.is_null() {
                    *y_out = y;
                }
                if !width_out.is_null() {
                    *width_out = w;
                }
                if !height_out.is_null() {
                    *height_out = h;
                }
            }
            true
        } else {
            false
        }
    })
}
#[no_mangle]
/// Appends `text` (null gives an empty string) as a new last item.
///
/// Returns `true` when the item was added.
pub extern "C" fn rw_combo_box_add_item(combo_box: u64, text: *const c_char) -> CBool {
    c_try!({ get_control_backend().combo_box_add_item(combo_box, &c_str_or_default(text)) })
}
#[no_mangle]
/// Removes every item, leaving the combo box empty and with no selection.
///
/// Returns `true` on success.
pub extern "C" fn rw_combo_box_clear_items(combo_box: u64) -> CBool {
    c_try!({ get_control_backend().combo_box_clear_items(combo_box) })
}
#[no_mangle]
/// Selects the item at `index`, which is zero-based.
///
/// Returns `false` if the index is out of range or the widget is unknown.
pub extern "C" fn rw_combo_box_set_current_index(combo_box: u64, index: c_uint) -> CBool {
    c_try!({
        crate::platform::get_platform().combo_box_set_current_index(combo_box, index as usize)
    })
}
#[no_mangle]
/// The index of the selected item, zero-based, or `-1` when nothing is selected
/// or the widget is unknown.
pub extern "C" fn rw_combo_box_current_index(combo_box: u64) -> c_int {
    c_try!({
        match crate::platform::get_platform().combo_box_current_index(combo_box) {
            Some(idx) => idx as c_int,
            None => -1,
        }
    })
}
#[no_mangle]
/// The number of items currently in the combo box; `0` if it is unknown.
pub extern "C" fn rw_combo_box_item_count(combo_box: u64) -> c_uint {
    c_try!({ crate::platform::get_platform().combo_box_item_count(combo_box) as c_uint })
}
#[no_mangle]
/// The text of the item at zero-based `index`.
///
/// An out-of-range index or an unknown widget yields an empty string rather than
/// an error. The result is a freshly allocated C string and must be released
/// with `rw_free_string`.
pub extern "C" fn rw_combo_box_item_text(combo_box: u64, index: c_uint) -> *const c_char {
    c_try!({
        let text = crate::platform::get_platform().combo_box_item_text(combo_box, index as usize);
        to_c_string_or_empty(text.unwrap_or_default())
    })
}
#[no_mangle]
/// Appends `text` (null gives an empty string) as a new last item.
///
/// Returns `true` when the item was added.
pub extern "C" fn rw_list_box_add_item(list_box: u64, text: *const c_char) -> CBool {
    c_try!({ get_control_backend().list_box_add_item(list_box, &c_str_or_default(text)) })
}
#[no_mangle]
/// Removes the item at zero-based `index`, shifting later items up.
///
/// Returns `false` if the index is out of range or the widget is unknown.
pub extern "C" fn rw_list_box_remove_item(list_box: u64, index: c_uint) -> CBool {
    c_try!({ get_control_backend().list_box_remove_item(list_box, index as usize) })
}
#[no_mangle]
/// Removes every item, leaving the list box empty and with no selection.
///
/// Returns `true` on success.
pub extern "C" fn rw_list_box_clear_items(list_box: u64) -> CBool {
    c_try!({ get_control_backend().list_box_clear_items(list_box) })
}
#[no_mangle]
/// Selects the item at zero-based `index`.
///
/// Returns `false` if the index is out of range or the widget is unknown.
pub extern "C" fn rw_list_box_set_current_index(list_box: u64, index: c_uint) -> CBool {
    c_try!({ crate::platform::get_platform().list_box_set_current_index(list_box, index as usize) })
}
#[no_mangle]
/// The index of the selected item, zero-based, or `-1` when nothing is selected
/// or the widget is unknown.
pub extern "C" fn rw_list_box_current_index(list_box: u64) -> c_int {
    c_try!({
        match crate::platform::get_platform().list_box_current_index(list_box) {
            Some(idx) => idx as c_int,
            None => -1,
        }
    })
}
#[no_mangle]
/// The number of items currently in the list box; `0` if it is unknown.
pub extern "C" fn rw_list_box_item_count(list_box: u64) -> c_uint {
    c_try!({ crate::platform::get_platform().list_box_item_count(list_box) as c_uint })
}
#[no_mangle]
/// The text of the item at zero-based `index`.
///
/// An out-of-range index or an unknown widget yields an empty string rather than
/// an error. The result is a freshly allocated C string and must be released
/// with `rw_free_string`.
pub extern "C" fn rw_list_box_item_text(list_box: u64, index: c_uint) -> *const c_char {
    c_try!({
        let text = crate::platform::get_platform().list_box_item_text(list_box, index as usize);
        to_c_string_or_empty(text.unwrap_or_default())
    })
}
#[no_mangle]
/// Replaces the system clipboard contents with `text` (null clears it).
///
/// Returns `true` when the clipboard accepted the text.
pub extern "C" fn rw_set_clipboard_text(text: *const c_char) -> CBool {
    c_try!({ get_control_backend().set_clipboard_text(&c_str_or_default(text)) })
}
#[no_mangle]
/// The current system clipboard text, or an empty string when unreadable.
///
/// The result is a freshly allocated C string and must be released with
/// `rw_free_string`; it is never null.
pub extern "C" fn rw_get_clipboard_text() -> *const c_char {
    c_try!({
        let text = get_control_backend().get_clipboard_text();
        to_c_string_or_empty(text)
    })
}
#[no_mangle]
/// Begins a drag operation from the given source widget.
///
/// # Safety
///
/// `mime_type` must be a null-terminated C string pointing to valid memory.
/// If `payload` is non-null and `payload_len > 0`, `payload` must point to
/// a valid memory region of at least `payload_len` bytes.
pub unsafe extern "C" fn rw_begin_drag(
    source: u64,
    mime_type: *const c_char,
    payload: *const u8,
    payload_len: c_uint,
) -> CBool {
    c_try!({
        let slice = if payload.is_null() || payload_len == 0 {
            &[]
        } else {
            unsafe { core::slice::from_raw_parts(payload, payload_len as usize) }
        };
        get_control_backend().begin_drag(source, &c_str_or_default(mime_type), slice)
    })
}
#[no_mangle]
/// Polls for a pending drop event and writes its fields through output pointers.
///
/// # Safety
///
/// All output pointer arguments must be either null or point to valid,
/// properly aligned memory. `mime_out` and `payload_out` must point to
/// locations where allocated C strings / byte arrays can be stored.
pub unsafe extern "C" fn rw_poll_drop_event(
    source_out: *mut u64,
    target_out: *mut u64,
    mime_out: *mut *mut c_char,
    payload_out: *mut *mut u8,
    payload_len_out: *mut c_uint,
) -> CBool {
    c_try!({
        let Some(event) = get_control_backend().poll_drop_event() else {
            return false;
        };
        unsafe {
            if !source_out.is_null() {
                *source_out = event.source_widget_id;
            }
            if !target_out.is_null() {
                *target_out = event.target_widget_id;
            }
            if !mime_out.is_null() {
                let cs = CString::new(event.mime).unwrap_or_else(|_| CString::new("").unwrap());
                *mime_out = cs.into_raw();
            }
            if !payload_out.is_null() && !payload_len_out.is_null() && !event.payload.is_empty() {
                let len = event.payload.len();
                let slice = event.payload.into_boxed_slice();
                *payload_out = Box::into_raw(slice) as *mut u8;
                *payload_len_out = len as c_uint;
            } else {
                if !payload_out.is_null() {
                    *payload_out = std::ptr::null_mut();
                }
                if !payload_len_out.is_null() {
                    *payload_len_out = 0;
                }
            }
        }
        true
    })
}
#[no_mangle]
/// Creates a menu bar as a child of `parent`.
///
/// Attach it to a window with `rw_attach_menu_bar_to_window`. Returns the new
/// widget's id, or `0` on failure.
pub extern "C" fn rw_create_menu_bar(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_menu_bar(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a top-level menu labelled `text` (null gives an empty label).
///
/// A menu is normally a child of a menu bar created by `rw_create_menu_bar`.
/// Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_menu(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_menu(parent, &c_str_or_default(text), x, y, width, height)
    })
}
#[no_mangle]
/// Installs `menu_bar` as the menu bar of `window`.
///
/// Both ids must refer to existing widgets. Returns `true` on success.
pub extern "C" fn rw_attach_menu_bar_to_window(window: u64, menu_bar: u64) -> CBool {
    c_try!({ get_control_backend().attach_menu_bar_to_window(window, menu_bar) })
}
#[no_mangle]
/// Adds a menu item to `parent_menu`.
///
/// `text` is the label (null gives an empty label). `shortcut` may be null, which
/// creates the item with no accelerator; a non-null value is parsed as a shortcut
/// description such as `"Ctrl+S"`. Returns the new item's id, or `0` on failure.
pub extern "C" fn rw_menu_add_item(
    parent_menu: u64,
    text: *const c_char,
    shortcut: *const c_char,
) -> u64 {
    c_try!({
        let shortcut_text =
            if shortcut.is_null() { None } else { Some(c_str_or_default(shortcut)) };
        get_control_backend().menu_add_item(
            parent_menu,
            &c_str_or_default(text),
            shortcut_text.as_deref(),
        )
    })
}
#[no_mangle]
/// Takes the next queued menu item activation, if any.
///
/// Returns the id of the activated item, or `0` when the queue is empty. `0` is
/// therefore unambiguous as "nothing pending", since no real menu item is
/// assigned that id.
pub extern "C" fn rw_poll_menu_triggered() -> u64 {
    c_try!({ get_control_backend().poll_menu_triggered().unwrap_or(0) })
}
#[no_mangle]
/// Takes the next queued widget activation, if any.
///
/// Returns the id of the activated widget, or `0` when the queue is empty. This
/// variant discards the trigger kind; use `rw_poll_widget_trigger_event` when the
/// caller needs to distinguish a click from a value change.
pub extern "C" fn rw_poll_widget_triggered() -> u64 {
    c_try!({ get_control_backend().poll_widget_triggered().unwrap_or(0) })
}
/// Polls the next widget trigger event and optionally writes the widget ID to the provided pointer.
///
/// # Safety
/// The `widget_id_out` pointer must be either null or valid for writing a `u64`.
#[no_mangle]
pub unsafe extern "C" fn rw_poll_widget_trigger_event(widget_id_out: *mut u64) -> c_uint {
    c_try!({
        let Some(event) = get_control_backend().poll_widget_trigger_event() else {
            return 0;
        };
        if !widget_id_out.is_null() {
            *widget_id_out = event.widget_id;
        }
        event.kind as c_uint
    })
}
/// Generic menu trigger injection entrypoint for native hosts.
#[no_mangle]
pub extern "C" fn rw_inject_menu_trigger(menu_item_id: u64) -> CBool {
    c_try!({ get_control_backend().inject_menu_trigger(menu_item_id) })
}
/// Generic typed widget trigger injection entrypoint for native hosts.
#[no_mangle]
pub extern "C" fn rw_inject_widget_trigger_event(widget_id: u64, kind_code: c_uint) -> CBool {
    c_try!({
        get_control_backend()
            .inject_widget_trigger_event(widget_id, trigger_kind_from_code(kind_code))
    })
}
/// Harmony callback alias: direct menu item trigger by widget id.
#[no_mangle]
pub extern "C" fn rw_harmony_on_menu_item(menu_item_id: u64) -> CBool {
    c_try!({ get_control_backend().inject_menu_trigger(menu_item_id) })
}
/// Harmony callback alias: direct click trigger by widget id.
#[no_mangle]
pub extern "C" fn rw_harmony_on_click(widget_id: u64) -> CBool {
    c_try!({
        get_control_backend()
            .inject_widget_trigger_event(widget_id, crate::platform::WidgetTriggerKind::Clicked)
    })
}
/// Harmony callback alias: direct value-changed trigger by widget id.
#[no_mangle]
pub extern "C" fn rw_harmony_on_value_changed(widget_id: u64) -> CBool {
    c_try!({
        get_control_backend().inject_widget_trigger_event(
            widget_id,
            crate::platform::WidgetTriggerKind::ValueChanged,
        )
    })
}
/// Harmony callback alias: direct typed trigger by widget id and kind code.
#[no_mangle]
pub extern "C" fn rw_harmony_on_widget_event(widget_id: u64, kind_code: c_uint) -> CBool {
    c_try!({
        get_control_backend()
            .inject_widget_trigger_event(widget_id, trigger_kind_from_code(kind_code))
    })
}
/// Register a Harmony node handle to logical widget id mapping.
#[no_mangle]
pub extern "C" fn rw_harmony_bind_node(node_handle: u64, widget_id: u64) -> CBool {
    c_try!({
        if node_handle == 0 || widget_id == 0 {
            return false;
        }
        harmony_node_registry()
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(node_handle, widget_id);
        true
    })
}
/// Remove a single Harmony node-handle mapping.
#[no_mangle]
pub extern "C" fn rw_harmony_unbind_node(node_handle: u64) -> CBool {
    c_try!({
        if node_handle == 0 {
            return false;
        }
        harmony_node_registry()
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .remove(&node_handle)
            .is_some()
    })
}
/// Resolve mapped widget id from Harmony node handle.
#[no_mangle]
pub extern "C" fn rw_harmony_lookup_widget_id(node_handle: u64) -> u64 {
    c_try!({ harmony_lookup_widget(node_handle).unwrap_or(0) })
}
/// Clear all Harmony node-handle mappings.
#[no_mangle]
pub extern "C" fn rw_harmony_clear_node_bindings() {
    c_try_void!({
        harmony_node_registry().lock().unwrap_or_else(|e| e.into_inner()).clear();
    })
}
/// Harmony callback alias: menu trigger by node handle.
#[no_mangle]
pub extern "C" fn rw_harmony_on_node_menu_item(node_handle: u64) -> CBool {
    c_try!({
        let Some(widget_id) = harmony_lookup_widget(node_handle) else {
            return false;
        };
        get_control_backend().inject_menu_trigger(widget_id)
    })
}
/// Harmony callback alias: click trigger by node handle.
#[no_mangle]
pub extern "C" fn rw_harmony_on_node_click(node_handle: u64) -> CBool {
    c_try!({
        let Some(widget_id) = harmony_lookup_widget(node_handle) else {
            return false;
        };
        get_control_backend()
            .inject_widget_trigger_event(widget_id, crate::platform::WidgetTriggerKind::Clicked)
    })
}
/// Harmony callback alias: value-changed trigger by node handle.
#[no_mangle]
pub extern "C" fn rw_harmony_on_node_value_changed(node_handle: u64) -> CBool {
    c_try!({
        let Some(widget_id) = harmony_lookup_widget(node_handle) else {
            return false;
        };
        get_control_backend().inject_widget_trigger_event(
            widget_id,
            crate::platform::WidgetTriggerKind::ValueChanged,
        )
    })
}
/// Harmony callback alias: typed trigger by node handle and kind code.
#[no_mangle]
pub extern "C" fn rw_harmony_on_node_widget_event(node_handle: u64, kind_code: c_uint) -> CBool {
    c_try!({
        let Some(widget_id) = harmony_lookup_widget(node_handle) else {
            return false;
        };
        get_control_backend()
            .inject_widget_trigger_event(widget_id, trigger_kind_from_code(kind_code))
    })
}
#[no_mangle]
/// Creates a tool bar as a child of `parent`.
///
/// Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_tool_bar(
    parent: u64,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({ get_control_backend().create_tool_bar(parent, x, y, width, height) })
}
#[no_mangle]
/// Creates a status bar as a child of `parent`, showing `text` (null gives an
/// empty message).
///
/// Returns the new widget's id, or `0` on failure.
pub extern "C" fn rw_create_status_bar(
    parent: u64,
    text: *const c_char,
    x: c_int,
    y: c_int,
    width: c_uint,
    height: c_uint,
) -> u64 {
    c_try!({
        get_control_backend().create_status_bar(
            parent,
            &c_str_or_default(text),
            x,
            y,
            width,
            height,
        )
    })
}
#[no_mangle]
/// Reveals a previously hidden widget.
///
/// An unknown `widget_id` is ignored. Returns nothing; query the new state with
/// `rw_is_widget_visible` if the caller needs confirmation.
pub extern "C" fn rw_show_widget(widget_id: u64) {
    c_try_void!({
        get_control_backend().show_widget(widget_id);
    })
}
#[no_mangle]
/// Conceals a widget without destroying it.
///
/// Unlike [`rw_destroy_widget`], the widget keeps its state, geometry and
/// registrations, so showing it again restores exactly what it was. An unknown
/// `widget_id` is ignored.
pub extern "C" fn rw_hide_widget(widget_id: u64) {
    c_try_void!({
        get_control_backend().hide_widget(widget_id);
    })
}
#[no_mangle]
/// Replaces the widget's text content with `text` (null clears it).
///
/// Applies to the label/caption of any widget that has one; an unknown
/// `widget_id` is ignored.
pub extern "C" fn rw_set_widget_text(widget_id: u64, text: *const c_char) {
    c_try_void!({
        get_control_backend().set_widget_text(widget_id, &c_str_or_default(text));
    })
}
#[no_mangle]
/// The widget's current text content.
///
/// An unknown `widget_id` yields an empty string rather than an error. The result
/// is a freshly allocated C string and must be released with `rw_free_string`;
/// it is never null.
pub extern "C" fn rw_get_widget_text(widget_id: u64) -> *const c_char {
    c_try!({
        let text = get_control_backend().get_widget_text(widget_id);
        to_c_string_or_empty(text)
    })
}
#[no_mangle]
/// Enables or disables user interaction with the widget.
///
/// A disabled control stays visible but is greyed out and ignores input. An
/// unknown `widget_id` is ignored.
pub extern "C" fn rw_set_widget_enabled(widget_id: u64, enabled: CBool) {
    c_try_void!({
        get_control_backend().set_widget_enabled(widget_id, enabled);
    })
}
#[no_mangle]
/// Reports whether the widget accepts user interaction; `false` for an unknown
/// widget.
pub extern "C" fn rw_is_widget_enabled(widget_id: u64) -> CBool {
    c_try!({ get_control_backend().is_widget_enabled(widget_id) })
}
#[no_mangle]
/// Sets whether the widget is drawn.
///
/// This is the flag counterpart of `rw_show_widget` / `rw_hide_widget` and
/// behaves identically; an unknown `widget_id` is ignored.
pub extern "C" fn rw_set_widget_visible(widget_id: u64, visible: CBool) {
    c_try_void!({
        get_control_backend().set_widget_visible(widget_id, visible);
    })
}
#[no_mangle]
/// Reports whether the widget is currently drawn; `false` for an unknown widget
/// or one that has been hidden.
pub extern "C" fn rw_is_widget_visible(widget_id: u64) -> CBool {
    c_try!({ get_control_backend().is_widget_visible(widget_id) })
}
#[no_mangle]
/// Enables or disables IME (input method) handling for the widget.
///
/// Relevant to text-entry widgets, where it controls whether composed input such
/// as CJK candidate selection is routed to the control. Returns `true` when the
/// platform applied the change; `false` if the capability is unsupported or the
/// widget is unknown.
pub extern "C" fn rw_set_widget_ime_enabled(widget_id: u64, enabled: CBool) -> CBool {
    c_try!({ crate::platform::get_platform().set_widget_ime_enabled(widget_id, enabled) })
}
#[no_mangle]
/// Reports whether IME handling is enabled for the widget; `false` when the
/// capability is unsupported or the widget is unknown.
pub extern "C" fn rw_is_widget_ime_enabled(widget_id: u64) -> CBool {
    c_try!({ crate::platform::get_platform().is_widget_ime_enabled(widget_id) })
}
#[no_mangle]
/// Sets the name screen readers announce for the widget.
///
/// `name` may be null, which clears the accessible name. Returns `true` when the
/// platform applied the change, `false` if the capability is unsupported.
pub extern "C" fn rw_set_widget_accessibility_name(widget_id: u64, name: *const c_char) -> CBool {
    c_try!({
        crate::platform::get_platform()
            .set_widget_accessibility_name(widget_id, &c_str_or_default(name))
    })
}
#[no_mangle]
/// The accessibility name previously set for the widget, or an empty string if
/// none is set or the capability is unsupported.
///
/// The result is a freshly allocated C string and must be released with
/// `rw_free_string`.
pub extern "C" fn rw_get_widget_accessibility_name(widget_id: u64) -> *const c_char {
    c_try!({
        let name = crate::platform::get_platform().get_widget_accessibility_name(widget_id);
        to_c_string_or_empty(name)
    })
}
#[no_mangle]
/// The name of the control backend currently serving widget creation, such as
/// `"native"` or `"custom"`.
///
/// Useful for diagnostics, since behaviour differs between backends. The result
/// is a freshly allocated C string and must be released with `rw_free_string`.
pub extern "C" fn rw_backend_name() -> *const c_char {
    c_try!({ to_c_string_or_empty(get_control_backend().backend_name()) })
}
#[no_mangle]
/// The platform's supported-capability bitmask, negotiated at compile time.
///
/// Bit layout:
/// - bit0: DPI scaling
/// - bit1: IME
/// - bit2: accessibility
/// - bit3: native menu bar
/// - bit4: typed widget trigger events
///
/// This reflects the platform's *general* capabilities; use
/// [`rw_platform_capability_contract`] for the contract of a specific runtime
/// profile.
pub extern "C" fn rw_platform_capabilities() -> c_uint {
    c_try!({
        let caps = crate::platform::capabilities();
        let mut mask: c_uint = 0;
        if caps.dpi_scaling {
            mask |= 1 << 0;
        }
        if caps.ime {
            mask |= 1 << 1;
        }
        if caps.accessibility {
            mask |= 1 << 2;
        }
        if caps.native_menu {
            mask |= 1 << 3;
        }
        if caps.typed_widget_trigger {
            mask |= 1 << 4;
        }
        mask
    })
}
#[no_mangle]
/// The factor that converts logical pixels to physical device pixels.
///
/// `1.0` means no scaling. Returns nothing about failure: a platform without DPI
/// support reports `1.0`.
pub extern "C" fn rw_platform_dpi_scale_factor() -> c_float {
    c_try!({ crate::platform::dpi_scale_factor() })
}
#[no_mangle]
/// Sets the software renderer's anti-aliasing quality, in samples per axis.
///
/// The value is clamped to `1..=8`, and the clamped value actually in effect is
/// returned — the caller does not need a follow-up read to learn the outcome.
/// The setting is process-wide and applies to canvases created afterwards.
pub extern "C" fn rw_set_render_aa_samples_per_axis(samples: c_uint) -> c_uint {
    c_try!({
        let config =
            crate::render::SoftwareRenderConfig { aa_samples_per_axis: samples as u8 }.normalized();
        crate::render::set_default_software_render_config(config);
        crate::render::default_software_render_config().aa_samples_per_axis as c_uint
    })
}
#[no_mangle]
/// The software renderer's current anti-aliasing quality, in samples per axis.
///
/// Always within `1..=8`.
pub extern "C" fn rw_get_render_aa_samples_per_axis() -> c_uint {
    c_try!({ crate::render::default_software_render_config().aa_samples_per_axis as c_uint })
}
#[no_mangle]
/// Sets the embedded render engine's target frame rate, in hertz (frames per
/// second).
///
/// The value is clamped to `1..=240`, and the clamped value actually in effect is
/// returned.
pub extern "C" fn rw_set_embedded_target_fps(fps: c_uint) -> c_uint {
    c_try!({ crate::render_engine::set_embedded_target_fps(fps) as c_uint })
}
#[no_mangle]
/// The embedded render engine's current target frame rate, in hertz.
///
/// Always within `1..=240`.
pub extern "C" fn rw_get_embedded_target_fps() -> c_uint {
    c_try!({ crate::render_engine::embedded_target_fps() as c_uint })
}
#[no_mangle]
/// Queues a no-op task on the embedded render engine and returns its task id.
///
/// `label` may be null for an empty label; if it is non-null it is copied, so the
/// caller keeps ownership of the original. The task body does nothing — this
/// exists so native hosts can exercise the scheduling path from C.
pub extern "C" fn rw_submit_embedded_noop_task(label: *const c_char) -> u64 {
    c_try!({ crate::render_engine::submit_embedded_task(c_str_or_default(label), |_| {}) })
}
#[no_mangle]
/// Reports whether the embedded render engine has been initialized.
pub extern "C" fn rw_embedded_engine_is_initialized() -> CBool {
    c_try!({ crate::render_engine::embedded_engine_stats().initialized })
}
#[no_mangle]
/// Reports whether the embedded render engine's loop is currently running.
pub extern "C" fn rw_embedded_engine_is_running() -> CBool {
    c_try!({ crate::render_engine::embedded_engine_stats().running })
}
#[no_mangle]
/// The number of frames the embedded render engine has rendered since start.
pub extern "C" fn rw_embedded_engine_frame_count() -> u64 {
    c_try!({ crate::render_engine::embedded_engine_stats().frame_count })
}
#[no_mangle]
/// The number of tasks queued on the embedded render engine but not yet run.
pub extern "C" fn rw_embedded_engine_pending_task_count() -> u64 {
    c_try!({ crate::render_engine::embedded_engine_stats().pending_task_count as u64 })
}
#[no_mangle]
/// The number of windows the embedded render engine is tracking.
pub extern "C" fn rw_embedded_engine_window_count() -> u64 {
    c_try!({ crate::render_engine::embedded_engine_stats().window_count as u64 })
}
#[no_mangle]
/// The number of buttons the embedded render engine is tracking.
pub extern "C" fn rw_embedded_engine_button_count() -> u64 {
    c_try!({ crate::render_engine::embedded_engine_stats().button_count as u64 })
}
#[no_mangle]
/// The capability contract negotiated for a runtime profile, as a bitmask.
///
/// `profile_code` is `1` for the embedded profile and any other value for the
/// full profile — note that an unrecognised code therefore silently means
/// "full" rather than being rejected.
///
/// Bit meanings are not shared between the two contract kinds. For native
/// contracts: bit0 is always set, bit1 DPI scaling, bit2 IME, bit3 accessibility,
/// bit4 native menu, bit5 typed widget triggers. For embedded contracts: bit0 is
/// never set, bit1 fixed DPI, bit2 low-memory mode, bit3 typed widget triggers.
pub extern "C" fn rw_platform_capability_contract(profile_code: c_uint) -> c_uint {
    c_try!({
        let profile = if profile_code == 1 {
            crate::core::RuntimeProfile::Embedded
        } else {
            crate::core::RuntimeProfile::Full
        };
        let contract = crate::platform::negotiate_capability_contract(profile);
        capability_contract_mask(contract)
    })
}
#[no_mangle]
/// The mobile backend's name, or an empty string when the `mobile-api` feature is
/// not compiled in.
///
/// The result is a freshly allocated C string and must be released with
/// `rw_free_string`.
pub extern "C" fn rw_mobile_backend_name() -> *const c_char {
    c_try!({
        #[cfg(feature = "mobile-api")]
        {
            to_c_string_or_empty(crate::platform::mobile_backend_name())
        }
        #[cfg(not(feature = "mobile-api"))]
        {
            // Empty string never contains interior NUL bytes.
            CString::new("").unwrap().into_raw()
        }
    })
}
#[no_mangle]
/// Binds the widget layer to an existing native view.
///
/// `native_handle` is the platform's own identifier for the view being taken
/// over, interpreted by the mobile backend. Returns `true` when the view was
/// attached; always `false` when the `mobile-api` feature is not compiled in.
pub extern "C" fn rw_mobile_attach_native_view(native_handle: u64) -> CBool {
    c_try!({
        #[cfg(feature = "mobile-api")]
        {
            crate::platform::mobile_attach_to_native_view(native_handle as usize)
        }
        #[cfg(not(feature = "mobile-api"))]
        {
            let _ = native_handle;
            false
        }
    })
}
#[no_mangle]
/// Return the C ABI binding contract version.
///
/// Independent of the crate semantic version: bumped only when the exported
/// `rw_*` symbol set or its calling conventions change. `8` marks the stable
/// 1.0 ABI line.
pub extern "C" fn rw_bindings_api_version() -> c_uint {
    c_try!({ 8 })
}
/// Return Node.js binding status bitmask.
///
/// Bit layout:
/// - bit0: C ABI entry points available
/// - bit1: Node.js adapter/example available
#[no_mangle]
pub extern "C" fn rw_nodejs_binding_status() -> c_uint {
    c_try!({ (1 << 0) | (1 << 1) })
}
/// Return Python binding status bitmask.
///
/// Bit layout:
/// - bit0: C ABI entry points available
/// - bit1: Python adapter/example available
/// - bit2: profile-aware capability query available
#[no_mangle]
pub extern "C" fn rw_python_binding_status() -> c_uint {
    c_try!({ (1 << 0) | (1 << 1) | (1 << 2) })
}
/// Return C++ wrapper status bitmask.
///
/// Bit layout:
/// - bit0: C ABI entry points available
/// - bit1: C++ wrapper skeleton/example available
#[no_mangle]
pub extern "C" fn rw_cpp_binding_status() -> c_uint {
    c_try!({ (1 << 0) | (1 << 1) })
}
/// Return Java/JNI binding status bitmask.
///
/// Bit layout:
/// - bit0: C ABI entry points available
/// - bit1: Java native-method skeleton available
/// - bit2: JNI bridge skeleton available
#[no_mangle]
pub extern "C" fn rw_java_binding_status() -> c_uint {
    c_try!({ (1 << 0) | (1 << 1) | (1 << 2) })
}
/// Return Java/JNI skeleton ABI version.
#[no_mangle]
pub extern "C" fn rw_java_jni_skeleton_version() -> c_uint {
    c_try!({ 1 })
}
/// Reserved C++ binding marker — returns the current C++ wrapper ABI version.
///
/// Kept as a stable, never-changing symbol so that language bindings can
/// probe for wrapper support without linking against a moving target.
#[no_mangle]
pub extern "C" fn rw_cpp_reserved() -> c_uint {
    c_try!({ 1 })
}
/// Reserved Java binding marker — returns the current JNI wrapper ABI version.
#[no_mangle]
pub extern "C" fn rw_java_reserved() -> c_uint {
    c_try!({ 1 })
}
/// Reserved Python binding marker — returns the current Python wrapper ABI version.
#[no_mangle]
pub extern "C" fn rw_python_reserved() -> c_uint {
    c_try!({ 1 })
}
/// Return the error code of the most recent failed C ABI call.
///
/// Returns `0` (`RW_ERROR_SUCCESS`) when no error has been recorded.
/// The `handle` argument is reserved for future per-widget error state
/// and is currently ignored (the last-error slot is process-wide).
#[no_mangle]
pub extern "C" fn rw_error_code(_handle: u64) -> c_int {
    c_try!({ crate::error::ffi::last_ffi_error().map(|e| e.id.0 as c_int).unwrap_or(0) })
}
/// Return the error message of the most recent failed C ABI call.
///
/// Returns an empty string when no error has been recorded. The returned
/// string must be freed with `rw_free_string`.
/// The `handle` argument is reserved for future per-widget error state
/// and is currently ignored (the last-error slot is process-wide).
#[no_mangle]
pub extern "C" fn rw_error_message(_handle: u64) -> *mut c_char {
    c_try!({
        let message = crate::error::ffi::last_ffi_error().map(|e| e.message).unwrap_or_default();
        CString::new(message).unwrap_or_default().into_raw()
    })
}
#[no_mangle]
/// # Safety
///
/// `s` must be either null or a pointer returned by this crate through
/// `CString::into_raw` and not already freed. Passing any other pointer or
/// double-freeing is undefined behavior.
pub unsafe extern "C" fn rw_free_string(s: *mut c_char) {
    c_try_void!({
        if s.is_null() {
            return;
        }
        unsafe {
            let _ = CString::from_raw(s);
        }
    })
}

/// Alias for [`rw_free_string`] — explicitly named for callers
/// who hold a `*mut c_char` from Rust-allocated strings and want clarity
/// in their own code.
#[no_mangle]
/// # Safety
///
/// Same requirements as [`rw_free_string`]: `s` must be null or a
/// valid pointer previously allocated by this crate for C ownership transfer.
pub unsafe extern "C" fn rw_free_rust_string(s: *mut c_char) {
    rw_free_string(s);
}
#[cfg(test)]
mod tests {
    use super::*;

    /// Exercise the core C ABI round-trip through the real `extern "C"` entry
    /// points: create a window and child controls, mutate text/geometry/
    /// visibility/enabled, read text back, then free the returned string.
    ///
    /// This is the contract C/Java callers depend on, so it asserts the return
    /// conventions (0 on failure, non-zero handles) and that `rw_free_string`
    /// releases what `rw_get_widget_text` allocated.
    #[test]
    fn c_abi_widget_lifecycle_roundtrip() {
        use std::ffi::{CStr, CString};

        let c = |s: &str| CString::new(s).expect("no interior NUL");

        unsafe {
            let title = c("abi-window");
            let window = rw_create_window(title.as_ptr(), 0, 0, 320, 240);
            assert_ne!(window, 0, "window creation must return a non-zero handle");

            // Child creation with a valid parent must succeed; an invalid parent is
            // rejected by the platform contract (returns 0).
            let label = c("hello");
            let button = rw_create_button(window, label.as_ptr(), 10, 10, 80, 30);
            assert_ne!(button, 0, "button creation must return a non-zero handle");
            assert_eq!(
                rw_create_button(9999, label.as_ptr(), 0, 0, 10, 10),
                0,
                "an unknown parent must be rejected"
            );

            // Text round-trip through the C string boundary.
            let updated = c("updated");
            rw_set_widget_text(button, updated.as_ptr());
            let ptr = rw_get_widget_text(button);
            assert!(!ptr.is_null(), "rw_get_widget_text must never return null");
            let read_back = CStr::from_ptr(ptr).to_string_lossy().into_owned();
            assert_eq!(read_back, "updated");
            rw_free_string(ptr as *mut c_char);

            // Geometry, visibility and enabled round-trips. `CBool` is `bool`.
            rw_set_widget_geometry(button, 20, 20, 120, 40);
            rw_hide_widget(button);
            assert!(!rw_is_widget_visible(button), "hidden widget reports not visible");
            rw_show_widget(button);
            assert!(rw_is_widget_visible(button), "shown widget reports visible");

            rw_set_widget_enabled(button, false);
            assert!(!rw_is_widget_enabled(button), "disabled widget reports disabled");
            rw_set_widget_enabled(button, true);
            assert!(rw_is_widget_enabled(button), "enabled widget reports enabled");
        }
    }

    /// Reading text for an unknown widget must yield an empty (non-null)
    /// string rather than a dangling pointer, and freeing it must be safe.
    #[test]
    fn c_abi_unknown_widget_text_is_empty_not_null() {
        use std::ffi::CStr;

        unsafe {
            let ptr = rw_get_widget_text(0xDEAD_BEEF);
            assert!(!ptr.is_null(), "unknown widget must still return a valid pointer");
            let text = CStr::from_ptr(ptr).to_string_lossy().into_owned();
            assert!(text.is_empty(), "unknown widget text should be empty, got {text:?}");
            rw_free_string(ptr as *mut c_char);
        }
    }

    /// The AA-sample config setters are exercised through the C ABI, which is
    /// available whenever `bindings` is built. The shared test lock, however,
    /// is only compiled on the `desktop` profile, so this case is gated to
    /// match it rather than leaving an unconditional reference.
    #[cfg(all(feature = "desktop", widgets_unstripped))]
    #[test]
    fn render_aa_sample_abi_roundtrip_clamps_values() {
        let _guard = crate::render::software_render_config_test_lock()
            .lock()
            .expect("software render config test lock poisoned");
        let original = rw_get_render_aa_samples_per_axis();
        let low = rw_set_render_aa_samples_per_axis(0);
        assert_eq!(low, 1);
        assert_eq!(rw_get_render_aa_samples_per_axis(), 1);
        let high = rw_set_render_aa_samples_per_axis(100);
        assert_eq!(high, 8);
        assert_eq!(rw_get_render_aa_samples_per_axis(), 8);
        rw_set_render_aa_samples_per_axis(original);
        assert_eq!(rw_get_render_aa_samples_per_axis(), original.clamp(1, 8));
    }
    #[test]
    fn embedded_target_fps_abi_roundtrip_clamps_values() {
        // Shares the embedded engine's process-wide test lock: this test drives the
        // same singleton as `render_engine::embedded`'s tests, so a module-local
        // lock here would exclude nothing and the two would interleave.
        let _guard = crate::render_engine::embedded::embedded_test_guard();
        let original = rw_get_embedded_target_fps();
        let low = rw_set_embedded_target_fps(0);
        assert_eq!(low, 1);
        assert_eq!(rw_get_embedded_target_fps(), 1);
        let high = rw_set_embedded_target_fps(1000);
        assert_eq!(high, 240);
        assert_eq!(rw_get_embedded_target_fps(), 240);
        rw_set_embedded_target_fps(original);
        assert_eq!(rw_get_embedded_target_fps(), original.clamp(1, 240));
    }
}