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
//! 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
pub
pub
pub
pub
pub
pub
/// 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.
pub use 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.
pub use e2e as x11_test_support;
pub use session_support;
pub use ;
pub use ShellCaps;
pub use ;
pub use ;
pub use ShellError;
pub use ShellEvent;
pub use ;
pub use HeadlessShell;
pub use ;
pub use ;
pub use ShellWaker;
pub use ;
/// 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 ;
/// Cross-seam vocabulary from `crcbl-core`: the input-event clock, the key
/// names, and the one sanctioned platform leak.
pub use ;
use 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.