pinel 0.8.0

A lightweight editor built with rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use std::{collections::HashMap, path::Path, sync::Mutex};

use iced::widget::image;
use include_dir::{include_dir, Dir};
use once_cell::sync::Lazy;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IconFormat {
    Svg,
    Png,
}

#[derive(Clone, Copy, Debug)]
pub struct IconAsset {
    pub format: IconFormat,
    pub bytes: &'static [u8],
}

static ICONS_DIR: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/src/assets/icons");
static ICON_HANDLE_CACHE: Lazy<Mutex<HashMap<IconCacheKey, image::Handle>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

const SVG_ICON_RASTER_SIZE: u32 = 64;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct IconCacheKey {
    ptr: usize,
    len: usize,
    size: u32,
}

impl IconCacheKey {
    fn new(bytes: &'static [u8], size: u32) -> Self {
        Self {
            ptr: bytes.as_ptr() as usize,
            len: bytes.len(),
            size,
        }
    }
}

/// Detemine width and height of svg icons to be rendered.
fn rasterize_svg_icon(bytes: &'static [u8], size: u32) -> Option<image::Handle> {
    let options = resvg::usvg::Options::default();
    let tree = resvg::usvg::Tree::from_data(bytes, &options).ok()?;
    let mut pixmap = resvg::tiny_skia::Pixmap::new(size, size)?;

    resvg::render(
        &tree,
        resvg::usvg::FitTo::Size(size, size),
        resvg::tiny_skia::Transform::default(),
        pixmap.as_mut(),
    )?;

    Some(image::Handle::from_rgba(
        pixmap.width(),
        pixmap.height(),
        pixmap.take(),
    ))
}

/// Detemine width and height of png icons to be rendered.
fn rasterize_png_icon(bytes: &'static [u8], size: u32) -> Option<image::Handle> {
    let image = ::image::load_from_memory(bytes).ok()?.into_rgba8();
    let resized = if image.width() == size && image.height() == size {
        image
    } else {
        ::image::imageops::resize(&image, size, size, ::image::imageops::FilterType::Triangle)
    };

    Some(image::Handle::from_rgba(
        resized.width(),
        resized.height(),
        resized.into_raw(),
    ))
}

pub fn icon_handle(icon: IconAsset, size: u32) -> image::Handle {
    let key = IconCacheKey::new(icon.bytes, size);
    let mut cache = ICON_HANDLE_CACHE.lock().expect("icon cache poisoned");

    if let Some(handle) = cache.get(&key) {
        return handle.clone();
    }

    match icon.format {
        IconFormat::Png => {
            let handle = rasterize_png_icon(icon.bytes, size)
                .unwrap_or_else(|| image::Handle::from_bytes(icon.bytes));
            cache.insert(key, handle.clone());
            handle
        },
        IconFormat::Svg => {
            let handle = rasterize_svg_icon(icon.bytes, size.max(SVG_ICON_RASTER_SIZE))
                .unwrap_or_else(|| image::Handle::from_bytes(icon.bytes));
            cache.insert(key, handle.clone());
            handle
        },
    }
}

fn resolve_icon(base: &str, name: &str) -> IconAsset {
    let svg_path = if base.is_empty() {
        format!("{name}.svg")
    } else {
        format!("{base}/{name}.svg")
    };
    if let Some(svg) = ICONS_DIR.get_file(&svg_path) {
        return IconAsset {
            format: IconFormat::Svg,
            bytes: svg.contents(),
        };
    }

    let png_path = if base.is_empty() {
        format!("{name}.png")
    } else {
        format!("{base}/{name}.png")
    };
    if let Some(png) = ICONS_DIR.get_file(&png_path) {
        return IconAsset {
            format: IconFormat::Png,
            bytes: png.contents(),
        };
    }

    let fallback = ICONS_DIR
        .get_file("file.png")
        .expect("embedded fallback icon src/assets/icons/file.png must exist");
    IconAsset {
        format: IconFormat::Png,
        bytes: fallback.contents(),
    }
}

