1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    crate::client::{Client, TaskQueue},
    crate::compositor::{Surface, SurfaceCommand, SurfaceRole},
    crate::display::Callback,
    crate::object::{NewObjectExt, ObjectRef, RequestReceiver},
    crate::scenic::{Flatland, FlatlandPtr},
    anyhow::{format_err, Error, Result},
    async_utils::hanging_get::client::HangingGetStream,
    fidl::endpoints::{create_endpoints, create_proxy, ServerEnd},
    fidl::prelude::*,
    fidl_fuchsia_element::{
        Annotation, AnnotationKey, AnnotationValue, ViewControllerMarker, ViewControllerProxy,
        ViewSpec,
    },
    fidl_fuchsia_math::{Rect, Size, SizeF},
    fidl_fuchsia_math::{SizeU, Vec_},
    fidl_fuchsia_ui_app::{ViewProviderControlHandle, ViewProviderMarker, ViewProviderRequest},
    fidl_fuchsia_ui_composition::{
        ChildViewWatcherMarker, ChildViewWatcherProxy, ContentId, FlatlandEvent,
        FlatlandEventStream, FlatlandMarker, ParentViewportWatcherMarker,
        ParentViewportWatcherProxy, TransformId, ViewportProperties,
    },
    fidl_fuchsia_ui_pointer::{
        MousePointerSample, MouseSourceMarker, MouseSourceProxy, TouchPointerSample,
        TouchSourceMarker, TouchSourceProxy,
    },
    fidl_fuchsia_ui_views::{
        ViewIdentityOnCreation, ViewRefFocusedMarker, ViewRefFocusedProxy, ViewportCreationToken,
    },
    fuchsia_async as fasync,
    fuchsia_component::client::connect_to_protocol,
    fuchsia_scenic::flatland::{ViewBoundProtocols, ViewCreationTokenPair},
    fuchsia_scenic::ViewRefPair,
    fuchsia_sync::Mutex,
    fuchsia_trace as ftrace, fuchsia_wayland_core as wl,
    fuchsia_wayland_core::Enum,
    futures::prelude::*,
    std::collections::BTreeSet,
    std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    xdg_shell_server_protocol::{
        self as xdg_shell,
        xdg_positioner::{Anchor, Gravity},
        xdg_toplevel, XdgPopupEvent, XdgPopupRequest, XdgPositionerRequest, XdgSurfaceEvent,
        XdgSurfaceRequest, XdgToplevelEvent, XdgToplevelRequest, XdgWmBase, XdgWmBaseRequest,
    },
};

// This must start at 1 to satisfy the ViewProducer protocol.
static NEXT_VIEW_ID: AtomicUsize = AtomicUsize::new(1);

// Annotations namespace for title.
static TITLE_ANNOTATION_NS: &'static str = "ermine";

// Title annotation value.
static TITLE_ANNOTATION_VALUE: &'static str = "name";

///
/// Popup, dialog, and multiple toplevel window status:
///
/// The view system on Fuchsia is lacking support for these
/// type of window management features today so we emulate them
/// using child views.
///
/// Here are the child surface features currently implemented:
///
/// - XDG shell popups with static placement. Configured to only
///   occupy the the desired area.
/// - XDG shell toplevels without a parent. Configured to occupy
///   the fullscreen area.
/// - XDG shell toplevels with parent and dynamic offset set
///   using the aura shell interface. Configured to only occupy
///   the the desired area. This is used to implement X11
///   override-redirect windows for tooltips and menus.
/// - XDG shell toplevels without a parent but created after
///   a view provider has already been created. These toplevels
///   are created as child views of the root XDG surface.
/// - Window controls are missing but XDG surfaces can be closed
///   by pressing Escape key three times quickly.
///

/// `XdgShell` is an implementation of the xdg_wm_base global.
///
/// `XdgShell` is used to create traditional desktop-style applications. The
/// `XdgShell` can be used to create `XdgSurface` objects. Similar to `Surface`,
/// an `XdgSurface` doesn't do much good on it's own until it's assigned a
/// sub-role (ex: `XdgToplevel`, `XdgPopup`).
pub struct XdgShell;

impl XdgShell {
    /// Creates a new `XdgShell` global.
    pub fn new() -> Self {
        Self
    }
}

impl RequestReceiver<XdgWmBase> for XdgShell {
    fn receive(
        this: ObjectRef<Self>,
        request: XdgWmBaseRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            XdgWmBaseRequest::Destroy => {
                client.delete_id(this.id())?;
            }
            XdgWmBaseRequest::GetXdgSurface { id, surface } => {
                let xdg_surface = XdgSurface::new(surface);
                let surface_ref = xdg_surface.surface_ref;
                let xdg_surface_ref = id.implement(client, xdg_surface)?;
                surface_ref.get_mut(client)?.set_role(SurfaceRole::XdgSurface(xdg_surface_ref))?;
            }
            XdgWmBaseRequest::CreatePositioner { id } => {
                id.implement(client, XdgPositioner::new())?;
            }
            XdgWmBaseRequest::Pong { .. } => {}
        }
        Ok(())
    }
}

pub struct XdgPositioner {
    size: Size,
    anchor_rect: Rect,
    anchor: Enum<Anchor>,
    gravity: Enum<Gravity>,
    offset: (i32, i32),
}

impl XdgPositioner {
    pub fn new() -> Self {
        Self {
            size: Size { width: 0, height: 0 },
            anchor_rect: Rect { x: 0, y: 0, width: 0, height: 0 },
            anchor: Enum::Recognized(Anchor::None),
            gravity: Enum::Recognized(Gravity::None),
            offset: (0, 0),
        }
    }

    pub fn get_geometry(&self) -> Result<Rect, Error> {
        let mut geometry = Rect {
            x: self.offset.0,
            y: self.offset.1,
            width: self.size.width,
            height: self.size.height,
        };

        let anchor = self.anchor.as_enum()?;
        geometry.x += match anchor {
            Anchor::Left | Anchor::BottomLeft | Anchor::TopLeft => self.anchor_rect.x,
            Anchor::Right | Anchor::BottomRight | Anchor::TopRight => {
                self.anchor_rect.x + self.anchor_rect.width
            }
            _ => self.anchor_rect.x + self.anchor_rect.width / 2,
        };

        geometry.y += match anchor {
            Anchor::Top | Anchor::TopLeft | Anchor::TopRight => self.anchor_rect.y,
            Anchor::Bottom | Anchor::BottomLeft | Anchor::BottomRight => {
                self.anchor_rect.y + self.anchor_rect.height
            }
            _ => self.anchor_rect.y + self.anchor_rect.height / 2,
        };

        let gravity = self.gravity.as_enum()?;
        geometry.x -= match gravity {
            Gravity::Left | Gravity::BottomLeft | Gravity::TopLeft => geometry.width,
            Gravity::Right | Gravity::BottomRight | Gravity::TopRight => 0,
            _ => geometry.width / 2,
        };

        geometry.y -= match gravity {
            Gravity::Top | Gravity::TopLeft | Gravity::TopRight => geometry.height,
            Gravity::Bottom | Gravity::BottomLeft | Gravity::BottomRight => 0,
            _ => geometry.height / 2,
        };

        Ok(geometry)
    }

    fn set_size(&mut self, width: i32, height: i32) {
        self.size = Size { width, height };
    }

    fn set_anchor_rect(&mut self, x: i32, y: i32, width: i32, height: i32) {
        self.anchor_rect = Rect { x, y, width, height };
    }

    fn set_anchor(&mut self, anchor: Enum<Anchor>) {
        self.anchor = anchor;
    }

    fn set_gravity(&mut self, gravity: Enum<Gravity>) {
        self.gravity = gravity;
    }

    fn set_offset(&mut self, x: i32, y: i32) {
        self.offset = (x, y);
    }
}

