guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
//! Multi-surface support for Guido applications.
//!
//! This module provides types for creating and managing multiple Wayland layer shell
//! surfaces within a single Guido application. Each surface has its own widget tree
//! but all surfaces share the same reactive signals and app state.
//!
//! # Static Surface Definition (at startup)
//!
//! ```no_run
//! # use guido::prelude::*;
//! # let status_bar_widget = || text("bar");
//! App::new().run(|app| {
//!     app.add_surface(
//!         SurfaceConfig::new()
//!             .height(32)
//!             .anchor(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT)
//!             .layer(Layer::Top)
//!             .namespace("status-bar"),
//!         move || status_bar_widget()
//!     );
//! });
//! ```
//!
//! # Dynamic Surface Creation (at runtime)
//!
//! ```no_run
//! # use guido::prelude::*;
//! # let popup_widget = || text("popup");
//! // In an event handler or anywhere in widget code:
//! let handle = spawn_surface(
//!     SurfaceConfig::new()
//!         .width(300)
//!         .height(200)
//!         .layer(Layer::Overlay),
//!     move || popup_widget()
//! );
//!
//! // Later, to close the surface:
//! handle.close();
//! ```

use std::sync::atomic::{AtomicU64, Ordering};

use crate::app_state::with_app_state;
use crate::outputs::OutputId;
use crate::platform::{Anchor, KeyboardInteractivity, Layer};
use crate::reactive::Trigger;
use crate::reactive::global::GlobalSignal;
use crate::widgets::{Color, Rect, Widget};

/// Unique identifier for each surface in the application.
///
/// Ids come from one counter that only goes up, so a larger id was handed out
/// later. [`raw`](SurfaceId::raw) is how to ask.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SurfaceId(u64);

impl SurfaceId {
    /// Create a new unique surface ID.
    pub fn next() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        SurfaceId(COUNTER.fetch_add(1, Ordering::Relaxed))
    }

    /// The counter value behind the id.
    ///
    /// Useful for logging, and load-bearing in one place: `descendants_bottom_up`
    /// sorts popups by it, a larger value meaning a later surface.
    pub fn raw(&self) -> u64 {
        self.0
    }
}

/// Configuration for a layer shell surface.
///
/// Use the builder pattern to configure surface properties:
///
/// ```no_run
/// # use guido::prelude::*;
/// SurfaceConfig::new()
///     .width(300)
///     .height(200)
///     .anchor(Anchor::TOP | Anchor::RIGHT)
///     .layer(Layer::Overlay)
///     .keyboard_interactivity(KeyboardInteractivity::Exclusive)
///     .namespace("my-popup")
///     .background_color(Color::rgb(0.2, 0.2, 0.3));
/// ```
#[derive(Clone)]
pub struct SurfaceConfig {
    /// Width of the surface (fixed pixels or content-following).
    pub width: SurfaceExtent,
    /// Height of the surface (fixed pixels or content-following).
    pub height: SurfaceExtent,
    /// Anchor edges for the surface position.
    pub anchor: Anchor,
    /// Layer shell layer (background, bottom, top, overlay).
    pub layer: Layer,
    /// Keyboard interactivity mode.
    pub keyboard_interactivity: KeyboardInteractivity,
    /// Namespace identifier for the surface.
    pub namespace: String,
    /// Background color for the surface.
    pub background_color: Color,
    /// Screen-space reservation policy (see [`ExclusiveZone`]).
    pub exclusive_zone: ExclusiveZone,
    /// Margins from the anchored screen edges.
    pub margin: Margin,
    /// Output (monitor) to show the surface on. None lets the compositor choose.
    pub output: Option<OutputId>,
    /// Input region in logical surface coordinates. `None` means the whole
    /// surface accepts input; `Some(rects)` limits input to those rectangles
    /// (an empty list makes the surface fully click-through).
    pub input_region: Option<Vec<Rect>>,
}

/// Margins from the anchored screen edges, in logical pixels.
///
/// The shorthands a [`Padding`](crate::widgets::Padding) takes, in the same
/// order — one value for every edge, `[vertical, horizontal]`, or the full
/// `[top, right, bottom, left]` — but **whole pixels only**: `i32`, `u32` and
/// arrays of them. `margin(8.0)` does not compile where `padding(8.0)` does,
/// because `zwlr_layer_surface_v1::set_margin` is defined in integers and a
/// fractional margin has nothing to round to that the compositor would honour.
///
/// ```no_run
/// # use guido::prelude::*;
/// SurfaceConfig::new().margin(8);                   // all four edges
/// SurfaceConfig::new().margin([0, 12]);             // none top/bottom, 12 aside
/// SurfaceConfig::new().margin([8, 12, 0, 12]);      // top, right, bottom, left
/// ```
///
/// Negative values are allowed: layer-shell reads them as pushing the surface
/// past its anchored edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Margin {
    pub top: i32,
    pub right: i32,
    pub bottom: i32,
    pub left: i32,
}

impl Margin {
    /// The same margin on every edge.
    pub fn all(value: i32) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }

    pub(crate) fn is_zero(self) -> bool {
        self == Self::default()
    }
}

impl From<i32> for Margin {
    fn from(v: i32) -> Self {
        Margin::all(v)
    }
}

impl From<u32> for Margin {
    fn from(v: u32) -> Self {
        Margin::all(v as i32)
    }
}

/// `[vertical, horizontal]` — CSS-style 2-value shorthand.
impl From<[i32; 2]> for Margin {
    fn from(v: [i32; 2]) -> Self {
        Margin {
            top: v[0],
            right: v[1],
            bottom: v[0],
            left: v[1],
        }
    }
}

/// `[top, right, bottom, left]` — CSS-style 4-value shorthand.
impl From<[i32; 4]> for Margin {
    fn from(v: [i32; 4]) -> Self {
        Margin {
            top: v[0],
            right: v[1],
            bottom: v[2],
            left: v[3],
        }
    }
}

/// `[vertical, horizontal]`, unsigned. A bare `[0, 12]` infers as `[i32; 2]`
/// and needs neither of these, which is why the pair was missing while the doc
/// said "arrays of them" — it takes a `[u32; 2]` named somewhere else to notice.
impl From<[u32; 2]> for Margin {
    fn from(v: [u32; 2]) -> Self {
        Margin::from([v[0] as i32, v[1] as i32])
    }
}

/// `[top, right, bottom, left]`, unsigned.
impl From<[u32; 4]> for Margin {
    fn from(v: [u32; 4]) -> Self {
        Margin::from([v[0] as i32, v[1] as i32, v[2] as i32, v[3] as i32])
    }
}

