waterui-internal 0.3.0

Internal implementation crate for WaterUI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Module defining the `Window` struct for UI windows.
//!
//! # Window Backgrounds
//!
//! Windows support solid color backgrounds. For blur effects, use `Material`:
//! `Material` is delegated to platform backends as `MaterialBackground` metadata
//! and is best-effort (quality and behavior may vary by platform).
//!
//! ```rust
//! use waterui::prelude::*;
//! use waterui::window::{Window, WindowState};
//!
//! // Semi-transparent colored window
//! let tinted = Window::new("Tinted", binding::<WindowState>(WindowState::default()), || text!("Hello"))
//!     .background(Color::srgb(0, 0, 0).with_opacity(0.8));
//!
//! // Frosted glass window (opaque window + material blur on content)
//! let frosted = Window::new("Frosted", binding::<WindowState>(WindowState::default()), || text!("Hello"))
//!     .background(Material::Regular);
//! ```

use std::{fmt::Debug, rc::Rc};

use nami::{Binding, Computed, SignalExt as _, impl_constant, signal::IntoComputed};
use waterui_core::handler::{AnyViewBuilder, ViewBuilder};
use waterui_core::{AnyView, Dynamic, Environment, IgnorableMetadata, View};
use waterui_graphics::Color;
use waterui_layout::{Point, Rect, Size};
use waterui_str::Str;

use crate::app::application_name;
#[cfg(feature = "snackbar")]
use crate::snackbar::SnackbarManager;
use crate::{
    ViewExt,
    background::{Material, MaterialBackground},
    component::label::LabelDisplayMode,
    prelude::FullScreenOverlayManager,
};

/// Represents a window in the UI.
#[derive(Debug)]
pub struct Window {
    /// The title of the window.
    ///
    /// Notice that it may not be displayed on all platforms.
    pub title: Computed<Str>,
    /// Whether the window is closable.
    ///
    /// Notice that it may not be supported on all platforms.
    pub closable: bool,
    /// Whether the window is resizable.
    ///
    /// Notice that it may not be supported on all platforms.
    pub resizable: bool,
    /// The frame of the window.
    ///
    /// Notice that it may not be supported on all platforms.
    pub frame: Binding<Rect>,
    /// The root view builder for the window content.
    pub content: AnyViewBuilder<AnyView>,
    /// The current state of the window.
    pub state: Binding<WindowState>,
    /// Optional toolbar content for the window.
    ///
    /// Notice that it may not be supported on all platforms.
    pub toolbar: Option<AnyView>,
    /// The visual style of the window.
    ///
    /// Notice that it may not be supported on all platforms.
    pub style: WindowStyle,
    /// The background style of the window.
    ///
    /// Use this to create transparent or frosted glass windows.
    /// Notice that it may not be supported on all platforms.
    pub background: WindowBackground,
    /// Explicit minimum content size the window can be resized down to.
    ///
    /// When `None` (the default), the backend derives the minimum from the
    /// content's own layout: each root-view axis is measured independently with
    /// a zero proposal, so the window can never be resized smaller than its
    /// content's minimum — the same negotiation every [`Layout`] container
    /// performs on its children, applied at the window boundary.
    ///
    /// Platform support: enforced by desktop backends (hydrolysis/winit,
    /// macOS `NSWindow.contentMinSize`/`contentMaxSize`). iOS/iPadOS has no
    /// per-window size control today (the Apple backend's multi-window support
    /// is macOS-only); Android's single-Activity model has no per-window
    /// runtime size limits; embedded (dew) displays are fixed-size — those
    /// targets ignore this.
    ///
    /// [`Layout`]: waterui_core::layout::Layout
    pub min_size: Option<Computed<Size>>,
    /// Explicit maximum content size the window can be resized up to.
    ///
    /// When `None` (the default), self-drawn desktop backends derive the maximum
    /// from the content's own layout by measuring each axis with an infinite
    /// proposal. A layout that accepts infinity leaves that axis unbounded.
    /// Native backends may require an explicit maximum. Same platform support
    /// notes as [`Self::min_size`].
    pub max_size: Option<Computed<Size>>,
}

