gpui-ce 0.3.0

A community fork of Zed's GPU-accelerated UI framework
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
//! Elements lay out and paint everything in a window. They form a tree, and their layout follows
//! the web layout rules implemented by [taffy](https://github.com/DioxusLabs/taffy). Most of the
//! time you won't use this module directly. The elements behind [`div`](crate::div) and friends have their
//! own APIs, and GPUI uses the traits in this module to turn the element tree into pixels.
//!
//! # Element basics
//!
//! GPUI builds the element tree by calling [`Render::render`] on the root view of a window. It
//! then lays the tree out with Taffy and paints it, one [`Element`] at a time. When the frame is
//! done, the tree and the callbacks it registered are dropped, and the next frame builds a new one.
//! [The frame](crate::_documentation::concepts::the_frame) describes this sequence in full.
//!
//! Elements hold no state between frames, because they are rebuilt every frame. State that
//! must survive a frame lives in an entity, or in element state keyed by a [`GlobalElementId`].
//! An element can also pass small pieces of state from one of its phases to the next through its
//! associated types. [`Element`] explains the three phases.
//!
//! # Implementing your own elements
//!
//! Elements are the low-level, imperative API of GPUI. Most elements stay inside the bounds their
//! parent gives them, which keeps GPUI's layout guarantees. [`deferred`](crate::deferred) lets an
//! element paint outside those bounds, which overlays and popups need. Use that power with care.
//!
//! Most of the time you don't need a custom element. Build components from the built-in elements
//! instead, with [`RenderOnce`] and `#[derive(IntoElement)]`. Write an [`Element`] only when you
//! need your own layout or painting, such as a custom layout algorithm or a code editor. The
//! [`custom_element`](crate::_documentation::examples::custom_element) example is a complete one.

#[cfg(any(feature = "inspector", debug_assertions))]
use crate::InspectorElementPath;
use crate::{
    A11ySubtreeBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
    FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
    util::FluentBuilder, window::with_element_arena,
};
use std::{
    any::Any,
    fmt::{self, Debug, Display},
    mem, panic,
    sync::Arc,
};

