lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
use std::{
  ops::Deref,
  sync::{Arc, RwLock, Weak},
};

use crate::{core::Signal, layout::size::Size, node::color::Color};

/// A snapshot of the window's geometry, returned by `ctx.window()`.
///
/// `resolved_*` values are in physical device pixels; `logical_*` divide those
/// by the scale factor and match the coordinate space layout reasons in.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowInfo {
  pub x: i32,
  pub y: i32,
  pub resolved_width: f32,
  pub resolved_height: f32,
  pub scale_factor: f32,
  pub is_minimized: bool,
  pub is_maximized: bool,
  pub is_full_screen: bool,
  pub is_decorated: bool,
  pub is_focused: bool,
  /// Whether the system draws the window's controls itself, over those of a title bar the app draws: on macOS the
  /// three lights of a window whose bar marks its controls (`.window_control(..)`), which are then the system's
  /// own, where the app's are, with what the system does at them (the menu of tilings under the pointer, full
  /// screen at a press). A bar of the app's leaves the room of its controls and draws none of them.
  pub native_controls: bool,
  /// The edges of the window the system draws over or cuts off; see [`SafeAreaInsets`].
  pub safe_area: SafeAreaInsets,
  /// What the person set for the whole system; see [`SystemSettings`].
  pub system: SystemSettings,
}

/// What the system tells an app about itself, heard with `ctx.window().on_app_event(..)`. A phone tells all of
/// it; a desktop tells [`GraphicsDeviceLost`](Self::GraphicsDeviceLost) alone.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AppEvent {
  /// The app is in front and takes input.
  Active,
  /// Something of the system's is over the app, or it is on its way out: the app is seen and takes no input.
  Inactive,
  /// The app is no longer seen. It is given a moment to save what it must, and may be ended without notice.
  Background,
  /// The app is coming back into view.
  Foreground,
  /// The app was opened with a link: its own scheme, or a universal link of its site.
  OpenUrl(String),
  /// The app was opened by one of its shortcuts on the home screen, named by the shortcut's type.
  Shortcut(String),
  /// The way the app's content is turned, told once at the start and again whenever the device is turned to
  /// a way the app allows.
  Rotated(Orientation),
  /// The system has a place for another window of the app and the app has opened none for it: the person
  /// asked for one, on a tablet, or plugged a display in (`external`). The window the app opens next
  /// ([`WindowOpener`](crate::app::WindowOpener)) is shown there; while it opens none the place stays empty,
  /// and a display shows what the device does.
  WindowAsked { external: bool },
  /// The graphics device the window was drawn with was lost (its card was reset, by a driver that hung or was
  /// updated, or taken away), and lurq draws the window with another from its next frame. Told to each window
  /// whose engine was replaced, once lurq let go of everything of its own made with the lost device and the
  /// app's `WgpuFrameExtension`s were told (`device_lost`). What the app made with the lost device itself, a
  /// texture or a pipeline it keeps outside an extension, is gone: it lets go of it and makes it again with the
  /// new device, which its extensions are given.
  GraphicsDeviceLost,
}

/// A way a phone is held, and so the way an app's content is turned. Several are joined with `|` into the
/// [`Orientations`] an app allows: `Orientation::Portrait | Orientation::LandscapeLeft`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Orientation {
  /// Upright.
  Portrait,
  /// Upright the other way up, the device's top at the bottom. A phone with no home button does not turn
  /// its content this way whatever an app allows.
  PortraitUpsideDown,
  /// On its side, the device's top, where its camera is, at the left.
  LandscapeLeft,
  /// On its other side, the device's top at the right.
  LandscapeRight,
}

/// The ways an app lets its content be turned: [`Orientation`]s joined with `|`. Given to the window before
/// it runs; a device turned to a way that is not among them leaves the content as it was. An iOS app's
/// `Info.plist` names the ways it supports too (`UISupportedInterfaceOrientations`), and only those among
/// these that it names are ever taken.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Orientations(u8);

impl Orientations {
  /// Either side.
  pub const LANDSCAPE: Self = Self(0b1100);
  /// Every way.
  pub const ALL: Self = Self(0b1111);

  const fn bit(orientation: Orientation) -> u8 {
    match orientation {
      Orientation::Portrait => 0b0001,
      Orientation::PortraitUpsideDown => 0b0010,
      Orientation::LandscapeLeft => 0b0100,
      Orientation::LandscapeRight => 0b1000,
    }
  }

  pub fn contains(self, orientation: Orientation) -> bool {
    self.0 & Self::bit(orientation) != 0
  }
}

impl From<Orientation> for Orientations {
  fn from(orientation: Orientation) -> Self {
    Self(Self::bit(orientation))
  }
}

impl std::ops::BitOr for Orientation {
  type Output = Orientations;

  fn bitor(self, other: Self) -> Orientations {
    Orientations(Orientations::bit(self) | Orientations::bit(other))
  }
}

