crcbl-shell 0.17.2

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
//! The Crucible windowing seam: one trait, engine-typed vocabulary, and a
//! complete headless implementation.
//!
//! Everything above this crate — the engine loop, the renderer, the samples,
//! the editor — talks to the window system exclusively through [`Shell`].
//! Everything below it (the Wayland and X11 backends at P0.5/P0.6, Win32 at
//! P5C, AppKit next to it, the canvas at P5) implements it. **No platform
//! type ever appears in a signature here, and a `#[cfg(target_os = …)]` in a
//! consumer is a regression** — the same discipline `crcbl-hal` applies to the
//! GPU, applied to the window.
//!
//! The one sanctioned leak is [`SurfaceTarget`], produced by
//! [`Shell::surface_target`] and destructured only by HAL backends. It lives in
//! `crcbl-core` because this crate and `crcbl-hal` must not depend on each
//! other; see [`crcbl_core::surface`] for the argument. The dependency
//! direction across the two seams is:
//!
//! ```text
//! crcbl-shell ──▶ crcbl-core ◀── crcbl-hal ◀── crcbl-vk / crcbl-webgpu / …
//! ```
//!
//! # What is in this crate
//!
//! P0.4 added the seam and [`HeadlessShell`]. P0.5a added the **Wayland
//! backend**'s window lifecycle — connection, registry, `xdg-shell`,
//! configure/ack, modes, monitors. P0.5b added everything downstream of
//! `wl_seat`: keyboard and pointer input with XKB keymaps, pointer lock and
//! confinement, raw relative motion, fractional scale, `xdg_output` monitor
//! geometry and `xdg-decoration`. P0.5c added `data-device`: the clipboard in
//! both directions and drag-and-drop *reception*, with the payload transfers
//! run across pipes without ever blocking the frame loop.
//!
//! P0.6 added the **X11 backend**: libxcb through `dlopen`, the window
//! lifecycle with ICCCM and EWMH properties, RandR monitor enumeration, XKB
//! keymaps read from the server, XInput 2 raw motion, pointer grabs, and the
//! selection protocol with `TARGETS` negotiation and `INCR` transfers in both
//! directions. Drag and drop (XDND) is deliberately *not* in it and
//! [`ShellCaps::DRAG_DROP`] says so. Both backends are compiled only on Linux,
//! reached only through [`open`], and built on hand-written `extern "C"`
//! declarations — for libwayland-client, libxcb and libxkbcommon — with the
//! Wayland protocol marshalling generated at build time from vendored XML by
//! `crcbl-wl-scanner`. There is no `wayland-client`, no `x11rb` and no `winit`.
//!
//! P5C added the **Win32 backend**: the window class and its procedure,
//! create/destroy, title, visibility, windowed ↔ borderless on a named monitor,
//! `WM_GETMINMAXINFO` and `WM_SIZING` size constraints, monitor enumeration with
//! per-monitor-v2 DPI, the message pump and a blocking `wait_events` — then
//! keyboard, text, pointer, wheel, raw relative motion, pointer lock and
//! confinement, cursors and warping. The clipboard and drag-and-drop are the
//! slice after it, and [`ShellCaps`] is clear on every bit they would set. It is
//! hand-written `extern "system"` FFI to `user32`, `gdi32`, `shcore` and
//! `kernel32` — **linked rather than `dlopen`ed**, which is the one place the
//! native backends deliberately disagree: a Linux box can genuinely lack
//! libwayland, and a Windows cannot lack `user32.dll`. There is no
//! `windows-rs`.
//!
//! P5C also added the **AppKit backend**: the Objective-C runtime FFI, the
//! `NSApplication` bootstrap, `NSWindow` and a layer-hosting `NSView` carrying
//! the `CAMetalLayer` that *is* [`SurfaceTarget::AppKit`], the event pump and a
//! blocking `wait_events`, windowed ↔ borderless on a named display, `NSScreen`
//! enumeration with scale and refresh, size constraints and close-request
//! interception — then keyboard, text through a real `NSTextInputClient`,
//! pointer, both scroll units, relative motion, pointer lock, cursors and
//! warping. The pasteboard and drag-and-drop are the slice after it, and
//! [`ShellCaps`] is clear on every bit they would set. It is hand-written
//! `objc_msgSend` FFI — **linked rather than `dlopen`ed**, for the same reason
//! the Win32 backend gives — with no `objc2` and no framework.
//!
//! Four macOS facts are worth knowing at this level rather than at that one.
//! **AppKit is main-thread-only and enforces it by raising an Objective-C
//! exception**, which is the concrete reason [`Shell`] is not `Send` and is a
//! stronger rule than Win32's thread affinity — there, any thread may own a
//! window as long as it is the one pumping. **The Y axis points up**, and macOS
//! is the only one of the five platforms whose coordinate system disagrees with
//! this seam's about that. **`backingScaleFactor` is 1.0 or 2.0 and nothing
//! between**, so [`ShellCaps::FRACTIONAL_SCALE`] is clear on the one desktop
//! backend a reader would expect it to be set on. And **macOS cannot confine a
//! pointer at all** — there is no `ClipCursor` and no `confine_to`, only warping
//! it back after it has already left — so [`ShellCaps::POINTER_CONFINE`] is
//! clear while [`ShellCaps::POINTER_LOCK`] is set, which is a split no other
//! desktop backend has.
//!
//! Two Win32 facts the other backends do not have are worth knowing at this
//! level rather than at that one. A window's contents freeze while the user
//! drags its edge, because Windows runs a **modal message loop** of its own
//! there and [`pump`](Shell::pump) does not return until the mouse is released.
//! And a window belongs to the thread that created it, which is the concrete
//! reason [`Shell`] is not `Send`.
//!
//! Two properties of the Wayland clipboard shaped the seam rather than being
//! worked around in the backend, because they are properties of the *platform*:
//! a client may only read the selection while one of its windows has keyboard
//! focus, and may only *claim* it while holding a serial from real user input.
//! So [`Shell::clipboard_readable`] says whether a read would answer now,
//! [`Shell::clipboard_request`] **holds** a read it cannot yet answer instead of
//! reporting an empty clipboard, [`ClipboardContent`] separates "empty" from
//! "could not be read", and [`ShellError::NeedsUserInteraction`] names the
//! refusal. [`HeadlessShell`] can simulate all three, so a consumer is tested
//! against them with no compositor in the room.
//!
//! P0.6 checked that prediction against the other platform, and it held with
//! one correction worth recording: X11 needs none of the *holding* (its
//! `GetSelectionOwner` answers synchronously and there is no focus gate) and
//! never returns [`ShellError::NeedsUserInteraction`] (there is no such rule),
//! but it does **not** get "answered within a bounded time" for free. A stalled
//! `INCR` transfer has no descriptor to poll and no protocol event for "the
//! owner gave up", so the X11 backend carries its own deadline. The seam did
//! not move; one backend obligation turned out to cost more than predicted, and
//! that is written down where it is paid.
//!
//! `HeadlessShell` is not a stub standing in for the real thing: per the
//! windowing rules in `docs/notes/backends.md` it is a first-class implementation that CI,
//! `crcbl screenshot` and `crcbl sim` run the *identical* engine loop through.
//! Where the real compositor turned out to differ from what it models, the
//! difference is documented in the Wayland backend rather than smoothed over —
//! the first configure carrying no size at all is the one to know about.
//!
//! # Decision: `dyn`-primary, like the HAL
//!
//! [`Shell`] is object-safe and [`open`] returns `Box<dyn Shell>`. This is
//! forced rather than chosen: the windowing rules require Wayland and
//! X11 to be compiled in together and selected *at runtime*, so the backend
//! cannot be a type parameter. The consequences are the ones `crcbl-hal`
//! documents — no generic methods, no `impl Trait` returns, no cross-crate
//! inlining — and they cost less here: a frame makes a handful of shell calls,
//! not one per draw. Generic use still works (`fn f<S: Shell + ?Sized>(s: &S)`)
//! and monomorphises normally.
//!
//! The trait requires [`Debug`](core::fmt::Debug) and deliberately **not**
//! `Send`/`Sync`. Shells are thread-affine and cannot promise otherwise: a
//! Win32 `HWND` belongs to the thread pumping its message queue, and AppKit is
//! main-thread-only. [`SurfaceTarget`] reached the same conclusion for the same
//! reason. Create the shell on the thread that will pump it.
//!
//! # Decision: `pump` is a drain, never a loop
//!
//! ```text
//! loop {                                  // native: the outer loop is yours
//!     shell.pump(&mut |event| …);         // ← drain what arrived
//!     clock.update(time.elapsed());
//!     while clock.consume_tick() { tick(clock.tick_dt()); }
//!     render(clock.alpha());
//! }
//! ```
//!
//! There is no `Shell::run(closure)` and there never will be, because
//! the browser requires the engine loop to be "a `fn tick(dt)`
//! driven by an outer loop, not a `loop {}` that owns the thread" — in a
//! browser the outer loop is `requestAnimationFrame`, which *calls* the engine
//! and cannot be called by it. A framework-shaped `run()` would compile on wasm
//! and then deadlock on the first frame, which is the worst possible failure
//! schedule. The rAF build is the same body with the `loop {` line deleted:
//!
//! ```text
//! // wasm: the outer loop is the browser's
//! extern "C" fn crcbl_frame(now_ms: f64) {   // called from rAF by the JS shim
//!     shell.pump(&mut |event| …);
//!     clock.update(Duration::from_secs_f64(now_ms / 1000.0));
//!     while clock.consume_tick() { tick(clock.tick_dt()); }
//!     render(clock.alpha());
//! }
//! ```
//!
//! [`Shell::wait_events`] exists for the editor, which idles at zero frames per
//! second on battery. It is *advisory*: returning immediately is always a
//! correct implementation, which is what makes it portable to a browser that
//! cannot block at all.
//!
//! # Decision: where the input vocabulary lives
//!
//! The shell-boundary rule in `docs/notes/backends.md` puts input normalization in
//! `crcbl-core::input`, and [`ShellEvent`] is naturally a `crcbl-shell` type.
//! Both are true, and the split is:
//!
//! | Lives in | What | Why |
//! | --- | --- | --- |
//! | [`crcbl_core::input`] | [`KeyCode`], [`Keysym`], [`PointerButton`], [`Modifiers`], [`ScrollDelta`], [`DeviceId`] | the P2 action layer, the profile store, the ECS and the UI all need to *name* a key; none of them should link a windowing library to spell `Space` |
//! | `crcbl-shell` | [`ShellEvent`] | it names [`WindowId`], and only a shell backend ever produces one |
//!
//! Dependency direction: `crcbl-shell → crcbl-core`, never the reverse, and
//! `crcbl-input` (P2) will depend on `crcbl-core` for vocabulary plus
//! `crcbl-shell` for the event stream. The vocabulary types are re-exported
//! here so an event consumer needs one `use`, not two.
//!
//! # Decision: raw events only
//!
//! This crate produces *normalized raw* events. Actions, bindings, contexts and
//! patterns are `crcbl-input`'s action layer. What
//! this slice owes that layer is the information it cannot reconstruct later —
//! per-device ids, and timestamps that are the window system's rather than the
//! frame's. Both are on every input event; see [`event`].
//!
//! # Decision: a window has no size until the window system says so
//!
//! [`Shell::create_window`] returns a [`WindowId`] and *nothing else*.
//! [`WindowState::size`] is `None` until the first
//! [`ShellEvent::Resized`] arrives, and a swapchain — which needs an extent —
//! cannot be created before then.
//!
//! This is the shape Wayland forces: an `xdg_surface` is unsized and may not be
//! given a buffer until the compositor answers with a `configure`, a round trip
//! away. Modelling it in the type rather than in prose is the difference
//! between every consumer written before P0.5 being correct and all of them
//! breaking on the same day. [`HeadlessShell`] deliberately defers the first
//! configure by at least one [`pump`](Shell::pump) — same reasoning as
//! `crcbl-hal`'s injected readback latency — so the create-then-wait loop is
//! *exercised* in CI rather than merely documented.
//!
//! The same distinction runs through [`WindowState`]: what was **requested**
//! ([`requested_mode`](WindowState::requested_mode),
//! [`requested_constraints`](WindowState::requested_constraints)) is always
//! known because we said it, while what is **effective**
//! ([`WindowConfiguration`]) only exists once the window system has answered
//! and may disagree forever. A compositor can refuse a fullscreen request; a
//! tiling window manager ignores every size hint there is.
//!
//! # Stability
//!
//! Provisional, like the HAL seam, and with a specific reason to be: it has no
//! real backend behind it yet. The places most likely to move are stated rather
//! than glossed — [`HeadlessShell`]'s event ordering is a *model* of a
//! compositor's, not a recording of one, and its configure delay is a fixed
//! number of pumps where a compositor's is a round trip.
//!
//! # Example
//!
//! A complete, deterministic window session with no window system anywhere:
//!
//! ```
//! use crcbl_shell::{CloseReply, HeadlessShell, PhysicalSize, Shell, WindowDesc};
//!
//! let mut shell = HeadlessShell::new();
//! let window = shell.create_window(&WindowDesc {
//!     title: "sandbox",
//!     ..WindowDesc::default()
//! })?;
//!
//! // The window has no size yet, so there is no swapchain to create.
//! assert_eq!(shell.window_state(window)?.size(), None);
//!
//! // Wait for the window system to configure it. This loop is mandatory, not
//! // defensive: on Wayland the answer is a round trip away.
//! let size = loop {
//!     shell.pump(&mut |_event| {});
//!     if let Some(size) = shell.window_state(window)?.size() {
//!         break size;
//!     }
//! };
//! assert_eq!(size, PhysicalSize::new(1280, 720));
//!
//! // Script what a compositor would do next.
//! shell.resize(window, PhysicalSize::new(1920, 1080))?;
//! shell.request_close(window)?;
//!
//! let mut names = Vec::new();
//! shell.pump(&mut |event| names.push(event.name()));
//! assert_eq!(names, ["Resized", "CloseRequested"]);
//!
//! // The close request is a question, not a notification.
//! shell.reply_close_request(window, CloseReply::Keep)?;
//! assert!(shell.window_state(window).is_ok(), "still open");
//! # Ok::<(), crcbl_shell::ShellError>(())
//! ```