impl RequestReceiver<xdg_shell::XdgPositioner> for XdgPositioner {
    fn receive(
        this: ObjectRef<Self>,
        request: XdgPositionerRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            XdgPositionerRequest::Destroy => {
                client.delete_id(this.id())?;
            }
            XdgPositionerRequest::SetSize { width, height } => {
                if width <= 0 || height <= 0 {
                    return Err(format_err!(
                        "invalid_input error width={:?} height={:?}",
                        width,
                        height
                    ));
                }
                this.get_mut(client)?.set_size(width, height);
            }
            XdgPositionerRequest::SetAnchorRect { x, y, width, height } => {
                if width <= 0 || height <= 0 {
                    return Err(format_err!(
                        "invalid_input error width={:?} height={:?}",
                        width,
                        height
                    ));
                }
                this.get_mut(client)?.set_anchor_rect(x, y, width, height);
            }
            XdgPositionerRequest::SetAnchor { anchor } => {
                this.get_mut(client)?.set_anchor(anchor);
            }
            XdgPositionerRequest::SetGravity { gravity } => {
                this.get_mut(client)?.set_gravity(gravity);
            }
            XdgPositionerRequest::SetConstraintAdjustment { .. } => {}
            XdgPositionerRequest::SetOffset { x, y } => {
                this.get_mut(client)?.set_offset(x, y);
            }
            XdgPositionerRequest::SetReactive { .. } => {}
            XdgPositionerRequest::SetParentSize { .. } => {}
            XdgPositionerRequest::SetParentConfigure { .. } => {}
        }
        Ok(())
    }
}

/// An `XdgSurface` is the common base to the different surfaces in the
/// `XdgShell` (ex: `XdgToplevel`, `XdgPopup`).
pub struct XdgSurface {
    /// A reference to the underlying `Surface` for this `XdgSurface`.
    surface_ref: ObjectRef<Surface>,
    /// A reference to the root `Surface` for this `XdgSurface`. The root surface
    /// is the surface that can receive keyboard focus.
    root_surface_ref: ObjectRef<Surface>,
    /// The sub-role assigned to this `XdgSurface`. This is needed because the
    /// `XdgSurface` is not a role itself, but a base for the concrete XDG
    /// surface roles.
    xdg_role: Option<XdgSurfaceRole>,
    /// The associated scenic view for this `XdgSurface`. This will be
    /// populated in response to requests to the public `ViewProvider` service,
    /// or by creating an internal child view.
    view: Option<XdgSurfaceViewPtr>,
}

impl XdgSurface {
    /// Creates a new `XdgSurface`.
    pub fn new(id: wl::ObjectId) -> Self {
        XdgSurface {
            surface_ref: id.into(),
            root_surface_ref: id.into(),
            xdg_role: None,
            view: None,
        }
    }

    /// Returns a reference to the underlying `Surface` for this `XdgSurface`.
    pub fn surface_ref(&self) -> ObjectRef<Surface> {
        self.surface_ref
    }

    /// Returns a reference to the root `Surface` for this `XdgSurface`.
    pub fn root_surface_ref(&self) -> ObjectRef<Surface> {
        self.root_surface_ref
    }