/// Per-axis sizing for layer surfaces.
///
/// `Fixed` is a size in logical pixels (plain integers convert into it).
/// `Content` follows the content's natural size on that axis — the
/// [`content()`] constructor reads like [`fill()`](crate::layout::fill)
/// and friends:
///
/// ```no_run
/// # use guido::prelude::*;
/// SurfaceConfig::new()
///     .width(360)             // fixed
///     .height(content());     // follows the toast stack
/// ```
///
/// Content semantics, designed to stay footgun-free:
/// - Resizing is asynchronous (one compositor round trip per change) and
///   happens on CONTENT changes, not per animation frame: the natural
///   size is measured against animation **targets**, so an animated
///   growth resizes once up front and the animation plays inside the
///   final-size surface.
/// - On an axis anchored to both screen edges the compositor owns the
///   size; `Content` there is ignored with a warning at creation.
/// - An exclusive zone of [`ExclusiveZone::Auto`] follows content
///   resizes; every other policy never moves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SurfaceExtent {
    /// Fixed size in logical pixels.
    Fixed(u32),
    /// Follow the content's natural size on this axis.
    Content,
}

/// Which axes the compositor owns, from the anchor: an axis pinned to both of
/// its screen edges is stretched to fit and the surface's request for it is
/// ignored.
///
/// Returns `(width, height)`.
pub(crate) fn compositor_owned_axes(anchor: Anchor) -> (bool, bool) {
    (
        anchor.contains(Anchor::LEFT) && anchor.contains(Anchor::RIGHT),
        anchor.contains(Anchor::TOP) && anchor.contains(Anchor::BOTTOM),
    )
}

/// Warn about a `content()` axis the compositor owns, which can never take
/// effect. For the creation path, where the *other* axis is usually just the
/// default nobody chose — a bar declares its height and leaves the width alone —
/// so a warning about a `Fixed` one there would be noise.
pub(crate) fn warn_content_on_stretched_axis(id: SurfaceId, config: &SurfaceConfig) {
    let (stretch_w, stretch_h) = compositor_owned_axes(config.anchor);
    if (stretch_w && config.width.is_content()) || (stretch_h && config.height.is_content()) {
        log::warn!(
            "Surface {id:?}: content() sizing on an axis anchored to both screen \
             edges is compositor-owned and will be ignored"
        );
    }
}

/// The same for a size asked for at runtime, where every value is one the caller
/// chose — so a `Fixed` one being discarded is worth saying too. Silently
/// dropping a number somebody passed is the failure mode this exists for.
pub(crate) fn warn_size_request_on_stretched_axis(id: SurfaceId, config: &SurfaceConfig) {
    let (stretch_w, stretch_h) = compositor_owned_axes(config.anchor);
    for (stretched, extent, axis) in [
        (stretch_w, config.width, "width"),
        (stretch_h, config.height, "height"),
    ] {
        if !stretched {
            continue;
        }
        match extent {
            SurfaceExtent::Content => log::warn!(
                "Surface {id:?}: content() {axis} on an axis anchored to both \
                 screen edges is compositor-owned and will be ignored"
            ),
            SurfaceExtent::Fixed(v) => log::warn!(
                "Surface {id:?}: {axis} of {v} on an axis anchored to both screen \
                 edges is compositor-owned and will be ignored"
            ),
        }
    }
}

/// The size an axis is currently asking for: its own, if it has one, and the
/// size the compositor has confirmed while a content axis waits to be measured.
///
/// Before the first configure there is no confirmed size, and the placeholder is
/// what creation asks for too — the content-measure pass runs on the first
/// frames of a surface either way, so 1px is a value it is leaving, not one it
/// can be stuck at.
pub(crate) fn requested_extent(extent: SurfaceExtent, live: Option<u32>) -> u32 {
    match extent {
        SurfaceExtent::Fixed(v) => v,
        SurfaceExtent::Content => live.unwrap_or_else(|| extent.initial()),
    }
}

/// What a resize asks the compositor for, and whether the surface has to be
/// re-measured before that answer is right.
///
/// A content axis has no size of its own yet — `SurfaceExtent::initial()` is
/// 1px — so asking for it directly collapses the surface, and nothing brings it
/// back: the content-measure pass runs only for a surface that had layout
/// activity, and a bare `set_size` produces none. So a content axis holds the
/// confirmed size and asks for a layout, which is what brings the measure round.
pub(crate) fn resize_request(config: &SurfaceConfig, live: Option<(u32, u32)>) -> (u32, u32, bool) {
    let (width, height) = honour_owned_axes(
        config.anchor,
        requested_extent(config.width, live.map(|(w, _)| w)),
        requested_extent(config.height, live.map(|(_, h)| h)),
    );
    (width, height, needs_content_measure(config))
}

/// The axes the content-measure pass holds still while it measures the others:
/// `None` for a content axis, which is what it measures.
///
/// A fixed axis is held at the value it was given, not at `confirmed`: a
/// `set_size` earlier in the same pass has just asked for that value and the
/// compositor has not confirmed it yet, so holding the confirmed size would ask
/// for the old one last. An axis the compositor owns has no value of ours, and
/// is held at what the compositor says.
pub(crate) fn measure_pins(
    config: &SurfaceConfig,
    confirmed: (u32, u32),
) -> (Option<u32>, Option<u32>) {
    let (owned_w, owned_h) = compositor_owned_axes(config.anchor);
    let pin = |extent: SurfaceExtent, owned: bool, confirmed: u32| match extent {
        SurfaceExtent::Content => None,
        SurfaceExtent::Fixed(_) if owned => Some(confirmed),
        SurfaceExtent::Fixed(v) => Some(v),
    };
    (
        pin(config.width, owned_w, confirmed.0),
        pin(config.height, owned_h, confirmed.1),
    )
}

/// What a surface declares the moment it is created.
///
/// One function because there are two callers and they must not disagree — the
/// layer surface being built for a compositor, and a surface being driven
/// without one.
pub(crate) struct InitialDeclaration {
    /// The size to ask for, with the axes the compositor owns zeroed. Through
    /// the same rule a runtime resize uses, so creation and re-anchoring cannot
    /// differ about which axes those are.
    pub asked: (u32, u32),
    /// The size the surface believes it has before any configure has arrived,
    /// which is what a reservation resolves against. Through `requested_extent`
    /// rather than `SurfaceExtent::initial()`, which agrees today only because
    /// the former falls back to it.
    pub believed: (u32, u32),
    /// The screen space to reserve, resolved against `believed`.
    pub exclusive_zone: i32,
    /// The input region to apply, or `None` where the surface declared none
    /// and takes input everywhere. Here rather than read from the config at
    /// each platform, so "applied at birth only when one was declared" is one
    /// rule rather than two copies of it.
    pub input_region: Option<Vec<Rect>>,
}

pub(crate) fn initial_declaration(config: &SurfaceConfig) -> InitialDeclaration {
    let (ask_w, ask_h, _) = resize_request(config, None);
    let believed = (
        requested_extent(config.width, None),
        requested_extent(config.height, None),
    );
    InitialDeclaration {
        asked: (ask_w, ask_h),
        believed,
        exclusive_zone: config.exclusive_zone.resolve(
            config.anchor,
            config.margin,
            believed.0,
            believed.1,
        ),
        input_region: config.input_region.clone(),
    }
}