/// A part of a window's element tree that lays itself out and paints itself.
///
/// GPUI draws each element in three phases. Each phase runs once per frame, in this order:
///
/// 1. [`request_layout`](Element::request_layout) asks Taffy for a [`LayoutId`] that describes the
///    element's size and position rules. It returns the element's
///    [`RequestLayoutState`](Element::RequestLayoutState). The element has no bounds yet.
/// 2. [`prepaint`](Element::prepaint) receives the element's final [`Bounds`] and returns its
///    [`PrepaintState`](Element::PrepaintState). Insert hitboxes and compute anything that `paint`
///    needs here.
/// 3. [`paint`](Element::paint) receives the bounds and both states, and draws. Add primitives to
///    the scene and register event listeners here.
///
/// The two associated state types carry data from one phase to the next:
///
/// * `RequestLayoutState` is produced by `request_layout`, and `prepaint` and `paint` each get a
///   `&mut` to it. Use it for what layout produced, such as the ids of child layouts or a measured
///   text shape.
/// * `PrepaintState` is produced by `prepaint`, and `paint` gets a `&mut` to it. Use it for what
///   needs the final bounds, such as a [`Hitbox`](crate::Hitbox) or the position of a cursor.
///
/// Use `()` for a state type when the element has nothing to pass on.
///
/// A parent calls its children's phases from inside its own. A child's `request_layout` therefore
/// runs during its parent's, and its `prepaint` and `paint` run while the parent's do. Call
/// [`Window::insert_hitbox`] from `prepaint`, and [`Window::on_mouse_event`] or
/// [`Window::paint_quad`] from `paint`. Window methods check the phase they run in with debug
/// assertions, so calling one in the wrong phase fails in debug builds.
///
/// [`Element::id`] returns the element's identity, if it has one. An element with an id receives a
/// [`GlobalElementId`] in all three phases, so it can read and write state that survives from frame
/// to frame. An element without one receives `None`. See
/// [element identity](crate::_documentation::concepts::elements#identity-and-element-state).
///
/// # Example
///
/// This element draws nothing. It records the phases it runs in, and the example checks their
/// order:
///
/// ```
/// use std::{cell::RefCell, rc::Rc};
///
/// use gpui::{
///     App, Bounds, Context, Element, ElementId, GlobalElementId, InspectorElementId,
///     IntoElement, LayoutId, Pixels, Render, Style, TestApp, Window, div, prelude::*,
/// };
///
/// #[derive(Clone, Default)]
/// struct Log(Rc<RefCell<Vec<&'static str>>>);
///
/// struct Probe {
///     log: Log,
/// }
///
/// impl IntoElement for Probe {
///     type Element = Self;
///
///     fn into_element(self) -> Self::Element {
///         self
///     }
/// }
///
/// impl Element for Probe {
///     type RequestLayoutState = ();
///     type PrepaintState = Bounds<Pixels>;
///
///     fn id(&self) -> Option<ElementId> {
///         None
///     }
///
///     fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
///         None
///     }
///
///     fn request_layout(
///         &mut self,
///         _id: Option<&GlobalElementId>,
///         _inspector_id: Option<&InspectorElementId>,
///         window: &mut Window,
///         cx: &mut App,
///     ) -> (LayoutId, Self::RequestLayoutState) {
///         self.log.0.borrow_mut().push("request_layout");
///         (window.request_layout(Style::default(), [], cx), ())
///     }
///
///     fn prepaint(
///         &mut self,
///         _id: Option<&GlobalElementId>,
///         _inspector_id: Option<&InspectorElementId>,
///         bounds: Bounds<Pixels>,
///         _request_layout: &mut Self::RequestLayoutState,
///         _window: &mut Window,
///         _cx: &mut App,
///     ) -> Self::PrepaintState {
///         self.log.0.borrow_mut().push("prepaint");
///         bounds
///     }
///
///     fn paint(
///         &mut self,
///         _id: Option<&GlobalElementId>,
///         _inspector_id: Option<&InspectorElementId>,
///         _bounds: Bounds<Pixels>,
///         _request_layout: &mut Self::RequestLayoutState,
///         _prepaint: &mut Self::PrepaintState,
///         _window: &mut Window,
///         _cx: &mut App,
///     ) {
///         self.log.0.borrow_mut().push("paint");
///     }
/// }
///
/// struct ProbeView {
///     log: Log,
/// }
///
/// impl Render for ProbeView {
///     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
///         div().size_full().child(Probe { log: self.log.clone() })
///     }
/// }
///
/// let log = Log::default();
/// let mut app = TestApp::new();
/// let mut window = app.open_window({
///     let log = log.clone();
///     move |_window, _cx| ProbeView { log }
/// });
///
/// log.0.borrow_mut().clear();
/// // Notify the view so the next draw renders it again instead of reusing its output.
/// window.update(|_, _, cx| cx.notify());
/// window.draw();
/// assert_eq!(*log.0.borrow(), ["request_layout", "prepaint", "paint"]);
/// ```
///
/// For a complete element, see
/// [`custom_element`](crate::_documentation::examples::custom_element). It is a slider that inserts
/// a hitbox in `prepaint` and handles dragging in `paint`.
pub trait Element: 'static + IntoElement {
    /// The state that [`Element::request_layout`] returns for the later phases.
    ///
    /// `prepaint` and `paint` each receive a `&mut` reference to it. Use `()` if the element needs
    /// no such state.
    type RequestLayoutState: 'static;

    /// The state that [`Element::prepaint`] returns for [`Element::paint`].
    ///
    /// `paint` receives a `&mut` reference to it. Use `()` if the element needs no such state.
    type PrepaintState: 'static;

    /// Returns the element's identity, or `None` if it has none.
    ///
    /// Return an id from any element whose state must survive from one frame to the next, such as
    /// a hover, a drag or a scroll offset. GPUI finds that state again by the id's path from the
    /// window root. The id must be stable on every frame; two elements with the same id path share
    /// state and accessibility identity. The path includes every ancestor that has an id.
    fn id(&self) -> Option<ElementId>;

    /// Returns where this element was created, for the inspector and debug output.
    ///
    /// GPUI uses this only in debug builds and with the `inspector` feature. Return `None` when the
    /// location doesn't matter. To capture it, mark the constructor `#[track_caller]` and store
    /// [`std::panic::Location::caller`].
    fn source_location(&self) -> Option<&'static panic::Location<'static>>;

    /// Requests a layout node from Taffy, and returns it with the state the later phases need.
    ///
    /// Describe the element's size and position rules here: build a [`Style`] and pass it to
    /// [`Window::request_layout`], along with the layout ids of any children. Lay out the children
    /// you draw here too, by calling their `request_layout` before this element's own. The element
    /// has no bounds in this phase.
    fn request_layout(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState);

    /// Runs once the element's bounds are known, and returns the state that `paint` needs.
    ///
    /// `bounds` is the element's final rectangle in window coordinates, in logical pixels. Insert
    /// hitboxes with [`Window::insert_hitbox`] here, so that the next mouse event can be tested
    /// against them. Compute anything `paint` needs too. Calls that draw, such as
    /// [`Window::paint_quad`], belong in `paint`.
    fn prepaint(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Self::PrepaintState;

    /// Draws the element. Runs after `prepaint`, once per frame.
    ///
    /// `bounds` is the rectangle that `prepaint` received. Add primitives with the painting methods
    /// on [`Window`], such as [`Window::paint_quad`], and register event listeners with
    /// [`Window::on_mouse_event`] and related methods. Listeners stay registered until the next
    /// frame replaces them, so an event is always delivered against the frame the user saw.
    fn paint(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        prepaint: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    );

    /// Returns the accessible role for this element, if any.
    /// Elements that return `None` have no accessibility node unless
    /// [`Element::is_a11y_hidden`] returns `true`.
    ///
    /// Note: inclusion in accessibility tree requires non-`None` [`id`][Element::id].
    ///
    /// See the [accessibility guide](crate::_documentation::guides::accessibility) for an overview.
    fn a11y_role(&self) -> Option<accesskit::Role> {
        None
    }

    /// Whether assistive technology should ignore this element and its
    /// descendants.
    ///
    /// GPUI gives a hidden element without a role an internal container node.
    /// AccessKit uses that node to omit the subtree.
    fn is_a11y_hidden(&self) -> bool {
        false
    }

    /// Write accessibility properties to the given node.
    /// GPUI calls this only when [`Element::a11y_role`] returns `Some` or
    /// [`Element::is_a11y_hidden`] returns `true`.
    ///
    /// See the [accessibility guide](crate::_documentation::guides::accessibility) for an overview.
    fn write_a11y_info(&self, _node: &mut accesskit::Node) {}

    /// Add synthetic child nodes to an [`Element`]. The element must have an
    /// [`.id()`][Element::id]. It must also have a
    /// [`.role()`][Element::a11y_role] or return `true` from
    /// [`Element::is_a11y_hidden`].
    ///
    /// Some elements may want to inject accessibility nodes that do not
    /// correspond to any GPUI element. For example, a custom text field element
    /// may want to inject synthetic child nodes for the text content.
    ///
    /// See [Expose elements that GPUI doesn't draw](crate::_documentation::guides::accessibility#expose-elements-that-gpui-doesnt-draw-as-nodes) in
    /// the accessibility guide for more detail.
    fn a11y_synthetic_children(
        &mut self,
        _prepaint: &mut Self::PrepaintState,
        _builder: &mut A11ySubtreeBuilder,
    ) {
    }

    /// Convert this element into a dynamically-typed [`AnyElement`].
    fn into_any(self) -> AnyElement {
        AnyElement::new(self)
    }
}

