icedtea 0.17.2

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

use std::borrow::Cow;

use iced::{Font, Pixels, Settings, Size};

use crate::density::{Density, DensityName};
use crate::i18n::{Catalog, Locale};
use crate::m3::{ElevationPolicy, ShapePolicy};
use crate::theme::{self, ThemeCatalog, Tokens};
use crate::typo;
use crate::window::{self, DisplayBounds, WindowKind};

/// How an icedtea application boots.
///
/// ```
/// let boot = icedtea::app::Boot::new("demo", "dev.icedtea.demo");
/// let prep = icedtea::app::bootstrap(&boot);
/// assert_eq!(prep.tokens.canvas, icedtea::theme::named("dark").tokens.canvas);
/// assert!(prep.iced_settings.fonts.is_empty());
/// assert!(!prep.window.transparent);
/// assert!(prep.window.decorations);
/// let glass = icedtea::app::bootstrap(
///     &icedtea::app::Boot::new("demo", "dev.icedtea.demo")
///         .transparent(true)
///         .decorations(false),
/// );
/// assert!(glass.window.transparent);
/// assert!(!glass.window.decorations);
/// ```
#[derive(Debug, Clone)]
pub struct Boot {
    pub title: String,
    pub application_id: String,
    pub window: WindowKind,
    pub theme_name: String,
    pub locale: Locale,
    pub density: DensityName,
    pub font_scale: f32,
    pub shape: ShapePolicy,
    pub elevation: ElevationPolicy,
    pub size: Option<Size>,
    pub min_size: Option<Size>,
    pub max_size: Option<Size>,
    pub pointer: Option<(f32, f32)>,
    pub displays: Vec<DisplayBounds>,
    pub transparent: bool,
    pub decorations: Option<bool>,
    /// Widget id focused on the first frame. Empty: first focus target.
    pub focus: Option<String>,
    /// Face bytes loaded at iced start. Empty unless [`Self::fonts`].
    pub fonts: Vec<Cow<'static, [u8]>>,
}

impl Boot {
    pub fn new(title: impl Into<String>, application_id: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            application_id: application_id.into(),
            window: WindowKind::Application,
            theme_name: "dark".into(),
            locale: Locale::default(),
            density: DensityName::Default,
            font_scale: 1.0,
            shape: ShapePolicy::Desktop,
            elevation: ElevationPolicy::Desktop,
            size: None,
            min_size: None,
            max_size: None,
            pointer: None,
            displays: Vec::new(),
            transparent: false,
            decorations: None,
            focus: None,
            fonts: Vec::new(),
        }
    }

    /// Focus this iced widget id on the first frame.
    pub fn focus(mut self, id: impl Into<String>) -> Self {
        self.focus = Some(id.into());
        self
    }

    pub fn overlay(mut self) -> Self {
        self.window = WindowKind::Overlay;
        self
    }

    pub fn dialog(mut self) -> Self {
        self.window = WindowKind::Dialog;
        self
    }

    pub fn theme(mut self, name: impl Into<String>) -> Self {
        self.theme_name = name.into();
        self
    }

    pub fn locale(mut self, locale: Locale) -> Self {
        self.locale = locale;
        self
    }

    pub fn density(mut self, density: DensityName) -> Self {
        self.density = density;
        self
    }

    /// Type-scale multiplier (1.0 is the Material body size).
    pub fn font_scale(mut self, scale: f32) -> Self {
        self.font_scale = scale;
        self
    }

    /// Corner policy applied to every constructor.
    pub fn shape(mut self, shape: ShapePolicy) -> Self {
        self.shape = shape;
        self
    }

    /// Shadow policy applied to every constructor.
    pub fn elevation(mut self, elevation: ElevationPolicy) -> Self {
        self.elevation = elevation;
        self
    }

    /// Inner window size in pixels.
    pub fn size(mut self, width: f32, height: f32) -> Self {
        self.size = Some(Size::new(width, height));
        self
    }

    /// Minimum inner window size in pixels.
    pub fn min_size(mut self, width: f32, height: f32) -> Self {
        self.min_size = Some(Size::new(width, height));
        self
    }

    /// Maximum inner window size in pixels.
    pub fn max_size(mut self, width: f32, height: f32) -> Self {
        self.max_size = Some(Size::new(width, height));
        self
    }

    /// Pointer used to pick the overlay's display.
    pub fn pointer(mut self, x: f32, y: f32) -> Self {
        self.pointer = Some((x, y));
        self
    }

    /// Display rectangles in the same space as [`Self::pointer`].
    pub fn displays(mut self, displays: impl Into<Vec<DisplayBounds>>) -> Self {
        self.displays = displays.into();
        self
    }

    /// ARGB window buffer. Later compositor blur needs the channel.
    pub fn transparent(mut self, on: bool) -> Self {
        self.transparent = on;
        self
    }

    /// Client title bar. `None` on [`Boot::new`] follows the window kind
    /// (on for application and dialog, off for overlay).
    pub fn decorations(mut self, on: bool) -> Self {
        self.decorations = Some(on);
        self
    }

    /// Named faces for the iced font database (then [`crate::typo::bind_sans_family`]).
    ///
    /// icedtea does not ship a font file. The application owns these bytes.
    ///
    /// ```
    /// use std::borrow::Cow;
    /// let boot = icedtea::Boot::new("demo", "dev.demo").fonts([Cow::Borrowed(&b"\0"[..])]);
    /// assert_eq!(icedtea::bootstrap(&boot).iced_settings.fonts.len(), 1);
    /// ```
    pub fn fonts(mut self, fonts: impl Into<Vec<Cow<'static, [u8]>>>) -> Self {
        self.fonts = fonts.into();
        self
    }
}