pub mod backend;
pub mod caps;
pub mod clipboard;
pub mod cursor;
pub mod error;
pub mod event;
pub mod geom;
pub mod headless;
pub mod monitor;
pub mod role;
pub mod url;
pub mod waker;
pub mod window;

pub(crate) mod frame;
pub(crate) mod keysym;

#[cfg(any(target_os = "macos", target_os = "windows", test))]
pub(crate) mod preedit;

#[cfg(desktop_unix)]
pub(crate) mod linux;

#[cfg(desktop_unix)]
pub(crate) mod wayland;

#[cfg(desktop_unix)]
pub(crate) mod x11;

#[cfg(any(target_os = "windows", test))]
pub(crate) mod win32;

#[cfg(any(target_os = "macos", test))]
pub(crate) mod appkit;

#[cfg(any(target_arch = "wasm32", test))]
pub(crate) mod web;

/// Scaffolding for the nested-compositor end-to-end suite, behind the
/// `wayland-e2e` feature.
///
/// Not part of the seam and not for consumers: it exists because a Wayland
/// surface is only managed by the compositor once it has a *buffer*, and
/// attaching one is the renderer's job — which does not exist until P1. See
/// the module's docs for the full finding.
#[cfg(all(desktop_unix, feature = "wayland-e2e"))]
pub use wayland::e2e as wayland_test_support;