/// A type that can be converted into an [`Element`], so it can be a child of another element.
///
/// [`ParentElement::child`] takes any `IntoElement`. Strings, [`Entity`](crate::Entity) views and every element
/// implement it. Derive it with `#[derive(IntoElement)]` on a [`RenderOnce`] component to make the
/// component usable wherever an element is.
///
/// # Example
///
/// ```
/// use gpui::{IntoElement, div, prelude::*};
///
/// let row = div().child("Name").child(String::from("Ada"));
/// let _element = row.into_element();
/// ```
pub trait IntoElement: Sized {
    /// The element type that this type converts into.
    ///
    /// Strings convert into text elements. A [`RenderOnce`] component that derives `IntoElement`
    /// converts into the element that renders it.
    type Element: Element;

    /// Converts `self` into an [`Element`].
    ///
    /// GPUI calls this when it needs the element. You rarely call it yourself, but it is the method
    /// to implement.
    fn into_element(self) -> Self::Element;

    /// Converts `self` into an [`AnyElement`], with its concrete type erased.
    ///
    /// Use this when two branches return different element types, or a list holds mixed types.
    fn into_any_element(self) -> AnyElement {
        self.into_element().into_any()
    }
}

impl<T: IntoElement> FluentBuilder for T {}

/// A view: an entity that GPUI draws in a window.
///
/// Implement `Render` for the state of a view. GPUI can then draw an [`Entity`](crate::Entity) of that type as an
/// element, and [`Context::notify`] redraws it. Use a view when a part of the interface has state
/// that must survive from frame to frame. For stateless pieces, use [`RenderOnce`].
///
/// GPUI calls `render` each time it draws the window and reaches this view. The view keeps its
/// state in `self`, not in the elements it returns. Those elements are consumed by the frame and
/// dropped, and the next call builds new ones. So `render` should only read state and build
/// elements from it. GPUI skips the call while nothing the view read has changed; see
/// [retained view rendering](crate::_documentation::concepts::retained_rendering).
///
/// # Example
///
/// ```
/// use std::{cell::Cell, rc::Rc};
///
/// use gpui::{Context, IntoElement, Render, TestApp, Window, div, prelude::*};
///
/// struct Greeting {
///     name: String,
///     renders: Rc<Cell<usize>>,
/// }
///
/// impl Render for Greeting {
///     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
///         self.renders.set(self.renders.get() + 1);
///         div().child(format!("Hello, {}", self.name))
///     }
/// }
///
/// let renders = Rc::new(Cell::new(0));
/// let mut app = TestApp::new();
/// let mut window = app.open_window({
///     let renders = renders.clone();
///     move |_window, _cx| Greeting {
///         name: "Ada".into(),
///         renders,
///     }
/// });
///
/// renders.set(0);
/// // Notify the view so the next draw renders it again instead of reusing its output.
/// window.update(|_, _, cx| cx.notify());
/// window.draw();
/// assert_eq!(renders.get(), 1);
/// ```
pub trait Render: 'static + Sized {
    /// Builds the view's element tree from its current state.
    ///
    /// `window` is the window being drawn, and `cx` gives access to this view through
    /// [`Context<Self>`](Context). Return the elements the view shows. Don't change state in this
    /// method, because GPUI may call it many times, or skip it, for one change.
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
}

impl Render for Empty {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        Empty
    }
}

