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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
// contains logic for displaying entries

use std::error;
use std::fmt;
use std::ops::Deref;

use iced::advanced;
use serde::Deserialize;
use url::Url;

use crate::icon::Icon;
use crate::theme;
use crate::ui;
use crate::{icon, platform};

// these are the weights for the different kind of matches.
// we prefer each weight to be different so we can differentiate them in the test plan
const FULL_KEYWORD_W: u32 = 100;
const PARTIAL_NAME_W: u32 = 3;
const FULL_NAME_W: u32 = 10;
const PARTIAL_TAG_W: u32 = 2;
const STARTSWITH_TAG_W: u32 = 4;
const FULL_TAG_W: u32 = 6;

pub type EntryId = usize;

#[derive(Debug)]
pub enum Error {
    ParseError(String),
    PlatformError(platform::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::PlatformError(e) => e.fmt(f),
            Error::ParseError(s) => f.write_str(s),
        }
    }
}

impl error::Error for Error {}

// theme settings for each shown entry result
#[derive(serde::Deserialize, Debug, Clone, PartialEq)]
#[serde(default)]
pub struct EntrySettings {
    #[serde(flatten)]
    common: ui::InheritedSettings,
    description_size: u16,
}

impl EntrySettings {
    pub fn propagate(&mut self, parent: &ui::InheritedSettings) {
        self.common.propagate(parent);
    }
}

impl Default for EntrySettings {
    fn default() -> Self {
        let inherited = ui::InheritedSettings::default();
        let description_size = (inherited.text_size() as f32 * 0.8).round() as u16;
        Self {
            common: inherited,
            description_size: description_size,
        }
    }
}

#[derive(serde::Deserialize, Debug)]
struct RawStoreEntry {
    location: Option<String>,
    url: Option<String>,
    system: Option<String>,
    keyword: Option<String>,
    escape: Option<bool>,
    #[serde(alias = "desc")]
    description: Option<String>,
    tags: Option<Vec<String>>,
    icon: Option<String>,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
enum Keyword {
    None,
    RawKeyword(String),
    EscapedKeyword(String),
}

#[derive(Debug, Clone, Hash)]
pub struct StoreEntry {
    name: String,
    description: Option<String>,
    entry: EntryType,
    tags: Vec<String>,
    keyword: Keyword,
    icon_type: icon::IconType,
    icon: Option<Icon>,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum EntryType {
    FileEntry(String),
    SystemEntry(String),
}

impl fmt::Display for EntryType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EntryType::FileEntry(_) => f.write_str("FileEntry"),
            EntryType::SystemEntry(_) => f.write_str("SystemEntry"),
        }
    }
}

impl StoreEntry {
    // parse a toml value into a store entry
    pub fn from_value(name: String, val: toml::Value) -> Result<Self, Error> {
        if !val.is_table() {
            return Err(Error::ParseError(format!(
                "Invalid entry '{name}': Jolly entries can only be TOML tables"
            )));
        }

        let raw_entry = RawStoreEntry::deserialize(val)
            .map_err(|e| Error::ParseError(format!("TOML Error: {}", e.message())))?;

        let keyword = if let Some(keyword) = raw_entry.keyword {
            if raw_entry.url.is_some() || raw_entry.escape.unwrap_or(false) {
                Keyword::EscapedKeyword(keyword)
            } else {
                Keyword::RawKeyword(keyword)
            }
        } else {
            Keyword::None
        };

        let is_system = raw_entry.system.is_some();

        let location = match (raw_entry.location, raw_entry.url, raw_entry.system) {
            (Some(loc), None, None) => loc,
            (None, Some(loc), None) => loc,
            (None, None, Some(loc)) => loc,
            (None, None, None) => name.to_string(),
            _ => {
                return Err(Error::ParseError(format!(
                    "Error with entry ['{}']: The entry should only specify one of location/url/system keys",
                    &name
                )))
            }
        };

        let entry = if is_system {
            EntryType::SystemEntry(location)
        } else {
            EntryType::FileEntry(location)
        };

        let tags = match raw_entry.tags {
            Some(tags) => tags,
            None => Vec::new(),
        };

        let icon_type = if let Some(p) = raw_entry.icon {
            icon::IconType::custom(p)
        } else {
            match &entry {
                EntryType::SystemEntry(loc) => icon::IconType::system(loc),
                EntryType::FileEntry(loc) => {
                    let parsed_loc = format_param(loc, "");

                    if let Ok(url) = Url::parse(&parsed_loc) {
                        icon::IconType::url(url)
                    } else {
                        icon::IconType::file(parsed_loc)
                    }
                }
            }
        };

        Ok(StoreEntry {
            name: name.to_string(),
            description: raw_entry.description,
            entry: entry,
            tags: tags,
            keyword: keyword,
            icon_type,
            icon: None,
        })
    }

