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