jolly 0.3.0

a bookmark manager meets an application launcher, developed with iced
Documentation
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// contains logic for loading icons for entries
//
// different implementations for macOs, windows, and linux. (linux and
// BSDs assumed to use freedesktop compatible icon standards)

// general overview and requirements for icon usage:
//
// Icons are mandatory for usage with Jolly.
// Icons are generated based on the entry type.
//
// location entries get searched as a file. If the file does not
// exist, a default icon may be returned
//
// url-like entries get searched as a protocol handler
//
// system entries are currently treated as file entries, which means
// they usually fail to load since the system command is not usually a
// file on disk.
//
// keyword entries are parsed by filling in their customizable value with a blank string ""
//
// If an icon cannot be loaded, we fall back to a platform specific default icon.
//
// If that default icon cannot be loaded, there is an extremely boring
// (grey square) icon that is used instead.
//
// The default icon is always cached staticly (one use per crate)
//
// All of the other icon lookups can be optionally cached using the IconCache struct

use std::collections::HashMap;
use std::hash::Hash;

use std::error;
use url::Url;

mod linux_and_friends;
mod macos;
mod windows;

use lazy_static::lazy_static;
lazy_static! {
    static ref FALLBACK_ICON: Icon = Icon::from_pixels(1, 1, &[127, 127, 127, 255]);
}

// TODO
//
// This is a list of supported icon formats by iced_graphics.
// This is based on iced_graphics using image-rs to load images, and
// looking at what features are enabled on that package. In the future
// we may not compile support for all formats but (for now) we have a
// comprehensive list here
const SUPPORTED_ICON_EXTS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "webp", "pbm", "pam", "ppm", "pgm", "tiff", "tif", "tga", "dds",
    "bmp", "ico", "hdr", "exr", "ff", "qoi",
];

const DEFAULT_ICON_SIZE: u16 = 48; // TODO, support other icon sizes

#[cfg(target_os = "macos")]
pub use macos::Os as IconSettings;

#[cfg(all(unix, not(target_os = "macos")))]
pub use linux_and_friends::Os as IconSettings;

#[cfg(target_os = "windows")]
pub use self::windows::Os as IconSettings;

#[derive(Debug)]
struct IconError(String, Option<Box<dyn error::Error + 'static>>);

use std::fmt;
impl fmt::Display for IconError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl error::Error for IconError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.1.as_deref()
    }
}

impl<S: AsRef<str> + fmt::Display> From<S> for IconError {
    fn from(value: S) -> Self {
        Self(value.to_string(), None)
    }
}

trait Context<T> {
    fn context<S: AsRef<str> + fmt::Display>(self, msg: S) -> Result<T, IconError>;
}

impl<T, E: error::Error + 'static> Context<T> for Result<T, E> {
    fn context<S: AsRef<str> + fmt::Display>(self, msg: S) -> Result<T, IconError> {
        self.map_err(|e| IconError(msg.to_string(), Some(Box::new(e))))
    }
}

impl<T> Context<T> for Option<T> {
    fn context<S: AsRef<str> + fmt::Display>(self, msg: S) -> Result<T, IconError> {
        self.ok_or(IconError(msg.to_string(), None))
    }
}

trait IconImpl {}

// defines functions that must be implemented for every operating
// system in order implement icons in jolly
trait IconInterface {
    // default icon to use if icon cannot be loaded.
    // must be infallible
    // the output is cached by icon module, so it should not be used be other logic
    fn get_default_icon(&self) -> Result<Icon, IconError>;

    // icon that would be used for a path that must exist
    // path is guaranteed to be already canonicalized
    fn get_icon_for_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<Icon, IconError>;

    // icon to use for a specific url or protocol handler.
    fn get_icon_for_url(&self, url: &str) -> Result<Icon, IconError>;

    // provided method: version of get_default_icon that caches its
    // value. One value for lifetime of application
    fn cached_default(&self) -> Icon {
        use once_cell::sync::OnceCell;
        static DEFAULT_ICON: OnceCell<Icon> = OnceCell::new();

        DEFAULT_ICON
            .get_or_init(|| self.get_default_icon().unwrap_or(FALLBACK_ICON.clone()))
            .clone()
    }