/// Whether this surface has a `content()` axis worth measuring.
///
/// A content axis the compositor owns is not one: the measure runs, and
/// [`honour_owned_axes`] throws the answer away. A bar declared
/// `width(content()).anchor(TOP | LEFT | RIGHT)` measured its content and
/// discarded it on every resize, every re-anchoring, and — until this was the
/// gate on the frame loop's measure pass too — on **every frame with any layout
/// activity at all**, since the width it measured could never equal the screen
/// width it had been given.
pub(crate) fn needs_content_measure(config: &SurfaceConfig) -> bool {
    let (owns_w, owns_h) = compositor_owned_axes(config.anchor);
    (config.width.is_content() && !owns_w) || (config.height.is_content() && !owns_h)
}

/// Zero the axes the compositor owns, whatever size was going to be asked for.
///
/// Zero on such an axis is how layer-shell says "you decide", and it is not
/// optional: `zwlr_layer_surface_v1::set_size` makes omitting a dimension
/// *without* opposite-edge anchoring a protocol error, and sending a number
/// *with* it hands back an axis that is not ours. The anchor decides, so every
/// path that sends a size comes through here — creation, a runtime resize, a
/// re-anchoring, and the content-measure pass.
pub(crate) fn honour_owned_axes(anchor: Anchor, width: u32, height: u32) -> (u32, u32) {
    let (stretch_w, stretch_h) = compositor_owned_axes(anchor);
    (
        if stretch_w { 0 } else { width },
        if stretch_h { 0 } else { height },
    )
}

/// The buffer a logical size is drawn into at `scale`, in physical pixels.
///
/// **Rounded halfway away from zero**, which fractional-scale-v1 requires of
/// the buffer a viewport declares a destination for, and which swaybg — a layer
/// shell client, so the same shell guido uses — spells `(size * numerator +
/// 60) / 120` and calls round half up in a comment beside it. `f64::round` is
/// that rule for a positive product, and the multiply is in `f64` so a scale
/// that is not a binary fraction cannot land the product on the wrong side of a
/// half at 4K.
///
/// Nothing else: a scale is floored to 1 by [`adopted_scale`] before a surface
/// ever holds one, so that every reader of it gets the same number rather than
/// the buffer path alone.
pub(crate) fn buffer_size((width, height): (u32, u32), scale: f32) -> (u32, u32) {
    let scale = f64::from(scale);
    (
        (f64::from(width) * scale).round() as u32,
        (f64::from(height) * scale).round() as u32,
    )
}

/// The scale a surface takes from a compositor that has just named one, and
/// whether that moved it from `held`, the scale it had.
///
/// **The floor is here** rather than at the buffer arithmetic, so the
/// invariant is "a surface's scale is never below 1" rather than "the one path
/// that happens to floor it" — the renderer and the damage rectangles read the
/// same number. A scale below 1 asks for a buffer smaller than the surface,
/// which is a decision nobody has taken here; zero asks for no buffer at all.
///
/// A compositor naming the scale the surface already holds — the 1 it
/// started at included — moves nothing.
///
/// A free function, and not a method on the surface state, because that state
/// holds a `wl_surface` and a shell role and so cannot be built by a test —
/// which is the whole of what is worth checking here.
pub(crate) fn adopted_scale(held: f32, named: f32) -> (f32, bool) {
    let named = named.max(1.0);
    (named, held != named)
}

/// Where one surface stands with the compositor's `wl_surface.frame`
/// callbacks, and what the loop decides from that: whether a frame now would
/// only queue behind one not yet shown, and whether the surface still repaints
/// in full regardless.
///
/// One definition for both platforms. The Wayland surface and the recorder
/// that stands in for it each hold one and tell it the same two things — a
/// frame committed, a callback come back — so the decision the loop takes from
/// it cannot drift between the compositor and the test.
///
/// A surface stops being forced at its own first present, not at the
/// compositor's first callback or its first word on the scale. Neither of
/// those is promised: a surface whose output is off hears no callback, and
/// sctk reports a scale only when it differs from the 1 it assumed, so a
/// compositor without fractional scaling at scale 1 never names one. Waiting
/// on either repainted such a surface in full at frame rate for good. Nothing
/// is lost by not waiting: once a frame is out there is a callback to pace
/// against, and a scale that arrives later is a scale change, which opens the
/// gate and repaints in full by itself.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FramePacing {
    /// A callback rode the last commit and has not come back.
    callback_pending: bool,
    /// A frame has gone out at least once.
    presented: bool,
}

impl FramePacing {
    /// A frame went out with a callback armed on its commit.
    pub(crate) fn committed(&mut self) {
        self.callback_pending = true;
        self.presented = true;
    }

    /// The callback came back: the compositor has shown the last frame.
    pub(crate) fn callback_done(&mut self) {
        self.callback_pending = false;
    }

    /// Whether a frame now would only queue behind one the compositor has not
    /// shown — so this surface's queued work waits for the callback.
    pub(crate) fn callback_pending(self) -> bool {
        self.callback_pending
    }

    /// Whether this surface bypasses the pacing gate and repaints in full:
    /// it has nothing on screen to pace against yet.
    pub(crate) fn forced(self) -> bool {
        !self.presented
    }
}

impl SurfaceExtent {
    /// The initial protocol size (`Content` starts at 1px until the first
    /// measure lands).
    pub(crate) fn initial(self) -> u32 {
        match self {
            SurfaceExtent::Fixed(v) => v,
            SurfaceExtent::Content => 1,
        }
    }

    pub(crate) fn is_content(self) -> bool {
        matches!(self, SurfaceExtent::Content)
    }
}

impl From<u32> for SurfaceExtent {
    fn from(v: u32) -> Self {
        SurfaceExtent::Fixed(v)
    }
}

impl From<i32> for SurfaceExtent {
    fn from(v: i32) -> Self {
        SurfaceExtent::Fixed(v.max(0) as u32)
    }
}

/// A [`SurfaceExtent`] that follows the content's natural size.
pub fn content() -> SurfaceExtent {
    SurfaceExtent::Content
}

/// Screen-space reservation for layer surfaces, mapping the layer-shell
/// exclusive-zone semantics to intent. Reserving is **opt-in**: the
/// default is [`ExclusiveZone::None`] — a bar declares its reservation
/// explicitly:
///
/// ```no_run
/// # use guido::prelude::*;
/// SurfaceConfig::new().exclusive_zone(ExclusiveZone::Auto);   // a bar reserving itself
/// SurfaceConfig::new().exclusive_zone(34);                    // fixed reservation
/// SurfaceConfig::new().exclusive_zone(ExclusiveZone::None);   // reserve nothing (toasts, OSD)
/// SurfaceConfig::new().exclusive_zone(ExclusiveZone::Ignore); // overlap panels too
/// ```
///
/// Whatever the policy, the compositor adds the margin on the anchored edge on
/// top of the zone: wlroots and smithay both reserve `zone + margin`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExclusiveZone {
    /// Reserve the surface's own extent on the anchored axis, plus the
    /// margin facing away from the anchor (gtk-layer-shell's "auto exclusive
    /// zone"): the height of a top/bottom bar, the width of a left/right dock —
    /// the axis follows from the anchor, it is never a choice. Content-sized
    /// surfaces keep the reservation in sync when they resize. Per the
    /// layer-shell spec a zone is only meaningful anchored to one edge
    /// (plus optionally both perpendicular ones); on other anchors this
    /// resolves to no reservation.
    Auto,
    /// Reserve this many logical pixels.
    Fixed(u32),
    /// Reserve nothing; the surface is moved by other surfaces' zones.
    None,
    /// Reserve nothing and ignore other surfaces' zones (the surface may
    /// overlap panels; protocol value -1).
    Ignore,
}