impl std::ops::BitOr<Orientation> for Orientations {
  type Output = Self;

  fn bitor(self, other: Orientation) -> Self {
    Self(self.0 | Self::bit(other))
  }
}

impl std::ops::BitOr for Orientations {
  type Output = Self;

  fn bitor(self, other: Self) -> Self {
    Self(self.0 | other.0)
  }
}

impl std::ops::BitOr<Orientations> for Orientation {
  type Output = Orientations;

  fn bitor(self, other: Orientations) -> Orientations {
    Orientations(Orientations::bit(self) | other.0)
  }
}

type AppEventHandler = Arc<dyn Fn(&AppEvent) + Send + Sync>;

/// A tap of the device's haptic engine, played with `ctx.window().haptic(..)`. A phone has one; where there is
/// none, nothing happens.
///
/// The names are the platform's: an impact for something that lands or snaps into place, a selection for a
/// value that changes under the finger, and a notification for how something ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Haptic {
  Light,
  Medium,
  Heavy,
  Selection,
  Success,
  Warning,
  Error,
}

/// How far in from each edge of the window content stays clear of what the device and the system put there: a
/// phone's status bar, camera housing, home indicator and rounded corners. In logical pixels, and zero on a
/// desktop.
///
/// The window covers the whole screen, so a background reaches its edges; content that must be read or
/// touched is padded by these.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SafeAreaInsets {
  pub top: f32,
  pub right: f32,
  pub bottom: f32,
  pub left: f32,
  /// How much more `bottom` is for the on-screen keyboard being up: 0 with the keyboard down. What stands at
  /// the bottom of the window, as a sheet does, rises by it.
  pub keyboard: f32,
}

/// Whether the system is in its light look or its dark one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Appearance {
  #[default]
  Light,
  Dark,
}

/// What a person set for the whole system, which an app is to follow: `ctx.window().system`. A phone tells all
/// of it; a desktop shell tells the appearance, and the rest is as if nothing was set. The theme takes the
/// appearance, the text scale and bold text by itself ([`Theme::apply_system`](crate::app::theme::Theme));
/// the rest is for the app and its components to read.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SystemSettings {
  pub appearance: Appearance,
  /// How much larger than usual the person asked text to be: 1 for the usual size (a phone's Dynamic Type).
  pub text_scale: f32,
  pub bold_text: bool,
  /// Things are not to move across the screen: one takes another's place by fading.
  pub reduce_motion: bool,
  /// Colors are to stand further apart.
  pub increase_contrast: bool,
  /// Nothing is to show through anything: no glass, no blur.
  pub reduce_transparency: bool,
  /// What a color says is to be said some other way too.
  pub differentiate_without_color: bool,
  /// What can be pressed is to look so: an outline or an underline.
  pub button_shapes: bool,
  /// A switch is to say on and off with a mark as well as with its place.
  pub on_off_labels: bool,
}

impl Default for SystemSettings {
  fn default() -> Self {
    Self {
      appearance: Appearance::Light,
      text_scale: 1.0,
      bold_text: false,
      reduce_motion: false,
      increase_contrast: false,
      reduce_transparency: false,
      differentiate_without_color: false,
      button_shapes: false,
      on_off_labels: false,
    }
  }
}

impl WindowInfo {
  pub fn position(&self) -> (i32, i32) {
    (self.x, self.y)
  }

  pub fn resolved_size(&self) -> Size {
    Size::new(self.resolved_width, self.resolved_height)
  }

  pub fn logical_size(&self) -> Size {
    let scale = self.scale_factor.max(f32::EPSILON);
    Size::new(self.resolved_width / scale, self.resolved_height / scale)
  }

  pub fn logical_width(&self) -> f32 {
    self.logical_size().width
  }