/// Scaffolding for the Xvfb end-to-end suite, behind the `x11-e2e` feature.
///
/// Not part of the seam and not for consumers. Where the Wayland version exists
/// because a surface needs a buffer, this one exists because on X11 the window
/// manager, the input devices and the clipboard owner are all *other programs* —
/// see the module's docs.
#[cfg(all(desktop_unix, feature = "x11-e2e"))]
pub use x11::e2e as x11_test_support;

#[cfg(target_os = "macos")]
pub use appkit::session_support;

/// The accessibility vocabulary [`Shell::update_accessibility`] and the
/// `Accessibility*` events speak, re-exported so a caller builds its tree with
/// the version the shell was built against. Behind the `accesskit` feature.
#[cfg(feature = "accesskit")]
pub use accesskit;

pub use backend::{BACKEND_ENV_VAR, ShellBackend, open, open_backend};
pub use caps::ShellCaps;
pub use clipboard::{
    ClipboardContent, ClipboardOffer, ClipboardRequestId, MimeType, ReceivedMime, parse_uri_list,
};
pub use cursor::{CursorIcon, PointerMode};
pub use error::ShellError;
pub use event::ShellEvent;
pub use geom::{
    AspectRatio, LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint, PhysicalRect, PhysicalSize,
};
pub use headless::HeadlessShell;
pub use monitor::{MonitorId, MonitorInfo};
pub use role::{
    Margins, PanelAnchor, PanelDesc, PanelKeyboard, PanelLayer, PopupDesc, PopupInput,
    PopupPlacement, Reserve, WindowRole,
};
pub use url::{WebUrl, WebUrlError};
pub use waker::ShellWaker;
pub use window::{
    CloseReply, DisplayMode, SizeConstraints, Window, WindowConfiguration, WindowDesc, WindowId,
    WindowState,
};

/// Cross-seam vocabulary from `crcbl-core`: the input-event clock, the key
/// names, and the one sanctioned platform leak.
pub use crcbl_core::input::TextPurpose;
/// Input vocabulary, defined in [`crcbl_core::input`] and re-exported so a
/// consumer of the event stream needs one `use` rather than two.
///
/// See the [crate docs](self) for why these live in `crcbl-core`.
pub use crcbl_core::input::{
    ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
    TouchPhase,
};
pub use crcbl_core::{EventTime, KeyCode, SurfaceTarget};

use core::time::Duration;

/// The window system, as the engine sees it.
///
/// Object-safe by requirement; see the [crate docs](self) for why, and
/// [`backend`] for how an implementation is selected at runtime.
///
/// # The loop is the caller's
///
/// There is no `run` that takes the program over: the caller loops on
/// [`pump`](Self::pump) and [`wait_events`](Self::wait_events) itself, so
/// ending the program is leaving that loop and dropping the shell. Each
/// desktop backend's `Drop` destroys the windows it still holds, so nothing has
/// to be torn down by hand first. Work that arrives
/// on another thread reaches a sleeping loop through a [`ShellWaker`].
///
/// # Implementing this
///
/// Six obligations that are not visible in the signatures. The first three are
/// P0.4's; the last three are P0.5c's, written down because a real compositor
/// showed that leaving them unstated pushes the work onto every consumer.
///
/// 1. **Stale handles fail cleanly.** Every method taking a [`WindowId`] must
///    return [`ShellError::InvalidWindow`] for a destroyed or foreign one, never
///    act on whatever window took the slot.
/// 2. **Timestamps are rebased.** Input events carry the window system's
///    timestamp converted to the engine epoch — see [`EventTime`], which
///    documents the conversion each platform needs.
/// 3. **Capabilities are latched.** [`caps`](Self::caps) must return the same
///    value for the shell's lifetime, so a consumer that branched on it at
///    startup is never contradicted mid-session. See [`caps`] for the
///    Wayland-binds-a-global-late edge this rules out.
/// 4. **Every accepted clipboard read is answered exactly once, and within a
///    bounded time.** [`clipboard_request`](Self::clipboard_request) that
///    returns `Ok` promises exactly one
///    [`ShellEvent::ClipboardData`] carrying that
///    [`ClipboardRequestId`]. A backend that cannot complete the read answers
///    [`ClipboardContent::Unavailable`] rather than dropping the request; a
///    request with no answer is a UI stuck on "pasting…" forever, which no
///    consumer can detect.
/// 5. **A read that cannot be answered *yet* is held, never answered "empty".**
///    If the backend does not yet know what is on the clipboard — Wayland's
///    focus-gated, asynchronous `wl_data_device.selection` is the case this
///    exists for — it holds the request until it does, and bounds that wait.
///    Reporting [`Empty`](ClipboardContent::Empty) for "I have not looked yet"
///    is indistinguishable from an empty clipboard, so it makes every consumer
///    write a retry loop with a timeout it cannot choose correctly. Where the
///    answer is always immediately available (X11 asks the server who owns the
///    selection; a headless shell owns it), holding costs nothing and this
///    obligation is discharged by answering.
/// 6. **A refusal for want of user interaction is named.** Where the window
///    system requires a recent input event to claim the clipboard — Wayland
///    does, the browser does, X11 and Win32 do not —
///    [`clipboard_offer`](Self::clipboard_offer) returns
///    [`ShellError::NeedsUserInteraction`] and not a generic backend error, so
///    a caller can distinguish "ask the user to press the key again" from "this
///    is broken". A backend on a platform without the rule never returns it.
pub trait Shell: core::fmt::Debug {
    /// Which implementation this is. Logs and bug reports only — behaviour
    /// branches on [`caps`](Self::caps).
    fn backend(&self) -> ShellBackend;