/// The state of a window.
///
/// `Default::default()` returns [`Self::Closed`]: a freshly initialized
/// state binding represents a window that has not yet been shown. Setting
/// the binding to [`Self::Normal`] is what triggers the window to open.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowState {
    /// The window is in its normal state.
    Normal,
    /// The window is closed.
    #[default]
    Closed,
    /// The window is minimized.
    Minimized,
    /// The window is maximized to fullscreen.
    Fullscreen,
}

/// The visual style of a window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WindowStyle {
    /// Standard window with title bar and controls.
    #[default]
    Titled,
    /// Borderless window without title bar.
    Borderless,
    /// Window where content extends into the title bar area.
    ///
    /// On macOS, this corresponds to `NSWindow.StyleMask.fullSizeContentView`.
    FullSizeContentView,
}

/// The background style of a window (FFI level).
///
/// This only supports opaque or solid color backgrounds.
/// For blur effects, use `Material` which wraps content with `MaterialBackground` metadata.
///
/// # Platform Support
///
/// - **macOS/iOS**: Supports both opaque and colored backgrounds.
/// - **Android**: Supports colored backgrounds via `Window.setBackgroundDrawable()`.
/// - **Linux (GTK)**: Supports colored backgrounds via window CSS/background styling.
#[derive(Debug, Clone, Default)]
pub enum WindowBackground {
    /// Opaque system default background.
    #[default]
    Opaque,
    /// Solid color background (can be semi-transparent via alpha).
    Color(Color),
}

/// Input type for `Window::background()` method.
///
/// Allows setting window background via `Color` or `Material`.
/// When `Material` is used, the window becomes opaque and the content
/// is wrapped with a `MaterialBackground` metadata for native blur effects.
#[derive(Debug)]
pub enum WindowBackgroundInput {
    /// A solid color background.
    Color(Color),
    /// A material blur effect (wraps content, window stays opaque).
    Material(Material),
}

impl From<Color> for WindowBackgroundInput {
    fn from(color: Color) -> Self {
        Self::Color(color)
    }
}

impl From<Material> for WindowBackgroundInput {
    fn from(material: Material) -> Self {
        Self::Material(material)
    }
}

/// Manages the display of windows.
#[derive(Clone)]
pub struct WindowManager(Rc<dyn Fn(Window)>);

impl Debug for WindowManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowManager").finish()
    }
}

impl WindowManager {
    /// Create a new `WindowManager` with the specified show function.
    pub fn new<F: 'static + Fn(Window)>(show: F) -> Self {
        Self(Rc::new(show))
    }

    /// Show a window using the window manager.
    pub fn show(&self, window: Window) {
        (self.0)(window);
    }
}

impl_constant!(WindowState);
impl_constant!(WindowStyle);

impl Window {
    /// Create a new window with the specified title, state binding, and content.
    ///
    /// `state` is required: every example calls `.with_state(...)` on every
    /// window in practice, so the parameter is positional. Use
    /// `binding::<WindowState>(default())` (which is [`WindowState::Closed`])
    /// to start the window closed; flip to [`WindowState::Normal`] to open it.
    ///
    /// Note: this does not show the window immediately. It is shown via
    /// [`Self::show`] or by being conditionally rendered with
    /// [`conditional_window`].
    #[must_use]
    pub fn new(
        title: impl IntoComputed<Str>,
        state: Binding<WindowState>,
        content: impl ViewBuilder,
    ) -> Self {
        let default_frame = Rect::new(Point::zero(), Size::new(800.0, 600.0));
        let (overlay_manager, overlay_view) = FullScreenOverlayManager::new();
        #[cfg(feature = "snackbar")]
        let (snackbar_manager, snackbar_view) = SnackbarManager::new();
        let content = AnyViewBuilder::new(move || {
            let overlay_manager = overlay_manager.clone();
            #[cfg(feature = "snackbar")]
            let snackbar_manager = snackbar_manager.clone();
            let content = content
                .build()
                .overlay(overlay_view.clone())
                .with(overlay_manager.clone())
                .state(&overlay_manager);
            #[cfg(feature = "snackbar")]
            let content = content
                .overlay(snackbar_view.clone())
                .with(snackbar_manager.clone())
                .state(&snackbar_manager);
            AnyView::new(content)
        });

        Self {
            title: title.into_computed(),
            closable: true,
            resizable: true,
            frame: Binding::container(default_frame),
            content,
            state,
            toolbar: None,
            style: WindowStyle::default(),
            background: WindowBackground::default(),
            min_size: None,
            max_size: None,
        }
    }

