1
//! Window state types for azul-layout
2
//!
3
//! These types are defined here (rather than azul-core) because CallbackInfo
4
//! needs to reference them, and CallbackInfo must live in azul-layout (since
5
//! it requires LayoutWindow).
6

            
7
use alloc::collections::BTreeMap;
8

            
9
use azul_core::{
10
    callbacks::LayoutCallback,
11
    dom::DomId,
12
    window::{
13
        DebugState, ImePosition, KeyboardState, Monitor, MouseState, PlatformSpecificOptions,
14
        RendererOptions, TouchState, WindowFlags, WindowPosition, WindowSize, WindowTheme,
15
    },
16
};
17
use azul_css::{
18
    corety::OptionU32, impl_option, impl_option_inner, impl_vec, impl_vec_clone, impl_vec_debug,
19
    impl_vec_mut, impl_vec_partialeq, props::basic::OptionColorU, AzString,
20
};
21

            
22
use crate::callbacks::OptionCallback;
23

            
24
/// Options for creating a new window
25
#[derive(Debug, Clone, PartialEq)]
26
#[repr(C)]
27
pub struct WindowCreateOptions {
28
    // Field order is by DECREASING alignment (8, 4, 1) so the struct carries no
29
    // interior padding: `azul-doc autofix` flags any other order as an FFI
30
    // layout issue. It is `#[repr(C)]`, so api.json lists the fields in this
31
    // same order and every binding lays them out the same way.
32
    /// Initial state for the new window
33
    pub window_state: FullWindowState,
34
    /// Optional callback invoked after the window is created
35
    pub create_callback: OptionCallback,
36
    /// Parent window's platform id (the window-registry key: X Window id on X11,
37
    /// `wl_surface` ptr on Wayland, HWND on Windows, `NSWindow` ptr on macOS), or 0
38
    /// for a top-level window with no parent. Child windows (menus, dropdowns,
39
    /// dialogs) set this so the backend can position them relative to the parent
40
    /// and, on X11, reuse the parent's display connection for the single shared
41
    /// event pump. 0 = no parent.
42
    pub parent_window_id: u64,
43
    /// Optional renderer configuration (e.g., `VSync`, SRGB)
44
    pub renderer: azul_core::window::OptionRendererOptions,
45
    /// The window's initial theme, when the app wants to choose it: `Some`
46
    /// seeds `FullWindowState::theme` at creation (over the OS probe; under
47
    /// an `AZ_THEME` pin), `None` follows the system. See
48
    /// `CommonWindowState::initial_window_theme`. The OS theme watchers keep
49
    /// following the system afterwards either way.
50
    pub theme: azul_core::window::OptionWindowTheme,
51
    /// Explicitly defined background color for light theme. If set, overrides the system light
52
    /// window background.
53
    pub background_color_light: OptionColorU,
54
    /// Explicitly defined background color for dark theme. If set, overrides the system dark
55
    /// window background.
56
    pub background_color_dark: OptionColorU,
57
    /// If true, the window is resized to fit its content after the first layout
58
    pub size_to_content: bool,
59
    /// If true, enables hot-reloading of CSS and resources
60
    pub hot_reload: bool,
61
}
62

            
63
impl Default for WindowCreateOptions {
64
1907
    fn default() -> Self {
65
1907
        Self {
66
1907
            window_state: FullWindowState::default(),
67
1907
            create_callback: OptionCallback::None,
68
1907
            renderer: azul_core::window::OptionRendererOptions::None,
69
1907
            theme: azul_core::window::OptionWindowTheme::None,
70
1907
            size_to_content: false,
71
1907
            hot_reload: false,
72
1907
            parent_window_id: 0,
73
1907
            background_color_light: OptionColorU::None,
74
1907
            background_color_dark: OptionColorU::None,
75
1907
        }
76
1907
    }
77
}
78

            
79
impl WindowCreateOptions {
80
    /// Create a new `WindowCreateOptions` with a layout callback
81
1879
    pub fn create(layout_callback: impl Into<LayoutCallback>) -> Self {
82
1879
        let mut options = Self::default();
83
1879
        options.window_state.layout_callback = layout_callback.into();
84
1879
        options
85
1879
    }
86
}
87

            
88
impl_option!(
89
    WindowCreateOptions,
90
    OptionWindowCreateOptions,
91
    copy = false,
92
    [Debug, Clone, PartialEq]
93
);
94
impl_vec!(
95
    WindowCreateOptions,
96
    WindowCreateOptionsVec,
97
    WindowCreateOptionsVecDestructor,
98
    WindowCreateOptionsVecDestructorType,
99
    WindowCreateOptionsVecSlice,
100
    OptionWindowCreateOptions
101
);
102
impl_vec_clone!(
103
    WindowCreateOptions,
104
    WindowCreateOptionsVec,
105
    WindowCreateOptionsVecDestructor
106
);
107
impl_vec_partialeq!(WindowCreateOptions, WindowCreateOptionsVec);
108
impl_vec_debug!(WindowCreateOptions, WindowCreateOptionsVec);
109
impl_vec_mut!(WindowCreateOptions, WindowCreateOptionsVec);
110

            
111
/// Full window state including internal fields not exposed to callbacks
112
#[derive(Debug, Clone, PartialEq)]
113
#[repr(C)]
114
pub struct FullWindowState {
115
    /// Platform-specific window options
116
    pub platform_specific_options: PlatformSpecificOptions,
117
    /// Current keyboard state (pressed keys, modifiers)
118
    pub keyboard_state: KeyboardState,
119
    /// Semantic window identifier for multi-window debugging.
120
    /// Can be set by the user to identify specific windows (e.g., "main", "settings", "popup-1")
121
    pub window_id: AzString,
122
    /// Window title bar text
123
    pub title: AzString,
124
    /// Optional callback invoked when the user requests the window to close
125
    pub close_callback: OptionCallback,
126
    /// Callback that returns the DOM for this window
127
    pub layout_callback: LayoutCallback,
128
    /// Window position on screen
129
    pub position: WindowPosition,
130
    /// Current touch/gesture input state
131
    pub touch_state: TouchState,
132
    /// Window dimensions (logical and physical)
133
    pub size: WindowSize,
134
    /// Window flags (minimized, maximized, fullscreen, etc.)
135
    pub flags: WindowFlags,
136
    /// Current mouse cursor state (position, buttons)
137
    pub mouse_state: MouseState,
138
    /// Active window theme (light/dark)
139
    pub theme: WindowTheme,
140
    /// Position of the IME candidate window
141
    pub ime_position: ImePosition,
142
    /// GPU renderer options (`VSync`, SRGB, hardware acceleration)
143
    pub renderer_options: RendererOptions,
144
    /// Monitor ID (not the full Monitor struct - just the identifier)
145
    pub monitor_id: OptionU32,
146
    /// Debug visualization state (layout borders, repaints, etc.)
147
    pub debug_state: DebugState,
148
    /// Window background color. If None, uses system window background color.
149
    pub background_color: OptionColorU,
150
    /// Whether this window currently has input focus
151
    pub window_focused: bool,
152
    /// Active route match (pattern + extracted parameters).
153
    /// Set by `CallbackInfo::switch_route()` or by the web server on URL match.
154
    /// Layout callbacks read this via `LayoutCallbackInfo::get_route_param()`.
155
    pub active_route: azul_core::resources::OptionRouteMatch,
156
    /// Every pointer seat OTHER than the primary (9b-ii), sorted by `seat_id`.
157
    /// APPENDED for ABI stability.
158
    ///
159
    /// `mouse_state` above IS the primary seat, and is deliberately not
160
    /// duplicated in here: two copies of one cursor are a desync waiting to
161
    /// happen, and every existing reader of "the mouse" keeps reading the
162
    /// primary. Empty on any platform that presents one cursor - Windows,
163
    /// macOS, Android, iOS - which is why nothing there changes. See
164
    /// [`azul_core::window::PointerSeat`] for why the key is a SEAT and not a
165
    /// device. Read and write through [`Self::pointer_seat`] /
166
    /// [`Self::pointer_seat_mut`], which fold the primary in.
167
    pub pointer_seats: azul_core::window::PointerSeatVec,
168
    /// The NON-primary seats' keyboards (9b-ii-a-i), the per-seat twin of
169
    /// `pointer_seats`; `keyboard_state` is the primary seat's and is never
170
    /// duplicated here. Read through [`Self::keyboard_seat`].
171
    pub keyboard_seats: azul_core::window::KeyboardSeatVec,
172
}
173

            
174
impl FullWindowState {
175
    /// The state of pointer seat `seat_id`: the primary for
176
    /// [`PRIMARY_POINTER_SEAT`](azul_core::window::PRIMARY_POINTER_SEAT),
177
    /// otherwise the matching entry of `pointer_seats`, or `None` for a seat
178
    /// this window has never seen.
179
    #[must_use]
180
72
    pub fn pointer_seat(&self, seat_id: u64) -> Option<&MouseState> {
181
72
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
182
1
            return Some(&self.mouse_state);
183
71
        }
184
71
        self.pointer_seats
185
71
            .as_ref()
186
71
            .iter()
187
71
            .find(|s| s.seat_id == seat_id)
188
71
            .map(|s| &s.state)
189
72
    }