    /// Sets the concrete role for this `XdgSurface`.
    ///
    /// Similar to `Surface`, an `XdgSurface` isn't of much use until a role
    /// has been assigned.
    pub fn set_xdg_role(&mut self, xdg_role: XdgSurfaceRole) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurface::set_xdg_role");
        // The role is valid unless a different role has been assigned before.
        let valid_role = match &self.xdg_role {
            Some(XdgSurfaceRole::Popup(_)) => match xdg_role {
                XdgSurfaceRole::Popup(_) => true,
                _ => false,
            },
            Some(XdgSurfaceRole::Toplevel(_)) => match xdg_role {
                XdgSurfaceRole::Toplevel(_) => true,
                _ => false,
            },
            _ => true,
        };
        if valid_role {
            self.xdg_role = Some(xdg_role);
            Ok(())
        } else {
            Err(format_err!(
                "Attemping to re-assign xdg_surface role from {:?} to {:?}",
                self.xdg_role,
                xdg_role
            ))
        }
    }

    /// Sets the backing view for this `XdgSurface`.
    fn set_view(&mut self, view: XdgSurfaceViewPtr) {
        // We shut down the ViewProvider after creating the first view, so this
        // should never happen.
        assert!(self.view.is_none());
        self.view = Some(view);
    }

    /// Sets the root surface for this `XdgSurface`.
    fn set_root_surface(&mut self, root_surface_ref: ObjectRef<Surface>) {
        self.root_surface_ref = root_surface_ref;
    }

    /// Performs a surface configuration sequence.
    ///
    /// Each concrete `XdgSurface` role configuration sequence is concluded and
    /// committed by a xdg_surface::configure event.
    pub fn configure(this: ObjectRef<Self>, client: &mut Client) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurface::configure");
        if let Some(xdg_surface) = this.try_get(client) {
            match xdg_surface.xdg_role {
                Some(XdgSurfaceRole::Popup(popup)) => {
                    XdgPopup::configure(popup, client)?;
                }
                Some(XdgSurfaceRole::Toplevel(toplevel)) => {
                    XdgToplevel::configure(toplevel, client)?;
                }
                _ => {}
            }
            let serial = client.event_queue().next_serial();
            client.event_queue().post(this.id(), XdgSurfaceEvent::Configure { serial })?;
        }
        Ok(())
    }

    /// Handle a commit request to this `XdgSurface`.
    ///
    /// This will be triggered by a wl_surface::commit request to the backing
    /// wl_surface object for this xdg_surface, and simply delegates the request
    /// to the concrete surface.
    pub fn finalize_commit(this: ObjectRef<Self>, client: &mut Client) -> Result<bool, Error> {
        ftrace::duration!(c"wayland", c"XdgSurface::finalize_commit");
        if let Some(xdg_surface) = this.try_get(client) {
            match xdg_surface.xdg_role {
                Some(XdgSurfaceRole::Popup(_)) => Ok(true),
                Some(XdgSurfaceRole::Toplevel(toplevel)) => {
                    XdgToplevel::finalize_commit(toplevel, client)
                }
                _ => Ok(false),
            }
        } else {
            Ok(false)
        }
    }

    pub fn shutdown(&self, client: &Client) {
        ftrace::duration!(c"wayland", c"XdgSurface::shutdown");
        self.view.as_ref().map(|v| v.lock().shutdown());
        match self.xdg_role {
            Some(XdgSurfaceRole::Popup(popup)) => {
                if let Some(popup) = popup.try_get(client) {
                    popup.shutdown();
                }
            }
            Some(XdgSurfaceRole::Toplevel(toplevel)) => {
                if let Some(toplevel) = toplevel.try_get(client) {
                    toplevel.shutdown(client);
                }
            }
            _ => {}
        }
    }

    fn get_event_target(
        root_surface_ref: ObjectRef<Surface>,
        client: &Client,
    ) -> Option<ObjectRef<Self>> {
        for xdg_surface_ref in client.xdg_surfaces.iter().rev() {
            if let Some(xdg_surface) = xdg_surface_ref.try_get(client) {
                if xdg_surface.root_surface_ref == root_surface_ref {
                    return Some(*xdg_surface_ref);
                }
            }
        }
        None
    }

    /// Adds a child view to this `XdgSurface`.
    fn add_child_view(
        this: ObjectRef<Self>,
        client: &mut Client,
        viewport_creation_token: ViewportCreationToken,
    ) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurface::add_child_view");
        let xdg_surface = this.get(client)?;
        let surface = xdg_surface.surface_ref().get(client)?;
        let flatland = surface
            .flatland()
            .ok_or(format_err!("Unable to create a child view without a flatland instance."))?;
        let transform = flatland.borrow_mut().alloc_transform_id();
        let task_queue = client.task_queue();
        let (child_view_watcher, server_end) = create_proxy::<ChildViewWatcherMarker>()
            .expect("failed to create ChildViewWatcher endpoints");
        XdgSurface::spawn_child_view_listener(
            this,
            child_view_watcher,
            task_queue.clone(),
            transform.value,
        );
        if let Some(view) = this.get_mut(client)?.view.clone() {
            view.lock().add_child_view(transform.value, viewport_creation_token, server_end);
        }
        Ok(())
    }

    fn spawn_child_view(
        this: ObjectRef<Self>,
        client: &mut Client,
        flatland: FlatlandPtr,
        parent_ref: ObjectRef<Self>,
        local_offset: Option<(i32, i32)>,
        geometry: Rect,
    ) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurface::spawn_child_view");
        let creation_tokens =
            ViewCreationTokenPair::new().expect("failed to create ViewCreationTokenPair");
        let parent = parent_ref.get(client)?;
        let parent_view = parent.view.clone();
        let root_surface_ref = parent.root_surface_ref();
        Self::add_child_view(parent_ref, client, creation_tokens.viewport_creation_token)?;
        let xdg_surface = this.get(client)?;
        let surface_ref = xdg_surface.surface_ref();
        let task_queue = client.task_queue();
        let (parent_viewport_watcher, server_end) = create_proxy::<ParentViewportWatcherMarker>()
            .expect("failed to create ParentViewportWatcherProxy");
        flatland
            .borrow()
            .proxy()
            .create_view(creation_tokens.view_creation_token, server_end)
            .expect("fidl error");
        XdgSurface::spawn_parent_viewport_listener(
            this,
            parent_viewport_watcher,
            task_queue.clone(),
        );
        let view_ptr = XdgSurfaceView::new(
            flatland,
            task_queue.clone(),
            this,
            surface_ref,
            parent_view,
            local_offset,
            geometry,
        )?;
        XdgSurfaceView::finish_setup_scene(&view_ptr, client)?;
        let xdg_surface = this.get_mut(client)?;
        xdg_surface.set_view(view_ptr.clone());
        xdg_surface.set_root_surface(root_surface_ref);
        client.xdg_surfaces.push(this);
        Ok(())
    }

    fn spawn_flatland_listener(
        this: ObjectRef<Self>,
        client: &mut Client,
        stream: FlatlandEventStream,
    ) -> Result<(), Error> {
        let task_queue = client.task_queue();
        let surface_ref = this.get(client)?.surface_ref;
        fasync::Task::local(
            stream
                .try_for_each(move |event| {
                    match event {
                        FlatlandEvent::OnNextFrameBegin { values } => {
                            task_queue.post(move |client| {
                                let infos = values
                                    .future_presentation_infos
                                    .as_ref()
                                    .expect("no future presentation infos");
                                let info =
                                    infos.iter().next().expect("no future presentation info");
                                let time_in_ms =
                                    (info.presentation_time.expect("no presentation time")
                                        / 1_000_000) as u32;
                                if let Some(surface) = surface_ref.try_get_mut(client) {
                                    let callbacks = surface.take_on_next_frame_begin_callbacks();
                                    callbacks.iter().try_for_each(|callback| {
                                        Callback::done(*callback, client, time_in_ms)?;
                                        client.delete_id(callback.id())
                                    })?;
                                }
                                Surface::add_present_credits(
                                    surface_ref,
                                    client,
                                    values.additional_present_credits.unwrap_or(0),
                                );
                                Ok(())
                            });
                        }
                        FlatlandEvent::OnFramePresented { frame_presented_info: _ } => {}
                        FlatlandEvent::OnError { error } => {
                            println!("FlatlandEvent::OnError: {:?}", error);
                        }
                    };
                    future::ok(())
                })
                .unwrap_or_else(|e| eprintln!("error listening for Flatland Events: {:?}", e)),
        )
        .detach();
        Ok(())
    }

    fn spawn_parent_viewport_listener(
        this: ObjectRef<Self>,
        parent_viewport_watcher: ParentViewportWatcherProxy,
        task_queue: TaskQueue,
    ) {
        let mut layout_info_stream =
            HangingGetStream::new(parent_viewport_watcher, ParentViewportWatcherProxy::get_layout);

        fasync::Task::local(async move {
            while let Some(result) = layout_info_stream.next().await {
                match result {
                    Ok(layout_info) => {
                        if let Some(logical_size) = layout_info.logical_size.map(|size| SizeF {
                            width: size.width as f32,
                            height: size.height as f32,
                        }) {
                            task_queue.post(move |client| {
                                if let Some(view) = this.get(client)?.view.clone() {
                                    view.lock().handle_layout_changed(&logical_size);
                                }
                                Ok(())
                            });
                        }
                    }
                    Err(fidl::Error::ClientChannelClosed { .. }) => {
                        return;
                    }
                    Err(fidl_error) => {
                        println!("parent viewport GetLayout() error: {:?}", fidl_error);
                        return;
                    }
                }
            }
        })
        .detach();
    }

    fn spawn_touch_listener(
        this: ObjectRef<Self>,
        touch_source: TouchSourceProxy,
        task_queue: TaskQueue,
    ) {
        fasync::Task::local(async move {
            let mut responses: Vec<fidl_fuchsia_ui_pointer::TouchResponse> = Vec::new();
            loop {
                let result = touch_source.watch(&responses).await;
                match result {
                    Ok(returned_events) => {
                        responses = returned_events
                            .iter()
                            .map(|event| fidl_fuchsia_ui_pointer::TouchResponse {
                                response_type: event.pointer_sample.as_ref().and_then(|_| {
                                    Some(fidl_fuchsia_ui_pointer::TouchResponseType::Yes)
                                }),
                                ..Default::default()
                            })
                            .collect();
                        let events = returned_events.clone();
                        task_queue.post(move |client| {
                            if let Some(xdg_surface) = this.try_get(client) {
                                let root_surface_ref = xdg_surface.root_surface_ref;
                                for event in &events {
                                    if let Some(TouchPointerSample {
                                        interaction: Some(interaction),
                                        phase: Some(phase),
                                        position_in_viewport: Some(position_in_viewport),
                                        ..
                                    }) = event.pointer_sample.as_ref()
                                    {
                                        let x = position_in_viewport[0];
                                        let y = position_in_viewport[1];
                                        let xdg_surface_ref =
                                            XdgSurface::get_event_target(root_surface_ref, client)
                                                .unwrap_or(this);
                                        let target =
                                            XdgSurface::hit_test(xdg_surface_ref, x, y, client);
                                        if let Some((_, surface_ref, offset)) = target {
                                            if let Some(surface) = surface_ref.try_get(client) {
                                                let position = {
                                                    let geometry = surface.window_geometry();
                                                    [
                                                        x + geometry.x as f32 - offset.0 as f32,
                                                        y + geometry.y as f32 - offset.1 as f32,
                                                    ]
                                                };

                                                let timestamp = event.timestamp.expect("timestamp");
                                                client
                                                    .input_dispatcher
                                                    .handle_touch_event(
                                                        surface_ref,
                                                        timestamp,
                                                        interaction
                                                            .interaction_id
                                                            .try_into()
                                                            .unwrap(),
                                                        &position,
                                                        *phase,
                                                    )
                                                    .expect("handle_touch_event");
                                            }
                                        }
                                    }
                                }
                            }
                            Ok(())
                        });
                    }
                    Err(fidl::Error::ClientChannelClosed { .. }) => {
                        return;
                    }
                    Err(fidl_error) => {
                        println!("touch source Watch() error: {:?}", fidl_error);
                        return;
                    }
                }
            }
        })
        .detach();
    }

    fn spawn_mouse_listener(
        this: ObjectRef<Self>,
        mouse_source: MouseSourceProxy,
        task_queue: TaskQueue,
    ) {
        fasync::Task::local(async move {
            loop {
                let result = mouse_source.watch().await;
                match result {
                    Ok(returned_events) => {
                        let events = returned_events.clone();
                        task_queue.post(move |client| {
                            if let Some(xdg_surface) = this.try_get(client) {
                                let root_surface_ref = xdg_surface.root_surface_ref;
                                for event in &events {
                                    if let Some(MousePointerSample {
                                        device_id: _,
                                        position_in_viewport: Some(position_in_viewport),
                                        relative_motion,
                                        scroll_v,
                                        scroll_h,
                                        pressed_buttons,
                                        ..
                                    }) = event.pointer_sample.as_ref()
                                    {
                                        let x = position_in_viewport[0];
                                        let y = position_in_viewport[1];
                                        let xdg_surface_ref =
                                            XdgSurface::get_event_target(root_surface_ref, client)
                                                .unwrap_or(this);
                                        let target =
                                            XdgSurface::hit_test(xdg_surface_ref, x, y, client);
                                        if let Some((_, surface_ref, offset)) = target {
                                            if let Some(surface) = surface_ref.try_get(client) {
                                                let position = {
                                                    let geometry = surface.window_geometry();
                                                    [
                                                        x + geometry.x as f32 - offset.0 as f32,
                                                        y + geometry.y as f32 - offset.1 as f32,
                                                    ]
                                                };

                                                let timestamp = event.timestamp.expect("timestamp");
                                                client
                                                    .input_dispatcher
                                                    .handle_pointer_event(
                                                        surface_ref,
                                                        timestamp,
                                                        &position,
                                                        pressed_buttons,
                                                        relative_motion,
                                                        scroll_v,
                                                        scroll_h,
                                                    )
                                                    .expect("handle_mouse_event");
                                            }
                                        }
                                    }
                                }
                            }
                            Ok(())
                        });
                    }
                    Err(fidl::Error::ClientChannelClosed { .. }) => {
                        return;
                    }
                    Err(fidl_error) => {
                        println!("mouse source Watch() error: {:?}", fidl_error);
                        return;
                    }
                }
            }
        })
        .detach();
    }

    fn spawn_child_view_listener(
        this: ObjectRef<Self>,
        child_view_watcher: ChildViewWatcherProxy,
        task_queue: TaskQueue,
        id: u64,
    ) {
        let mut status_stream =
            HangingGetStream::new(child_view_watcher, ChildViewWatcherProxy::get_status);

        fasync::Task::local(async move {
            while let Some(result) = status_stream.next().await {
                match result {
                    Ok(_status) => {}
                    Err(fidl::Error::ClientChannelClosed { .. }) => {
                        let xdg_surface_ref = this;
                        task_queue.post(move |client| {
                            if let Some(xdg_surface) = xdg_surface_ref.try_get(client) {
                                if let Some(view) = xdg_surface.view.as_ref() {
                                    view.lock().handle_view_disconnected(id);
                                }
                            }
                            Ok(())
                        });
                        return;
                    }
                    Err(fidl_error) => {
                        println!("child view GetStatus() error: {:?}", fidl_error);
                        return;
                    }
                }
            }
        })
        .detach();
    }

    fn spawn_view_ref_focused_listener(
        this: ObjectRef<Self>,
        source_surface_ref: ObjectRef<Surface>,
        view_ref_focused: ViewRefFocusedProxy,
        task_queue: TaskQueue,
    ) {
        let mut focus_state_stream =
            HangingGetStream::new(view_ref_focused, ViewRefFocusedProxy::watch);

        fasync::Task::local(async move {
            while let Some(result) = focus_state_stream.next().await {
                match result {
                    Ok(focus_state) => {
                        task_queue.post(move |client| {
                            if let Some(xdg_surface) = this.try_get(client) {
                                let root_surface_ref = xdg_surface.root_surface_ref;
                                let xdg_surface_ref =
                                    XdgSurface::get_event_target(root_surface_ref, client)
                                        .unwrap_or(this);
                                let surface_ref = xdg_surface_ref.get(client)?.surface_ref;
                                if surface_ref.try_get(client).is_some() {
                                    let had_focus = client.input_dispatcher.has_focus(surface_ref);
                                    client.input_dispatcher.handle_keyboard_focus(
                                        source_surface_ref,
                                        surface_ref,
                                        focus_state.focused.unwrap(),
                                    )?;
                                    let has_focus = client.input_dispatcher.has_focus(surface_ref);
                                    if had_focus != has_focus {
                                        // If our focus has changed we need to reconfigure so that the
                                        // Activated flag can be set or cleared.
                                        Self::configure(xdg_surface_ref, client)?;
                                    }
                                }
                            }
                            Ok(())
                        });
                    }
                    Err(fidl::Error::ClientChannelClosed { .. }) => {
                        return;
                    }
                    Err(fidl_error) => {
                        println!("ViewRefFocused Watch() error: {:?}", fidl_error);
                        return;
                    }
                }
            }
        })
        .detach();
    }

    fn hit_test(
        this: ObjectRef<Self>,
        location_x: f32,
        location_y: f32,
        client: &Client,
    ) -> Option<(ObjectRef<Self>, ObjectRef<Surface>, (i32, i32))> {
        let mut maybe_xdg_surface_ref = Some(this);
        while let Some(xdg_surface_ref) = maybe_xdg_surface_ref.take() {
            if let Some(xdg_surface) = xdg_surface_ref.try_get(client) {
                if let Some((parent_view, view_offset)) = xdg_surface.view.as_ref().map(|v| {
                    let view = v.lock();
                    (view.parent(), view.absolute_offset())
                }) {
                    let surface_ref = xdg_surface.surface_ref;
                    if let Some(surface) = surface_ref.try_get(client) {
                        let x = location_x - view_offset.0 as f32;
                        let y = location_y - view_offset.1 as f32;
                        if let Some((surface_ref, offset)) = surface.hit_test(x, y, client) {
                            let offset_x = offset.0 + view_offset.0;
                            let offset_y = offset.1 + view_offset.1;
                            return Some((xdg_surface_ref, surface_ref, (offset_x, offset_y)));
                        }
                    }
                    maybe_xdg_surface_ref = parent_view.as_ref().map(|v| v.lock().xdg_surface());
                }
            }
        }
        None
    }
}