impl ExclusiveZone {
    /// Protocol value. [`Auto`](ExclusiveZone::Auto) resolves against the
    /// surface extent on the anchored axis plus the margin facing away from the
    /// anchor.
    pub(crate) fn resolve(self, anchor: Anchor, margin: Margin, width: u32, height: u32) -> i32 {
        match self {
            ExclusiveZone::Auto => match Self::follow_axis(anchor) {
                Some(FollowAxis::Height) => {
                    let inner_margin = if anchor.contains(Anchor::TOP) {
                        margin.bottom
                    } else {
                        margin.top
                    };
                    height as i32 + inner_margin
                }
                Some(FollowAxis::Width) => {
                    let inner_margin = if anchor.contains(Anchor::LEFT) {
                        margin.right
                    } else {
                        margin.left
                    };
                    width as i32 + inner_margin
                }
                None => {
                    log::warn!(
                        "ExclusiveZone::Auto on a corner/full anchor has no \
                         meaningful axis (layer-shell spec); reserving nothing"
                    );
                    0
                }
            },
            ExclusiveZone::Fixed(z) => z as i32,
            ExclusiveZone::None => 0,
            ExclusiveZone::Ignore => -1,
        }
    }

    /// The axis an `Auto` reservation tracks, from the anchor — the
    /// layer-shell rule: a zone is meaningful anchored to one edge, or
    /// one edge plus both perpendicular ones.
    pub(crate) fn follow_axis(anchor: Anchor) -> Option<FollowAxis> {
        let vertical_edge = anchor.contains(Anchor::TOP) != anchor.contains(Anchor::BOTTOM);
        let horizontal_edge = anchor.contains(Anchor::LEFT) != anchor.contains(Anchor::RIGHT);
        match (vertical_edge, horizontal_edge) {
            (true, false) => Some(FollowAxis::Height),
            (false, true) => Some(FollowAxis::Width),
            // Corner (one edge of each axis) or no meaningful anchor
            _ => None,
        }
    }
}

/// The axis an [`ExclusiveZone::Auto`] reservation tracks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FollowAxis {
    Width,
    Height,
}

impl From<u32> for ExclusiveZone {
    fn from(z: u32) -> Self {
        ExclusiveZone::Fixed(z)
    }
}

impl Default for SurfaceConfig {
    fn default() -> Self {
        Self {
            width: SurfaceExtent::Fixed(400),
            height: SurfaceExtent::Fixed(300),
            anchor: Anchor::empty(),
            layer: Layer::Top,
            keyboard_interactivity: KeyboardInteractivity::OnDemand,
            namespace: "guido-surface".to_string(),
            background_color: Color::rgb(0.1, 0.1, 0.15),
            exclusive_zone: ExclusiveZone::None,
            margin: Margin::default(),
            output: None,
            input_region: None,
        }
    }
}

impl SurfaceConfig {
    /// Create a new surface configuration with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the width of the surface.
    pub fn width(mut self, width: impl Into<SurfaceExtent>) -> Self {
        self.width = width.into();
        self
    }

    /// Set the height of the surface.
    pub fn height(mut self, height: impl Into<SurfaceExtent>) -> Self {
        self.height = height.into();
        self
    }

    /// Set the anchor edges for the surface.
    pub fn anchor(mut self, anchor: Anchor) -> Self {
        self.anchor = anchor;
        self
    }

    /// Set the layer shell layer.
    pub fn layer(mut self, layer: Layer) -> Self {
        self.layer = layer;
        self
    }

    /// Set the namespace identifier for the surface.
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = namespace.into();
        self
    }

    /// Set the background color for the surface.
    pub fn background_color(mut self, color: Color) -> Self {
        self.background_color = color;
        self
    }

    /// Set the exclusive zone (reserves screen space).
    /// Pass Some(0) for no exclusive zone, None to use the surface height.
    pub fn exclusive_zone(mut self, zone: impl Into<ExclusiveZone>) -> Self {
        self.exclusive_zone = zone.into();
        self
    }

    /// Set the keyboard interactivity mode.
    ///
    /// - `KeyboardInteractivity::None`: Surface never receives keyboard focus.
    /// - `KeyboardInteractivity::OnDemand`: Surface receives focus when clicked (default).
    /// - `KeyboardInteractivity::Exclusive`: Surface grabs keyboard focus exclusively.
    pub fn keyboard_interactivity(mut self, mode: KeyboardInteractivity) -> Self {
        self.keyboard_interactivity = mode;
        self
    }

    /// Set the margins from the anchored screen edges, applied at creation.
    ///
    /// Use [`SurfaceHandle::set_margin`] to change them at runtime.
    pub fn margin(mut self, margin: impl Into<Margin>) -> Self {
        self.margin = margin.into();
        self
    }

    /// Pin the surface to a specific output (monitor).
    ///
    /// Get output ids from the reactive [`crate::outputs::outputs`] list. If
    /// the output is disconnected before the surface is created, the
    /// compositor chooses one instead. The output cannot be changed after
    /// creation (a layer surface is bound to its output for its lifetime).
    pub fn output(mut self, output: OutputId) -> Self {
        self.output = Some(output);
        self
    }

    /// Limit pointer/touch input to the given rectangles (logical surface
    /// coordinates). Everything outside them lets clicks pass through to
    /// whatever is below. An empty list makes the surface fully
    /// click-through.
    ///
    /// Use `SurfaceHandle::set_input_region` to change it at runtime.
    pub fn input_region(mut self, rects: impl Into<Vec<Rect>>) -> Self {
        self.input_region = Some(rects.into());
        self
    }

    /// Make the whole surface click-through: pointer and touch input passes
    /// to whatever is below. Shorthand for `input_region([])`.
    pub fn click_through(mut self) -> Self {
        self.input_region = Some(Vec::new());
        self
    }
}

/// Which point of the anchor rectangle a popup attaches to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PopupAnchor {
    /// Center of the anchor rect.
    #[default]
    None,
    Top,
    Bottom,
    Left,
    Right,
    TopLeft,
    BottomLeft,
    TopRight,
    BottomRight,
}

/// Which direction a popup grows from its anchor point.
///
/// `Bottom` means "downwards" (typical menu under a bar button).
pub type PopupGravity = PopupAnchor;

