file_associations.rs

 1use std::{path::Path, str, sync::Arc};
 2
 3use collections::HashMap;
 4
 5use gpui::{AppContext, AssetSource, Global};
 6use serde_derive::Deserialize;
 7use util::{maybe, paths::PathExt};
 8
 9#[derive(Deserialize, Debug)]
10struct TypeConfig {
11    icon: Arc<str>,
12}
13
14#[derive(Deserialize, Debug)]
15pub struct FileAssociations {
16    suffixes: HashMap<String, String>,
17    types: HashMap<String, TypeConfig>,
18}
19
20impl Global for FileAssociations {}
21
22const COLLAPSED_DIRECTORY_TYPE: &'static str = "collapsed_folder";
23const EXPANDED_DIRECTORY_TYPE: &'static str = "expanded_folder";
24const COLLAPSED_CHEVRON_TYPE: &'static str = "collapsed_chevron";
25const EXPANDED_CHEVRON_TYPE: &'static str = "expanded_chevron";
26pub const FILE_TYPES_ASSET: &'static str = "icons/file_icons/file_types.json";
27
28pub fn init(assets: impl AssetSource, cx: &mut AppContext) {
29    cx.set_global(FileAssociations::new(assets))
30}
31
32impl FileAssociations {
33    pub fn new(assets: impl AssetSource) -> Self {
34        assets
35            .load("icons/file_icons/file_types.json")
36            .and_then(|file| {
37                serde_json::from_str::<FileAssociations>(str::from_utf8(&file).unwrap())
38                    .map_err(Into::into)
39            })
40            .unwrap_or_else(|_| FileAssociations {
41                suffixes: HashMap::default(),
42                types: HashMap::default(),
43            })
44    }
45
46    pub fn get_icon(path: &Path, cx: &AppContext) -> Option<Arc<str>> {
47        let this = cx.try_global::<Self>()?;
48
49        // FIXME: Associate a type with the languages and have the file's language
50        //        override these associations
51        maybe!({
52            let suffix = path.icon_suffix()?;
53
54            this.suffixes
55                .get(suffix)
56                .and_then(|type_str| this.types.get(type_str))
57                .map(|type_config| type_config.icon.clone())
58        })
59        .or_else(|| this.types.get("default").map(|config| config.icon.clone()))
60    }
61
62    pub fn get_folder_icon(expanded: bool, cx: &AppContext) -> Option<Arc<str>> {
63        let this = cx.try_global::<Self>()?;
64
65        let key = if expanded {
66            EXPANDED_DIRECTORY_TYPE
67        } else {
68            COLLAPSED_DIRECTORY_TYPE
69        };
70
71        this.types
72            .get(key)
73            .map(|type_config| type_config.icon.clone())
74    }
75
76    pub fn get_chevron_icon(expanded: bool, cx: &AppContext) -> Option<Arc<str>> {
77        let this = cx.try_global::<Self>()?;
78
79        let key = if expanded {
80            EXPANDED_CHEVRON_TYPE
81        } else {
82            COLLAPSED_CHEVRON_TYPE
83        };
84
85        this.types
86            .get(key)
87            .map(|type_config| type_config.icon.clone())
88    }
89}