quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! GTK implementation of [`quadraui::PlatformServices`].
//!
//! Clipboard uses `arboard` for synchronous system clipboard access
//! (GTK's native read API is async, incompatible with the sync trait).
//! `open_url` uses GIO. File dialogs use `gtk4::FileDialog`, and message
//! dialogs use `gtk4::AlertDialog` — `gtk4::MessageDialog`
//! has been deprecated since GTK 4.10, and the fleet is on 4.14.5 — both
//! behind the same nested-mainloop adapter (see [`pump_until_ready`]) so
//! the trait's synchronous signatures can be honored even though GTK4
//! only exposes async dialog APIs.
//!
//! ## `shell.*` parity
//!
//! `reveal_in_file_manager` calls `org.freedesktop.FileManager1.ShowItems`
//! over the session D-Bus directly (no dedicated GIO wrapper exists for
//! this interface — see [`GtkPlatformServices::reveal_in_file_manager`]'s
//! doc). `open_path` reuses the same `gio::AppInfo::launch_default_for_uri`
//! call `open_url` makes, fed a `file://` URI instead of a caller-supplied
//! URL string. `move_to_trash` delegates to
//! [`crate::desktop::move_to_trash`] — the cross-platform `trash` crate,
//! not a hand-rolled `gio::File::trash` — see that function's doc for why
//! every backend shares it. `beep` is `gdk::Display::beep`.
//!
//! ## Notifications
//!
//! `send_notification` is a real `gio::Notification` sent through the
//! `gtk4::Application` the window belongs to
//! (`GtkWindowExt::application`) — no async trait shape was needed after
//! all; `gio::Application::send_notification` is itself synchronous
//! (fire-and-forget, like every other `PlatformServices` method). This
//! is the one backend [`crate::backend::BackendCaps::notifications`]
//! reports `true` for — see that field's own doc and
//! `compose::notification::notify_or_toast` for how a caller that wants
//! to work on every backend degrades on the other three.
//!
//! Action buttons and the notification body itself route back through a
//! single app-scoped `GAction` (`app.quadraui-notification-activated`,
//! [`NOTIFICATION_ACTION_ID`]), registered once per `Application` by
//! [`GtkPlatformServices::ensure_notification_action`] and never
//! per-notification — which `Notification`/action a given activation
//! belongs to travels in the `GAction`'s own `(ss)` target `Variant`
//! ([`notification_target`]/[`decode_notification_target`]), not in the
//! action's identity. The activation handler decodes that target and
//! pushes [`crate::UiEvent::NotificationActivated`] onto the same shared
//! event queue [`crate::gtk::backend::GtkBackend::poll_events`] drains —
//! wired via [`GtkPlatformServices::set_events_handle`], called once from
//! [`crate::gtk::backend::GtkBackend::new`] right after both the queue
//! and the services exist, mirroring [`GtkPlatformServices::set_window`].
//!
//! `n.icon()` maps to `gio::BytesIcon`/`gio::FileIcon` — GIO's own
//! `GLoadableIcon` machinery decodes/loads it, not this crate's image
//! pipeline, so no pixel decoding happens in-process for a notification
//! icon the way [`Backend::draw_image`][crate::Backend::draw_image] does
//! for a painted one. `n.is_silent()` has nothing to bind to: GTK4's
//! `gio::Notification` carries no sound-control property at all — the
//! desktop shell/notification daemon decides, same as
//! [`Self::show_message_dialog`]'s `opts.severity` having nowhere to go
//! on `gtk4::AlertDialog`.
//!
//! ## Tray / status-bar icon — deliberately not implemented
//! here
//!
//! `GtkBackend::tray` (see [`crate::backend::Backend::tray`]) is left at
//! the trait's `None` default rather than gaining a `GtkTrayService` in
//! this file. Unlike every other gap this module documents, this one
//! isn't "stubbed pending a trait shape" — it's "no GTK4 API exists at
//! all": GTK4 itself ships no status-icon widget (`GtkStatusIcon` was
//! removed in the GTK3→4 transition), so a real implementation needs
//! StatusNotifierItem over D-Bus (the `ksni` crate, or a hand-rolled
//! implementation) or `libayatana-appindicator`, and must additionally
//! report honest `Unsupported`/`None` on desktops with no SNI host
//! running at all (stock GNOME without an extension, notably) rather
//! than silently no-oping. That's a materially larger, separate piece of
//! work than the macOS (`NSStatusBar`) and Win (`Shell_NotifyIconW`)
//! implementations, which reuse existing in-tree image-decode and
//! `ContextMenu`-rendering machinery — see `macos::tray`/`win::tray`'s
//! module docs for those. Tracked as GTK follow-up, not silently
//! dropped: `Backend::tray` returning `None` here is the honest,
//! structural "not yet" this crate's docs consistently prefer over a
//! capability flag nobody set.
//!
//! ## Displays
//!
//! `displays` reads `gdk::Display::monitors()` +
//! `Monitor::geometry()`/`scale_factor()`. `cursor_screen_point` stays
//! `Err(BackendError::Unsupported)` — GDK4 has no global pointer-position
//! query at all, a real Wayland protocol restriction, not a missing
//! binding. See [`GtkPlatformServices::displays`]/
//! [`GtkPlatformServices::cursor_screen_point`]'s own docs for the full
//! detail, including the GDK4 work-area and primary-monitor gaps.
//!
//! ## Re-entrancy guard (#427 follow-up)
//!
//! `pump_until_ready` is called from inside `AppLogic::handle`, which
//! `quadraui::gtk::run` invokes while holding the shared
//! `Rc<RefCell<GtkBackend>>` mutably borrowed for the whole call. Pumping
//! `glib::MainContext::iteration(true)` in that state lets *any* pending
//! GLib source run — including the runner's own 33ms idle-drain timer and
//! every input event controller, all of which also do
//! `backend.borrow_mut()`. Left unguarded, that second borrow panics with
//! "already borrowed", and because it happens inside a non-unwindable GLib
//! callback frame, the panic aborts the whole process instead of
//! propagating. `pumping` (a depth counter, not a bool, so nested dialogs
//! stay guarded until the outermost pump finishes) lets those callbacks
//! detect "a dialog pump is in flight further up the stack" and no-op
//! instead of touching the backend. See `GtkBackend::pump_depth` /
//! `quadraui::gtk::run::activate`.
//!
//! The depth counter and its RAII guard are the backend-neutral
//! [`crate::desktop::ModalPumpDepth`] / [`crate::desktop::ModalPumpGuard`]
//! — extracted here first and generalised because AppKit's
//! `runModal` and Win32's `IFileOpenDialog::Show` have the identical
//! nested-pump re-entrancy hazard.
//!
//! ## Native-dialog CSS theming
//!
//! `gtk4::FileDialog`'s fallback widgets — the places sidebar, the
//! scrollbars, and popover-hosted content (the filter dropdown, the
//! "create folder" popover) — are real GTK chrome this crate doesn't
//! rasterise itself, so they only ever pick up the desktop's own GTK
//! theme. Every GTK consumer used to have to ship its own CSS + display
//! provider purely to make those widgets match the app's [`crate::Theme`]
//! (vimcode's `PlatformCssProvider`, ~216 lines, reloaded by hand on
//! every colourscheme change). [`GtkPlatformServices`] now owns that
//! provider itself: [`GtkPlatformServices::set_theme`] rebuilds
//! [`dialog_css`] from the current `Theme` and reloads it into
//! [`GtkPlatformServices::css_provider`], so every GTK consumer's native
//! dialogs stay in sync with the app's colours with zero per-consumer
//! CSS. See [`dialog_css`]'s own doc for exactly which `Theme` fields
//! back which rule, and [`GtkPlatformServices::ensure_css_provider_attached`]
//! for why attaching the provider to a live `gdk::Display` is decoupled
//! from loading its CSS (theme and window can each arrive first,
//! depending on the consumer's startup order).

use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use gtk4::gio;
use gtk4::gio::prelude::*;
use gtk4::glib;
use gtk4::prelude::{GtkWindowExt, WidgetExt};

use crate::backend::{
    BackendError, Clipboard, Display, FileDialogOptions, MessageDialogButton, MessageDialogChoice,
    MessageDialogOptions, Notification, RgbaImage, ServiceResult, SystemTheme,
};
use crate::desktop::{ModalPumpDepth, ModalPumpGuard};
use crate::event::{Point, Rect, UiEvent};
use crate::primitives::image::ImageSource;
use crate::types::WidgetId;
use crate::PlatformServices;

/// The event queue `GtkBackend::poll_events` drains — the same handle
/// `GtkBackend::events_handle` returns. Aliased so [`GtkPlatformServices::events`]'s
/// type stays under clippy's `type_complexity` threshold.
type EventQueueHandle = Rc<RefCell<VecDeque<UiEvent>>>;