    // provided method: uses icon interfaces to turn icontype into icon
    fn load_icon(&self, itype: IconType) -> Icon {
        let icon = self.try_load_icon(itype);
        icon.unwrap_or(self.cached_default())
    }

    // convert an icontype into an icon
    fn try_load_icon(&self, itype: IconType) -> Result<Icon, IconError> {
        match itype.0 {
            IconVariant::Url(u) => self.get_icon_for_url(u.as_str()),
            IconVariant::File(p) => {
                if p.exists() {
                    if let Ok(p) = p.canonicalize() {
                        self.get_icon_for_file(p)
                    } else {
                        Err("File Icon does not exist".into())
                    }
                } else {
                    Err("Cannot load icon for nonexistant file".into()) // TODO handle file type lookup by extension
                }
            }
            IconVariant::CustomIcon(p) => {
                let ext = p.extension().context("No extension on custom icon file")?;
                if SUPPORTED_ICON_EXTS
                    .iter()
                    .find(|s| ext.eq_ignore_ascii_case(s))
                    .is_some()
                {
                    Ok(Icon::from_path(p))
                } else if ext.eq_ignore_ascii_case("svg") {
                    icon_from_svg(&p)
                } else {
                    Err("is unsupported icon type".into())
                }
            }
            IconVariant::System(command) => {
                // heuristic: dont use full path but only first
                // word in system entry
                use which::which;

                if let Some(exe) = command.split(" ").next().and_then(|e| which(e).ok()) {
                    self.try_load_icon(IconType::file(exe))
                } else if let Some(exe) = command
                    .split(" ")
                    .next()
                    .and_then(|exe| self.try_load_icon(IconType::file(exe)).ok())
                {
                    Ok(exe)
                } else {
                    self.try_load_icon(IconType::file(command))
                }
            }
        }
    }
}

// sufficient for now, until we implement SVG support
pub type Icon = iced::widget::image::Handle;

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct IconType(IconVariant);

impl IconType {
    pub fn custom<P: AsRef<std::path::Path>>(path: P) -> Self {
        Self(IconVariant::CustomIcon(path.as_ref().into()))
    }
    pub fn url(url: Url) -> Self {
        // hack to make paths that start with disk drives not show up as URLs
        #[cfg(target_os = "windows")]
        if url.scheme().len() == 1
            && "abcdefghijklmnopqrstuvwxyz".contains(url.scheme().chars().next().unwrap())
        {
            return Self(IconVariant::File(url.as_ref().into()));
        }

        Self(IconVariant::Url(url))
    }
    pub fn file<P: AsRef<std::path::Path>>(path: P) -> Self {
        Self(IconVariant::File(path.as_ref().into()))
    }

    pub fn system<S: ToString>(cmd: S) -> Self {
        Self(IconVariant::System(cmd.to_string()))
    }
}

// represents the necessary information in an entry to look up an icon
// type. Importantly, url based entries are assumed to have the same
// icon if they have the same protocol (for example, all web links)
#[derive(Debug, Clone)]
enum IconVariant {
    // render using icon for protocol of url
    Url(url::Url),
    // render using icon for path
    File(std::path::PathBuf),
    // Like a file, but uses heuristics in case command has arguments
    System(String),
    // override "normal" icon and use icon from this path
    CustomIcon(std::path::PathBuf),
}

impl Hash for IconVariant {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            IconVariant::Url(u) => u.scheme().hash(state),
            IconVariant::File(p) => p.hash(state),
            IconVariant::CustomIcon(p) => p.hash(state),
            IconVariant::System(p) => p.hash(state),
        }
    }
}