/// A component: a value that describes a pattern of elements and renders it once.
///
/// Use `RenderOnce` for reusable pieces of interface that keep no state of their own. Build the
/// component from plain data, and derive [`IntoElement`] on it so it can be a child of an element.
/// The component's `render` takes `self` by value, and the component is consumed when it is drawn.
/// A component can't call [`Context::notify`], because it has no entity. To report events, store a
/// callback in the component and let the parent view decide what the callback does. Use [`Render`]
/// for a piece of interface that holds state.
///
/// Elements that need state across frames need ids. Pass the id in from the parent, and use it
/// with [`InteractiveElement::id`](crate::InteractiveElement::id). GPUI scopes a component's elements under the component's type
/// name, so two instances of the same component side by side would otherwise share their state.
///
/// # Example
///
/// ```
/// use std::{cell::Cell, rc::Rc};
///
/// use gpui::{App, Context, IntoElement, Render, RenderOnce, TestApp, Window, div, prelude::*};
///
/// #[derive(IntoElement)]
/// struct Badge {
///     renders: Rc<Cell<usize>>,
/// }
///
/// impl RenderOnce for Badge {
///     fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
///         self.renders.set(self.renders.get() + 1);
///         div().child("3")
///     }
/// }
///
/// struct Inbox {
///     renders: Rc<Cell<usize>>,
/// }
///
/// impl Render for Inbox {
///     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
///         div().child(Badge {
///             renders: self.renders.clone(),
///         })
///     }
/// }
///
/// let renders = Rc::new(Cell::new(0));
/// let mut app = TestApp::new();
/// let mut window = app.open_window({
///     let renders = renders.clone();
///     move |_window, _cx| Inbox { renders }
/// });
///
/// renders.set(0);
/// // Notify the view so the next draw renders it again instead of reusing its output.
/// window.update(|_, _, cx| cx.notify());
/// window.draw();
/// assert_eq!(renders.get(), 1);
/// ```
pub trait RenderOnce: 'static {
    /// Builds the component's element tree. Takes `self` by value, so the component is used up.
    ///
    /// GPUI calls this once for each time the component appears in a frame. Return the elements
    /// the component shows.
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
}

/// A parent element whose children all have one concrete type.
///
/// Use it when a container's children carry a shared type, such as rows with their own data.
/// Most containers use [`ParentElement`], which accepts any [`IntoElement`].
pub trait ParentElementTyped {
    /// The type of child that this element accepts.
    type Child;

    /// Adds the given children to the end of this element's children.
    fn extend(&mut self, elements: impl IntoIterator<Item = Self::Child>);

    /// Adds one child to this element, and returns the element for chaining.
    fn child(mut self, child: Self::Child) -> Self
    where
        Self: Sized,
    {
        self.extend(std::iter::once(child));
        self
    }

    /// Adds several children to this element, in iteration order, and returns the element.
    fn children(mut self, children: impl IntoIterator<Item = Self::Child>) -> Self
    where
        Self: Sized,
    {
        self.extend(children);
        self
    }
}

/// An element that can hold any number of children of any type.
///
/// This is the trait behind `.child()` and `.children()` on containers such as [`div`](crate::div). Each
/// child is anything that implements [`IntoElement`], so strings, views and other elements can be
/// mixed in one container.
pub trait ParentElement {
    /// Adds the given children to the end of this element's children.
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);

    /// Adds one child to this element, and returns the element for chaining.
    fn child(mut self, child: impl IntoElement) -> Self
    where
        Self: Sized,
    {
        self.extend(std::iter::once(child.into_any_element()));
        self
    }

    /// Adds several children to this element, in iteration order, and returns the element.
    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
    where
        Self: Sized,
    {
        self.extend(children.into_iter().map(|child| child.into_any_element()));
        self
    }
}

/// A globally unique identifier for an element, used to track state across frames.
///
/// The hash of the id path is computed once, when the id is built. Every
/// element with an id is looked up in the element-state maps of two frames
/// and recorded as accessed on every frame it is drawn, and each of those
/// hashes the whole path — every ancestor's id, string names byte by byte —
/// so on a deep tree the hashing alone was a visible share of a frame.
#[derive(Clone, Debug)]
pub struct GlobalElementId {
    ids: Arc<[ElementId]>,
    hash: u64,
}

/// The hash of an empty id path; every path hash is folded from it with
/// [`extend_path_hash`], one id at a time, so the window can keep the hash
/// of each prefix of its id stack and never re-hash a path.
pub(crate) const EMPTY_PATH_HASH: u64 = 0;

/// The hash of the path `prefix` + `id`, given the hash of `prefix`.
pub(crate) fn extend_path_hash(prefix: u64, id: &ElementId) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = collections::FxHasher::with_seed(prefix as usize);
    id.hash(&mut hasher);
    hasher.finish()
}

impl GlobalElementId {
    pub(crate) fn new(ids: &[ElementId]) -> Self {
        let hash = ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash);
        Self::with_hash(ids, hash)
    }

    /// `ids` with its hash already known, as the window's id stack keeps it.
    pub(crate) fn with_hash(ids: &[ElementId], hash: u64) -> Self {
        debug_assert_eq!(hash, ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash));
        Self {
            ids: Arc::from(ids),
            hash,
        }
    }

    pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
        accesskit::NodeId(self.hash)
    }
}

impl Default for GlobalElementId {
    fn default() -> Self {
        Self::new(&[])
    }
}

impl std::ops::Deref for GlobalElementId {
    type Target = [ElementId];

    fn deref(&self) -> &Self::Target {
        &self.ids
    }
}

impl PartialEq for GlobalElementId {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)
    }
}

impl Eq for GlobalElementId {}