  pub fn logical_height(&self) -> f32 {
    self.logical_size().height
  }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowResizeDirection {
  East,
  North,
  NorthEast,
  NorthWest,
  South,
  SouthEast,
  SouthWest,
  West,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowCornerRadius {
  Default,
  None,
  Rounded,
  RoundedSmall,
}

/// The 1px frame the OS compositor draws around a window. Windows 11 draws it around undecorated
/// windows too (DWM `DWMWA_BORDER_COLOR`); other platforms ignore it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WindowBorderColor {
  /// The system color.
  #[default]
  Default,
  /// No compositor border.
  None,
  Color(Color),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowIcon {
  rgba: Vec<u8>,
  width: u32,
  height: u32,
}

impl WindowIcon {
  pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Self {
    assert_eq!(rgba.len(), (width * height * 4) as usize);
    Self { rgba, width, height }
  }

  #[cfg(feature = "raster")]
  pub fn from_image_data(image: &crate::images::ImageData) -> Self {
    Self::from_rgba((*image.data_arc()).clone(), image.width(), image.height())
  }

  pub fn rgba(&self) -> &[u8] {
    &self.rgba
  }

  pub fn width(&self) -> u32 {
    self.width
  }

  pub fn height(&self) -> u32 {
    self.height
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn into_rgba(self) -> (Vec<u8>, u32, u32) {
    (self.rgba, self.width, self.height)
  }
}

/// The icon as an image, to draw in the window: a title bar the app draws itself shows the window's icon so.
#[cfg(feature = "raster")]
impl From<&WindowIcon> for crate::images::ImageData {
  fn from(icon: &WindowIcon) -> Self {
    Self::from_rgba(icon.rgba.clone(), icon.width, icon.height)
  }
}

/// Origin of a vetoable close request. Programmatic `close()` bypasses this path.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CloseRequestSource {
  Os,
  App,
}

/// A one-shot decision that may be moved to another thread or retained for a dialog.
/// Dropping it, or calling `cancel`, keeps the window open. A stale request cannot
/// close a replacement window: it refers only to its original window's queue.
pub struct CloseRequest {
  window: Weak<RwLock<WindowInner>>,
  source: CloseRequestSource,
}

impl CloseRequest {
  pub fn source(&self) -> CloseRequestSource {
    self.source
  }
  pub fn proceed(self) {
    if let Some(window) = self.window.upgrade() {
      let waker = {
        let mut inner = window.write().unwrap();
        inner.queue_command(WindowCommand::Close);
        inner.waker.clone()
      };
      if let Some(waker) = waker {
        waker();
      }
    }
  }
  pub fn cancel(self) {}
}

type CloseHandler = Arc<dyn Fn(CloseRequest) + Send + Sync>;

pub(crate) mod controls;
mod handle;
pub(crate) mod parent;
pub(crate) mod resize;
#[cfg(test)]
mod resize_tests;
#[cfg(test)]
pub(crate) mod simulated_window;
#[cfg(feature = "mcp")]
pub(crate) use handle::DialogWindow;
pub use handle::WindowHandle;
use resize::ResizeRequest;

/// A logical-pixel window region for a partial frame capture, matching the
/// units of [`crate::core::ElementRect`] bounds.
#[cfg(feature = "screenshot")]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScreenshotRegion {
  pub x: f32,
  pub y: f32,
  pub width: f32,
  pub height: f32,
}

// Not `Eq`: synthetic input carries pixel positions.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum WindowCommand {
  /// Play a tap of the device's haptic engine; see [`Haptic`].
  Haptic(Haptic),
  /// Show the system's share sheet for an address; see [`Share`](crate::app::Share).
  Share(crate::app::Share),
  Close,
  RequestClose(CloseRequestSource),
  SetMinimized(bool),
  SetMaximized(bool),
  SetFullScreen(bool),
  SetDecorated(bool),
  SetTitle(String),
  SetTitleBarColor(Option<Color>),
  SetBorderColor(WindowBorderColor),
  SetIcon(Option<WindowIcon>),
  SetCornerRadius(WindowCornerRadius),
  Move {
    x: i32,
    y: i32,
  },
  Resize(ResizeRequest),
  StartDrag,
  StartResize(WindowResizeDirection),
  StopDrag,
  /// Show the system's menu of the window (Restore, Move, Size, Minimize, Maximize, Close) where the pointer is,
  /// as a right press on a title bar the system draws does. Only Windows has one; elsewhere it does nothing.
  ShowSystemMenu,
  InjectInput(crate::app::synthetic_input::SyntheticInput),
  /// Read the OS clipboard and paste it into the focused text input, as
  /// Ctrl+V does: for an app's own Paste menu item. `synthetic` is whether
  /// the request was made while lurq delivered synthetic input (an MCP
  /// click on that menu item); the shell refuses it then, since the
  /// person's clipboard is theirs.
  #[cfg(feature = "clipboard")]
  PasteFromClipboard {
    synthetic: bool,
  },
  #[cfg(feature = "screenshot")]
  Screenshot(std::path::PathBuf, Option<ScreenshotRegion>),
  OpenDevtools,
  CloseDevtools,
  ToggleDevtools,
}

/// Reactive, per-window geometry handle held by the `Tree` and injected into
/// its root `Ctx`. Reads through `ctx.window()` subscribe to changes via the
/// version signal; the shell pushes resize/scale/move updates here.
#[derive(Clone)]
pub struct Window {
  inner: Arc<RwLock<WindowInner>>,
  version_signal: Signal<u64>,
  /// The menu of editing commands a finger asked for, while it is open.
  edit_menu: Signal<Option<EditMenuRequest>>,
  /// The callbacks of [`WindowHandle::on_frame`].
  frames: crate::app::ctx::WindowFrames,
}