/// Configuration for an xdg popup anchored to a parent surface.
///
/// The compositor positions the popup relative to `anchor_rect` (parent
/// surface coordinates) and adjusts it to stay on screen (flip/slide).
///
/// ```no_run
/// # use guido::prelude::*;
/// # let bar_surface_id = SurfaceId::next();
/// # let button_rect = Rect::new(0.0, 0.0, 10.0, 10.0);
/// # let menu_widget = || text("menu");
/// spawn_popup(
///     bar_surface_id,
///     PopupConfig::new(250)
///         .anchor_rect(button_rect)
///         .anchor(PopupAnchor::Bottom)
///         .gravity(PopupGravity::Bottom)
///         .grab(),
///     move || menu_widget(),
/// );
/// ```
#[derive(Clone)]
pub struct PopupConfig {
    /// Popup width in logical pixels.
    pub width: u32,
    /// Popup height in logical pixels. `None` (the default) sizes the popup
    /// to its content: the widget is laid out at the given width before the
    /// popup is created, and repositioned when its content height changes
    /// (submenus expanding, lists growing). Content using `height(fill())`
    /// resolves to the screen-height cap — give such popups an explicit
    /// height instead.
    pub height: Option<u32>,
    /// Rectangle the popup anchors to, in parent surface coordinates.
    pub anchor_rect: Rect,
    /// Which point of the anchor rect to attach to.
    pub anchor: PopupAnchor,
    /// Which direction the popup grows.
    pub gravity: PopupGravity,
    /// Extra offset from the anchor point.
    pub offset: (i32, i32),
    /// Take an input grab: clicking outside dismisses the popup (menu
    /// semantics). The compositor reports the dismissal reactively — see
    /// [`PopupHandle::dismissed`].
    pub grab: bool,
    /// Background color of the popup surface.
    pub background_color: Color,
}

impl PopupConfig {
    /// Create a popup configuration with the given width; the height sizes
    /// to the content (see [`PopupConfig::height`] to fix it instead).
    pub fn new(width: u32) -> Self {
        Self {
            width,
            height: None,
            anchor_rect: Rect::new(0.0, 0.0, 1.0, 1.0),
            anchor: PopupAnchor::Bottom,
            gravity: PopupGravity::Bottom,
            offset: (0, 0),
            grab: false,
            background_color: Color::TRANSPARENT,
        }
    }

    /// Fix the popup height instead of sizing it to the content.
    pub fn height(mut self, height: u32) -> Self {
        self.height = Some(height);
        self
    }

    /// Set the rectangle the popup anchors to (parent surface coordinates).
    /// Typically a widget's bounds from a [`crate::widget_ref::WidgetRef`].
    pub fn anchor_rect(mut self, rect: Rect) -> Self {
        self.anchor_rect = rect;
        self
    }

    /// Set which point of the anchor rect the popup attaches to.
    pub fn anchor(mut self, anchor: PopupAnchor) -> Self {
        self.anchor = anchor;
        self
    }

    /// Set which direction the popup grows.
    pub fn gravity(mut self, gravity: PopupGravity) -> Self {
        self.gravity = gravity;
        self
    }

    /// Set an extra offset from the anchor point.
    pub fn offset(mut self, x: i32, y: i32) -> Self {
        self.offset = (x, y);
        self
    }

    /// Take an input grab: clicking outside dismisses the popup.
    pub fn grab(mut self) -> Self {
        self.grab = true;
        self
    }

    /// Set the background color of the popup surface.
    pub fn background_color(mut self, color: Color) -> Self {
        self.background_color = color;
        self
    }
}

/// Handle to a spawned surface for controlling it from widget code.
///
/// The handle can be cloned and shared between callbacks. It allows
/// closing the surface and checking if it's still open.
#[derive(Clone)]
pub struct SurfaceHandle {
    id: SurfaceId,
}

impl SurfaceHandle {
    /// Close this surface (removes from screen, destroys widget tree).
    ///
    /// The surface goes on the loop's next pass, but its widgets take no
    /// further input from the moment this is called: a key press or a click
    /// already queued behind the one that closed it is not delivered.
    pub fn close(&self) {
        push_surface_command(SurfaceCommand::Close(self.id));
    }

    /// Get the surface ID.
    pub fn id(&self) -> SurfaceId {
        self.id
    }

    /// Set the layer shell layer for this surface.
    ///
    /// Changes take effect immediately. Use `Layer::Overlay` to appear above
    /// other windows, `Layer::Top` for normal status bars, etc.
    pub fn set_layer(&self, layer: Layer) {
        push_surface_command(SurfaceCommand::SetLayer { id: self.id, layer });
    }

    /// Set the keyboard interactivity mode for this surface.
    ///
    /// - `KeyboardInteractivity::None`: Surface never receives keyboard focus.
    /// - `KeyboardInteractivity::OnDemand`: Surface receives focus when clicked.
    /// - `KeyboardInteractivity::Exclusive`: Surface grabs keyboard focus exclusively.
    pub fn set_keyboard_interactivity(&self, mode: KeyboardInteractivity) {
        push_surface_command(SurfaceCommand::SetKeyboardInteractivity { id: self.id, mode });
    }

    /// Set the anchor edges for this surface.
    ///
    /// Anchor determines which screen edges the surface attaches to.
    /// For example, `Anchor::TOP | Anchor::LEFT | Anchor::RIGHT` creates a
    /// top bar that spans the width of the screen.
    pub fn set_anchor(&self, anchor: Anchor) {
        push_surface_command(SurfaceCommand::SetAnchor {
            id: self.id,
            anchor,
        });
    }

    /// Set the size of this surface, in the same vocabulary
    /// [`SurfaceConfig::width`] takes — so an axis can be handed back to
    /// [`content()`] at runtime, not only pinned to a number.
    ///
    /// Note: when anchored to both edges on an axis (e.g. LEFT and RIGHT),
    /// the compositor may override that dimension.
    pub fn set_size(&self, width: impl Into<SurfaceExtent>, height: impl Into<SurfaceExtent>) {
        push_surface_command(SurfaceCommand::SetSize {
            id: self.id,
            width: width.into(),
            height: height.into(),
        });
    }

    /// Set the screen-space reservation for this surface, in the same
    /// vocabulary [`SurfaceConfig::exclusive_zone`] takes.
    ///
    /// [`ExclusiveZone::Auto`] keeps following the surface's extent from here
    /// on, exactly as it would had it been declared at creation.
    pub fn set_exclusive_zone(&self, zone: impl Into<ExclusiveZone>) {
        push_surface_command(SurfaceCommand::SetExclusiveZone {
            id: self.id,
            zone: zone.into(),
        });
    }

    /// Set the margins from the anchored screen edges, in the same vocabulary
    /// [`SurfaceConfig::margin`] takes.
    pub fn set_margin(&self, margin: impl Into<Margin>) {
        push_surface_command(SurfaceCommand::SetMargin {
            id: self.id,
            margin: margin.into(),
        });
    }

    /// Set the input region for this surface.
    ///
    /// `None` restores the default (the whole surface accepts input).
    /// `Some(rects)` limits pointer/touch input to those rectangles in
    /// logical surface coordinates — everything outside them lets clicks
    /// pass through to whatever is below. `Some(vec![])` makes the surface
    /// fully click-through.
    pub fn set_input_region(&self, rects: Option<Vec<Rect>>) {
        push_surface_command(SurfaceCommand::SetInputRegion { id: self.id, rects });
    }
}