impl std::hash::Hash for GlobalElementId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write_u64(self.hash);
    }
}
impl Display for GlobalElementId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, element_id) in self.ids.iter().enumerate() {
            if i > 0 {
                write!(f, ".")?;
            }
            write!(f, "{}", element_id)?;
        }
        Ok(())
    }
}

trait ElementObject {
    fn inner_element(&mut self) -> &mut dyn Any;

    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;

    fn prepaint(&mut self, window: &mut Window, cx: &mut App);

    fn paint(&mut self, window: &mut Window, cx: &mut App);

    fn layout_as_root(
        &mut self,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels>;
}

/// An [`Element`] together with the state GPUI keeps while drawing it in one frame.
///
/// GPUI creates a `Drawable` for each element in the tree, and an [`AnyElement`] holds one.
/// Its phase state moves through the frame's phases in order. You don't construct it yourself.
/// Use `element` to reach the wrapped element.
pub struct Drawable<E: Element> {
    /// The wrapped element.
    pub element: E,
    phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
}

#[derive(Default)]
enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
    #[default]
    Start,
    RequestLayout {
        layout_id: LayoutId,
        global_id: Option<GlobalElementId>,
        inspector_id: Option<InspectorElementId>,
        request_layout: RequestLayoutState,
    },
    LayoutComputed {
        layout_id: LayoutId,
        global_id: Option<GlobalElementId>,
        inspector_id: Option<InspectorElementId>,
        available_space: Size<AvailableSpace>,
        request_layout: RequestLayoutState,
    },
    Prepaint {
        node_id: DispatchNodeId,
        global_id: Option<GlobalElementId>,
        inspector_id: Option<InspectorElementId>,
        bounds: Bounds<Pixels>,
        request_layout: RequestLayoutState,
        prepaint: PrepaintState,
        inline_fragments: Option<Arc<[Bounds<Pixels>]>>,
    },
    Painted,
}