impl Eq for IconVariant {}
impl PartialEq for IconVariant {
    fn eq(&self, other: &Self) -> bool {
        match self {
            IconVariant::Url(s) => {
                if let IconVariant::Url(o) = other {
                    s.scheme() == o.scheme()
                } else {
                    false
                }
            }
            IconVariant::File(s) => {
                if let IconVariant::File(o) = other {
                    s == o
                } else {
                    false
                }
            }
            IconVariant::CustomIcon(s) => {
                if let IconVariant::CustomIcon(o) = other {
                    s == o
                } else {
                    false
                }
            }
            IconVariant::System(s) => {
                if let IconVariant::System(o) = other {
                    s == o
                } else {
                    false
                }
            }
        }
    }
}

pub fn default_icon(is: &IconSettings) -> Icon {
    is.cached_default()
}

use crate::Message;
use iced::futures::channel::mpsc;

// represents an icon cache that can look up icons in a deferred worker thread
#[derive(Default)]
pub struct IconCache {
    cmd: Option<std::sync::mpsc::Sender<IconCommand>>,
    cache: HashMap<IconType, Option<Icon>>,
}

impl IconCache {
    pub fn new() -> Self {
        Self {
            cmd: None,
            cache: HashMap::new(),
        }
    }

    pub fn get(&mut self, it: &IconType) -> Option<Icon> {
        // if the key is the cache, either we have the icon or it has
        // already been scheduled. either way, send it.
        if let Some(icon) = self.cache.get(it) {
            return icon.clone();
        }

        // if we have a reference the iconwork command channel, then
        // we kick off a request to lookup the new icontype
        if let Some(cmd) = &self.cmd {
            cmd.send(IconCommand::LoadIcon(it.clone()))
                .expect("Could not send new icon lookup command");
            self.cache.insert(it.clone(), None);
        }

        // at this point, we know we had a cache miss
        None
    }

    pub fn add_icon(&mut self, it: IconType, i: Icon) {
        self.cache.insert(it, Some(i));
    }

    pub fn set_cmd(&mut self, cmd: std::sync::mpsc::Sender<IconCommand>) {
        self.cmd = Some(cmd);
    }
}

#[derive(Debug)]
pub enum IconCommand {
    LoadSettings(IconSettings),
    LoadIcon(IconType),
}

pub fn icon_worker() -> mpsc::Receiver<Message> {
    // todo: fix magic for channel size
    let (mut output, sub_stream) = mpsc::channel(100);

    std::thread::spawn(move || {
        let (input, command_stream) = std::sync::mpsc::channel();

        // send the application a channel to provide us icon work
        // TODO: implement error checking if we cant send
        output
            .try_send(Message::StartedIconWorker(input))
            .expect("Could not send iconworker back to application");

        let command = match command_stream.recv() {
            Ok(i) => i,
            _ => return,
        };
        let settings = if let IconCommand::LoadSettings(settings) = command {
            settings
        } else {
            return;
        };

        loop {
            let command = match command_stream.recv() {
                Ok(i) => i,
                _ => break,
            };

            match command {
                IconCommand::LoadIcon(icontype) => {
                    // todo: handle error
                    output
                        .try_send(Message::IconReceived(
                            icontype.clone(),
                            settings.load_icon(icontype),
                        ))
                        .expect("Could not send icon back  application");
                }
                _ => break,
            }
        }
    });
    sub_stream
}

// convert an svg file into a pixmap
fn icon_from_svg(path: &std::path::Path) -> Result<Icon, IconError> {
    use resvg::usvg::TreeParsing;
    let svg_data = std::fs::read(path).context("could not open file")?;
    let utree = resvg::usvg::Tree::from_data(&svg_data, &Default::default())
        .context("could not parse svg")?;

    let icon_size = DEFAULT_ICON_SIZE as u32;

    let mut pixmap =
        resvg::tiny_skia::Pixmap::new(icon_size, icon_size).context("could not create pixmap")?;

    let rtree = resvg::Tree::from_usvg(&utree);

    // we have non-square svg
    if rtree.size.width() != rtree.size.height() {
        return Err("SVG icons must be square".into());
    }

    let scalefactor = icon_size as f32 / rtree.size.width();
    let transform = resvg::tiny_skia::Transform::from_scale(scalefactor, scalefactor);

    rtree.render(transform, &mut pixmap.as_mut());

    Ok(Icon::from_pixels(
        icon_size,
        icon_size,
        pixmap.take().leak(),
    ))
}

