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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Type scale. UI is the platform sans; code is the platform mono.
//!
//! icedtea does not ship a font file. Applications that want a named
//! family load it on the iced application themselves.
//!
//! iced + cosmic-text map `Font::DEFAULT` / `Font::MONOSPACE` to generic
//! families that default to names which may not exist on the machine
//! (and which Linux usually rewrites via fontconfig). Call
//! [`install_platform_faces`] before the first frame (done by [`crate::run!`]
//! and [`crate::daemon!`]) so SansSerif and Monospace resolve to faces
//! that are actually installed and, for UI, support normal and bold.

use std::collections::BTreeMap;
use std::sync::OnceLock;

use iced::advanced::graphics::text::cosmic_text::fontdb::{self, Family as DbFamily};
use iced::advanced::graphics::text::font_system;
use iced::font::{Style, Weight};
use iced::Font;

use crate::host_font;

/// Platform sans (`Family::SansSerif`).
pub const UI: Font = Font::DEFAULT;

/// Titles and selected labels.
pub const UI_BOLD: Font = Font {
    weight: Weight::Bold,
    ..Font::DEFAULT
};

/// Dim / thought prose.
pub const UI_ITALIC: Font = Font {
    style: Style::Italic,
    ..Font::DEFAULT
};

/// Platform monospace — ids, paths, code.
pub const MONO: Font = Font::MONOSPACE;

// App-facing type steps map 1:1 onto Material Design 3 roles
// (see [`crate::m3::TypeRole`]). Sizes are the M3 scale in dp.

/// Large reading — M3 Display Small (36).
pub const DISPLAY: u32 = 36;
/// Page title — M3 Title Large (22).
pub const PAGE: u32 = 22;
/// Section / card title — M3 Title Medium (16).
pub const TITLE: u32 = 16;
/// Body copy — M3 Body Medium (14).
pub const BODY: u32 = 14;
/// Meta, tabs, footer, keys — M3 Label Medium (12).
pub const META: u32 = 12;
/// Code / monospace — M3 Body Small (12).
pub const CODE: u32 = 12;

/// Platform sans or mono for a body that paints as text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontFace {
    Ui,
    Mono,
}

impl FontFace {
    /// Font for this face.
    pub fn font(self) -> Font {
        match self {
            Self::Ui => UI,
            Self::Mono => MONO,
        }
    }
}

/// Named step on the type scale (maps onto [`crate::m3::TypeRole`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeRole {
    Display,
    Page,
    Title,
    Body,
    Meta,
    Code,
}

impl TypeRole {
    /// Matching Material Design 3 type role.
    pub fn m3(self) -> crate::m3::TypeRole {
        match self {
            Self::Display => crate::m3::TypeRole::DisplaySmall,
            Self::Page => crate::m3::TypeRole::TitleLarge,
            Self::Title => crate::m3::TypeRole::TitleMedium,
            Self::Body => crate::m3::TypeRole::BodyMedium,
            Self::Meta => crate::m3::TypeRole::LabelMedium,
            Self::Code => crate::m3::TypeRole::BodySmall,
        }
    }

    /// Pixel size for this role (M3 scale).
    ///
    /// ```
    /// assert_eq!(icedtea::typo::TypeRole::Body.size(), 14);
    /// assert_eq!(
    ///     icedtea::typo::TypeRole::Body.size() as f32,
    ///     icedtea::m3::TypeRole::BodyMedium.scale().size
    /// );
    /// ```
    pub fn size(self) -> u32 {
        self.m3().scale().size as u32
    }

    pub fn font(self) -> Font {
        match self {
            Self::Code => MONO,
            Self::Display | Self::Title | Self::Page => UI_BOLD,
            Self::Body | Self::Meta => UI,
        }
    }
}

/// Point iced's generic SansSerif and Monospace at real installed faces.
///
/// Safe to call more than once. [`crate::run!`] and [`crate::daemon!`] call
/// this before the event loop. Call it yourself only if you start iced
/// without those macros.
///
/// Selection order: host preference list (Core Text on macOS, non-client
/// metrics on Windows; empty on Linux where fontconfig already rewrote
/// the generics), then the database's current generic mapping, then any
/// usable family already loaded. UI requires a normal face and a bold
/// face at weight 700 so `UI_BOLD` does not fall through to monospaced
/// cascade entries.
pub fn install_platform_faces() {
    static ONCE: OnceLock<()> = OnceLock::new();
    ONCE.get_or_init(|| {
        let lock = font_system();
        let mut system = lock.write().expect("font system");
        let db = system.raw().db_mut();
        let covers = faces_from_db(db);
        let sans_current = db.family_name(&DbFamily::SansSerif).to_string();
        let mono_current = db.family_name(&DbFamily::Monospace).to_string();
        let sans = select_family(
            &covers,
            FamilyKind::Ui,
            &host_font::ui_preferences(),
            &sans_current,
        );
        let mono = select_family(
            &covers,
            FamilyKind::Mono,
            &host_font::mono_preferences(),
            &mono_current,
        );
        db.set_sans_serif_family(sans);
        db.set_monospace_family(mono);
    });
}