/// GTK platform-services impl. Clipboard is backed by `arboard` for
/// cross-platform synchronous access. File dialogs use `gtk4::FileDialog`
/// pumped through a nested main-loop iteration (see module docs).
/// Notifications use a real `gio::Notification` (see module docs).
pub struct GtkPlatformServices {
    clipboard: GtkClipboard,
    /// Top-level window used to parent file dialogs, so they open modal
    /// to (and centered on) the app window instead of floating
    /// unparented. `None` until [`Self::set_window`] is called (and in
    /// unit tests, which never call it) — dialogs opened before that
    /// point, or in tests, still work, just without a parent.
    window: Rc<RefCell<Option<gtk4::ApplicationWindow>>>,
    /// Depth counter, `> 0` while a [`pump_until_ready`] nested-mainloop
    /// wait is in flight (possibly several, if a dialog is opened
    /// re-entrantly from inside another dialog's pump). Shared (via
    /// [`Self::pump_depth`]) with `quadraui::gtk::run`'s event
    /// controllers and idle-drain timer so they can detect the
    /// re-entrant-pump condition and skip touching the backend's
    /// `RefCell` — see the module-level re-entrancy note.
    pumping: ModalPumpDepth,
    /// The queue `GtkBackend::poll_events` drains, shared via
    /// [`Self::set_events_handle`] — `None` until that's
    /// called (and in unit tests, which never call it), mirroring
    /// `window`'s own "`None` until wired" shape. A notification action
    /// activated before this is set (or in a test-only
    /// `GtkPlatformServices` that never wires it) simply has nowhere to
    /// deliver [`crate::UiEvent::NotificationActivated`] — see
    /// [`Self::ensure_notification_action`].
    events: Rc<RefCell<Option<EventQueueHandle>>>,
    /// Whether [`Self::ensure_notification_action`] has already
    /// registered `app.quadraui-notification-activated` on the current
    /// `Application`. Checked first so `send_notification` doesn't pay
    /// for `ActionMap::lookup_action` on every call once it's
    /// registered.
    action_registered: Cell<bool>,
    /// Display-level CSS provider theming quadraui's own native-dialog
    /// fallback widgets — see the module doc's "Native-dialog
    /// CSS theming" section and [`dialog_css`]'s doc for the full
    /// rationale. Reloaded from scratch on every [`Self::set_theme`] call
    /// rather than diffed, mirroring how cheaply every other backend
    /// re-derives its whole per-frame `current_theme` cache.
    ///
    /// `None` until the first [`Self::set_theme`] call that runs with GTK
    /// already initialized — `gtk4::CssProvider::new()` itself asserts a
    /// live main-thread GTK runtime (`assert_initialized_main_thread!`),
    /// which a bare `GtkPlatformServices::new()` (every unit test in this
    /// module, and any consumer that constructs one before `gtk4::init()`
    /// runs) deliberately does not have — see this file's own doc for why
    /// that must keep working. Lazily constructed instead of eagerly in
    /// [`Self::new`] for exactly that reason.
    css_provider: RefCell<Option<gtk4::CssProvider>>,
    /// Whether [`Self::css_provider`] has already been attached to a live
    /// `gdk::Display` (see [`Self::ensure_css_provider_attached`]).
    /// `gtk4::style_context_add_provider_for_display` has no "already
    /// attached" no-op of its own — calling it twice on the same display
    /// just stacks the same rules twice — so this guards against that
    /// instead of relying on GTK to dedupe it.
    css_provider_attached: Cell<bool>,
    /// The CSS string most recently loaded into [`Self::css_provider`] —
    /// `gtk4::CssProvider` keeps no getter back to its own loaded source,
    /// so this is kept alongside it purely so [`Self::set_theme`]'s effect
    /// is assertable (by [`Self::dialog_css_for_test`]) without a live
    /// `gdk::Display`. `set_theme` is a user-triggered colourscheme
    /// change, not a per-frame call, so the extra `String` isn't on any
    /// hot path.
    last_dialog_css: RefCell<String>,
}

impl GtkPlatformServices {
    pub fn new() -> Self {
        Self {
            clipboard: GtkClipboard::new(),
            window: Rc::new(RefCell::new(None)),
            pumping: ModalPumpDepth::new(),
            events: Rc::new(RefCell::new(None)),
            action_registered: Cell::new(false),
            css_provider: RefCell::new(None),
            css_provider_attached: Cell::new(false),
            last_dialog_css: RefCell::new(String::new()),
        }
    }

    /// Store the top-level window handle so file dialogs can be parented
    /// to it. Called once by `GtkBackend::set_window` right after the
    /// window is constructed.
    ///
    /// Also gives [`Self::ensure_css_provider_attached`] another chance to
    /// run: a consumer that calls `Backend::set_theme`
    /// before the window/display exists yet (theme-then-window ordering)
    /// otherwise never gets its dialog CSS attached, since
    /// [`Self::set_theme`]'s own attach attempt would have found no
    /// display and given up.
    pub(crate) fn set_window(&self, window: gtk4::ApplicationWindow) {
        *self.window.borrow_mut() = Some(window);
        self.ensure_css_provider_attached();
    }

    /// Share the backend's event queue so a notification-action
    /// activation can push [`crate::UiEvent::NotificationActivated`]
    /// onto it. Called once by [`crate::gtk::backend::GtkBackend::new`]
    /// right after both the queue and `self` exist — see the module doc.
    pub(crate) fn set_events_handle(&self, events: EventQueueHandle) {
        *self.events.borrow_mut() = Some(events);
    }

    /// Register the shared `app.quadraui-notification-activated`
    /// [`gio::SimpleAction`] on `app`, exactly once. Idempotent two ways:
    /// [`Self::action_registered`] short-circuits repeat calls from this
    /// `GtkPlatformServices`, and `app.lookup_action` guards against a
    /// second `GtkPlatformServices` (or a second call before the first
    /// one's `events` handle was wired — see below) sharing the same
    /// `Application`, e.g. across two windows of the same app.
    ///
    /// A no-op when [`Self::events`] hasn't been wired yet
    /// ([`Self::set_events_handle`] not called) — the next
    /// `send_notification` retries. This only happens before
    /// `GtkBackend::new` finishes, or in a unit test that constructs
    /// `GtkPlatformServices` directly and calls `send_notification`
    /// without a backend at all; a real app always has both wired before
    /// the event loop starts.
    fn ensure_notification_action(&self, app: &gtk4::Application) {
        if self.action_registered.get() {
            return;
        }
        if app.lookup_action(NOTIFICATION_ACTION_ID).is_some() {
            self.action_registered.set(true);
            return;
        }
        let Some(events) = self.events.borrow().clone() else {
            return;
        };
        let param_type = <(String, String)>::static_variant_type();
        let action = gio::SimpleAction::new(NOTIFICATION_ACTION_ID, Some(&*param_type));
        action.connect_activate(move |_action, parameter| {
            let Some(parameter) = parameter else {
                return;
            };
            let Some((tag, action_id)) = decode_notification_target(parameter) else {
                return;
            };
            events
                .borrow_mut()
                .push_back(UiEvent::NotificationActivated {
                    tag,
                    action: action_id,
                });
        });
        app.add_action(&action);
        self.action_registered.set(true);
    }

    /// Clone of the pump-depth counter (see the `pumping` field docs).
    /// `quadraui::gtk::run::activate` fetches this once, before installing
    /// any event controllers, and clones it into each closure that would
    /// otherwise call `backend.borrow_mut()` — so they can check
    /// `depth.is_pumping()` and no-op while a dialog's nested pump is live.
    pub(crate) fn pump_depth(&self) -> ModalPumpDepth {
        self.pumping.clone()
    }

    /// Concrete (non-trait-object) handle on the clipboard, so in-crate
    /// tests can call [`GtkClipboard::install_test_contents`] — the
    /// `&dyn Clipboard` returned by [`PlatformServices::clipboard`]
    /// can't reach an inherent method. Test-only.
    #[cfg(test)]
    pub(crate) fn gtk_clipboard(&self) -> &GtkClipboard {
        &self.clipboard
    }

    /// Rebuilds [`Self::css_provider`]'s rules from `theme` and reloads
    /// them. Called from `GtkBackend::set_theme` every time the app
    /// changes its [`crate::Theme`].
    ///
    /// [`dialog_css`] is a pure string builder that updates
    /// [`Self::last_dialog_css`] regardless of whether GTK is initialized.
    /// Only the GTK-object half ([`Self::css_provider`]'s lazy construction
    /// + `load_from_data`) is gated on `gtk4::is_initialized_main_thread()`.
    pub(crate) fn set_theme(&self, theme: &crate::Theme) {
        let css = dialog_css(theme);
        *self.last_dialog_css.borrow_mut() = css.clone();

        if !gtk4::is_initialized_main_thread() {
            return;
        }
        {
            let mut provider = self.css_provider.borrow_mut();
            // `load_from_string` needs gtk4-rs's `v4_12` feature, which
            // this crate doesn't enable (only `v4_10` — see Cargo.toml);
            // `load_from_data` is the always-available equivalent (only
            // `#[deprecated]` under `v4_12`, so no lint fires here).
            provider
                .get_or_insert_with(gtk4::CssProvider::new)
                .load_from_data(&css);
        }
        self.ensure_css_provider_attached();
    }