/// Commands for dynamic surface creation/destruction and property modification.
#[allow(clippy::type_complexity)]
pub(crate) enum SurfaceCommand {
    /// Create a new surface with the given configuration and widget factory.
    Create {
        id: SurfaceId,
        config: SurfaceConfig,
        widget_fn: Box<dyn FnOnce() -> Box<dyn Widget>>,
    },
    /// Close and destroy a surface by ID.
    Close(SurfaceId),
    /// Set the layer shell layer for a surface.
    SetLayer { id: SurfaceId, layer: Layer },
    /// Set the keyboard interactivity mode for a surface.
    SetKeyboardInteractivity {
        id: SurfaceId,
        mode: KeyboardInteractivity,
    },
    /// Set the anchor edges for a surface.
    SetAnchor { id: SurfaceId, anchor: Anchor },
    /// Set the size of a surface.
    SetSize {
        id: SurfaceId,
        width: SurfaceExtent,
        height: SurfaceExtent,
    },
    /// Set the screen-space reservation for a surface. Resolved to a protocol
    /// value by the loop, which is where the anchor and the current extent are.
    SetExclusiveZone { id: SurfaceId, zone: ExclusiveZone },
    /// Set the margin for a surface.
    SetMargin { id: SurfaceId, margin: Margin },
    /// Set the input region for a surface.
    SetInputRegion {
        id: SurfaceId,
        rects: Option<Vec<Rect>>,
    },
    /// Create an xdg popup anchored to a parent surface.
    CreatePopup {
        id: SurfaceId,
        parent: SurfaceId,
        config: PopupConfig,
        widget_fn: Box<dyn FnOnce() -> Box<dyn Widget>>,
    },
}

/// Push a surface command to the application's queue, waking the loop that
/// will carry it out.
pub(crate) fn push_surface_command(cmd: SurfaceCommand) {
    with_app_state(|app| app.surface_commands.push(cmd));
}

/// Drain all pending surface commands. Called by the main event loop.
pub(crate) fn drain_surface_commands() -> Vec<SurfaceCommand> {
    with_app_state(|app| app.surface_commands.drain())
}

/// The surfaces a close is queued for and not yet carried out.
pub(crate) fn closes_requested() -> Vec<SurfaceId> {
    with_app_state(|app| {
        app.surface_commands.peek(|queued| {
            queued
                .iter()
                .filter_map(|cmd| match cmd {
                    SurfaceCommand::Close(id) => Some(*id),
                    _ => None,
                })
                .collect()
        })
    })
}

/// Spawn a new surface at runtime.
///
/// This function can be called from anywhere in widget code (e.g., event handlers)
/// to create a new layer shell surface dynamically.
///
/// The widget factory closure creates the root widget for the surface.
///
/// # Arguments
///
/// * `config` - Configuration for the new surface
/// * `widget_fn` - Factory function that creates the root widget for the surface
///
/// # Returns
///
/// A `SurfaceHandle` that can be used to close the surface later.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// let handle = spawn_surface(
///     SurfaceConfig::new()
///         .width(300)
///         .height(200)
///         .layer(Layer::Overlay),
///     || {
///         container()
///             .background(Color::rgb(0.2, 0.2, 0.3))
///             .child(text("Popup content"))
///     }
/// );
///
/// // Later, to close:
/// handle.close();
/// ```
pub fn spawn_surface<W, F>(config: SurfaceConfig, widget_fn: F) -> SurfaceHandle
where
    W: Widget + 'static,
    F: FnOnce() -> W + 'static,
{
    let id = SurfaceId::next();

    push_surface_command(SurfaceCommand::Create {
        id,
        config,
        widget_fn: Box::new(move || Box::new(widget_fn())),
    });

    SurfaceHandle { id }
}

/// Handle to a spawned popup.
///
/// Popups close either programmatically ([`PopupHandle::close`]) or by the
/// compositor (grab + outside click, parent gone): watch that reactively
/// via [`PopupHandle::dismissed`].
#[derive(Clone, Copy)]
pub struct PopupHandle {
    id: SurfaceId,
}

impl PopupHandle {
    /// The popup's surface ID.
    pub fn id(&self) -> SurfaceId {
        self.id
    }

    /// Close the popup programmatically.
    ///
    /// Dismissal is announced when the loop closes it, not here: closing walks
    /// the popup's descendants first, so a submenu is reported gone before the
    /// menu it hangs from — the order the compositor's own dismissal gives.
    ///
    /// Input stops sooner: from the moment this is called, the popup and every
    /// popup hanging from it take none of what is still queued for them, so a
    /// second click on a menu item that closed the menu picks nothing.
    pub fn close(&self) {
        push_surface_command(SurfaceCommand::Close(self.id));
    }

    /// Whether the popup has been dismissed (tracked read — reactive inside
    /// tracked closures). True after `close()` or a compositor dismissal
    /// (click outside a grabbed popup, parent closed).
    ///
    /// Safe to read after the popup is gone — including from a submenu whose
    /// parent was dismissed by the same click.
    pub fn dismissed(&self) -> bool {
        let live = with_app_state(|app| app.live_popups.borrow().contains(&self.id));
        if live {
            // Tracked only while there is still something to wait for. One
            // notifier serves every popup, so a watcher that stayed subscribed
            // after its own popup was gone would be woken by every dismissal
            // that followed — and applications create these watchers in the
            // click that opens the popup, where the owner is the root, so they
            // accumulate for the life of the `App`. Reading a popup that is
            // already gone subscribes to nothing: the answer can never change
            // again.
            popup_dismissal().track();
        }
        !live
    }
}

/// The notifier that makes reading the registry reactive. It belongs to the
/// application, not to whichever popup happened to be opened first.
static POPUP_DISMISSAL: GlobalSignal<()> = GlobalSignal::new(|| ());

fn popup_dismissal() -> Trigger {
    Trigger::from_signal(POPUP_DISMISSAL.get())
}

/// Mark a popup dismissed (called by the platform layer on popup_done, and
/// on close). Removes the registry entry and notifies every watcher.
pub(crate) fn mark_popup_dismissed(id: SurfaceId) {
    let was_open = with_app_state(|app| app.live_popups.borrow_mut().remove(&id));
    if was_open {
        popup_dismissal().notify();
    }
}

