ltk/
app.rs

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
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

pub use xkeysym::Keysym;
pub use crate::channel::ChannelSender;

use crate::widget::Element;

/// Wayland `ext-foreign-toplevel-list-v1` event delivered to apps via
/// [`App::on_toplevel_event`]. `Opened` fires after the compositor
/// commits the first `done` for a new handle (so `app_id` is the value
/// in effect at that point — the protocol allows the compositor to
/// re-commit later, but most don't). `Closed` fires when the
/// compositor sends `closed` and the runtime is about to destroy the
/// handle proxy. Both carry the same `id`, the Wayland protocol id of
/// the handle, unique within the session and stable for the handle's
/// lifetime. `identifier` is the compositor's opaque per-window token,
/// the one to name a single window by when talking to the compositor.
#[ derive( Debug, Clone ) ]
pub enum ToplevelEvent
{
	Opened { id: u32, app_id: String, identifier: String, title: String },
	Closed { id: u32 },
}

/// Wayland shell mode for the application surface.
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum ShellMode
{
	/// Normal application window using xdg-shell protocol.
	/// This is the default for regular applications.
	Window,

	/// Layer-shell surface at the specified layer.
	/// Used for shell components like panels, backgrounds, overlays.
	Layer( Layer ),

	/// `ext-session-lock-v1` lock surface. The compositor blanks the outputs
	/// and shows only this surface until the app requests exit (see
	/// [`App::requested_exit`]). Used by the screen locker.
	SessionLock,
}

/// Layer-shell layer position.
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum Layer
{
	/// Below normal windows (wallpapers, desktop backgrounds).
	Background,
	/// Below normal windows but above background.
	Bottom,
	/// Not a layer-shell surface at all: an ordinary `xdg_toplevel`
	/// window stacked among the applications, decorated and listed by
	/// the compositor like any other. [`OverlaySpec::size`] is its fixed
	/// size (`0` falls back to a default, it cannot "fill"); anchor,
	/// exclusive zone and keyboard exclusivity are ignored. The
	/// compositor's close button delivers [`OverlaySpec::on_dismiss`].
	Window,
	/// Above normal windows (panels, docks).
	Top,
	/// Above everything (notifications, on-screen displays).
	Overlay,
}

impl Layer
{
	/// Convert to smithay's wlr-layer Layer type.
	#[ cfg( feature = "wayland" ) ]
	pub( crate ) fn to_wlr_layer( self ) -> smithay_client_toolkit::shell::wlr_layer::Layer
	{
		use smithay_client_toolkit::shell::wlr_layer::Layer as WlrLayer;
		match self
		{
			Layer::Background => WlrLayer::Background,
			Layer::Bottom     => WlrLayer::Bottom,
			Layer::Top        => WlrLayer::Top,
			Layer::Overlay    => WlrLayer::Overlay,
			// Never reaches layer-shell; the reconciler creates a window first.
			Layer::Window     => WlrLayer::Top,
		}
	}
}

/// Layer-shell anchor edges.
/// Determines which screen edges the surface is attached to.
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub struct Anchor
{
	pub top:    bool,
	pub bottom: bool,
	pub left:   bool,
	pub right:  bool,
}

impl Anchor
{
	/// Anchor to all edges (fill screen).
	pub const ALL: Self = Self { top: true, bottom: true, left: true, right: true };

	/// Anchor to top edge only (horizontal bar at top).
	pub const TOP: Self = Self { top: true, bottom: false, left: true, right: true };

	/// Anchor to bottom edge only (horizontal bar at bottom).
	pub const BOTTOM: Self = Self { top: false, bottom: true, left: true, right: true };

	/// Anchor to left edge only (vertical bar at left).
	pub const LEFT: Self = Self { top: true, bottom: true, left: true, right: false };

	/// Anchor to right edge only (vertical bar at right).
	pub const RIGHT: Self = Self { top: true, bottom: true, left: false, right: true };

	/// Convert to smithay's Anchor bitflags.
	#[ cfg( feature = "wayland" ) ]
	pub( crate ) fn to_wlr_anchor( self ) -> smithay_client_toolkit::shell::wlr_layer::Anchor
	{
		use smithay_client_toolkit::shell::wlr_layer::Anchor as WlrAnchor;
		let mut anchor = WlrAnchor::empty();
		if self.top    { anchor |= WlrAnchor::TOP; }
		if self.bottom { anchor |= WlrAnchor::BOTTOM; }
		if self.left   { anchor |= WlrAnchor::LEFT; }
		if self.right  { anchor |= WlrAnchor::RIGHT; }
		anchor
	}
}

/// Stable identifier for an overlay surface. The runtime uses it to diff the
/// overlay list between frames: if the same `OverlayId` is returned from
/// [`App::overlays`] on consecutive frames the underlying Wayland surface
/// and its internal state are kept; if it disappears the surface is destroyed.
#[ derive( Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord ) ]
pub struct OverlayId( pub u32 );

/// Stable identifier for a subsurface, used to diff the list returned by
/// [`App::subsurfaces`] between frames the same way [`OverlayId`] diffs
/// overlays.
#[ derive( Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord ) ]
pub struct SubsurfaceId( pub u32 );

/// Which surface a [`SubsurfaceSpec`] is composited as a child of. `Main`
/// (the default position) parents to the app's main surface; `Overlay(id)`
/// parents to one of the [`App::overlays`] surfaces, so a slide can ride
/// above app windows the way an overlay panel does. An `Overlay` parent that
/// is absent or not yet configured is skipped for that frame.
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum SubsurfaceParent
{
	Main,
	Overlay( OverlayId ),
}

/// One of the surfaces an [`App`] can target with an invalidation. Used inside
/// [`InvalidationScope::Only`] to name the affected surfaces.
#[ derive( Debug, Clone, Copy, PartialEq, Eq, Hash ) ]
pub enum SurfaceTarget
{
	/// The application's main surface (the one returned by [`App::view`]).
	Main,
	/// The overlay with the given stable [`OverlayId`].
	Overlay( OverlayId ),
}

/// Which surfaces a given [`App::update`] mutation can affect.
///
/// Returned by [`App::invalidate_after`] (default [`InvalidationScope::All`])
/// to let the runtime skip redraws on surfaces whose contents could not
/// possibly have changed by the message in question. On a shell with many
/// overlays most messages only touch one of them, so the savings are large.
#[ derive( Debug, Clone ) ]
pub enum InvalidationScope
{
	/// Treat every surface as potentially affected (safe default).
	All,
	/// Only the listed surfaces may have changed; others can be skipped this
	/// iteration. An empty list means "nothing visible to redraw" — useful
	/// for messages that only touch internal bookkeeping.
	Only( Vec<SurfaceTarget> ),
}

impl InvalidationScope
{
	/// Combine two scopes. `All` absorbs any other scope; two `Only` scopes
	/// merge into a deduped list of targets. Used by the run loop to fold the
	/// per-message scopes from a batch of pending messages into a single
	/// decision before applying it.
	pub fn union( self, other: Self ) -> Self
	{
		match ( self, other )
		{
			( Self::All, _ ) | ( _, Self::All ) => Self::All,
			( Self::Only( mut a ), Self::Only( b ) ) =>
			{
				for t in b
				{
					if !a.contains( &t ) { a.push( t ); }
				}
				Self::Only( a )
			}
		}
	}
}

/// Description of an additional layer-shell surface rendered on top of the
/// main application surface.
///
/// Apps return a list of these from [`App::overlays`] each frame. The runtime
/// creates one Wayland layer-shell surface per active overlay, renders its
/// [`view`](Self::view) to its own canvas, and dispatches input to it
/// independently of the main surface. Overlays share the same message type as
/// the main app — messages emitted by widgets inside an overlay are delivered
/// to [`App::update`] exactly like messages from the main view.
///
/// Overlays are useful for building shells whose main surface sits behind
/// regular app windows (e.g. a homescreen on [`Layer::Background`]) while
/// still exposing on-demand panels above everything (launcher, quick
/// settings, power menu…).
pub struct OverlaySpec<Message: Clone>
{
	/// Stable identifier, used to diff overlays between frames.
	pub id: OverlayId,

	/// Wayland layer for this overlay. Typically [`Layer::Overlay`] or
	/// [`Layer::Top`].
	pub layer: Layer,

	/// Screen edges to anchor to.
	pub anchor: Anchor,

	/// Desired size `( width, height )`, resolved to logical pixels against
	/// the main surface (output) when the overlay is materialized. A
	/// [`Length::px`](crate::Length::px) keeps a fixed size; a
	/// [`Length::widget`](crate::Length::widget) / `vmin` / `dp` makes the
	/// overlay surface scale with the display like any other sized element.
	/// A component that resolves to `0` (e.g. `Length::px( 0.0 )`) means
	/// "fill available space in that dimension".
	pub size: ( crate::types::Length, crate::types::Length ),

	/// Exclusive zone in pixels reserved from the anchored edge.
	/// `-1` requests focus without reserving space, `0` is the default for
	/// transient overlays that should not push other surfaces around.
	pub exclusive_zone: i32,