/// A menu of editing commands a finger asked for, at a point of the window: three fingers tapped, or text was
/// selected by touch, or a long press placed the caret. lurq shows it over the app by itself (a
/// [`ContextMenu`](crate::ui::ContextMenu)'s bar), and each command runs as its key would
/// ([`EditCommand`](crate::app::events::EditCommand)).
#[derive(Clone, Debug, PartialEq)]
pub struct EditMenuRequest {
  /// Where the menu stands, in logical pixels: the fingers, or the top of what was selected.
  pub x: f32,
  pub y: f32,
  /// Its commands, in order.
  pub commands: Vec<crate::app::events::EditCommand>,
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for EditMenuRequest {
  fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
    formatter.value_debug(self);
  }
}

/// Where a command of going back or forward starts; see [`HistoryEvent`](crate::app::events::HistoryEvent).
#[derive(Clone)]
pub(crate) enum NavigationOrigin {
  /// The focused element, or with none the last element that hears the command.
  Focus,
  /// The element under a point of the window, in logical pixels, then as `Focus`.
  Point(f32, f32),
  /// A part of the window: the focused element in it, or the last element in it that hears the command.
  Part(crate::core::ElementRef),
}

/// What runs once a command asked for without input has gone through the window: told whether something took it.
pub(crate) type NavigationDone = Box<dyn FnOnce(bool) + Send + Sync>;

/// A command of going back or forward the app asked for without input, for the tree to run after the event.
pub(crate) struct NavigationRequest {
  pub(crate) command: crate::app::events::NavigationCommand,
  pub(crate) source: crate::app::events::NavigationSource,
  pub(crate) origin: NavigationOrigin,
  pub(crate) done: Option<NavigationDone>,
}

/// Wakes the shell's event loop so a command pushed from another thread is
/// processed without waiting for the next OS event.
pub(crate) type WindowWaker = Arc<dyn Fn() + Send + Sync>;