/// Spawn an xdg popup anchored to a parent surface.
///
/// The compositor positions the popup relative to `config.anchor_rect`
/// (parent surface coordinates), keeps it on screen (flip/slide at screen
/// edges), and — with [`PopupConfig::grab`] — dismisses it when the user
/// clicks outside: real menu semantics, no fullscreen overlay needed.
///
/// The popup renders its own widget tree and shares the reactive state
/// with the rest of the app, like any surface.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// # let button_ref = create_widget_ref();
/// # let bar_id = SurfaceId::next();
/// # let menu_open = create_signal(true);
/// # let menu_widget = || text("menu");
/// let button_rect = button_ref.rect().get();
/// let popup = spawn_popup(
///     bar_id,
///     PopupConfig::new(250)
///         .anchor_rect(button_rect)
///         .grab(),
///     move || menu_widget(),
/// );
/// // Reactively observe dismissal (e.g. reset the open/closed state):
/// create_effect(move || {
///     if popup.dismissed() {
///         menu_open.set(false);
///     }
/// });
/// ```
pub fn spawn_popup<W, F>(parent: SurfaceId, config: PopupConfig, widget_fn: F) -> PopupHandle
where
    W: Widget + 'static,
    F: FnOnce() -> W + 'static,
{
    let id = SurfaceId::next();
    with_app_state(|app| app.live_popups.borrow_mut().insert(id));

    push_surface_command(SurfaceCommand::CreatePopup {
        id,
        parent,
        config,
        widget_fn: Box::new(move || Box::new(widget_fn())),
    });

    PopupHandle { id }
}