    // basic idea: search query consists of multiple filters that
    // are ANDED together. And Each query is run on the name and
    // each tag and ORed together
    //
    // score functions score(item, query)
    //
    // for entry (name='foo', tags = ['abc', '123'])
    //
    // for query = "foo a"
    //
    // overall score = MIN(
    //                   MAX(score('foo', 'foo'), score('abc', 'foo'), score('123', 'foo')),
    //                   MAX(score('foo', 'a'), score('abc', 'a'), score('123', 'a')),
    //                 );
    //
    //
    // search results are a little different for keword entries.
    //
    // for keyword entries, they follow the same normal scoring as
    // seen above, so they show up in results for searchs. But
    // they OR together a special check for (1st search token) == keyword token
    pub fn score(&self, searchtext: &str) -> u32 {
        // determine if we are doing case sensitive or case - insensitive match
        let change_case = if searchtext == searchtext.to_lowercase() {
            |s: &str| s.to_uppercase()
        } else {
            |s: &str| s.to_string()
        };

        // build temporary strings with the right case
        let name = change_case(&self.name);
        let tags: Vec<_> = self
            .tags
            .iter()
            .map(String::deref)
            .map(change_case)
            .collect();
        let query: Vec<_> = searchtext.split_whitespace().map(change_case).collect();

        // if vec is empty or first element is empty, no score
        if query.len() == 0 || query[0].len() == 0 {
            return 0;
        }

        // check to see if we match a keyword
        let full_keyword = FULL_KEYWORD_W
            * match &self.keyword {
                Keyword::None => false,
                Keyword::RawKeyword(k) => change_case(k) == query[0],
                Keyword::EscapedKeyword(k) => change_case(k) == query[0],
            } as u32;

        let mut running_score = u32::MAX;

        for ref q in query {
            running_score = running_score.min(
                // calculate measures of a match
                [
                    FULL_NAME_W * ((&name == q) as u32),
                    PARTIAL_NAME_W * (name.contains(q) as u32),
                    FULL_TAG_W * (tags.iter().any(|t| t == q) as u32),
                    PARTIAL_TAG_W * (tags.iter().any(|t| t.contains(q)) as u32),
                    STARTSWITH_TAG_W * (tags.iter().any(|t| t.starts_with(q)) as u32),
                ]
                .into_iter()
                .reduce(std::cmp::max)
                .unwrap(),
            );
        }
        running_score.max(full_keyword)
    }

    // format example:
    //

    pub fn format_name(&self, searchtext: &str) -> String {
        if self.keyword == Keyword::None {
            return self.name.clone();
        }

        let param = if let Some((_, back)) = searchtext.split_once(char::is_whitespace) {
            back
        } else {
            "%s"
        };

        format_param(&self.name, param)
    }

    pub fn format_selection(&self, searchtext: &str) -> String {
        let param = if let Some((_, back)) = searchtext.split_once(char::is_whitespace) {
            back
        } else {
            "%s"
        };

        let s = match &self.entry {
            EntryType::FileEntry(s) => s,
            EntryType::SystemEntry(s) => s,
        };

        let escaped_param = match self.keyword {
            Keyword::EscapedKeyword(_) => urlencoding::encode(param).into_owned(),
            Keyword::None => return s.clone(),
            _ => param.to_string(),
        };

        format_param(s, escaped_param)
    }