impl<E: Element> Drawable<E> {
    pub(crate) fn new(element: E) -> Self {
        Drawable {
            element,
            phase: ElementDrawPhase::Start,
        }
    }

    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
        match mem::take(&mut self.phase) {
            ElementDrawPhase::Start => {
                let global_id = self
                    .element
                    .id()
                    .map(|element_id| prepare_element_id(element_id, window));

                let inspector_id;
                #[cfg(any(feature = "inspector", debug_assertions))]
                {
                    inspector_id = if window.inspector_enabled() {
                        self.element
                            .source_location()
                            .map(|source| prepare_inspector_id(source, window))
                    } else {
                        None
                    };
                }
                #[cfg(not(any(feature = "inspector", debug_assertions)))]
                {
                    inspector_id = None;
                }

                #[cfg(all(
                    feature = "hot-patching",
                    debug_assertions,
                    not(target_family = "wasm")
                ))]
                let (layout_id, request_layout) = subsecond::HotFn::current(E::request_layout)
                    .call((
                        &mut self.element,
                        global_id.as_ref(),
                        inspector_id.as_ref(),
                        window,
                        cx,
                    ));
                #[cfg(not(all(
                    feature = "hot-patching",
                    debug_assertions,
                    not(target_family = "wasm")
                )))]
                let (layout_id, request_layout) = self.element.request_layout(
                    global_id.as_ref(),
                    inspector_id.as_ref(),
                    window,
                    cx,
                );

                if global_id.is_some() {
                    window.element_id_stack.pop();
                }

                self.phase = ElementDrawPhase::RequestLayout {
                    layout_id,
                    global_id,
                    inspector_id,
                    request_layout,
                };
                layout_id
            }
            _ => panic!("must call request_layout only once"),
        }
    }

    pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
        match mem::take(&mut self.phase) {
            ElementDrawPhase::RequestLayout {
                layout_id,
                global_id,
                inspector_id,
                mut request_layout,
            }
            | ElementDrawPhase::LayoutComputed {
                layout_id,
                global_id,
                inspector_id,
                mut request_layout,
                ..
            } => {
                if let Some(element_id) = self.element.id() {
                    window.element_id_stack.push(element_id);
                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
                }

                let bounds = window.layout_bounds(layout_id);
                let mut pushed_a11y_node = false;
                if window.a11y.is_active() {
                    if let Some(global_id) = global_id.as_ref() {
                        let hidden = self.element.is_a11y_hidden();
                        let role = self.element.a11y_role();
                        if role.is_some() || hidden {
                            let role = role.unwrap_or(accesskit::Role::GenericContainer);
                            let node_id = global_id.accesskit_node_id();
                            let mut node = accesskit::Node::new(role);
                            let scale = window.scale_factor();
                            node.set_bounds(accesskit::Rect {
                                x0: (bounds.origin.x.0 * scale) as f64,
                                y0: (bounds.origin.y.0 * scale) as f64,
                                x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
                                y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
                            });
                            self.element.write_a11y_info(&mut node);
                            if hidden {
                                node.set_hidden();
                            }
                            window.a11y.node_bounds.insert(node_id, bounds);
                            pushed_a11y_node = window.a11y.nodes.push(node_id, node);
                            #[cfg(debug_assertions)]
                            if pushed_a11y_node {
                                let view = window
                                    .a11y
                                    .view_type_names
                                    .get(&window.current_view())
                                    .copied();
                                let source_location = self.element.source_location();
                                window.a11y.nodes.record_node_info(
                                    node_id,
                                    crate::window::a11y::debug::NodeDebugInfo {
                                        synthetic: false,
                                        view,
                                        element_id: global_id.last().map(|id| format!("{id:?}")),
                                        source_location,
                                    },
                                );
                            }
                        }
                    }
                }

                let node_id = window.next_frame.dispatch_tree.push_node();

                let inline_fragments = window.inline_fragments(layout_id);
                let previous_fragments = std::mem::replace(
                    &mut window.current_inline_fragments,
                    inline_fragments.clone(),
                );

                let mut prepaint = window.with_layout_direction_context(layout_id, |window| {
                    #[cfg(all(
                        feature = "hot-patching",
                        debug_assertions,
                        not(target_family = "wasm")
                    ))]
                    {
                        subsecond::HotFn::current(E::prepaint).call((
                            &mut self.element,
                            global_id.as_ref(),
                            inspector_id.as_ref(),
                            bounds,
                            &mut request_layout,
                            window,
                            cx,
                        ))
                    }

                    #[cfg(not(all(
                        feature = "hot-patching",
                        debug_assertions,
                        not(target_family = "wasm")
                    )))]
                    {
                        self.element.prepaint(
                            global_id.as_ref(),
                            inspector_id.as_ref(),
                            bounds,
                            &mut request_layout,
                            window,
                            cx,
                        )
                    }
                });

                window.current_inline_fragments = previous_fragments;
                window.next_frame.dispatch_tree.pop_node();

                if pushed_a11y_node {
                    if let Some(global_id) = global_id.as_ref() {
                        #[cfg(debug_assertions)]
                        let creator = crate::window::a11y::debug::NodeCreator {
                            view: window
                                .a11y
                                .view_type_names
                                .get(&window.current_view())
                                .copied(),
                            element_id: global_id.last().map(|id| format!("{id:?}")),
                            source_location: self.element.source_location(),
                        };
                        let mut builder = A11ySubtreeBuilder::new(
                            global_id.accesskit_node_id(),
                            &mut window.a11y.nodes,
                        );
                        #[cfg(debug_assertions)]
                        {
                            builder = builder.with_creator(creator);
                        }
                        self.element
                            .a11y_synthetic_children(&mut prepaint, &mut builder);
                    }
                    window.a11y.nodes.pop();
                }

                if global_id.is_some() {
                    window.element_id_stack.pop();
                }

                self.phase = ElementDrawPhase::Prepaint {
                    node_id,
                    global_id,
                    inspector_id,
                    bounds,
                    request_layout,
                    prepaint,
                    inline_fragments,
                };
            }
            _ => panic!("must call request_layout before prepaint"),
        }
    }

    pub(crate) fn paint(
        &mut self,
        window: &mut Window,
        cx: &mut App,
    ) -> (E::RequestLayoutState, E::PrepaintState) {
        match mem::take(&mut self.phase) {
            ElementDrawPhase::Prepaint {
                node_id,
                global_id,
                inspector_id,
                bounds,
                mut request_layout,
                mut prepaint,
                inline_fragments,
                ..
            } => {
                if let Some(element_id) = self.element.id() {
                    window.element_id_stack.push(element_id);
                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
                }

                window.next_frame.dispatch_tree.set_active_node(node_id);

                let previous_fragments =
                    std::mem::replace(&mut window.current_inline_fragments, inline_fragments);

                #[cfg(all(
                    feature = "hot-patching",
                    debug_assertions,
                    not(target_family = "wasm")
                ))]
                subsecond::HotFn::current(E::paint).call((
                    &mut self.element,
                    global_id.as_ref(),
                    inspector_id.as_ref(),
                    bounds,
                    &mut request_layout,
                    &mut prepaint,
                    window,
                    cx,
                ));
                #[cfg(not(all(
                    feature = "hot-patching",
                    debug_assertions,
                    not(target_family = "wasm")
                )))]
                self.element.paint(
                    global_id.as_ref(),
                    inspector_id.as_ref(),
                    bounds,
                    &mut request_layout,
                    &mut prepaint,
                    window,
                    cx,
                );

                if global_id.is_some() {
                    window.element_id_stack.pop();
                }

                window.current_inline_fragments = previous_fragments;

                self.phase = ElementDrawPhase::Painted;
                (request_layout, prepaint)
            }
            _ => panic!("must call prepaint before paint"),
        }
    }

    fn compute_layout_as_root(
        &mut self,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Size<Pixels>) {
        if matches!(&self.phase, ElementDrawPhase::Start) {
            self.request_layout(window, cx);
        }

        let layout_id = match mem::take(&mut self.phase) {
            ElementDrawPhase::RequestLayout {
                layout_id,
                global_id,
                inspector_id,
                request_layout,
            } => {
                window.compute_layout(layout_id, available_space, cx);
                self.phase = ElementDrawPhase::LayoutComputed {
                    layout_id,
                    global_id,
                    inspector_id,
                    available_space,
                    request_layout,
                };
                layout_id
            }
            ElementDrawPhase::LayoutComputed {
                layout_id,
                global_id,
                inspector_id,
                available_space: prev_available_space,
                request_layout,
            } => {
                if available_space != prev_available_space {
                    window.compute_layout(layout_id, available_space, cx);
                }
                self.phase = ElementDrawPhase::LayoutComputed {
                    layout_id,
                    global_id,
                    inspector_id,
                    available_space,
                    request_layout,
                };
                layout_id
            }
            _ => panic!("cannot measure after painting"),
        };

        (layout_id, window.layout_bounds(layout_id).size)
    }

    pub(crate) fn layout_as_root(
        &mut self,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels> {
        self.compute_layout_as_root(available_space, window, cx).1
    }
}