#[cfg(test)]
mod tests {
    use crate::icon::IconType;

    use super::{Icon, IconError, IconInterface, IconSettings};
    use iced::advanced::image;

    pub(crate) fn hash_eq_icon(icon: &Icon, ficon: &Icon) -> bool {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut ihash = DefaultHasher::new();
        let mut fhash = DefaultHasher::new();
        icon.hash(&mut ihash);
        ficon.hash(&mut fhash);
        ihash.finish() == fhash.finish()
    }

    fn iconlike(icon: Icon, err_msg: &str) {
        match icon.data() {
            image::Data::Path(p) => {
                assert!(p.exists())
            }
            image::Data::Bytes(bytes) => {
                assert!(bytes.len() > 0)
            }
            image::Data::Rgba {
                width,
                height,
                pixels,
            } => {
                let num_pixels = width * height;

                assert!(num_pixels > 0, "zero pixels: {}", err_msg);
                assert_eq!(
                    (num_pixels * 4) as usize,
                    pixels.len(),
                    "incorrect buffer size: {}",
                    err_msg
                )
            }
        };

        assert!(
            !hash_eq_icon(&icon, &super::FALLBACK_ICON),
            "icon hash matches fallback icon, should not occur during happycase"
        );
    }

    #[test]
    fn default_icon_is_iconlike() {
        iconlike(
            IconSettings::default().get_default_icon().unwrap(),
            "for default icon",
        );
    }

    // ignore on linux since exes are all detected as libraries which
    // dont have a default icon
    #[test]
    #[cfg(any(target_os = "windows", target_os = "macos"))]
    fn executable_is_iconlike() {
        let cur_exe = std::env::current_exe().unwrap();

        iconlike(
            IconSettings::default().get_icon_for_file(&cur_exe).unwrap(),
            "for current executable",
        );
    }

    #[test]
    fn paths_are_canonicalized() {
        struct MockIcon;

        impl IconInterface for MockIcon {
            fn get_default_icon(&self) -> Result<crate::icon::Icon, crate::icon::IconError> {
                Ok(super::Icon::from_pixels(1, 1, &[1, 1, 1, 1]))
            }

            fn get_icon_for_file<P: AsRef<std::path::Path>>(
                &self,
                path: P,
            ) -> Result<Icon, IconError> {
                let path = path.as_ref();
                assert!(path.as_os_str() == path.canonicalize().unwrap().as_os_str());
                self.get_default_icon()
            }

            fn get_icon_for_url(&self, _url: &str) -> Result<Icon, IconError> {
                panic!("expected file, not url")
            }
        }

        use tempfile;
        let curdir = std::env::current_dir().unwrap();
        let dir = tempfile::tempdir_in(&curdir).unwrap();
        let dirname = dir.path().strip_prefix(curdir).unwrap();

        let filename = dirname.join("test.txt");

        let _file = std::fs::File::create(&filename).unwrap();

        let icon_type = super::IconType(super::IconVariant::File(filename));
        let mock = MockIcon;
        mock.load_icon(icon_type);
    }