    pub fn handle_selection(&self, searchtext: &str) -> Result<(), Error> {
        let func = match &self.entry {
            EntryType::FileEntry(_) => platform::open_file,
            EntryType::SystemEntry(_) => platform::system,
        };
        let selection = self.format_selection(searchtext);

        ::log::info!(r#"Selected Entry {}("{}")"#, &self.entry, selection);

        func(&selection).map_err(Error::PlatformError)
    }

    pub fn build_entry<'a, F, Message, Renderer>(
        &'a self,
        message_func: F,
        searchtext: &str,
        settings: &ui::UISettings,
        selected: bool,
        my_id: EntryId,
    ) -> iced::Element<'a, Message, Renderer>
    where
        F: 'static + Copy + Fn(EntryId) -> Message,
        Message: 'static + Clone,
        Renderer: advanced::Renderer<Theme = theme::Theme> + 'a,
        Renderer: advanced::text::Renderer,
        Renderer: advanced::image::Renderer<Handle = iced::widget::image::Handle>,
    {
        let text_color = if selected {
            settings.theme.selected_text_color.clone()
        } else {
            settings.theme.text_color.clone()
        };

        let button_style = if selected {
            theme::ButtonStyle::Selected
        } else {
            theme::ButtonStyle::Transparent
        };

        let text_color: iced::Color = text_color.into();

        let title_text = iced::widget::text::Text::new(self.format_name(searchtext))
            .size(settings.entry.common.text_size())
            .style(text_color)
            .horizontal_alignment(iced::alignment::Horizontal::Left)
            .vertical_alignment(iced::alignment::Vertical::Center)
            .shaping(iced::widget::text::Shaping::Advanced);

        let description = match &self.description {
            Some(desc) => {
                let paragraphs = desc_to_paragraphs(desc);
                let paragraphs = paragraphs
                    .unwrap_or(vec![desc.to_string()])
                    .into_iter()
                    .map(|paragraph| {
                        iced::widget::text::Text::new(paragraph)
                            .size(settings.entry.description_size)
                            .style(iced::Color::from(text_color))
                            .horizontal_alignment(iced::alignment::Horizontal::Left)
                            .vertical_alignment(iced::alignment::Vertical::Center)
                            .shaping(iced::widget::text::Shaping::Advanced)
                            .into()
                    })
                    .collect();
                iced::widget::Column::with_children(paragraphs).width(iced::Length::Fill)
            }
            None => iced::widget::Column::new(),
        };

        let icon = iced::widget::image::Image::new(
            self.icon
                .clone()
                .unwrap_or_else(|| icon::default_icon(&settings.icon)),
        );

        let icon = icon
            .height(settings.entry.common.text_size())
            .width(settings.entry.common.text_size());

        let icon_row = iced::widget::Row::new()
            .height(iced::Length::Fixed(
                (settings.entry.common.text_size() + 4) as f32,
            ))
            .spacing(2)
            .align_items(iced::Alignment::Center)
            .push(icon)
            .push(title_text);

        let column = iced::widget::Column::new()
            .width(iced::Length::Fill)
            .push(icon_row)
            .push(description);

        // need an empty container to create padding around title.
        // let _container =
        //     iced::widget::container::Container::new(title_text).padding::<u16>(0u16.into());

        let button = iced::widget::button::Button::new(column)
            .on_press(message_func(my_id))
            .style(button_style)
            .width(iced::Length::Fill);

        let element: iced::Element<'_, _, _> = button.into();
        element
    }

    // pull out the icon type of this entry in preparation for
    // determing it. current icontype is replaced with pending value
    pub fn icontype(&self) -> &icon::IconType {
        &self.icon_type
    }

    pub fn icon(&mut self, icon: Icon) {
        self.icon = Some(icon);
    }

    pub fn icon_loaded(&self) -> bool {
        self.icon.is_some()
    }
}

fn format_param<S: AsRef<str>>(fmt_str: &str, searchtext: S) -> String {
    fmt_str
        .split("%%")
        .map(|s| s.replace("%s", searchtext.as_ref()))
        .collect::<Vec<_>>()
        .join("%")
}