    /// Set an explicit minimum content size for the window.
    ///
    /// Without one, the backend derives the minimum from the content's layout
    /// by measuring each axis independently at a zero proposal. See
    /// [`Self::min_size`] for platform support notes.
    #[must_use]
    pub fn min_size(mut self, size: impl IntoComputed<Size>) -> Self {
        self.min_size = Some(size.into_computed());
        self
    }

    /// Set an explicit maximum content size for the window.
    ///
    /// See [`Self::max_size`] for platform support notes.
    #[must_use]
    pub fn max_size(mut self, size: impl IntoComputed<Size>) -> Self {
        self.max_size = Some(size.into_computed());
        self
    }

    /// Set whether the window is resizable.
    #[must_use]
    pub const fn resizable(mut self, resizable: bool) -> Self {
        self.resizable = resizable;
        self
    }

    /// Set the toolbar content for the window.
    ///
    /// Toolbar subtrees automatically install [`LabelDisplayMode::IconOnly`] so
    /// semantic labels adapt to compact window chrome while preserving their
    /// accessibility text. Individual labels can opt back into
    /// [`LabelDisplayMode::TitleOnly`] or [`LabelDisplayMode::TitleAndIcon`].
    #[must_use]
    pub fn toolbar(mut self, toolbar: impl View) -> Self {
        self.toolbar = Some(AnyView::new(toolbar.install(LabelDisplayMode::IconOnly)));
        self
    }