#[cfg(target_arch = "wasm32")]
thread_local! {
  /// Whether the shell's loop is in a turn: between the start of a batch of events and the end of the pass
  /// that follows them. See [`Window::off_loop_waker`].
  static IN_LOOP_TURN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// The shell says when a turn of its loop starts and ends.
#[cfg(target_arch = "wasm32")]
#[cfg_attr(not(feature = "winit"), allow(dead_code))]
pub(crate) fn set_in_loop_turn(in_turn: bool) {
  IN_LOOP_TURN.with(|turn| turn.set(in_turn));
}

struct WindowInner {
  #[cfg(feature = "mcp")]
  accepted_close: bool,
  /// The file dialog broker of the tree the window is of, where the tree registered one.
  #[cfg(feature = "mcp")]
  file_dialogs: crate::mcp::ServingBroker,
  /// How many times the window lost focus; input an MCP client holds is released by the next loss.
  #[cfg(feature = "mcp")]
  focus_losses: u64,
  info: WindowInfo,
  corner_radius: WindowCornerRadius,
  border_color: WindowBorderColor,
  /// How much of the window's top the app's own title bar is drawn over.
  title_bar_inset: f32,
  /// `None` until the shell creates the window or the app sets a title.
  title: Option<String>,
  version: u64,
  commands: Vec<WindowCommand>,
  /// Registered by the shell once its event loop exists. Without it, a
  /// cross-thread `push_command` sat unprocessed while the loop idled in
  /// `ControlFlow::Wait`.
  waker: Option<WindowWaker>,
  /// The thread that registered `waker`, which runs the event loop.
  loop_thread: Option<std::thread::ThreadId>,
  /// Set once a platform shell applies this window's commands; a headless tree has none.
  shell_attached: bool,
  resize_reports: resize::ResizeReports,
  /// The system's handles of the window, recorded by the shell: the parent of a dialog of the system.
  parent: Option<parent::ParentWindow>,
  close_handler: Option<CloseHandler>,
  app_event_handler: Option<AppEventHandler>,
  /// Where the window's controls are, in a title bar the app draws itself: what the tree found at its last
  /// layout, for a shell that tells the system. See `controls`.
  controls: Arc<controls::WindowControlRegions>,
  /// The window's icon as the app set it, and as an image to draw in a title bar the app draws itself.
  icon: Option<WindowIcon>,
  #[cfg(feature = "raster")]
  icon_image: Option<crate::images::ImageData>,
  /// Texts the app asked to be put on the clipboard, which the runtime writes after the event that asked, each with
  /// what is told whether it was written.
  copies: Vec<(String, Option<CopyDone>)>,
  /// Undos and redos the app asked for without a key (an Edit menu), which the runtime runs on the focused element
  /// after the event that asked.
  edits: Vec<(crate::app::events::EditCommand, bool)>,
  /// Going back or forward the app asked for without input (`Ctx::history_back`, a stack's back button, a browser's
  /// back), which the runtime runs after the event that asked.
  navigations: Vec<NavigationRequest>,
}

impl WindowInner {
  fn queue_command(&mut self, command: WindowCommand) {
    #[cfg(feature = "mcp")]
    if command == WindowCommand::Close {
      self.accepted_close = true;
    }
    self.commands.push(command);
  }

  /// Queues a resize under the caller's lock; returns the waker to call once the lock is released.
  #[cfg_attr(not(feature = "mcp"), allow(dead_code))]
  fn queue_resize(&mut self, request: ResizeRequest) -> Option<WindowWaker> {
    self.queue_command(WindowCommand::Resize(request));
    self.waker.clone()
  }
}

impl Default for Window {
  fn default() -> Self {
    Self::new()
  }
}

impl Window {
  pub fn new() -> Self {
    Self {
      inner: Arc::new(RwLock::new(WindowInner {
        #[cfg(feature = "mcp")]
        accepted_close: false,
        #[cfg(feature = "mcp")]
        file_dialogs: crate::mcp::ServingBroker::default(),
        #[cfg(feature = "mcp")]
        focus_losses: 0,
        info: WindowInfo {
          x: 0,
          y: 0,
          resolved_width: 0.0,
          resolved_height: 0.0,
          scale_factor: 1.0,
          is_minimized: false,
          is_maximized: false,
          is_full_screen: false,
          is_decorated: true,
          is_focused: true,
          native_controls: false,
          safe_area: SafeAreaInsets::default(),
          system: SystemSettings::default(),
        },
        corner_radius: WindowCornerRadius::Default,
        border_color: WindowBorderColor::Default,
        title_bar_inset: 0.0,
        title: None,
        version: 0,
        commands: Vec::new(),
        waker: None,
        loop_thread: None,
        shell_attached: false,
        resize_reports: resize::ResizeReports::default(),
        parent: None,
        close_handler: None,
        app_event_handler: None,
        controls: Arc::default(),
        icon: None,
        #[cfg(feature = "raster")]
        icon_image: None,
        copies: Vec::new(),
        edits: Vec::new(),
        navigations: Vec::new(),
      })),
      version_signal: Signal::new(0),
      edit_menu: Signal::new(None),
      frames: crate::app::ctx::WindowFrames::default(),
    }
  }

  /// The shell records the system's handles of the window it made, and clears them as the window goes.
  #[cfg_attr(not(all(feature = "winit", windows)), allow(dead_code))]
  pub(crate) fn set_parent(&self, parent: Option<parent::ParentWindow>) {
    self.inner.write().unwrap().parent = parent;
  }

  /// The system's handles of the window, where the shell recorded them.
  pub(crate) fn parent(&self) -> Option<parent::ParentWindow> {
    self.inner.read().unwrap().parent
  }

  /// Tells the window which file dialog broker serves it: its tree's.
  #[cfg(feature = "mcp")]
  pub(crate) fn serve_file_dialogs(&self, broker: &crate::mcp::ServingBroker) {
    if self.inner.read().unwrap().file_dialogs.is(broker) {
      return;
    }
    self.inner.write().unwrap().file_dialogs = broker.clone();
  }

  /// The file dialog broker of the window's tree, while it lives: what a dialog of lurq's own over this window
  /// asks in place of the system.
  #[cfg(feature = "mcp")]
  pub(crate) fn file_dialog_broker(&self) -> Option<crate::mcp::FileDialogBroker> {
    self.inner.read().unwrap().file_dialogs.broker()
  }

  pub(crate) fn set_app_event_handler(&self, handler: Option<AppEventHandler>) {
    self.inner.write().unwrap().app_event_handler = handler;
  }

  #[cfg_attr(not(target_os = "ios"), allow(dead_code))]
  pub(crate) fn has_app_event_handler(&self) -> bool {
    self.inner.read().unwrap().app_event_handler.is_some()
  }

  /// Gives the window's handler something the system said of the app.
  pub(crate) fn dispatch_app_event(&self, event: &AppEvent) {
    // Never hold the state lock across application code.
    let handler = self.inner.read().unwrap().app_event_handler.clone();
    if let Some(handler) = handler {
      handler(event);
    }
  }

  /// The single event-loop entry point for OS, queued app and MCP requests.
  pub(crate) fn dispatch_close_request(&self, source: CloseRequestSource) {
    let handler = self.inner.read().unwrap().close_handler.clone();
    let request = CloseRequest {
      window: Arc::downgrade(&self.inner),
      source,
    };
    // Never hold the state lock across application code (which may close/register).
    if let Some(handler) = handler {
      handler(request);
    } else {
      request.proceed();
    }
  }

  #[cfg(feature = "mcp")]
  pub(crate) fn close_queued(&self) -> bool {
    self.inner.read().unwrap().commands.contains(&WindowCommand::Close)
  }

  /// Whether a close of this window was accepted (queued for the shell), even if already applied.
  #[cfg(feature = "mcp")]
  pub(crate) fn close_accepted(&self) -> bool {
    self.inner.read().unwrap().accepted_close
  }

  /// How many times the window has lost focus.
  #[cfg(feature = "mcp")]
  pub(crate) fn focus_losses(&self) -> u64 {
    self.inner.read().unwrap().focus_losses
  }

  /// Records the window's icon, which the app set; what reads it is told, and the loop woken.
  pub(crate) fn set_icon(&self, icon: Option<WindowIcon>) {
    let (version, waker) = {
      let mut inner = self.inner.write().unwrap();
      if inner.icon == icon {
        return;
      }
      #[cfg(feature = "raster")]
      {
        inner.icon_image = icon.as_ref().map(crate::images::ImageData::from);
      }
      inner.icon = icon;
      (Self::bump_version(&mut inner), inner.waker.clone())
    };
    self.version_signal.set(version);
    if let Some(waker) = waker {
      waker();
    }
  }

  /// Asks for `text` to be put on the clipboard; the runtime writes it after the event, or at the next pass.
  pub(crate) fn request_copy(&self, text: String) {
    self.push_copy(text, None);
  }

  /// Asks for `text` to be put on the clipboard, as [`request_copy`](Self::request_copy) does, and calls `done` with
  /// whether it was written, once it is.
  pub(crate) fn request_copy_then(&self, text: String, done: impl FnOnce(bool) + Send + Sync + 'static) {
    self.push_copy(text, Some(Box::new(done)));
  }

  fn push_copy(&self, text: String, done: Option<CopyDone>) {
    let waker = {
      let mut inner = self.inner.write().unwrap();
      inner.copies.push((text, done));
      inner.waker.clone()
    };
    if let Some(waker) = waker {
      waker();
    }
  }

  /// The texts asked to be put on the clipboard since the last time, in order.
  pub(crate) fn take_copies(&self) -> Vec<(String, Option<CopyDone>)> {
    std::mem::take(&mut self.inner.write().unwrap().copies)
  }

  /// Asks for `command` to be run on the focus, marked when it was asked while lurq delivered synthetic input: a
  /// paste of such a request reads no clipboard.
  pub(crate) fn request_edit(&self, command: crate::app::events::EditCommand) {
    let synthetic = crate::app::events::is_synthetic_input();
    let waker = {
      let mut inner = self.inner.write().unwrap();
      inner.edits.push((command, synthetic));
      inner.waker.clone()
    };
    if let Some(waker) = waker {
      waker();
    }
  }

  /// Whether a command of editing, of going back or forward, or a copy was asked for and waits for the tree's next
  /// pass: an Edit menu's item, which asks from outside any event, has the pass run at once for it.
  pub(crate) fn has_requests(&self) -> bool {
    let inner = self.inner.read().unwrap();
    !inner.edits.is_empty() || !inner.navigations.is_empty() || !inner.copies.is_empty()
  }

  /// The commands asked for since the last time, in order, each with whether synthetic input asked for it.
  pub(crate) fn take_edits(&self) -> Vec<(crate::app::events::EditCommand, bool)> {
    std::mem::take(&mut self.inner.write().unwrap().edits)
  }

  /// Asks for a command of going back or forward to be run once the event that asked is handled (or at the next
  /// pass, asked from elsewhere).
  pub(crate) fn request_navigation(&self, request: NavigationRequest) {
    let waker = {
      let mut inner = self.inner.write().unwrap();
      inner.navigations.push(request);
      inner.waker.clone()
    };
    if let Some(waker) = waker {
      waker();
    }
  }

  /// The commands of going back or forward asked for since the last time, in order.
  pub(crate) fn take_navigations(&self) -> Vec<NavigationRequest> {
    std::mem::take(&mut self.inner.write().unwrap().navigations)
  }

  /// The window's icon, as the app set it.
  pub(crate) fn icon(&self) -> Option<WindowIcon> {
    self.inner.read().unwrap().icon.clone()
  }

  /// The window's icon as an image, the same one each time it is asked for, so that it is uploaded once.
  #[cfg(feature = "raster")]
  pub(crate) fn icon_image(&self) -> Option<crate::images::ImageData> {
    self.inner.read().unwrap().icon_image.clone()
  }

  pub(crate) fn track_access(&self) {
    let _ = self.version_signal.get();
  }

  pub(crate) fn info(&self) -> WindowInfo {
    self.inner.read().unwrap().info
  }

  #[allow(dead_code)]
  pub(crate) fn corner_radius(&self) -> WindowCornerRadius {
    self.inner.read().unwrap().corner_radius
  }

  /// The callbacks of [`WindowHandle::on_frame`].
  pub(crate) fn frames(&self) -> &crate::app::ctx::WindowFrames {
    &self.frames
  }

  pub(crate) fn handle(&self) -> WindowHandle {
    WindowHandle {
      info: self.info(),
      window: self.clone(),
    }
  }

  /// Records the title a window is created with, unless the app already set
  /// one (its `SetTitle` command is still queued and wins).
  pub(crate) fn record_initial_title(&self, title: &str) {
    let mut inner = self.inner.write().unwrap();
    if inner.title.is_none() {
      inner.title = Some(title.to_owned());
    }
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn take_commands(&self) -> Vec<WindowCommand> {
    std::mem::take(&mut self.inner.write().unwrap().commands)
  }

  /// Resolve one generation of app requests on the event-loop thread. Requests
  /// queued by a callback remain for the next turn, avoiding recursive handlers.
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn take_shell_commands(&self) -> Vec<WindowCommand> {
    let mut result = Vec::new();
    for command in self.take_commands() {
      if let WindowCommand::RequestClose(source) = command {
        self.dispatch_close_request(source);
      } else {
        result.push(command);
      }
    }
    for command in self.take_commands() {
      if matches!(command, WindowCommand::RequestClose(_)) {
        self.push_command(command);
      } else {
        result.push(command);
      }
    }
    result
  }

  #[cfg(all(feature = "winit", target_os = "macos"))]
  pub(crate) fn requeue_command(&self, command: WindowCommand) {
    self.push_command(command);
  }

  fn push_command(&self, command: WindowCommand) {
    let waker = {
      let mut inner = self.inner.write().unwrap();
      inner.queue_command(command);
      inner.waker.clone()
    };
    // Invoked outside the lock: the waker may re-enter window state.
    if let Some(waker) = waker {
      waker();
    }
  }

  /// Registers the shell's event-loop waker; every subsequent `push_command`
  /// invokes it so commands queued from other threads are drained promptly.
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_waker(&self, waker: WindowWaker) {
    let mut inner = self.inner.write().unwrap();
    inner.waker = Some(waker);
    inner.loop_thread = Some(std::thread::current().id());
  }

  /// Registers the platform shell that applies this window's commands, with its event-loop waker.
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn attach_shell(&self, waker: WindowWaker) {
    self.set_waker(waker);
    self.inner.write().unwrap().shell_attached = true;
  }

  /// Wakes the host for paint work without queuing a component/window mutation.
  pub(crate) fn wake(&self) {
    let waker = self.inner.read().unwrap().waker.clone();
    if let Some(waker) = waker {
      waker();
    }
  }

  /// A waker for work that finishes outside the event loop (timers started, futures and queries that can make
  /// progress): it wakes the shell attached to the window when it is called, and does nothing once the window is
  /// gone.
  pub(crate) fn loop_waker(&self) -> WindowWaker {
    let window = Arc::downgrade(&self.inner);
    Arc::new(move || {
      let wake = window.upgrade().and_then(|window| window.read().unwrap().waker.clone());
      if let Some(wake) = wake {
        wake();
      }
    })
  }

  /// A waker for writes made off the event loop's thread, such as a `Signal` set from a Tokio task or a
  /// `std::thread`: called from any other thread it wakes the attached shell, so the loop picks the write up at
  /// once instead of at its next event. On the loop's own thread, whose turn picks the write up already, and
  /// once the window is gone, it does nothing.
  ///
  /// A page has one thread, and what the browser calls on it between the loop's turns (a promise that settled,
  /// a listener of the page, a timer) is as far from a turn as another thread is: there the shell is woken
  /// unless a turn is running.
  pub(crate) fn off_loop_waker(&self) -> WindowWaker {
    let window = Arc::downgrade(&self.inner);
    Arc::new(move || {
      let wake = window.upgrade().and_then(|window| {
        let window = window.read().unwrap();
        let in_turn = window.loop_thread == Some(std::thread::current().id());
        #[cfg(target_arch = "wasm32")]
        let in_turn = in_turn && IN_LOOP_TURN.with(std::cell::Cell::get);
        if in_turn { None } else { window.waker.clone() }
      });
      if let Some(wake) = wake {
        wake();
      }
    })
  }

  pub fn version(&self) -> u64 {
    self.inner.read().unwrap().version
  }

  pub(crate) fn set_resolved_size(&self, width: f32, height: f32) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.resolved_width == width && inner.info.resolved_height == height {
        return;
      }
      inner.info.resolved_width = width;
      inner.info.resolved_height = height;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  pub(crate) fn set_scale_factor(&self, scale_factor: f32) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.scale_factor == scale_factor {
        return;
      }
      inner.info.scale_factor = scale_factor;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  pub(crate) fn set_position(&self, x: i32, y: i32) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.x == x && inner.info.y == y {
        return;
      }
      inner.info.x = x;
      inner.info.y = y;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_minimized(&self, minimized: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.is_minimized == minimized {
        return;
      }
      inner.info.is_minimized = minimized;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_maximized(&self, maximized: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.is_maximized == maximized {
        return;
      }
      inner.info.is_maximized = maximized;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_full_screen(&self, full_screen: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.is_full_screen == full_screen {
        return;
      }
      inner.info.is_full_screen = full_screen;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  /// The system draws the window's controls over the app's own, or no longer does.
  #[cfg_attr(not(all(feature = "winit", target_os = "macos")), allow(dead_code))]
  pub(crate) fn set_native_controls(&self, native: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.native_controls == native {
        return;
      }
      inner.info.native_controls = native;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  /// Where the window's controls are, as the tree last laid them out.
  #[cfg_attr(not(all(feature = "winit", target_os = "macos")), allow(dead_code))]
  pub(crate) fn control_regions(&self) -> Arc<controls::WindowControlRegions> {
    self.inner.read().unwrap().controls.clone()
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_decorated(&self, decorated: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.is_decorated == decorated {
        return;
      }
      inner.info.is_decorated = decorated;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  /// The menu of editing commands a finger asked for, while it is open: read so that what reads it is rendered
  /// again when it opens or closes.
  pub fn edit_menu(&self) -> Option<EditMenuRequest> {
    self.edit_menu.get()
  }

  /// The signal that holds the menu of editing commands a finger asked for: `None` closes it.
  pub fn edit_menu_signal(&self) -> Signal<Option<EditMenuRequest>> {
    self.edit_menu.clone()
  }

  /// Opens the menu of editing commands at a point, or closes it with `None`.
  pub fn set_edit_menu(&self, menu: Option<EditMenuRequest>) {
    if self.edit_menu.get_untracked() != menu {
      self.edit_menu.set(menu);
    }
  }

  /// Sets the insets a shell read from the platform. Public for tests and for shells outside the crate.
  pub fn set_safe_area(&self, safe_area: SafeAreaInsets) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.safe_area == safe_area {
        return;
      }
      inner.info.safe_area = safe_area;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  /// Sets what a shell read of the system's settings. Public for tests and for shells outside the crate.
  pub fn set_system_settings(&self, system: SystemSettings) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.system == system {
        return;
      }
      inner.info.system = system;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_focused(&self, focused: bool) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.info.is_focused == focused {
        return;
      }
      inner.info.is_focused = focused;
      #[cfg(feature = "mcp")]
      if !focused {
        inner.focus_losses += 1;
      }
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_corner_radius(&self, radius: WindowCornerRadius) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.corner_radius == radius {
        return;
      }
      inner.corner_radius = radius;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  /// The tree says where the window's controls are, after a layout. Nothing that reads the window is told: only
  /// a shell asks, at the system's hit test.
  pub(crate) fn set_control_regions(&self, regions: controls::WindowControlRegions) {
    let mut inner = self.inner.write().unwrap();
    if *inner.controls != regions {
      inner.controls = Arc::new(regions);
    }
  }

  /// Which of the window's controls is at a point of the window, in physical pixels, as the tree last laid them
  /// out: the element the app marked with `.window_control(..)`, where nothing covers it.
  #[cfg_attr(not(all(feature = "winit", windows)), allow(dead_code))]
  pub(crate) fn control_at(&self, x: f32, y: f32) -> Option<crate::node::WindowControl> {
    let (regions, scale) = {
      let inner = self.inner.read().unwrap();
      if inner.controls.is_empty() {
        return None;
      }
      (inner.controls.clone(), inner.info.scale_factor.max(0.01))
    };
    regions.at(x / scale, y / scale)
  }

  pub(crate) fn set_title_bar_inset(&self, inset: f32) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.title_bar_inset == inset {
        return;
      }
      inner.title_bar_inset = inset;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_border_color(&self, color: WindowBorderColor) {
    let version = {
      let mut inner = self.inner.write().unwrap();
      if inner.border_color == color {
        return;
      }
      inner.border_color = color;
      Self::bump_version(&mut inner)
    };
    self.version_signal.set(version);
  }

  fn bump_version(inner: &mut WindowInner) -> u64 {
    inner.version = inner.version.wrapping_add(1);
    inner.version
  }
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod orientation_tests {
  use super::{Orientation, Orientations};

  #[test]
  fn orientations_joined_with_or_are_the_ones_named() {
    let allowed = Orientation::Portrait | Orientation::LandscapeLeft;
    assert!(allowed.contains(Orientation::Portrait));
    assert!(allowed.contains(Orientation::LandscapeLeft));
    assert!(!allowed.contains(Orientation::LandscapeRight));
    assert!(!allowed.contains(Orientation::PortraitUpsideDown));

    let more = allowed | Orientation::LandscapeRight;
    assert_eq!(more, Orientation::Portrait | Orientations::LANDSCAPE);
    assert_eq!(more | Orientation::PortraitUpsideDown, Orientations::ALL);
    assert_eq!(
      Orientations::from(Orientation::Portrait) | Orientations::LANDSCAPE,
      more
    );
  }
}

/// What is told whether a copy the app asked for was written.
pub(crate) type CopyDone = Box<dyn FnOnce(bool) + Send + Sync>;