    /// What this backend can do. Fixed for the shell's lifetime.
    fn caps(&self) -> ShellCaps;

    /// Creates a window. **The window has no size yet.**
    ///
    /// `desc.size` is a request. The authoritative size arrives later, as the
    /// first [`ShellEvent::Resized`], and until it does
    /// [`WindowState::size`] is `None`. This is not a headless quirk: a Wayland
    /// `xdg_surface` is unsized and may not be given a buffer until the
    /// compositor answers with a `configure`, which is a round trip away.
    ///
    /// A swapchain needs an extent, so this is a hard ordering constraint:
    ///
    /// ```
    /// # use crcbl_shell::{HeadlessShell, PhysicalSize, Shell, WindowDesc};
    /// # let mut shell = HeadlessShell::new();
    /// let window = shell.create_window(&WindowDesc::default())?;
    /// let size: PhysicalSize = loop {
    ///     shell.pump(&mut |_event| { /* … */ });
    ///     if let Some(size) = shell.window_state(window)?.size() {
    ///         break size;
    ///     }
    /// };
    /// // Only now is there an extent to create a swapchain at.
    /// assert_eq!(size, PhysicalSize::new(1280, 720));
    /// # Ok::<(), crcbl_shell::ShellError>(())
    /// ```
    ///
    /// [`HeadlessShell`] deliberately defers the first configure by at least one
    /// `pump`, so a consumer that skips the loop fails in CI rather than at
    /// P0.5.
    ///
    /// # Errors
    ///
    /// [`ShellError::WindowCreation`] if the window system refused, or
    /// [`ShellError::Unsupported`] if this would be a second window on a
    /// backend without [`ShellCaps::MULTI_WINDOW`].
    fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError>;

    /// Destroys a window. A [`ShellEvent::WindowDestroyed`] follows.
    ///
    /// The [`SurfaceTarget`] previously returned for this window is dead
    /// afterwards; the HAL surface built from it must be destroyed **first**.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError>;

    /// A snapshot of the window's current state.
    ///
    /// For consumers that started late; not a substitute for handling events.
    /// Note that [`WindowState::size`] is `None` until the window system has
    /// configured the window, and that the *requested* mode and the *effective*
    /// one are separate fields — see [`WindowState`].
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError>;

    /// Sets the title bar text.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError>;

    /// Maps or unmaps the window.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError>;

    /// Asks for windowed or borderless.
    ///
    /// **A request, not a command.** It updates
    /// [`WindowState::requested_mode`] immediately and nothing else; the mode
    /// that is actually in effect appears in
    /// [`WindowConfiguration::mode`] when the window system answers, which it
    /// may do with something other than what was asked (a compositor can refuse
    /// fullscreen, and a tiling window manager makes the question moot). Use
    /// [`WindowState::mode_request_honoured`] rather than reading the request
    /// back as fact.
    ///
    /// The answer usually arrives as a [`ShellEvent::Resized`], preceded by a
    /// [`ShellEvent::ScaleFactorChanged`] when the target monitor has a
    /// different scale. Never assume the new size — read the event.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale, or
    /// [`ShellError::NoSuchMonitor`] if the named monitor is gone.
    fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError>;

    /// Asks for resize limits and an aspect lock.
    ///
    /// Hints, not guarantees, and a request rather than a command: it updates
    /// [`WindowState::requested_constraints`] immediately, and the only
    /// observable effect is whatever size the window system reports next. No
    /// platform reports back "effective constraints", so neither does this
    /// seam. See [`SizeConstraints`].
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_constraints(
        &mut self,
        window: WindowId,
        constraints: SizeConstraints,
    ) -> Result<(), ShellError>;

    /// Moves a live popup against a new `anchor` in its parent and gives it
    /// `size`, placed by the [`PopupPlacement`] it was created with: flipped
    /// or slid to stay on screen, as when it opened.
    ///
    /// For a popup whose anchor moved — a bar's clock grew and its calendar
    /// should follow — or whose content changed size. A request, like the
    /// rest of a window's geometry: the new size arrives as the next
    /// [`ShellEvent::Resized`], once the window system has placed it.
    ///
    /// Requires [`ShellCaps::POPUP_REPOSITION`]. Without it, close the popup
    /// and open another.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] without the capability,
    /// [`ShellError::InvalidWindow`] for a stale handle, and
    /// [`ShellError::InvalidDescriptor`] for a window that is not a popup.
    fn reposition_popup(
        &mut self,
        popup: WindowId,
        anchor: LogicalRect,
        size: LogicalSize,
    ) -> Result<(), ShellError> {
        let _ = (popup, anchor, size);
        Err(ShellError::Unsupported {
            backend: self.backend(),
            what: "repositioning a popup",
        })
    }