	/// When `true`, the compositor sends keyboard events to this overlay
	/// without requiring a click first.
	pub keyboard_exclusive: bool,

	/// Interactive input region as a list of rects (logical pixels). Only
	/// these areas receive pointer/touch input; the rest passes through.
	/// `None` means the full surface receives input.
	pub input_region: Option<Vec<crate::types::Rect>>,

	/// Widget tree for this overlay.
	pub view: Element<Message>,

	/// Message sent when the overlay should be dismissed. The runtime
	/// fires it in three situations:
	///
	/// 1. The compositor sends `xdg_popup.popup_done` (xdg-popup mode)
	///    — typically when the user clicks outside the popup with the
	///    grab fully active.
	/// 2. The user presses pointer / touch on the main surface while
	///    the overlay is still mapped, and the press does not fall on
	///    the trigger rect identified by [`Self::anchor_widget_id`].
	///    This covers compositors (notably Mutter) that route the
	///    button to the parent surface instead of breaking the popup
	///    grab when the cursor was already over the parent.
	/// 3. The user presses Escape while at least one xdg-popup overlay
	///    is open.
	///
	/// The application is expected to flip its `is_open` flag (or
	/// equivalent) to `false` in `update()` so the next frame stops
	/// returning the spec from [`App::overlays`]. The runtime is
	/// idempotent if the message arrives more than once for the same
	/// open / close cycle.
	pub on_dismiss: Option<Message>,

	/// When set, the overlay is rendered as a Wayland **xdg-popup**
	/// anchored to the rect of the widget tagged with this
	/// [`WidgetId`](struct@crate::types::WidgetId) in the previous frame's layout — the
	/// standard mechanism for combo / context-menu / tooltip popups in
	/// `xdg-shell` applications. The compositor positions the popup
	/// adjacent to the anchor and is allowed to flip it (drop-up
	/// instead of drop-down) when there is not enough room.
	///
	/// When this field is `None`, the overlay is rendered as a
	/// [`wlr-layer-shell`](Layer) surface — the path used by shells,
	/// panels, lock screens and overlays that need full-surface
	/// coverage. In that mode `layer` / `anchor` / `exclusive_zone` /
	/// `keyboard_exclusive` carry the placement; for the popup mode
	/// they are ignored.
	pub anchor_widget_id: Option<crate::types::WidgetId>,
}

/// An input-transparent child surface composited over the main surface and
/// moved by the compositor.
///
/// Returned from [`App::subsurfaces`]. The runtime creates one `wl_subsurface`
/// per active spec, full-size over the main surface, with an **empty input
/// region** — all pointer/touch falls through to the main surface, so the host
/// keeps a single input/gesture model. The win is in the move: the content
/// buffer is rasterised only when [`content_version`](Self::content_version)
/// (or the surface size) changes, while [`x`](Self::x) / [`y`](Self::y)
/// changes only emit `wl_subsurface.set_position` + a parent commit — no
/// re-raster, no buffer re-upload. This makes an animated reveal/slide track
/// the finger at the compositor's compositing cost rather than the client's
/// raster cost.
pub struct SubsurfaceSpec<Message: Clone>
{
	/// Stable identifier, used to diff subsurfaces between frames.
	pub id: SubsurfaceId,

	/// Surface this subsurface is composited as a child of. Sized to that
	/// parent; [`x`](Self::x) / [`y`](Self::y) are relative to its top-left.
	pub parent: SubsurfaceParent,

	/// Widget tree for this subsurface. Should paint its own opaque
	/// background if it must cover the main surface beneath it.
	pub view: Element<Message>,

	/// Position of the subsurface relative to the parent's top-left, in
	/// layout (physical) pixels — the same space as [`App::on_resize`] and
	/// widget rects. The runtime divides by the surface scale to obtain the
	/// logical position it hands to the compositor. Animate this for a cheap
	/// compositor-side move.
	pub x: i32,
	pub y: i32,

	/// Content revision. Bump it whenever [`view`](Self::view) would paint
	/// differently; leave it unchanged for position-only updates so the
	/// runtime skips the re-raster and only repositions.
	pub content_version: u64,

	/// Render through GLES (so `backdrop-filter` glass works) rather than the
	/// software rasteriser. GLES is only worth it for content that actually
	/// uses the blur: it pays a per-surface EGL-surface creation (and a
	/// one-time shader compile) the cheap software path avoids, so a panel
	/// without glass should leave this `false`.
	pub gpu: bool,
}

/// What an app did with a back request. Returned by [`App::on_back`].
#[ derive( Debug, Clone, PartialEq ) ]
pub enum BackResponse<Message>
{
	/// There was something to go back from: deliver this message, which
	/// undoes the top-most piece of navigation state.
	Message( Message ),
	/// The request was handled outside the message loop — for hosts whose
	/// back stack lives elsewhere (an embedded Android runtime, a guest
	/// toolkit) and cannot be inspected ahead of time.
	Consumed,
	/// Nothing to go back to. The runtime applies [`App::back_at_root`].
	Unhandled,
}

/// What a back request does once the app has nothing left to go back to.
/// Returned by [`App::back_at_root`].
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum BackAtRoot
{
	/// Minimise the window (`xdg_toplevel.set_minimized`); the app keeps
	/// running and the compositor shows whatever was behind it.
	Minimize,
	/// Close the window, through [`App::on_close_requested`].
	Close,
	/// Do nothing.
	Ignore,
}

/// A key press or release as [`App::on_raw_key_event`] reports it.
#[ derive( Debug, Clone ) ]
pub struct RawKey
{
	pub keysym:  Keysym,
	pub keycode: u32,
	pub pressed: bool,
	pub ctrl:    bool,
	pub shift:   bool,
	pub alt:     bool,
	/// What the key types once dead keys and compose sequences are applied; `None` on release, halfway through a sequence and for keys that type nothing.
	pub text:    Option<String>,
}

/// A mouse button, as [`App::on_mouse_button`] reports it.
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum MouseButton
{
	Left,
	Middle,
	Right,
}

/// A mouse button pressed or released, as [`App::on_mouse_button`] reports it.
#[ derive( Debug, Clone, Copy ) ]
pub struct MouseButtonEvent
{
	pub button:  MouseButton,
	/// In physical pixels of the surface under the pointer, as [`App::on_pointer_move`] reports them.
	pub x:       f32,
	pub y:       f32,
	pub pressed: bool,
	pub ctrl:    bool,
	pub shift:   bool,
	pub alt:     bool,
}

/// Which of the two selections an app reads, through [`App::take_paste_request`].
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum SelectionKind
{
	/// What Copy put there, pasted with Ctrl+V.
	Clipboard,
	/// The text last selected, pasted with the middle button.
	Primary,
}

/// What an app asks a text field to do, through [`App::take_text_command`], as its menu or its search would: the field's cursor and selection are the runtime's, which the app does not see.
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum TextCommand
{
	/// Put the selection in the clipboard.
	Copy,
	/// Put the selection in the clipboard and delete it.
	Cut,
	/// Type the clipboard over the selection.
	Paste,
	SelectAll,
	/// Select the bytes `start..end` of the value, the cursor at `end`, and scroll a multiline field to them; `start == end` only places the cursor. Offsets beyond the value are taken back to its end, and into a character to its start.
	Select { start: usize, end: usize },
	/// [`Self::Select`] leaving the focus where it is, as a search does while its own field keeps the keys; a multiline field without the focus shows its selection dimmed.
	Reveal { start: usize, end: usize },
}

/// Trait that application types must implement to integrate with ltk.
pub trait App: 'static
{
	/// The message type produced by this application.
	type Message: Clone + 'static;

	/// Build the widget tree for the current frame.
	fn view( &self ) -> Element<Self::Message>;

	/// Apply a message to the application state.
	fn update( &mut self, msg: Self::Message );

	/// Stable application identifier, reverse-DNS style
	/// (`"net.liberux.settings"`, `"io.eydos.Calls"`), constant for the
	/// life of the process.
	///
	/// The runtime uses it in three places:
	///
	/// * `xdg_toplevel.set_app_id` on the main window, so the compositor,
	///   the dock and the task switcher can match the window to its
	///   `.desktop` entry (use the desktop file's name minus `.desktop`,
	///   or its `StartupWMClass`);
	/// * the accessibility tree — AccessKit / AT-SPI2 report it as the
	///   application name;
	/// * the on-disk session directory `$XDG_STATE_HOME/<app_id>/`
	///   where [`save_state`](Self::save_state) is persisted.
	///
	/// It must not be empty and must not contain `/`; the runtime then
	/// disables session persistence and logs once. Layer-shell and
	/// session-lock components still return one (it names them in the
	/// a11y tree), even though they never get a toplevel. The `app_id`
	/// element of the deprecated [`window_config`](Self::window_config)
	/// tuple is ignored in favour of this method — keep both pointing at
	/// the same `const`.
	///
	/// ```rust
	/// # use ltk::{ App, Element, text };
	/// # #[ derive( Clone ) ] enum Msg {}
	/// # struct Notes;
	/// const APP_ID: &str = "net.example.Notes";
	///
	/// impl App for Notes
	/// {
	/// #     type Message = Msg;
	/// #     fn view( &self ) -> Element<Msg> { text( "" ).into() }
	/// #     fn update( &mut self, _: Msg ) {}
	/// #     fn save_state( &self ) -> Option<Vec<u8>> { None }
	/// #     fn restore_state( &mut self, _: Vec<u8> ) {}
	///     fn app_id( &self ) -> &str { APP_ID }
	/// }
	/// ```
	fn app_id( &self ) -> &str;