/// Get a handle to control an existing surface.
///
/// This can be used to modify surfaces added via `add_surface()` or `spawn_surface()`.
/// The handle allows changing surface properties like layer, keyboard interactivity,
/// anchor, size, exclusive zone, and margin.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// # let config = SurfaceConfig::new();
/// # let status_bar_id = SurfaceId::next();
/// // Store the ID when adding the surface
/// App::new().run(|app| {
///     let status_bar_id = app.add_surface(config, move || {
///         container()
///             .on_click(move || {
///                 // Get handle and modify properties
///                 let handle = surface_handle(status_bar_id);
///                 handle.set_layer(Layer::Overlay);
///             })
///             .child(text("Click to promote to overlay"))
///     });
/// });
/// ```
pub fn surface_handle(id: SurfaceId) -> SurfaceHandle {
    SurfaceHandle { id }
}

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

    /// A fixed axis is held at its own value, an owned one at what the
    /// compositor confirmed, and a content axis is left to the measure.
    #[test]
    fn a_measure_holds_fixed_axes_at_their_value_and_owned_ones_at_the_compositors() {
        let confirmed = (300, 32);
        let free = SurfaceConfig::new().width(content()).height(48);
        assert_eq!(measure_pins(&free, confirmed), (None, Some(48)));

        let stretched = SurfaceConfig::new()
            .width(200)
            .height(content())
            .anchor(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT);
        assert_eq!(measure_pins(&stretched, confirmed), (Some(300), None));
    }

    /// The doc promises "the same shorthands a `Padding` takes, in the same
    /// order". The two types are written out separately — one holds i32 for the
    /// protocol, the other f32 for layout — so the promise is only worth
    /// anything if something checks it. This does, edge by edge, over every
    /// shorthand and a set of inputs where confusing two edges shows up:
    /// asymmetric, and non-zero everywhere.
    #[test]
    fn a_margin_converts_exactly_as_a_padding_does() {
        let same = |m: Margin, p: crate::widgets::Padding, what: &str| {
            assert_eq!(m.top as f32, p.top, "{what}: top");
            assert_eq!(m.right as f32, p.right, "{what}: right");
            assert_eq!(m.bottom as f32, p.bottom, "{what}: bottom");
            assert_eq!(m.left as f32, p.left, "{what}: left");
        };

        same(
            Margin::from(8),
            crate::widgets::Padding::from(8),
            "one value",
        );
        same(
            Margin::all(8),
            crate::widgets::Padding::all(8.0),
            "all(), the named form",
        );
        same(
            Margin::from([4, 12]),
            crate::widgets::Padding::from([4, 12]),
            "[vertical, horizontal]",
        );
        same(
            Margin::from([1, 2, 3, 4]),
            crate::widgets::Padding::from([1, 2, 3, 4]),
            "[top, right, bottom, left]",
        );

        // And spelled out once, so a shared mistake in both types would still
        // be caught: CSS order, clockwise from the top.
        assert_eq!(
            Margin::from([1, 2, 3, 4]),
            Margin {
                top: 1,
                right: 2,
                bottom: 3,
                left: 4
            }
        );
        assert_eq!(
            Margin::from([4, 12]),
            Margin {
                top: 4,
                right: 12,
                bottom: 4,
                left: 12
            }
        );
    }

    /// The anchored edge's margin is the compositor's to add, so `Auto` counts
    /// only the one facing away.
    #[test]
    fn an_auto_zone_adds_the_margin_facing_away_from_its_anchor() {
        let margin = Margin::from([6, 20, 9, 30]);
        let top = ExclusiveZone::Auto.resolve(Anchor::TOP, margin, 800, 32);
        assert_eq!(top, 32 + 9, "a top bar counts its bottom margin");

        let bottom = ExclusiveZone::Auto.resolve(Anchor::BOTTOM, margin, 800, 32);
        assert_eq!(bottom, 32 + 6, "a bottom bar counts its top margin");

        let left = ExclusiveZone::Auto.resolve(Anchor::LEFT, margin, 48, 600);
        assert_eq!(left, 48 + 20, "a left dock counts its right margin");

        let right = ExclusiveZone::Auto.resolve(Anchor::RIGHT, margin, 48, 600);
        assert_eq!(right, 48 + 30, "a right dock counts its left margin");

        let full_width = ExclusiveZone::Auto.resolve(
            Anchor::TOP | Anchor::LEFT | Anchor::RIGHT,
            margin,
            800,
            32,
        );
        assert_eq!(
            full_width,
            32 + 9,
            "and a full-width bar the same as a top one"
        );
    }

    /// A corner anchor names one edge of each axis, so neither axis is the one
    /// the reservation follows and `Auto` reserves nothing — the layer-shell
    /// spec has no answer for it either.
    ///
    /// It is worth pinning because it is a premise elsewhere: the dock fixtures
    /// that watch the deferral guard in `publish_exclusive_zone` are anchored
    /// `LEFT | TOP | BOTTOM` rather than `TOP | LEFT` precisely so that their
    /// assertions do not hold for this reason instead of the intended one.
    #[test]
    fn a_corner_or_full_anchor_has_no_axis_to_follow_and_reserves_nothing() {
        let margin = Margin::all(10);
        assert_eq!(
            ExclusiveZone::Auto.resolve(Anchor::TOP | Anchor::LEFT, margin, 48, 600),
            0
        );
        assert_eq!(
            ExclusiveZone::Auto.resolve(
                Anchor::TOP | Anchor::LEFT | Anchor::RIGHT | Anchor::BOTTOM,
                margin,
                48,
                600
            ),
            0,
            "and so does a surface pinned to all four"
        );
    }

    /// The other policies are numbers, and never consult anything.
    #[test]
    fn the_other_zone_policies_ignore_the_surface() {
        let m = Margin::all(10);
        assert_eq!(ExclusiveZone::None.resolve(Anchor::TOP, m, 800, 32), 0);
        assert_eq!(ExclusiveZone::Ignore.resolve(Anchor::TOP, m, 800, 32), -1);
        assert_eq!(
            ExclusiveZone::from(34u32).resolve(Anchor::TOP, m, 800, 32),
            34
        );
    }

    /// A clean slate: a root owner for the effects, no popups left over from
    /// another test on this thread, and the command queue drained of the
    /// `CreatePopup`s these tests push and nobody consumes.
    fn fresh() {
        crate::reactive::owner::create_root_owner();
        crate::app_state::reset();
    }

    fn popup() -> PopupHandle {
        spawn_popup(SurfaceId::next(), PopupConfig::new(120), || {
            crate::widgets::container()
        })
    }

    /// A `PopupHandle` is `Copy` and outlives its popup by design, so every
    /// read through it has to survive the scope that opened it. For a nested
    /// popup that scope *is* the parent popup — the click that opens the child
    /// is dispatched to a widget living inside the parent, and one outside
    /// click dismisses both. A dismissal announced through something owned by
    /// that scope is announced to nobody.
    #[test]
    fn a_popup_reports_its_dismissal_after_the_scope_that_opened_it_is_gone() {
        fresh();
        let (child, parent_scope) = crate::reactive::owner::with_owner(|| {
            let child = popup();
            // The parent popup is also the first thing to watch its child.
            assert!(!child.dismissed());
            child
        });
        crate::reactive::owner::dispose_owner_now(parent_scope);

        assert!(!child.dismissed(), "a live popup is not dismissed");
        mark_popup_dismissed(child.id());
        assert!(child.dismissed(), "and its death is still readable");
    }

    /// Dismissal is the one thing an application watches a popup for, and it
    /// watches it reactively — closing the menu means resetting the state that
    /// opened it.
    #[test]
    fn watching_a_popup_reacts_to_its_dismissal() {
        fresh();
        let popup = popup();
        let seen = std::rc::Rc::new(std::cell::Cell::new(false));
        let observer = seen.clone();
        crate::reactive::create_effect(move || observer.set(popup.dismissed()));
        assert!(!seen.get(), "the effect ran once, on a live popup");

        mark_popup_dismissed(popup.id());
        assert!(seen.get(), "the effect re-ran when the popup was dismissed");
    }

    /// One popup's death says nothing about another's.
    #[test]
    fn a_dismissal_speaks_only_for_the_popup_it_names() {
        fresh();
        let (first, second) = (popup(), popup());

        mark_popup_dismissed(first.id());
        assert!(first.dismissed());
        assert!(!second.dismissed(), "the other popup is still open");
    }

    /// One notifier serves every popup, and applications create their watchers
    /// in the click that opens one — where the owner is the root, so the
    /// watcher lives as long as the `App`. If a watcher stayed subscribed after
    /// its own popup was gone, opening and closing a menu five hundred times
    /// would leave five hundred of them to re-run on the next dismissal.
    #[test]
    fn a_watcher_stops_being_woken_once_its_own_popup_is_gone() {
        fresh();
        let (watched, other) = (popup(), popup());
        let runs = std::rc::Rc::new(std::cell::Cell::new(0));
        let counter = runs.clone();
        crate::reactive::create_effect(move || {
            watched.dismissed();
            counter.set(counter.get() + 1);
        });
        assert_eq!(runs.get(), 1, "the initial run");

        mark_popup_dismissed(watched.id());
        assert_eq!(runs.get(), 2, "woken for its own popup");

        mark_popup_dismissed(other.id());
        assert_eq!(
            runs.get(),
            2,
            "and not for anybody else's, once its own answer can no longer change"
        );
    }

    /// `close()` hands the popup to the loop rather than declaring it gone on
    /// the spot: closing walks the descendants first, so a submenu is reported
    /// gone before the menu it hangs from — the order the compositor's own
    /// dismissal gives. Declaring it here would report them the other way
    /// round, and only for this one path.
    #[test]
    fn closing_leaves_the_announcement_to_the_close_that_follows() {
        fresh();
        let popup = popup();
        popup.close();

        assert!(!popup.dismissed(), "still open until the loop closes it");
        let queued = drain_surface_commands();
        assert!(
            queued
                .iter()
                .any(|c| matches!(c, SurfaceCommand::Close(id) if *id == popup.id())),
            "and the close is queued"
        );
    }

    /// A surface never holds a scale below 1, and a scale it already holds is
    /// not a change.
    ///
    /// The floor used to live inside `buffer_size`, where only the buffer got
    /// it; the renderer and the damage rectangles read the same number and did
    /// not.
    #[test]
    fn a_scale_is_floored_at_one_and_a_repeat_of_it_is_not_a_change() {
        assert_eq!(adopted_scale(1.0, 1.5), (1.5, true));
        assert_eq!(adopted_scale(1.5, 1.5), (1.5, false));
        assert_eq!(adopted_scale(1.5, 2.0), (2.0, true));

        // The 1 a surface starts at, confirmed, tells it nothing new.
        assert_eq!(adopted_scale(1.0, 1.0), (1.0, false));

        // Below 1 is floored, and the floor is what the repeat compares
        // against — so 0.5 twice is one change, not two.
        assert_eq!(adopted_scale(2.0, 0.5), (1.0, true));
        assert_eq!(adopted_scale(1.0, 0.5), (1.0, false));
    }

    /// The buffer is the logical size times the scale, rounded halfway away
    /// from zero — and the two casts this replaced are both wrong at 1.5.
    ///
    /// The scale reached the render target through `scale_factor as u32`,
    /// which is 1 for every scale below 2: a 2560x33 bar on a 1.5-scaled
    /// output drew 2560x33 pixels and the compositor stretched them over
    /// 3840x50. Rounding the product instead, but with a cast, still loses the
    /// half pixel the protocol rounds up — and half a pixel short of the
    /// destination a viewport declares is `wp_viewport: error 2`, which is
    /// fatal.
    #[test]
    fn a_buffer_is_the_logical_size_scaled_and_rounded_half_away_from_zero() {
        // 2560 x 33 at 1.5 is 3840 x 49.5, and the half goes up.
        assert_eq!(buffer_size((2560, 33), 1.5), (3840, 50));

        // Held against both casts this replaced, so that a `buffer_size` that
        // went back to either of them fails here rather than passing the line
        // above by accident. Truncating the scale gives the bar's own size, at
        // 1:1; truncating the product gives half a pixel short.
        let truncated_scale = 1.5_f32 as u32;
        assert_ne!(
            (2560 * truncated_scale, 33 * truncated_scale),
            buffer_size((2560, 33), 1.5)
        );
        assert_ne!(
            ((2560.0 * 1.5) as u32, (33.0 * 1.5) as u32),
            buffer_size((2560, 33), 1.5)
        );

        // The session lock surface from the report, which asked for 5120x2880
        // on a 3840x2160 screen.
        assert_eq!(buffer_size((3840, 2160), 1.5), (5760, 3240));

        // Integer scales are unmoved — what every compositor without the
        // protocol still gets.
        assert_eq!(buffer_size((2560, 32), 1.0), (2560, 32));
        assert_eq!(buffer_size((2560, 32), 2.0), (5120, 64));

        // A scale that is not a binary fraction: 125/120 of 2560 is
        // 2666.66..., and 1.0416666 in f32 is not that number.
        assert_eq!(buffer_size((2560, 33), 125.0 / 120.0), (2667, 34));
    }
}