    /// Attach [`Self::css_provider`] to whichever `gdk::Display` is
    /// reachable right now — the parented window's own display once
    /// [`Self::set_window`] has run, falling back to
    /// [`gtk4::gdk::Display::default`] otherwise, the same fallback chain
    /// [`Self::beep`]/[`Self::displays`] use. A no-op when the provider
    /// hasn't been created yet ([`Self::set_theme`] never called), when
    /// it's already attached, or when neither display source exists yet
    /// (headless CI, or a call that races the window/theme the other way
    /// — see [`Self::set_window`]'s doc for how both orderings still end
    /// up attached).
    fn ensure_css_provider_attached(&self) {
        if self.css_provider_attached.get() {
            return;
        }
        let Some(provider) = self.css_provider.borrow().clone() else {
            return;
        };
        let display = match self.window.borrow().as_ref() {
            Some(w) => Some(WidgetExt::display(w)),
            None => gtk4::gdk::Display::default(),
        };
        if let Some(display) = display {
            gtk4::style_context_add_provider_for_display(
                &display,
                &provider,
                gtk4::STYLE_PROVIDER_PRIORITY_APPLICATION,
            );
            self.css_provider_attached.set(true);
        }
    }

    /// The CSS string most recently loaded via [`Self::set_theme`] —
    /// for test inspection, since `gtk4::CssProvider` itself keeps no
    /// getter back to its loaded source.
    #[cfg(test)]
    pub(crate) fn dialog_css_for_test(&self) -> String {
        self.last_dialog_css.borrow().clone()
    }
}

impl Default for GtkPlatformServices {
    fn default() -> Self {
        Self::new()
    }
}

impl PlatformServices for GtkPlatformServices {
    fn clipboard(&self) -> &dyn Clipboard {
        &self.clipboard
    }

    fn show_file_open_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf> {
        let dialog = build_file_dialog(&opts, None);
        let window = self.window.borrow().clone();
        let result = Rc::new(RefCell::new(None));
        let result_cb = Rc::clone(&result);
        dialog.open(window.as_ref(), gio::Cancellable::NONE, move |res| {
            *result_cb.borrow_mut() = Some(res);
        });
        pump_until_ready(&result, &self.pumping)
            .ok()
            .and_then(|file| gtk4::prelude::FileExt::path(&file))
    }

    fn show_file_save_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf> {
        let initial_name = opts.initial_filename.clone();
        let dialog = build_file_dialog(&opts, initial_name.as_deref());
        let window = self.window.borrow().clone();
        let result = Rc::new(RefCell::new(None));
        let result_cb = Rc::clone(&result);
        dialog.save(window.as_ref(), gio::Cancellable::NONE, move |res| {
            *result_cb.borrow_mut() = Some(res);
        });
        pump_until_ready(&result, &self.pumping)
            .ok()
            .and_then(|file| gtk4::prelude::FileExt::path(&file))
    }

    /// `gtk4::FileDialog::select_folder` — opens a native folder picker
    /// with the same builder and nested-pump adapter as the file dialogs.
    fn show_folder_open_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf> {
        let dialog = build_file_dialog(&opts, None);
        let window = self.window.borrow().clone();
        let result = Rc::new(RefCell::new(None));
        let result_cb = Rc::clone(&result);
        dialog.select_folder(window.as_ref(), gio::Cancellable::NONE, move |res| {
            *result_cb.borrow_mut() = Some(res);
        });
        pump_until_ready(&result, &self.pumping)
            .ok()
            .and_then(|file| gtk4::prelude::FileExt::path(&file))
    }

    /// `gtk4::AlertDialog::choose()` — see the module docs
    /// for why `AlertDialog`, not the deprecated `MessageDialog`. Driven
    /// through the same [`pump_until_ready`] + `pump_depth` guard the
    /// file dialogs use above; this does **not** hand-roll a second
    /// nested loop.
    fn show_message_dialog(&self, opts: MessageDialogOptions) -> Option<MessageDialogChoice> {
        let order = hig_button_order(&opts.buttons);
        let labels: Vec<&str> = order
            .iter()
            .map(|&i| opts.buttons[i].label.as_str())
            .collect();

        let dialog = gtk4::AlertDialog::default();
        dialog.set_message(&opts.title);
        dialog.set_detail(&opts.body);
        dialog.set_modal(true);
        dialog.set_buttons(&labels);
        // `opts.severity` is intentionally unread here: gtk4-rs 0.7.3's
        // `AlertDialog` (`auto/alert_dialog.rs`) exposes no icon-setting
        // API at all, so there is nothing to map it onto. Not a bug —
        // `MessageDialogOptions::severity`'s doc already says "backends
        // *may* use this" — but worth calling out so the next reader
        // doesn't go looking for where it's supposed to go.
        if let Some(pos) = order.iter().position(|&i| opts.buttons[i].is_cancel) {
            dialog.set_cancel_button(pos as i32);
        }
        if let Some(pos) = order.iter().position(|&i| opts.buttons[i].is_default) {
            dialog.set_default_button(pos as i32);
        }

        let window = self.window.borrow().clone();
        let result = Rc::new(RefCell::new(None));
        let result_cb = Rc::clone(&result);
        dialog.choose(window.as_ref(), gio::Cancellable::NONE, move |res| {
            *result_cb.borrow_mut() = Some(res);
        });
        let idx = pump_until_ready(&result, &self.pumping).ok()?;
        let pos = usize::try_from(idx).ok()?;
        let orig = *order.get(pos)?;
        Some(opts.buttons[orig].id)
    }

    /// `gio::Notification` sent through the window's owning
    /// `gtk4::Application` — see the module doc for the full
    /// design (action routing, icon decode, the `silent` gap). A no-op
    /// when there is no window yet, or the window has no `Application`
    /// (a `GtkPlatformServices` used outside `quadraui::gtk::run`, e.g.
    /// directly in a unit test) — the same "nothing to parent this to
    /// yet" degrade `show_file_open_dialog` et al. already have via
    /// `self.window.borrow().clone()`.
    fn send_notification(&self, n: Notification) {
        let Some(window) = self.window.borrow().clone() else {
            return;
        };
        let Some(app) = window.application() else {
            return;
        };
        self.ensure_notification_action(&app);

        let notification = gio::Notification::new(&n.title);
        notification.set_body(Some(&n.body));
        notification.set_priority(if n.urgent {
            gio::NotificationPriority::Urgent
        } else {
            gio::NotificationPriority::Normal
        });
        if let Some(icon_source) = n.icon() {
            notification.set_icon(&decode_gio_icon(icon_source));
        }

        let tag = n.tag();
        notification.set_default_action_and_target_value(
            NOTIFICATION_ACTION_DETAILED,
            Some(&notification_target(tag, None)),
        );
        for (id, label) in n.actions() {
            notification.add_button_with_target_value(
                label,
                NOTIFICATION_ACTION_DETAILED,
                Some(&notification_target(tag, Some(id.as_str()))),
            );
        }

        // `gio::Application::send_notification`'s `id` both dedupes
        // repeat calls (a second `send_notification` with the same id
        // replaces the on-screen notification instead of stacking a
        // second one) and is what a later
        // `gio::Application::withdraw_notification(id)` would target —
        // `Notification::with_tag`'s doc names this as the intended use.
        // Untagged notifications each get a fresh id from the counter
        // below so they never collide with each other.
        let owned_tag;
        let notif_id: &str = match tag {
            Some(tag) => tag,
            None => {
                owned_tag = format!(
                    "quadraui-notification-{}",
                    NEXT_NOTIFICATION_ID.fetch_add(1, Ordering::Relaxed)
                );
                &owned_tag
            }
        };
        app.send_notification(Some(notif_id), &notification);
    }

    fn open_url(&self, url: &str) {
        let _ = self.open_url_result(url);
    }