    /// Gives a live panel a new size and a new [`PanelDesc`]: its layer,
    /// anchor, reserve, margins and keyboard change in place, with the same
    /// surface and the same swapchain, where destroying it and creating
    /// another would flicker.
    ///
    /// `size` means what [`WindowDesc::size`] means for a panel: ignored along
    /// an axis anchored to both opposite edges. The new descriptor is checked
    /// as [`create_window`](Self::create_window) checks one, so a reserving
    /// panel must still name one edge. A request, like the rest of a window's
    /// geometry: the size the panel gets arrives as the next
    /// [`ShellEvent::Resized`], as its first one did, and none arrives when
    /// the size did not change.
    ///
    /// **The namespace and the monitor cannot change.** `wlr-layer-shell`
    /// fixes both when the surface is made, and every backend refuses a
    /// change to either alike; close the panel and open another for that.
    ///
    /// A visible panel changed to [`PanelKeyboard::Exclusive`] takes the
    /// keyboard at once on Wayland, where the compositor hands it over; on
    /// Win32 and AppKit it takes it when it is next shown, as a new one does.
    ///
    /// A provided method answering [`ShellError::Unsupported`], as
    /// [`create_window`](Self::create_window) answers a panel on a backend
    /// without [`ShellCaps::PANEL`], once the handle has been checked; every
    /// backend with panels implements it.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] for a stale handle,
    /// [`ShellError::InvalidDescriptor`] for a window that is not a panel or a
    /// descriptor that changes its namespace or its monitor, and whatever
    /// [`create_window`](Self::create_window) refuses a panel with:
    /// [`ShellError::Unsupported`] for what the backend cannot build, and
    /// [`ShellError::NoSuchMonitor`] if the panel's monitor is gone.
    fn set_panel(
        &mut self,
        window: WindowId,
        size: LogicalSize,
        panel: &PanelDesc<'_>,
    ) -> Result<(), ShellError> {
        let _ = (size, panel);
        self.window_state(window)?;
        Err(ShellError::Unsupported {
            backend: self.backend(),
            what: "panel windows",
        })
    }

    /// Every connected monitor.
    ///
    /// Invalidated by [`ShellEvent::MonitorsChanged`]; call again rather than
    /// caching across it.
    fn monitors(&self) -> &[MonitorInfo];

    /// One monitor by id, or `None` if it is not connected.
    ///
    /// A provided method rather than a required one: it is a lookup over
    /// [`monitors`](Self::monitors), and every backend would write the same
    /// three lines.
    fn monitor(&self, id: MonitorId) -> Option<&MonitorInfo> {
        self.monitors().iter().find(|monitor| monitor.id == id)
    }