	/// Serialize the part of the state worth surviving a restart.
	///
	/// Return the bytes the runtime should persist, or `None` when there
	/// is nothing to bring back (a shell panel, a lock screen, a
	/// stateless tool). The encoding is the app's own — JSON, CBOR, a
	/// hand-rolled line format — ltk never inspects it and puts no serde
	/// bound on the trait. Keep it small and cheap: the runtime calls
	/// this
	///
	/// * every ~30 s while the app runs, touching the disk only when
	///   the bytes differ from the last save (a UI-only change that
	///   round-trips to identical bytes costs one comparison);
	/// * when the window closes — after
	///   [`on_close_requested`](Self::on_close_requested) allowed it or
	///   [`requested_exit`](Self::requested_exit) returned `true`;
	/// * on `SIGTERM` / `SIGINT`, which the runtime turns into a clean
	///   exit of the event loop instead of letting the process die.
	///
	/// The bytes are written atomically (temp file + rename, mode
	/// `0600`) to `$XDG_STATE_HOME/<app_id>/state.bin`
	/// (`~/.local/state/<app_id>/state.bin` when the variable is unset)
	/// next to a `session.json` holding the compositor's
	/// `xdg-session-management-v1` session id and a clean-exit marker.
	/// Returning `None` removes a stale `state.bin`. Only
	/// [`ShellMode::Window`] apps (and the deprecated
	/// [`window_config`](Self::window_config) path) are persisted;
	/// layer and session-lock surfaces are skipped silently, so shell
	/// components simply return `None`.
	///
	/// The file is plain on disk: never put secrets in it (passwords
	/// belong to the secure-mode `text_edit` and its wiped buffers),
	/// and keep large blobs (images, caches) elsewhere. The signal
	/// handler is installed process-wide when [`run`](crate::run) is
	/// entered, so the clean exit holds no matter which thread receives
	/// the signal or when it was started.
	///
	/// [`restore_state`](Self::restore_state) explains when — and when
	/// not — the bytes come back.
	///
	/// ```rust
	/// use ltk::{ App, Element, text };
	/// use serde::{ Deserialize, Serialize };
	///
	/// #[ derive( Clone ) ]
	/// enum Msg { Tab( usize ) }
	///
	/// #[ derive( Serialize, Deserialize ) ]
	/// struct Persisted { version: u32, tab: usize, draft: String }
	///
	/// struct Editor { tab: usize, draft: String, cursor_blink: bool }
	///
	/// impl App for Editor
	/// {
	///     type Message = Msg;
	///
	///     fn app_id( &self ) -> &str { "net.example.Editor" }
	///
	///     fn save_state( &self ) -> Option<Vec<u8>>
	///     {
	///         // Only what a relaunch needs — the blink phase stays out.
	///         let p = Persisted { version: 1, tab: self.tab, draft: self.draft.clone() };
	///         serde_json::to_vec( &p ).ok()
	///     }
	///
	///     fn restore_state( &mut self, state: Vec<u8> )
	///     {
	///         // Tolerate an older or corrupt file: keep the defaults.
	///         if let Ok( p ) = serde_json::from_slice::<Persisted>( &state )
	///         {
	///             self.tab   = p.tab;
	///             self.draft = p.draft;
	///         }
	///     }
	/// #   fn view( &self ) -> Element<Msg> { text( self.draft.clone() ).into() }
	/// #   fn update( &mut self, msg: Msg ) { let Msg::Tab( t ) = msg; self.tab = t; }
	/// }
	/// ```
	fn save_state( &self ) -> Option<Vec<u8>>;

	/// Re-apply bytes previously returned by [`save_state`](Self::save_state).
	///
	/// Called at most once per process, synchronously inside
	/// [`run`](crate::run) / [`try_run`](crate::try_run), before the
	/// window is created and before the first [`view`](Self::view) — the
	/// first frame already shows the restored state. It is **not**
	/// called on an ordinary launch unless
	/// [`restore_on_launch`](Self::restore_on_launch) says so. The runtime
	/// restores app state only when
	///
	/// * the process is relaunched as part of a session restore: the
	///   shell sets `LTK_SESSION_RESTORE=1` in the environment (the
	///   runtime removes the variable before the app can spawn
	///   children); or
	/// * the previous run of this `app_id` did not exit cleanly (crash,
	///   `SIGKILL`, power loss): its `session.json` still says
	///   `clean_exit: false`.
	///
	/// This mirrors Android's saved-instance-state contract: opening the
	/// app from the launcher gives a fresh instance, coming back after
	/// the system killed it lands where the user left off. Window
	/// geometry (size, position, workspace) is separate — the compositor
	/// restores it through `xdg-session-management-v1` on *every*
	/// launch, plain ones included, using the session id ltk stores.
	///
	/// `state` is exactly what `save_state` produced, possibly by an
	/// older build: validate, version, and fall back to defaults instead
	/// of panicking. Nothing is called when no state file exists or the
	/// app returned `None` last time. Shell components never receive
	/// this call and implement it as a no-op.
	///
	/// See [`save_state`](Self::save_state) for the file layout and a
	/// worked example.
	fn restore_state( &mut self, state: Vec<u8> );

	/// Whether an ordinary launch also restores the saved state.
	///
	/// By default [`restore_state`](Self::restore_state) follows Android's
	/// saved-instance-state contract: the state comes back after a crash
	/// or a session restore, and a launch from the launcher starts fresh.
	/// Some apps keep state that the user expects to find on every launch,
	/// however the last run ended, as Android browsers keep their tabs in
	/// their own storage even when closed from the app switcher. Such an
	/// app returns `true`, and the runtime then hands the saved bytes to
	/// `restore_state` on a plain launch too. Nothing else changes: saving,
	/// the file layout and the window geometry are the same either way.
	///
	/// Asked once per process, inside [`run`](crate::run) /
	/// [`try_run`](crate::try_run), right before `restore_state` would be
	/// called and before the window exists, so the answer can only come
	/// from the state the app was constructed with, for instance a user
	/// setting read in `main`. It is not asked, and nothing is restored,
	/// when persistence is off: no usable [`app_id`](Self::app_id),
	/// another live instance holding the state directory, or a layer or
	/// session-lock surface. With no state file, or after `save_state`
	/// returned `None`, `restore_state` is not called either.
	///
	/// Since `restore_state` now runs on launches that carry their own
	/// intent, such as a file or URL on the command line, it should merge
	/// that intent into the restored state rather than let the restore
	/// replace it. What `save_state` returns then outlives every exit, so
	/// leave out what the user would expect to be forgotten on closing
	/// the app (a private window, a half-typed password).
	///
	/// Default `false`.
	///
	/// ```rust
	/// # use ltk::{ App, Element, text };
	/// # #[ derive( Clone ) ] enum Msg {}
	/// struct Browser { tabs: Vec<String>, keep_tabs: bool, opened: Option<String> }
	///
	/// impl App for Browser
	/// {
	/// #     type Message = Msg;
	/// #     fn app_id( &self ) -> &str { "net.example.Browser" }
	/// #     fn view( &self ) -> Element<Msg> { text( "" ).into() }
	/// #     fn update( &mut self, _: Msg ) {}
	///     fn save_state( &self ) -> Option<Vec<u8>>
	///     {
	///         Some( self.tabs.join( "\n" ).into_bytes() )
	///     }
	///
	///     fn restore_state( &mut self, state: Vec<u8> )
	///     {
	///         let Ok( text ) = String::from_utf8( state ) else { return };
	///         self.tabs = text.lines().map( String::from ).collect();
	///         // The URL this launch was asked to open goes after the restored tabs.
	///         self.tabs.extend( self.opened.take() );
	///     }
	///
	///     fn restore_on_launch( &self ) -> bool { self.keep_tabs }
	/// }
	/// ```
	fn restore_on_launch( &self ) -> bool { false }

	/// Tell the runtime which surfaces *could* have changed visibly as a
	/// result of [`update`](Self::update) being called with this message.
	///
	/// Default is [`InvalidationScope::All`] — every surface is redrawn.
	/// A shell that knows, for example, that a `SetVolume` message only
	/// affects its quick-settings overlay can return
	/// `InvalidationScope::Only( vec![ SurfaceTarget::Overlay( quick_id ) ] )`
	/// to skip pointless work on other surfaces.
	///
	/// Called *before* [`update`](Self::update) (so it sees the message but
	/// not the post-update state). Side-effect free: must not mutate `self`.
	fn invalidate_after( &self, _msg: &Self::Message ) -> InvalidationScope
	{
		InvalidationScope::All
	}