    #[test]
    fn common_urls_are_iconlike() {
        use crate::icon::Context;
        // test urls that default macos has support for
        #[cfg(any(target_os = "macos", target_os = "windows"))]
        let happycase_urls = vec!["http://example.com", "https://example.com"];

        #[cfg(all(unix, not(target_os = "macos")))]
        let happycase_urls: Vec<&str> = Vec::new();

        #[cfg(windows)]
        let happycase_urls: Vec<_> = happycase_urls
            .into_iter()
            .chain(
                [
                    "accountpicturefile:",
                    "AudioCD:",
                    "batfile:",
                    "fonfile:",
                    "hlpfile:",
                    "regedit:",
                ]
                .into_iter(),
            )
            .collect();

        let sadcase_urls = vec![
            "totallynonexistantprotocol:",
            "http:", // malformed url
        ];

        #[cfg(windows)]
        let sadcase_urls: Vec<_> = sadcase_urls
            .into_iter()
            .chain(
                [
                    "anifile:", // uses %1 as the icon
                    "tel:",     // defined but empty on windows
                ]
                .into_iter(),
            )
            .collect();

        let os = IconSettings::default();

        let failed_results: Vec<_> = happycase_urls
            .into_iter()
            .filter_map(|u| {
                os.get_icon_for_url(&u)
                    .context(format!("failed to load '{u}'"))
                    .err()
                    .map(|e| e.to_string())
            })
            .chain(sadcase_urls.into_iter().filter_map(|u| {
                os.get_icon_for_url(&u)
                    .ok()
                    .map(|_| format!("successfully loaded '{u}'"))
            }))
            .collect();

        assert!(
            failed_results.is_empty(),
            "some default urls were loaded incorrectly: {:?}",
            failed_results
        );
    }

    #[test]
    fn common_files_are_iconlike() {
        let dir = tempfile::tempdir().unwrap();
        let files = ["foo.txt", "bar.html", "baz.png", "bat.pdf"];

        let os = IconSettings::default();

        os.get_icon_for_file(dir.path())
            .expect("No Icon for folder".into());

        for f in files {
            let path = dir.path().join(f);
            let file = std::fs::File::create(&path).unwrap();
            file.sync_all().unwrap();

            assert!(path.exists());
            os.get_icon_for_file(&path)
                .expect(&format!("No Icon for file: {f}"));
        }
    }

    #[test]
    fn load_custom_icons() {
        use super::*;
        // example test pbm image
        let pbm_bytes = "P1\n2 2\n1 0 1 0".as_bytes();
        // example test svg
        let test_svg = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("icon/jolly.svg");

        let dir = tempfile::tempdir().unwrap();

        let pbm_fn = dir.path().join("test.pbm");

        std::fs::write(&pbm_fn, pbm_bytes).unwrap();

        let os = IconSettings::default();

        let pbm_icon = os.try_load_icon(IconType::custom(pbm_fn)).unwrap();
        assert!(matches!(pbm_icon.data(), image::Data::Path(_)));

        os.try_load_icon(IconType::custom("file_with_no_extension"))
            .unwrap_err();

        os.try_load_icon(IconType::custom("unsupported_icon_type.pdf"))
            .unwrap_err();

        let svg_icon = os.try_load_icon(IconType::custom(test_svg)).unwrap();
        assert!(matches!(
            svg_icon.data(),
            image::Data::Rgba {
                width: w,
                height: h,
                pixels: _
            }
            if *w == DEFAULT_ICON_SIZE as u32 && *h == DEFAULT_ICON_SIZE as u32
        ));
    }

    #[test]
    fn system_entry_heuristic() {
        use tempfile::tempdir;

        #[cfg(windows)]
        let exe = "cmd.exe";
        #[cfg(not(windows))]
        let exe = "echo";

        let os = IconSettings::default();

        os.try_load_icon(IconType::system(format!("{exe}")))
            .unwrap();
        os.try_load_icon(IconType::system(format!("{exe} a b c")))
            .unwrap();

        let dir = tempdir().unwrap();

        let exe = dir.path().join("test.txt").display().to_string();
        std::fs::File::create(&exe).unwrap();

        assert!(
            !exe.contains(" "),
            "test requires that temp dir path not have spaces: actual path: {exe}"
        );

        os.try_load_icon(IconType::system(format!("{exe}")))
            .unwrap();
        os.try_load_icon(IconType::system(format!("{exe} a b c")))
            .unwrap();

        let exe = dir.path().join("test with spaces.py").display().to_string();
        std::fs::File::create(&exe).unwrap();

        os.try_load_icon(IconType::system(format!("{exe}")))
            .unwrap();
        os.try_load_icon(IconType::system(format!("{exe} a b c")))
            .unwrap_err();
    }
}