xcursor 0.3.11

A library for loading XCursor themes
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
//! A crate to load cursor themes, and parse XCursor files.

use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};

/// A module implementing XCursor file parsing.
pub mod parser;

/// The on-disk format of a cursor within a theme directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CursorFormat {
    /// Legacy raster cursors, stored as a file in `cursors/<name>`.
    XCursor,
    /// Scalable SVG cursors, stored as a directory in `cursors_scalable/<name>`.
    Scalable,
}

impl CursorFormat {
    /// The theme sub-directory this format lives in.
    fn subdir(self) -> &'static str {
        match self {
            CursorFormat::XCursor => "cursors",
            CursorFormat::Scalable => "cursors_scalable",
        }
    }

    /// Whether an entry of this format is a directory (scalable) or a file (xcursor).
    fn matches(self, path: &Path) -> bool {
        match self {
            CursorFormat::XCursor => path.is_file(),
            CursorFormat::Scalable => path.is_dir(),
        }
    }
}

/// A cursor theme.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CursorTheme {
    theme: CursorThemeIml,
    /// Global search path for themes.
    search_paths: Vec<PathBuf>,
}

impl CursorTheme {
    /// Search for a theme with the given name in the given search paths,
    /// and returns an XCursorTheme which represents it. If no inheritance
    /// can be determined, then the themes inherits from the "default" theme.
    pub fn load(name: &str) -> Self {
        let search_paths = theme_search_paths(SearchPathsEnvironment::get());

        let theme = CursorThemeIml::load(name, &search_paths);

        CursorTheme {
            theme,
            search_paths,
        }
    }

    /// Try to load an icon from the theme.
    /// If the icon is not found within this theme's
    /// directories, then the function looks at the
    /// theme from which this theme is inherited.
    pub fn load_icon(&self, icon_name: &str) -> Option<PathBuf> {
        let mut walked_themes = HashSet::new();

        self.theme
            .load_icon_with_depth(
                icon_name,
                CursorFormat::XCursor,
                &self.search_paths,
                &mut walked_themes,
            )
            .map(|(pathbuf, _)| pathbuf)
    }

    /// Try to load an icon from the theme, returning it with its inheritance
    /// depth.
    ///
    /// If the icon is not found within this theme's directories, then the
    /// function looks at the theme from which this theme is inherited. The
    /// second element of the returned tuple indicates how many levels of
    /// inheritance were traversed before the icon was found.
    pub fn load_icon_with_depth(&self, icon_name: &str) -> Option<(PathBuf, usize)> {
        let mut walked_themes = HashSet::new();

        self.theme.load_icon_with_depth(
            icon_name,
            CursorFormat::XCursor,
            &self.search_paths,
            &mut walked_themes,
        )
    }

    /// Try to load a scalable (SVG) cursor from the theme.
    ///
    /// Returns the path to the cursor's directory within `cursors_scalable`,
    /// which contains a `metadata.json` and one or more SVG files. Theme
    /// inheritance is followed exactly as in [`CursorTheme::load_icon`].
    ///
    /// Reading `metadata.json` and rendering the SVGs is left to the caller
    pub fn load_scalable(&self, icon_name: &str) -> Option<PathBuf> {
        let mut walked_themes = HashSet::new();

        self.theme
            .load_icon_with_depth(
                icon_name,
                CursorFormat::Scalable,
                &self.search_paths,
                &mut walked_themes,
            )
            .map(|(pathbuf, _)| pathbuf)
    }