    /// Fallible twin of [`Self::open_url`]: reports
    /// `gio::AppInfo::launch_default_for_uri`'s real outcome instead of
    /// `open_url`'s discarded one — before this override,
    /// `open_url_result` fell to
    /// [`crate::backend::PlatformServices::open_url_result`]'s default
    /// (`open_url` then always `Ok(())`), so a URL scheme with no
    /// registered handler (or no session D-Bus at all) was silently
    /// reported as success.
    fn open_url_result(&self, url: &str) -> ServiceResult<()> {
        gtk4::gio::AppInfo::launch_default_for_uri(url, None::<&gtk4::gio::AppLaunchContext>)
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("gio::AppInfo::launch_default_for_uri: {e}"),
            })
    }

    /// `org.freedesktop.FileManager1.ShowItems` over the session D-Bus
    /// — the standard method every major Linux file manager
    /// (Nautilus/Files, Dolphin, Nemo, Thunar via a plugin) implements
    /// for "reveal this file, selected, in a file-manager window." GIO
    /// ships no dedicated wrapper for this interface the way it does for
    /// [`Self::open_path`]'s `AppInfo::launch_default_for_uri`, so this
    /// drives it directly through [`gio::DBusConnection::call_sync`] —
    /// the same synchronous session-bus machinery GIO's own generated
    /// D-Bus proxies use internally. `Err(BackendError::Unsupported)`
    /// only on `gio::bus_get_sync` itself failing (no session bus at
    /// all — e.g. a bare TTY with no desktop session); a live bus with no
    /// `FileManager1` listener (headless container, minimal window
    /// manager) instead surfaces as `BackendError::PlatformFailure` from
    /// the `ShowItems` call itself, since that's a real answer from a
    /// real bus rather than "this backend has no implementation."
    fn reveal_in_file_manager(&self, path: &Path) -> ServiceResult<()> {
        let uri = gio::File::for_path(path).uri();
        let connection = gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE)
            .map_err(|_| BackendError::Unsupported)?;
        let params = (vec![uri.to_string()], String::new()).to_variant();
        connection
            .call_sync(
                Some("org.freedesktop.FileManager1"),
                "/org/freedesktop/FileManager1",
                "org.freedesktop.FileManager1",
                "ShowItems",
                Some(&params),
                None,
                gio::DBusCallFlags::NONE,
                -1,
                gio::Cancellable::NONE,
            )
            .map(|_| ())
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("org.freedesktop.FileManager1.ShowItems: {e}"),
            })
    }

    /// `gio::AppInfo::launch_default_for_uri` on `path`'s `file://` URI
    /// — the same launch call [`Self::open_url`] makes,
    /// just fed a path converted to a URI (`gio::File::for_path(..).uri()`)
    /// instead of a caller-supplied URL string directly.
    fn open_path(&self, path: &Path) -> ServiceResult<()> {
        let uri = gio::File::for_path(path).uri();
        gio::AppInfo::launch_default_for_uri(&uri, None::<&gio::AppLaunchContext>).map_err(|e| {
            BackendError::PlatformFailure {
                context: format!("gio::AppInfo::launch_default_for_uri: {e}"),
            }
        })
    }

    /// [`crate::desktop::move_to_trash`] — see that
    /// function's doc for why every backend, GTK included, shares this
    /// one `trash`-crate-backed implementation instead of hand-rolling
    /// `gio::File::trash` here.
    fn move_to_trash(&self, path: &Path) -> ServiceResult<()> {
        crate::desktop::move_to_trash(path)
    }

    /// `gdk::Display::beep` — the parented window's own
    /// display when one is attached (mirrors
    /// [`Self::show_file_open_dialog`]'s parenting), falling back to
    /// [`gtk4::gdk::Display::default`] otherwise (unit tests, or a
    /// `GtkPlatformServices` used before [`Self::set_window`] is called).
    /// `Err(BackendError::Unsupported)` only when neither exists — no
    /// window *and* no default display at all, i.e. no live GTK display
    /// connection (headless CI, no X11/Wayland).
    fn beep(&self) -> ServiceResult<()> {
        use gtk4::gdk::prelude::DisplayExt;
        let display = match self.window.borrow().as_ref() {
            Some(window) => WidgetExt::display(window),
            None => gtk4::gdk::Display::default().ok_or(BackendError::Unsupported)?,
        };
        display.beep();
        Ok(())
    }

    /// `gtk4::Settings`' dark-preference + theme-name
    /// properties. `Settings::default()` returns `None` only when GTK has
    /// no default display connection at all (headless dev box, CI) — the
    /// same condition this module's own `require_gtk` test helper skips
    /// its dialog tests on — so that's the one case this reports
    /// `Unsupported` rather than a guessed value.
    fn system_theme(&self) -> ServiceResult<SystemTheme> {
        let settings = gtk4::Settings::default().ok_or(BackendError::Unsupported)?;
        let dark = settings.is_gtk_application_prefer_dark_theme();
        let theme_name = settings.gtk_theme_name();
        Ok(system_theme_from_gtk_settings(dark, theme_name.as_deref()))
    }

    /// `gdk::Display::monitors()` + `Monitor::geometry()`/
    /// `scale_factor()` — the parented window's own display
    /// when one is attached, falling back to [`gtk4::gdk::Display::default`]
    /// otherwise, the exact same fallback chain [`Self::beep`] uses (see
    /// that method's doc).
    ///
    /// No work-area API exists in GDK4 **at all** — removed from GDK3
    /// entirely, not merely absent on Wayland — so [`Display::work_area`]
    /// is always a copy of [`Display::bounds`] here, on every desktop,
    /// X11 included, rather than faking a value on some and not others.
    /// GDK4 also dropped GDK3's `is_primary` monitor flag entirely, so
    /// [`Display::primary`] is a best-effort proxy: index `0` in
    /// `monitors()`'s enumeration order — documented, not a native
    /// signal (see [`Display::primary`]'s own doc).
    ///
    /// `Err(BackendError::Unsupported)` only when neither exists — no
    /// window *and* no default display at all, i.e. no live GTK display
    /// connection (headless CI, no X11/Wayland), same condition
    /// [`Self::beep`]/[`Self::system_theme`] already guard against.
    fn displays(&self) -> ServiceResult<Vec<Display>> {
        use gtk4::gdk::prelude::{DisplayExt, MonitorExt};
        use gtk4::glib::prelude::Cast;

        let display = match self.window.borrow().as_ref() {
            Some(window) => WidgetExt::display(window),
            None => gtk4::gdk::Display::default().ok_or(BackendError::Unsupported)?,
        };
        let monitors = display.monitors();
        let count = monitors.n_items();
        let mut out = Vec::with_capacity(count as usize);
        for i in 0..count {
            let Some(monitor) = monitors
                .item(i)
                .and_then(|o| o.downcast::<gtk4::gdk::Monitor>().ok())
            else {
                continue;
            };
            let geom = monitor.geometry();
            let bounds = Rect::new(
                geom.x() as f32,
                geom.y() as f32,
                geom.width() as f32,
                geom.height() as f32,
            );
            out.push(Display {
                bounds,
                work_area: bounds,
                scale: monitor.scale_factor() as f32,
                primary: i == 0,
            });
        }
        Ok(out)
    }

    /// **Deliberately not overridden** — GDK4 removed the global/root-window
    /// pointer-position query entirely. `Surface::device_position` only
    /// returns a surface-relative position with no way to translate to a
    /// global point. This is a Wayland protocol restriction, not a missing
    /// binding. `Err(BackendError::Unsupported)` is the correct answer.
    fn cursor_screen_point(&self) -> ServiceResult<Point> {
        Err(BackendError::Unsupported)
    }

    fn platform_name(&self) -> &'static str {
        "gtk"
    }
}

// ── Notifications ────────────────────────────────────────────────────────

/// Counter backing an untagged notification's `gio::Application::send_notification`
/// id — a fresh value per call, so two untagged notifications never
/// collide and replace each other the way two calls with the same `tag`
/// deliberately do. Mirrors `win::services::NEXT_NOTIFICATION_ID`'s exact
/// role for the Win-GUI balloon-tip path.
static NEXT_NOTIFICATION_ID: AtomicU64 = AtomicU64::new(1);

/// Bare name [`gio::SimpleAction::new`]/`ActionMap::add_action` register
/// under — no `app.` prefix, since that's implied by which action group
/// (`Application`'s own) it's added to.
const NOTIFICATION_ACTION_ID: &str = "quadraui-notification-activated";

/// The same action, `app.`-prefixed, as
/// [`gio::Notification::set_default_action_and_target_value`]/
/// `add_button_with_target_value` expect — those two are NOT "detailed
/// action name" parsers (no `::target` suffix syntax); they take a plain
/// action name scoped by group prefix, which for an app-registered
/// action is always `app.`.
const NOTIFICATION_ACTION_DETAILED: &str = "app.quadraui-notification-activated";

/// Encode `(tag, action)` as the `(ss)` `Variant` the shared
/// notification action's target carries — empty string standing in for
/// `None` on each side (see [`decode_notification_target`]'s doc for the
/// resulting edge case). A tuple over a custom `GVariant` dict/struct
/// because `(ss)` is exactly two fixed fields, no future third one
/// anticipated, and glib's tuple `ToVariant`/`FromVariant` impls need no
/// extra ceremony to round-trip through.
fn notification_target(tag: Option<&str>, action: Option<&str>) -> glib::Variant {
    (tag.unwrap_or_default(), action.unwrap_or_default()).to_variant()
}

/// Inverse of [`notification_target`] — decodes a notification action's
/// activation `Variant` back into `(tag, action)`. `None` on a
/// non-`(ss)` payload (shouldn't happen: this crate is the only writer
/// of this action's target), rather than panicking on a malformed
/// `Variant` from a source this module doesn't control.
///
/// An empty string on either side round-trips as `None` — so a
/// `Notification` tagged `""` (rather than `with_tag` never called) or
/// an action registered with `WidgetId::new("")` is indistinguishable
/// from having no tag/action at all. Both are degenerate inputs no
/// caller in this crate constructs; documented here rather than guarded
/// against, matching this module's existing posture on similarly
/// unreachable-in-practice edge cases (e.g. `hig_button_order`'s
/// declared-order fallback).
fn decode_notification_target(
    variant: &glib::Variant,
) -> Option<(Option<String>, Option<WidgetId>)> {
    let (tag, action) = variant.get::<(String, String)>()?;
    let tag = if tag.is_empty() { None } else { Some(tag) };
    let action = if action.is_empty() {
        None
    } else {
        Some(WidgetId::new(action))
    };
    Some((tag, action))
}

/// Decode a [`ImageSource`] into a `gio::Icon` for
/// [`gio::Notification::set_icon`]. GIO does its own format sniffing
/// (`GLoadableIcon`) for `Bytes`; `Path` hands the file path straight to
/// the notification daemon via `gio::FileIcon` rather than this process
/// reading the bytes itself — the daemon needs the file to still exist
/// when it gets around to rendering the notification either way, so
/// there's no correctness difference, only one less read in this
/// process.
fn decode_gio_icon(source: &ImageSource) -> gio::Icon {
    match source {
        ImageSource::Bytes(bytes) => {
            gio::BytesIcon::new(&glib::Bytes::from_owned(bytes.clone())).upcast()
        }
        ImageSource::Path(path) => gio::FileIcon::new(&gio::File::for_path(path)).upcast(),
    }
}