	/// Describe the auxiliary overlay surfaces that should be active this
	/// frame. Each entry becomes its own Wayland layer-shell surface
	/// independent from the main surface returned by [`view`](Self::view).
	///
	/// Return an empty `Vec` (the default) to disable multi-surface support —
	/// the app then renders only onto its main surface.
	///
	/// The runtime diffs the list across frames using [`OverlaySpec::id`]:
	/// stable IDs are kept alive, new IDs cause a surface to be created, and
	/// IDs that disappear cause the surface to be destroyed.
	fn overlays( &self ) -> Vec<OverlaySpec<Self::Message>> { Vec::new() }

	/// Title of a [`Layer::Window`] overlay, shown in its decoration and
	/// in the compositor's window lists. Default: the [`app_id`](Self::app_id).
	fn overlay_title( &self, _id: OverlayId ) -> Option<String> { None }

	/// wlr-layer-shell namespace of a layer overlay, so the compositor can
	/// tell it apart from the rest. Read when the surface is created.
	/// Default: `"ltk-overlay"`.
	fn overlay_namespace( &self, _id: OverlayId ) -> Option<&'static str> { None }

	/// Describe the input-transparent child surfaces composited over the main
	/// surface this frame. Each becomes a `wl_subsurface` the compositor moves
	/// by position; see [`SubsurfaceSpec`]. Diffed across frames by
	/// [`SubsurfaceSpec::id`]. Default empty.
	fn subsurfaces( &self ) -> Vec<SubsurfaceSpec<Self::Message>> { Vec::new() }

	/// Return any pending messages from external sources (timers, async, etc.).
	fn poll_external( &mut self ) -> Vec<Self::Message> { vec![] }

	/// Tags for which the app wants a fresh `xdg-activation-v1` token this
	/// iteration. Drained once per loop; each tag is echoed back verbatim
	/// through [`App::on_activation_token`] once the compositor issues the
	/// token, so the app can hand it to a child it is about to spawn via the
	/// `$XDG_ACTIVATION_TOKEN` launch convention. Default none.
	fn take_activation_requests( &mut self ) -> Vec<String> { Vec::new() }

	/// Deliver a token issued for an earlier [`App::take_activation_requests`]
	/// tag. `tag` is the string the app handed out; `token` is the opaque
	/// activation token to place in the launched child's environment.
	fn on_activation_token( &mut self, _tag: String, _token: String ) -> Option<Self::Message> { None }

	/// Called once, immediately after the first buffer for the main surface
	/// has been rendered and committed to the compositor. Note: this is the
	/// client-side commit, not the compositor's present — under VT switching
	/// the actual present can be deferred (no DRM master yet), so a handoff
	/// signal that fires here is enough to tell a parent "ready to be
	/// presented as soon as my VT becomes active".
	fn on_first_frame_committed( &mut self ) {}

	/// Called every time a buffer for the main surface has been rendered and
	/// committed, before the subsurfaces are reconciled for the same
	/// iteration. Lets a host sequence a subsurface change after the main
	/// frame it depends on: a subsurface retired here goes away only once
	/// the main frame that replaces it has been sent.
	fn on_main_frame_committed( &mut self ) {}

	/// Called every time a buffer for the overlay `id` has been rendered and
	/// committed.
	fn on_overlay_frame_committed( &mut self, _id: OverlayId ) {}

	/// Called every time the content of the subsurface `id` has been
	/// rasterised and committed (first raster, resize or a new
	/// `content_version`), before the parent commit that maps it.
	fn on_subsurface_committed( &mut self, _id: SubsurfaceId ) {}

	/// Called when the surface is asked to close (compositor request, titlebar button,
	/// layer-shell closed event). Return `true` to allow the application to exit,
	/// or `false` to cancel.
	///
	/// Default: `true` (always close).
	fn on_close_requested( &mut self ) -> bool { true }

	/// Called when tapping/clicking outside any widget.
	fn on_tap( &mut self ) -> Option<Self::Message> { None }

	/// Called on key press when no text input is focused.
	fn on_key( &mut self, _keysym: Keysym ) -> Option<Self::Message> { None }

	/// Called on key press with modifier state. Override this instead of
	/// `on_key` when you need Ctrl/Shift/Alt awareness.
	fn on_key_with_modifiers( &mut self, keysym: Keysym, _ctrl: bool, _shift: bool ) -> Option<Self::Message>
	{
		self.on_key( keysym )
	}

	/// Called on a back request — the shell's back button or gesture
	/// (delivered as the `XF86Back` key) or a mouse's back button — once
	/// the runtime has nothing of its own left to close.
	///
	/// Back peels one layer per request, top-most first:
	///
	/// 1. transient UI the runtime owns — the built-in context menu, open
	///    xdg-popup overlays, a text selection, the top-most pressable
	///    carrying an `on_escape` (a [`dialog`](crate::dialog)'s cancel);
	/// 2. text-input focus — dropping it also retires the on-screen
	///    keyboard on compositors that did not close it themselves;
	/// 3. **this hook** — the app's own navigation state;
	/// 4. [`Self::on_key_with_modifiers`] with `Keysym::XF86_Back`, for
	///    apps that predate this hook;
	/// 5. [`Self::back_at_root`].
	///
	/// Return [`BackResponse::Message`] with the message that undoes the
	/// top-most piece of *navigation state* — the part of the model that
	/// says where the user is: the open panel, the current screen, the
	/// position in a history. Derive the answer from the model every time
	/// instead of keeping a separate list of things to undo: a list drifts
	/// the first time the user leaves a screen some other way (its own
	/// close button, a link), while the model cannot disagree with itself.
	///
	/// Navigation state is also what [`Self::save_state`] should persist.
	/// Keeping the two the same is what makes back behave identically
	/// after a session restore or a crash: the restored model yields the
	/// same answers here, with nothing extra to serialise.
	/// [`NavStack`](crate::NavStack) packages that pattern for the common
	/// multi-screen app. `docs/navigation.md` covers the model at length.
	///
	/// `Escape` is a different request: it only runs step 1, drops the
	/// focus and reaches [`Self::on_key_with_modifiers`]. It never
	/// navigates and never leaves the app.
	///
	/// ```rust
	/// # use ltk::{ App, BackResponse, Element, text };
	/// # #[ derive( Clone, Copy, PartialEq ) ] enum Screen { List, Detail }
	/// #[ derive( Clone ) ]
	/// enum Msg { CloseSearch, Show( Screen ) }
	///
	/// struct Notes { screen: Screen, searching: bool }
	///
	/// impl App for Notes
	/// {
	/// #   type Message = Msg;
	/// #   fn app_id( &self ) -> &str { "net.example.Notes" }
	/// #   fn save_state( &self ) -> Option<Vec<u8>> { None }
	/// #   fn restore_state( &mut self, _: Vec<u8> ) {}
	/// #   fn view( &self ) -> Element<Msg> { text( "" ).into() }
	/// #   fn update( &mut self, _: Msg ) {}
	///     fn on_back( &mut self ) -> BackResponse<Msg>
	///     {
	///         if self.searching { return BackResponse::Message( Msg::CloseSearch ); }
	///         match self.screen
	///         {
	///             Screen::Detail => BackResponse::Message( Msg::Show( Screen::List ) ),
	///             Screen::List   => BackResponse::Unhandled,
	///         }
	///     }
	/// }
	/// ```
	fn on_back( &mut self ) -> BackResponse<Self::Message> { BackResponse::Unhandled }

	/// What a back request does when [`Self::on_back`] had nothing to go
	/// back to. Default: [`BackAtRoot::Minimize`] — the window leaves the
	/// screen and the app keeps its state, the way a root activity behaves
	/// on Android.
	///
	/// Only applies to [`ShellMode::Window`] surfaces; layer-shell and
	/// session-lock surfaces never react to back at the root.
	fn back_at_root( &self ) -> BackAtRoot { BackAtRoot::Minimize }

	/// Called when a sufficient upward swipe gesture is detected.
	///
	/// Return a message to handle the swipe (e.g., opening an overview).
	/// The gesture is recognized when the user drags upward by at least
	/// `swipe_threshold()` × screen height and then releases.
	fn on_swipe_up( &mut self ) -> Option<Self::Message> { None }

	/// Called during an upward swipe gesture with progress ≥ 0.0.
	///
	/// Use this to create follow-the-finger animations. `progress` starts at 0.0
	/// when the drag begins and increases as the finger moves upward, reaching 1.0
	/// when the drag distance equals `swipe_threshold()` × screen height. It is
	/// **not** clamped at 1.0 — the value keeps growing if the finger drags further
	/// so that follow-the-finger panels can continue tracking the finger all the way
	/// up the screen. Clamp inside the handler if you need a bounded `[0, 1]` range
	/// for a visual indicator.
	///
	/// When the user releases without completing the gesture, this method is called
	/// once more with `progress = 0.0` to signal cancellation.
	fn on_swipe_progress( &mut self, _progress: f32 ) {}

	/// Called when a sufficient downward swipe gesture is detected.
	///
	/// Return a message to handle the swipe (e.g., toggling quick settings).
	/// The gesture is recognized when the user drags downward by at least
	/// `swipe_down_threshold()` × screen height and then releases.
	fn on_swipe_down( &mut self ) -> Option<Self::Message> { None }