impl RequestReceiver<xdg_shell::XdgSurface> for XdgSurface {
    fn receive(
        this: ObjectRef<Self>,
        request: XdgSurfaceRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            XdgSurfaceRequest::Destroy => {
                client.delete_id(this.id())?;
            }
            XdgSurfaceRequest::GetToplevel { id } => {
                let proxy =
                    connect_to_protocol::<FlatlandMarker>().expect("error connecting to Flatland");
                let flatland = Flatland::new(proxy);
                let toplevel = XdgToplevel::new(this, client, flatland.clone())?;
                let toplevel_ref = id.implement(client, toplevel)?;
                this.get_mut(client)?.set_xdg_role(XdgSurfaceRole::Toplevel(toplevel_ref))?;
                XdgSurface::spawn_flatland_listener(
                    this,
                    client,
                    flatland.borrow().proxy().take_event_stream(),
                )?;
            }
            XdgSurfaceRequest::GetPopup { id, parent, positioner } => {
                let proxy =
                    connect_to_protocol::<FlatlandMarker>().expect("error connecting to Flatland");
                let flatland = Flatland::new(proxy);
                let popup = XdgPopup::new(this, client, flatland.clone(), positioner.into())?;
                let geometry = popup.geometry();
                let popup_ref = id.implement(client, popup)?;
                let xdg_surface = this.get_mut(client)?;
                xdg_surface.set_xdg_role(XdgSurfaceRole::Popup(popup_ref))?;
                XdgSurface::spawn_child_view(
                    this,
                    client,
                    flatland.clone(),
                    parent.into(),
                    Some((geometry.x, geometry.y)),
                    geometry,
                )?;
                XdgSurface::spawn_flatland_listener(
                    this,
                    client,
                    flatland.borrow().proxy().take_event_stream(),
                )?;
            }
            XdgSurfaceRequest::SetWindowGeometry { x, y, width, height } => {
                let surface_ref = this.get(client)?.surface_ref;
                surface_ref.get_mut(client)?.enqueue(SurfaceCommand::SetWindowGeometry(Rect {
                    x,
                    y,
                    width,
                    height,
                }));
            }
            XdgSurfaceRequest::AckConfigure { .. } => {}
        }
        Ok(())
    }
}

/// Models the different roles that can be assigned to an `XdgSurface`.
#[derive(Copy, Clone, Debug)]
pub enum XdgSurfaceRole {
    Popup(ObjectRef<XdgPopup>),
    Toplevel(ObjectRef<XdgToplevel>),
}

pub struct XdgPopup {
    /// A reference to the underlying wl_surface for this toplevel.
    surface_ref: ObjectRef<Surface>,
    /// A reference to the underlying xdg_surface for this toplevel.
    xdg_surface_ref: ObjectRef<XdgSurface>,
    /// This will be used to support reactive changes to positioner.
    #[allow(dead_code)]
    positioner_ref: ObjectRef<XdgPositioner>,
    /// Popup geometry.
    geometry: Rect,
}