/// Resolved boot data used by `run`.
#[derive(Debug, Clone)]
pub struct Prepared {
    pub title: String,
    pub tokens: Tokens,
    pub theme_name: String,
    pub density: Density,
    pub locale: Locale,
    pub catalog: Catalog,
    pub iced_settings: Settings,
    pub window: iced::window::Settings,
    pub iced_theme: iced::Theme,
    pub focus: Option<iced::widget::Id>,
}

/// Load theme and window settings. Does not open a window.
pub fn bootstrap(boot: &Boot) -> Prepared {
    bootstrap_with_catalog(boot, &ThemeCatalog::new())
}

pub fn bootstrap_with_catalog(boot: &Boot, themes: &ThemeCatalog) -> Prepared {
    let named = themes
        .get(&boot.theme_name)
        .or_else(|| themes.get("dark"))
        .expect("dark theme");
    let tokens = named
        .tokens
        .with_density(Density::named(boot.density))
        .with_font_scale(boot.font_scale)
        .with_shape(boot.shape)
        .with_elevation(boot.elevation)
        .with_direction(boot.locale.direction)
        .with_clock_digits(crate::i18n::ClockDigits::for_lang(&boot.locale.lang));
    let iced_theme = theme::iced_theme(&named.name, tokens);
    let iced_settings = Settings {
        id: Some(boot.application_id.clone()),
        fonts: boot.fonts.clone(),
        default_font: typo::UI,
        default_text_size: Pixels(tokens.body()),
        antialiasing: true,
        vsync: true,
    };
    Prepared {
        title: boot.title.clone(),
        tokens,
        theme_name: named.name,
        density: Density::named(boot.density),
        locale: boot.locale.clone(),
        catalog: Catalog::for_locale(&boot.locale),
        iced_settings,
        window: {
            let mut win = window::settings(boot.window, &boot.application_id);
            if let Some(size) = boot.size {
                win.size = size;
            }
            if let Some(min) = boot.min_size {
                win.min_size = Some(min);
            }
            if let Some(max) = boot.max_size {
                win.max_size = Some(max);
            }
            if boot.window == WindowKind::Overlay {
                if let Some(pointer) = boot.pointer {
                    win.position = iced::window::Position::Specific(window::place(
                        pointer,
                        win.size,
                        &boot.displays,
                    ));
                }
            }
            win.transparent = boot.transparent;
            if let Some(decorations) = boot.decorations {
                win.decorations = decorations;
            }
            win
        },
        iced_theme,
        focus: boot.focus.clone().map(iced::widget::Id::from),
    }
}

impl Prepared {
    /// Text direction from [`Boot::locale`], used by chrome recipes.
    pub fn direction(&self) -> crate::i18n::Direction {
        self.locale.direction
    }

