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