static FILE_EXT_MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    HashMap::from([
        ("rs", "rust"),
        ("py", "python"),
        ("js", "javascript"),
        ("mjs", "javascript"),
        ("cjs", "javascript"),
        ("ts", "typescript"),
        ("jsx", "react"),
        ("tsx", "react"),
        ("html", "html"),
        ("htm", "html"),
        ("css", "css"),
        ("scss", "sass"),
        ("sass", "sass"),
        ("less", "less"),
        ("json", "json"),
        ("json5", "json5"),
        ("yaml", "yaml"),
        ("yml", "yml"),
        ("toml", "toml"),
        ("md", "markdown"),
        ("mdx", "mdx"),
        ("go", "go"),
        ("java", "java"),
        ("c", "c"),
        ("h", "c-h"),
        ("cpp", "cpp"),
        ("cc", "cpp"),
        ("cxx", "cpp"),
        ("hpp", "cpp-h"),
        ("cs", "csharp"),
        ("rb", "ruby"),
        ("swift", "swift"),
        ("kt", "kotlin"),
        ("kts", "kotlin"),
        ("dart", "dart"),
        ("lua", "lua"),
        ("pl", "perl"),
        ("pm", "perl"),
        ("php", "php"),
        ("sql", "database"),
        ("sh", "shell"),
        ("bash", "shell"),
        ("zsh", "shell"),
        ("fish", "fish"),
        ("ps1", "powershell"),
        ("svg", "svg"),
        ("xml", "markup"),
        ("graphql", "graphql"),
        ("gql", "graphql"),
        ("proto", "proto"),
        ("ex", "elixir"),
        ("exs", "elixir"),
        ("erl", "erlang"),
        ("hs", "haskell"),
        ("scala", "scala"),
        ("clj", "clojure"),
        ("cljs", "clojure"),
        ("nim", "nim"),
        ("zig", "zig"),
        ("vue", "vue"),
        ("svelte", "svelte"),
        ("elm", "elm"),
        ("rkt", "racket"),
        ("r", "rlang"),
        ("jl", "julia"),
        ("tex", "tex"),
        ("rst", "rst"),
        ("pdf", "pdf"),
        ("wasm", "wasm"),
        ("lock", "key"),
        ("log", "log"),
        ("env", "dotenv"),
        ("dockerfile", "docker"),
        ("dockerignore", "docker"),
        ("gitignore", "git"),
        ("gitattributes", "git"),
        ("gitmodules", "git"),
        ("editorconfig", "editorconfig"),
        ("eslintrc", "eslint"),
        ("prettierrc", "prettier"),
        ("png", "image"),
        ("jpg", "image"),
        ("jpeg", "image"),
        ("gif", "image"),
        ("ico", "image"),
        ("webp", "image"),
        ("bmp", "image"),
        ("mp3", "audio"),
        ("wav", "audio"),
        ("ogg", "audio"),
        ("flac", "audio"),
        ("mp4", "video"),
        ("mov", "video"),
        ("avi", "video"),
        ("mkv", "video"),
        ("zip", "zip"),
        ("tar", "zip"),
        ("gz", "zip"),
        ("rar", "zip"),
        ("exe", "exe"),
        ("bin", "binary"),
        ("dll", "binary"),
        ("csv", "excel"),
        ("xlsx", "excel"),
        ("xls", "excel"),
        ("doc", "word"),
        ("docx", "word"),
        ("pptx", "powerpoint"),
        ("nix", "nix"),
        ("sol", "solidity"),
        ("tf", "terraform"),
        ("prisma", "prisma"),
        ("gradle", "gradle"),
        ("groovy", "groovy"),
        ("f90", "fortran"),
        ("f95", "fortran"),
        ("d", "dlang"),
        ("cr", "crystal"),
        ("fs", "fsharp"),
        ("fsx", "fsharp"),
        ("ml", "ocaml"),
        ("mli", "ocaml"),
        ("hx", "haxe"),
        ("pas", "pascal"),
        ("pp", "pascal"),
        ("pug", "pug"),
        ("slim", "slim"),
        ("haml", "haml"),
        ("styl", "stylus"),
        ("postcss", "postcss"),
        ("coffee", "coffeescript"),
        ("litcoffee", "coffeescript"),
        ("asm", "assembly"),
        ("s", "assembly"),
        ("m", "objectivec"),
        ("mm", "objectivecpp"),
        ("ipynb", "jupyter"),
        ("rmd", "rstudio"),
        ("twig", "twig"),
        ("hbs", "handlebars"),
        ("mustache", "mustache"),
        ("ejs", "ejs"),
        ("njk", "nunjucks"),
        ("jinja", "jinja"),
        ("jinja2", "jinja"),
    ])
});