/// Pure mapping from `gtk4::Settings`' two theme properties to
/// [`SystemTheme`] — split out from `system_theme` so it's unit-testable
/// without a live GTK display, mirroring this module's
/// `hig_button_order`/`native_button_order`-style helpers.
///
/// No accent-colour source: GTK4 itself exposes none (that lives on
/// libadwaita's `AdwStyleManager`, which this crate doesn't depend on), so
/// `accent` is always `None` here.
fn system_theme_from_gtk_settings(dark: bool, theme_name: Option<&str>) -> SystemTheme {
    let high_contrast = theme_name
        .map(|name| name.to_ascii_lowercase().contains("highcontrast"))
        .unwrap_or(false);
    SystemTheme {
        dark,
        accent: None,
        high_contrast,
    }
}

// ── Native-dialog CSS theming ────────────────────────────────────────────

/// CSS rules [`GtkPlatformServices::set_theme`] loads into
/// [`GtkPlatformServices::css_provider`] to theme the GTK chrome
/// in native dialogs: `gtk4::FileDialog`'s places sidebar (`.sidebar`),
/// scrollbars, and popover-hosted content — the filter dropdown and
/// "create folder" popover. See the module doc's "Native-dialog CSS
/// theming" section for context.
///
/// Uses [`crate::Theme::surface_bg`]/[`crate::Theme::surface_fg`] for
/// sidebar and popover backgrounds/text, plus [`crate::Theme::muted_fg`]
/// for scrollbar slider. Pure and GTK-object-free, unit-testable and
/// kept current via [`GtkPlatformServices::last_dialog_css`].
fn dialog_css(theme: &crate::Theme) -> String {
    let surface_bg = css_hex(theme.surface_bg);
    let surface_fg = css_hex(theme.surface_fg);
    let slider = css_hex(theme.muted_fg);
    format!(
        "\
.sidebar {{
    background-color: {surface_bg};
    color: {surface_fg};
}}
scrollbar slider {{
    background-color: {slider};
}}
popover contents {{
    background-color: {surface_bg};
    color: {surface_fg};
}}
"
    )
}

/// `"#rrggbb"` — none of [`dialog_css`]'s three rules need alpha, so
/// [`crate::types::Color::a`] is dropped rather than emitted as an
/// `#rrggbbaa` GTK CSS never asked for.
fn css_hex(color: crate::types::Color) -> String {
    format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b)
}

/// Build a `gtk4::FileDialog` from the backend-agnostic
/// [`FileDialogOptions`]. `initial_name` is passed separately (rather
/// than read off `opts.initial_filename`) because it only applies to
/// the save dialog — `show_file_open_dialog` calls this with `None`.
fn build_file_dialog(opts: &FileDialogOptions, initial_name: Option<&str>) -> gtk4::FileDialog {
    let dialog = gtk4::FileDialog::new();
    if let Some(ref title) = opts.title {
        dialog.set_title(title);
    }
    if let Some(ref dir) = opts.initial_dir {
        dialog.set_initial_folder(Some(&gio::File::for_path(dir)));
    }
    if let Some(name) = initial_name {
        dialog.set_initial_name(Some(name));
    }
    if !opts.filters.is_empty() {
        let filters = gio::ListStore::new::<gtk4::FileFilter>();
        for (name, extensions) in &opts.filters {
            let filter = gtk4::FileFilter::new();
            filter.set_name(Some(name));
            for ext in extensions {
                filter.add_suffix(ext);
            }
            filters.append(&filter);
        }
        dialog.set_filters(Some(&filters));
    }
    dialog
}

/// Nested-mainloop adapter: `gtk4::FileDialog::open`/`save` and
/// `gtk4::AlertDialog::choose` are async-only (GTK4
/// dropped the blocking `FileChooserDialog` API and never had a blocking
/// alert), but [`PlatformServices::show_file_open_dialog`] /
/// `show_file_save_dialog` / `show_message_dialog` are synchronous
/// across every backend (the signature macOS's `NSOpenPanel::runModal` /
/// `NSAlert::runModal` and Win32's `comdlg32` / `MessageBoxEx` map onto
/// directly). This closes the gap the same way GTK itself closes it
/// internally for modal dialogs (e.g. the legacy `gtk_dialog_run`): pump
/// `glib::MainContext::iteration(true)` — which blocks until *some*
/// source is ready and dispatches it — in a loop until the async
/// operation's completion callback has stashed a result in `result`.
/// Generic over the result type so every blocking-dialog call site
/// (file open/save, message/alert) shares this one pump instead of each
/// hand-rolling its own nested loop.
///
/// # Re-entrancy note
///
/// Pumping the main loop here lets *any* pending GLib source run,
/// including redraw/timer/other-widget callbacks that would normally
/// wait their turn — the same way a native nested loop (or GTK's old
/// `gtk_dialog_run`) does. If one of those callbacks itself triggers
/// another dialog, the inner call's `iteration(true)` loop will also
/// service the outer dialog's completion source, which is safe but
/// means dialogs can resolve out of call order. Apps should avoid
/// opening a second dialog from inside a callback that runs while one is
/// already open.
///
/// Critically, this is called while `quadraui::gtk::run`'s caller (an
/// `AppLogic::handle` invocation) still holds the shared
/// `GtkBackend`'s `RefCell` mutably borrowed. `pumping` — bumped for the
/// duration of this call — is how the runner's other backend-touching
/// callbacks (idle-drain timer, input controllers, draw func) detect
/// that and skip their own `backend.borrow_mut()` instead of panicking
/// on a double-borrow.
fn pump_until_ready<T>(result: &Rc<RefCell<Option<T>>>, pumping: &ModalPumpDepth) -> T {
    let _guard = ModalPumpGuard::new(pumping);
    let ctx = glib::MainContext::default();
    while result.borrow().is_none() {
        ctx.iteration(true);
    }
    result
        .borrow_mut()
        .take()
        .expect("loop above only exits once `result` is Some")
}

/// GNOME HIG button ordering for `gtk4::AlertDialog::set_buttons`: the
/// cancel button (if any) goes first (leftmost); the default/primary
/// button (if any) goes last (rightmost); every other button keeps its
/// original relative order in between. Returns indices into `buttons`,
/// in the order to hand to `set_buttons` — `show_message_dialog` maps
/// the chosen index back through this same `Vec` to recover the
/// original [`MessageDialogButton::id`].
///
/// A button with both `is_default` and `is_cancel` set (a single-button
/// "OK" dialog) is treated as the cancel slot here — see below, both
/// `set_cancel_button` and `set_default_button` are still pointed at its
/// position afterward regardless of which bucket placed it.
fn hig_button_order(buttons: &[MessageDialogButton]) -> Vec<usize> {
    let mut cancel_idx = None;
    let mut default_idx = None;
    let mut middle = Vec::new();
    for (i, b) in buttons.iter().enumerate() {
        if b.is_cancel && cancel_idx.is_none() {
            cancel_idx = Some(i);
        } else if b.is_default && default_idx.is_none() {
            default_idx = Some(i);
        } else {
            middle.push(i);
        }
    }
    let mut order = Vec::with_capacity(buttons.len());
    order.extend(cancel_idx);
    order.extend(middle);
    if let Some(d) = default_idx {
        order.push(d);
    }
    order
}

// The RAII bump/decrement for the shared pump-depth counter is defined
// in `crate::desktop::ModalPumpGuard` — extracted there for use by all backends.

/// In-memory stand-in for the two OS selections, installed by
/// [`GtkClipboard::install_test_contents`] so unit tests can exercise the
/// clipboard-paste code paths **without** depending on whatever the host
/// running the tests happens to have on its real clipboard.
///
/// Test-only on purpose: without it, a test asserting "nothing to paste"
/// passes on a headless box (where `arboard::Clipboard::new()` fails) and
/// fails on any developer machine or CI runner with a live display and a
/// non-empty clipboard — a genuinely flaky, environment-dependent
/// assertion rather than a statement about quadraui's behaviour.
#[cfg(test)]
#[derive(Clone, Debug, Default)]
pub(crate) struct TestClipboardContents {
    /// Contents of the CLIPBOARD selection — what Ctrl-V / Ctrl-Shift-V
    /// reads. `None` models "nothing has been copied".
    pub clipboard: Option<String>,
    /// Contents of the PRIMARY selection — what middle-click reads.
    /// `None` models "nothing is selected anywhere".
    pub primary: Option<String>,
}

/// System clipboard via `arboard`. The handle is kept alive for the
/// process lifetime so Linux clipboard serving threads persist.
pub struct GtkClipboard {
    inner: RefCell<Option<arboard::Clipboard>>,
    /// When `Some`, every read/write below is served from this in-memory
    /// fake instead of the OS, making clipboard-dependent unit tests
    /// deterministic on any host. Only ever populated by
    /// [`Self::install_test_contents`]; production builds don't compile
    /// the field at all.
    #[cfg(test)]
    test_contents: RefCell<Option<TestClipboardContents>>,
}

impl GtkClipboard {
    fn new() -> Self {
        Self {
            inner: RefCell::new(arboard::Clipboard::new().ok()),
            #[cfg(test)]
            test_contents: RefCell::new(None),
        }
    }