	/// Called during a downward swipe gesture with progress ≥ 0.0.
	///
	/// Use this to create follow-the-finger animations. `progress` starts at 0.0
	/// when the drag begins and increases as the finger moves downward, reaching
	/// 1.0 when the drag distance equals `swipe_down_threshold()` × screen height.
	/// It is **not** clamped at 1.0 — the value keeps growing if the finger drags
	/// further so that follow-the-finger panels can continue tracking the finger
	/// all the way down the screen. Clamp inside the handler if you need a
	/// bounded `[0, 1]` range for a visual indicator.
	///
	/// When the user releases without completing the gesture, this method is called
	/// once more with `progress = 0.0` to signal cancellation.
	fn on_swipe_down_progress( &mut self, _progress: f32 ) {}

	/// Fraction of screen height required to trigger [`on_swipe_up`](Self::on_swipe_up).
	///
	/// Default: `0.6` (60% of screen height). Lower values make the gesture easier
	/// to trigger; higher values require more vertical travel.
	fn swipe_threshold( &self ) -> f32 { 0.6 }

	/// Fraction of screen height required to trigger [`on_swipe_down`](Self::on_swipe_down).
	///
	/// Default: `0.15` (15% of screen height). Typically lower than `swipe_threshold()`
	/// because downward swipes are often initiated from a small UI element like a top bar.
	fn swipe_down_threshold( &self ) -> f32 { 0.15 }

	/// Top-edge band where a downward swipe may originate, as a fraction of
	/// screen height. Presses below this band never fire
	/// [`on_swipe_down`](Self::on_swipe_down) nor
	/// [`on_swipe_down_progress`](Self::on_swipe_down_progress).
	///
	/// Default: `1.0` (entire screen — any starting point is accepted).
	/// Set to a small value like `0.05` to restrict the gesture to the top
	/// edge, matching the usual system-panel pull-down UX.
	fn swipe_down_edge( &self ) -> f32 { 1.0 }

	/// Called while a vertical `scroll` is pinned at
	/// its top and the finger keeps pulling down. `progress` is the
	/// accumulated overscroll as a fraction of the surface height (≥ 0.0,
	/// unbounded). Use it to drive a pull-from-top-to-dismiss panel that
	/// tracks the finger.
	fn on_overscroll_down_progress( &mut self, _progress: f32 ) {}

	/// Called when the finger releases after a top overscroll pull-down.
	/// `committed` is `true` when the pull passed
	/// [`overscroll_dismiss_threshold`](Self::overscroll_dismiss_threshold).
	fn on_overscroll_down( &mut self, _committed: bool ) -> Option<Self::Message> { None }

	/// Fraction of surface height a top overscroll pull-down must exceed to
	/// commit a dismiss on release. Default: `0.25`.
	fn overscroll_dismiss_threshold( &self ) -> f32 { 0.25 }

	/// Called when a sufficient leftward swipe gesture is detected.
	///
	/// Return a message to handle the swipe (e.g., paging to the next
	/// homescreen). Fires on release when the user dragged left by at least
	/// `swipe_horizontal_threshold()` × screen width. Unlike vertical swipes,
	/// horizontal swipes survive starting the press on an interactive widget:
	/// once the drag distance crosses an 8 px threshold the press is promoted
	/// to a horizontal drag and no tap will fire at release.
	fn on_swipe_left( &mut self ) -> Option<Self::Message> { None }

	/// Called when a sufficient rightward swipe gesture is detected.
	/// Mirror of [`on_swipe_left`](Self::on_swipe_left) for the other direction.
	fn on_swipe_right( &mut self ) -> Option<Self::Message> { None }

	/// Called during a horizontal swipe with signed progress. Negative values
	/// mean the finger has moved left, positive values mean right. The value
	/// is `dx / (threshold * width)`, so ±1.0 marks the commit threshold;
	/// it is **not** clamped so follow-the-finger panels can keep tracking
	/// past the threshold. When the user releases without completing the
	/// gesture this method is called once more with `0.0` to signal
	/// cancellation.
	fn on_swipe_horizontal_progress( &mut self, _progress: f32 ) {}

	/// Fraction of screen width required to commit [`App::on_swipe_left`] /
	/// [`App::on_swipe_right`]. Default: `0.5` (half the screen). A shell that
	/// wants easier paging can lower this; one that wants to avoid
	/// accidental pages can raise it.
	fn swipe_horizontal_threshold( &self ) -> f32 { 0.5 }

	/// Duration a press must remain stationary (within tolerance) before the
	/// widget's long-press message fires and the gesture transitions into
	/// drag mode. Default: `500 ms`.
	fn long_press_duration( &self ) -> std::time::Duration
	{
		std::time::Duration::from_millis( 500 )
	}

	/// Called on every pointer motion once a long-press has fired and the
	/// gesture has entered drag mode. `x`, `y` are in physical pixels of the
	/// surface that owned the original press.
	fn on_drag_move( &mut self, _x: f32, _y: f32 ) {}

	/// Called on release once a long-press has fired. Return a message to
	/// handle the drop (e.g., commit the drop target). `x`, `y` are in
	/// physical pixels of the surface that owned the original press. The
	/// regular tap / swipe handling is suppressed for this gesture.
	fn on_drop( &mut self, _x: f32, _y: f32 ) -> Option<Self::Message> { None }

	/// Called when a text-input widget gains or loses focus.
	fn on_text_input_focused( &mut self, _active: bool ) {}

	/// `Some( serial )` holds the input method for a text field ltk does not
	/// own (an editable in an embedded web view) while no ltk text widget is
	/// focused; a new `serial` renews the request, e.g. on a press on the field.
	fn external_text_input( &self ) -> Option<u64> { None }

	/// What the field held by [`Self::external_text_input`] is for; `Terminal` gives the on-screen keyboard its row of terminal keys.
	fn external_text_purpose( &self ) -> crate::osk::Purpose { crate::osk::Purpose::Normal }

	/// Text committed by the input method while [`Self::external_text_input`] holds it.
	fn on_external_text_commit( &mut self, _text: &str ) {}

	/// Delete around the external field's cursor, in UTF-8 bytes as `zwp_text_input_v3` counts.
	fn on_external_text_delete( &mut self, _before: u32, _after: u32 ) {}

	/// `true` to draw ltk's own on-screen keyboard under a focused text field even when the compositor offers an input method; it is drawn regardless when none is offered, or with `LTK_BUILTIN_OSK=1`.
	fn builtin_keyboard( &self ) -> bool { false }

	/// Translate a Wayland `ext-foreign-toplevel-list-v1` event into an
	/// app message. The runtime binds the protocol globally and forwards
	/// every open / close it sees here; apps that ignore window state
	/// leave the default (return `None`) and pay nothing.
	///
	/// The `id` field is the Wayland object id of the toplevel handle —
	/// unique within the session, stable for the handle's lifetime, the
	/// same value coming in on `Closed` as the matching `Opened`.
	/// `app_id` on `Opened` is the toplevel's `app_id` event (may be
	/// empty if the compositor never sent one before the first `done`).
	fn on_toplevel_event( &self, _event: ToplevelEvent ) -> Option<Self::Message>
	{
		None
	}

	/// A directory the app listed through [`crate::files::list`] changed: in a browser, through another client of the desktop. Natively not reported yet.
	fn on_files_changed( &self, _dir: &std::path::Path ) -> Option<Self::Message>
	{
		None
	}

	/// The folders of the user's computer mounted in a browser, when the app connects and whenever one comes or goes. Natively there are none.
	fn on_mounts_changed( &self, _mounts: &[ crate::files::Mount ] ) -> Option<Self::Message>
	{
		None
	}

	/// The files a browser's desktop launched the app to open. Natively they come in the app's arguments instead.
	fn on_open_files( &self, _paths: Vec<std::path::PathBuf> ) -> Option<Self::Message>
	{
		None
	}

	/// Return `Some(id)` once to focus the widget with that [`WidgetId`](struct@crate::types::WidgetId).
	/// The app must return `None` after the first call.
	///
	/// The runtime waits a few drawn frames for the widget to appear, so a
	/// request made from the `update` that adds the widget to the view is
	/// honoured, and a target scrolled out of a viewport is brought into
	/// view before it is focused. A widget that never appears is dropped.
	fn take_focus_request( &mut self ) -> Option<crate::types::WidgetId> { None }

	/// Return `true` once to drop the keyboard focus, which folds the on-screen keyboard; a [`take_focus_request`](Self::take_focus_request) in the same cycle wins.
	fn take_blur_request( &mut self ) -> bool { false }

	/// Return `Some( text )` once to put it in the clipboard, for other applications as well.
	fn take_clipboard_request( &mut self ) -> Option<String> { None }

	/// Return `Some( text )` once to make it the primary selection, which the middle button pastes, here and in other applications.
	fn take_primary_request( &mut self ) -> Option<String> { None }

	/// Return `Some( kind )` once to have [`Self::on_paste`] called with the text that selection holds.
	fn take_paste_request( &mut self ) -> Option<SelectionKind> { None }