impl XdgPopup {
    /// Performs a configure sequence for the XdgPopup object referenced by
    /// `this`.
    pub fn configure(this: ObjectRef<Self>, client: &mut Client) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgPopup::configure");
        let geometry = this.get(client)?.geometry;
        client.event_queue().post(
            this.id(),
            XdgPopupEvent::Configure {
                x: geometry.x,
                y: geometry.y,
                width: geometry.width,
                height: geometry.height,
            },
        )?;
        Ok(())
    }

    fn geometry(&self) -> Rect {
        self.geometry
    }

    /// Creates a new `XdgPopup` surface.
    pub fn new(
        xdg_surface_ref: ObjectRef<XdgSurface>,
        client: &mut Client,
        flatland: FlatlandPtr,
        positioner_ref: ObjectRef<XdgPositioner>,
    ) -> Result<Self, Error> {
        let geometry = positioner_ref.get(client)?.get_geometry()?;
        let surface_ref = xdg_surface_ref.get(client)?.surface_ref();
        surface_ref.get_mut(client)?.set_flatland(flatland)?;
        Ok(XdgPopup { surface_ref, xdg_surface_ref, positioner_ref, geometry })
    }

    pub fn shutdown(&self) {}
}

impl RequestReceiver<xdg_shell::XdgPopup> for XdgPopup {
    fn receive(
        this: ObjectRef<Self>,
        request: XdgPopupRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            XdgPopupRequest::Destroy => {
                let (surface_ref, xdg_surface_ref) = {
                    let popup = this.get(client)?;
                    (popup.surface_ref, popup.xdg_surface_ref)
                };
                xdg_surface_ref.get(client)?.shutdown(client);
                // We need to present here to commit the removal of our
                // popup. This will inform our parent that our view has
                // been destroyed.
                Surface::present_internal(surface_ref, client);

                surface_ref.get_mut(client)?.clear_flatland();
                client.delete_id(this.id())?;
            }
            XdgPopupRequest::Grab { .. } => {}
            XdgPopupRequest::Reposition { .. } => {}
        }
        Ok(())
    }
}

/// `XdgToplevel` is a surface that should appear as a top-level window.
///
/// `XdgToplevel` will be implemented as a scenic `View`/`ViewProvider` that
/// hosts the surface contents. The actual presentation of the `View` will be
/// deferred to whatever user shell is used.
pub struct XdgToplevel {
    /// A reference to the underlying wl_surface for this toplevel.
    surface_ref: ObjectRef<Surface>,
    /// A reference to the underlying xdg_surface for this toplevel.
    xdg_surface_ref: ObjectRef<XdgSurface>,
    /// This handle can be used to terminate the |ViewProvider| FIDL service
    /// associated with this toplevel.
    view_provider_controller: Option<ViewProviderControlHandle>,
    /// This proxy can be used to dismiss the |View| associated with this
    /// toplevel.
    view_controller_proxy: Option<ViewControllerProxy>,
    /// Identifier for the view.
    view_id: u32,
    /// This will be set to false after we received an initial commit.
    waiting_for_initial_commit: bool,
    /// A reference to an optional parent `XdgToplevel`.
    parent_ref: Option<ObjectRef<XdgToplevel>>,
    /// Optional title for `XdgToplevel`.
    title: Option<String>,
    /// Maximum size for `XdgToplevel`. A value of zero means no maximum
    /// size in the given dimension.
    max_size: Size,
}

impl XdgToplevel {
    /// Performs a configure sequence for the XdgToplevel object referenced by
    /// `this`.
    pub fn configure(this: ObjectRef<Self>, client: &mut Client) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgToplevel::configure");
        let (width, height, maximized, surface_ref) = {
            let (view, max_size, surface_ref, maybe_parent_ref) = {
                let toplevel = this.get(client)?;
                let max_size = toplevel.max_size;
                let xdg_surface_ref = toplevel.xdg_surface_ref;
                let xdg_surface = xdg_surface_ref.get(client)?;
                (xdg_surface.view.clone(), max_size, toplevel.surface_ref, toplevel.parent_ref)
            };
            // Let the client determine the size if it has a parent.
            let (width, height, maximized) = if maybe_parent_ref.is_some() {
                surface_ref
                    .try_get(client)
                    .map(|surface| {
                        let geometry = surface.window_geometry();
                        (geometry.width, geometry.height, false)
                    })
                    .unwrap_or((0, 0, false))
            } else {
                let display_info = client.display().display_info();
                let physical_size = view
                    .as_ref()
                    .map(|view| view.lock().physical_size())
                    .filter(|size| size.width != 0 && size.height != 0)
                    .unwrap_or(Size {
                        width: display_info.width_in_px as i32,
                        height: display_info.height_in_px as i32,
                    });
                (
                    if max_size.width > 0 {
                        physical_size.width.min(max_size.width)
                    } else {
                        physical_size.width
                    },
                    if max_size.height > 0 {
                        physical_size.height.min(max_size.height)
                    } else {
                        physical_size.height
                    },
                    true,
                )
            };
            (width, height, maximized, surface_ref)
        };

        let mut states = wl::Array::new();
        // If the surface doesn't have a parent, set the maximized state
        // to hint to the client it really should obey the geometry we're
        // asking for. From the xdg_shell spec:
        //
        // maximized:
        //    The surface is maximized. The window geometry specified in the
        //    configure event must be obeyed by the client.
        if maximized {
            states.push(xdg_toplevel::State::Maximized)?;
        }
        if client.input_dispatcher.has_focus(surface_ref) {
            // If the window has focus, we set the activated state. This is
            // just a hint to pass along to the client so it can draw itself
            // differently with and without focus.
            states.push(xdg_toplevel::State::Activated)?;
        }
        client
            .event_queue()
            .post(this.id(), XdgToplevelEvent::Configure { width, height, states })?;