    /// Open a window with these settings. Used from [`crate::daemon!`].
    ///
    /// The process stays up when the window closes. Map the [`iced::Task`]
    /// to store the id, then [`iced::window::close`] to hide.
    ///
    /// ```
    /// let prep = icedtea::bootstrap(&icedtea::Boot::new("hud", "dev.hud").overlay());
    /// let (id, _open) = prep.open();
    /// let (again, _) = prep.open();
    /// assert_ne!(id, again);
    /// ```
    pub fn open(&self) -> (iced::window::Id, iced::Task<iced::window::Id>) {
        iced::window::open(self.window.clone())
    }

    /// Open a decorated desktop window from the same settings.
    ///
    /// [`crate::window::retarget`] first. Pop-out from an overlay.
    ///
    /// ```
    /// let prep = icedtea::bootstrap(&icedtea::Boot::new("hud", "dev.hud").overlay());
    /// let (id, _open) = prep.open_desktop();
    /// let _ = id;
    /// ```
    pub fn open_desktop(&self) -> (iced::window::Id, iced::Task<iced::window::Id>) {
        let mut win = self.window.clone();
        let app_id = self.iced_settings.id.as_deref().unwrap_or("");
        crate::window::retarget(&mut win, app_id);
        iced::window::open(win)
    }
}

/// Default UI font after bootstrap.
pub fn default_font() -> Font {
    typo::UI
}

/// Window title that does not borrow application state.
///
/// ```
/// let t = icedtea::app::WindowTitle("demo".into());
/// assert_eq!(<icedtea::app::WindowTitle as icedtea::iced::application::TitleFn<()>>::title(&t, &()), "demo");
/// assert_eq!(
///     <icedtea::app::WindowTitle as icedtea::iced::daemon::TitleFn<()>>::title(
///         &t,
///         &(),
///         icedtea::iced::window::Id::unique(),
///     ),
///     "demo"
/// );
/// ```
#[derive(Debug, Clone)]
pub struct WindowTitle(pub String);

impl<S> iced::application::TitleFn<S> for WindowTitle {
    fn title(&self, _state: &S) -> String {
        self.0.clone()
    }
}