	/// The text of the selection [`Self::take_paste_request`] asked for; not called when it is empty.
	fn on_paste( &mut self, _text: &str ) {}

	/// Return `Some( ( id, command ) )` once to have the text field with
	/// that [`WidgetId`](struct@crate::types::WidgetId) take the focus and do
	/// `command`, after the frame that lays it out is drawn. A field that
	/// is not on screen then drops the command.
	fn take_text_command( &mut self ) -> Option<( crate::types::WidgetId, TextCommand )> { None }

	/// Called on every pointer motion (mouse move, button press, button
	/// release) and on every primary-finger touch down and motion. `x`, `y` are in physical pixels of the main surface,
	/// the same coordinate space as widget rects. Default: no-op.
	///
	/// Useful for embedding components that need to know the live
	/// pointer position without going through a full
	/// [`crate::widget::external::ExternalSource`] / `WidgetHandlers`
	/// dispatch path — for example forwarding clicks into an embedded
	/// WPE WebView.
	fn on_pointer_move( &mut self, _x: f32, _y: f32 ) {}

	/// Mouse motion over `target`, in physical pixels of that surface, or
	/// `None` when the pointer leaves it. Touch never reports here.
	fn on_pointer_hover( &mut self, _target: SurfaceTarget, _position: Option<( f32, f32 )> ) {}

	/// The `( rect, corner radius )` of every [`Container::blur_behind`](crate::widget::container::Container::blur_behind)
	/// drawn on `target`, in its physical pixels, after a frame where they
	/// changed: for a shell to tell its compositor what to blur.
	fn on_blur_regions( &mut self, _target: SurfaceTarget, _regions: &[ ( crate::types::Rect, f32 ) ] ) {}

	/// Called on a wheel / touchpad scroll event whose position does
	/// not fall inside any LTK [`scroll`](crate::scroll) viewport. `x`,
	/// `y` are in physical pixels (same coordinate space as
	/// [`Self::on_pointer_move`]); `dx`, `dy` are scroll deltas in the
	/// raw axis units the compositor delivered (`AxisSource::Wheel`
	/// gives ~10 px ticks, touchpads give continuous values). Default:
	/// no-op.
	///
	/// Useful for embeddings that take over scrolling for their own
	/// content — for example forwarding the event to a WPE view that
	/// owns a scrollable web page — or for wheel-driven view state such
	/// as a stepped carousel. The runtime rebuilds and repaints after
	/// the hook returns, so state mutated here shows immediately.
	fn on_pointer_axis( &mut self, _x: f32, _y: f32, _dx: f32, _dy: f32 ) {}

	/// Called before [`Self::on_pointer_axis`] for a scroll event from a
	/// wheel or any device that reports discrete detents, with the number
	/// of detents on each axis (fractional on high-resolution wheels;
	/// positive is right / down). Return `true` to consume it; `false`, the
	/// default, lets the same event reach `on_pointer_axis` in raw units.
	fn on_pointer_wheel( &mut self, _x: f32, _y: f32, _notches_x: f32, _notches_y: f32 ) -> bool { false }

	/// Raw multi-touch callbacks. Default: no-op.
	///
	/// The first finger to land becomes the *primary slot* and is fed
	/// through the regular gesture machine — `on_pointer_*`, swipe,
	/// scroll, long-press, drag-and-drop all run from that slot. Every
	/// additional finger fires `on_touch_down` / `on_touch_move` /
	/// `on_touch_up` instead, with `id` matching the `wl_touch.id`
	/// the compositor delivered.
	///
	/// Use this for app-defined multi-finger gestures (pinch-zoom,
	/// two-finger pan in a canvas, parallel keyboard keys) that the
	/// built-in single-slot machine cannot model. `(x, y)` are in
	/// physical pixels, matching the coordinate space of
	/// [`Self::on_pointer_move`].
	///
	/// When [`Self::claims_raw_touch`] returns `true` the primary
	/// finger arrives here as well, instead of driving the gesture
	/// machine.
	fn on_touch_down( &mut self, _id: i64, _x: f32, _y: f32 ) {}
	/// See [`Self::on_touch_down`].
	fn on_touch_move( &mut self, _id: i64, _x: f32, _y: f32 ) {}
	/// See [`Self::on_touch_down`]. `x`, `y` are the last known
	/// position of the finger (`wl_touch.up` does not carry one).
	fn on_touch_up( &mut self, _id: i64, _x: f32, _y: f32 ) {}

	/// Return `true` to receive the *primary* finger through the raw
	/// [`Self::on_touch_down`] / move / up stream as well, bypassing
	/// the built-in single-slot gesture machine entirely — widget
	/// presses, taps and swipes stop working on touch. For apps whose
	/// surface is one self-contained input consumer (an embedded
	/// WebView, a game canvas) that needs every finger verbatim.
	fn claims_raw_touch( &self ) -> bool { false }

	/// Per-press variant of [`Self::claims_raw_touch`]: return `true` to
	/// take the finger landing at `(x, y)` (physical pixels of the main
	/// surface) through the raw [`Self::on_touch_down`] / move / up stream,
	/// while fingers landing elsewhere keep driving the widget gesture
	/// machine. For apps that embed a self-contained input consumer (a
	/// WebView) next to regular widgets. A claimed press clears the widget
	/// focus. Only consulted for the main surface.
	fn claims_raw_touch_at( &self, _x: f32, _y: f32 ) -> bool { false }

	/// Pointer of a cross-application drag-and-drop entered or moved
	/// inside the main surface. `(x, y)` is in logical pixels.
	fn on_drop_motion( &mut self, _x: f32, _y: f32 ) {}
	/// The drag left without dropping.
	fn on_drop_leave( &mut self ) {}
	/// External drop payload landed on the surface. `mime` is the
	/// best mime the source offered (text/uri-list, text/plain, …)
	/// and `text` is the decoded payload (UTF-8). `(x, y)` is the
	/// release position in logical pixels.
	fn on_drop_received( &mut self, _x: f32, _y: f32, _mime: &str, _text: &str ) {}

	/// Called on every left-button mouse press / release, and on every
	/// primary-finger touch down / up, before the regular gesture machine fires. `pressed = true` for press,
	/// `false` for release. `(x, y)` are in physical pixels (same
	/// coordinate space as [`Self::on_pointer_move`]). Default: no-op.
	///
	/// Lets embeddings see the raw button transitions without going
	/// through LTK's tap/long-press/drag classification — needed for
	/// forwarding clicks AND drags to an embedded view, since the tap
	/// classifier collapses press+release into a single event.
	fn on_pointer_button( &mut self, _x: f32, _y: f32, _pressed: bool ) {}

	/// A secondary-button press that no widget of ltk's own answered, in physical pixels. Default: no-op.
	fn on_pointer_secondary( &mut self, _x: f32, _y: f32 ) {}

	/// A middle-button press, in physical pixels. Default: no-op.
	fn on_pointer_middle( &mut self, _x: f32, _y: f32 ) {}

	/// Every press and release of the left, middle and right buttons, with the modifiers held, before ltk handles it: for an
	/// app that hands the mouse on, as a terminal does to a program that asks for it. Default: no-op.
	fn on_mouse_button( &mut self, _event: &MouseButtonEvent ) {}

	/// The modifiers held changed, for an app that needs them with the wheel or a motion, which do not carry them. Default: no-op.
	fn on_modifiers( &mut self, _ctrl: bool, _shift: bool, _alt: bool ) {}

	/// The window lost the keyboard, so no release will come for the keys held: for an app that repeats keys itself. Default: no-op.
	fn on_keyboard_leave( &mut self ) {}

	/// Called on every keyboard event (press *and* release) before the
	/// regular focus-aware dispatch ([`Self::on_key`] /
	/// [`Self::on_key_with_modifiers`]) runs. Default: no-op.
	///
	/// `keycode` is the raw hardware scancode straight from the
	/// compositor (`wl_keyboard.key`'s `key` argument); `keysym` is
	/// the xkb-translated keysym the user effectively pressed. Most
	/// consumers only care about `keysym`, but embeddings that
	/// forward into an inner window system (a WPE web view, an X11
	/// emulator, …) typically need both — the inner system does its
	/// own keycode → keysym translation for layout-aware shortcuts.
	///
	/// This bypass exists for those embeddings: it fires *in addition*
	/// to the normal callbacks; consume or ignore at will.
	///
	/// `XF86_Back` is not reported here: it is a navigation request, not
	/// input for the embedded system, and goes through [`Self::on_back`].
	fn on_raw_key( &mut self, _keysym: Keysym, _keycode: u32, _pressed: bool, _ctrl: bool, _shift: bool ) {}

	/// [`Self::on_raw_key`] with the Alt state and the typed text too; the runtime calls this one, which forwards to `on_raw_key` unless overridden. Override it instead when Alt or dead keys matter, as in a terminal.
	fn on_raw_key_event( &mut self, key: &RawKey )
	{
		self.on_raw_key( key.keysym, key.keycode, key.pressed, key.ctrl, key.shift );
	}