        Ok(())
    }

    /// Sets the parent for this `XdgToplevel`.
    pub fn set_parent(&mut self, parent: Option<ObjectRef<XdgToplevel>>) {
        self.parent_ref = parent;
    }

    /// Sets the title for this `XdgToplevel`.
    fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    /// Sets the maximum size for this `XdgToplevel`.
    ///
    /// Returns true iff the new size is different from the previous value.
    fn set_max_size(&mut self, max_size: Size) -> bool {
        if max_size != self.max_size {
            self.max_size = max_size;
            return true;
        }
        false
    }

    fn close(this: ObjectRef<Self>, client: &mut Client) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgToplevel::close");
        client.event_queue().post(this.id(), XdgToplevelEvent::Close)
    }

    /// Creates a new `XdgToplevel` surface.
    pub fn new(
        xdg_surface_ref: ObjectRef<XdgSurface>,
        client: &mut Client,
        flatland: FlatlandPtr,
    ) -> Result<Self, Error> {
        let surface_ref = xdg_surface_ref.get(client)?.surface_ref();
        surface_ref.get_mut(client)?.set_flatland(flatland)?;
        Ok(XdgToplevel {
            surface_ref,
            xdg_surface_ref,
            view_provider_controller: None,
            view_controller_proxy: None,
            view_id: NEXT_VIEW_ID.fetch_add(1, Ordering::SeqCst) as u32,
            waiting_for_initial_commit: true,
            parent_ref: None,
            title: None,
            max_size: Size { width: 0, height: 0 },
        })
    }

    fn spawn_view_provider(
        this: ObjectRef<Self>,
        client: &mut Client,
        flatland: FlatlandPtr,
    ) -> Result<ViewProviderControlHandle, Error> {
        ftrace::duration!(c"wayland", c"XdgToplevel::spawn_view_provider");
        // Create a new ViewProvider service, hand off the client endpoint to
        // our ViewSink to be presented.
        let (client_end, server_end) = create_endpoints::<ViewProviderMarker>();
        let view_id = this.get(client)?.view_id;
        client.display().new_view_provider(client_end, view_id);

        // Spawn the view provider server for this surface.
        let surface_ref = this.get(client)?.surface_ref;
        let xdg_surface_ref = this.get(client)?.xdg_surface_ref;
        let task_queue = client.task_queue();
        let mut stream = server_end.into_stream().unwrap();
        let control_handle = stream.control_handle();
        fasync::Task::local(
            async move {
                // This only supports a single view, so this is an "if" instead of a "while".  For
                // example, we move `flatland` into the XdgSurfaceView we create below, so it
                // wouldn't be available for a subsequent iteration of the loop.  This would need to
                // be restructured to handle subsequent requests.
                if let Some(request) = stream.try_next().await.unwrap() {
                    match request {
                        ViewProviderRequest::CreateView2 { args, .. } => {
                            let view_creation_token = args.view_creation_token.unwrap();
                            let viewref_pair = ViewRefPair::new()?;
                            let view_identity = ViewIdentityOnCreation::from(viewref_pair);
                            let (parent_viewport_watcher, parent_viewport_watcher_request) =
                                create_proxy::<ParentViewportWatcherMarker>()
                                    .expect("failed to create ParentViewportWatcherProxy");
                            let (view_ref_focused, view_ref_focused_request) =
                                create_proxy::<ViewRefFocusedMarker>()
                                    .expect("failed to create ViewRefFocusedProxy");
                            let (touch_source, touch_source_request) =
                                create_proxy::<TouchSourceMarker>()
                                    .expect("failed to create TouchSourceProxy");
                            let (mouse_source, mouse_source_request) =
                                create_proxy::<MouseSourceMarker>()
                                    .expect("failed to create MouseSourceProxy");
                            let view_bound_protocols = ViewBoundProtocols {
                                view_ref_focused: Some(view_ref_focused_request),
                                touch_source: Some(touch_source_request),
                                mouse_source: Some(mouse_source_request),
                                ..Default::default()
                            };
                            flatland
                                .borrow()
                                .proxy()
                                .create_view2(
                                    view_creation_token,
                                    view_identity,
                                    view_bound_protocols,
                                    parent_viewport_watcher_request,
                                )
                                .expect("fidl error");
                            XdgSurface::spawn_view_ref_focused_listener(
                                xdg_surface_ref,
                                surface_ref,
                                view_ref_focused,
                                task_queue.clone(),
                            );
                            XdgSurface::spawn_parent_viewport_listener(
                                xdg_surface_ref,
                                parent_viewport_watcher,
                                task_queue.clone(),
                            );
                            XdgSurface::spawn_touch_listener(
                                xdg_surface_ref,
                                touch_source,
                                task_queue.clone(),
                            );
                            XdgSurface::spawn_mouse_listener(
                                xdg_surface_ref,
                                mouse_source,
                                task_queue.clone(),
                            );
                            let view_ptr = XdgSurfaceView::new(
                                flatland,
                                task_queue.clone(),
                                xdg_surface_ref,
                                surface_ref,
                                None,
                                Some((0, 0)),
                                Rect { x: 0, y: 0, width: 0, height: 0 },
                            )?;
                            task_queue.post(move |client| {
                                XdgSurfaceView::finish_setup_scene(&view_ptr, client)?;
                                xdg_surface_ref.get_mut(client)?.set_view(view_ptr.clone());
                                Ok(())
                            });
                        }
                        _ => {
                            panic!("unsupported view provider request: {:?}", request)
                        }
                    }
                }

                // See previous comment about only supporting a single view.  Here, we ensure that
                // our client never asks us to create a second view.
                if let Some(request) = stream.try_next().await.unwrap() {
                    panic!("unsupported view provider request: {:?}", request)
                }

                task_queue.post(|_client| {
                    // Returning an error causes the client connection to be
                    // closed (and that typically closes the application).
                    Err(format_err!("View provider channel closed "))
                });
                Ok(())
            }
            .unwrap_or_else(|e: Error| println!("{:?}", e)),
        )
        .detach();
        Ok(control_handle)
    }

    fn spawn_view(
        this: ObjectRef<Self>,
        client: &mut Client,
        flatland: FlatlandPtr,
    ) -> Result<ViewControllerProxy, Error> {
        ftrace::duration!(c"wayland", c"XdgToplevel::spawn_view");
        let (proxy, server_end) = create_proxy::<ViewControllerMarker>()?;
        let stream = proxy.take_event_stream();
        let creation_tokens = ViewCreationTokenPair::new().expect("failed to create token pair");
        let viewref_pair = ViewRefPair::new()?;
        let view_ref_dup = fuchsia_scenic::duplicate_view_ref(&viewref_pair.view_ref)?;
        let view_identity = ViewIdentityOnCreation::from(viewref_pair);
        let toplevel = this.get(client)?;
        let annotations = toplevel.title.as_ref().map(|title| {
            let title_key = AnnotationKey {
                namespace: TITLE_ANNOTATION_NS.to_string(),
                value: TITLE_ANNOTATION_VALUE.to_string(),
            };
            vec![Annotation { key: title_key, value: AnnotationValue::Text(title.clone()) }]
        });
        let view_spec = ViewSpec {
            viewport_creation_token: Some(creation_tokens.viewport_creation_token),
            view_ref: Some(view_ref_dup),
            annotations,
            ..Default::default()
        };
        let (parent_viewport_watcher, parent_viewport_watcher_request) =
            create_proxy::<ParentViewportWatcherMarker>()
                .expect("failed to create ParentViewportWatcherProxy");
        let (view_ref_focused, view_ref_focused_request) =
            create_proxy::<ViewRefFocusedMarker>().expect("failed to create ViewRefFocusedProxy");
        let (touch_source, touch_source_request) =
            create_proxy::<TouchSourceMarker>().expect("failed to create TouchSourceProxy");
        let (mouse_source, mouse_source_request) =
            create_proxy::<MouseSourceMarker>().expect("failed to create MouseSourceProxy");
        let view_bound_protocols = ViewBoundProtocols {
            view_ref_focused: Some(view_ref_focused_request),
            touch_source: Some(touch_source_request),
            mouse_source: Some(mouse_source_request),
            ..Default::default()
        };
        flatland
            .borrow()
            .proxy()
            .create_view2(
                creation_tokens.view_creation_token,
                view_identity,
                view_bound_protocols,
                parent_viewport_watcher_request,
            )
            .expect("fidl error");
        let xdg_surface_ref = toplevel.xdg_surface_ref;
        let surface_ref = toplevel.surface_ref;
        let max_size = toplevel.max_size;
        let task_queue = client.task_queue();
        XdgSurface::spawn_view_ref_focused_listener(
            xdg_surface_ref,
            surface_ref,
            view_ref_focused,
            task_queue.clone(),
        );
        XdgSurface::spawn_parent_viewport_listener(
            xdg_surface_ref,
            parent_viewport_watcher,
            task_queue.clone(),
        );
        XdgSurface::spawn_touch_listener(xdg_surface_ref, touch_source, task_queue.clone());
        XdgSurface::spawn_mouse_listener(xdg_surface_ref, mouse_source, task_queue.clone());
        let view_ptr = XdgSurfaceView::new(
            flatland,
            task_queue.clone(),
            xdg_surface_ref,
            surface_ref,
            None,
            Some((0, 0)),
            Rect { x: 0, y: 0, width: max_size.width, height: max_size.height },
        )?;
        XdgSurfaceView::finish_setup_scene(&view_ptr, client)?;
        xdg_surface_ref.get_mut(client)?.set_view(view_ptr.clone());
        let graphical_presenter = client.display().graphical_presenter().clone();
        fasync::Task::local(
            async move {
                graphical_presenter
                    .present_view(view_spec, None, Some(server_end))
                    .await
                    .expect("failed to present view")
                    .unwrap_or_else(|e| println!("{:?}", e));

                // Wait for stream to close.
                let _ = stream.collect::<Vec<_>>().await;
                task_queue.post(move |client| {
                    XdgToplevel::close(this, client)?;
                    Ok(())
                });
                Ok(())
            }
            .unwrap_or_else(|e: Error| println!("{:?}", e)),
        )
        .detach();
        Ok(proxy)
    }

    pub fn finalize_commit(this: ObjectRef<Self>, client: &mut Client) -> Result<bool, Error> {
        ftrace::duration!(c"wayland", c"XdgToplevel::finalize_commit");
        let top_level = this.get(client)?;
        // Initial commit requires that we spawn a view and send a configure event.
        if top_level.waiting_for_initial_commit {
            let xdg_surface_ref = top_level.xdg_surface_ref;
            let xdg_surface = xdg_surface_ref.get(client)?;
            let surface_ref = xdg_surface.surface_ref();
            let surface = surface_ref.get(client)?;
            let flatland = surface
                .flatland()
                .ok_or(format_err!("Unable to spawn view without a flatland instance"))?;

            // Spawn a child view if `XdgToplevel` has a parent or there's an existing
            // `XdgSurface` that can be used as parent.
            let maybe_parent_ref = if let Some(parent_ref) = top_level.parent_ref {
                let parent = parent_ref.get(client)?;
                Some(parent.xdg_surface_ref)
            } else {
                None
            };

            let (maybe_view_provider_control_handle, maybe_view_controller_proxy) = {
                if let Some(parent_ref) = maybe_parent_ref {
                    let offset = surface.offset();
                    let geometry = surface.window_geometry();
                    XdgSurface::spawn_child_view(
                        xdg_surface_ref,
                        client,
                        flatland.clone(),
                        parent_ref,
                        offset,
                        geometry,
                    )?;
                    (None, None)
                } else if client.take_view_provider_request() {
                    let control_handle =
                        XdgToplevel::spawn_view_provider(this, client, flatland.clone())?;
                    (Some(control_handle), None)
                } else {
                    let view_controller_proxy =
                        XdgToplevel::spawn_view(this, client, flatland.clone())?;
                    (None, Some(view_controller_proxy))
                }
            };

            // Initial commit requires that we send a configure event.
            let top_level = this.get_mut(client)?;
            top_level.waiting_for_initial_commit = false;
            top_level.view_provider_controller = maybe_view_provider_control_handle;
            top_level.view_controller_proxy = maybe_view_controller_proxy;
            // Maybe move keyboard focus to this XDG surface.
            if let Some(parent_ref) = maybe_parent_ref {
                let root_surface_ref = parent_ref.get(client)?.root_surface_ref();
                client
                    .input_dispatcher
                    .maybe_update_keyboard_focus(root_surface_ref, surface_ref)?;
            }
            XdgSurface::configure(xdg_surface_ref, client)?;
            client.xdg_surfaces.push(xdg_surface_ref);
        } else {
            let xdg_surface_ref = top_level.xdg_surface_ref;
            let xdg_surface = xdg_surface_ref.get(client)?;
            let surface = xdg_surface.surface_ref().get(client)?;
            let geometry = surface.window_geometry();
            let local_offset = surface.offset();
            if let Some(view) = xdg_surface.view.clone() {
                view.lock().set_geometry_and_local_offset(&geometry, &local_offset);
            }
        }
        Ok(true)
    }

    pub fn shutdown(&self, client: &Client) {
        if let Some(view_provider_controller) = self.view_provider_controller.as_ref() {
            view_provider_controller.shutdown();
            client.display().delete_view_provider(self.view_id);
        }
        if let Some(view_controller_proxy) = self.view_controller_proxy.as_ref() {
            view_controller_proxy.dismiss().unwrap_or_else(|e| println!("{:?}", e));
        }
    }
}