fn desc_to_paragraphs(desc: &str) -> Option<Vec<String>> {
    use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag};
    let p = Parser::new(desc);
    let mut last_tag = None;
    let mut result = Vec::new();
    let mut cur_paragraph = String::new();
    for event in p {
        match event {
            Event::Start(tag) => {
                // do not allow nested elements. Only list of paragraphs or indented code blocks
                if last_tag.is_some() {
                    return None;
                }

                if tag == Tag::Paragraph || tag == Tag::CodeBlock(CodeBlockKind::Indented) {
                    last_tag = Some(tag);
                    cur_paragraph = String::new();
                } else {
                    // we saw any other kind of tag. Not allowed, abort.
                    return None;
                }
            }
            Event::End(tag) => {
                if Some(tag) != last_tag {
                    return None;
                } else {
                    last_tag = None;
                    result.push(cur_paragraph.clone());
                }
            }
            Event::Text(txt) => cur_paragraph.push_str(&txt),
            Event::Code(txt) => cur_paragraph.push_str(&txt),
            Event::SoftBreak => cur_paragraph.push_str(" "),
            _ => return None,
        }
    }
    Some(result)
}

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

    use super::*;
    use tempfile;

    // lets cheat and use the hash of an entry for partial equivalence
    // good enough for testing
    impl std::cmp::PartialEq for StoreEntry {
        fn eq(&self, other: &Self) -> bool {
            use std::collections::hash_map::DefaultHasher;
            use std::hash::{Hash, Hasher};
            let mut sh = DefaultHasher::new();
            let mut oh = DefaultHasher::new();
            self.hash(&mut sh);
            other.hash(&mut oh);
            sh.finish() == oh.finish()
        }
    }

    fn parse_entry(text: &str) -> StoreEntry {
        let value: toml::Value = toml::from_str(text).unwrap();

        if let toml::Value::Table(table) = value {
            let (k, v) = table.into_iter().next().unwrap();
            StoreEntry::from_value(k, v).unwrap()
        } else {
            panic!("Toml is not a Table")
        }
    }

    #[test]
    fn case_sensitive() {
        let entry = parse_entry(
            r#"['fOO.txt']
                location = "test/location/asdf.txt"
		tags = ['FOO']"#,
        );

        // if we give a lowercase query, then default case insensitive match
        assert_eq!(entry.score("fo"), STARTSWITH_TAG_W);
        // if we give a
        assert_eq!(entry.score("FO"), STARTSWITH_TAG_W);
        assert_eq!(entry.score("FOO"), FULL_TAG_W);
        assert_eq!(entry.score("fO"), PARTIAL_NAME_W);
    }

    #[test]
    fn non_keword_score() {
        let entry = parse_entry(
            r#"['foo.txt']
                location = "test/location/foo.txt"
		tags = ["foo", "bar", "baz"]"#,
        );

        assert_eq!(entry.score("tx"), PARTIAL_NAME_W);
        assert_eq!(entry.score("foo"), FULL_TAG_W);
        assert_eq!(entry.score("foo.txt"), FULL_NAME_W);

        assert_eq!(entry.score("ba"), STARTSWITH_TAG_W);
        assert_eq!(entry.score("az"), PARTIAL_TAG_W);

        assert_eq!(entry.score("baz"), FULL_TAG_W);
        assert_eq!(entry.score("bar fo"), STARTSWITH_TAG_W);
        assert_eq!(entry.score("bar az"), PARTIAL_TAG_W);
        assert_eq!(entry.score(""), 0);
    }

    #[test]
    fn keword_score() {
        let entry = parse_entry(
            r#"['foo.txt']
                location = "test/location/foo.txt"
                keyword = "y"
		tags = ["foo", "bar", "baz"]"#,
        );

        // if you dont use a keyword, score normally
        assert_eq!(entry.score("fo"), STARTSWITH_TAG_W);

        // otherwise get big bonus for using keyword
        assert_eq!(entry.score("y foo"), FULL_KEYWORD_W);
    }

    #[test]
    fn parse_single_file_entry() {
        let pairs = [
            (
                r#"['foo.txt']
		    tags = ["foo", 'bar', 'baz']
                    description = "asdf"
                    location = "test/location""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: Some("asdf".to_string()),
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("test/location".to_string()),
                    tags: ["foo", "bar", "baz"]
                        .into_iter()
                        .map(str::to_string)
                        .collect(),
                    icon: None,
                    icon_type: IconType::file("test/location"),
                },
            ),
            (
                r#"['foo.txt']
                    location = "test/location""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: None,
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("test/location".to_string()),
                    tags: [].into_iter().map(str::to_string).collect(),
                    icon: None,
                    icon_type: IconType::file("test/location"),
                },
            ),
            (
                r#"['foo.txt']
                    location = "tel:12345""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: None,
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("tel:12345".to_string()),
                    tags: [].into_iter().map(str::to_string).collect(),
                    icon: None,
                    icon_type: IconType::url(url::Url::parse("tel:12345").unwrap()),
                },
            ),
            (
                r#"['test/location/foo.txt']
		    tags = ["foo", 'bar', 'baz']"#,
                StoreEntry {
                    name: "test/location/foo.txt".to_string(),
                    description: None,
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("test/location/foo.txt".to_string()),
                    tags: ["foo", "bar", "baz"]
                        .into_iter()
                        .map(str::to_string)
                        .collect(),
                    icon: None,
                    icon_type: IconType::file("test/location/foo.txt"),
                },
            ),
            (
                r#"['foo.txt']
                    description = "asdf""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: Some("asdf".to_string()),
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("foo.txt".to_string()),
                    tags: [].into_iter().map(str::to_string).collect(),
                    icon: None,
                    icon_type: IconType::file("foo.txt"),
                },
            ),
            (
                r#"['foo.txt']
                    desc = "asdf""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: Some("asdf".to_string()),
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("foo.txt".to_string()),
                    tags: [].into_iter().map(str::to_string).collect(),
                    icon: None,
                    icon_type: IconType::file("foo.txt"),
                },
            ),
            (
                r#"['foo.txt']
                   icon = "asdf.png""#,
                StoreEntry {
                    name: "foo.txt".to_string(),
                    description: None,
                    keyword: Keyword::None,
                    entry: EntryType::FileEntry("foo.txt".to_string()),
                    tags: [].into_iter().map(str::to_string).collect(),
                    icon: None,
                    icon_type: IconType::custom("asdf.png"),
                },
            ),
        ];

        for (toml, expected_entry) in pairs {
            let entry = parse_entry(toml);

            assert_eq!(expected_entry, entry);
        }
    }

    #[test]
    fn system_entry() {
        let dir = tempfile::tempdir().unwrap();
        let dirname = dir.path().to_string_lossy();
        let toml = format!(
            r#"['{}']
                    system = 'foo bar'
		    tags = ["foo", 'bar', 'baz']"#,
            dirname
        );
        let expected_entry = StoreEntry {
            name: dirname.to_string(),
            description: None,
            keyword: Keyword::None,
            entry: EntryType::SystemEntry("foo bar".to_string()),
            tags: ["foo", "bar", "baz"]
                .into_iter()
                .map(str::to_string)
                .collect(),
            icon: None,
            icon_type: IconType::system("foo bar"),
        };

        let entry = parse_entry(&toml);
        assert_eq!(expected_entry, entry);
    }

    #[test]
    fn single_dir_entry() {
        let dir = tempfile::tempdir().unwrap();
        let dirname = dir.path().to_string_lossy();
        let toml = format!(
            r#"['{}']
		    tags = ["foo", 'bar', 'baz']"#,
            dirname
        );
        let expected_entry = StoreEntry {
            name: dirname.to_string(),
            description: None,
            keyword: Keyword::None,
            entry: EntryType::FileEntry(dirname.to_string()),
            tags: ["foo", "bar", "baz"]
                .into_iter()
                .map(str::to_string)
                .collect(),
            icon: None,
            icon_type: IconType::file(dirname.to_string()),
        };

        let entry = parse_entry(&toml);

        assert_eq!(expected_entry, entry);
    }

    #[test]
    fn keyword_search_results() {
        let mut entry = parse_entry(
            r#"['name:%s']
                location = "file/%s""#,
        );

        let raw: Keyword = Keyword::RawKeyword(Default::default());
        let escaped: Keyword = Keyword::EscapedKeyword(Default::default());
        let none: Keyword = Keyword::None;

        let tests = [
            (&raw, "a b", "name:b", "file/b"),
            (&raw, "a B", "name:B", "file/B"),
            (&raw, "a b c", "name:b c", "file/b c"),
            (&escaped, "a b", "name:b", "file/b"),
            (&escaped, "a b c", "name:b c", "file/b%20c"),
            (&none, "a b", "name:%s", "file/%s"),
        ];

        for (entry_type, searchtext, formatted_name, formatted_selection) in tests {
            entry.keyword = entry_type.clone();

            assert_eq!(
                formatted_name,
                entry.format_name(searchtext),
                r#"formatted_name:"{}" -> "{}" failed: "#,
                searchtext,
                formatted_name
            );

            assert_eq!(
                formatted_selection,
                entry.format_selection(searchtext),
                r#"format_selection:"{}" -> "{}" failed: "#,
                searchtext,
                formatted_selection
            );
        }
    }

    #[test]
    fn test_format() {
        let tests = [
            ("%s", "a", "a"),
            ("test %s", "a", "test a"),
            ("%%s", "a", "%s"),
            ("%%%s", "a", "%a"),
            ("%s", "a a", "a a"),
        ];

        for test in tests {
            assert_eq!(
                test.2,
                format_param(test.0, test.1),
                r#"format("{}", "{}") -> "{}" failed: "#,
                test.0,
                test.1,
                test.2
            );
        }
    }

    #[test]
    fn test_paragraph_parser() {
        let succeses = [
            "",
            "test string",
            r"2

            paragraphs",
            r"    pre",
        ];

        for s in succeses {
            assert!(
                desc_to_paragraphs(s).is_some(),
                "could not parse {}, tokens are: {:?}",
                s,
                pulldown_cmark::Parser::new(s)
                    .into_iter()
                    .collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn test_keyword_icontypes_are_parsed() {
        let entry = parse_entry(
            r#"['a']
               location = 'http://example.com/%s'
               keyword = 'a'
               "#,
        );

        assert_eq!(
            entry.icon_type,
            IconType::url(url::Url::parse("http://example.com/").unwrap())
        );

        let entry = parse_entry(
            r#"['a']
               location = '%s.txt'
               keyword = 'a'
               "#,
        );

        assert_eq!(entry.icon_type, IconType::file(".txt"))
    }
}