	/// `true` while every key belongs to [`Self::on_raw_key`], as in a terminal: ltk then neither dispatches keys to its widgets, so Enter and Space do not press the focused or hovered one, nor repeats them. `XF86_Back` still goes through [`Self::on_back`].
	fn claims_keyboard( &self ) -> bool { false }

	/// Called when the surface is (re-)configured with a new size.
	///
	/// `width` and `height` are in **physical pixels** (the Wayland surface
	/// size multiplied by the current buffer scale). They therefore match the
	/// coordinate space used for layout and the pointer/touch callbacks
	/// (`on_drag_move`, `on_drop`, widget hit-testing). Also fired when the
	/// buffer scale changes, so apps can refresh any state keyed off the old
	/// physical dimensions.
	fn on_resize( &mut self, _width: u32, _height: u32 ) {}

	/// Called when the compositor reports a new integer buffer scale for the
	/// main surface. `scale` is the integer buffer scale (1 = standard DPI,
	/// 2 = HiDPI ×2); physical pixels equal logical pixels × scale. In a
	/// browser the scale is the page's `devicePixelRatio`, which may be
	/// fractional; `scale` is then that ratio rounded, and
	/// [`on_resize`](Self::on_resize) gives the exact physical size. The default
	/// is inert so apps that only care about physical pixels can keep using
	/// [`on_resize`](Self::on_resize).
	fn on_scale_changed( &mut self, _scale: u32 ) {}

	/// Called once at startup with a channel sender that can be used from any
	/// thread to deliver messages into the event loop.  Sending a message
	/// immediately wakes the event loop — no polling delay.
	fn set_channel_sender( &mut self, _sender: ChannelSender<Self::Message> ) {}

	/// How often the event loop should call [`poll_external`](Self::poll_external) for
	/// periodic work such as clock ticks. Return `None` (the default) to disable the
	/// timer — `poll_external` will still be called after every Wayland event.
	fn poll_interval( &self ) -> Option<std::time::Duration> { None }

	/// Delay before the runtime starts repeating a held-down key.
	///
	/// `Some(d)` overrides whatever the compositor advertises through
	/// `wl_keyboard.repeat_info`; `None` (the default) means "use the
	/// compositor's setting, or fall back to 500 ms when the compositor
	/// did not provide one".
	///
	/// Returning `Some(Duration::ZERO)` effectively disables the wait
	/// before the first repeat — useful only for diagnostic builds.
	fn key_repeat_delay( &self ) -> Option<std::time::Duration> { None }

	/// Interval between successive synthetic key events while a key is
	/// held down past the initial [`Self::key_repeat_delay`].
	///
	/// `Some(d)` overrides the compositor's `wl_keyboard.repeat_info`
	/// rate; `None` (the default) means "use the compositor's setting,
	/// or fall back to 33 ms (~30 Hz) when the compositor did not
	/// provide one". Pass `Some(Duration::ZERO)` to disable repeats
	/// entirely (or override the per-key gate via
	/// [`Self::key_repeats`]).
	fn key_repeat_interval( &self ) -> Option<std::time::Duration> { None }

	/// Override the pointer cursor shape globally. When `Some(shape)`,
	/// the runtime sends that shape to the compositor regardless of
	/// which widget the pointer is over — useful for "the app is busy"
	/// states (return [`crate::CursorShape::Wait`]) or while the app
	/// is doing a long synchronous operation. Returning `None` (the
	/// default) lets per-widget defaults take effect.
	///
	/// The runtime calls this every frame, so flipping a `loading`
	/// boolean in [`Self::update`] propagates to the cursor on the
	/// next iteration without any extra wiring.
	fn cursor_override( &self ) -> Option<crate::types::CursorShape> { None }

	/// The cursor the app wants at `( x, y )`, in physical pixels of the main surface: below the window's resize edges and [`Self::cursor_override`], above the cursor of the widget under it. `None`, the default, leaves the widget's.
	fn cursor_at( &self, _x: f32, _y: f32 ) -> Option<crate::types::CursorShape> { None }

	/// Decide whether a given key participates in held-key repeat.
	///
	/// Default: every non-modifier key repeats *except* `Escape`,
	/// `XF86_Back`, `Tab` and `ISO_Left_Tab` — those drive one-shot UI
	/// semantics (dismiss / go back / focus cycle) where a held key would
	/// multiply the effect in surprising ways. Override to widen or
	/// narrow the gate (a chess clock app, for example, might want even
	/// Tab to repeat).
	fn key_repeats( &self, keysym: Keysym ) -> bool
	{
		!matches!( keysym,
			Keysym::Escape | Keysym::XF86_Back | Keysym::Tab | Keysym::ISO_Left_Tab,
		)
	}

	/// Return `true` while a frame-by-frame animation is running.
	/// The event loop will keep requesting redraws at ~60 fps until this returns `false`.
	fn is_animating( &self ) -> bool { false }

	/// Return `true` when the main surface's pixels changed but its widgets did not, such as an [`crate::widget::external::External`] with a new frame: the surface is drawn again from the cached view, without calling [`Self::view`]. Asked once per iteration, after the messages are processed.
	fn needs_repaint( &mut self ) -> bool { false }

	/// Cap [`Self::is_animating`] redraws to ~30 Hz when the **software**
	/// renderer is active. Default `true`: 60 fps software rasterization is a
	/// common battery sink on mobile (no GPU offload), and halving it is
	/// usually imperceptible for the animations software fallback can afford.
	/// The GLES backend is never capped. Return `false` to keep the full
	/// display rate on software.
	fn cap_software_animation( &self ) -> bool { true }

	/// Return `true` when a finger-tracked swipe or an [`Self::is_animating`]
	/// slide only repositions the app's input-transparent subsurfaces
	/// ([`Self::subsurfaces`]) while the main surface buffer stays unchanged.
	/// The runtime then skips the per-frame main re-raster that
	/// [`Self::on_swipe_progress`] and `is_animating` would otherwise force,
	/// keeping the animation pumped (motion events during the drag, a bare
	/// frame callback while `is_animating`) and letting the per-frame
	/// subsurface reconcile carry the motion. Use it for a slide-to-reveal
	/// panel over a static main surface.
	fn subsurface_motion_only( &self ) -> bool { false }

	/// Background color for the canvas. Override to make the surface
	/// transparent or to deviate from the theme. Default: the active
	/// theme's `bg` token, so the window matches the rest of the
	/// shell out of the box.
	fn background_color( &self ) -> crate::types::Color
	{
		crate::theme::palette().bg
	}

	/// Return the interactive input region as a list of rects (logical pixels).
	/// Only these areas receive pointer/touch input; the rest passes through.
	/// Return `None` (default) to receive input everywhere.
	fn input_region( &self ) -> Option<Vec<crate::types::Rect>> { None }

	/// Rects (physical layout pixels) of overlay `id` that are fully opaque
	/// this frame, so the compositor can skip blending them and repainting
	/// what lies underneath. `None` (default) declares nothing opaque.
	fn overlay_opaque_region( &self, _id: OverlayId ) -> Option<Vec<crate::types::Rect>> { None }

	/// Return `Some(( title, app_id ))` to force an XDG toplevel window instead of
	/// layer-shell overlay. The compositor will display the title in the title bar
	/// and use the app_id for taskbar/icon matching. Return `None` (default) to
	/// use layer-shell when available. The `app_id` element is ignored:
	/// [`app_id`](Self::app_id) names the window.
	///
	/// **Deprecated**: Use [`shell_mode`](Self::shell_mode) instead.
	fn window_config( &self ) -> Option<( &str, &str )> { None }

	/// Specify the Wayland shell mode for this application.
	///
	/// - [`ShellMode::Window`]: Normal application window (xdg-shell). **Default.**
	/// - [`ShellMode::Layer`]: System component at a specific layer (layer-shell).
	/// - [`ShellMode::SessionLock`]: `ext-session-lock-v1` lock surface (screen locker).
	///
	/// For regular applications, use the default `Window` mode.
	/// For shell components (panels, backgrounds, overlays), use `Layer`.
	/// For a screen locker, use `SessionLock` and request the unlock by
	/// returning `true` from [`requested_exit`](Self::requested_exit).
	fn shell_mode( &self ) -> ShellMode { ShellMode::Window }

	/// Content for the surfaces the runtime creates on every output beyond
	/// the first. In [`ShellMode::SessionLock`] these are lock surfaces —
	/// the compositor blanks any output without one, so each is covered. In
	/// [`ShellMode::Layer`] on [`Layer::Background`] they are background
	/// layer surfaces, so a shell's wallpaper reaches extended outputs
	/// (typically without the grid or any chrome). They take no input.
	/// `width` / `height` are that output's surface size in physical pixels.
	/// Default `None`: the surface is filled with
	/// [`background_color`](Self::background_color).
	fn secondary_view( &self, _width: u32, _height: u32 ) -> Option<Element<Self::Message>>
	{
		None
	}

	/// Return `true` to tear the surface down and exit the event loop. For a
	/// [`ShellMode::SessionLock`] surface the runtime calls `unlock` first, so
	/// the compositor lifts the lock instead of leaving the outputs blanked.
	/// Polled after every batch of `update`s.
	fn requested_exit( &self ) -> bool { false }

