teksilo-core 0.24.2

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Configuration for creating a new window.
//!
//! Consumed by either the app builder's "initial window" at startup or
//! [`EventContext::open_window`](crate::widget::EventContext) from
//! handler code. The two paths share the same config and produce the
//! same windows — there is no "initial vs runtime" split.

use std::rc::Rc;

use crate::signal::Prop;
use crate::widget::EventContext;
use crate::widget_id::WidgetId;
use crate::widget_tree::WidgetTree;

use super::close_decision::CloseDecision;
use super::decorations::DecorationsMode;
use super::icon::WindowIcon;
use super::id::TeksiloWindowId;
use super::placement::WindowPlacement;
use super::state::WindowState;

/// Parent + focus wiring for a modal window.
///
/// Modal is an `Option<ModalConfig>` on [`WindowConfig`]; the type
/// system enforces that a modal always names a parent, something a
/// `modal: bool` + `parent: Option<...>` split could not express.
#[derive(Debug, Clone)]
pub struct ModalConfig {
    /// Window whose input is blocked while this modal is open. Also
    /// the window the modal is transient for (Z-order parent on every
    /// OS).
    pub parent: TeksiloWindowId,
    /// Explicit initial-focus target inside the modal's root subtree.
    /// When `None` the framework falls back to the root widget's
    /// `initial_focus_hint`, then `first_focusable_descendant`.
    pub focus_target: Option<WidgetId>,
}

/// Signature of a window's root-builder closure.
///
/// Receives a mutable [`WidgetTree`] and a cloned [`WindowState`] so
/// the builder can register widgets that bind against window-level
/// signals (placement, title, size, …).
pub type RootBuilder = Box<dyn FnOnce(&mut WidgetTree, WindowState) -> WidgetId>;

/// Per-window post-root hook. Runs after the user's `root_builder`
/// returns, with the resulting `WidgetId`. The hook may wrap the user
/// root in another widget and return the wrapper's id, or simply return
/// the original id unchanged. Used by the debug inspector to splice an
/// inspector shell around every window's root in debug builds.
pub type PostRootBuilder = Box<dyn FnOnce(&mut WidgetTree, WidgetId) -> WidgetId>;

/// Verdict returned by a window's [close guard](WindowConfig::on_close_requested)
/// when the user (or the app) asks to close the window, or a quit asks it.
///
/// The guard runs *before* the window's tree is torn down, and answers now
/// ([`Close`](CloseResponse::Close), [`Veto`](CloseResponse::Veto)) or
/// later ([`Defer`](CloseResponse::Defer)). A guard that asks the user
/// first (a "you have unsaved changes" dialog) defers, and the dialog's
/// answer settles the close through the [`CloseDecision`].
#[derive(Debug, Clone)]
pub enum CloseResponse {
    /// Proceed with closing the window.
    Close,
    /// Refuse: the window stays open. A final no: a quit that asked is
    /// abandoned at once.
    Veto,
    /// Answer later, through the [`CloseDecision`]: the window stays open
    /// until [`proceed`](CloseDecision::proceed) closes it, and
    /// [`cancel`](CloseDecision::cancel) (or dropping every clone
    /// unanswered) leaves it open. A quit that asked waits for the answer,
    /// with the window brought to the front, and goes on or is abandoned
    /// with it. Until then, another close of the window asks nothing and
    /// brings it forward, and a quit adopts the answer rather than asking
    /// again.
    Defer(CloseDecision),
}

/// Signature of a window's close-request guard.
///
/// Invoked with a real [`EventContext`] for the window's own tree, so
/// the guard can show a confirmation dialog, open a modal child, set
/// signals, or fire intents before deciding. It is consulted on every
/// user-initiated close attempt (OS close button / `Alt+F4` / `Cmd+W`,
/// a custom-chrome close button, and
/// [`EventContext::close_window`](crate::widget::EventContext::close_window))
/// and by a guarded quit
/// ([`EventContext::quit`](crate::widget::EventContext::quit)), and may
/// run many times over a window's lifetime, so it is an `Fn`, not an
/// `FnOnce`. It is not asked again while an answer it deferred is
/// pending.
///
/// It is **not** consulted for a
/// [`close_window_forced`](crate::widget::EventContext::close_window_forced),
/// nor for framework-internal teardown (modal cleanup, the last-window
/// shutdown drain).
pub type CloseGuard = Rc<dyn Fn(&mut EventContext) -> CloseResponse>;

/// Signature of the [`on_close_blocked`](WindowConfig::on_close_blocked)
/// callback: the `Fn`-shaped hook fired when the
/// [`can_close`](WindowConfig::can_close) sugar signal blocks a close.
/// Runs with the window's [`EventContext`] so it can present the
/// confirmation UI, and owns the [`CloseDecision`] of that close: answer it
/// with [`proceed`](CloseDecision::proceed) or
/// [`cancel`](CloseDecision::cancel), now or later.
pub type CloseBlockedCallback = Rc<dyn Fn(&mut EventContext, CloseDecision)>;

