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
// font-kit/src/sources/fs.rs
//
// Copyright © 2018 The Pathfinder Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A source that loads fonts from a directory or directories on disk.
//!
//! This source uses the WalkDir abstraction from the `walkdir` crate to locate fonts.
//!
//! This is the native source on Android and OpenHarmony.

use std::any::Any;
use std::fs::File;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

#[cfg(not(any(target_os = "android", target_family = "windows", target_env = "ohos")))]
use dirs;
#[cfg(target_family = "windows")]
use std::ffi::OsString;
#[cfg(target_family = "windows")]
use std::os::windows::ffi::OsStringExt;
#[cfg(target_family = "windows")]
use winapi::shared::minwindef::{MAX_PATH, UINT};
#[cfg(target_family = "windows")]
use winapi::um::sysinfoapi;

use crate::error::SelectionError;
use crate::family_handle::FamilyHandle;
use crate::family_name::FamilyName;
use crate::file_type::FileType;
use crate::font::Font;
use crate::handle::Handle;
use crate::properties::Properties;
use crate::source::Source;
use crate::sources::mem::MemSource;

/// A source that loads fonts from a directory or directories on disk.
///
/// This source uses the WalkDir abstraction from the `walkdir` crate to locate fonts.
///
/// This is the native source on Android and OpenHarmony.
#[allow(missing_debug_implementations)]
pub struct FsSource {
    mem_source: MemSource,
}

impl Default for FsSource {
    fn default() -> Self {
        Self::new()
    }
}

impl FsSource {
    /// Opens the default set of directories on this platform and indexes the fonts found within.
    ///
    /// Do not rely on this function for systems other than Android or OpenHarmony. It makes a best
    /// effort to locate fonts in the typical platform directories, but it is too simple to pick up
    /// fonts that are stored in unusual locations but nevertheless properly installed.
    pub fn new() -> FsSource {
        let mut fonts = vec![];
        for font_directory in default_font_directories() {
            fonts.extend(Self::discover_fonts(&font_directory));
        }

        FsSource {
            mem_source: MemSource::from_fonts(fonts.into_iter()).unwrap(),
        }
    }

    fn discover_fonts(path: &Path) -> Vec<Handle> {
        let mut fonts = vec![];
        for directory_entry in WalkDir::new(path).into_iter() {
            let directory_entry = match directory_entry {
                Ok(directory_entry) => directory_entry,
                Err(_) => continue,
            };
            let path = directory_entry.path();
            let mut file = match File::open(path) {
                Err(_) => continue,
                Ok(file) => file,
            };
            match Font::analyze_file(&mut file) {
                Err(_) => continue,
                Ok(FileType::Single) => fonts.push(Handle::from_path(path.to_owned(), 0)),
                Ok(FileType::Collection(font_count)) => {
                    for font_index in 0..font_count {
                        fonts.push(Handle::from_path(path.to_owned(), font_index))
                    }
                }
            }
        }
        fonts
    }

    /// Indexes all fonts found in `path`
    pub fn in_path<P>(path: P) -> FsSource
    where
        P: AsRef<Path>,
    {
        let fonts = Self::discover_fonts(path.as_ref());
        FsSource {
            mem_source: MemSource::from_fonts(fonts.into_iter()).unwrap(),
        }
    }

    /// Returns paths of all fonts installed on the system.
    pub fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> {
        self.mem_source.all_fonts()
    }

    /// Returns the names of all families installed on the system.
    pub fn all_families(&self) -> Result<Vec<String>, SelectionError> {
        self.mem_source.all_families()
    }

    /// Looks up a font family by name and returns the handles of all the fonts in that family.
    pub fn select_family_by_name(&self, family_name: &str) -> Result<FamilyHandle, SelectionError> {
        self.mem_source.select_family_by_name(family_name)
    }

    /// Selects a font by PostScript name, which should be a unique identifier.
    ///
    /// This implementation does a brute-force search of installed fonts to find the one that
    /// matches.
    pub fn select_by_postscript_name(
        &self,
        postscript_name: &str,
    ) -> Result<Handle, SelectionError> {
        self.mem_source.select_by_postscript_name(postscript_name)
    }

    /// Performs font matching according to the CSS Fonts Level 3 specification and returns the
    /// handle.
    #[inline]
    pub fn select_best_match(
        &self,
        family_names: &[FamilyName],
        properties: &Properties,
    ) -> Result<Handle, SelectionError> {
        <Self as Source>::select_best_match(self, family_names, properties)
    }
}

impl Source for FsSource {
    #[inline]
    fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> {
        self.all_fonts()
    }

    #[inline]
    fn all_families(&self) -> Result<Vec<String>, SelectionError> {
        self.all_families()
    }

    fn select_family_by_name(&self, family_name: &str) -> Result<FamilyHandle, SelectionError> {
        self.select_family_by_name(family_name)
    }

    fn select_by_postscript_name(&self, postscript_name: &str) -> Result<Handle, SelectionError> {
        self.select_by_postscript_name(postscript_name)
    }

    #[inline]
    fn as_any(&self) -> &dyn Any {
        self
    }

    #[inline]
    fn as_mut_any(&mut self) -> &mut dyn Any {
        self
    }
}

#[cfg(any(target_os = "android", target_env = "ohos"))]
fn default_font_directories() -> Vec<PathBuf> {
    vec![PathBuf::from("/system/fonts")]
}

#[cfg(target_family = "windows")]
fn default_font_directories() -> Vec<PathBuf> {
    unsafe {
        let mut buffer = vec![0; MAX_PATH];
        let len = sysinfoapi::GetWindowsDirectoryW(buffer.as_mut_ptr(), buffer.len() as UINT);
        assert!(len != 0);
        buffer.truncate(len as usize);

        let mut path = PathBuf::from(OsString::from_wide(&buffer));
        path.push("Fonts");
        vec![path]
    }
}

#[cfg(target_os = "macos")]
fn default_font_directories() -> Vec<PathBuf> {
    let mut directories = vec![
        PathBuf::from("/System/Library/Fonts"),
        PathBuf::from("/Library/Fonts"),
        PathBuf::from("/Network/Library/Fonts"),
    ];
    if let Some(mut path) = dirs::home_dir() {
        path.push("Library");
        path.push("Fonts");
        directories.push(path);
    }
    directories
}

#[cfg(not(any(
    target_os = "android",
    target_family = "windows",
    target_os = "macos",
    target_env = "ohos"
)))]
fn default_font_directories() -> Vec<PathBuf> {
    let mut directories = vec![
        PathBuf::from("/usr/share/fonts"),
        PathBuf::from("/usr/local/share/fonts"),
        PathBuf::from("/var/run/host/usr/share/fonts"), // Flatpak specific
        PathBuf::from("/var/run/host/usr/local/share/fonts"),
    ];
    if let Some(path) = dirs::home_dir() {
        directories.push(path.join(".fonts")); // ~/.fonts is deprecated
        directories.push(path.join("local").join("share").join("fonts")); // Flatpak specific
    }
    if let Some(mut path) = dirs::data_dir() {
        path.push("fonts");
        directories.push(path);
    }
    directories
}