1use crate::config::{IconConfig, IconPattern, IconPatternKind};
3use crate::file_entry::FileEntry;
4use crate::filter::matches_pattern;
5use std::collections::HashMap;
6use std::ffi::OsStr;
7use std::os::unix::fs::MetadataExt;
8use std::path::PathBuf;
9use std::sync::OnceLock;
10
11impl IconPattern {
12 pub(crate) fn matches(&self, entry: &FileEntry) -> bool {
13 if (self.pattern.ends_with('/') && !entry.is_dir)
14 || matches!(self.kind, IconPatternKind::Directory) && !entry.is_dir
15 || matches!(self.kind, IconPatternKind::File) && entry.is_dir
16 {
17 return false;
18 }
19 let pattern = self
20 .pattern
21 .strip_suffix('/')
22 .filter(|pattern| !pattern.is_empty())
23 .unwrap_or(&self.pattern);
24 let target = if pattern.contains('/') {
25 entry.full_path.as_os_str()
26 } else {
27 entry
28 .full_path
29 .file_name()
30 .unwrap_or(entry.full_path.as_os_str())
31 };
32 matches_pattern(pattern, &target.to_string_lossy())
33 }
34}
35
36fn with_lowercase<R>(name: &OsStr, f: impl FnOnce(&str) -> Option<R>) -> Option<R> {
38 let name = name.to_str()?;
39 let mut buffer = [0u8; 64];
40 match buffer.get_mut(..name.len()) {
41 Some(lowercase) => {
42 lowercase.copy_from_slice(name.as_bytes());
43 lowercase.make_ascii_lowercase();
44 f(std::str::from_utf8(lowercase).ok()?)
46 }
47 None => f(&name.to_ascii_lowercase()),
48 }
49}
50
51pub(crate) fn file_name_icon(name: &OsStr) -> Option<&'static str> {
52 with_lowercase(name, lowercase_file_name_icon)
53}
54
55fn lowercase_file_name_icon(name: &str) -> Option<&'static str> {
56 let stem = name.split(['.', '-', '_']).next()?;
57 let named_icon = match stem {
58 "license" | "licence" | "copying" | "copyright" => Some("\u{e60a}"),
59 "readme" | "changelog" | "contributing" | "authors" => Some("\u{f02d}"),
60 "makefile" | "gnumakefile" | "bsdmakefile" => Some("\u{e673}"),
61 "dockerfile" | "containerfile" => Some("\u{e650}"),
62 _ => None,
63 };
64 if named_icon.is_some() {
65 return named_icon;
66 }
67 match name {
68 "cargo.toml" => return Some("\u{e68b}"),
69 "package.json" => return Some("\u{e616}"),
70 "pyproject.toml" | "pipfile" => return Some("\u{e606}"),
71 "go.mod" => return Some("\u{e627}"),
72 "gemfile" => return Some("\u{e605}"),
73 "composer.json" => return Some("\u{e608}"),
74 "package-lock.json" | "pnpm-lock.yaml" | "go.sum" | "bun.lockb" => return Some("\u{e672}"),
75 "compose.yml"
76 | "compose.yaml"
77 | "docker-compose.yml"
78 | "docker-compose.yaml"
79 | ".dockerignore" => return Some("\u{e650}"),
80 ".gitignore" | ".gitattributes" | ".gitmodules" | ".gitkeep" => return Some("\u{e702}"),
81 ".editorconfig" | ".npmrc" | ".prettierrc" | ".eslintrc" => return Some("\u{e615}"),
82 ".bashrc" | ".zshrc" | ".profile" | ".bash_profile" | ".zprofile" | ".envrc" => {
83 return Some("\u{e691}");
84 }
85 _ => {}
86 }
87 if name == ".env" || name.starts_with(".env.") {
88 return Some("\u{e615}");
89 }
90 Some(match name.rsplit_once('.')?.1 {
91 "rs" => "\u{e68b}",
92 "py" | "pyi" | "pyw" => "\u{e606}",
93 "js" | "mjs" | "cjs" => "\u{e60c}",
94 "ts" | "mts" | "cts" => "\u{e628}",
95 "jsx" | "tsx" => "\u{e625}",
96 "go" => "\u{e627}",
97 "c" | "h" => "\u{e61e}",
98 "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" => "\u{e646}",
99 "java" => "\u{e66d}",
100 "rb" => "\u{e605}",
101 "php" => "\u{e608}",
102 "lua" => "\u{e620}",
103 "swift" => "\u{e699}",
104 "kt" | "kts" => "\u{e634}",
105 "sh" | "bash" | "zsh" | "fish" => "\u{e691}",
106 "ps1" => "\u{e683}",
107 "html" | "htm" => "\u{e60e}",
108 "css" => "\u{e614}",
109 "scss" | "sass" => "\u{e603}",
110 "json" | "jsonc" | "json5" => "\u{e60b}",
111 "toml" | "yaml" | "yml" | "ini" | "conf" | "cfg" => "\u{e615}",
112 "xml" => "\u{f121}",
113 "lock" => "\u{e672}",
114 "md" | "markdown" | "mdx" => "\u{e609}",
115 "txt" | "log" | "rst" => "\u{e64e}",
116 "pdf" => "\u{e67d}",
117 "doc" | "docx" | "odt" | "rtf" => "\u{f1c2}",
118 "csv" | "tsv" | "xls" | "xlsx" | "ods" => "\u{e64a}",
119 "ppt" | "pptx" | "odp" => "\u{f1c4}",
120 "epub" | "mobi" => "\u{f02d}",
121 "svg" => "\u{e698}",
122 "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "heic" | "bmp" | "ico" | "tif"
123 | "tiff" => "\u{e60d}",
124 "mp3" | "wav" | "flac" | "ogg" | "opus" | "m4a" | "aiff" => "\u{f1c7}",
125 "mp4" | "mkv" | "mov" | "avi" | "webm" | "m4v" | "mpg" | "mpeg" => "\u{f1c8}",
126 "zip" | "tar" | "gz" | "tgz" | "bz2" | "xz" | "7z" | "rar" | "zst" => "\u{f1c6}",
127 "sql" | "db" | "sqlite" | "sqlite3" => "\u{e64d}",
128 "ttf" | "otf" | "woff" | "woff2" => "\u{e659}",
129 _ => return None,
130 })
131}
132
133pub(crate) fn file_category(name: &OsStr) -> Option<&'static str> {
134 with_lowercase(name, lowercase_file_category)
135}
136
137fn lowercase_file_category(name: &str) -> Option<&'static str> {
138 let stem = name.split(['.', '-', '_']).next()?;
139
140 match stem {
141 "license" | "licence" | "copying" | "copyright" | "readme" | "changelog"
142 | "contributing" | "authors" => return Some("file_type.document"),
143 "makefile" | "gnumakefile" | "bsdmakefile" | "dockerfile" | "containerfile" => {
144 return Some("file_type.build");
145 }
146 _ => {}
147 }
148
149 match name {
150 "cargo.toml"
151 | "cargo.lock"
152 | "package.json"
153 | "package-lock.json"
154 | "pnpm-lock.yaml"
155 | "yarn.lock"
156 | "bun.lockb"
157 | "pyproject.toml"
158 | "pipfile"
159 | "pipfile.lock"
160 | "poetry.lock"
161 | "go.mod"
162 | "go.sum"
163 | "gemfile"
164 | "gemfile.lock"
165 | "composer.json"
166 | "composer.lock"
167 | "compose.yml"
168 | "compose.yaml"
169 | "docker-compose.yml"
170 | "docker-compose.yaml" => return Some("file_type.build"),
171 ".gitignore" | ".gitattributes" | ".gitmodules" | ".gitkeep" | ".dockerignore"
172 | ".editorconfig" | ".npmrc" | ".prettierrc" | ".eslintrc" | ".bashrc" | ".zshrc"
173 | ".profile" | ".bash_profile" | ".zprofile" | ".envrc" => return Some("file_type.config"),
174 _ => {}
175 }
176
177 if name == ".env" || name.starts_with(".env.") {
178 return Some("file_type.config");
179 }
180 if name.ends_with('~') {
181 return Some("file_type.temporary");
182 }
183
184 Some(match name.rsplit_once('.')?.1 {
185 "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "heic" | "bmp" | "ico" | "tif"
186 | "tiff" | "svg" => "file_type.image",
187 "mp4" | "mkv" | "mov" | "avi" | "webm" | "m4v" | "mpg" | "mpeg" => "file_type.video",
188 "mp3" | "wav" | "flac" | "ogg" | "opus" | "m4a" | "aiff" => "file_type.audio",
189 "zip" | "tar" | "gz" | "tgz" | "bz2" | "xz" | "7z" | "rar" | "zst" => "file_type.archive",
190 "md" | "markdown" | "mdx" | "txt" | "rst" | "pdf" | "doc" | "docx" | "odt" | "rtf"
191 | "csv" | "tsv" | "xls" | "xlsx" | "ods" | "ppt" | "pptx" | "odp" | "epub" | "mobi"
192 | "db" | "sqlite" | "sqlite3" => "file_type.document",
193 "rs" | "py" | "pyi" | "pyw" | "js" | "mjs" | "cjs" | "ts" | "mts" | "cts" | "jsx"
194 | "tsx" | "go" | "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "java"
195 | "rb" | "php" | "lua" | "swift" | "kt" | "kts" | "sh" | "bash" | "zsh" | "fish"
196 | "ps1" | "html" | "htm" | "css" | "scss" | "sass" | "sql" => "file_type.source",
197 "json" | "jsonc" | "json5" | "toml" | "yaml" | "yml" | "ini" | "conf" | "cfg" | "xml" => {
198 "file_type.config"
199 }
200 "lock" => "file_type.build",
201 "tmp" | "temp" | "bak" | "old" | "orig" | "swp" | "swo" | "part" | "cache" | "log" => {
202 "file_type.temporary"
203 }
204 _ => return None,
205 })
206}
207
208pub(crate) fn directory_name_icon(name: &OsStr) -> Option<&'static str> {
209 Some(match name.to_str()? {
210 ".git" => "\u{e702}",
211 ".github" | ".gitlab" | ".vscode" | ".idea" => "\u{f107f}",
212 "src" | "source" | "sources" | "lib" => "\u{f121}",
213 "test" | "tests" | "__tests__" | "spec" | "specs" => "\u{f197e}",
214 "target" | "build" | "dist" => "\u{f19fc}",
215 "doc" | "docs" | "documentation" | "notes" => "\u{f0c82}",
216 "assets" | "images" => "\u{f024f}",
217 "node_modules" | "vendor" => "\u{f0253}",
218 "scripts" | "bin" => "\u{f120}",
219 _ => return None,
220 })
221}
222
223pub(crate) fn system_directory_icon(filesystem_identity: (u64, u64)) -> Option<&'static str> {
224 static ICONS: OnceLock<HashMap<(u64, u64), &'static str>> = OnceLock::new();
225 let icons = ICONS.get_or_init(|| {
226 let mut directories = vec![
227 (dirs::home_dir(), "\u{f10b5}"),
228 (dirs::desktop_dir(), "\u{f108}"),
229 (dirs::document_dir(), "\u{f0c82}"),
230 (dirs::download_dir(), "\u{f024d}"),
231 (dirs::audio_dir(), "\u{f1359}"),
232 (dirs::picture_dir(), "\u{f024f}"),
233 (dirs::video_dir(), "\u{f19fa}"),
234 (dirs::public_dir(), "\u{f024c}"),
235 (dirs::template_dir(), "\u{f069d}"),
236 (dirs::config_dir(), "\u{f107f}"),
237 (dirs::cache_dir(), "\u{f0aba}"),
238 ];
239 if let Some(home) = dirs::home_dir() {
240 for (path, icon) in [
241 (".config", "\u{f107f}"),
242 (".cache", "\u{f0aba}"),
243 (".local", "\u{f0253}"),
244 (".Trash", "\u{f1f8}"),
245 (".ssh", "\u{f0250}"),
246 ] {
247 directories.push((Some(home.join(path)), icon));
248 }
249 }
250 #[cfg(target_os = "macos")]
251 {
252 for path in ["/Applications", "/System/Applications"] {
253 directories.push((Some(PathBuf::from(path)), "\u{f1b3}"));
254 }
255 directories.push((Some(PathBuf::from("/Library")), "\u{f02d}"));
256 if let Some(home) = dirs::home_dir() {
257 directories.push((Some(home.join("Applications")), "\u{f1b3}"));
258 directories.push((Some(home.join("Library")), "\u{f02d}"));
259 }
260 }
261 #[cfg(target_os = "linux")]
262 {
263 directories.extend([
264 (dirs::data_dir(), "\u{f0253}"),
265 (dirs::state_dir(), "\u{f0aba}"),
266 (dirs::executable_dir(), "\u{f120}"),
267 (dirs::data_dir().map(|path| path.join("Trash")), "\u{f1f8}"),
268 ]);
269 for (path, icon) in [
270 ("/etc", "\u{f107f}"),
271 ("/usr", "\u{f1b3}"),
272 ("/var", "\u{f0aba}"),
273 ("/tmp", "\u{f0aba}"),
274 ("/home", "\u{f024c}"),
275 ] {
276 directories.push((Some(PathBuf::from(path)), icon));
277 }
278 }
279 let mut icons = HashMap::new();
280 for (path, icon) in directories {
281 if let Some(metadata) = path.and_then(|path| std::fs::metadata(path).ok()) {
282 if metadata.is_dir() {
283 icons
285 .entry((metadata.dev(), metadata.ino()))
286 .or_insert(icon);
287 }
288 }
289 }
290 icons
291 });
292 icons.get(&filesystem_identity).copied()
293}
294
295#[derive(Debug, Clone, Copy)]
296pub enum FileIcon {
297 Directory,
298 Executable,
299 Symlink,
300 RegularFile,
301}
302
303impl FileIcon {
304 pub fn as_str_custom(&self, config: &IconConfig) -> String {
305 self.icon(config).to_string()
306 }
307
308 pub fn icon<'a>(&self, config: &'a IconConfig) -> &'a str {
310 self.configured_icon(config).unwrap_or(if config.enabled {
311 match self {
312 FileIcon::Directory => "\u{f024b}",
313 FileIcon::Executable => "",
314 FileIcon::Symlink => "",
315 FileIcon::RegularFile => "",
316 }
317 } else {
318 ""
319 })
320 }
321
322 pub(crate) fn configured_icon<'a>(&self, config: &'a IconConfig) -> Option<&'a str> {
323 match self {
324 FileIcon::Directory => config.directory.as_deref(),
325 FileIcon::Executable => config.executable.as_deref(),
326 FileIcon::Symlink => config.symlink.as_deref(),
327 FileIcon::RegularFile => config.regular.as_deref(),
328 }
329 }
330}