impl<E> ElementObject for Drawable<E>
where
    E: Element,
    E::RequestLayoutState: 'static,
{
    fn inner_element(&mut self) -> &mut dyn Any {
        &mut self.element
    }

    #[inline]
    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
        Drawable::request_layout(self, window, cx)
    }

    #[inline]
    fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
        Drawable::prepaint(self, window, cx);
    }

    #[inline]
    fn paint(&mut self, window: &mut Window, cx: &mut App) {
        Drawable::paint(self, window, cx);
    }

    #[inline]
    fn layout_as_root(
        &mut self,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels> {
        Drawable::layout_as_root(self, available_space, window, cx)
    }
}

/// An element with its concrete type erased, so that elements of different types can share one
/// type.
///
/// Use it when a function must return one type but its branches build different elements, or when
/// a list holds elements of mixed types. Create one with [`IntoElement::into_any_element`] or
/// [`Element::into_any`]. Its methods run the same phases as the element it wraps.
///
/// # Example
///
/// ```
/// use gpui::{AnyElement, Div, IntoElement, div, prelude::*};
///
/// fn label(wide: bool) -> AnyElement {
///     if wide {
///         div().w_full().child("Wide").into_any_element()
///     } else {
///         "Narrow".into_any_element()
///     }
/// }
///
/// let mut wide = label(true);
/// assert!(wide.downcast_mut::<Div>().is_some());
///
/// let mut narrow = label(false);
/// assert!(narrow.downcast_mut::<Div>().is_none());
/// ```
pub struct AnyElement(ArenaBox<dyn ElementObject>);

impl AnyElement {
    pub(crate) fn new<E>(element: E) -> Self
    where
        E: 'static + Element,
        E::RequestLayoutState: Any,
    {
        let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
            .map(|element| element as &mut dyn ElementObject);
        AnyElement(element)
    }

    /// Returns a mutable reference to the wrapped element if it has type `T`, or `None` otherwise.
    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.0.inner_element().downcast_mut::<T>()
    }

    /// Runs the request-layout phase on the wrapped element, and returns its layout id.
    ///
    /// Call this from a parent's `request_layout`, before the parent's own layout is requested.
    pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
        self.0.request_layout(window, cx)
    }

    /// Runs the prepaint phase on the wrapped element, with the bounds that layout gave it.
    ///
    /// Returns the [`FocusHandle`] of a focused element in this subtree, if one became focused
    /// during this call. Otherwise returns `None`.
    pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
        let focus_assigned = window.next_frame.focus.is_some();

        self.0.prepaint(window, cx);

        if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
            return FocusHandle::for_id(focus_id, &cx.focus_handles);
        }

        None
    }

    /// Runs the paint phase on the wrapped element. Call it after [`AnyElement::prepaint`].
    pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
        self.0.paint(window, cx);
    }

    /// Lays out this element as the root of its own layout, within `available_space`, and returns
    /// its size.
    ///
    /// The element is not placed in the window by this call. Use it to measure an element before
    /// placing it with [`AnyElement::prepaint_at`]. If the layout hasn't been requested yet, this
    /// method requests it first.
    pub fn layout_as_root(
        &mut self,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> Size<Pixels> {
        self.0.layout_as_root(available_space, window, cx)
    }

    /// Runs the prepaint phase with `origin` as the element's origin, in window coordinates.
    ///
    /// Call [`AnyElement::layout_as_root`] first, or use [`AnyElement::prepaint_as_root`], which
    /// does both. Returns the focus handle of a focused element in the subtree that became focused
    /// during this call, if any.
    pub fn prepaint_at(
        &mut self,
        origin: Point<Pixels>,
        window: &mut Window,
        cx: &mut App,
    ) -> Option<FocusHandle> {
        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
    }

    /// Lays out this element as a root within `available_space`, then prepaints it at `origin`.
    ///
    /// Use it for an element that sits outside its parent's layout, such as a popover placed at a
    /// window position. Returns the focus handle of a focused element in the subtree that became
    /// focused during this call, if any.
    pub fn prepaint_as_root(
        &mut self,
        origin: Point<Pixels>,
        available_space: Size<AvailableSpace>,
        window: &mut Window,
        cx: &mut App,
    ) -> Option<FocusHandle> {
        self.layout_as_root(available_space, window, cx);
        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
    }
}

impl Element for AnyElement {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let layout_id = self.request_layout(window, cx);
        (layout_id, ())
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) {
        self.prepaint(window, cx);
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        self.paint(window, cx);
    }
}

impl IntoElement for AnyElement {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }

    fn into_any_element(self) -> AnyElement {
        self
    }
}

