tauri_plugin_system_fonts/
commands.rs

1use fontdb::{Database, Source, Style};
2use serde::Serialize;
3use std::collections::HashSet;
4use tauri::command;
5
6#[derive(Clone, Serialize)]
7#[serde(rename_all = "camelCase")]
8pub struct SystemFont {
9    pub id: String,
10    pub name: String,
11    pub font_name: String,
12    pub path: String,
13    pub weight: u16,
14    pub style: String,
15    pub monospaced: bool,
16}
17
18/// Get all fonts installed on the system.
19///
20/// # Example
21/// ```
22/// use tauri_plugin_system_fonts::get_system_fonts;
23///
24/// let fonts = get_system_fonts().await;
25/// ```
26#[command]
27pub async fn get_system_fonts() -> Vec<SystemFont> {
28    let mut db = Database::new();
29
30    db.load_system_fonts();
31
32    let mut seen = HashSet::new();
33
34    db.faces()
35        .filter_map(|font| match &font.source {
36            Source::File(path) => {
37                let name = font.families[0].0.clone();
38
39                if name.starts_with('.') {
40                    return None;
41                }
42
43                let style = match font.style {
44                    Style::Normal => "normal",
45                    Style::Italic => "italic",
46                    Style::Oblique => "oblique",
47                };
48
49                let font = SystemFont {
50                    id: font.id.to_string(),
51                    name,
52                    font_name: font.post_script_name.clone(),
53                    path: path.to_string_lossy().to_string(),
54                    weight: font.weight.0,
55                    style: style.to_string(),
56                    monospaced: font.monospaced,
57                };
58
59                if seen.insert((font.name.clone(), font.path.clone())) {
60                    Some(font)
61                } else {
62                    None
63                }
64            }
65            Source::Binary(_) => None,
66            Source::SharedFile(..) => None,
67        })
68        .collect()
69}