Skip to main content

teksilo_core/window/
state.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Per-window reactive state.
5//!
6//! A [`WindowState`] is a refcounted handle to the signal-bound surface
7//! of a single window. Widgets bind against these signals
8//! (`ctx.window().placement().map(|p| ...)`) for reactive UI that
9//! stays in sync with the OS; app code writes to the signals to push
10//! state to the OS.
11//!
12//! ## Two-way sync pattern
13//!
14//! Every public signal has two writers:
15//!
16//! - **App-side writes** — `state.title().set("Hello")` or any code
17//!   that assigns through the `Signal` handle returned from the
18//!   getter. These fire the observer wired in [`WindowState::new`];
19//!   the observer pushes a [`WindowCommand`] into
20//!   `WindowStateInner::pending_os_commands`, which the app-level
21//!   window manager drains once per tick and translates into a winit
22//!   call.
23//!
24//! - **OS-side writes** — the app-level window manager calls the
25//!   private `set_*_from_os` methods on `WindowStateInner` when a
26//!   winit `WindowEvent` reports that the OS changed state. Those
27//!   setters flip the `applying_from_os` guard
28//!   before updating the signal; the observer sees the guard is set
29//!   and skips enqueuing a command. Without this guard, every
30//!   OS-initiated change would loop back into a redundant OS call —
31//!   at best wasteful, at worst a mid-animation state-drift bug
32//!   (Compose Multiplatform issues #1489, #4006).
33
34use std::cell::{Cell, RefCell};
35use std::rc::Rc;
36
37use crate::signal::{ObserverHandle, Signal};
38
39use super::command::{UserAttentionKind, WindowCommand};
40use super::id::TeksiloWindowId;
41use super::placement::WindowPlacement;
42
43/// A refcounted handle to a single window's reactive state.
44///
45/// Cloning gives you another handle to the same underlying state.
46/// Widgets should store a [`WindowState`] clone when they need to read
47/// or write window-level signals outside of a single `build()` call.
48#[derive(Clone)]
49pub struct WindowState {
50    inner: Rc<WindowStateInner>,
51}
52
53impl std::fmt::Debug for WindowState {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("WindowState")
56            .field("id", &self.inner.id)
57            .field("string_id", &self.inner.string_id.get())
58            .field("placement", &self.inner.placement.get())
59            .field("title", &self.inner.title.get())
60            .field("size", &self.inner.size.get())
61            .field("position", &self.inner.position.get())
62            .field("focused", &self.inner.focused.get())
63            .field("resizable", &self.inner.resizable.get())
64            .field("always_on_top", &self.inner.always_on_top.get())
65            .field(
66                "pending_commands",
67                &self.inner.pending_os_commands.borrow().len(),
68            )
69            .finish()
70    }
71}
72
73/// Initial values for a [`WindowState`] at creation time.
74///
75/// Built from the equivalent fields on `WindowConfig` by the app-level
76/// window manager, then passed to [`WindowState::new`].
77#[derive(Debug, Clone)]
78pub struct WindowStateInit {
79    pub id: TeksiloWindowId,
80    pub string_id: Option<String>,
81    pub placement: WindowPlacement,
82    pub title: String,
83    pub size: (u32, u32),
84    pub position: (i32, i32),
85    pub focused: bool,
86    pub resizable: bool,
87    pub always_on_top: bool,
88}
89
90pub(crate) struct WindowStateInner {
91    id: TeksiloWindowId,
92    /// The stable string id, which the window manager changes when the app
93    /// renames the window (`WindowOps::set_window_string_id`). A signal of
94    /// its own, rather than a field of this struct read through the state,
95    /// so the geometry savers can hold it without holding the state: see
96    /// [`WindowState::string_id_signal`].
97    string_id: Signal<Option<String>>,
98
99    placement: Signal<WindowPlacement>,
100    title: Signal<String>,
101    size: Signal<(u32, u32)>,
102    position: Signal<(i32, i32)>,
103    focused: Signal<bool>,
104    resizable: Signal<bool>,
105    always_on_top: Signal<bool>,
106    /// Whether the window's title bar offers a minimise and a maximise
107    /// button, as the window manager created it; see
108    /// [`WindowState::set_caption_buttons`].
109    caption_buttons: Cell<(bool, bool)>,
110    /// Caps Lock active state, OS-driven only — no observer and no
111    /// app→OS command (the app never sets the keyboard lock). Toggled by
112    /// the window manager on each `Key::CapsLock` press; read by password
113    /// fields to show a Caps Lock warning.
114    caps_lock: Signal<bool>,
115    /// The physical identity of the key event about to be dispatched, and
116    /// whether it is an auto-repeat, noted by the window manager; see
117    /// [`WindowState::note_key_identity_from_os`].
118    key_identity: Cell<Option<(u64, bool)>>,
119
120    /// `true` while the Alt key is currently held down. OS-driven only —
121    /// no observer and no app→OS command. Set by the window manager from
122    /// winit's `ModifiersChanged` — winit reports modifier keys there, not
123    /// through `KeyboardInput`, and our `Key` enum has no `Alt`. Read by:
124    ///
125    /// - `MenuLabel` to show / hide mnemonic underlines while Alt is held
126    ///   (matches the Win32 `WM_CHANGEUISTATE` underlining convention).
127    /// - [`note_non_alt_keydown_during_alt`](WindowState::note_non_alt_keydown_during_alt),
128    ///   for the bare-Alt tap that focuses the menu bar's first trigger.
129    ///   The tap itself is read from the Alt key's own events
130    ///   ([`note_alt_key_from_os`](WindowState::note_alt_key_from_os)), not
131    ///   from this signal's falling edge: a window also hears of a held Alt
132    ///   here when it takes the focus with Alt down.
133    alt_down: Signal<bool>,
134
135    /// Sticky flag that records whether any non-Alt key was pressed
136    /// while Alt was held. Cleared on every rising edge of `alt_down`
137    /// (which the manager drives from winit's `ModifiersChanged`);
138    /// flipped to `true` by the manager
139    /// on any non-Alt `KeyDown` that arrives while `alt_down` is
140    /// `true`. Read by `MenuBar` at the Alt → release moment to
141    /// decide whether the user did a bare-Alt-tap (no other key
142    /// pressed → focus menubar) or used Alt as a modifier for a
143    /// real chord (skip).
144    ///
145    /// `Cell<bool>` rather than `Signal<bool>` — only the MenuBar
146    /// effect reads it at the transition moment, never reactively.
147    other_key_pressed_during_alt: Cell<bool>,
148
149    /// Whether this window saw the current Alt hold begin: a real press of
150    /// an Alt key while it had the focus. A window that takes the focus with
151    /// Alt already down (the one behind a window Alt+F4 closed, or the one
152    /// Alt+Tab brings forward) learns of the hold only from the modifier
153    /// state or from a synthetic key, and its release is no tap. Set by
154    /// [`note_alt_key_from_os`](WindowState::note_alt_key_from_os), cleared
155    /// by the release and by a change of focus.
156    alt_press_seen: Cell<bool>,
157
158    /// At-most-one menubar dispatcher per window. See
159    /// [`super::menubar_dispatcher`]. Wrapped in `Rc` so the slot
160    /// can be shared with the [`super::menubar_dispatcher::MenubarGuard`]
161    /// returned to the caller — when the guard drops, it clears the
162    /// slot iff it still points to the same dispatcher.
163    menubar_dispatcher: Rc<super::menubar_dispatcher::MenubarDispatcherSlot>,
164
165    /// Commands queued by observers on app-side signal writes. Drained
166    /// by the app-level window manager once per tick.
167    pending_os_commands: RefCell<Vec<WindowCommand>>,
168
169    /// A pending `xdg_activation_v1` token stashed by
170    /// [`WindowState::set_activation_token`] and consumed by the next
171    /// [`WindowState::focus`], which carries it on the emitted
172    /// [`WindowCommand::Focus`]. Only meaningful for Wayland cross-process
173    /// raises; ignored on every other platform.
174    pending_activation_token: RefCell<Option<String>>,
175
176    /// `true` while a `set_*_from_os` call is in progress. The
177    /// observers installed in [`WindowState::new`] check this flag and
178    /// do nothing when it is set — the OS already knows, there is no
179    /// command to send back.
180    applying_from_os: Cell<bool>,
181
182    /// Holds the `ObserverHandle`s returned from
183    /// [`Signal::observe`] during construction. They must stay alive
184    /// for the lifetime of the `WindowState`; dropping them would
185    /// silently unsubscribe the OS-sync observers.
186    _observer_handles: RefCell<Vec<ObserverHandle>>,
187}
188
189impl WindowState {
190    /// Construct a new state from initial values.
191    ///
192    /// Wires an observer on every signal that pushes a matching
193    /// [`WindowCommand`] onto the pending queue, guarded by
194    /// `WindowStateInner::applying_from_os`.
195    pub fn new(init: WindowStateInit) -> Self {
196        let inner = Rc::new(WindowStateInner {
197            id: init.id,
198            string_id: Signal::new(init.string_id),
199            placement: Signal::new(init.placement),
200            title: Signal::new(init.title),
201            size: Signal::new(init.size),
202            position: Signal::new(init.position),
203            focused: Signal::new(init.focused),
204            resizable: Signal::new(init.resizable),
205            always_on_top: Signal::new(init.always_on_top),
206            caption_buttons: Cell::new((true, true)),
207            caps_lock: Signal::new(false),
208            key_identity: Cell::new(None),
209            alt_down: Signal::new(false),
210            other_key_pressed_during_alt: Cell::new(false),
211            alt_press_seen: Cell::new(false),
212            menubar_dispatcher: Rc::new(RefCell::new(None)),
213            pending_os_commands: RefCell::new(Vec::new()),
214            pending_activation_token: RefCell::new(None),
215            applying_from_os: Cell::new(false),
216            _observer_handles: RefCell::new(Vec::new()),
217        });
218
219        // Wire the observers. Each one queues a WindowCommand on
220        // app-side writes and silently ignores OS-originated writes.
221        let mut handles = Vec::new();
222
223        {
224            let inner_w = Rc::downgrade(&inner);
225            handles.push(inner.placement.observe(move |v| {
226                if let Some(inner) = inner_w.upgrade() {
227                    inner.enqueue_unless_from_os(WindowCommand::SetPlacement(*v));
228                }
229            }));
230        }
231        {
232            let inner_w = Rc::downgrade(&inner);
233            handles.push(inner.title.observe(move |v| {
234                if let Some(inner) = inner_w.upgrade() {
235                    inner.enqueue_unless_from_os(WindowCommand::SetTitle(v.clone()));
236                }
237            }));
238        }
239        {
240            let inner_w = Rc::downgrade(&inner);
241            handles.push(inner.size.observe(move |v| {
242                if let Some(inner) = inner_w.upgrade() {
243                    inner.enqueue_unless_from_os(WindowCommand::SetSize(v.0, v.1));
244                }
245            }));
246        }
247        {
248            let inner_w = Rc::downgrade(&inner);
249            handles.push(inner.position.observe(move |v| {
250                if let Some(inner) = inner_w.upgrade() {
251                    inner.enqueue_unless_from_os(WindowCommand::SetPosition(v.0, v.1));
252                }
253            }));
254        }
255        {
256            let inner_w = Rc::downgrade(&inner);
257            handles.push(inner.resizable.observe(move |v| {
258                if let Some(inner) = inner_w.upgrade() {
259                    inner.enqueue_unless_from_os(WindowCommand::SetResizable(*v));
260                }
261            }));
262        }
263        {
264            let inner_w = Rc::downgrade(&inner);
265            handles.push(inner.always_on_top.observe(move |v| {
266                if let Some(inner) = inner_w.upgrade() {
267                    inner.enqueue_unless_from_os(WindowCommand::SetAlwaysOnTop(*v));
268                }
269            }));
270        }
271        // `focused` has no observer: it is purely OS-driven. Writes
272        // go through `set_focused_from_os`; app code that wants to
273        // pull focus calls `focus()` instead, which emits
274        // `WindowCommand::Focus` directly.
275
276        *inner._observer_handles.borrow_mut() = handles;
277        Self { inner }
278    }
279
280    pub fn id(&self) -> TeksiloWindowId {
281        self.inner.id
282    }
283
284    /// The stable string id the window is known by: the one it was opened
285    /// with ([`WindowConfig::id`](super::WindowConfig::id)), or the one it
286    /// was given since with
287    /// [`EventContext::set_window_string_id`](crate::widget::EventContext::set_window_string_id).
288    /// `None` for a window that never had one.
289    pub fn string_id(&self) -> Option<String> {
290        self.inner.string_id.get()
291    }
292
293    /// The signal holding [`string_id`](Self::string_id), for the window
294    /// manager: it writes the new id there when the window is renamed, and
295    /// the geometry savers read it each time they save, so they save under
296    /// the id the window has now. A saver holds this signal and not the
297    /// whole state, which would make a reference cycle through the state's
298    /// own observers.
299    ///
300    /// Do not set it from an app: the window manager's lookup table and
301    /// the saved geometry would not follow. Rename a window with
302    /// [`EventContext::set_window_string_id`](crate::widget::EventContext::set_window_string_id).
303    #[doc(hidden)]
304    pub fn string_id_signal(&self) -> &Signal<Option<String>> {
305        &self.inner.string_id
306    }
307
308    pub fn placement(&self) -> &Signal<WindowPlacement> {
309        &self.inner.placement
310    }
311
312    pub fn title(&self) -> &Signal<String> {
313        &self.inner.title
314    }
315
316    pub fn size(&self) -> &Signal<(u32, u32)> {
317        &self.inner.size
318    }
319
320    pub fn position(&self) -> &Signal<(i32, i32)> {
321        &self.inner.position
322    }
323
324    pub fn focused(&self) -> &Signal<bool> {
325        &self.inner.focused
326    }
327
328    pub fn resizable(&self) -> &Signal<bool> {
329        &self.inner.resizable
330    }
331
332    pub fn always_on_top(&self) -> &Signal<bool> {
333        &self.inner.always_on_top
334    }
335
336    /// Whether the window's title bar offers a minimise button: `false` for
337    /// a modal dialog, which follows the window it blocks, and for a window
338    /// created with `WindowConfig::minimizable(false)`. A title bar the
339    /// application draws reads it to leave the button out.
340    #[doc(hidden)]
341    pub fn is_minimizable(&self) -> bool {
342        self.inner.caption_buttons.get().0
343    }
344
345    /// Whether the window's title bar offers a maximise button; see
346    /// [`is_minimizable`](Self::is_minimizable).
347    #[doc(hidden)]
348    pub fn is_maximizable(&self) -> bool {
349        self.inner.caption_buttons.get().1
350    }
351
352    /// Record which caption buttons the window was created with. Called by
353    /// the window manager before the window's root is built; both are
354    /// `true` until then.
355    #[doc(hidden)]
356    pub fn set_caption_buttons(&self, minimizable: bool, maximizable: bool) {
357        self.inner.caption_buttons.set((minimizable, maximizable));
358    }
359
360    /// Caps Lock active state. OS-driven only — the window manager
361    /// toggles it on each `Key::CapsLock` press. Read this (e.g. via
362    /// `ctx.window()`) to drive a Caps Lock warning on password fields.
363    pub fn caps_lock(&self) -> &Signal<bool> {
364        &self.inner.caps_lock
365    }
366
367    /// Whether the Alt key is currently held down. OS-driven only — the
368    /// window manager flips this from winit's `ModifiersChanged`, where
369    /// winit reports modifier keys. Read
370    /// this to drive mnemonic-underline visibility on menus and menubars.
371    /// See the menubar key-dispatch documentation for the full Alt-tap
372    /// / Alt+letter / mnemonic-underline contract.
373    pub fn alt_down(&self) -> &Signal<bool> {
374        &self.inner.alt_down
375    }
376
377    /// Read whether any non-Alt key has been pressed during the
378    /// current Alt-hold window. `false` means the user has not
379    /// composed a chord since pressing Alt, so the next Alt release
380    /// is a bare-Alt tap if this window saw the press (see
381    /// [`note_alt_key_from_os`](Self::note_alt_key_from_os)).
382    pub fn other_key_pressed_during_alt(&self) -> bool {
383        self.inner.other_key_pressed_during_alt.get()
384    }
385
386    /// Install (or replace) the per-window menubar key dispatcher.
387    /// Returns a [`super::menubar_dispatcher::MenubarGuard`] that
388    /// clears the slot on drop iff it still points at this exact
389    /// dispatcher (`Rc::ptr_eq`).
390    ///
391    /// At most one dispatcher is supported per window. A second
392    /// install while another is still live `debug_assert!`s and
393    /// overwrites in release. This matches the "one MenuBar per
394    /// window" invariant the framework enforces upstream.
395    pub fn install_menubar_dispatcher(
396        &self,
397        dispatcher: Rc<dyn super::menubar_dispatcher::MenubarDispatcher>,
398    ) -> super::menubar_dispatcher::MenubarGuard {
399        let slot = self.inner.menubar_dispatcher.clone();
400        {
401            let mut slot_ref = slot.borrow_mut();
402            debug_assert!(
403                slot_ref.is_none(),
404                "WindowState: a menubar dispatcher is already installed for this \
405                 window — only one keyboard-dispatching MenuBar is supported per \
406                 window because the dispatcher slot routes F10 / Alt+letter / \
407                 Alt-tap to exactly one trigger set.\n\n\
408                 \
409                 Causes typically fall into one of:\n\
410                 \
411                 1. Two MenuBar widgets are mounted in the same window. Pick \
412                    the primary one — the one that should own F10 / Alt+letter \
413                    — and call `.no_dispatcher_install()` on every secondary \
414                    MenuBar (showcase content, embedded demos, settings \
415                    previews, …). Secondary MenuBars still render and respond \
416                    to mouse + arrow-key navigation; only the window-level \
417                    keyboard dispatch is left to the primary.\n\
418                 \
419                 2. A MenuBar was added with `tree.add_boxed(MenuBar::new()…)` \
420                    from inside another MenuBar's tab / popover / submenu. Same \
421                    fix: mark the inner one with `.no_dispatcher_install()`.\n\
422                 \
423                 3. The host widget that owns the MenuBar reconstructs a fresh \
424                    `MenuBar::new()` on every rebuild without dropping its \
425                    previous `MenubarGuard` first. `MenuBar::build` already \
426                    handles its own rebuild path; if you're hand-rolling the \
427                    install (custom MenubarDispatcher impl), drop the old \
428                    `MenubarGuard` BEFORE calling this method again."
429            );
430            *slot_ref = Some(dispatcher.clone());
431        }
432        super::menubar_dispatcher::MenubarGuard {
433            slot,
434            own: dispatcher,
435        }
436    }
437
438    /// Snapshot of the currently-installed menubar dispatcher. Used by
439    /// `teksilo-app`'s key-event arm to consult the menubar BEFORE
440    /// focus-based dispatch. Returns `None` when no `MenuBar` is
441    /// mounted in this window.
442    pub fn menubar_dispatcher(
443        &self,
444    ) -> Option<Rc<dyn super::menubar_dispatcher::MenubarDispatcher>> {
445        self.inner.menubar_dispatcher.borrow().clone()
446    }
447
448    /// Request user attention (bouncing dock icon on macOS, flashing
449    /// taskbar on Windows). Queues a [`WindowCommand::RequestAttention`]
450    /// command for the next drain.
451    pub fn request_attention(&self, kind: UserAttentionKind) {
452        self.inner
453            .pending_os_commands
454            .borrow_mut()
455            .push(WindowCommand::RequestAttention(kind));
456    }
457
458    /// Focus this window — raise it above others and give it keyboard
459    /// focus. Queues a [`WindowCommand::Focus`] command for the next
460    /// drain, carrying (and clearing) any token set via
461    /// [`WindowState::set_activation_token`].
462    pub fn focus(&self) {
463        let activation_token = self.inner.pending_activation_token.borrow_mut().take();
464        self.inner
465            .pending_os_commands
466            .borrow_mut()
467            .push(WindowCommand::Focus { activation_token });
468    }
469
470    /// Stash an `xdg_activation_v1` token — an opaque string minted by the
471    /// focused requester and handed across a process boundary — to be consumed
472    /// by the next [`WindowState::focus`]. Only affects a Wayland raise;
473    /// ignored on every other platform, where `focus()` raises on its own.
474    pub fn set_activation_token(&self, token: String) {
475        *self.inner.pending_activation_token.borrow_mut() = Some(token);
476    }
477
478    /// Close this window. Queues a [`WindowCommand::Close`] command
479    /// for the next drain.
480    pub fn close(&self) {
481        self.inner
482            .pending_os_commands
483            .borrow_mut()
484            .push(WindowCommand::Close);
485    }
486
487    /// Test helper: returns the count of pending commands without
488    /// draining. Test-only to avoid exposing queue state to
489    /// application code.
490    #[cfg(test)]
491    pub(crate) fn pending_command_count(&self) -> usize {
492        self.inner.pending_os_commands.borrow().len()
493    }
494}
495
496// Framework-internal write-back API consumed by the app-level window
497// manager when a winit `WindowEvent` reports an OS-initiated state
498// change. Each method backing an observed signal flips the re-entrancy
499// guard before updating it so the observers do not push the same change
500// back out as a
501// [`WindowCommand`], which would at best duplicate work and at worst
502// cause OS↔app drift mid-animation (Compose Multiplatform #1489). The
503// keyboard-state setters below have no observer, so they need no guard.
504//
505// These are `pub` rather than `pub(crate)` because teksilo-app lives in a
506// separate crate. Application code should never call them; they read
507// like internals and have no stability guarantee. Use the public
508// signal setters instead — those fire OS commands through the normal
509// drain path.
510impl WindowState {
511    /// Drain the pending OS-command queue.
512    pub fn drain_os_commands(&self) -> Vec<WindowCommand> {
513        std::mem::take(&mut *self.inner.pending_os_commands.borrow_mut())
514    }
515
516    /// OS-originated placement write. Observers do not push back to
517    /// the OS while the guard is set.
518    pub fn set_placement_from_os(&self, p: WindowPlacement) {
519        self.inner.with_os_guard(|| self.inner.placement.set(p));
520    }
521
522    pub fn set_title_from_os(&self, title: String) {
523        self.inner.with_os_guard(|| self.inner.title.set(title));
524    }
525
526    pub fn set_size_from_os(&self, size: (u32, u32)) {
527        self.inner.with_os_guard(|| self.inner.size.set(size));
528    }
529
530    pub fn set_position_from_os(&self, position: (i32, i32)) {
531        self.inner
532            .with_os_guard(|| self.inner.position.set(position));
533    }
534
535    pub fn set_focused_from_os(&self, focused: bool) {
536        if self.inner.focused.get() != focused {
537            // An Alt hold seen before the focus moved ends in no tap here.
538            self.inner.alt_press_seen.set(false);
539        }
540        self.inner.with_os_guard(|| self.inner.focused.set(focused));
541    }
542
543    pub fn set_resizable_from_os(&self, resizable: bool) {
544        self.inner
545            .with_os_guard(|| self.inner.resizable.set(resizable));
546    }
547
548    pub fn set_always_on_top_from_os(&self, on_top: bool) {
549        self.inner
550            .with_os_guard(|| self.inner.always_on_top.set(on_top));
551    }
552
553    /// Note the physical key of the key event the window manager is about to
554    /// dispatch (an opaque hash of it), and whether it is an auto-repeat. The
555    /// tree reads it to pair a release with the press of the same physical
556    /// key, which the logical key cannot do: on macOS, Option+Shift+2 with
557    /// Shift released first is pressed as "€" and released as "2". Read once,
558    /// by the next key event.
559    #[doc(hidden)]
560    pub fn note_key_identity_from_os(&self, identity: u64, repeat: bool) {
561        self.inner.key_identity.set(Some((identity, repeat)));
562    }
563
564    /// Take what [`note_key_identity_from_os`](Self::note_key_identity_from_os)
565    /// noted for the key event being dispatched.
566    pub(crate) fn take_key_identity(&self) -> Option<(u64, bool)> {
567        self.inner.key_identity.take()
568    }
569
570    /// Update Caps Lock state from the OS. No observer / command is
571    /// wired (the app never drives the keyboard lock), so this writes the
572    /// signal directly. Idempotent: skips the write when unchanged to
573    /// avoid spurious repaints on auto-repeat.
574    pub fn set_caps_lock_from_os(&self, active: bool) {
575        if self.inner.caps_lock.get() != active {
576            self.inner.caps_lock.set(active);
577        }
578    }
579
580    /// Update Alt-held state from the OS. Resets the
581    /// `other_key_pressed_during_alt` flag on every Alt KeyDown
582    /// edge so each Alt-hold window starts fresh. Idempotent.
583    pub fn set_alt_from_os(&self, active: bool) {
584        if self.inner.alt_down.get() != active {
585            self.inner.alt_down.set(active);
586            if active {
587                // Fresh Alt-hold window — no other key has been
588                // pressed yet during this hold.
589                self.inner.other_key_pressed_during_alt.set(false);
590            }
591        }
592    }
593
594    /// Mark that a non-Alt key was pressed while Alt is currently
595    /// held. Sticky — only cleared by the next
596    /// [`set_alt_from_os(true)`](Self::set_alt_from_os) edge. No-op
597    /// when Alt is not held. Idempotent.
598    pub fn note_non_alt_keydown_during_alt(&self) {
599        if self.inner.alt_down.get() {
600            self.inner.other_key_pressed_during_alt.set(true);
601        }
602    }
603
604    /// The OS asked to close the window. With Alt held this was Alt+F4,
605    /// whose F4 winit does not report on Windows (it leaves it to
606    /// `DefWindowProc`), so the hold is a chord and its release no tap. The
607    /// window stays open when an in-window modal took the request, and the
608    /// release would otherwise put its menu bar in keyboard mode.
609    pub fn note_close_request_from_os(&self) {
610        self.note_non_alt_keydown_during_alt();
611    }
612
613    /// A real press or release of an Alt key in this window, never a
614    /// synthetic one (the keys a window is told are held as it takes or
615    /// loses the focus). Returns `true` for the release that ends a bare Alt
616    /// tap: this window saw the press, and no other key went down before
617    /// the release.
618    ///
619    /// `alone` is whether no other modifier (Control, Shift, Super) was
620    /// already held as Alt went down; it is read on the press only. Alt+Shift,
621    /// Ctrl+Alt and the like are chords, not the lone Alt that opens the menu
622    /// bar, even when the key that completes them never reaches the window
623    /// (an input method swallows it).
624    pub fn note_alt_key_from_os(&self, pressed: bool, alone: bool) -> bool {
625        if pressed {
626            self.inner.alt_press_seen.set(alone);
627            return false;
628        }
629        self.inner.alt_press_seen.replace(false) && !self.inner.other_key_pressed_during_alt.get()
630    }
631}
632
633impl WindowStateInner {
634    fn enqueue_unless_from_os(&self, cmd: WindowCommand) {
635        if self.applying_from_os.get() {
636            return;
637        }
638        self.pending_os_commands.borrow_mut().push(cmd);
639    }
640
641    fn with_os_guard<R>(&self, f: impl FnOnce() -> R) -> R {
642        // Set-and-restore rather than set-true-then-false: re-entry
643        // through nested signal observers stays correct.
644        let prev = self.applying_from_os.replace(true);
645        let out = f();
646        self.applying_from_os.set(prev);
647        out
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    fn init(id: u64) -> WindowStateInit {
656        WindowStateInit {
657            id: TeksiloWindowId::new(id),
658            string_id: Some("test".to_string()),
659            placement: WindowPlacement::Floating,
660            title: "Test".to_string(),
661            size: (800, 600),
662            position: (0, 0),
663            focused: false,
664            resizable: true,
665            always_on_top: false,
666        }
667    }
668
669    #[test]
670    fn app_side_write_enqueues_command() {
671        let state = WindowState::new(init(1));
672        state.placement().set(WindowPlacement::Fullscreen);
673        let cmds = state.drain_os_commands();
674        assert_eq!(
675            cmds,
676            vec![WindowCommand::SetPlacement(WindowPlacement::Fullscreen)]
677        );
678    }
679
680    #[test]
681    fn os_side_write_does_not_enqueue_command() {
682        let state = WindowState::new(init(1));
683        state.set_placement_from_os(WindowPlacement::Maximized);
684        assert_eq!(state.placement().get(), WindowPlacement::Maximized);
685        assert_eq!(state.drain_os_commands(), vec![]);
686    }
687
688    #[test]
689    fn os_side_write_still_notifies_derived_signals() {
690        let state = WindowState::new(init(1));
691        let is_fs = state.placement().map(|p| p.is_fullscreen());
692        assert!(!is_fs.get());
693        state.set_placement_from_os(WindowPlacement::Fullscreen);
694        assert!(is_fs.get());
695        // ... but no OS command was emitted.
696        assert_eq!(state.drain_os_commands(), vec![]);
697    }
698
699    #[test]
700    fn drain_is_consuming() {
701        let state = WindowState::new(init(1));
702        state.title().set("One".to_string());
703        state.title().set("Two".to_string());
704        assert_eq!(state.pending_command_count(), 2);
705        let _ = state.drain_os_commands();
706        assert_eq!(state.pending_command_count(), 0);
707    }
708
709    #[test]
710    fn focus_close_attention_do_not_depend_on_signals() {
711        let state = WindowState::new(init(1));
712        state.focus();
713        state.close();
714        state.request_attention(UserAttentionKind::Critical);
715        let cmds = state.drain_os_commands();
716        assert_eq!(
717            cmds,
718            vec![
719                WindowCommand::Focus {
720                    activation_token: None
721                },
722                WindowCommand::Close,
723                WindowCommand::RequestAttention(UserAttentionKind::Critical),
724            ]
725        );
726    }
727
728    #[test]
729    fn multiple_app_writes_of_different_fields() {
730        let state = WindowState::new(init(1));
731        state.title().set("Hello".to_string());
732        state.size().set((1200, 800));
733        state.resizable().set(false);
734        let cmds = state.drain_os_commands();
735        assert_eq!(
736            cmds,
737            vec![
738                WindowCommand::SetTitle("Hello".to_string()),
739                WindowCommand::SetSize(1200, 800),
740                WindowCommand::SetResizable(false),
741            ]
742        );
743    }
744
745    #[test]
746    fn guard_is_scoped_to_a_single_from_os_call() {
747        let state = WindowState::new(init(1));
748        // First OS-originated change: guard suppresses command.
749        state.set_size_from_os((1024, 768));
750        assert_eq!(state.drain_os_commands(), vec![]);
751        // Now an app-side write still works as normal.
752        state.size().set((640, 480));
753        assert_eq!(
754            state.drain_os_commands(),
755            vec![WindowCommand::SetSize(640, 480)]
756        );
757    }
758
759    #[test]
760    fn id_and_string_id_accessors() {
761        let state = WindowState::new(init(42));
762        assert_eq!(state.id(), TeksiloWindowId::new(42));
763        assert_eq!(state.string_id().as_deref(), Some("test"));
764    }
765
766    #[test]
767    fn state_is_cloneable_and_shares_storage() {
768        let a = WindowState::new(init(1));
769        let b = a.clone();
770        a.title().set("From a".to_string());
771        assert_eq!(b.title().get(), "From a");
772        // Either handle can drain — they share the same queue.
773        let cmds = b.drain_os_commands();
774        assert_eq!(cmds.len(), 1);
775        assert_eq!(a.pending_command_count(), 0);
776    }
777
778    // --- Alt-down tracking ---
779
780    #[test]
781    fn alt_down_signal_defaults_false() {
782        let state = WindowState::new(init(1));
783        assert!(!state.alt_down().get());
784        assert!(!state.other_key_pressed_during_alt());
785    }
786
787    #[test]
788    fn set_alt_from_os_toggles_signal() {
789        let state = WindowState::new(init(1));
790        state.set_alt_from_os(true);
791        assert!(state.alt_down().get());
792        state.set_alt_from_os(false);
793        assert!(!state.alt_down().get());
794    }
795
796    #[test]
797    fn set_alt_from_os_does_not_enqueue_command() {
798        // Alt is keyboard-driven; the app cannot drive it.
799        let state = WindowState::new(init(1));
800        state.set_alt_from_os(true);
801        assert!(state.drain_os_commands().is_empty());
802    }
803
804    #[test]
805    fn alt_down_edge_resets_other_key_flag() {
806        let state = WindowState::new(init(1));
807        // Alt+letter chord: Alt down, then letter pressed.
808        state.set_alt_from_os(true);
809        state.note_non_alt_keydown_during_alt();
810        assert!(state.other_key_pressed_during_alt());
811        // Release Alt — flag persists (the consumer reads it on
812        // release to decide whether the tap is bare or chorded).
813        state.set_alt_from_os(false);
814        assert!(state.other_key_pressed_during_alt());
815        // Next Alt-down edge resets the flag so the new hold window
816        // starts fresh.
817        state.set_alt_from_os(true);
818        assert!(!state.other_key_pressed_during_alt());
819    }
820
821    #[test]
822    fn note_non_alt_keydown_is_noop_when_alt_not_held() {
823        let state = WindowState::new(init(1));
824        state.note_non_alt_keydown_during_alt();
825        assert!(!state.other_key_pressed_during_alt());
826    }
827
828    /// A bare tap, in both orders winit reports an Alt key and the modifier
829    /// state in.
830    #[test]
831    fn a_press_and_release_seen_here_with_nothing_between_is_a_tap() {
832        let state = WindowState::new(init(1));
833        state.set_focused_from_os(true);
834        // Windows: the modifier state, then the key.
835        state.set_alt_from_os(true);
836        assert!(!state.note_alt_key_from_os(true, true));
837        state.set_alt_from_os(false);
838        assert!(state.note_alt_key_from_os(false, true));
839        // Wayland: the key, then the modifier state.
840        assert!(!state.note_alt_key_from_os(true, true));
841        state.set_alt_from_os(true);
842        assert!(state.note_alt_key_from_os(false, true));
843        state.set_alt_from_os(false);
844    }
845
846    /// Another modifier already held as Alt went down (Shift+Alt, Ctrl+Alt).
847    #[test]
848    fn alt_pressed_with_another_modifier_held_is_not_a_tap() {
849        let state = WindowState::new(init(1));
850        state.set_focused_from_os(true);
851        state.set_alt_from_os(true);
852        assert!(!state.note_alt_key_from_os(true, false));
853        state.set_alt_from_os(false);
854        assert!(!state.note_alt_key_from_os(false, true));
855    }
856
857    #[test]
858    fn a_chord_is_not_a_tap() {
859        let state = WindowState::new(init(1));
860        state.set_focused_from_os(true);
861        state.set_alt_from_os(true);
862        state.note_alt_key_from_os(true, true);
863        state.note_non_alt_keydown_during_alt();
864        state.set_alt_from_os(false);
865        assert!(!state.note_alt_key_from_os(false, true));
866    }
867
868    /// The window behind one Alt+F4 closed takes the focus with Alt held. It
869    /// hears of the hold only from the modifier state, so the release that
870    /// follows opens nothing.
871    #[test]
872    fn a_hold_begun_in_another_window_is_not_a_tap() {
873        let state = WindowState::new(init(1));
874        state.set_focused_from_os(false);
875        state.set_focused_from_os(true);
876        state.set_alt_from_os(true);
877        state.set_alt_from_os(false);
878        assert!(!state.note_alt_key_from_os(false, true));
879    }
880
881    /// Alt+F4 that an in-window modal takes leaves the window open, and
882    /// winit reports no F4 on Windows: the close request ends the tap.
883    #[test]
884    fn alt_f4_is_not_a_tap() {
885        let state = WindowState::new(init(1));
886        state.set_focused_from_os(true);
887        state.set_alt_from_os(true);
888        state.note_alt_key_from_os(true, true);
889        state.note_close_request_from_os();
890        state.set_alt_from_os(false);
891        assert!(!state.note_alt_key_from_os(false, true));
892    }
893
894    /// Alt+Tab away and back: the press seen before the focus left is
895    /// forgotten.
896    #[test]
897    fn a_hold_the_focus_left_during_is_not_a_tap() {
898        let state = WindowState::new(init(1));
899        state.set_focused_from_os(true);
900        state.set_alt_from_os(true);
901        state.note_alt_key_from_os(true, true);
902        state.set_focused_from_os(false);
903        state.set_focused_from_os(true);
904        state.set_alt_from_os(false);
905        assert!(!state.note_alt_key_from_os(false, true));
906    }
907
908    #[test]
909    fn alt_signal_observers_fire_on_transition() {
910        let state = WindowState::new(init(1));
911        let received: Rc<RefCell<Vec<bool>>> = Rc::new(RefCell::new(Vec::new()));
912        let received_w = Rc::downgrade(&received);
913        let _handle = state.alt_down().observe(move |v| {
914            if let Some(r) = received_w.upgrade() {
915                r.borrow_mut().push(*v);
916            }
917        });
918        state.set_alt_from_os(true);
919        state.set_alt_from_os(true); // idempotent — no second notify
920        state.set_alt_from_os(false);
921        assert_eq!(*received.borrow(), vec![true, false]);
922    }
923}