    /// Swap this clipboard over to an in-memory fake seeded with
    /// `contents`. Every subsequent read and write goes to the fake and
    /// the OS clipboard is left untouched — so a test can assert on the
    /// "there is something to paste" and "there is nothing to paste"
    /// branches independently of the host.
    #[cfg(test)]
    pub(crate) fn install_test_contents(&self, contents: TestClipboardContents) {
        *self.test_contents.borrow_mut() = Some(contents);
    }

    /// OS-level PRIMARY-selection read, split out from the trait method
    /// so the trait method itself stays uncfg'd (and therefore honours
    /// [`Self::install_test_contents`] on every target).
    ///
    /// Gated to the same `cfg` `arboard` itself uses for `GetExtLinux`
    /// (see `arboard::lib`). Windows/macOS have no PRIMARY-selection
    /// concept, and quadraui's `gtk` feature only ships a Linux backend
    /// in practice, so there the OS read is simply `None`.
    #[cfg(all(
        unix,
        not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
    ))]
    fn read_os_primary_selection(&self) -> Option<String> {
        use arboard::{GetExtLinux, LinuxClipboardKind};
        self.inner
            .borrow_mut()
            .as_mut()?
            .get()
            .clipboard(LinuxClipboardKind::Primary)
            .text()
            .ok()
    }

    /// Non-Linux counterpart of [`Self::read_os_primary_selection`] —
    /// there is no PRIMARY selection to read.
    #[cfg(not(all(
        unix,
        not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
    )))]
    fn read_os_primary_selection(&self) -> Option<String> {
        None
    }
}

impl Clipboard for GtkClipboard {
    fn read_text(&self) -> Option<String> {
        #[cfg(test)]
        {
            if let Some(fake) = self.test_contents.borrow().as_ref() {
                return fake.clipboard.clone();
            }
        }
        self.inner.borrow_mut().as_mut()?.get_text().ok()
    }

    fn write_text(&self, text: &str) {
        #[cfg(test)]
        {
            if let Some(fake) = self.test_contents.borrow_mut().as_mut() {
                fake.clipboard = Some(text.to_string());
                return;
            }
        }
        if let Some(cb) = self.inner.borrow_mut().as_mut() {
            let _ = cb.set_text(text);
        }
    }

    /// PRIMARY selection (middle-click paste source) — only meaningful on
    /// X11/Wayland, where `arboard`'s Linux extension trait exposes it as
    /// a distinct selection from CLIPBOARD. See
    /// [`GtkClipboard::read_os_primary_selection`] for the per-target
    /// split.
    fn read_primary_selection(&self) -> Option<String> {
        #[cfg(test)]
        {
            if let Some(fake) = self.test_contents.borrow().as_ref() {
                return fake.primary.clone();
            }
        }
        self.read_os_primary_selection()
    }

    /// Decoded RGBA pixels via `arboard::Clipboard::get_image`.
    /// Not covered by [`Self::install_test_contents`]'s fake — that only
    /// modeled text — so this always goes to the real OS clipboard.
    fn read_image(&self) -> ServiceResult<RgbaImage> {
        let mut inner = self.inner.borrow_mut();
        let cb = inner.as_mut().ok_or(BackendError::PlatformFailure {
            context: NO_ARBOARD_HANDLE_CONTEXT.to_string(),
        })?;
        let img = cb
            .get_image()
            .map_err(|e| map_arboard_error("arboard::get_image", e))?;
        Ok(RgbaImage {
            width: img.width as u32,
            height: img.height as u32,
            pixels: img.bytes.into_owned(),
        })
    }

    fn write_image(&self, image: &RgbaImage) -> ServiceResult<()> {
        let mut inner = self.inner.borrow_mut();
        let cb = inner.as_mut().ok_or(BackendError::PlatformFailure {
            context: NO_ARBOARD_HANDLE_CONTEXT.to_string(),
        })?;
        let data = arboard::ImageData {
            width: image.width as usize,
            height: image.height as usize,
            bytes: std::borrow::Cow::Borrowed(&image.pixels),
        };
        cb.set_image(data)
            .map_err(|e| map_arboard_error("arboard::set_image", e))
    }

    fn write_html(&self, html: &str, alt_text: &str) -> ServiceResult<()> {
        let mut inner = self.inner.borrow_mut();
        let cb = inner.as_mut().ok_or(BackendError::PlatformFailure {
            context: NO_ARBOARD_HANDLE_CONTEXT.to_string(),
        })?;
        cb.set_html(html, Some(alt_text))
            .map_err(|e| map_arboard_error("arboard::set_html", e))
    }

    fn read_file_list(&self) -> ServiceResult<Vec<PathBuf>> {
        let mut inner = self.inner.borrow_mut();
        let cb = inner.as_mut().ok_or(BackendError::PlatformFailure {
            context: NO_ARBOARD_HANDLE_CONTEXT.to_string(),
        })?;
        cb.get()
            .file_list()
            .map_err(|e| map_arboard_error("arboard::get().file_list()", e))
    }

    fn clear(&self) -> ServiceResult<()> {
        let mut inner = self.inner.borrow_mut();
        let cb = inner.as_mut().ok_or(BackendError::PlatformFailure {
            context: NO_ARBOARD_HANDLE_CONTEXT.to_string(),
        })?;
        cb.clear()
            .map_err(|e| map_arboard_error("arboard::clear", e))
    }
}

/// Context string used when there is no live `arboard::Clipboard` handle
/// at all (construction failed — e.g. headless, no display) rather than a
/// native call on a real handle failing.
const NO_ARBOARD_HANDLE_CONTEXT: &str = "arboard::Clipboard::new (no clipboard available)";

/// Map an `arboard::Error` from a named native call into a
/// [`BackendError::PlatformFailure`] — the one
/// implementation shared with `macos::services`; see
/// [`crate::desktop::map_arboard_error`]'s own doc for the full
/// rationale.
use crate::desktop::map_arboard_error;

#[cfg(test)]
mod tests {
    use super::*;
    use gtk4::prelude::ListModelExt;
    use std::sync::OnceLock;

    // ── Clipboard image/html/file-list/clear ───────────────────────────

    /// Real OS-clipboard round trip through all clipboard methods.
    /// Needs no `gtk4::init()` (arboard talks directly to the display
    /// server) but does need a live clipboard session. Skips gracefully
    /// on headless CI runners with no X11/Wayland, the same way as
    /// `build_file_dialog_behaviors`. Single test so parallel threads
    /// don't fight over the systemwide clipboard.
    #[allow(clippy::print_stderr)]
    #[test]
    fn clipboard_image_html_file_list_and_clear_round_trip() {
        let svc = GtkPlatformServices::new();
        let cb = svc.clipboard();

        let image = RgbaImage {
            width: 2,
            height: 2,
            pixels: vec![
                255, 0, 0, 255, // red
                0, 255, 0, 255, // green
                0, 0, 255, 255, // blue
                255, 255, 0, 255, // yellow
            ],
        };
        if let Err(e) = cb.write_image(&image) {
            eprintln!("skipping: no live OS clipboard in this environment ({e:?})");
            return;
        }
        let read_back = cb
            .read_image()
            .expect("read_image should see what write_image just wrote");
        assert_eq!(read_back.width, image.width);
        assert_eq!(read_back.height, image.height);
        assert_eq!(
            read_back.pixels.len(),
            (image.width * image.height * 4) as usize
        );

        cb.write_html("<b>hi</b>", "hi").expect(
            "write_html should succeed once write_image already proved the clipboard is live",
        );

        let tmp = std::env::temp_dir().join("quadraui-954-gtk-clipboard-test-file.txt");
        std::fs::write(&tmp, b"quadraui#954").expect("write temp file");
        arboard::Clipboard::new()
            .expect("a second arboard handle should also see the live clipboard")
            .set()
            .file_list(&[&tmp])
            .expect("seeding the clipboard with a file list should succeed");
        let files = cb
            .read_file_list()
            .expect("read_file_list should see the seeded file");
        assert_eq!(
            files
                .iter()
                .map(|p| p.canonicalize().unwrap_or_else(|_| p.clone()))
                .collect::<Vec<_>>(),
            vec![tmp.canonicalize().expect("temp file should exist")]
        );
        let _ = std::fs::remove_file(&tmp);

        cb.write_text("some text #954");
        assert_eq!(cb.read_text(), Some("some text #954".to_string()));
        cb.clear()
            .expect("clear should succeed once the clipboard has proven live");
        assert_eq!(cb.read_text(), None);
    }