impl<S> iced::daemon::TitleFn<S> for WindowTitle {
    fn title(&self, _state: &S, _window: iced::window::Id) -> String {
        self.0.clone()
    }
}

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

    fn specific_xy(pos: iced::window::Position) -> Option<(f32, f32)> {
        match pos {
            iced::window::Position::Specific(p) => Some((p.x, p.y)),
            iced::window::Position::Centered
            | iced::window::Position::Default
            | iced::window::Position::SpecificWith(_) => None,
        }
    }

    #[test]
    fn bootstrap_loads_theme_and_window_kinds() {
        let mut boot = Boot::new("App", "dev.icedtea.app")
            .theme("nord")
            .density(DensityName::Compact)
            .font_scale(1.25)
            .shape(ShapePolicy::Material)
            .elevation(ElevationPolicy::Flat);
        boot = boot.locale(Locale::new("ar"));
        let prep = bootstrap(&boot);
        assert_eq!(prep.theme_name, "nord");
        assert_eq!(prep.density.space, 4);
        assert_eq!(prep.tokens.density.space, 4);
        assert_eq!(prep.tokens.body(), 18.0);
        assert_eq!(prep.tokens.shape, ShapePolicy::Material);
        assert_eq!(prep.tokens.elevation, ElevationPolicy::Flat);
        assert_eq!(prep.locale.direction, crate::i18n::Direction::Rtl);
        assert_eq!(prep.direction(), crate::i18n::Direction::Rtl);
        assert_eq!(prep.catalog.t("direction"), "rtl");
        assert!(prep.iced_settings.fonts.is_empty());
        assert_eq!(default_font(), typo::UI);
        let ov = bootstrap(&Boot::new("p", "dev.x").overlay());
        assert!(!ov.window.decorations);
        assert!(ov.window.max_size.is_none());
        let placed = bootstrap(
            &Boot::new("p", "dev.x")
                .overlay()
                .size(900.0, 700.0)
                .pointer(100.0, 80.0)
                .displays(vec![DisplayBounds {
                    x: 0.0,
                    y: 0.0,
                    width: 1920.0,
                    height: 1080.0,
                }]),
        );
        assert_eq!(placed.window.size.width, 900.0);
        assert_eq!(placed.window.size.height, 700.0);
        assert!(placed.window.max_size.is_none());
        assert_eq!(specific_xy(placed.window.position), Some((100.0, 80.0)));
        assert_eq!(specific_xy(iced::window::Position::Centered), None);
        assert_eq!(specific_xy(iced::window::Position::Default), None);
        let place: fn(iced::Size, iced::Size) -> iced::Point = |_, _| iced::Point::ORIGIN;
        assert_eq!(
            place(iced::Size::ZERO, iced::Size::ZERO),
            iced::Point::ORIGIN
        );
        assert_eq!(
            specific_xy(iced::window::Position::SpecificWith(place)),
            None
        );
        let dlg = bootstrap(&Boot::new("d", "dev.x").dialog());
        assert!(dlg.window.decorations);
        let mut cat = ThemeCatalog::new();
        cat.register("brand", crate::theme::named("light").tokens, false);
        let prep = bootstrap_with_catalog(&Boot::new("a", "dev.x").theme("brand"), &cat);
        assert_eq!(prep.theme_name, "brand");
        let missing = bootstrap(&Boot::new("a", "dev.x").theme("nope"));
        assert_eq!(missing.theme_name, "dark");
        let sized = bootstrap(
            &Boot::new("tool", "dev.tool")
                .size(380.0, 640.0)
                .min_size(360.0, 560.0)
                .max_size(420.0, 720.0),
        );
        assert_eq!(sized.window.size.width, 380.0);
        assert_eq!(sized.window.size.height, 640.0);
        assert_eq!(sized.window.min_size.unwrap().width, 360.0);
        assert_eq!(sized.window.min_size.unwrap().height, 560.0);
        assert_eq!(sized.window.max_size.unwrap().width, 420.0);
        let t = WindowTitle("demo".into());
        assert_eq!(
            <WindowTitle as iced::application::TitleFn<()>>::title(&t, &()),
            "demo"
        );
        assert_eq!(
            <WindowTitle as iced::daemon::TitleFn<()>>::title(&t, &(), iced::window::Id::unique()),
            "demo"
        );
    }

    #[test]
    fn bootstrap_copies_focus_id() {
        let prep = bootstrap(&Boot::new("demo", "dev.icedtea.demo").focus("palette-query"));
        assert_eq!(prep.focus, Some(iced::widget::Id::new("palette-query")));
        assert!(bootstrap(&Boot::new("demo", "dev.icedtea.demo"))
            .focus
            .is_none());
    }

    #[test]
    fn bootstrap_loads_application_fonts() {
        let bytes: Cow<'static, [u8]> = Cow::Borrowed(&b"\0"[..]);
        let prep = bootstrap(&Boot::new("demo", "dev.demo").fonts([bytes]));
        assert_eq!(prep.iced_settings.fonts.len(), 1);
        assert_eq!(prep.iced_settings.fonts[0].as_ref(), b"\0");
    }

    #[test]
    fn bootstrap_transparent_and_decorations_follow_boot() {
        let app = bootstrap(&Boot::new("App", "dev.x"));
        assert!(!app.window.transparent);
        assert!(app.window.decorations);

        let glass = bootstrap(&Boot::new("App", "dev.x").transparent(true));
        assert!(glass.window.transparent);
        assert!(glass.window.decorations);

        let opaque = bootstrap(&Boot::new("App", "dev.x").transparent(false));
        assert!(!opaque.window.transparent);

        let bare = bootstrap(&Boot::new("App", "dev.x").decorations(false));
        assert!(!bare.window.decorations);
        assert!(!bare.window.transparent);

        let framed = bootstrap(&Boot::new("App", "dev.x").decorations(true));
        assert!(framed.window.decorations);

        let overlay = bootstrap(&Boot::new("p", "dev.x").overlay());
        assert!(!overlay.window.decorations);
        assert!(!overlay.window.transparent);

        let overlay_chrome = bootstrap(&Boot::new("p", "dev.x").overlay().decorations(true));
        assert!(overlay_chrome.window.decorations);

        let overlay_glass = bootstrap(&Boot::new("p", "dev.x").overlay().transparent(true));
        assert!(overlay_glass.window.transparent);
        assert!(!overlay_glass.window.decorations);
    }
}