/// Snapshot handed to a [`WindowConfig::on_removed`] callback once its
/// window has finished tearing down.
///
/// There is no [`EventContext`] here, unlike [`CloseGuard`] /
/// [`CloseBlockedCallback`]: those run *before* teardown, while the
/// window's own tree is still alive to build a context from; `on_removed`
/// runs *after* — the tree, platform window, and every framework
/// registry entry for this window are already gone (see `on_removed`'s
/// doc comment for exactly where in teardown it fires).
#[derive(Debug, Clone)]
pub struct WindowRemovedEvent {
    /// Identity of the window that was just removed. Redundant with
    /// whatever the closure already captured — a `WindowConfig` callback
    /// is inherently per-window — but useful when one closure is shared
    /// across several windows (e.g. `Rc<dyn Fn>` cloned onto every window
    /// opened for the same document).
    pub id: TeksiloWindowId,
    /// The window's `string_id`, if it had one (persistence key / stable
    /// handle apps use to correlate a window with their own bookkeeping).
    pub string_id: Option<String>,
    /// How many windows remain across the whole app, counted AFTER this
    /// one's removal. `0` means this was the last window standing. The
    /// framework has no notion of "this app's Work/document" grouping —
    /// an app that needs a *scoped* last-window answer (e.g. "last window
    /// for this particular Work") combines this fact with its own
    /// window-to-Work bookkeeping; this field only answers "last window,
    /// full stop".
    pub remaining_windows: usize,
}

/// Signature of the [`on_removed`](WindowConfig::on_removed) callback —
/// the framework's window-teardown hook. See [`WindowRemovedEvent`] and
/// [`WindowConfig::on_removed`] for exactly when it runs and what it
/// receives.
pub type WindowRemovedCallback = Rc<dyn Fn(&WindowRemovedEvent)>;

/// Configuration for creating a new window.
pub struct WindowConfig {
    pub title: String,
    pub string_id: Option<String>,
    /// The application id the desktop matches this window against, on the
    /// platforms that have one.
    ///
    /// Set it to the basename of the installed desktop entry, without the
    /// `.desktop` suffix, and matching the reverse-DNS convention that entry
    /// already follows: `"eu.example.MyApp"`.
    ///
    /// **Wayland**: this becomes the toplevel's `xdg_toplevel.set_app_id`. A
    /// toplevel that sends none cannot be tied to its desktop entry at all, so
    /// the shell shows the window as a separate unnamed entry carrying the
    /// generic fallback icon, however many icons the application installed.
    /// `StartupWMClass` in the desktop entry does not rescue it: a Wayland
    /// compositor has no `WM_CLASS` to put there, and GNOME reads that key for
    /// X11 windows only. Portals attribute notifications by the same id.
    ///
    /// **X11**: it becomes `WM_CLASS`. Without it winit falls back to the
    /// executable's own name, which is right often enough that the Wayland
    /// half of this gap goes unnoticed on an X11 session.
    ///
    /// **Windows and macOS**: ignored. Neither identifies a window this way.
    ///
    /// `None` by default, which leaves winit's own behaviour untouched.
    pub app_id: Option<String>,
    pub size: (u32, u32),
    pub position: Option<(i32, i32)>,
    pub min_size: Option<(u32, u32)>,
    pub max_size: Option<(u32, u32)>,
    /// Whether this window's geometry is **restored** from the persisted
    /// window state at creation. Default `true`.
    ///
    /// Persisting and restoring are usually the same decision, so
    /// [`string_id`](Self::string_id) normally governs both. They come apart in
    /// one common case: a **multi-window (or multi-process) app where every
    /// window shares one geometry slot.** Restoring the saved geometry into
    /// *every* window would stack them exactly on top of each other; you want
    /// the first window to land where the user left it, and any window opened
    /// alongside it to be placed by the OS (which cascades). But you still want
    /// every window to *save* its geometry, so whichever the user moved or
    /// closed last is what reopens next time — the behaviour of Word, Firefox
    /// and most document apps.
    ///
    /// Set `false` for those later windows: they still persist under their
    /// `string_id`, they simply don't read the saved value back. With
    /// [`position`](Self::position) left `None`, the window manager picks the
    /// spot.
    pub restore_geometry: bool,
    pub initial_placement: WindowPlacement,
    pub decorations: DecorationsMode,
    pub resizable: bool,
    /// Whether the OS window resizes itself to fit its content's intrinsic
    /// size. See [`SizeToContent`]. Default [`SizeToContent::Off`].
    pub size_to_content: SizeToContent,
    pub always_on_top: bool,
    pub skip_taskbar: bool,
    /// Whether the title bar offers a minimise button; `None` leaves it to
    /// the kind of window. Ignored for a modal window. See
    /// [`minimizable`](Self::minimizable).
    pub minimizable: Option<bool>,
    /// Whether the title bar offers a maximise button; `None` leaves it to
    /// the kind of window. See [`maximizable`](Self::maximizable).
    pub maximizable: Option<bool>,
    /// When set, this window consumes an `xdg_activation_v1` startup token from
    /// the environment at creation so it comes up focused on Wayland (the
    /// launching process set it via `set_child_activation_env`). No effect off
    /// Wayland/X11.
    pub activate_from_env: bool,
    pub icon: Option<WindowIcon>,
    pub modal: Option<ModalConfig>,
    pub root_builder: Option<RootBuilder>,
    /// Optional post-root wrapper. When set, the framework calls it
    /// after `root_builder` and uses the returned id as the window's
    /// effective root. See [`PostRootBuilder`].
    pub post_root_builder: Option<PostRootBuilder>,
    /// Optional close guard. Consulted before this window closes in
    /// response to a user gesture; returning [`CloseResponse::Veto`]
    /// cancels the close. See [`WindowConfig::on_close_requested`].
    pub on_close_requested: Option<CloseGuard>,
    /// Optional reactive "may this window close?" signal. Sugar over
    /// `on_close_requested`: when present and `false`, a close attempt
    /// is blocked: vetoed, or deferred to
    /// [`on_close_blocked`](Self::on_close_blocked) when that is set. See [`WindowConfig::can_close`].
    pub can_close: Option<Prop<bool>>,
    /// Optional hook run when the [`can_close`](Self::can_close) signal
    /// blocks a close: it presents the confirmation UI and answers the
    /// close's [`CloseDecision`]. See [`WindowConfig::on_close_blocked`].
    pub on_close_blocked: Option<CloseBlockedCallback>,
    /// Optional teardown hook, fired once this window has been fully
    /// removed from the window manager. See [`WindowConfig::on_removed`].
    pub on_removed: Option<WindowRemovedCallback>,
}

