1use std::{path::Path, str, sync::Arc};
2
3use collections::HashMap;
4
5use gpui::{AppContext, AssetSource};
6use serde_derive::Deserialize;
7use util::{iife, 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) -> Arc<str> {
45 iife!({
46 let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
47
48 // FIXME: Associate a type with the languages and have the file's langauge
49 // override these associations
50 iife!({
51 let suffix = path.icon_suffix()?;
52
53 this.suffixes
54 .get(suffix)
55 .and_then(|type_str| this.types.get(type_str))
56 .map(|type_config| type_config.icon.clone())
57 })
58 .or_else(|| this.types.get("default").map(|config| config.icon.clone()))
59 })
60 .unwrap_or_else(|| Arc::from("".to_string()))
61 }
62
63 pub fn get_folder_icon(expanded: bool, cx: &AppContext) -> Arc<str> {
64 iife!({
65 let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
66
67 let key = if expanded {
68 EXPANDED_DIRECTORY_TYPE
69 } else {
70 COLLAPSED_DIRECTORY_TYPE
71 };
72
73 this.types
74 .get(key)
75 .map(|type_config| type_config.icon.clone())
76 })
77 .unwrap_or_else(|| Arc::from("".to_string()))
78 }
79
80 pub fn get_chevron_icon(expanded: bool, cx: &AppContext) -> Arc<str> {
81 iife!({
82 let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
83
84 let key = if expanded {
85 EXPANDED_CHEVRON_TYPE
86 } else {
87 COLLAPSED_CHEVRON_TYPE
88 };
89
90 this.types
91 .get(key)
92 .map(|type_config| type_config.icon.clone())
93 })
94 .unwrap_or_else(|| Arc::from("".to_string()))
95 }
96}