    /// Set the visual style of the window.
    #[must_use]
    pub const fn style(mut self, style: WindowStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the background style of the window.
    ///
    /// Accepts either a `Color` for solid backgrounds or a `Material` for blur effects.
    /// When using `Material`, the window stays opaque and the content is wrapped with
    /// `MaterialBackground` metadata handled by the native backend on a best-effort basis.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use waterui::prelude::*;
    /// use waterui::window::{Window, WindowState};
    ///
    /// // Semi-transparent colored window
    /// let tinted = Window::new("Tinted", binding::<WindowState>(WindowState::default()), || text!("Hello"))
    ///     .background(Color::srgb(0, 0, 0).with_opacity(0.8));
    ///
    /// // Frosted glass window (opaque + material blur on content)
    /// let frosted = Window::new("Frosted", binding::<WindowState>(WindowState::default()), || text!("Hello"))
    ///     .background(Material::Regular);
    /// ```
    #[must_use]
    pub fn background(mut self, background: impl Into<WindowBackgroundInput>) -> Self {
        match background.into() {
            WindowBackgroundInput::Color(color) => {
                self.background = WindowBackground::Color(color);
            }
            WindowBackgroundInput::Material(material) => {
                // Keep window opaque, wrap content with MaterialBackground metadata
                self.background = WindowBackground::Opaque;
                let content = self.content;
                self.content = AnyViewBuilder::new(move || {
                    AnyView::new(IgnorableMetadata::new(
                        content.build(),
                        MaterialBackground(material),
                    ))
                });
            }
        }
        self
    }

    /// Builds the current window content tree.
    pub fn build_content(&self) -> AnyView {
        self.content.build()
    }

    /// Set the title of the window.
    #[must_use]
    pub fn title(mut self, title: impl IntoComputed<Str>) -> Self {
        self.title = title.into_computed();
        self
    }

    /// The title to put on the window, which is what a backend should show.
    ///
    /// A window that declares no title of its own — an empty one — is shown
    /// under the application's name, so that an application which never says
    /// what its window is called is still named after itself rather than after
    /// the framework. This is resolved here rather than in each backend so that
    /// every one of them titles a window the same way.
    ///
    /// The name is empty when nothing told the application what it is called,
    /// which leaves the decision to the platform: a bundle knows its own name
    /// and keeps whatever it had.
    #[must_use]
    pub fn display_title(&self) -> Computed<Str> {
        let application = application_name();
        self.title
            .map(move |declared| {
                if declared.is_empty() {
                    application.clone()
                } else {
                    declared
                }
            })
            .into_computed()
    }

    /// Get a handle to control the window after showing it.
    #[must_use]
    pub fn handle(&self) -> WindowHandle {
        WindowHandle {
            frame: self.frame.clone(),
            state: self.state.clone(),
        }
    }

    /// Show the window on screen.
    ///
    /// # Panics
    ///
    /// Panics if `WindowManager` is not found in the environment.
    pub fn show(self, env: &Environment) {
        env.get::<WindowManager>()
            .expect("WindowManager not found in environment")
            .show(self);
    }
}

// Implement View for Window to allow reactive window display.
// When a Window is rendered as a View, it shows itself via WindowManager.
impl View for Window {
    fn body(self, env: &Environment) -> impl View {
        self.show(env);
        // Return empty view - the window is shown separately
    }
}

/// Owns the explicit presentation state for a conditionally created window.
///
/// Keep this value at the same semantic level as the window's [`WindowState`]
/// binding. Its retained `presented` binding prevents unrelated state changes
/// such as Normal → Minimized from creating duplicate native windows.
#[derive(Debug, Clone)]
pub struct WindowPresentation {
    state: Binding<WindowState>,
    presented: Binding<bool>,
}

impl WindowPresentation {
    /// Creates presentation state for a window controlled by `state`.
    #[must_use]
    pub fn new(state: &Binding<WindowState>) -> Self {
        Self {
            state: state.clone(),
            presented: Binding::container(false),
        }
    }

    /// Returns the window-state binding controlled by this presentation.
    #[must_use]
    pub fn state(&self) -> Binding<WindowState> {
        self.state.clone()
    }
}

/// Shows a window only once per "open" cycle.
///
/// The window is shown when the presentation's state transitions from
/// [`WindowState::Closed`] to any other state. Closing the window resets the
/// retained presentation binding so a subsequent open creates a new native
/// window.
pub fn conditional_window<F>(presentation: &WindowPresentation, creator: F) -> impl View + use<F>
where
    F: Fn(Binding<WindowState>) -> Window + 'static,
{
    let state = presentation.state.clone();
    let presented = presentation.presented.clone();

    Dynamic::watch(state.clone(), move |s| {
        if s == WindowState::Closed {
            presented.set(false);
            AnyView::new(())
        } else if !presented.get() {
            presented.set(true);
            AnyView::new(creator(state.clone()))
        } else {
            AnyView::new(())
        }
    })
}

/// A handle to control a window after it has been shown.
#[derive(Debug, Clone)]
pub struct WindowHandle {
    frame: Binding<Rect>,
    state: Binding<WindowState>,
}

impl WindowHandle {
    /// Close the window.
    pub fn close(&self) {
        self.state.set(WindowState::Closed);
    }

    /// Minimize the window.
    pub fn minimize(&self) {
        self.state.set(WindowState::Minimized);
    }

    /// Maximize the window to fullscreen.
    pub fn fullscreen(&self) {
        self.state.set(WindowState::Fullscreen);
    }

    /// Restore the window to its normal state.
    pub fn restore(&self) {
        self.state.set(WindowState::Normal);
    }

    /// Set the frame of the window.
    pub fn set_frame(&self, frame: Rect) {
        self.frame.set(frame);
    }
}