/// An element that draws nothing and takes up no space.
///
/// Return it where a view or component must produce an element but has nothing to show. Its
/// layout has `display: none`, so it doesn't affect its siblings.
pub struct Empty;

impl IntoElement for Empty {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for Empty {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        (
            window.request_layout(
                Style {
                    display: crate::Display::None,
                    ..Default::default()
                },
                None,
                cx,
            ),
            (),
        )
    }

    fn prepaint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<Pixels>,
        _state: &mut Self::RequestLayoutState,
        _window: &mut Window,
        _cx: &mut App,
    ) {
    }

    fn paint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<Pixels>,
        _request_layout: &mut Self::RequestLayoutState,
        _prepaint: &mut Self::PrepaintState,
        _window: &mut Window,
        _cx: &mut App,
    ) {
    }
}

#[inline(never)]
fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
    window.element_id_stack.push(element_id);
    window.element_id_stack.global_id()
}

#[cfg(any(feature = "inspector", debug_assertions))]
#[inline(never)]
fn prepare_inspector_id(
    source: &'static panic::Location<'static>,
    window: &mut Window,
) -> InspectorElementId {
    let path = InspectorElementPath {
        global_id: window.element_id_stack.global_id(),
        source_location: source,
    };
    window.build_inspector_element_id(path)
}

#[cfg(test)]
mod global_element_id_tests {
    use super::*;
    use std::hash::{Hash, Hasher};

    fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
        let mut ids: Vec<ElementId> = (0..depth as u64)
            .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
            .collect();
        ids.push(ElementId::NamedInteger("leaf".into(), leaf));
        ids
    }

    fn fx_hash(value: &impl Hash) -> u64 {
        let mut hasher = collections::FxHasher::default();
        value.hash(&mut hasher);
        hasher.finish()
    }

    #[test]
    fn equal_paths_are_equal_and_hash_alike() {
        let a = GlobalElementId::new(&path(8, 1));
        let b = GlobalElementId::new(&path(8, 1));
        let c = GlobalElementId::new(&path(8, 2));
        let shallower = GlobalElementId::new(&path(7, 1));
        assert_eq!(a, b);
        assert_eq!(fx_hash(&a), fx_hash(&b));
        assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
        assert_ne!(a, c);
        assert_ne!(a, shallower);
        assert_ne!(fx_hash(&a), fx_hash(&c));
        assert_eq!(&*a, path(8, 1).as_slice());
        assert_eq!(a.to_string(), b.to_string());
        assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
    }

    /// A window of `items` columns of `depth` nested stateful divs — the
    /// shape of a list of cards — drawn from scratch on every frame.
    struct DeepStatefulTree {
        items: usize,
        depth: usize,
    }

    impl crate::Render for DeepStatefulTree {
        fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
            use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
            let depth = self.depth;
            div()
                .flex()
                .flex_wrap()
                .size_full()
                .children((0..self.items).map(move |item| {
                    let mut element = div().id(("leaf", item as u64)).size(px(2.));
                    for level in (0..depth).rev() {
                        element = div()
                            .id(("some-container-element", level as u64))
                            .child(element);
                    }
                    element.id(("item", item as u64)).size(px(4.))
                }))
        }
    }

    /// Frame cost of a tree of stateful elements: every one of them builds a
    /// `GlobalElementId` and looks its state up in two frames' maps.
    ///
    /// `cargo test -p gpui --release --lib global_element_id_tests::frame_cost -- --ignored --nocapture`
    #[crate::test]
    #[ignore = "prints timings; run by hand"]
    fn frame_cost(cx: &mut crate::TestAppContext) {
        use crate::AppContext as _;
        for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
            let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
            let window = crate::AnyWindowHandle::from(window);
            let mut frame = |cx: &mut crate::TestAppContext| {
                cx.update_window(window, |_, window, cx| {
                    window.refresh();
                    let started = std::time::Instant::now();
                    window.draw(cx).clear(cx);
                    started.elapsed()
                })
                .unwrap()
            };
            for _ in 0..5 {
                frame(cx);
            }
            let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
            samples.sort();
            let median = samples[samples.len() / 2];
            let stateful = items * (depth + 2);
            eprintln!(
                "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
                median.as_secs_f64() * 1e3,
                median.as_nanos() as f64 / stateful as f64,
            );
        }
    }

    /// `cargo test -p gpui --release --lib global_element_id_tests::hash_cost -- --ignored --nocapture`
    #[test]
    #[ignore = "prints timings; run by hand"]
    fn hash_cost() {
        let ids = path(11, 7);
        let id = GlobalElementId::new(&ids);
        let n = 1_000_000u64;
        let mut acc = 0u64;
        let started = std::time::Instant::now();
        for _ in 0..n {
            acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
        }
        let walk = started.elapsed();
        let started = std::time::Instant::now();
        for _ in 0..n {
            acc ^= fx_hash(std::hint::black_box(&id));
        }
        let cached = started.elapsed();
        let started = std::time::Instant::now();
        for _ in 0..n {
            acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash;
        }
        let build = started.elapsed();
        eprintln!(
            "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
            walk.as_nanos() as f64 / n as f64,
            cached.as_nanos() as f64 / n as f64,
            build.as_nanos() as f64 / n as f64,
        );
    }
}