    /// Constructing a real `gtk4::FileDialog` requires `gtk4::init()` to
    /// have succeeded, which needs a display connection (X11/Wayland).
    /// CI and headless dev boxes don't have one, so these tests degrade
    /// to a no-op skip there rather than fail — mirrors how the crate's
    /// other GTK-object tests avoid needing a live display (see
    /// `gtk::tab_bar` — Cairo `ImageSurface` tests intentionally sidestep
    /// this same problem). Cached in a `OnceLock` since `gtk4::init()`
    /// after a failed first attempt keeps failing.
    ///
    /// # Thread affinity
    ///
    /// gtk4-rs's thread-affinity guard is a per-thread flag
    /// (`IS_MAIN_THREAD`, a `thread_local!` in gtk4-rs's `rt.rs`) set only
    /// on whichever thread's call actually ran `gtk_init_check()`. Rust's
    /// default test harness runs every `#[test]` fn on its own spawned OS
    /// thread, so if more than one `#[test]` fn calls `require_gtk()`,
    /// only the winner of this `OnceLock` race — one specific thread —
    /// is ever GTK-safe; every other test's thread reads the cached
    /// `true` without ever calling `gtk4::init()` itself, then panics
    /// with "GTK may only be used from the main thread" the moment it
    /// touches a real GTK object. gtk4-rs ships `#[gtk4::test]` /
    /// `test_synced` for exactly this (marshal every GTK-touching test
    /// onto one dedicated worker thread) — not used here because its
    /// `Lazy` worker-thread init calls `gtk4::init().expect(...)`
    /// unconditionally, with no graceful-skip path, which would turn a
    /// headless dev box's "no display" case into a hard panic instead of
    /// the skip this helper is designed to give it. So instead, every
    /// `#[test]` fn that needs a real `gtk4::FileDialog` lives in
    /// [`build_file_dialog_behaviors`] below — one function body, hence
    /// one OS thread, guaranteeing it's the same thread that (first) runs
    /// `gtk4::init()`. Do **not** add another separate `#[test]` fn that
    /// calls `require_gtk()` and then constructs a real GTK object —
    /// fold its assertions into `build_file_dialog_behaviors` instead, or
    /// this panic comes back.
    ///
    /// # macOS main-thread affinity
    ///
    /// On macOS, gtk4-rs's `gtk4::init()` asserts main-thread affinity
    /// itself, *before* it can fail gracefully: `rt.rs::set_initialized`
    /// calls the C `pthread_main_np()` and hard-panics with "Attempted to
    /// initialize GTK on OSX from non-main thread" rather than returning
    /// `Err`. Rust's default test harness never runs a `#[test]` fn on
    /// the process's actual OS main thread (that thread stays inside the
    /// harness, dispatching tests to a worker pool), so unconditionally
    /// calling `gtk4::init()` here would panic on every macOS run instead
    /// of degrading to the same "no display" skip this guard already
    /// gives headless Linux boxes. [`is_main_thread`] checks the same
    /// `pthread_main_np()` symbol gtk4-rs itself calls (declared directly
    /// rather than pulling in the `libc` crate, which the `gtk` feature
    /// doesn't otherwise depend on) so this guard can report `false`
    /// *before* ever touching `gtk4::init()` on a non-main thread.
    fn require_gtk() -> bool {
        static INIT: OnceLock<bool> = OnceLock::new();
        *INIT.get_or_init(|| {
            #[cfg(target_os = "macos")]
            if !is_main_thread() {
                return false;
            }
            gtk4::init().is_ok()
        })
    }

    /// True when called from the process's actual OS main thread.
    /// Declares the same C symbol gtk4-rs's own `rt.rs` calls internally
    /// (`pthread_main_np`, macOS-only — see [`require_gtk`]'s doc)
    /// instead of adding a `libc` dependency to the `gtk` feature for one
    /// FFI call.
    #[cfg(target_os = "macos")]
    fn is_main_thread() -> bool {
        unsafe extern "C" {
            fn pthread_main_np() -> i32;
        }
        unsafe { pthread_main_np() != 0 }
    }

    /// `require_gtk()` must degrade to a graceful `false`
    /// on macOS instead of panicking inside `gtk4::init()` — `cargo test`
    /// never runs a `#[test]` fn on the process's real OS main thread, so
    /// this is a deterministic assertion here (not an environment-gap
    /// no-op like `build_file_dialog_behaviors`'s display skip): the
    /// guard itself must not panic regardless of which test thread wins
    /// the `OnceLock` race.
    #[cfg(target_os = "macos")]
    #[test]
    fn require_gtk_does_not_panic_off_main_thread_on_macos() {
        assert!(
            !require_gtk(),
            "cargo test never runs on the OS main thread, so require_gtk() \
             must report false here instead of calling gtk4::init() and \
             hitting gtk4-rs's own main-thread panic"
        );
    }

    /// Covers every `build_file_dialog` behavior that requires
    /// constructing a real `gtk4::FileDialog`. Deliberately one `#[test]`
    /// fn (not three) — see the thread-affinity note on [`require_gtk`]:
    /// splitting these across separate `#[test]` fns lets the
    /// Rust test harness run them on different OS threads, which
    /// deterministically panics every thread except whichever one wins
    /// the `require_gtk()` / `gtk4::init()` race.
    // Exempt from the crate-wide `print_stderr` deny. `cargo test`
    // output, not code that runs inside a host's live UI session — this
    // line only ever executes on a headless dev box with no display,
    // where it's the reason the test reports "ok" without covering
    // anything.
    #[allow(clippy::print_stderr)]
    #[test]
    fn build_file_dialog_behaviors() {
        if !require_gtk() {
            eprintln!("skipping: GTK failed to initialize (no display available)");
            return;
        }

        // The dialog builder must apply every `FileDialogOptions` field
        // GTK has a settable property for, so a future maintainer
        // changing the wiring can't silently drop one (e.g. forgetting
        // `set_filters`).
        {
            let opts = FileDialogOptions {
                title: Some("Open File".to_string()),
                initial_dir: Some(PathBuf::from("/tmp")),
                initial_filename: None,
                filters: vec![("Rust files".to_string(), vec!["rs".to_string()])],
            };
            let dialog = build_file_dialog(&opts, None);
            assert_eq!(dialog.title(), "Open File");
            assert_eq!(
                gtk4::prelude::FileExt::path(&dialog.initial_folder().unwrap()),
                Some(PathBuf::from("/tmp"))
            );
            let filters = dialog.filters().expect("filters should be set");
            assert_eq!(filters.n_items(), 1);
        }

        // `initial_name` only applies when explicitly passed (the
        // save-dialog path) — `show_file_open_dialog` always passes
        // `None` regardless of `opts.initial_filename`, since that field
        // is documented save-only.
        {
            let opts = FileDialogOptions {
                initial_filename: Some("untitled.txt".to_string()),
                ..Default::default()
            };
            let without = build_file_dialog(&opts, None);
            assert_eq!(without.initial_name(), None);

            let with = build_file_dialog(&opts, opts.initial_filename.as_deref());
            assert_eq!(with.initial_name().as_deref(), Some("untitled.txt"));
        }

        // No filters configured → `set_filters` must not be called (a
        // `Some` empty list would still change the dialog's
        // filter-picker UI).
        {
            let dialog = build_file_dialog(&FileDialogOptions::default(), None);
            assert!(dialog.filters().is_none());
        }

        // `beep` also needs a real live GTK/GDK object
        // (`gdk4::Display::default()`, since no window is attached to
        // this bare `GtkPlatformServices`) — folded in here, despite this
        // function's file-dialog-flavoured name, for the exact
        // thread-affinity reason `require_gtk`'s doc comment gives: a
        // separate `#[test]` fn touching a real GTK/GDK object would run
        // on its own OS thread and panic unless it happens to be the one
        // that won the `gtk4::init()` race.
        {
            let services = GtkPlatformServices::new();
            assert_eq!(services.beep(), Ok(()));
        }

        // `displays` needs the same real `gdk4::Display`
        // `beep` above does — folded in for the identical thread-affinity
        // reason. A live display always has at least one monitor; every
        // returned `Display` must report the crate-wide "no work-area
        // API on GTK" and "index-0-is-primary" degrades this backend's
        // own doc promises (see `GtkPlatformServices::displays`).
        {
            let services = GtkPlatformServices::new();
            let displays = services.displays().expect("a live display has monitors");
            assert!(!displays.is_empty());
            assert!(displays[0].primary);
            for d in &displays {
                assert_eq!(d.work_area, d.bounds);
            }
        }
    }

    /// `set_window` stores the handle used to parent future dialogs.
    /// Guards against a panic/wrong-field regression in the setter.
    #[test]
    fn set_window_is_none_until_called() {
        let services = GtkPlatformServices::new();
        assert!(services.window.borrow().is_none());
    }

    /// GDK4 has no global pointer-position query at all —
    /// `cursor_screen_point` always reports `Unsupported`, on every host
    /// this runs on (no `gtk4::init()`/display needed, unlike `displays`
    /// above, so this is an ordinary `#[test]` fn with no
    /// `require_gtk()` guard).
    #[test]
    fn cursor_screen_point_always_reports_unsupported_on_gtk() {
        let services = GtkPlatformServices::new();
        assert_eq!(
            services.cursor_screen_point(),
            Err(BackendError::Unsupported)
        );
    }

    /// `open_url_result` reports real failures when there's no registered
    /// handler for a URL's scheme. A made-up scheme no desktop registers
    /// is the deterministic way to test this without a live display/session.
    /// GIO's scheme lookup needs no `gtk4::init()`, so this runs unconditionally.
    #[test]
    fn open_url_result_reports_failure_for_an_unregistered_scheme() {
        let services = GtkPlatformServices::new();
        assert!(services
            .open_url_result("quadraui-1087-nonexistent-scheme://x")
            .is_err());
    }

    // Regression test for #427 ("depth counter stays positive until the
    // outermost re-entrant pump unwinds") used to live here directly
    // against a local `PumpGuard`; that behavior is now covered once,
    // backend-neutrally, by `crate::desktop`'s own `modal_pump_tests`.
    // The test below stays GTK-specific: it pins that
    // `GtkPlatformServices::pump_depth()`'s returned handle really does
    // share state with the services' own counter (same `Rc`, not an
    // independent clone).