impl std::fmt::Debug for WindowConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowConfig")
            .field("title", &self.title)
            .field("string_id", &self.string_id)
            .field("size", &self.size)
            .field("position", &self.position)
            .field("min_size", &self.min_size)
            .field("max_size", &self.max_size)
            .field("initial_placement", &self.initial_placement)
            .field("decorations", &self.decorations)
            .field("resizable", &self.resizable)
            .field("size_to_content", &self.size_to_content)
            .field("always_on_top", &self.always_on_top)
            .field("skip_taskbar", &self.skip_taskbar)
            .field("minimizable", &self.minimizable)
            .field("maximizable", &self.maximizable)
            .field("activate_from_env", &self.activate_from_env)
            .field("icon", &self.icon.as_ref().map(|i| (i.width, i.height)))
            .field("modal", &self.modal)
            .field(
                "root_builder",
                &self.root_builder.as_ref().map(|_| "<closure>"),
            )
            .field(
                "post_root_builder",
                &self.post_root_builder.as_ref().map(|_| "<closure>"),
            )
            .field(
                "on_close_requested",
                &self.on_close_requested.as_ref().map(|_| "<closure>"),
            )
            .field("can_close", &self.can_close.as_ref().map(|_| "<signal>"))
            .field(
                "on_close_blocked",
                &self.on_close_blocked.as_ref().map(|_| "<closure>"),
            )
            .field("on_removed", &self.on_removed.as_ref().map(|_| "<closure>"))
            .finish()
    }
}

/// Whether an OS window resizes itself to fit its content's intrinsic height.
///
/// `Off` (default) keeps the window at its configured
/// [`size`](WindowConfig::size). `Height` fixes the width and grows or shrinks
/// the height to the content's natural height — the modal-dialog case, e.g. a
/// `MessageBox` whose "Show details" expander adds text.
///
/// The window never shrinks below its [`min_size`](WindowConfig::min_size)
/// floor, and its width is left untouched. Intended for a window with a single
/// primary content root (a dialog). The content's height must NOT depend on the
/// window's own height (e.g. a signal bound to the window size), or the
/// measure → resize loop may fail to converge. On Wayland only the size
/// round-trips (position is compositor-owned), which is fine — size-to-content
/// changes only size.
///
/// (A width / both-axes mode is intentionally not offered: no consumer needs
/// it, and a half-wired variant would silently behave like `Height`.)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SizeToContent {
    /// The window keeps its configured size (the default).
    #[default]
    Off,
    /// Width is fixed; height follows the content's intrinsic height.
    Height,
}

impl SizeToContent {
    /// The window sizes its height to the content.
    pub fn sizes_height(self) -> bool {
        matches!(self, Self::Height)
    }
}

impl WindowConfig {
    /// Start a config with sensible defaults.
    ///
    /// Defaults: title `"Teksilo"`, size `800x600`,
    /// `WindowPlacement::Floating`, `DecorationsMode::Native`,
    /// resizable, no parent, no `id`, no root builder.
    pub fn new() -> Self {
        Self {
            title: "Teksilo".to_string(),
            string_id: None,
            app_id: None,
            size: (800, 600),
            position: None,
            min_size: None,
            max_size: None,
            restore_geometry: true,
            initial_placement: WindowPlacement::Floating,
            decorations: DecorationsMode::Native,
            resizable: true,
            size_to_content: SizeToContent::Off,
            always_on_top: false,
            skip_taskbar: false,
            minimizable: None,
            maximizable: None,
            activate_from_env: false,
            icon: None,
            modal: None,
            root_builder: None,
            post_root_builder: None,
            on_close_requested: None,
            can_close: None,
            on_close_blocked: None,
            on_removed: None,
        }
    }