	/// Suggest an initial size for an xdg-shell window in logical pixels.
	///
	/// Returning `Some(( w, h ))` makes ltk call both
	/// `xdg_toplevel.set_min_size( w, h )` and
	/// `xdg_toplevel.set_max_size( w, h )` before the first commit, which
	/// most compositors honour as an exact size for the configure they
	/// send back. The window is still resizable from the application's
	/// point of view — if the compositor sends a different configure, the
	/// runtime adopts that size on the next frame.
	///
	/// A hint larger than the screen is shrunk on the first configure,
	/// keeping its aspect ratio: to the compositor's
	/// `xdg_toplevel.configure_bounds` when it sends them, otherwise to
	/// 90 % of the output. A phone-shaped 720x1440 hint therefore opens as
	/// 486x972 on a 1080p desktop instead of running off its bottom edge.
	///
	/// Only applies to [`ShellMode::Window`] surfaces and to the
	/// xdg-shell fallback path used when `wlr-layer-shell` is missing.
	/// Ignored for layer-shell surfaces, which use [`Self::layer_size`]
	/// instead.
	///
	/// **Default**: `None` (let the compositor pick).
	fn window_size_hint( &self ) -> Option<( u32, u32 )> { None }

	/// The main window's title, which the compositor's title bar, task
	/// switcher and dock show; read once, when the window is made.
	///
	/// Only applies to [`ShellMode::Window`] surfaces and to the
	/// xdg-shell fallback of a layer surface.
	///
	/// **Default**: the [`app_id`](Self::app_id).
	fn window_title( &self ) -> String { self.app_id().to_string() }

	/// Whether the user may resize an xdg-shell window.
	///
	/// When [`Self::window_size_hint`] is set, ltk pins
	/// `min_size == max_size` before the first commit so the compositor's
	/// first configure honours the requested size, and then releases
	/// both from the first configure so the surface becomes
	/// user-resizable; a minimum left in place would make a mobile
	/// compositor shrink the window's scale to honour it. Returning
	/// `false` skips that release: the pin stays
	/// in place for the lifetime of the toplevel, declaring a fixed-size
	/// window that compositors must not resize or restore a remembered
	/// geometry over.
	///
	/// Ignored when [`Self::window_size_hint`] returns `None`.
	///
	/// **Default**: `true`.
	fn window_resizable( &self ) -> bool { true }

	/// Request fullscreen on the toplevel before its first commit.
	///
	/// When `true`, ltk calls `xdg_toplevel.set_fullscreen( None )` so
	/// the compositor picks an output and maps the surface fullscreen
	/// from the start (no flicker through a windowed configure first).
	/// The compositor's own decorations are suppressed for fullscreen
	/// surfaces; the built-in titlebar from [`Self::window_config`] is
	/// still painted by ltk on top of the surface unless the app opts
	/// out.
	///
	/// Only applies to [`ShellMode::Window`] surfaces and to the
	/// xdg-shell fallback path used when `wlr-layer-shell` is missing.
	///
	/// **Default**: `false`.
	fn start_fullscreen( &self ) -> bool { false }

	/// Desired fullscreen state of the toplevel while the app runs.
	///
	/// Polled after every batch of `update`s: when the returned value
	/// changes, ltk calls `xdg_toplevel.set_fullscreen` /
	/// `unset_fullscreen`. While the compositor reports the window as
	/// fullscreen the built-in titlebar is not painted. `None` (the
	/// default) leaves the window state alone.
	///
	/// Only applies to [`ShellMode::Window`] surfaces.
	fn fullscreen( &self ) -> Option<bool> { None }

	/// Specify the exclusive zone for layer-shell surfaces.
	///
	/// The exclusive zone reserves screen space for this surface.
	/// For example, a top panel with height 50 should return `50` to prevent
	/// other windows from overlapping it.
	///
	/// - `> 0`: Reserve this many pixels from the anchored edge
	/// - `0`: No exclusive zone (default for overlays)
	/// - `-1`: Don't reserve space but request focus
	///
	/// Only applies to [`ShellMode::Layer`] surfaces. Ignored for windows.
	fn exclusive_zone( &self ) -> i32 { -1 }

	/// Specify which screen edges the layer-shell surface is anchored to.
	///
	/// Anchoring determines the position and size of the surface:
	/// - [`Anchor::TOP`]: Top bar (anchored to top, left, right)
	/// - [`Anchor::BOTTOM`]: Bottom bar (anchored to bottom, left, right)
	/// - [`Anchor::LEFT`]: Left sidebar (anchored to left, top, bottom)
	/// - [`Anchor::RIGHT`]: Right sidebar (anchored to right, top, bottom)
	/// - [`Anchor::ALL`]: Full screen (anchored to all edges)
	///
	/// **Default**: `Anchor::ALL` (full screen)
	///
	/// Only applies to [`ShellMode::Layer`] surfaces. Ignored for windows.
	fn layer_anchor( &self ) -> Anchor { Anchor::ALL }

	/// Specify the desired size for layer-shell surfaces.
	///
	/// Returns `(width, height)` where:
	/// - `0` means "fill available space in that dimension"
	/// - `> 0` means "use this exact size in pixels"
	///
	/// **Examples:**
	/// - Top bar: `(0, 50)` - full width, 50px height
	/// - Bottom bar: `(0, 40)` - full width, 40px height
	/// - Side panel: `(300, 0)` - 300px width, full height
	/// - Full screen: `(0, 0)` - fill everything (default)
	///
	/// **Default**: `(0, 0)` (fill all available space)
	///
	/// Only applies to [`ShellMode::Layer`] surfaces. Ignored for windows.
	fn layer_size( &self ) -> ( u32, u32 ) { ( 0, 0 ) }

	/// Request exclusive keyboard focus for this layer-shell surface.
	///
	/// When `true`, the compositor sends keyboard events to this surface
	/// without requiring a pointer click first. Useful for greeters,
	/// lock screens, and other surfaces that must capture input immediately.
	///
	/// **Default**: `false` (on-demand keyboard interactivity)
	///
	/// Only applies to [`ShellMode::Layer`] surfaces. Ignored for windows.
	fn keyboard_exclusive( &self ) -> bool { false }
}

/// Run the application. Blocks until the window is closed; in a browser,
/// whose page must not block, it returns once the app is running.
///
/// Panics on init failure (no Wayland compositor, missing protocol, etc.).
/// Embedders that need to recover gracefully — e.g. fall back to a
/// software TTY UI when no compositor is reachable — should call
/// [`try_run`] instead and match on the returned [`RunError`].
#[ cfg( backend ) ]
pub fn run<A: App>( app: A )
{
	crate::platform::run( app );
}

/// Run the application, returning a typed error on init failure.
///
/// Same as [`run`] but recoverable: every fatal init step (Wayland
/// connection, registry, calloop event loop, `wl_compositor` / `wl_shm`
/// / `xdg_wm_base` bindings) is converted into a [`RunError`] variant
/// the caller can match on. Once init succeeds the function blocks
/// until the surface is closed and returns `Ok(())`. Errors from the
/// dispatch loop itself (already on screen) still panic — they are
/// non-recoverable since the surface state machine cannot be unwound
/// cleanly from this entry point.
///
/// Use this when:
///
/// * the application needs a graceful fallback path on systems without
///   a Wayland session (CI runners, minimal containers, X11-only
///   environments where ltk has no backend),
/// * an embedder wants to log the specific protocol that's missing
///   instead of panicking with a generic stack trace,
/// * the caller wants to retry / wait for a compositor to come up
///   instead of aborting.
///
/// The standard `run( app )` remains the simpler entry point for
/// applications that always run on a known-good Wayland session.
///
/// ```rust,no_run
/// # use ltk::{ button, App, Element, RunError };
/// # #[ derive( Clone ) ] enum Msg {}
/// # struct MyApp;
/// # impl App for MyApp {
/// #     type Message = Msg;
/// #     fn app_id( &self ) -> &str { "net.example.MyApp" }
/// #     fn save_state( &self ) -> Option<Vec<u8>> { None }
/// #     fn restore_state( &mut self, _: Vec<u8> ) {}
/// #     fn view( &self ) -> Element<Msg> { button( "x" ).into() }
/// #     fn update( &mut self, _: Msg ) {}
/// # }
/// match ltk::try_run( MyApp )
/// {
///     Ok( () ) => {}
///     Err( RunError::NoWaylandConnection( _ ) ) =>
///     {
///         eprintln!( "no compositor — falling back to stdio" );
///         // run a CLI fallback…
///     }
///     Err( RunError::MissingProtocol { name, .. } ) =>
///     {
///         eprintln!( "compositor lacks `{name}` — refusing to start" );
///         std::process::exit( 1 );
///     }
///     Err( e ) =>
///     {
///         eprintln!( "ltk init failed: {e}" );
///         std::process::exit( 1 );
///     }
/// }
/// ```
#[ cfg( backend ) ]
pub fn try_run<A: App>( app: A ) -> Result<(), RunError>
{
	crate::platform::try_run( app )
}

#[ cfg( backend ) ]
pub use crate::event_loop::RunError;