    /// `GtkPlatformServices::pump_depth()` — the handle
    /// `quadraui::gtk::run::activate` clones into its event
    /// controllers — must observe mutations `pump_until_ready` makes
    /// through the services' own copy (same underlying counter via
    /// `ModalPumpDepth`'s `Rc`, not an independent one).
    #[test]
    fn pump_depth_handle_observes_guard_mutations_on_the_services_copy() {
        let services = GtkPlatformServices::new();
        let handle = services.pump_depth();
        assert_eq!(handle.get(), 0);
        let _guard = ModalPumpGuard::new(&services.pumping);
        assert_eq!(
            handle.get(),
            1,
            "handle must observe the mutation made through services.pumping"
        );
    }

    // ── hig_button_order ───────────────────────────────────────────────

    fn msg_btn(id: &str, is_default: bool, is_cancel: bool) -> MessageDialogButton {
        MessageDialogButton {
            id: crate::types::WidgetId::new(id),
            label: id.to_string(),
            is_default,
            is_cancel,
        }
    }

    #[test]
    fn hig_button_order_puts_cancel_first_and_default_last() {
        let buttons = vec![
            msg_btn("save", true, false),
            msg_btn("dont-save", false, false),
            msg_btn("cancel", false, true),
        ];
        // Declared order is default, other, cancel — HIG order must
        // reshuffle to cancel, other, default.
        assert_eq!(hig_button_order(&buttons), vec![2, 1, 0]);
    }

    #[test]
    fn hig_button_order_preserves_middle_button_relative_order() {
        let buttons = vec![
            msg_btn("cancel", false, true),
            msg_btn("a", false, false),
            msg_btn("b", false, false),
            msg_btn("save", true, false),
        ];
        assert_eq!(hig_button_order(&buttons), vec![0, 1, 2, 3]);
    }

    #[test]
    fn hig_button_order_single_button_both_default_and_cancel() {
        // A single "OK" button dialog: is_cancel is checked first, so it
        // lands in the cancel slot — but `show_message_dialog` still
        // points both `set_cancel_button` and `set_default_button` at
        // its position since `is_default` also reads true on it.
        let buttons = vec![msg_btn("ok", true, true)];
        assert_eq!(hig_button_order(&buttons), vec![0]);
    }

    #[test]
    fn hig_button_order_no_default_or_cancel_keeps_declared_order() {
        let buttons = vec![msg_btn("a", false, false), msg_btn("b", false, false)];
        assert_eq!(hig_button_order(&buttons), vec![0, 1]);
    }

    // ── system_theme_from_gtk_settings ──────────────────────────────────

    #[test]
    fn system_theme_from_gtk_settings_reports_dark() {
        let theme = system_theme_from_gtk_settings(true, Some("Adwaita-dark"));
        assert!(theme.dark);
        assert_eq!(theme.accent, None);
        assert!(!theme.high_contrast);
    }

    #[test]
    fn system_theme_from_gtk_settings_reports_light() {
        let theme = system_theme_from_gtk_settings(false, Some("Adwaita"));
        assert!(!theme.dark);
        assert!(!theme.high_contrast);
    }

    #[test]
    fn system_theme_from_gtk_settings_detects_high_contrast_case_insensitively() {
        assert!(system_theme_from_gtk_settings(false, Some("HighContrast")).high_contrast);
        assert!(system_theme_from_gtk_settings(false, Some("HighContrastInverse")).high_contrast);
        assert!(system_theme_from_gtk_settings(true, Some("highcontrast")).high_contrast);
    }

    #[test]
    fn system_theme_from_gtk_settings_no_theme_name_is_not_high_contrast() {
        assert!(!system_theme_from_gtk_settings(true, None).high_contrast);
    }

    // ── Native-dialog CSS theming ────────────────────────────────────────

    /// [`dialog_css`] is a pure string builder — needs no `gtk4::init()`
    /// — so it's tested directly for the exact colours/selectors the
    /// module doc promises: `.sidebar` and `popover contents` both track
    /// `surface_bg`/`surface_fg`, `scrollbar slider` tracks `muted_fg`.
    #[test]
    fn dialog_css_reflects_theme_surface_and_muted_colors() {
        let theme = crate::Theme {
            surface_bg: crate::types::Color::rgb(0x11, 0x22, 0x33),
            surface_fg: crate::types::Color::rgb(0xaa, 0xbb, 0xcc),
            muted_fg: crate::types::Color::rgb(0x44, 0x55, 0x66),
            ..crate::Theme::default()
        };
        let css = dialog_css(&theme);
        assert!(css.contains(".sidebar"));
        assert!(css.contains("scrollbar slider"));
        assert!(css.contains("popover contents"));
        assert!(
            css.contains("#112233"),
            "sidebar/popover bg should be surface_bg: {css}"
        );
        assert!(
            css.contains("#aabbcc"),
            "sidebar/popover fg should be surface_fg: {css}"
        );
        assert!(
            css.contains("#445566"),
            "scrollbar slider should be muted_fg: {css}"
        );
    }

    /// Asserts the provider's CSS reflects a changed `Theme` background
    /// after `set_theme`. Runs with no `gtk4::init()` — `set_theme` always
    /// refreshes [`GtkPlatformServices::last_dialog_css`] regardless of
    /// whether a live GTK runtime exists, so this covers every consumer's
    /// headless test suite.
    #[test]
    fn set_theme_updates_the_dialog_css_provider_when_theme_background_changes() {
        let services = GtkPlatformServices::new();

        let dark = crate::Theme {
            surface_bg: crate::types::Color::rgb(0x10, 0x10, 0x10),
            ..crate::Theme::default()
        };
        services.set_theme(&dark);
        let dark_css = services.dialog_css_for_test();
        assert!(dark_css.contains("#101010"));

        let light = crate::Theme {
            surface_bg: crate::types::Color::rgb(0xf0, 0xf0, 0xf0),
            ..crate::Theme::default()
        };
        services.set_theme(&light);
        let light_css = services.dialog_css_for_test();
        assert!(light_css.contains("#f0f0f0"));
        assert!(
            !light_css.contains("#101010"),
            "stale CSS from the previous theme must not linger: {light_css}"
        );
    }

    // ── Notification target encode/decode + icon decode ─────────────────
    //
    // Pure functions — no `gtk4::init()`/display needed (unlike
    // `build_file_dialog_behaviors` above), so these run as ordinary
    // `#[test]` fns with no `require_gtk()` guard. The full
    // `send_notification` → real `gio::Notification` → on-screen click
    // path needs a live desktop notification daemon and is covered by
    // `examples/gtk_platform_services.rs`'s manual smoke test instead.

    #[test]
    fn notification_target_round_trips_tag_and_action() {
        let variant = notification_target(Some("build-status"), Some("open-problems"));
        assert_eq!(
            decode_notification_target(&variant),
            Some((
                Some("build-status".to_string()),
                Some(WidgetId::new("open-problems"))
            ))
        );
    }

    #[test]
    fn notification_target_no_tag_or_action_decodes_to_none_none() {
        let variant = notification_target(None, None);
        assert_eq!(decode_notification_target(&variant), Some((None, None)));
    }

    #[test]
    fn notification_target_tag_only() {
        let variant = notification_target(Some("t"), None);
        assert_eq!(
            decode_notification_target(&variant),
            Some((Some("t".to_string()), None))
        );
    }

    #[test]
    fn decode_gio_icon_bytes_produces_a_bytes_icon() {
        let icon = decode_gio_icon(&ImageSource::Bytes(vec![1, 2, 3]));
        assert!(icon.is::<gio::BytesIcon>());
    }

    #[test]
    fn decode_gio_icon_path_produces_a_file_icon() {
        let icon = decode_gio_icon(&ImageSource::Path(PathBuf::from(
            "/tmp/quadraui-955-icon.png",
        )));
        assert!(icon.is::<gio::FileIcon>());
    }

    /// No window wired ⇒ `send_notification` returns before touching any
    /// GTK/GIO object that would need a live display — safe to run
    /// headlessly, unlike `build_file_dialog_behaviors`.
    #[test]
    fn send_notification_without_a_window_is_a_no_op() {
        let services = GtkPlatformServices::new();
        services.send_notification(Notification::new("t", "b"));
        // The early-return path taken above never touches `window` —
        // assert it's still exactly what `new()` left it as, so a
        // future refactor that accidentally starts constructing a
        // window on this path (rather than bailing out first) fails
        // this test instead of only being caught by a live-display run.
        assert!(
            services.window.borrow().is_none(),
            "no window was ever set, so send_notification must not have created one"
        );
    }

    #[test]
    fn notification_action_ids_agree_on_the_app_prefix() {
        // `NOTIFICATION_ACTION_DETAILED` must be exactly
        // `NOTIFICATION_ACTION_ID` with `"app."` prepended — a drift
        // between the two would mean `send_notification`'s buttons
        // target an action name that doesn't match what
        // `ensure_notification_action` actually registers, and clicks
        // would silently do nothing.
        assert_eq!(
            NOTIFICATION_ACTION_DETAILED,
            format!("app.{NOTIFICATION_ACTION_ID}")
        );
    }
}