static FILE_NAME_MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    HashMap::from([
        ("dockerfile", "docker"),
        ("docker-compose.yml", "docker"),
        ("docker-compose.yaml", "docker"),
        ("makefile", "gnu"),
        ("cmakelists.txt", "cmake"),
        (".gitignore", "git"),
        (".gitattributes", "git"),
        (".gitmodules", "git"),
        (".env", "dotenv"),
        (".env.local", "dotenv"),
        (".env.development", "dotenv"),
        (".env.production", "dotenv"),
        ("package.json", "npm"),
        ("package-lock.json", "npm"),
        ("cargo.toml", "rust"),
        ("cargo.lock", "rust"),
        ("tsconfig.json", "typescript"),
        ("jsconfig.json", "javascript"),
        (".eslintrc", "eslint"),
        (".eslintrc.js", "eslint"),
        (".eslintrc.json", "eslint"),
        (".prettierrc", "prettier"),
        (".prettierrc.js", "prettier"),
        (".prettierrc.json", "prettier"),
        ("jest.config.js", "jest"),
        ("jest.config.ts", "jest"),
        ("webpack.config.js", "webpack"),
        ("webpack.config.ts", "webpack"),
        ("rollup.config.js", "rollup"),
        ("rollup.config.ts", "rollup"),
        ("vite.config.js", "vitejs"),
        ("vite.config.ts", "vitejs"),
        ("next.config.js", "nextjs"),
        ("next.config.mjs", "nextjs"),
        ("tailwind.config.js", "tailwind"),
        ("tailwind.config.ts", "tailwind"),
        ("babel.config.js", "babel"),
        (".babelrc", "babel"),
        ("license", "certificate"),
        ("licence", "certificate"),
        ("readme.md", "markdown"),
        ("changelog.md", "markdown"),
        ("todo.md", "todo"),
        ("todo.txt", "todo"),
        ("todo", "todo"),
        (".editorconfig", "editorconfig"),
        ("yarn.lock", "yarn"),
        (".yarnrc", "yarn"),
        ("pnpm-lock.yaml", "pnpm"),
        (".npmrc", "npm"),
        ("nginx.conf", "nginx"),
        (".prettierignore", "prettier"),
        (".eslintignore", "eslint"),
        ("vercel.json", "vercel"),
        ("netlify.toml", "server"),
        (".dockerignore", "docker"),
    ])
});

static FOLDER_NAME_MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    HashMap::from([
        ("src", "src"),
        ("source", "src"),
        ("lib", "src"),
        ("build", "build"),
        ("dist", "build"),
        ("out", "build"),
        ("output", "build"),
        ("node_modules", "node"),
        ("test", "tests"),
        ("tests", "tests"),
        ("__tests__", "tests"),
        ("spec", "tests"),
        (".git", "git"),
        ("styles", "styles"),
        ("css", "styles"),
        ("style", "styles"),
        ("images", "images"),
        ("img", "images"),
        ("assets", "images"),
        ("icons", "images"),
        ("views", "views"),
        ("pages", "views"),
        ("screens", "views"),
        ("db", "db"),
        ("database", "db"),
        ("migrations", "db"),
        ("i18n", "i18n"),
        ("locale", "i18n"),
        ("locales", "i18n"),
        ("lang", "i18n"),
        ("app", "app"),
        ("theme", "theme"),
        ("themes", "theme"),
        ("services", "services"),
        ("service", "services"),
        ("layout", "layout"),
        ("layouts", "layout"),
        (".vscode", "vsc"),
        ("bench", "bench"),
        ("benchmarks", "bench"),
        ("cypress", "cypress"),
        ("next", "next"),
        ("bower_components", "bower"),
        ("save", "save"),
        ("backup", "save"),
    ])
});

/// Resolves a filename to the icon/asset key used both for the local file
/// tree icon and (see [`crate::discord_rpc`]) the Discord Rich Presence
/// large image key - the two need to agree on naming since Discord's art
/// assets are uploaded under these same key names.
pub fn file_icon_key(filename: &str) -> &'static str {
    let filename_lower = filename.to_lowercase();

    if let Some(&icon_name) = FILE_NAME_MAP.get(filename_lower.as_str()) {
        return icon_name;
    }

    // Try compound extension (e.g. "test.spec.ts" → "spec.ts")
    let parts: Vec<&str> = filename_lower.split('.').collect();
    for i in 1..parts.len() {
        let compound_ext = parts[i..].join(".");
        if let Some(&icon_name) = FILE_EXT_MAP.get(compound_ext.as_str()) {
            return icon_name;
        }
    }

    // Try simple extension
    if let Some(ext) = Path::new(filename).extension().and_then(|e| e.to_str()) {
        if let Some(&icon_name) = FILE_EXT_MAP.get(ext.to_lowercase().as_str()) {
            return icon_name;
        }
    }

    // Default file icon
    "file"
}

pub fn get_file_icon(filename: &str) -> IconAsset {
    resolve_icon("", file_icon_key(filename))
}

pub fn get_folder_icon(folder_name: &str, is_open: bool) -> IconAsset {
    let folder_lower = folder_name.to_lowercase();

    let icon_base_name = FOLDER_NAME_MAP.get(folder_lower.as_str()).copied().unwrap_or("default");

    let name = if is_open {
        format!("{}-open", icon_base_name)
    } else {
        icon_base_name.to_string()
    };

    resolve_icon("folders", &name)
}