    /// Drains everything that has arrived from the window system into `sink`.
    ///
    /// Non-blocking and finite: it delivers what is queued and returns. Call it
    /// once at the top of every frame. See the [crate docs](self) for why there
    /// is no `run()` and how a `requestAnimationFrame`-driven build uses this.
    ///
    /// The sink is `&mut dyn FnMut` rather than a generic parameter because the
    /// trait must stay object-safe. That is not purely a cost: a closure passed
    /// here can borrow the caller's state mutably, which an
    /// `Iterator`-returning shape could not while the shell is also borrowed.
    fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent));

    /// Lets the window system run, and delivers nothing.
    ///
    /// Everything [`pump`](Self::pump) does except hand events to a sink: the
    /// platform's queue is drained, whatever it asks of the client is answered,
    /// and what it produced is **kept** in this shell's queue, in order, for the
    /// next `pump`. Every backend implements `pump` as this followed by the
    /// delivery, so the two cannot drift apart.
    ///
    /// # What it is for: a long load on the thread that owns the window
    ///
    /// Desktops mark a client that stops draining its queue as hung. Windows
    /// ghosts a window whose thread has not asked for a message for about five
    /// seconds — `IsHungAppWindow`, a greyed "Not Responding" title, clicks
    /// held — a Wayland compositor pings through `xdg_wm_base` and offers to
    /// kill a client that does not answer (GNOME's "not responding" dialog),
    /// and macOS puts the spinning cursor over an application whose main thread
    /// has stopped taking events. A game that loads its assets between opening
    /// its window and its first frame calls this every so often — a few times a
    /// second is plenty — and stays responsive to all three.
    ///
    /// **Nothing is dropped**, which is why this is not `pump` with an empty
    /// sink: a key pressed, a resize or a close request made during the load is
    /// delivered by the first frame's `pump`, exactly as if the load had been
    /// one long frame. So a close request stays unanswered until then — the
    /// window stays open and the load finishes first — and a loader that must
    /// stop for one has to pump and handle events itself.
    ///
    /// Work that can leave the loop thread should, instead: a loop that keeps
    /// running frames keeps pumping on its own, and can show progress while it
    /// does. This is for the load that cannot — work on the device the loop
    /// owns, or on anything else tied to this thread.
    ///
    /// Non-blocking and finite, like `pump`, and with the same exception: on
    /// Win32 and AppKit it does not return while the user is dragging the
    /// window's border.
    fn keep_alive(&mut self);

    /// Blocks until an event arrives or `timeout` elapses.
    ///
    /// **Advisory.** Returning immediately is always correct, and backends
    /// without [`ShellCaps::EVENT_WAIT`] — a browser above all — do exactly
    /// that. A caller must treat this as "sleep if you can" and must not assume
    /// an event is pending afterwards; [`pump`](Self::pump) is still what
    /// delivers them.
    ///
    /// `timeout` of `None` means "until something happens", which on a backend
    /// without the capability still means "immediately".
    fn wait_events(&mut self, timeout: Option<Duration>) {
        let _ = timeout;
    }

    /// A handle that wakes [`wait_events`](Self::wait_events) from another
    /// thread — see [`ShellWaker`].
    ///
    /// Every call hands out a handle to the same doorbell, so a program can ask
    /// once and clone, or ask wherever it needs one. `None` from a backend
    /// whose wait never blocks, which is the browser: there, nothing sleeps and
    /// there is nothing to wake.
    fn waker(&mut self) -> Option<ShellWaker> {
        None
    }

    /// Puts input timestamps on the engine's clock.
    ///
    /// Call this **once, at startup**, with the reading of the
    /// [`TimeSource`](crcbl_core::time::TimeSource) that will drive
    /// [`FrameClock::update`](crcbl_core::FrameClock::update).
    ///
    /// [`EventTime`]'s epoch is defined as "the same origin as" that source,
    /// and no backend can know it: a shell is created some time *after* the
    /// clock starts, and the window system's own clock has a third origin
    /// again. Without this call, timestamps are measured from the shell's own
    /// creation — internally consistent, so durations between two input events
    /// are already correct, but offset from a
    /// [`FrameClock`](crcbl_core::FrameClock) reading by however long startup
    /// took. That offset is exactly what `docs/plan/26-prediction.md`'s input-to-photon
    /// latency measurement is a subtraction across.
    ///
    /// A provided method with a no-op default, because it is only meaningful
    /// for a backend whose event clock is not already the engine's — the
    /// browser's `event.timeStamp` needs nothing done to it. The obligation it
    /// discharges is the "Timestamps are rebased" one in this trait's
    /// [implementor notes](Self), which previously had no way to be satisfied
    /// from outside the crate.
    ///
    /// ```
    /// # use core::time::Duration;
    /// # use crcbl_shell::{HeadlessShell, Shell};
    /// let mut shell = HeadlessShell::new();
    /// // The engine clock has been running for 40 ms by the time the window
    /// // system is up; input stamped "now" should read as 40 ms, not as zero.
    /// shell.align_event_clock(Duration::from_millis(40));
    /// ```
    fn align_event_clock(&mut self, elapsed: Duration) {
        let _ = elapsed;
    }

    /// The native handles a HAL backend needs to create a surface for this
    /// window.
    ///
    /// Opaque to everyone except a HAL backend. Re-query it after a
    /// [`set_mode`](Self::set_mode): some backends recreate the underlying
    /// surface on a mode switch, and a cached target then names a dead object.
    /// **A resize is not such an event** — see below.
    ///
    /// # Available before the window is configured, and unchanged by a resize
    ///
    /// The *handle* exists as soon as the window does — a `wl_surface` is
    /// created up front and only its size is pending — so this succeeds
    /// immediately and a HAL surface can be created from it right away. Only
    /// the **swapchain** has to wait, because only the swapchain needs an
    /// extent.
    ///
    /// **No variant carries a size**, so the value this returns does not change
    /// when the window is resized, and a HAL surface created before the first
    /// configure stays correct forever. That is what makes "re-query after a
    /// mode change" a complete rule. [`SurfaceTarget::Offscreen`] used to carry
    /// `width`/`height` and was the one exception; P0.7 removed it, because an
    /// exception in this rule means a surface silently describing a size the
    /// window no longer has. The extent reaches a backend through
    /// [`WindowState::size`] and the swapchain descriptor, and only there —
    /// `crcbl-hal`'s `swapchain` module states that precedence as a backend
    /// obligation.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError>;

    /// Frees, confines or locks the pointer.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] if [`caps`](Self::caps) lacks
    /// [`PointerMode::required_cap`], or [`ShellError::InvalidWindow`] for a
    /// stale handle.
    fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError>;

    /// Sets the cursor shape, or hides the cursor with `None`.
    ///
    /// Visibility and capture are separate axes; see [`cursor`].
    ///
    /// Hiding works on every backend. A shape is seen only where
    /// [`ShellCaps::CURSOR_SHAPE`] is set; elsewhere it is accepted and
    /// recorded rather than refused, because a UI calls this on every hover.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_cursor(
        &mut self,
        window: WindowId,
        cursor: Option<CursorIcon>,
    ) -> Result<(), ShellError>;

    /// Moves the pointer to a position in the window.
    ///
    /// Requires [`ShellCaps::POINTER_WARP`], which **Wayland does not have and
    /// will not get**. Anything reaching for this to implement a camera should
    /// use [`PointerMode::Locked`] instead; warping is for a UI that needs to
    /// reposition a cursor (a slider snapping to a value), not for input.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] without the capability, or
    /// [`ShellError::InvalidWindow`] for a stale handle.
    fn warp_pointer(&mut self, window: WindowId, position: PhysicalPoint)
    -> Result<(), ShellError>;

    /// Answers a [`ShellEvent::CloseRequested`].
    ///
    /// Until this is called the window stays open and the request stays
    /// outstanding. See [`CloseReply`].
    ///
    /// # Errors
    ///
    /// [`ShellError::NoPendingCloseRequest`] if nothing was asked, or
    /// [`ShellError::InvalidWindow`] for a stale handle.
    fn reply_close_request(
        &mut self,
        window: WindowId,
        reply: CloseReply,
    ) -> Result<(), ShellError>;

    /// Publishes clipboard content in one or more formats.
    ///
    /// Synchronous: every platform's write is "claim the selection", and the
    /// bytes transfer later, on demand. Offer both [`MimeType::TextUtf8`] and
    /// [`MimeType::CrcblRon`] for engine data; see [`clipboard`].
    ///
    /// An empty `offers` slice releases the clipboard, where the platform can
    /// express that.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`],
    /// [`ShellError::InvalidWindow`] for a stale handle, or
    /// [`ShellError::NeedsUserInteraction`] where the window system requires a
    /// recent input event to claim the clipboard and there has not been one —
    /// implementor obligation 6 above, and **not** a failure a caller should
    /// retry blindly.
    fn clipboard_offer(
        &mut self,
        window: WindowId,
        offers: &[ClipboardOffer<'_>],
    ) -> Result<(), ShellError>;

    /// Asks for the clipboard's content in `mime`.
    ///
    /// Asynchronous by necessity — the answer arrives as
    /// [`ShellEvent::ClipboardData`] carrying the returned id, and **exactly one
    /// answer arrives for every `Ok` return** (implementor obligations 4 and 5).
    /// [`clipboard`] has the full argument; briefly, X11 `INCR` transfers,
    /// Wayland file descriptors and the browser's Promise make the synchronous
    /// shape unimplementable on three of five backends.
    ///
    /// The answer may be several frames away, and on a backend whose clipboard
    /// is not readable at the moment of asking it is *held* until it is, rather
    /// than being answered [`Empty`](ClipboardContent::Empty). A caller
    /// therefore never needs to poll or retry: ask once, handle the event.
    /// [`clipboard_readable`](Self::clipboard_readable) is the way to find out
    /// in advance that the answer will not be immediate.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`], or
    /// [`ShellError::InvalidWindow`] for a stale handle. An empty clipboard is
    /// **not** an error — it is an answer.
    fn clipboard_request(
        &mut self,
        window: WindowId,
        mime: MimeType,
    ) -> Result<ClipboardRequestId, ShellError>;

    /// Whether a [`clipboard_request`](Self::clipboard_request) issued for
    /// `window` right now could be answered without waiting.
    ///
    /// What a "Paste" menu item greys out on, and the visible form of a
    /// platform rule that is otherwise invisible: **on Wayland a client is told
    /// what is on the clipboard only while one of its windows has keyboard
    /// focus**, and only asynchronously, so a background window genuinely
    /// cannot read the clipboard. `clipboard_request` still works there — it
    /// holds the request — but it may take until focus arrives, and a UI that
    /// would rather not offer the action than offer a slow one asks here first.
    ///
    /// `false` for a stale handle, and for a backend without
    /// [`ShellCaps::CLIPBOARD`].
    ///
    /// # A provided method, because most platforms have nothing to say
    ///
    /// The default is "readable whenever the capability is present and the
    /// handle is live", which is exactly right for X11 (any window may
    /// `ConvertSelection` at any time, focus is not involved), for Win32, and
    /// for [`HeadlessShell`] in its default configuration. Only a backend that
    /// really has a gate overrides it — so this is a fact a consumer can rely
    /// on, not ceremony every backend has to perform.
    ///
    /// The staleness half goes through
    /// [`window_state`](Self::window_state) rather than being left to each
    /// implementation. P0.6 found the earlier default — which ignored `window`
    /// entirely — contradicting the "`false` for a stale handle" sentence
    /// above: both backends that existed had *overridden* it and so had
    /// covered for it, and the first backend to accept the default inherited
    /// the bug. A default that cannot keep its own promise is worse than no
    /// default.
    fn clipboard_readable(&self, window: WindowId) -> bool {
        self.caps().contains(ShellCaps::CLIPBOARD) && self.window_state(window).is_ok()
    }

    /// A token another program can raise its own window with, made from
    /// `window` and the latest input this program received.
    ///
    /// What a notification daemon sends as the notification spec's
    /// `ActivationToken` before `ActionInvoked`, and what a launcher puts in a
    /// child's `XDG_ACTIVATION_TOKEN`: the receiver hands it back to its window
    /// system, which raises the window if it accepts the token. Ask for it in
    /// answer to the click that warrants it, since the window system judges a
    /// token by the input it was made from.
    ///
    /// `Ok(None)` where the window system has no such thing: Wayland without
    /// `xdg-activation-v1`, and every other backend, whose default this is.
    /// Wayland waits for the compositor's answer, a round trip or more.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] for a stale handle, or
    /// [`ShellError::Backend`] where the window system has the mechanism but
    /// gave no token.
    fn activation_token(&mut self, window: WindowId) -> Result<Option<String>, ShellError> {
        self.window_state(window).map(|_| None)
    }

    /// Tells the input method where text is being entered, so it can put its
    /// composition window and candidate list there instead of at a corner of the
    /// screen.
    ///
    /// `area` is the text field's caret, or the line it sits on, in the
    /// window's **client** device pixels; the candidate list opens beside it
    /// without covering it. `None` hands placement back to the input method's
    /// default. Call it when a field gains focus and whenever its caret moves.
    /// A hint: the input method may place its windows elsewhere, and nothing
    /// reports where they went.
    ///
    /// # A provided method, and a no-op where there is nothing to place
    ///
    /// Only a backend with an input method that draws its own windows has
    /// anything to do here — Win32's IMM and TSF, a Wayland compositor's
    /// `text-input-v3` cursor rectangle, AppKit's `firstRectForCharacterRange:`.
    /// The default validates the handle and does nothing else, which is exactly
    /// right for the rest. Win32, Wayland and AppKit override it. Wayland
    /// sends the area only while [`set_text_input`](Self::set_text_input)
    /// names a field, since `text-input-v3` has nowhere to put it otherwise;
    /// AppKit answers `firstRectForCharacterRange:` with it whenever asked.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_text_input_area(
        &mut self,
        window: WindowId,
        area: Option<PhysicalRect>,
    ) -> Result<(), ShellError> {
        let _ = area;
        self.window_state(window).map(|_| ())
    }

    /// Limits where `window` takes the pointer to a union of rectangles, so
    /// the pointer anywhere else goes to whatever is behind the window.
    ///
    /// For a transparent window that draws a shape smaller than itself: a
    /// launcher's rounded panel, whose transparent corners should let a click
    /// through to the program beneath. A pixel of alpha zero is otherwise the
    /// window's on every desktop backend; nothing hit-tests by alpha, because
    /// that would read the frame back from the GPU on every pointer move.
    ///
    /// `region` is in the window's **client** device pixels, the units of
    /// [`set_text_input_area`](Self::set_text_input_area). Empty rectangles
    /// are ignored, and parts outside the window take nothing; an empty slice
    /// leaves the window no pointer input at all. `None` gives the whole window
    /// back, which is where every window starts. Keyboard focus is not
    /// affected. The rectangles are the caller's layout, so send them again
    /// after a [`ShellEvent::Resized`] or [`ShellEvent::ScaleFactorChanged`]
    /// that moves the shape. [`PhysicalRect::rounded`] builds them for a
    /// rounded rectangle.
    ///
    /// **Give the outer bound of what the window draws, antialiased edge
    /// included.** On Win32 the region is a window region, which also clips
    /// the window's drawing to it, so a region inside the edge's blend cuts
    /// the edge off. Elsewhere a tighter region only loses the pointer over
    /// the edge.
    ///
    /// A [`Passthrough`](PopupInput::Passthrough) popup stays passthrough: a
    /// region given to it is validated and has no effect.
    ///
    /// # A provided method
    ///
    /// The default validates the handle and does nothing else, which leaves
    /// the whole window taking the pointer. Wayland, X11 and Win32 override it,
    /// and [`ShellCaps::INPUT_REGION`] is set only where it is acted on; a
    /// caller that must have the click-through checks the bit rather than the
    /// platform.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_input_region(
        &mut self,
        window: WindowId,
        region: Option<&[PhysicalRect]>,
    ) -> Result<(), ShellError> {
        let _ = region;
        self.window_state(window).map(|_| ())
    }

    /// Keeps the display on and the screensaver from starting while `window`
    /// asks: `true` to ask, `false` to stop.
    ///
    /// For a game played on a gamepad, or a cutscene, which nothing the system
    /// counts as user activity interrupts. Ask while the game is being played
    /// and stop in the menus, as a video player stops at pause; asking for the
    /// whole session keeps a desktop awake that its user walked away from.
    ///
    /// Per window, because Wayland's `zwp_idle_inhibit_manager_v1` inhibits
    /// per surface, and its compositor honours that only while the surface is
    /// shown; Win32 keeps the display on whether or not the window is. The
    /// display is kept on while **any** window of the shell asks. Asking twice
    /// is asking once, and stopping a window that never asked does nothing.
    /// Destroying a window ends its request, and dropping the shell ends them
    /// all.
    ///
    /// # A provided method
    ///
    /// The default validates the handle and answers
    /// [`ShellError::Unsupported`], since a request nothing acts on would let
    /// the display sleep while the caller thinks otherwise.
    /// [`ShellCaps::IDLE_INHIBIT`] is set only where it is acted on, and says
    /// which backends that is.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale,
    /// [`ShellError::Unsupported`] without [`ShellCaps::IDLE_INHIBIT`], and
    /// [`ShellError::Backend`] if the system refused.
    fn set_idle_inhibit(&mut self, window: WindowId, inhibit: bool) -> Result<(), ShellError> {
        let _ = inhibit;
        self.window_state(window)?;
        Err(ShellError::Unsupported {
            backend: self.backend(),
            what: "idle inhibit",
        })
    }

    /// Opens `url` in the user's web browser, for a store page, a community
    /// link, or the end-user licence and privacy policy.
    ///
    /// Only a [`WebUrl`] is taken: an absolute `http` or `https` URL, checked
    /// by [`WebUrl::parse`] before any backend sees it. The system's own
    /// "open" would also run a program, open a file with whatever is
    /// associated with it, or start any registered protocol handler, and a
    /// game passing on a link a server sent it must never reach any of that;
    /// see the [`url`] module.
    ///
    /// `window` owns whatever the system shows while it opens the browser,
    /// such as Win32's message box when no browser is registered, as Wayland's
    /// `org.freedesktop.portal.OpenURI` takes a parent window. Whether the
    /// browser opened the page is not reported back: success means the system
    /// accepted the request. Leave the browser's window to come forward on its
    /// own; a fullscreen game may want to leave fullscreen first.
    ///
    /// # A provided method
    ///
    /// The default validates the handle and answers
    /// [`ShellError::Unsupported`], since a link that silently does nothing
    /// leaves the player clicking it again. [`ShellCaps::OPEN_URL`] is set
    /// only where it is acted on, and says which backends that is.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale,
    /// [`ShellError::Unsupported`] without [`ShellCaps::OPEN_URL`], and
    /// [`ShellError::Backend`] if the system refused.
    fn open_url(&mut self, window: WindowId, url: &WebUrl) -> Result<(), ShellError> {
        let _ = url;
        self.window_state(window)?;
        Err(ShellError::Unsupported {
            backend: self.backend(),
            what: "opening a URL",
        })
    }

    /// Asks for a [`ShellEvent::FrameReady`] when `window` should present its
    /// next frame.
    ///
    /// For a loop that presents only when told to: a status bar on an output
    /// the compositor has turned off is never asked for a frame there, and a
    /// FIFO present to it can block the loop for as long as the output stays
    /// off. Ask **before** presenting the frame the answer paces, then present
    /// the next one once it comes. The first frame needs no answer.
    ///
    /// ```
    /// # use crcbl_shell::{HeadlessShell, Shell, ShellEvent, WindowDesc};
    /// # let mut shell = HeadlessShell::new();
    /// # let window = shell.create_window(&WindowDesc::default())?;
    /// let mut may_present = true;
    /// # let mut presented = 0;
    /// for _ in 0..3 {
    ///     shell.pump(&mut |event| {
    ///         if let ShellEvent::FrameReady { window: ready } = event {
    ///             may_present |= ready == window;
    ///         }
    ///     });
    ///     if may_present {
    ///         shell.request_frame(window)?;
    ///         // … record and present …
    /// #       presented += 1;
    ///         may_present = false;
    ///     }
    /// }
    /// // With no compositor to hold it back, each answer came at the next pump.
    /// assert_eq!(presented, 3);
    /// # Ok::<(), crcbl_shell::ShellError>(())
    /// ```
    ///
    /// Requests made before the answer comes share it: one `FrameReady`
    /// answers them all. A window destroyed with a request outstanding gets no
    /// answer.
    ///
    /// Where [`ShellCaps::FRAME_CALLBACK`] is set — Wayland, as
    /// `wl_surface.frame` — the compositor answers. The request is surface
    /// state that rides the next commit, which is the one the swapchain's
    /// present makes, and this call commits nothing itself, so a window that
    /// asks and then never presents may never be answered. Everywhere else
    /// the answer comes at the next [`pump`](Self::pump), and
    /// [`wait_events`](Self::wait_events) does not sleep while one is due.
    ///
    /// A required method, unlike its neighbours: a default could validate the
    /// handle but not keep the request, and a request nothing answers stalls
    /// the loop waiting for it.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn request_frame(&mut self, window: WindowId) -> Result<(), ShellError>;

    /// Tells the input method what text field in `window` is taking typing:
    /// `Some(purpose)` as a field gains the keyboard focus, `None` as it loses
    /// it.
    ///
    /// While a field is taking typing, a platform input method composes what
    /// is typed in the window, reporting the composition as
    /// [`TextPreedit`](ShellEvent::TextPreedit) and the result as
    /// [`TextCommit`](ShellEvent::TextCommit). While none is, the input method
    /// keeps out of the way and keys reach the window as keys: one in its
    /// native mode would otherwise turn a game's WASD into a candidate list. A
    /// window starts with none.
    ///
    /// The [`TextPurpose`] says what the field is for. A password or a PIN is
    /// [sensitive](TextPurpose::is_sensitive): nothing typed into it may be
    /// learned, stored or suggested back.
    ///
    /// # A provided method
    ///
    /// The default validates the handle and does nothing else. Wayland acts on
    /// it with `text-input-v3`'s `enable`, `set_content_type` and `disable`;
    /// Win32 associates the window's input context only for a
    /// [`Normal`](TextPurpose::Normal) field, keeping it off for a password or
    /// a PIN as a Windows password box does. AppKit draws the same line by
    /// holding the view's input context to the keyboard layouts for no field
    /// and for a sensitive one, and also holds secure event input while a
    /// password or PIN field's window has the keyboard.
    /// [`ShellCaps::TEXT_IME`] is set only where this is acted on.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_text_input(
        &mut self,
        window: WindowId,
        field: Option<TextPurpose>,
    ) -> Result<(), ShellError> {
        let _ = field;
        self.window_state(window).map(|_| ())
    }

    /// Hands `window`'s accessibility tree, or what changed in it, to the
    /// platform's assistive technologies.
    ///
    /// Send a whole tree (with [`TreeUpdate::tree`](accesskit::TreeUpdate::tree)
    /// set) after each
    /// [`AccessibilityActivated`](ShellEvent::AccessibilityActivated), then
    /// only what changed, each frame something did. An update sent while
    /// nobody is reading — before the activation, or after
    /// [`AccessibilityDeactivated`](ShellEvent::AccessibilityDeactivated) — is
    /// dropped, so a program may also send unconditionally and skip tracking
    /// the two events.
    ///
    /// # A provided method
    ///
    /// The default validates the handle and drops the update, which is right
    /// for a backend with no adapter: it never raises the activation either.
    /// [`ShellCaps::ACCESSIBILITY`] says whether the trees go anywhere.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    #[cfg(feature = "accesskit")]
    fn update_accessibility(
        &mut self,
        window: WindowId,
        update: accesskit::TreeUpdate,
    ) -> Result<(), ShellError> {
        let _ = update;
        self.window_state(window).map(|_| ())
    }
}