190

            
191
    /// Mutable access to seat `seat_id`, CREATING it (default state) when it
192
    /// is new - the platform handlers call this the moment a second master
193
    /// pointer moves, and "first seen" is the only registration a seat gets.
194
    /// Keeps `pointer_seats` sorted so equality and the event diff are
195
    /// order-independent.
196
45
    pub fn pointer_seat_mut(&mut self, seat_id: u64) -> &mut MouseState {
197
        use azul_core::window::{PointerSeat, PointerSeatVec};
198
45
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
199
9
            return &mut self.mouse_state;
200
36
        }
201
36
        let idx = match self
202
36
            .pointer_seats
203
36
            .as_ref()
204
36
            .binary_search_by_key(&seat_id, |s| s.seat_id)
205
        {
206
23
            Ok(i) => i,
207
13
            Err(i) => {
208
13
                let mut v = self.pointer_seats.clone().into_library_owned_vec();
209
13
                v.insert(
210
13
                    i,
211
13
                    PointerSeat {
212
13
                        seat_id,
213
13
                        state: MouseState::default(),
214
13
                    },
215
                );
216
13
                self.pointer_seats = PointerSeatVec::from_vec(v);
217
13
                i
218
            }
219
        };
220
36
        &mut self.pointer_seats.as_mut()[idx].state
221
45
    }
222

            
223
    /// Forget a non-primary seat (the master pointer was removed, the
224
    /// `wl_seat` went away). The event diff then releases whatever it held,
225
    /// because a seat present in the previous state and absent in the current
226
    /// one is diffed against a default state. The primary cannot be removed;
227
    /// returns whether anything went.
228
3
    pub fn remove_pointer_seat(&mut self, seat_id: u64) -> bool {
229
        use azul_core::window::PointerSeatVec;
230
3
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
231
1
            return false;
232
2
        }
233
2
        let before = self.pointer_seats.len();
234
2
        if !self
235
2
            .pointer_seats
236
2
            .as_ref()
237
2
            .iter()
238
2
            .any(|s| s.seat_id == seat_id)
239
        {
240
1
            return false;
241
1
        }
242
1
        let mut v = self.pointer_seats.clone().into_library_owned_vec();
243
1
        v.retain(|s| s.seat_id != seat_id);
244
1
        self.pointer_seats = PointerSeatVec::from_vec(v);
245
1
        self.pointer_seats.len() != before
246
3
    }
247

            
248
    /// Every seat, primary first.
249
1
    pub fn pointer_seats_with_primary(&self) -> impl Iterator<Item = (u64, &MouseState)> {
250
1
        core::iter::once((azul_core::window::PRIMARY_POINTER_SEAT, &self.mouse_state)).chain(
251
1
            self.pointer_seats
252
1
                .as_ref()
253
1
                .iter()
254
2
                .map(|s| (s.seat_id, &s.state)),
255
        )
256
1
    }
257

            
258
    /// One seat's keyboard (9b-ii-a-i): the primary's own for seat 0.
259
    #[must_use]
260
7
    pub fn keyboard_seat(&self, seat_id: u64) -> Option<&KeyboardState> {
261
7
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
262
            return Some(&self.keyboard_state);
263
7
        }
264
7
        self.keyboard_seats
265
7
            .as_ref()
266
7
            .iter()
267
7
            .find(|s| s.seat_id == seat_id)
268
7
            .map(|s| &s.state)
269
7
    }
270

            
271
    /// One seat's keyboard for writing, created (sorted by id) on first use.
272
116
    pub fn keyboard_seat_mut(&mut self, seat_id: u64) -> &mut KeyboardState {
273
        use azul_core::window::{KeyboardSeat, KeyboardSeatVec, KeyboardState};
274
116
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
275
102
            return &mut self.keyboard_state;
276
14
        }
277
14
        let idx = match self
278
14
            .keyboard_seats
279
14
            .as_ref()
280
14
            .binary_search_by_key(&seat_id, |s| s.seat_id)
281
        {
282
11
            Ok(i) => i,
283
3
            Err(i) => {
284
3
                let mut v = self.keyboard_seats.clone().into_library_owned_vec();
285
3
                v.insert(
286
3
                    i,
287
3
                    KeyboardSeat {
288
3
                        seat_id,
289
3
                        state: KeyboardState::default(),
290
3
                    },
291
                );
292
3
                self.keyboard_seats = KeyboardSeatVec::from_vec(v);
293
3
                i
294
            }
295
        };
296
14
        &mut self.keyboard_seats.as_mut()[idx].state
297
116
    }
298

            
299
    /// Drop a seat's keyboard (the seat went away). Never the primary's.