impl RequestReceiver<xdg_shell::XdgToplevel> for XdgToplevel {
    fn receive(
        this: ObjectRef<Self>,
        request: XdgToplevelRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            XdgToplevelRequest::Destroy => {
                let (surface_ref, xdg_surface_ref) = {
                    let toplevel = this.get(client)?;
                    (toplevel.surface_ref, toplevel.xdg_surface_ref)
                };
                client.xdg_surfaces.retain(|&x| x != xdg_surface_ref);
                let xdg_surface = xdg_surface_ref.get(client)?;
                xdg_surface.shutdown(client);
                if client.input_dispatcher.has_focus(surface_ref) {
                    // Move keyboard focus to new event target.
                    let source_surface_ref = xdg_surface.root_surface_ref();
                    let maybe_target = XdgSurface::get_event_target(source_surface_ref, client);
                    if let Some(target_xdg_surface_ref) = maybe_target {
                        let target_surface_ref = target_xdg_surface_ref.get(client)?.surface_ref;
                        client
                            .input_dispatcher
                            .maybe_update_keyboard_focus(source_surface_ref, target_surface_ref)?;
                    }
                }
                // We need to present here to commit the removal of our
                // toplevel. This will inform our parent that our view has
                // been destroyed.
                Surface::present_internal(surface_ref, client);

                surface_ref.get_mut(client)?.clear_flatland();
                client.delete_id(this.id())?;
            }
            XdgToplevelRequest::SetParent { parent } => {
                let toplevel = this.get_mut(client)?;
                let maybe_parent = if parent != 0 { Some(parent.into()) } else { None };
                toplevel.set_parent(maybe_parent);
            }
            XdgToplevelRequest::SetTitle { title } => {
                let toplevel = this.get_mut(client)?;
                toplevel.set_title(Some(title));
            }
            XdgToplevelRequest::SetAppId { .. } => {}
            XdgToplevelRequest::ShowWindowMenu { .. } => {}
            XdgToplevelRequest::Move { .. } => {}
            XdgToplevelRequest::Resize { .. } => {}
            XdgToplevelRequest::SetMaxSize { width, height } => {
                let toplevel = this.get_mut(client)?;
                if toplevel.set_max_size(Size { width, height })
                    && !toplevel.waiting_for_initial_commit
                {
                    XdgSurface::configure(toplevel.xdg_surface_ref, client)?;
                }
            }
            XdgToplevelRequest::SetMinSize { .. } => {}
            XdgToplevelRequest::SetMaximized => {}
            XdgToplevelRequest::UnsetMaximized => {}
            XdgToplevelRequest::SetFullscreen { .. } => {}
            XdgToplevelRequest::UnsetFullscreen => {}
            XdgToplevelRequest::SetMinimized => {}
        }
        Ok(())
    }
}

/// A scenic view implementation to back an |XdgSurface| resource.
///
/// An `XdgSurfaceView` will be created by the `ViewProvider` for an
/// `XdgSurface`.
struct XdgSurfaceView {
    flatland: FlatlandPtr,
    root_transform: Option<TransformId>,
    container_transform: TransformId,
    logical_size: SizeF,
    local_offset: Option<(i32, i32)>,
    absolute_offset: (i32, i32),
    task_queue: TaskQueue,
    xdg_surface: ObjectRef<XdgSurface>,
    surface: ObjectRef<Surface>,
    geometry: Rect,
    parent: Option<XdgSurfaceViewPtr>,
    children: BTreeSet<u64>,
}

type XdgSurfaceViewPtr = Arc<Mutex<XdgSurfaceView>>;

impl XdgSurfaceView {
    fn present_internal(&mut self) {
        let surface_ref = self.surface;
        self.task_queue.post(move |client| Ok(Surface::present_internal(surface_ref, client)));
    }

    fn update_and_present(&mut self) {
        self.update();
        self.present_internal();
    }

    fn reconfigure(&self) {
        // If we have both a size and a pixel scale, we're ready to send the
        // configure event to the client. We need both because we send expose
        // physical pixels to the client.
        if self.logical_size.width != 0.0 && self.logical_size.height != 0.0 {
            // Post the xdg_toplevel::configure event to inform the client about
            // the change.
            let xdg_surface = self.xdg_surface;
            self.task_queue.post(move |client| XdgSurface::configure(xdg_surface, client))
        }
    }

    fn compute_absolute_offset(
        parent: &Option<XdgSurfaceViewPtr>,
        physical_size: &Size,
        local_offset: &Option<(i32, i32)>,
        geometry: &Rect,
    ) -> (i32, i32) {
        // Use local offset if we have a parent view.
        parent.as_ref().map_or_else(
            ||
            // Center in available space if geometry is non-zero.
            (
                if geometry.width != 0 {
                    (physical_size.width as i32 - geometry.width) / 2
                } else {
                    0
                },
                if geometry.height != 0 {
                    (physical_size.height as i32 - geometry.height) / 2
                } else {
                    0
                }
            ),
            |parent| {
                // Center in available space by default and relative to parent if
                // local offset is set.
                local_offset.map_or_else(
                    || {
                        if physical_size.width != 0 && physical_size.height != 0 {
                            (
                                (physical_size.width as i32 - geometry.width) / 2,
                                (physical_size.height as i32 - geometry.height) / 2,
                            )
                        } else {
                            (0, 0)
                        }
                    },
                    |(x, y)| {
                        let parent_offset = parent.lock().absolute_offset();
                        (parent_offset.0 + x, parent_offset.1 + y)
                    },
                )
            },
        )
    }

    fn update_absolute_offset(&mut self) {
        self.absolute_offset = Self::compute_absolute_offset(
            &self.parent,
            &self.physical_size(),
            &self.local_offset,
            &self.geometry,
        );
    }