/// Current SansSerif family name in the font database.
pub fn sans_family() -> String {
    let lock = font_system();
    let mut system = lock.write().expect("font system");
    system
        .raw()
        .db()
        .family_name(&DbFamily::SansSerif)
        .to_string()
}

/// Point [`UI`] / `Font::DEFAULT` at a family already in the database.
///
/// Load the face on the iced application ([`crate::Boot::fonts`] or
/// `font::load`) first. Empty `name` is ignored. Call again to switch.
///
/// ```
/// icedtea::typo::bind_sans_family("Noto Sans");
/// assert!(!icedtea::typo::sans_family().is_empty());
/// ```
pub fn bind_sans_family(name: impl AsRef<str>) {
    let name = name.as_ref();
    if name.is_empty() {
        return;
    }
    let lock = font_system();
    let mut system = lock.write().expect("font system");
    system.raw().db_mut().set_sans_serif_family(name);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FamilyKind {
    Ui,
    Mono,
}

#[derive(Debug, Clone)]
struct FaceCover {
    families: Vec<String>,
    monospaced: bool,
    weight: u16,
    post_script_name: String,
}

fn faces_from_db(db: &fontdb::Database) -> Vec<FaceCover> {
    db.faces()
        .map(|face| FaceCover {
            families: face.families.iter().map(|(n, _)| n.clone()).collect(),
            monospaced: face.monospaced,
            weight: face.weight.0,
            post_script_name: face.post_script_name.clone(),
        })
        .collect()
}

/// One English primary name per family, with coverage of installed faces.
fn family_index(faces: &[FaceCover]) -> BTreeMap<String, FamilyCoverage> {
    let mut map: BTreeMap<String, FamilyCoverage> = BTreeMap::new();
    for face in faces {
        if face.post_script_name.contains("Emoji") {
            continue;
        }
        // Prefer the first listed name (English US in fontdb).
        let Some(primary) = face.families.first() else {
            continue;
        };
        let entry = map.entry(primary.clone()).or_default();
        entry.monospaced |= face.monospaced;
        if face.weight == 400 {
            entry.has_normal = true;
        }
        if face.weight == 700 {
            entry.has_bold = true;
        }
        // Also index alternate family names so OS preferences that use
        // another language or alias still match this face set.
        for alt in &face.families {
            if alt == primary {
                continue;
            }
            let alt_entry = map.entry(alt.clone()).or_default();
            alt_entry.monospaced |= face.monospaced;
            if face.weight == 400 {
                alt_entry.has_normal = true;
            }
            if face.weight == 700 {
                alt_entry.has_bold = true;
            }
            alt_entry.canonical = Some(primary.clone());
        }
    }
    map
}

#[derive(Debug, Clone, Default)]
struct FamilyCoverage {
    monospaced: bool,
    has_normal: bool,
    has_bold: bool,
    /// When this key is an alias, the primary English family name to bind.
    canonical: Option<String>,
}

impl FamilyCoverage {
    fn usable(&self, kind: FamilyKind) -> bool {
        match kind {
            FamilyKind::Ui => !self.monospaced && self.has_normal && self.has_bold,
            FamilyKind::Mono => self.monospaced && self.has_normal,
        }
    }

    fn bind_name<'a>(&'a self, key: &'a str) -> &'a str {
        self.canonical.as_deref().unwrap_or(key)
    }
}

fn select_family(
    faces: &[FaceCover],
    kind: FamilyKind,
    preferences: &[String],
    current: &str,
) -> String {
    let index = family_index(faces);
    let mut tried = Vec::new();

    let mut consider = |name: &str| -> Option<String> {
        if name.is_empty() || tried.iter().any(|t| t == name) {
            return None;
        }
        tried.push(name.to_string());
        let cover = index.get(name)?;
        if cover.usable(kind) {
            Some(cover.bind_name(name).to_string())
        } else {
            None
        }
    };

    for pref in preferences {
        if let Some(name) = consider(pref) {
            return name;
        }
    }
    if let Some(name) = consider(current) {
        return name;
    }
    // Stable scan of everything loaded: first usable by primary name order.
    for (name, cover) in &index {
        if cover.canonical.is_some() {
            // Alias row; primary is listed separately.
            continue;
        }
        if cover.usable(kind) {
            return name.clone();
        }
    }
    // Last resort: keep the database's current mapping.
    current.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    static FONT_DB: Mutex<()> = Mutex::new(());

    fn cover(family: &str, mono: bool, weight: u16) -> FaceCover {
        FaceCover {
            families: vec![family.into()],
            monospaced: mono,
            weight,
            post_script_name: format!("{family}-{weight}"),
        }
    }

    fn cover_alias(primary: &str, alias: &str, mono: bool, weight: u16) -> FaceCover {
        FaceCover {
            families: vec![primary.into(), alias.into()],
            monospaced: mono,
            weight,
            post_script_name: format!("{primary}-{weight}"),
        }
    }

    #[test]
    fn scale_is_ordered() {
        assert!(TypeRole::Display.size() > TypeRole::Page.size());
        assert!(TypeRole::Page.size() > TypeRole::Title.size());
        assert!(TypeRole::Title.size() > TypeRole::Body.size());
        assert!(TypeRole::Body.size() > TypeRole::Meta.size());
        assert!(TypeRole::Code.size() >= TypeRole::Meta.size());
        assert_eq!(UI, Font::DEFAULT);
        assert_eq!(MONO, Font::MONOSPACE);
        assert_eq!(TypeRole::Display.size(), DISPLAY);
        assert_eq!(TypeRole::Display.font(), UI_BOLD);
        // Constants track M3 scale (not forced onto the 4dp layout grid).
        for role in [
            TypeRole::Display,
            TypeRole::Page,
            TypeRole::Title,
            TypeRole::Body,
            TypeRole::Meta,
            TypeRole::Code,
        ] {
            assert_eq!(role.size() as f32, role.m3().scale().size);
        }
        assert_eq!(TypeRole::Page.size(), PAGE);
        assert_eq!(TypeRole::Title.size(), TITLE);
        assert_eq!(TypeRole::Body.size(), BODY);
        assert_eq!(TypeRole::Meta.size(), META);
        assert_eq!(TypeRole::Code.size(), CODE);
        assert_eq!(TypeRole::Code.font(), MONO);
        assert_eq!(TypeRole::Title.font(), UI_BOLD);
        assert_eq!(TypeRole::Page.font(), UI_BOLD);
        assert_eq!(TypeRole::Body.font(), UI);
        assert_eq!(TypeRole::Meta.font(), UI);
        assert_eq!(FontFace::Ui.font(), UI);
        assert_eq!(FontFace::Mono.font(), MONO);
        let _ = UI_ITALIC;
    }

    #[test]
    fn bind_sans_family_sets_the_named_face() {
        let _g = FONT_DB.lock().expect("font db");
        bind_sans_family("");
        assert!(!sans_family().is_empty());
        bind_sans_family("Noto Sans");
        assert_eq!(sans_family(), "Noto Sans");
    }

    #[test]
    fn prefers_os_list_when_family_has_normal_and_bold() {
        let faces = vec![
            cover("Missing", false, 400),
            cover("GoodSans", false, 400),
            cover("GoodSans", false, 700),
            cover("Other", false, 400),
            cover("Other", false, 700),
            cover("MonoA", true, 400),
        ];
        let name = select_family(
            &faces,
            FamilyKind::Ui,
            &["NoSuch".into(), "GoodSans".into()],
            "Missing",
        );
        assert_eq!(name, "GoodSans");
    }

    #[test]
    fn rejects_ui_family_without_bold_weight() {
        // System Font style: regular only — bold would cascade to mono.
        let faces = vec![
            cover("SystemOnly", false, 400),
            cover("HasBold", false, 400),
            cover("HasBold", false, 700),
        ];
        let name = select_family(&faces, FamilyKind::Ui, &["SystemOnly".into()], "SystemOnly");
        assert_eq!(name, "HasBold");
    }

    #[test]
    fn keeps_current_when_already_usable() {
        let faces = vec![
            cover("Current", false, 400),
            cover("Current", false, 700),
            cover("Other", false, 400),
            cover("Other", false, 700),
        ];
        let name = select_family(&faces, FamilyKind::Ui, &[], "Current");
        assert_eq!(name, "Current");
    }

    #[test]
    fn mono_needs_monospaced_normal_only() {
        let faces = vec![
            cover("Prop", false, 400),
            cover("Prop", false, 700),
            cover("Code", true, 400),
        ];
        let name = select_family(&faces, FamilyKind::Mono, &["Prop".into()], "MissingMono");
        assert_eq!(name, "Code");
    }

    #[test]
    fn resolves_alias_to_primary_family_name() {
        let faces = vec![
            cover_alias("System Font", ".SF NS", false, 400),
            cover("RealSans", false, 400),
            cover("RealSans", false, 700),
        ];
        // Alias preference without bold fails; RealSans wins.
        let name = select_family(&faces, FamilyKind::Ui, &[".SF NS".into()], "System Font");
        assert_eq!(name, "RealSans");
    }

    #[test]
    fn bold_alias_counts_toward_ui_family() {
        let faces = vec![
            cover_alias("System Font", ".SF NS", false, 400),
            cover_alias("System Font", ".SF NS", false, 700),
        ];
        let name = select_family(&faces, FamilyKind::Ui, &[".SF NS".into()], "other");
        assert_eq!(name, "System Font");
    }

    #[test]
    fn last_resort_keeps_current_when_nothing_usable() {
        let faces = vec![cover("Thin", false, 400)];
        let name = select_family(&faces, FamilyKind::Ui, &[], "Thin");
        assert_eq!(name, "Thin");
    }

    #[test]
    fn family_index_skips_emoji_and_empty_name_lists() {
        let faces = vec![
            FaceCover {
                families: vec![],
                monospaced: false,
                weight: 400,
                post_script_name: "Empty-400".into(),
            },
            FaceCover {
                families: vec!["EmojiOne".into()],
                monospaced: false,
                weight: 400,
                post_script_name: "EmojiOneColor".into(),
            },
            cover("Keep", false, 400),
            cover("Keep", false, 700),
        ];
        let idx = family_index(&faces);
        assert!(!idx.contains_key("EmojiOne"));
        assert!(idx.contains_key("Keep"));
        assert_eq!(
            select_family(&faces, FamilyKind::Ui, &["Keep".into()], "x"),
            "Keep"
        );
    }

    #[test]
    fn consider_skips_empty_and_duplicate_preferences() {
        let faces = vec![
            cover("A", false, 400),
            cover("A", false, 700),
            cover("B", false, 400),
            cover("B", false, 700),
        ];
        // Empty pref entries are ignored; the same name is not tried twice.
        let name = select_family(
            &faces,
            FamilyKind::Ui,
            &["".into(), "A".into(), "A".into(), "B".into()],
            "B",
        );
        assert_eq!(name, "A");
    }

    #[test]
    fn install_binds_usable_ui_and_mono_families() {
        let _g = FONT_DB.lock().expect("font db");
        install_platform_faces();
        let lock = font_system();
        let mut system = lock.write().expect("font system");
        let db = system.raw().db();
        let sans_name = db.family_name(&DbFamily::SansSerif).to_string();
        let mono_name = db.family_name(&DbFamily::Monospace).to_string();
        assert!(!sans_name.is_empty());
        assert!(!mono_name.is_empty());
        let normal = fontdb::Query {
            families: &[DbFamily::SansSerif],
            weight: fontdb::Weight::NORMAL,
            stretch: fontdb::Stretch::Normal,
            style: fontdb::Style::Normal,
        };
        let bold = fontdb::Query {
            families: &[DbFamily::SansSerif],
            weight: fontdb::Weight::BOLD,
            stretch: fontdb::Stretch::Normal,
            style: fontdb::Style::Normal,
        };
        let mono = fontdb::Query {
            families: &[DbFamily::Monospace],
            weight: fontdb::Weight::NORMAL,
            stretch: fontdb::Stretch::Normal,
            style: fontdb::Style::Normal,
        };
        let normal_id = db.query(&normal).expect("sans normal face");
        let bold_id = db.query(&bold).expect("sans bold face");
        let mono_id = db.query(&mono).expect("mono face");
        let normal_face = db.face(normal_id).expect("normal face info");
        let bold_face = db.face(bold_id).expect("bold face info");
        let mono_face = db.face(mono_id).expect("mono face info");
        assert!(!normal_face.monospaced);
        assert!(!bold_face.monospaced);
        assert!(mono_face.monospaced);
        assert_eq!(bold_face.weight.0, 700);
    }
}