    /// Like [`CursorTheme::load_scalable`], but also returns the number of
    /// inheritance levels traversed before the cursor was found.
    pub fn load_scalable_with_depth(&self, icon_name: &str) -> Option<(PathBuf, usize)> {
        let mut walked_themes = HashSet::new();

        self.theme.load_icon_with_depth(
            icon_name,
            CursorFormat::Scalable,
            &self.search_paths,
            &mut walked_themes,
        )
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
struct CursorThemeIml {
    /// Theme name.
    name: String,
    /// Directories where the theme is presented and corresponding names of inherited themes.
    /// `None` if theme inherits nothing.
    data: Vec<(PathBuf, Option<String>)>,
}

impl CursorThemeIml {
    /// The implementation of cursor theme loading.
    fn load(name: &str, search_paths: &[PathBuf]) -> Self {
        let mut data = Vec::new();

        // Find directories where this theme is presented.
        for mut path in search_paths.iter().cloned() {
            path.push(name);
            if path.is_dir() {
                let data_dir = path.clone();

                path.push("index.theme");
                let inherits = if let Some(inherits) = theme_inherits(&path) {
                    Some(inherits)
                } else if name != "default" {
                    Some(String::from("default"))
                } else {
                    None
                };

                data.push((data_dir, inherits));
            }
        }

        CursorThemeIml {
            name: name.to_owned(),
            data,
        }
    }

    /// The implementation of cursor icon loading.
    fn load_icon_with_depth(
        &self,
        icon_name: &str,
        format: CursorFormat,
        search_paths: &[PathBuf],
        walked_themes: &mut HashSet<String>,
    ) -> Option<(PathBuf, usize)> {
        for data in &self.data {
            let mut icon_path = data.0.clone();
            icon_path.push(format.subdir());
            icon_path.push(icon_name);
            if format.matches(&icon_path) {
                return Some((icon_path, 0));
            }
        }

        // We've processed all based theme files. Traverse inherited themes, marking this theme
        // as already visited to avoid infinite recursion.
        walked_themes.insert(self.name.clone());

        for data in &self.data {
            // Get inherited theme name, if any.
            let inherits = match data.1.as_ref() {
                Some(inherits) => inherits,
                None => continue,
            };

            // We've walked this theme, avoid rebuilding.
            if walked_themes.contains(inherits) {
                continue;
            }

            let inherited_theme = CursorThemeIml::load(inherits, search_paths);

            match inherited_theme.load_icon_with_depth(
                icon_name,
                format,
                search_paths,
                walked_themes,
            ) {
                Some((icon_path, depth)) => return Some((icon_path, depth + 1)),
                None => continue,
            }
        }

        None
    }
}

#[derive(Default)]
struct SearchPathsEnvironment {
    home: Option<String>,
    xcursor_path: Option<String>,
    xdg_data_home: Option<String>,
    xdg_data_dirs: Option<String>,
}

impl SearchPathsEnvironment {
    fn get() -> Self {
        SearchPathsEnvironment {
            home: env::var("HOME").ok().filter(|x| !x.is_empty()),
            xcursor_path: env::var("XCURSOR_PATH").ok().filter(|x| !x.is_empty()),
            xdg_data_home: env::var("XDG_DATA_HOME").ok().filter(|x| !x.is_empty()),
            xdg_data_dirs: env::var("XDG_DATA_DIRS").ok().filter(|x| !x.is_empty()),
        }
    }
}

/// Get the list of paths where the themes have to be searched, according to the XDG Icon Theme
/// specification. If `XCURSOR_PATH` is set, it will override the default search paths.
fn theme_search_paths(environment: SearchPathsEnvironment) -> Vec<PathBuf> {
    let home_dir = environment
        .home
        .as_ref()
        .map(|home| Path::new(home.as_str()));

    if let Some(xcursor_path) = environment.xcursor_path {
        return xcursor_path
            .split(':')
            .flat_map(|entry| {
                if entry.is_empty() {
                    return None;
                }
                expand_home_dir(PathBuf::from(entry), home_dir)
            })
            .collect();
    }

    // The order is following other XCursor loading libs, like libwayland-cursor.
    let mut paths = Vec::new();

    if let Some(xdg_data_home) = environment.xdg_data_home {
        paths.extend(expand_home_dir(PathBuf::from(xdg_data_home), home_dir));
    } else if let Some(home_dir) = home_dir {
        paths.push(home_dir.join(".local/share/icons"))
    }

    if let Some(home_dir) = home_dir {
        paths.push(home_dir.join(".icons"));
    }

    if let Some(xdg_data_dirs) = environment.xdg_data_dirs {
        paths.extend(xdg_data_dirs.split(':').flat_map(|entry| {
            if entry.is_empty() {
                return None;
            }
            let mut entry = expand_home_dir(PathBuf::from(entry), home_dir)?;
            entry.push("icons");
            Some(entry)
        }))
    } else {
        paths.push(PathBuf::from("/usr/local/share/icons"));
        paths.push(PathBuf::from("/usr/share/icons"));
    }

    paths.push(PathBuf::from("/usr/share/pixmaps"));

    if let Some(home_dir) = home_dir {
        paths.push(home_dir.join(".cursors"));
    }

    paths.push(PathBuf::from("/usr/share/cursors/xorg-x11"));

    paths
}

/// If the first component of the path is `~`, replaces it with the home dir. If no home dir is
/// present, returns `None`.
fn expand_home_dir(path: PathBuf, home_dir: Option<&Path>) -> Option<PathBuf> {
    let mut components = path.iter();
    if let Some(first_component) = components.next() {
        if first_component == "~" {
            if let Some(home_dir) = home_dir {
                let mut path = home_dir.to_path_buf();
                for component in components {
                    path.push(component);
                }
                return Some(path);
            } else {
                return None;
            }
        }
    }
    Some(path)
}

/// Load the specified index.theme file, and returns a `Some` with
/// the value of the `Inherits` key in it.
/// Returns `None` if the file cannot be read for any reason,
/// if the file cannot be parsed, or if the `Inherits` key is omitted.
fn theme_inherits(file_path: &Path) -> Option<String> {
    let content = std::fs::read_to_string(file_path).ok()?;

    parse_theme(&content)
}

/// Parse the content of the `index.theme` and return the `Inherits` value.
fn parse_theme(content: &str) -> Option<String> {
    const PATTERN: &str = "Inherits";

    let is_xcursor_space_or_separator =
        |&ch: &char| -> bool { ch.is_whitespace() || ch == ';' || ch == ',' };

    for line in content.lines() {
        // Line should start with `Inherits`, otherwise go to the next line.
        if !line.starts_with(PATTERN) {
            continue;
        }

        // Skip the `Inherits` part and trim the leading white spaces.
        let mut chars = line.get(PATTERN.len()..).unwrap().trim_start().chars();

        // If the next character after leading white spaces isn't `=` go the next line.
        if Some('=') != chars.next() {
            continue;
        }

        // Skip XCursor spaces/separators.
        let result: String = chars
            .skip_while(is_xcursor_space_or_separator)
            .take_while(|ch| !is_xcursor_space_or_separator(ch))
            .collect();

        if !result.is_empty() {
            return Some(result);
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::{Path, PathBuf};

    #[test]
    fn test_parse_theme() {
        let theme_name = String::from("XCURSOR_RS");

        let theme = format!("Inherits={}", theme_name.clone());

        assert_eq!(parse_theme(&theme), Some(theme_name.clone()));

        let theme = format!(" Inherits={}", theme_name.clone());

        assert_eq!(parse_theme(&theme), None);

        let theme = format!(
            "[THEME name]\nInherits   = ,;\t\t{};;;;Tail\n\n",
            theme_name.clone()
        );

        assert_eq!(parse_theme(&theme), Some(theme_name.clone()));

        let theme = format!("Inherits;=;{}", theme_name.clone());

        assert_eq!(parse_theme(&theme), None);

        let theme = format!("Inherits = {}\n\nInherits=OtherTheme", theme_name.clone());

        assert_eq!(parse_theme(&theme), Some(theme_name.clone()));

        let theme = format!(
            "Inherits = ;;\nSome\tgarbage\nInherits={}",
            theme_name.clone()
        );

        assert_eq!(parse_theme(&theme), Some(theme_name.clone()));
    }

    #[test]
    fn test_expand_home_dir() {
        let home = Path::new("/home/user");

        let result = expand_home_dir("~".into(), Some(home));
        assert_eq!(result, Some("/home/user".into()));

        let result = expand_home_dir("~/.icons".into(), Some(home));
        assert_eq!(result, Some("/home/user/.icons".into()));

        let result = expand_home_dir("~/.local/share/icons".into(), Some(home));
        assert_eq!(result, Some("/home/user/.local/share/icons".into()));

        let result = expand_home_dir("~/.icons".into(), None);
        assert_eq!(result, None);

        let path: PathBuf = "/usr/share/icons".into();
        let result = expand_home_dir(path.clone(), Some(home));
        assert_eq!(result, Some(path));

        let path: PathBuf = "".into();
        let result = expand_home_dir(path.clone(), Some(home));
        assert_eq!(result, Some(path));

        // ~ in the middle of path should not expand
        let path: PathBuf = "/some/path/~/icons".into();
        let result = expand_home_dir(path.clone(), Some(home));
        assert_eq!(result, Some(path));
    }

    #[test]
    fn test_theme_search_paths() {
        assert_eq!(
            theme_search_paths(SearchPathsEnvironment {
                home: Some("/home/user".to_string()),
                xdg_data_home: Some("/home/user/.data".to_string()),
                xdg_data_dirs: Some("/opt/share::/usr/local/share:~/custom/share".to_string()),
                ..Default::default()
            }),
            vec![
                PathBuf::from("/home/user/.data"),
                PathBuf::from("/home/user/.icons"),
                PathBuf::from("/opt/share/icons"),
                PathBuf::from("/usr/local/share/icons"),
                PathBuf::from("/home/user/custom/share/icons"),
                PathBuf::from("/usr/share/pixmaps"),
                PathBuf::from("/home/user/.cursors"),
                PathBuf::from("/usr/share/cursors/xorg-x11"),
            ]
        );

        // XCURSOR_PATH overrides all other paths
        assert_eq!(
            theme_search_paths(SearchPathsEnvironment {
                home: Some("/home/user".to_string()),
                xcursor_path: Some("~/custom/xcursor/icons:/absolute-path/icons".to_string()),
                ..Default::default()
            }),
            vec![
                PathBuf::from("/home/user/custom/xcursor/icons"),
                PathBuf::from("/absolute-path/icons")
            ]
        );

        // no home causes tilde paths to be omitted
        assert_eq!(
            theme_search_paths(SearchPathsEnvironment {
                xdg_data_home: Some("~/.data".to_string()),
                ..Default::default()
            }),
            vec![
                PathBuf::from("/usr/local/share/icons"),
                PathBuf::from("/usr/share/icons"),
                PathBuf::from("/usr/share/pixmaps"),
                PathBuf::from("/usr/share/cursors/xorg-x11"),
            ]
        );
    }
}