300
    pub fn remove_keyboard_seat(&mut self, seat_id: u64) -> bool {
301
        use azul_core::window::KeyboardSeatVec;
302
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
303
            return false;
304
        }
305
        if !self
306
            .keyboard_seats
307
            .as_ref()
308
            .iter()
309
            .any(|s| s.seat_id == seat_id)
310
        {
311
            return false;
312
        }
313
        let mut v = self.keyboard_seats.clone().into_library_owned_vec();
314
        v.retain(|s| s.seat_id != seat_id);
315
        self.keyboard_seats = KeyboardSeatVec::from_vec(v);
316
        true
317
    }
318

            
319
    /// Every keyboard, the primary's first.
320
    pub fn keyboard_seats_with_primary(&self) -> impl Iterator<Item = (u64, &KeyboardState)> {
321
        core::iter::once((
322
            azul_core::window::PRIMARY_POINTER_SEAT,
323
            &self.keyboard_state,
324
        ))
325
        .chain(
326
            self.keyboard_seats
327
                .as_ref()
328
                .iter()
329
                .map(|s| (s.seat_id, &s.state)),
330
        )
331
    }
332
}
333

            
334
impl_option!(
335
    FullWindowState,
336
    OptionFullWindowState,
337
    copy = false,
338
    [Debug, Clone, PartialEq]
339
);
340

            
341
// C-ABI vec so that `CallbackInfo::queue_window_state_sequence()` can be
342
// exposed over FFI (a `Vec<FullWindowState>` is not repr(C)).
343
impl_vec!(
344
    FullWindowState,
345
    FullWindowStateVec,
346
    FullWindowStateVecDestructor,
347
    FullWindowStateVecDestructorType,
348
    FullWindowStateVecSlice,
349
    OptionFullWindowState
350
);
351
impl_vec_clone!(
352
    FullWindowState,
353
    FullWindowStateVec,
354
    FullWindowStateVecDestructor
355
);
356
impl_vec_partialeq!(FullWindowState, FullWindowStateVec);
357
impl_vec_debug!(FullWindowState, FullWindowStateVec);
358

            
359
impl Default for FullWindowState {
360
20267
    fn default() -> Self {
361
20267
        Self {
362
20267
            platform_specific_options: PlatformSpecificOptions::default(),
363
20267
            keyboard_state: KeyboardState::default(),
364
20267
            window_id: AzString::from_const_str("azul-window"),
365
20267
            title: AzString::from_const_str("Azul Window"),
366
20267
            close_callback: OptionCallback::None,
367
20267
            layout_callback: LayoutCallback::default(),
368
20267
            position: WindowPosition::default(),
369
20267
            touch_state: TouchState::default(),
370
20267
            size: WindowSize::default(),
371
20267
            flags: WindowFlags::default(),
372
20267
            mouse_state: MouseState::default(),
373
20267
            pointer_seats: azul_core::window::PointerSeatVec::from_const_slice(&[]),
374
20267
            keyboard_seats: azul_core::window::KeyboardSeatVec::from_const_slice(&[]),
375
20267
            theme: WindowTheme::default(),
376
20267
            ime_position: ImePosition::default(),
377
20267
            renderer_options: RendererOptions::default(),
378
20267
            monitor_id: OptionU32::None,
379
20267
            debug_state: DebugState::default(),
380
20267
            background_color: OptionColorU::None,
381
20267
            window_focused: true,
382
20267
            active_route: azul_core::resources::OptionRouteMatch::None,
383
20267
        }
384
20267
    }
385
}
386

            
387
#[cfg(test)]
388
mod autotest_generated {
389
    use azul_core::{
390
        callbacks::{LayoutCallbackInfo, LayoutCallbackType, Update},
391
        dom::Dom,
392
        geom::{LogicalSize, PhysicalPositionI32},
393
        refany::RefAny,
394
        resources::{OptionRouteMatch, RouteMatch},
395
        window::{AzStringPair, OptionWindowTheme, StringPairVec},
396
    };
397
    use azul_css::props::basic::ColorU;
398

            
399
    use super::*;
400
    use crate::callbacks::{Callback, CallbackInfo};
401

            
402
    // ------------------------------------------------------------------
403
    // Pointer seats (9b-ii)
404
    // ------------------------------------------------------------------
405

            
406
    #[test]
407
    fn seat_zero_is_the_primary_and_never_an_entry() {
408
        use azul_core::window::PRIMARY_POINTER_SEAT;
409
        let mut s = FullWindowState::default();
410
        s.pointer_seat_mut(PRIMARY_POINTER_SEAT).left_down = true;
411
        assert!(s.mouse_state.left_down, "seat 0 IS mouse_state");
412
        assert!(
413
            s.pointer_seats.is_empty(),
414
            "and is never duplicated into the vec"
415
        );
416
        assert!(!s.remove_pointer_seat(PRIMARY_POINTER_SEAT));
417
        assert_eq!(
418
            s.pointer_seat(PRIMARY_POINTER_SEAT).map(|m| m.left_down),
419
            Some(true)
420
        );
421
    }
422

            
423
    #[test]
424
    fn seats_are_created_on_first_touch_and_kept_sorted() {
425
        let mut s = FullWindowState::default();
426
        assert!(s.pointer_seat(7).is_none());
427
        s.pointer_seat_mut(7).right_down = true;
428
        s.pointer_seat_mut(3).left_down = true;
429
        s.pointer_seat_mut(7).middle_down = true;
430
        let ids: Vec<u64> = s.pointer_seats.as_ref().iter().map(|p| p.seat_id).collect();
431
        assert_eq!(ids, vec![3, 7], "sorted, and 7 was not re-created");
432
        let seven = s.pointer_seat(7).unwrap();
433
        assert!(seven.right_down && seven.middle_down);
434
        assert!(!s.mouse_state.right_down, "the primary is untouched");
435
        let all: Vec<u64> = s.pointer_seats_with_primary().map(|(id, _)| id).collect();
436
        assert_eq!(all, vec![0, 3, 7]);
437
    }
438

            
439
    #[test]
440
    fn a_removed_seat_is_gone_and_equality_sees_it() {
441
        let mut a = FullWindowState::default();
442
        a.pointer_seat_mut(5).left_down = true;
443
        let b = FullWindowState::default();
444
        assert_ne!(a, b, "a second cursor holding a button is a state delta");
445
        assert!(a.remove_pointer_seat(5));
446
        assert!(!a.remove_pointer_seat(5));
447
        assert_eq!(a, b);
448
    }
449

            
450
    // ------------------------------------------------------------------
451
    // Harness
452
    // ------------------------------------------------------------------
453

            
454
    // The four layout callbacks below deliberately have DIFFERENT bodies:
455
    // identical-body `extern "C"` functions can be folded onto a single symbol
456
    // by the linker (identical code folding), which would silently make two
457
    // "distinct" callbacks compare equal. Every assertion here is still written
458
    // so it holds either way — the pointer that goes in is the pointer that
459
    // must come out — but distinct bodies keep the tests meaningful.
460

            
461
    extern "C" fn cb_alpha(_: RefAny, _: LayoutCallbackInfo) -> Dom {
462
        Dom::create_body()
463
    }
464

            
465
    extern "C" fn cb_beta(_: RefAny, _: LayoutCallbackInfo) -> Dom {
466
        Dom::create_text_do_not_use_without_block_level_wrapper("beta")
467
    }
468

            
469
    extern "C" fn cb_gamma(_: RefAny, _: LayoutCallbackInfo) -> Dom {
470
        Dom::create_text_do_not_use_without_block_level_wrapper("gamma-gamma-gamma")
471
    }
472

            
473
    /// Stored by `create` but never invoked by it — invoking it fails the test.
474
    extern "C" fn cb_never_called(_: RefAny, _: LayoutCallbackInfo) -> Dom {
475
        unreachable!("WindowCreateOptions::create must not invoke the layout callback")
476
    }
477

            
478
    extern "C" fn close_cb(_: RefAny, _: CallbackInfo) -> Update {
479
        Update::DoNothing
480
    }
481

            
482
    fn ptr_of(f: LayoutCallbackType) -> usize {
483
        f as usize
484
    }
485

            
486
    fn stored_cb(o: &WindowCreateOptions) -> usize {
487
        o.window_state.layout_callback.cb as usize
488
    }
489

            
490
    /// `FullWindowState::default()` with one mutation applied. Written as a
491
    /// helper so the tests do not trip `field_reassign_with_default`.
492
    fn state_with(mutate: impl FnOnce(&mut FullWindowState)) -> FullWindowState {
493
        let mut s = FullWindowState::default();
494
        mutate(&mut s);
495
        s
496
    }
497

            
498
    fn options_with(mutate: impl FnOnce(&mut WindowCreateOptions)) -> WindowCreateOptions {
499
        let mut o = WindowCreateOptions::default();
500
        mutate(&mut o);
501
        o
502
    }
503

            
504
    fn opts_with_id(id: u64) -> WindowCreateOptions {
505
        let mut o = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
506
        o.parent_window_id = id;
507
        o
508
    }
509

            
510
    fn ids_of(v: &WindowCreateOptionsVec) -> Vec<u64> {
511
        v.as_slice().iter().map(|o| o.parent_window_id).collect()
512
    }
513

            
514
    /// Strings that break naive string handling: empty, interior NUL, astral
515
    /// planes, ZWJ sequences, RTL, combining marks, bidi/zero-width controls,
516
    /// fullwidth forms, and a 128 KiB blob.
517
    fn nasty_strings() -> Vec<String> {
518
        vec![
519
            String::new(),
520
            "\0".to_string(),
521
            "a\0b\0".to_string(),
522
            "🦀🐉👨‍👩‍👧‍👦".to_string(),
523
            "مرحبا بالعالم".to_string(),
524
            "e\u{0301}\u{0301}\u{0301}".to_string(),
525
            "\u{200B}\u{FEFF}\u{202E}drowssap".to_string(),
526
            "fullwidth".to_string(),
527
            "ß".repeat(65_536),
528
        ]
529
    }
530

            
531
    // ------------------------------------------------------------------
532
    // WindowCreateOptions::create
533
    // ------------------------------------------------------------------
534

            
535
    #[test]
536
    fn create_stores_the_callback_and_leaves_every_other_field_at_default() {
537
        let opts = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
538
        let def = WindowCreateOptions::default();
539

            
540
        assert_eq!(stored_cb(&opts), ptr_of(cb_alpha));
541
        assert!(opts.window_state.layout_callback.ctx.is_none());
542

            
543
        assert_eq!(opts.create_callback, def.create_callback);
544
        assert_eq!(opts.renderer, def.renderer);
545
        assert_eq!(opts.theme, def.theme);
546
        assert_eq!(opts.size_to_content, def.size_to_content);
547
        assert_eq!(opts.hot_reload, def.hot_reload);
548
        assert_eq!(opts.parent_window_id, def.parent_window_id);
549
        assert_eq!(opts.window_state.title, def.window_state.title);
550
        assert_eq!(opts.window_state.window_id, def.window_state.window_id);
551
        assert_eq!(
552
            opts.window_state.close_callback,
553
            def.window_state.close_callback
554
        );
555
        assert_eq!(
556
            opts.window_state.window_focused,
557
            def.window_state.window_focused
558
        );
559
    }
560

            
561
    #[test]
562
    fn create_records_exactly_the_pointer_it_was_given() {
563
        let all: [LayoutCallbackType; 4] = [cb_alpha, cb_beta, cb_gamma, cb_never_called];
564
        for cb in all.iter().copied() {
565
            let opts = WindowCreateOptions::create(cb);
566
            assert_eq!(stored_cb(&opts), cb as usize);
567
        }
568
    }
569

            
570
    #[test]
571
    fn create_does_not_invoke_the_stored_callback() {
572
        // `cb_never_called` panics if it ever runs; reaching the assert proves
573
        // `create` only *stores* the pointer.
574
        let opts = WindowCreateOptions::create(cb_never_called as LayoutCallbackType);
575
        assert_eq!(stored_cb(&opts), ptr_of(cb_never_called));
576
    }
577

            
578
    #[test]
579
    fn create_with_the_default_callback_equals_default_options() {
580
        let opts = WindowCreateOptions::create(LayoutCallback::default());
581
        assert_eq!(opts, WindowCreateOptions::default());
582
    }
583

            
584
    #[test]
585
    fn create_accepts_a_layout_callback_value_and_preserves_its_ctx() {
586
        // The `impl Into<LayoutCallback>` arg may already carry an FFI ctx
587
        // payload; `create` must not drop it.
588
        let cb = LayoutCallback {
589
            cb: cb_beta,
590
            ctx: Some(RefAny::new(vec![0xAAu8; 4096])).into(),
591
        };
592
        let opts = WindowCreateOptions::create(cb);
593
        assert_eq!(stored_cb(&opts), ptr_of(cb_beta));
594
        assert!(opts.window_state.layout_callback.ctx.is_some());
595

            
596
        // Same, routed through `LayoutCallback::create`.
597
        let opts =
598
            WindowCreateOptions::create(LayoutCallback::create(cb_gamma as LayoutCallbackType));
599
        assert_eq!(stored_cb(&opts), ptr_of(cb_gamma));
600
        assert!(opts.window_state.layout_callback.ctx.is_none());
601
    }
602

            
603
    #[test]
604
    fn create_is_deterministic_and_independent_across_calls() {
605
        let first = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
606
        for _ in 0..500 {
607
            let next = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
608
            assert_eq!(next, first);
609
        }
610

            
611
        // Mutating one result must not disturb a later one.
612
        let mut a = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
613
        a.parent_window_id = u64::MAX;
614
        a.window_state.title = AzString::from("mutated");
615
        let b = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
616
        assert_eq!(b, first);
617
        assert_ne!(a, b);
618
    }
619

            
620
    // ------------------------------------------------------------------
621
    // Default invariants
622
    // ------------------------------------------------------------------
623

            
624
    #[test]
625
    fn full_window_state_default_invariants() {
626
        let s = FullWindowState::default();
627

            
628
        assert_eq!(s.window_id.as_str(), "azul-window");
629
        assert_eq!(s.title.as_str(), "Azul Window");
630
        assert!(s.window_focused);
631
        assert!(s.monitor_id.is_none());
632
        assert!(s.background_color.is_none());
633
        assert!(s.active_route.is_none());
634
        assert_eq!(s.close_callback, OptionCallback::None);
635
        assert_eq!(s.theme, WindowTheme::default());
636
        assert_eq!(s.position, WindowPosition::default());
637
        assert_eq!(s.ime_position, ImePosition::default());
638

            
639
        // Default is a pure value: stable, self-equal, and clone-equal.
640
        assert_eq!(s, FullWindowState::default());
641
        assert_eq!(s.clone(), s);
642
    }
643

            
644
    #[test]
645
    fn window_create_options_default_invariants() {
646
        let o = WindowCreateOptions::default();
647

            
648
        assert_eq!(o.parent_window_id, 0, "0 means 'no parent window'");
649
        assert!(!o.size_to_content);
650
        assert!(!o.hot_reload);
651
        assert!(o.renderer.is_none());
652
        assert!(o.theme.is_none());
653
        assert_eq!(o.create_callback, OptionCallback::None);
654
        assert_eq!(o.window_state, FullWindowState::default());
655

            
656
        assert_eq!(o, WindowCreateOptions::default());
657
        assert_eq!(o.clone(), o);
658
    }
659

            
660
    // ------------------------------------------------------------------
661
    // Equality / predicate invariants
662
    // ------------------------------------------------------------------
663

            
664
    #[test]
665
    fn mutating_any_scalar_field_breaks_equality() {
666
        let base = WindowCreateOptions::default();
667

            
668
        assert_ne!(options_with(|o| o.parent_window_id = u64::MAX), base);
669
        assert_ne!(options_with(|o| o.parent_window_id = 1), base);
670
        assert_ne!(options_with(|o| o.size_to_content = true), base);
671
        assert_ne!(options_with(|o| o.hot_reload = true), base);
672
        assert_ne!(
673
            options_with(|o| o.theme = OptionWindowTheme::Some(WindowTheme::DarkMode)),
674
            base
675
        );
676
        assert_ne!(
677
            options_with(|o| o.create_callback =
678
                OptionCallback::Some(Callback::from(close_cb as crate::callbacks::CallbackType))),
679
            base
680
        );
681
        assert_ne!(
682
            options_with(|o| o.window_state.window_focused = false),
683
            base
684
        );
685
        assert_ne!(
686
            options_with(|o| o.window_state.monitor_id = OptionU32::Some(u32::MAX)),
687
            base
688
        );
689
        assert_ne!(
690
            options_with(|o| o.window_state.monitor_id = OptionU32::Some(0)),
691
            base
692
        );
693
        assert_ne!(
694
            options_with(
695
                |o| o.window_state.background_color = OptionColorU::Some(ColorU {
696
                    r: 0,
697
                    g: 0,
698
                    b: 0,
699
                    a: 0,
700
                })
701
            ),
702
            base
703
        );
704
        assert_ne!(
705
            options_with(|o| o.window_state.title = AzString::from("")),
706
            base
707
        );
708
    }
709

            
710
    #[test]
711
    #[allow(clippy::eq_op)] // `a == a` IS the reflexivity check being asserted
712
    fn equality_is_reflexive_symmetric_and_transitive_for_extreme_values() {
713
        let a = options_with(|o| {
714
            o.parent_window_id = u64::MAX;
715
            o.window_state.title = AzString::from("🦀\0🦀");
716
            o.window_state.size.dimensions = LogicalSize::new(f32::NAN, -0.0);
717
        });
718
        let b = a.clone();
719
        let c = b.clone();
720

            
721
        assert_eq!(a, a); // reflexive, even with a NaN inside
722
        assert_eq!(a, b);
723
        assert_eq!(b, a); // symmetric
724
        assert_eq!(b, c);
725
        assert_eq!(a, c); // transitive
726
        assert_ne!(a, WindowCreateOptions::default());
727
    }
728

            
729
    #[test]
730
    fn callback_ctx_is_deliberately_not_part_of_equality() {
731
        // `impl_callback!` compares callbacks by function pointer only, so two
732
        // otherwise-identical states that differ ONLY in the FFI ctx payload
733
        // compare equal. Pinned so a change to that rule is loud.
734
        let a = WindowCreateOptions::create(cb_alpha as LayoutCallbackType);
735
        let mut b = a.clone();
736
        b.window_state.layout_callback.ctx = Some(RefAny::new(0xDEAD_BEEF_u32)).into();
737

            
738
        assert!(a.window_state.layout_callback.ctx.is_none());
739
        assert!(b.window_state.layout_callback.ctx.is_some());
740
        assert_eq!(a, b);
741
    }
742

            
743
    // ------------------------------------------------------------------
744
    // Numeric limits / NaN / saturation
745
    // ------------------------------------------------------------------
746

            
747
    #[test]
748
    fn nan_dimensions_stay_reflexive_and_do_not_alias_the_origin() {
749
        let nan = state_with(|s| s.size.dimensions = LogicalSize::new(f32::NAN, f32::NAN));
750
        let zero = state_with(|s| s.size.dimensions = LogicalSize::new(0.0, 0.0));
751

            
752
        // `LogicalSize`'s PartialEq quantizes, mapping NaN to a fixed sentinel,
753
        // so equality stays reflexive (unlike raw f32) and NaN != origin.
754
        assert_eq!(nan, nan.clone());
755
        assert_ne!(nan, zero);
756
        assert_ne!(nan, FullWindowState::default());
757
    }
758

            
759
    #[test]
760
    fn out_of_range_dimensions_saturate_rather_than_wrap() {
761
        // Quantization multiplies by 1000 and saturates the f32->i64 cast, so
762
        // every coordinate at or beyond the overflow point collapses onto the
763
        // same bound. Pinned as behaviour, not as a claim that it is ideal.
764
        let inf = state_with(|s| {
765
            s.size.dimensions = LogicalSize::new(f32::INFINITY, f32::NEG_INFINITY);
766
        });
767
        let max = state_with(|s| s.size.dimensions = LogicalSize::new(f32::MAX, -f32::MAX));
768

            
769
        assert_eq!(inf, inf.clone());
770
        assert_eq!(max, max.clone());
771
        assert_eq!(
772
            inf, max,
773
            "f32::MAX * 1000 overflows to inf, so both saturate"
774
        );
775

            
776
        // Tiny magnitudes quantize to 0 and are therefore indistinguishable
777
        // from the origin — no panic, no wraparound.
778
        let tiny = state_with(|s| {
779
            s.size.dimensions = LogicalSize::new(f32::MIN_POSITIVE, -f32::MIN_POSITIVE);
780
        });
781
        assert_eq!(
782
            tiny,
783
            state_with(|s| s.size.dimensions = LogicalSize::new(0.0, -0.0))
784
        );
785
    }
786

            
787
    #[test]
788
    fn integer_window_state_limits_survive_clone_and_containers() {
789
        let extreme = state_with(|s| {
790
            s.size.dpi = 0; // platform reported no DPI at all
791
            s.size.min_dimensions = Some(LogicalSize::new(-0.0, 0.0)).into();
792
            s.size.max_dimensions = Some(LogicalSize::new(f32::INFINITY, f32::INFINITY)).into();
793
            s.monitor_id = OptionU32::Some(u32::MAX);
794
            s.position = WindowPosition::Initialized(PhysicalPositionI32 {
795
                x: i32::MIN,
796
                y: i32::MAX,
797
            });
798
            s.background_color = OptionColorU::Some(ColorU {
799
                r: u8::MAX,
800
                g: 0,
801
                b: u8::MAX,
802
                a: 0,
803
            });
804
        });
805

            
806
        let cloned = extreme.clone();
807
        assert_eq!(cloned, extreme);
808
        assert_eq!(cloned.size.dpi, 0);
809
        assert_eq!(cloned.monitor_id.into_option(), Some(u32::MAX));
810
        assert_eq!(
811
            cloned.position,
812
            WindowPosition::Initialized(PhysicalPositionI32 {
813
                x: i32::MIN,
814
                y: i32::MAX,
815
            })
816
        );
817

            
818
        let round_tripped: Option<FullWindowState> = OptionFullWindowState::Some(cloned).into();
819
        assert_eq!(round_tripped, Some(extreme.clone()));
820

            
821
        let v = FullWindowStateVec::from_vec(vec![extreme.clone()]);
822
        assert_eq!(v.as_slice()[0], extreme);
823
    }
824

            
825
    #[test]
826
    fn parent_window_id_boundaries_survive_every_round_trip() {
827
        let ids: [u64; 5] = [0, 1, u64::MAX / 2, u64::MAX - 1, u64::MAX];
828
        for id in ids.iter().copied() {
829
            let o = opts_with_id(id);
830
            assert_eq!(o.parent_window_id, id);
831
            assert_eq!(o.clone().parent_window_id, id);
832

            
833
            let opt: OptionWindowCreateOptions = Some(o.clone()).into();
834
            assert_eq!(opt.as_ref().map(|x| x.parent_window_id), Some(id));
835

            
836
            let v = WindowCreateOptionsVec::from_vec(vec![o.clone()]);
837
            assert_eq!(v.as_slice()[0].parent_window_id, id);
838

            
839
            let out: Vec<WindowCreateOptions> = v.into();
840
            assert_eq!(out[0], o);
841
        }
842
    }
843

            
844
    // ------------------------------------------------------------------
845
    // Unicode / huge strings
846
    // ------------------------------------------------------------------
847

            
848
    #[test]
849
    fn unicode_and_huge_strings_round_trip_through_state_and_containers() {
850
        for s in nasty_strings() {
851
            let st = state_with(|w| {
852
                w.title = AzString::from(s.clone());
853
                w.window_id = AzString::from(s.clone());
854
            });
855

            
856
            assert_eq!(st.title.as_str(), s.as_str());
857
            assert_eq!(st.title.as_str().len(), s.len(), "byte length preserved");
858
            assert_eq!(st.window_id.as_str(), s.as_str());
859

            
860
            let cloned = st.clone();
861
            assert_eq!(cloned, st);
862
            assert_eq!(cloned.title.as_str(), s.as_str());
863

            
864
            // encode == decode through the FFI Option wrapper
865
            let opt: OptionFullWindowState = Some(st.clone()).into();
866
            let back: Option<FullWindowState> = opt.into();
867
            assert_eq!(back.as_ref().map(|x| x.title.as_str()), Some(s.as_str()));
868

            
869
            // ... and through the FFI Vec wrapper
870
            let v = FullWindowStateVec::from_vec(vec![st.clone(), st.clone()]);
871
            assert_eq!(v.len(), 2);
872
            assert_eq!(v.as_slice()[1].title.as_str(), s.as_str());
873
            assert_eq!(v.clone(), v);
874

            
875
            let out: Vec<FullWindowState> = v.into_library_owned_vec();
876
            assert_eq!(out.len(), 2);
877
            assert_eq!(out[0].title.as_str(), s.as_str());
878
            assert_eq!(out[0], st);
879
        }
880
    }
881

            
882
    #[test]
883
    fn debug_rendering_survives_nasty_strings() {
884
        for s in nasty_strings().into_iter().filter(|s| s.len() < 4096) {
885
            let o = options_with(|w| {
886
                w.window_state.title = AzString::from(s.clone());
887
                w.parent_window_id = u64::MAX;
888
            });
889
            let rendered = format!("{o:?}");
890
            assert!(rendered.starts_with("WindowCreateOptions"));
891
            assert!(rendered.contains("18446744073709551615"));
892
        }
893
    }
894

            
895
    #[test]
896
    fn active_route_round_trips_with_unicode_pattern_and_params() {
897
        let route = RouteMatch {
898
            pattern: AzString::from("/user/:id/🦀"),
899
            params: StringPairVec::from_vec(vec![AzStringPair {
900
                key: AzString::from("id"),
901
                value: AzString::from("𝟜𝟚"),
902
            }]),
903
        };
904
        let st = state_with(|s| s.active_route = OptionRouteMatch::Some(route.clone()));
905

            
906
        assert!(st.active_route.is_some());
907
        assert_ne!(st, FullWindowState::default());
908

            
909
        let opt: OptionFullWindowState = Some(st.clone()).into();
910
        let back = opt.into_option().expect("just constructed as Some");
911
        assert_eq!(back, st);
912
        assert_eq!(
913
            back.active_route.as_ref().map(|r| r.pattern.as_str()),
914
            Some("/user/:id/🦀")
915
        );
916
        assert_eq!(
917
            back.active_route
918
                .as_ref()
919
                .and_then(|r| r.get_param("id"))
920
                .map(|v| v.as_str()),
921
            Some("𝟜𝟚")
922
        );
923
        assert!(back
924
            .active_route
925
            .as_ref()
926
            .and_then(|r| r.get_param("missing"))
927
            .is_none());
928
    }
929

            
930
    // ------------------------------------------------------------------
931
    // OptionWindowCreateOptions / OptionFullWindowState
932
    // ------------------------------------------------------------------
933

            
934
    #[test]
935
    fn option_wrappers_agree_with_std_option() {
936
        let opts = WindowCreateOptions::create(cb_beta as LayoutCallbackType);
937

            
938
        let none: OptionWindowCreateOptions = Option::<WindowCreateOptions>::None.into();
939
        assert!(none.is_none());
940
        assert!(!none.is_some());
941
        assert!(none.as_ref().is_none());
942
        assert!(none.as_option().is_none());
943
        assert_eq!(none, OptionWindowCreateOptions::default());
944
        let back: Option<WindowCreateOptions> = none.into();
945
        assert_eq!(back, None);
946

            
947
        let some: OptionWindowCreateOptions = Some(opts.clone()).into();
948
        assert!(some.is_some());
949
        assert!(!some.is_none());
950
        assert_eq!(some.as_ref(), Some(&opts));
951
        assert_eq!(some.into_option(), Some(opts.clone()));
952
        assert_eq!(some.clone().map(|o| o.parent_window_id), Some(0));
953
        assert_eq!(
954
            some.clone()
955
                .and_then(|o| o.window_state.title.as_str().chars().next()),
956
            Some('A')
957
        );
958
        let back: Option<WindowCreateOptions> = some.into();
959
        assert_eq!(back, Some(opts));
960
    }
961

            
962
    #[test]
963
    fn option_replace_returns_the_previous_value() {
964
        let a = opts_with_id(1);
965
        let b = opts_with_id(2);
966

            
967
        let mut o = OptionWindowCreateOptions::None;
968
        assert!(o.replace(a.clone()).is_none());
969
        assert_eq!(o.as_ref(), Some(&a));
970

            
971
        let prev = o.replace(b.clone());
972
        assert_eq!(prev.as_ref(), Some(&a));
973
        assert_eq!(o.as_ref(), Some(&b));
974

            
975
        if let Some(inner) = o.as_mut() {
976
            inner.parent_window_id = u64::MAX;
977
        }
978
        assert_eq!(o.as_ref().map(|x| x.parent_window_id), Some(u64::MAX));
979
        // the value handed back by `replace` is independent of `o`
980
        assert_eq!(prev.as_ref().map(|x| x.parent_window_id), Some(1));
981
    }
982

            
983
    #[test]
984
    fn option_into_option_hands_back_an_independent_clone() {
985
        let mut o: OptionFullWindowState = Some(FullWindowState::default()).into();
986

            
987
        let mut taken = o.into_option().expect("constructed as Some");
988
        taken.title = AzString::from("changed");
989
        assert_eq!(
990
            o.as_ref().map(|s| s.title.as_str()),
991
            Some("Azul Window"),
992
            "into_option must clone, not alias"
993
        );
994

            
995
        if let Some(inner) = o.as_mut() {
996
            inner.title = AzString::from("also changed");
997
        }
998
        assert_eq!(taken.title.as_str(), "changed");
999
    }
    // ------------------------------------------------------------------
    // WindowCreateOptionsVec
    // ------------------------------------------------------------------
    #[test]
    fn vec_round_trips_empty_single_and_large() {
        for n in [0usize, 1, 2, 1000].iter().copied() {
            let src: Vec<WindowCreateOptions> = (0..n as u64).map(opts_with_id).collect();
            let v = WindowCreateOptionsVec::from_vec(src.clone());
            assert_eq!(v.len(), n);
            assert_eq!(v.is_empty(), n == 0);
            assert!(v.capacity() >= v.len());
            assert_eq!(v.as_slice(), src.as_slice());
            assert_eq!(v.iter().count(), n);
            assert_eq!(v.as_c_slice().len(), n);
            assert_eq!(v.as_c_slice().as_slice(), src.as_slice());
            let out: Vec<WindowCreateOptions> = v.into_library_owned_vec();
            assert_eq!(out, src, "encode == decode");
        }
    }
    #[test]
    fn vec_get_is_none_out_of_bounds() {
        let v = WindowCreateOptionsVec::from_vec(vec![opts_with_id(7)]);
        assert_eq!(v.get(0).map(|o| o.parent_window_id), Some(7));
        assert!(v.get(1).is_none());
        assert!(v.get(usize::MAX).is_none());
        assert!(v.c_get(1).is_none());
        assert!(v.c_get(usize::MAX).is_none());
        assert_eq!(
            v.c_get(0).into_option().map(|o| o.parent_window_id),
            Some(7)
        );
        let empty = WindowCreateOptionsVec::new();
        assert!(empty.is_empty());
        assert!(empty.get(0).is_none());
        assert!(empty.get(usize::MAX).is_none());
        assert!(empty.c_get(0).is_none());
        assert_eq!(empty.as_slice(), &[] as &[WindowCreateOptions]);
    }
    #[test]
    fn vec_c_slice_range_clamps_instead_of_panicking() {
        let v = WindowCreateOptionsVec::from_vec((0..4u64).map(opts_with_id).collect());
        assert_eq!(v.as_c_slice_range(0, 4).len(), 4);
        assert_eq!(v.as_c_slice_range(1, 3).len(), 2);
        assert_eq!(v.as_c_slice_range(1, 3).as_slice()[0].parent_window_id, 1);
        assert_eq!(v.as_c_slice_range(3, 1).len(), 0, "inverted range -> empty");
        assert_eq!(v.as_c_slice_range(4, 4).len(), 0);
        assert_eq!(
            v.as_c_slice_range(0, usize::MAX).len(),
            4,
            "end clamps to len"
        );
        assert_eq!(v.as_c_slice_range(2, usize::MAX).as_slice().len(), 2);
        assert_eq!(v.as_c_slice_range(usize::MAX, usize::MAX).len(), 0);
        assert_eq!(v.as_c_slice_range(usize::MAX, 0).len(), 0);
        let empty = WindowCreateOptionsVec::new();
        assert!(empty.as_c_slice_range(0, usize::MAX).is_empty());
        assert!(empty.as_c_slice_range(usize::MAX, usize::MAX).is_empty());
        assert!(empty.as_c_slice().as_slice().is_empty());
    }
    #[test]
    fn vec_insert_and_remove_are_noops_out_of_bounds() {
        let mut v = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1), opts_with_id(2)]);
        v.insert(3, opts_with_id(99)); // index > len
        assert_eq!(ids_of(&v), vec![1, 2]);
        v.insert(usize::MAX, opts_with_id(99));
        assert_eq!(ids_of(&v), vec![1, 2]);
        v.remove(2); // index == len
        assert_eq!(ids_of(&v), vec![1, 2]);
        v.remove(usize::MAX);
        assert_eq!(ids_of(&v), vec![1, 2]);
        v.insert(0, opts_with_id(0)); // prepend
        v.insert(3, opts_with_id(3)); // index == len -> append
        assert_eq!(ids_of(&v), vec![0, 1, 2, 3]);
        v.remove(0);
        assert_eq!(ids_of(&v), vec![1, 2, 3]);
        v.remove(2);
        assert_eq!(ids_of(&v), vec![1, 2]);
    }
    #[test]
    fn vec_push_pop_truncate_retain_keep_len_and_capacity_consistent() {
        let mut v = WindowCreateOptionsVec::new();
        assert!(v.pop().is_none(), "pop on an empty vec must not panic");
        for i in 0..256u64 {
            v.push(opts_with_id(i));
            assert_eq!(v.len(), i as usize + 1);
            assert!(v.capacity() >= v.len());
        }
        assert_eq!(v.get(255).map(|o| o.parent_window_id), Some(255));
        assert_eq!(v.pop().map(|o| o.parent_window_id), Some(255));
        assert_eq!(v.len(), 255);
        v.truncate(1000); // larger than len -> no-op
        assert_eq!(v.len(), 255);
        v.retain(|o| o.parent_window_id % 2 == 0);
        assert_eq!(v.len(), 128);
        assert!(v.as_slice().iter().all(|o| o.parent_window_id % 2 == 0));
        v.truncate(0);
        assert!(v.is_empty());
        assert!(v.pop().is_none());
        assert_eq!(v.as_slice(), &[] as &[WindowCreateOptions]);
    }
    #[test]
    fn vec_append_moves_everything_and_empties_the_source() {
        let mut a = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1)]);
        let mut b = WindowCreateOptionsVec::from_vec(vec![opts_with_id(2), opts_with_id(3)]);
        a.append(&mut b);
        assert_eq!(ids_of(&a), vec![1, 2, 3]);
        assert!(b.is_empty());
        let mut empty = WindowCreateOptionsVec::new();
        a.append(&mut empty); // appending nothing changes nothing
        assert_eq!(ids_of(&a), vec![1, 2, 3]);
        empty.append(&mut a); // appending into a zero-capacity vec
        assert_eq!(ids_of(&empty), vec![1, 2, 3]);
        assert!(a.is_empty());
    }
    #[test]
    fn vec_clone_is_deep_and_growth_does_not_alias_the_original() {
        let original = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1), opts_with_id(2)]);
        let mut cloned = original.clone();
        assert_eq!(cloned, original);
        assert_ne!(
            cloned.as_ptr(),
            original.as_ptr(),
            "a clone must own a separate buffer"
        );
        for i in 0..64u64 {
            cloned.push(opts_with_id(100 + i));
        }
        assert_eq!(cloned.len(), 66);
        assert_eq!(ids_of(&original), vec![1, 2], "original must be untouched");
        for o in cloned.iter_mut() {
            o.hot_reload = true;
        }
        assert!(!original.as_slice()[0].hot_reload);
    }
    #[test]
    fn vec_from_iterator_extend_and_sort_are_consistent() {
        let mut v: WindowCreateOptionsVec = (0..8u64).rev().map(opts_with_id).collect();
        assert_eq!(v.len(), 8);
        assert_eq!(ids_of(&v), vec![7, 6, 5, 4, 3, 2, 1, 0]);
        v.extend((8..12u64).map(opts_with_id));
        assert_eq!(v.len(), 12);
        v.sort_by(|a, b| a.parent_window_id.cmp(&b.parent_window_id));
        assert_eq!(ids_of(&v), (0..12u64).collect::<Vec<_>>());
        let back: Vec<WindowCreateOptions> = v.into();
        assert_eq!(back.len(), 12);
        let again: WindowCreateOptionsVec = back.into();
        assert_eq!(ids_of(&again), (0..12u64).collect::<Vec<_>>());
        let single = WindowCreateOptionsVec::from_item(opts_with_id(42));
        assert_eq!(ids_of(&single), vec![42]);
        let reserved = WindowCreateOptionsVec::with_capacity(0);
        assert!(reserved.is_empty());
    }
    #[test]
    fn vec_equality_and_debug_are_well_behaved() {
        let a = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1)]);
        let b = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1)]);
        let c = WindowCreateOptionsVec::from_vec(vec![opts_with_id(2)]);
        let longer = WindowCreateOptionsVec::from_vec(vec![opts_with_id(1), opts_with_id(1)]);
        let empty = WindowCreateOptionsVec::new();
        assert_eq!(a, b);
        assert_ne!(a, c);
        assert_ne!(a, longer, "length is part of equality");
        assert_ne!(a, empty);
        assert_eq!(empty, WindowCreateOptionsVec::default());
        assert_eq!(format!("{empty:?}"), "[]");
        assert!(format!("{a:?}").starts_with('['));
    }
    // ------------------------------------------------------------------
    // FullWindowStateVec (no mutation API — read-only surface)
    // ------------------------------------------------------------------
    #[test]
    fn full_window_state_vec_round_trips_and_clones_deeply() {
        let extreme = state_with(|s| {
            s.title = AzString::from("t".repeat(4096));
            s.size.dimensions = LogicalSize::new(f32::NAN, f32::INFINITY);
            s.monitor_id = OptionU32::Some(u32::MAX);
            s.window_focused = false;
        });
        let v = FullWindowStateVec::from_vec(vec![FullWindowState::default(), extreme.clone()]);
        assert_eq!(v.len(), 2);
        assert!(!v.is_empty());
        assert!(v.get(2).is_none());
        assert!(v.get(usize::MAX).is_none());
        assert!(v.c_get(2).is_none());
        assert_eq!(v.c_get(1).into_option().as_ref(), Some(&extreme));
        assert_eq!(v.iter().count(), 2);
        assert_eq!(v.as_c_slice_range(1, usize::MAX).len(), 1);
        let cloned = v.clone();
        assert_eq!(cloned, v);
        assert_ne!(cloned.as_ptr(), v.as_ptr());
        let out: Vec<FullWindowState> = cloned.into_library_owned_vec();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0], FullWindowState::default());
        assert_eq!(out[1], extreme);
        assert_eq!(v.len(), 2, "original survives the clone being consumed");
        let single = FullWindowStateVec::from_item(extreme.clone());
        assert_eq!(single.len(), 1);
        assert_eq!(single.as_slice()[0], extreme);
        let empty = FullWindowStateVec::new();
        assert!(empty.is_empty());
        assert!(empty.get(0).is_none());
        assert_eq!(empty, FullWindowStateVec::default());
        assert_eq!(format!("{empty:?}"), "[]");
    }
    #[test]
    fn state_vec_survives_a_large_batch_of_extreme_states() {
        let src: Vec<FullWindowState> = (0..512u32)
            .map(|i| {
                state_with(|s| {
                    s.monitor_id = OptionU32::Some(i);
                    s.title = AzString::from(format!("win-{i}-🦀"));
                    s.size.dimensions = LogicalSize::new(i as f32, f32::NAN);
                })
            })
            .collect();
        let v = FullWindowStateVec::from_vec(src.clone());
        assert_eq!(v.len(), 512);
        assert_eq!(v.clone(), v);
        assert_eq!(v.as_slice()[511].title.as_str(), "win-511-🦀");
        let out: Vec<FullWindowState> = v.into_library_owned_vec();
        assert_eq!(out, src, "encode == decode for 512 extreme states");
    }
}