    fn absolute_offset(&self) -> (i32, i32) {
        self.absolute_offset
    }

    fn parent(&self) -> Option<XdgSurfaceViewPtr> {
        self.parent.clone()
    }

    fn xdg_surface(&self) -> ObjectRef<XdgSurface> {
        self.xdg_surface
    }
}

impl XdgSurfaceView {
    pub fn new(
        flatland: FlatlandPtr,
        task_queue: TaskQueue,
        xdg_surface: ObjectRef<XdgSurface>,
        surface: ObjectRef<Surface>,
        parent: Option<XdgSurfaceViewPtr>,
        local_offset: Option<(i32, i32)>,
        geometry: Rect,
    ) -> Result<XdgSurfaceViewPtr, Error> {
        // Get initial size from parent if available.
        let logical_size = parent
            .as_ref()
            .map_or(SizeF { width: 0.0, height: 0.0 }, |parent| parent.lock().logical_size);
        let physical_size = Self::physical_size_internal(&logical_size);
        let absolute_offset =
            Self::compute_absolute_offset(&parent, &physical_size, &local_offset, &geometry);
        let root_transform = flatland.borrow_mut().alloc_transform_id();
        let container_transform = flatland.borrow_mut().alloc_transform_id();
        flatland.borrow().proxy().create_transform(&root_transform).expect("fidl error");
        flatland.borrow().proxy().create_transform(&container_transform).expect("fidl error");
        let view_controller = XdgSurfaceView {
            flatland,
            root_transform: Some(root_transform),
            container_transform,
            logical_size,
            local_offset,
            absolute_offset,
            task_queue,
            xdg_surface,
            surface,
            geometry,
            parent,
            children: BTreeSet::new(),
        };
        let view_controller = Arc::new(Mutex::new(view_controller));
        Ok(view_controller)
    }

    pub fn finish_setup_scene(
        view_controller: &XdgSurfaceViewPtr,
        client: &mut Client,
    ) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::finish_setup_scene");
        let mut vc = view_controller.lock();
        vc.setup_scene();
        vc.attach(vc.surface, client)?;

        // Perform an update if we have an initial size.
        if vc.logical_size.width != 0.0 && vc.logical_size.height != 0.0 {
            vc.update();
            vc.reconfigure();
        }
        vc.present_internal();
        Ok(())
    }

    pub fn shutdown(&mut self) {
        self.root_transform.take().map(|_| {
            self.flatland.borrow().proxy().release_view().expect("fidl error");
        });
    }

    fn physical_size_internal(logical_size: &SizeF) -> Size {
        Size {
            width: logical_size.width.round() as i32,
            height: logical_size.height.round() as i32,
        }
    }

    pub fn physical_size(&self) -> Size {
        Self::physical_size_internal(&self.logical_size)
    }

    fn attach(&self, surface: ObjectRef<Surface>, client: &Client) -> Result<(), Error> {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::attach");
        let surface = surface.get(client)?;
        let surface_transform = surface.transform().expect("surface is missing a transform");
        self.flatland
            .borrow()
            .proxy()
            .add_child(&self.container_transform, &surface_transform)
            .expect("fidl error");
        Ok(())
    }

    fn setup_scene(&self) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::setup_scene");
        self.root_transform.as_ref().map(|root_transform| {
            self.flatland.borrow().proxy().set_root_transform(&root_transform).expect("fidl error");
            // TODO(https://fxbug.dev/42172143): Add background color if there's no parent.
            self.flatland
                .borrow()
                .proxy()
                .add_child(&root_transform, &self.container_transform)
                .expect("fidl error");
        });
    }

    fn update(&mut self) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::update");
        let translation = Vec_ { x: self.absolute_offset.0, y: self.absolute_offset.1 };
        self.flatland
            .borrow()
            .proxy()
            .set_translation(&self.container_transform, &translation)
            .expect("fidl error");
    }

    pub fn handle_layout_changed(&mut self, logical_size: &SizeF) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::handle_layout_changed");
        if *logical_size != self.logical_size {
            self.logical_size = *logical_size;
            for id in &self.children {
                self.set_viewport_properties(*id);
            }
            self.update_absolute_offset();
            self.update_and_present();
            self.reconfigure();
        }
    }

    pub fn set_geometry_and_local_offset(
        &mut self,
        geometry: &Rect,
        local_offset: &Option<(i32, i32)>,
    ) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::set_geometry_and_local_offset");
        self.geometry = *geometry;
        self.local_offset = *local_offset;
        let absolute_offset = Self::compute_absolute_offset(
            &self.parent,
            &self.physical_size(),
            &self.local_offset,
            &self.geometry,
        );
        if absolute_offset != self.absolute_offset {
            self.absolute_offset = absolute_offset;
            self.update_and_present();
        }
    }

    pub fn add_child_view(
        &mut self,
        id: u64,
        viewport_creation_token: ViewportCreationToken,
        server_end: ServerEnd<ChildViewWatcherMarker>,
    ) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::add_child_view");
        let viewport_properties = ViewportProperties {
            logical_size: Some(SizeU {
                width: self.logical_size.width.round() as u32,
                height: self.logical_size.height.round() as u32,
            }),
            ..Default::default()
        };
        let child_transform = TransformId { value: id.into() };
        let link = ContentId { value: id.into() };
        self.flatland.borrow().proxy().create_transform(&child_transform).expect("fidl error");
        self.flatland
            .borrow()
            .proxy()
            .create_viewport(&link, viewport_creation_token, &viewport_properties, server_end)
            .expect("fidl error");
        self.flatland.borrow().proxy().set_content(&child_transform, &link).expect("fidl error");
        self.root_transform.as_ref().map(|root_transform| {
            self.flatland
                .borrow()
                .proxy()
                .add_child(&root_transform.clone(), &child_transform)
                .expect("fidl error");
        });
        self.children.insert(id);
        self.update_and_present();
    }

    pub fn handle_view_disconnected(&mut self, id: u64) {
        ftrace::duration!(c"wayland", c"XdgSurfaceView::handle_view_disconnected");
        if self.children.remove(&id) {
            self.root_transform.as_ref().map(|root_transform| {
                let child_transform = TransformId { value: id.into() };
                self.flatland
                    .borrow()
                    .proxy()
                    .remove_child(&root_transform, &child_transform)
                    .expect("fidl error");
                self.flatland
                    .borrow()
                    .proxy()
                    .release_transform(&child_transform)
                    .expect("fidl error");
                let link = ContentId { value: id.into() };
                let _ = self.flatland.borrow().proxy().release_viewport(&link);
            });
        }
        self.update_and_present();
    }

    fn set_viewport_properties(&self, id: u64) {
        let viewport_properties = ViewportProperties {
            logical_size: Some(SizeU {
                width: self.logical_size.width.round() as u32,
                height: self.logical_size.height.round() as u32,
            }),
            ..Default::default()
        };
        let link = ContentId { value: id.into() };
        self.flatland
            .borrow()
            .proxy()
            .set_viewport_properties(&link, &viewport_properties)
            .expect("fidl error");
    }
}

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

    #[test]
    fn positioner_default() -> Result<(), Error> {
        let positioner = XdgPositioner::new();
        assert_eq!(Rect { x: 0, y: 0, width: 0, height: 0 }, positioner.get_geometry()?);
        Ok(())
    }

    #[test]
    fn positioner_set_offset_and_size() -> Result<(), Error> {
        let mut positioner = XdgPositioner::new();
        positioner.set_offset(250, 550);
        positioner.set_size(100, 200);
        assert_eq!(Rect { x: 200, y: 450, width: 100, height: 200 }, positioner.get_geometry()?);
        Ok(())
    }

    #[test]
    fn positioner_set_anchor_rect() -> Result<(), Error> {
        let mut positioner = XdgPositioner::new();
        positioner.set_offset(0, 0);
        positioner.set_size(168, 286);
        positioner.set_anchor_rect(486, 0, 44, 28);
        positioner.set_anchor(Enum::Recognized(Anchor::BottomLeft));
        positioner.set_gravity(Enum::Recognized(Gravity::BottomRight));
        assert_eq!(Rect { x: 486, y: 28, width: 168, height: 286 }, positioner.get_geometry()?);
        Ok(())
    }
}