    /// User-visible title. Also becomes the initial value of
    /// [`WindowState::title`].
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// The application id the desktop matches this window against. See
    /// [`app_id`](Self::app_id) for what each platform does with it, and why a
    /// Wayland session shows the wrong icon without it.
    pub fn app_id(mut self, app_id: impl Into<String>) -> Self {
        self.app_id = Some(app_id.into());
        self
    }

    /// Restored size in logical pixels. This is the size the window
    /// returns to when leaving `Maximized` or `Fullscreen`, and the
    /// current size when placement is `Floating`.
    pub fn size(mut self, width: u32, height: u32) -> Self {
        self.size = (width, height);
        self
    }

    /// Restored on-screen position in logical pixels: the top-left corner
    /// of the window's frame, its title bar included, on every platform, as
    /// [`WindowState::position`](crate::window::WindowState::position) and
    /// the saved geometry hold it. `None` lets the window manager pick.
    pub fn position(mut self, x: i32, y: i32) -> Self {
        self.position = Some((x, y));
        self
    }

    /// Lower bound on the floating size. The OS prevents the user
    /// from resizing the window below this.
    pub fn min_size(mut self, width: u32, height: u32) -> Self {
        self.min_size = Some((width, height));
        self
    }

    /// Upper bound on the floating size.
    pub fn max_size(mut self, width: u32, height: u32) -> Self {
        self.max_size = Some((width, height));
        self
    }

    /// Whether to restore this window's persisted geometry at creation
    /// (default `true`). See [`WindowConfig::restore_geometry`].
    ///
    /// Pass `false` for a window that should still *save* its geometry but be
    /// placed by the OS rather than reopened at the remembered spot — the
    /// second and later windows of an app whose windows share one geometry
    /// slot, which would otherwise all land exactly on top of each other.
    pub fn restore_geometry(mut self, restore: bool) -> Self {
        self.restore_geometry = restore;
        self
    }

    /// Stable string identifier for later lookup via
    /// [`EventContext::find_window`](crate::widget::EventContext).
    /// Optional — omit for "open a fresh window every time."
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.string_id = Some(id.into());
        self
    }

    /// Initial placement. Defaults to `Floating`; pass
    /// `WindowPlacement::Fullscreen` / `Maximized` to start in that
    /// state.
    pub fn initial_placement(mut self, placement: WindowPlacement) -> Self {
        self.initial_placement = placement;
        self
    }

    /// Chrome mode. `Native` draws OS decorations; `CustomChrome`
    /// constructs a [`PlatformTitleBarHost`](crate::PlatformTitleBarHost)
    /// (on X11, falls back to `Native` when the window manager lacks
    /// `_NET_WM_MOVERESIZE`); `None` is borderless.
    pub fn decorations(mut self, mode: DecorationsMode) -> Self {
        self.decorations = mode;
        self
    }

    /// Whether the user can resize the window interactively. Also
    /// affects whether maximize gestures are accepted on some
    /// platforms.
    pub fn resizable(mut self, resizable: bool) -> Self {
        self.resizable = resizable;
        self
    }

    /// Make this window resize itself to fit its content's intrinsic size.
    /// See [`SizeToContent`]. The configured [`size`](Self::size) /
    /// [`min_size`](Self::min_size) act as a floor. Used for native modal dialogs
    /// (e.g. `MessageBox`) so the OS window grows when the content does —
    /// matching the in-tree overlay path.
    ///
    /// Do NOT also call `.resizable(false)`: winit encodes non-resizable as
    /// equal min/max size hints (notably on X11), which would clamp away the
    /// programmatic growth this relies on.
    pub fn size_to_content(mut self, mode: SizeToContent) -> Self {
        self.size_to_content = mode;
        self
    }

    /// Keep this window above all others regardless of focus.
    pub fn always_on_top(mut self, on_top: bool) -> Self {
        self.always_on_top = on_top;
        self
    }

    /// Keep this window out of the taskbar. Useful for tool palettes and
    /// secondary overlays.
    ///
    /// Honoured on Windows and X11, when the window is created. Wayland has
    /// no protocol open to every client for it, so the compositor decides.
    /// On macOS, where the Dock lists applications, the window is kept out
    /// of the Window menu and the Dock icon's menu, the lists of windows a
    /// user switches between, as AppKit's panels are; keeping the
    /// application itself out of the Dock is its activation policy, not
    /// this setting.
    ///
    /// On Windows a window with no taskbar button is also left out of
    /// Alt+Tab, so once minimised the user has no way to bring it back. Give
    /// such a window no minimise button ([`minimizable(false)`](Self::minimizable)),
    /// or hide it and offer a way to show it again, such as a tray menu.
    pub fn skip_taskbar(mut self, skip: bool) -> Self {
        self.skip_taskbar = skip;
        self
    }

    /// Offer a minimise button in the window's title bar, or not. An
    /// ordinary window has one unless refused.
    ///
    /// A [modal](Self::modal_to) window never has one, whatever this says
    /// (a debug build warns when it says `true`): a dialog is minimised and
    /// restored with the window it blocks, as Windows does with an owned
    /// window and macOS with a child window, and a dialog minimised alone
    /// would leave that window refusing input with nothing on screen to say
    /// why.
    ///
    /// Applied when the window is created: on Windows and macOS through the
    /// window's own title bar, and in a title bar the application draws
    /// itself ([`DecorationsMode::CustomChrome`]), whose `TitleBar`
    /// (teksilo-widgets) leaves the button out.
    /// The title bar an X11 window manager or a Wayland compositor draws is
    /// theirs: on X11 a modal window is a transient dialog, which window
    /// managers usually draw without a minimise button.
    pub fn minimizable(mut self, minimizable: bool) -> Self {
        self.minimizable = Some(minimizable);
        self
    }

    /// Offer a maximise button in the window's title bar, or not; on macOS
    /// the zoom button. By default an ordinary window has one and a
    /// [modal](Self::modal_to) one does not, unless it asks. Where it applies
    /// is as for [`minimizable`](Self::minimizable).
    pub fn maximizable(mut self, maximizable: bool) -> Self {
        self.maximizable = Some(maximizable);
        self
    }

    /// Whether the title bar offers a minimise button: never for a modal
    /// window, otherwise as set with [`minimizable`](Self::minimizable), by
    /// default yes.
    pub fn is_minimizable(&self) -> bool {
        !self.is_modal() && self.minimizable.unwrap_or(true)
    }

    /// Whether the title bar offers a maximise button: as set with
    /// [`maximizable`](Self::maximizable), otherwise unless the window is
    /// modal.
    pub fn is_maximizable(&self) -> bool {
        self.maximizable.unwrap_or(!self.is_modal())
    }

    /// Consume an `xdg_activation_v1` startup token from the environment at
    /// creation so this window comes up focused on Wayland. Set on the initial
    /// window of a process spawned by another instance's "open in new window".
    pub fn activate_from_env(mut self, on: bool) -> Self {
        self.activate_from_env = on;
        self
    }

    /// Set the window's icon from a raw RGBA8 buffer. The icon is
    /// used by the taskbar / dock and the window's title bar on
    /// platforms where it applies.
    ///
    /// Invalid buffers (`rgba.len() != width * height * 4`) are
    /// logged and dropped at creation time — the window still opens,
    /// just with the platform default icon.
    pub fn icon(mut self, icon: WindowIcon) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Make this window modal to the given parent, with no explicit
    /// focus target. Prefer this over constructing [`ModalConfig`]
    /// yourself when you already have the parent id handy.
    ///
    /// The parent is the dialog's owner. It refuses input while the dialog
    /// is open (a click or the focus there brings the dialog forward), and
    /// its close button does nothing but bring the dialog forward. The
    /// dialog stays in front of it, has no taskbar entry and no minimise
    /// button of its own ([`minimizable`](Self::minimizable) is ignored),
    /// and is minimised, restored and closed with it (its own close guard is
    /// not asked then). On Wayland, where winit gives a window no parent, the
    /// compositor treats it as a window of its own, and it is not minimised
    /// or restored with its owner: no protocol tells the application of
    /// either.
    pub fn modal_to(mut self, parent: TeksiloWindowId) -> Self {
        self.modal = Some(ModalConfig {
            parent,
            focus_target: None,
        });
        self
    }

    /// Make this window modal using a caller-built [`ModalConfig`].
    /// Use this form when you need to specify an explicit
    /// `focus_target`. The window belongs to `config.parent` as
    /// [`modal_to`](Self::modal_to) describes.
    pub fn modal(mut self, config: ModalConfig) -> Self {
        self.modal = Some(config);
        self
    }

    /// Root-widget builder. Called once during window creation with
    /// the new window's [`WidgetTree`] and a cloned [`WindowState`]
    /// so widgets can bind against window-level signals.
    pub fn root(
        mut self,
        builder: impl FnOnce(&mut WidgetTree, WindowState) -> WidgetId + 'static,
    ) -> Self {
        self.root_builder = Some(Box::new(builder));
        self
    }

    // ----- Query helpers used by the app-level window manager -------

    /// Take the root builder out of the config, leaving `None` in its
    /// place. Consumed by the window manager exactly once during
    /// `create_window`.
    pub fn take_root_builder(&mut self) -> Option<RootBuilder> {
        self.root_builder.take()
    }

    /// Attach a per-window post-root hook. Runs after the user's
    /// `root_builder` returns; receives the user's root id and may
    /// return either the same id or a wrapper's id. The framework uses
    /// the returned id as the window's effective root.
    ///
    /// Typically used by the debug inspector. Apps that want to
    /// install a default wrapper across all windows should use the
    /// app-level mechanism instead of setting this per-config.
    pub fn post_root(
        mut self,
        builder: impl FnOnce(&mut WidgetTree, WidgetId) -> WidgetId + 'static,
    ) -> Self {
        self.post_root_builder = Some(Box::new(builder));
        self
    }

    /// Take the post-root builder out of the config.
    pub fn take_post_root_builder(&mut self) -> Option<PostRootBuilder> {
        self.post_root_builder.take()
    }

    /// Install a **close guard** consulted before this window closes in
    /// response to a user gesture (the OS close button / `Alt+F4` /
    /// `Cmd+W`, a custom-chrome close button, or
    /// [`EventContext::close_window`](crate::widget::EventContext::close_window)),
    /// and when a guarded quit
    /// ([`EventContext::quit`](crate::widget::EventContext::quit)) asks it.
    ///
    /// The guard runs with a real [`EventContext`] for this window's
    /// tree, and answers with a [`CloseResponse`]: `Close` lets the close
    /// proceed, `Veto` refuses it (and abandons a quit that asked), and
    /// `Defer` answers later through a
    /// [`CloseDecision`]. Asking the user is a deferred
    /// answer:
    ///
    /// ```ignore
    /// WindowConfig::new()
    ///     .on_close_requested(move |ctx| {
    ///         if !has_unsaved_changes() {
    ///             return CloseResponse::Close;
    ///         }
    ///         let decision = CloseDecision::new();
    ///         let answer = decision.clone();
    ///         ctx.present_message_box(
    ///             MessageBox::question(lit!("Save before closing?"))
    ///                 .buttons(MessageBoxButtons::SaveDiscardCancel)
    ///                 .on_result(move |result, _ctx| match result.button {
    ///                     StandardButton::Save => { save(); answer.proceed(); }
    ///                     StandardButton::Discard => answer.proceed(),
    ///                     _ => answer.cancel(),
    ///                 }),
    ///         );
    ///         CloseResponse::Defer(decision)
    ///     });
    /// ```
    ///
    /// `proceed` closes the window without asking the guard again, and a
    /// quit waiting on it goes on; `cancel` leaves it open and abandons such
    /// a quit. The guard is **not** consulted for a forced close
    /// ([`close_window_forced`](crate::widget::EventContext::close_window_forced),
    /// [`close_window_by_id`](crate::widget::EventContext::close_window_by_id)),
    /// a forced quit, or framework-internal teardown (modal cleanup, the
    /// final-window shutdown drain).
    pub fn on_close_requested(
        mut self,
        guard: impl Fn(&mut EventContext) -> CloseResponse + 'static,
    ) -> Self {
        self.on_close_requested = Some(Rc::new(guard));
        self
    }

    /// Reactive sugar over [`on_close_requested`](Self::on_close_requested):
    /// bind a `Signal<bool>` that answers "may this window close right
    /// now?". While the signal reads `false`, every user-initiated close
    /// attempt is blocked. With no [`on_close_blocked`](Self::on_close_blocked)
    /// the close is vetoed, which is final: a quit that asks the window is
    /// abandoned. With one, the close defers
    /// ([`CloseResponse::Defer`]) and the callback answers it, so a
    /// confirmation can let the close, and a quit waiting on it, go on.
    ///
    /// `can_close` is evaluated *before* the `on_close_requested` guard:
    /// a `false` signal short-circuits to a veto; a `true` signal (or no
    /// signal) falls through to the guard, then to closing.
    pub fn can_close(mut self, may_close: impl Into<Prop<bool>>) -> Self {
        self.can_close = Some(may_close.into());
        self
    }

    /// Hook run when the [`can_close`](Self::can_close) signal blocks a
    /// close attempt, whether it came from the user or from a quit. Runs
    /// with this window's [`EventContext`] and a [`CloseDecision`] for the
    /// close: present the confirmation, then answer with
    /// [`proceed`](CloseDecision::proceed) (the window closes without its
    /// guard being asked again, and a quit goes on) or
    /// [`cancel`](CloseDecision::cancel) (the window stays, and a guarded
    /// quit is abandoned; a quit that leaves no time to ask closes the
    /// window whatever the answer, and a forced one does not run this). The decision is `Send` and cloneable, so a dialog's
    /// result callback can hold it; one dropped unanswered cancels, and a
    /// debug build says so. A callback that only wants to say why calls
    /// `cancel` at once.
    ///
    /// Setting it turns the block from a veto into a
    /// [`CloseResponse::Defer`]; without it the block is a final
    /// [`CloseResponse::Veto`]. No-op unless a `can_close` signal is also
    /// set.
    pub fn on_close_blocked(
        mut self,
        on_blocked: impl Fn(&mut EventContext, CloseDecision) + 'static,
    ) -> Self {
        self.on_close_blocked = Some(Rc::new(on_blocked));
        self
    }

    /// Take the close guard out of the config. Consumed by the window
    /// manager once during `create_window`, which stores it on the
    /// managed window for the window's lifetime.
    pub fn take_close_guard(&mut self) -> Option<CloseGuard> {
        self.on_close_requested.take()
    }

    /// Take the `can_close` prop out of the config.
    pub fn take_can_close(&mut self) -> Option<Prop<bool>> {
        self.can_close.take()
    }

    /// Take the `on_close_blocked` callback out of the config.
    pub fn take_close_blocked(&mut self) -> Option<CloseBlockedCallback> {
        self.on_close_blocked.take()
    }

    /// Register a teardown hook for this window: an `Fn`, not `FnOnce` or
    /// `FnMut`, because a shared closure (`Rc`-cloned config, or a
    /// closure built once and attached to several windows opened for the
    /// same document) may run once per window it's attached to.
    ///
    /// Fires exactly once, no matter which of the two ways this window
    /// closes:
    /// - a *guarded* close ([`EventContext::close_window`](crate::widget::EventContext::close_window)
    ///   / the OS close button / `Alt+F4` / `Cmd+W`), once
    ///   [`can_close`](Self::can_close) / [`on_close_requested`](Self::on_close_requested)
    ///   let it through;
    /// - a *forced* close ([`EventContext::close_window_forced`](crate::widget::EventContext::close_window_forced) /
    ///   [`EventContext::close_window_by_id`](crate::widget::EventContext::close_window_by_id)),
    ///   which bypasses the guard entirely;
    ///
    /// because the window manager funnels both through the same, single
    /// teardown routine.
    ///
    /// Runs **after** the window is gone: its tree has been dropped, its
    /// platform window destroyed, and every framework-internal
    /// registration for it (native menu, drag-and-drop target, pending
    /// async completions, …) purged. This is the deliberate choice — it
    /// is what lets [`WindowRemovedEvent::remaining_windows`] already
    /// exclude the window being removed, so a handler that wants to know
    /// "was this the last window [for my Work]" gets an unambiguous
    /// answer rather than having to remember to subtract one. The
    /// trade-off is that the callback cannot reach into the removed
    /// window's own widget tree — by the time it runs, there isn't one.
    /// If a hook needs to read tree state before it's torn down, that has
    /// to happen earlier, in [`on_close_requested`](Self::on_close_requested)
    /// or [`on_close_blocked`](Self::on_close_blocked).
    ///
    /// The intended use is releasing whatever an app keeps keyed by a
    /// window's [`TeksiloWindowId`] — a shared-document refcount, an
    /// entry in the app's own "windows open for this Work" map — so that
    /// bookkeeping is decremented exactly when the framework agrees the
    /// window is really gone, instead of a hand-maintained registry that
    /// only ever grows.
    pub fn on_removed(mut self, hook: impl Fn(&WindowRemovedEvent) + 'static) -> Self {
        self.on_removed = Some(Rc::new(hook));
        self
    }

    /// Take the `on_removed` teardown hook out of the config.
    pub fn take_on_removed(&mut self) -> Option<WindowRemovedCallback> {
        self.on_removed.take()
    }

    pub fn is_modal(&self) -> bool {
        self.modal.is_some()
    }

    pub fn modal_parent(&self) -> Option<TeksiloWindowId> {
        self.modal.as_ref().map(|m| m.parent)
    }

    pub fn modal_focus_target(&self) -> Option<WidgetId> {
        self.modal.as_ref().and_then(|m| m.focus_target)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signal::Signal;

    #[test]
    fn window_config_defaults() {
        let config = WindowConfig::new();
        assert_eq!(config.title, "Teksilo");
        assert_eq!(config.size, (800, 600));
        assert_eq!(config.initial_placement, WindowPlacement::Floating);
        assert_eq!(config.decorations, DecorationsMode::Native);
        assert!(config.resizable);
        assert!(!config.always_on_top);
        assert!(!config.skip_taskbar);
        assert!(config.is_minimizable());
        assert!(config.is_maximizable());
        assert!(config.modal.is_none());
        assert!(config.string_id.is_none());
        assert!(config.app_id.is_none());
        assert!(config.position.is_none());
        assert!(config.min_size.is_none());
        assert!(config.max_size.is_none());
        assert!(config.on_close_requested.is_none());
        assert!(config.can_close.is_none());
        assert!(config.on_close_blocked.is_none());
        assert!(config.on_removed.is_none());
        // Geometry is restored unless an app explicitly opts out.
        assert!(config.restore_geometry);
    }

    /// Persisting and restoring geometry are separate decisions.
    ///
    /// An app whose windows share one geometry slot wants the *first* window to
    /// reopen where the user left it and any window opened alongside it to be
    /// placed by the window manager — otherwise they all land on the same pixel.
    /// But those later windows must still *save* their geometry, so whichever
    /// the user moved or closed last is the one that reopens. That is
    /// `id(..)` + `restore_geometry(false)`: persist, don't restore.
    #[test]
    fn restore_geometry_can_be_opted_out_of_without_giving_up_persistence() {
        let config = WindowConfig::new().id("main").restore_geometry(false);

        assert!(!config.restore_geometry, "this window must not be restored");
        assert_eq!(
            config.string_id.as_deref(),
            Some("main"),
            "...but it keeps its id, so it still persists into that slot"
        );
        // And with no explicit position, the window manager picks the spot.
        assert!(config.position.is_none());
    }

    #[test]
    fn close_guard_builders_set_and_take() {
        let may_close = Signal::new(false);
        let mut config = WindowConfig::new()
            .on_close_requested(|_ctx| CloseResponse::Veto)
            .can_close(may_close.clone())
            .on_close_blocked(|_ctx, decision| decision.cancel());

        assert!(config.on_close_requested.is_some());
        assert!(config.can_close.is_some());
        assert!(config.on_close_blocked.is_some());

        // The window manager drains the guard fields exactly once at
        // create_window time; after that the config no longer carries them.
        let guard = config.take_close_guard();
        let signal = config.take_can_close();
        let blocked = config.take_close_blocked();
        assert!(guard.is_some());
        assert!(signal.is_some());
        assert!(blocked.is_some());
        assert!(config.on_close_requested.is_none());
        assert!(config.can_close.is_none());
        assert!(config.on_close_blocked.is_none());

        // The taken signal is the same handle the caller passed in.
        signal.unwrap().as_signal().set(true);
        assert!(may_close.get());
    }

    #[test]
    fn on_removed_builder_sets_and_takes() {
        use std::cell::RefCell;
        use std::rc::Rc;

        let seen: Rc<RefCell<Vec<WindowRemovedEvent>>> = Rc::new(RefCell::new(Vec::new()));
        let log = seen.clone();
        let mut config =
            WindowConfig::new().on_removed(move |ev| log.borrow_mut().push(ev.clone()));

        assert!(config.on_removed.is_some());

        // The window manager drains this exactly once at create_window
        // time, same discipline as the close-guard fields above.
        let hook = config.take_on_removed();
        assert!(hook.is_some());
        assert!(config.on_removed.is_none());

        // The taken callback is the same closure the caller passed in,
        // and it receives exactly the event it's handed — no field is
        // dropped or reordered on the way through the `Rc<dyn Fn>`.
        let id = TeksiloWindowId::new(7);
        hook.unwrap()(&WindowRemovedEvent {
            id,
            string_id: Some("main".to_string()),
            remaining_windows: 0,
        });
        let logged = seen.borrow();
        assert_eq!(logged.len(), 1);
        assert_eq!(logged[0].id, id);
        assert_eq!(logged[0].string_id.as_deref(), Some("main"));
        assert_eq!(logged[0].remaining_windows, 0);
    }

    #[test]
    fn builder_sets_fields() {
        let config = WindowConfig::new()
            .title("Test")
            .size(400, 300)
            .id("test-window")
            .initial_placement(WindowPlacement::Fullscreen)
            .decorations(DecorationsMode::CustomChrome)
            .min_size(200, 150)
            .resizable(false)
            .always_on_top(true)
            .skip_taskbar(true)
            .position(100, 50);

        assert_eq!(config.title, "Test");
        assert_eq!(config.size, (400, 300));
        assert_eq!(config.string_id, Some("test-window".to_string()));
        assert_eq!(config.initial_placement, WindowPlacement::Fullscreen);
        assert_eq!(config.decorations, DecorationsMode::CustomChrome);
        assert_eq!(config.min_size, Some((200, 150)));
        assert_eq!(config.position, Some((100, 50)));
        assert!(!config.resizable);
        assert!(config.always_on_top);
        assert!(config.skip_taskbar);
    }

    #[test]
    fn modal_to_sets_parent() {
        let parent = TeksiloWindowId::new(3);
        let config = WindowConfig::new().modal_to(parent);
        assert!(config.is_modal());
        assert_eq!(config.modal_parent(), Some(parent));
        assert_eq!(config.modal_focus_target(), None);
    }

    /// A dialog has no minimise button, asked for one or not, in either
    /// builder order: it follows the window it blocks. It has no maximise
    /// button unless asked. An ordinary window has both unless refused.
    #[test]
    fn a_modal_window_has_no_minimise_button_of_its_own() {
        let parent = TeksiloWindowId::new(3);
        let dialog = WindowConfig::new().modal_to(parent);
        assert!(!dialog.is_minimizable());
        assert!(!dialog.is_maximizable());

        let asked = WindowConfig::new().minimizable(true).modal_to(parent);
        assert!(!asked.is_minimizable(), "set before modal_to");
        assert!(!asked.is_maximizable());
        let asked = WindowConfig::new().modal_to(parent).minimizable(true);
        assert!(!asked.is_minimizable(), "set after modal_to");
        let asked = WindowConfig::new().modal_to(parent).maximizable(true);
        assert!(asked.is_maximizable(), "set after modal_to");

        let palette = WindowConfig::new().minimizable(false);
        assert!(!palette.is_minimizable());
        assert!(palette.is_maximizable());
    }

    #[test]
    fn modal_with_focus_target() {
        let parent = TeksiloWindowId::new(3);
        let target = WidgetId::default();
        let config = WindowConfig::new().modal(ModalConfig {
            parent,
            focus_target: Some(target),
        });
        assert!(config.is_modal());
        assert_eq!(config.modal_parent(), Some(parent));
        assert_eq!(config.modal_focus_target(), Some(target));
    }
}