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
//! ⚡ Supercharge your Alfred workflows by building them in Rust!
//!
//! # Introduction
//!
//! This crate provides types for developing script filter Alfred workflows in
//! Rust. Additionally, this project includes the `powerpack-cli` crate which
//! contains a command-line tool to help build and install your workflows.
//!
//! Types in this crate closely mirror the script filter JSON format. View the
//! official documentation for that [here][fmt].
//!
//! [fmt]: https://www.alfredapp.com/help/workflows/inputs/script-filter/json/
//!
//! # Examples
//!
//! Each row in an Alfred script filter result is represented by an [`Item`]. A
//! workflow must output a sequence of items to stdout using the [`output()`]
//! function.
//!
//! ```
//! use std::iter;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let item = powerpack::Item::new("Example title")
//!     .subtitle("example subtitle")
//!     .arg("example");
//!
//! powerpack::output(iter::once(item))?;
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;
use std::io;
use std::path::PathBuf;
use std::time::Duration;

use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};

pub use serde_json::json as value;
pub use serde_json::Value;

#[cfg(feature = "detach")]
pub use powerpack_detach as detach;

#[cfg(feature = "env")]
pub use powerpack_env as env;

fn is_default<T: Default + PartialEq>(t: &T) -> bool {
    t == &T::default()
}

////////////////////////////////////////////////////////////////////////////////
// Definitions
////////////////////////////////////////////////////////////////////////////////

/// An arg, either a string or a sequence of strings.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(untagged)]
enum Arg {
    /// A single string.
    One(String),
    /// A sequence of strings.
    Many(Vec<String>),
}

/// A keyboard modifier key.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize)]
pub enum Key {
    /// ⌘
    #[serde(rename = "cmd")]
    Command,
    /// ⌥
    #[serde(rename = "alt")]
    Option,
    /// ⌃
    #[serde(rename = "ctrl")]
    Control,
    /// ⇧
    #[serde(rename = "shift")]
    Shift,
    /// fn
    #[serde(rename = "fn")]
    Function,
}

/// A keyboard modifier combination.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(untagged)]
enum Keys {
    One(Key),
    #[serde(serialize_with = "serialize_many_keys")]
    Many(Vec<Key>),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum IconInner {
    /// Load an image from a path.
    Image(PathBuf),
    /// An object whose icon should be shown.
    FileIcon(PathBuf),
    /// Uniform Type Identifier (UTI) icon.
    FileType(String),
}

/// An icon for an [`Item`].
///
/// If not provided the icon will default to the workflow icon.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Icon(IconInner);

/// The type of item.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize)]
pub enum Kind {
    #[serde(rename = "default")]
    Default,
    #[serde(rename = "file")]
    File,
    #[serde(rename = "file:skipcheck")]
    FileSkipCheck,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize)]
struct Text {
    /// Defines the text the user will get when copying the item (⌘+C).
    #[serde(skip_serializing_if = "Option::is_none")]
    copy: Option<String>,

    /// Defines the text the user will see in large type (⌘+L).
    #[serde(rename = "largetype", skip_serializing_if = "Option::is_none")]
    large_type: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize)]
struct Data {
    /// The subtitle displayed in the result row.
    #[serde(skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,

    /// The argument which is passed through to the output.
    #[serde(skip_serializing_if = "Option::is_none")]
    arg: Option<String>,

    /// The icon displayed in the result row when the modifier is pressed.
    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<Icon>,

    /// Mark whether the item is valid when the modifier is pressed.
    #[serde(skip_serializing_if = "Option::is_none")]
    valid: Option<bool>,
}

/// The modifier settings for an [`Item`] when a modifier key is pressed.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct Modifier {
    /// The modifier key.
    key: Keys,

    /// The modifier data.
    data: Data,
}

/// An Alfred script filter item.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Item {
    /// The title displayed in the result row.
    title: String,

    /// The subtitle displayed in the result row.
    #[serde(skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,

    /// A unique identifier for the item.
    #[serde(skip_serializing_if = "Option::is_none")]
    uid: Option<String>,

    /// The argument which is passed through to the output.
    #[serde(skip_serializing_if = "Option::is_none")]
    arg: Option<Arg>,

    /// The icon displayed in the result row.
    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<Icon>,

    /// Whether this item is valid or not.
    #[serde(skip_serializing_if = "Option::is_none")]
    valid: Option<bool>,

    /// Enables you to define what Alfred matches against.
    #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
    matches: Option<String>,

    /// Populates the search field when the user auto-completes the result.
    #[serde(skip_serializing_if = "Option::is_none")]
    autocomplete: Option<String>,

    /// The type of item.
    #[serde(rename = "type", skip_serializing_if = "is_default")]
    kind: Kind,

    /// Control how the modifier keys react.
    #[serde(rename = "mods", skip_serializing_if = "HashMap::is_empty")]
    modifiers: HashMap<Keys, Data>,

    /// Defines the copied or large type text for this item.
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<Text>,

    /// A Quick Look URL which will be shown if the user uses Quick Look (⌘+Y).
    #[serde(rename = "quicklookurl", skip_serializing_if = "Option::is_none")]
    quicklook_url: Option<String>,

    #[serde(skip_serializing_if = "Value::is_null")]
    action: Value,
}

/// The output of a workflow (i.e. input for the script filter)
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Output {
    /// The interval in seconds after which to rerun the script filter.
    #[serde(
        skip_serializing_if = "Option::is_none",
        serialize_with = "duration_as_secs"
    )]
    rerun: Option<Duration>,

    /// Whether to skip Alfred's knowledge for this output.
    #[serde(rename = "skipknowledge", skip_serializing_if = "Option::is_none")]
    skip_knowledge: Option<bool>,

    /// Each row item.
    items: Vec<Item>,
}

////////////////////////////////////////////////////////////////////////////////
// Implementations
////////////////////////////////////////////////////////////////////////////////

fn serialize_many_keys<S>(duration: &[Key], s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut out = String::with_capacity(5 * duration.len());
    for (i, key) in duration.iter().enumerate() {
        if i != 0 {
            out.push('+');
        }
        out.push_str(match key {
            Key::Command => "cmd",
            Key::Option => "alt",
            Key::Control => "ctrl",
            Key::Shift => "shift",
            Key::Function => "fn",
        });
    }
    s.serialize_str(&out)
}

impl Serialize for Icon {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match &self.0 {
            IconInner::Image(path) => {
                let mut s = serializer.serialize_struct("Icon", 1)?;
                s.serialize_field("path", &path)?;
                s.end()
            }
            IconInner::FileIcon(path) => {
                let mut s = serializer.serialize_struct("Icon", 2)?;
                s.serialize_field("type", "fileicon")?;
                s.serialize_field("path", &path)?;
                s.end()
            }
            IconInner::FileType(string) => {
                let mut s = serializer.serialize_struct("Icon", 2)?;
                s.serialize_field("type", "filetype")?;
                s.serialize_field("path", &string)?;
                s.end()
            }
        }
    }
}

impl Icon {
    /// Create a new icon using the image at the given path.
    ///
    /// This path can be relative to the workflow directory.
    ///
    /// # Examples
    ///
    /// ```
    /// # use powerpack::Icon;
    /// let icon = Icon::with_image("./assets/icon.png");
    /// ```
    pub fn with_image(path: impl Into<PathBuf>) -> Self {
        Self(IconInner::Image(path.into()))
    }

    /// Create a new icon based on the file provided.
    ///
    /// This path can be relative to the workflow directory.
    ///
    /// # Examples
    ///
    /// ```
    /// # use powerpack::Icon;
    /// let icon = Icon::with_file_icon("./assets/example.jpg");
    /// ```
    ///
    /// The above code would use the following icon:
    ///
    /// <img src="https://user-images.githubusercontent.com/17109887/118356177-4695fa80-b574-11eb-8908-c0ccd5f6d23c.png" height="50"/>
    ///
    /// You could combine with "/Applications/Safari.app" to show Safari's icon:
    ///
    /// ```
    /// # use powerpack::Icon;
    /// let icon = Icon::with_file_icon("/Applications/Safari.app");
    /// ```
    pub fn with_file_icon(path: impl Into<PathBuf>) -> Self {
        Self(IconInner::FileIcon(path.into()))
    }

    /// Create a new icon using an Apple [Uniform Type Identifier (UTI)][uti].
    ///
    /// # Examples
    ///
    /// ```
    /// # use powerpack::Icon;
    /// let icon = Icon::with_type("public.jpeg");
    /// ```
    ///
    /// The above code would use the following icon:
    ///
    /// <img src="https://user-images.githubusercontent.com/17109887/118356177-4695fa80-b574-11eb-8908-c0ccd5f6d23c.png" height="50"/>
    ///
    /// [uti]: https://en.wikipedia.org/wiki/Uniform_Type_Identifier
    pub fn with_type(uti: impl Into<String>) -> Self {
        Self(IconInner::FileType(uti.into()))
    }
}

impl Default for Kind {
    fn default() -> Self {
        Self::Default
    }
}

impl Modifier {
    /// Create a new modifier.
    #[must_use]
    pub fn new(key: Key) -> Self {
        Self {
            key: Keys::One(key),
            data: Data::default(),
        }
    }

    /// Create a new modifier with multiple keys.
    ///
    /// # Examples
    ///
    /// ```
    /// # use powerpack::{Key, Modifier};
    /// let m = Modifier::new_multi([Key::Command, Key::Option]);
    /// ```
    #[must_use]
    pub fn new_multi(keys: impl IntoIterator<Item = Key>) -> Self {
        Self {
            key: Keys::Many(keys.into_iter().collect()),
            data: Data::default(),
        }
    }

    /// The subtitle for when this modifier is activated.
    #[must_use]
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.data.subtitle = Some(subtitle.into());
        self
    }

    /// The arg for when this modifier is activated.
    #[must_use]
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.data.arg = Some(arg.into());
        self
    }

    /// The icon for when this modifier is activated.
    #[must_use]
    pub fn icon(mut self, arg: Icon) -> Self {
        self.data.icon = Some(arg);
        self
    }

    /// Whether this item is valid when the modifier is activated.
    #[must_use]
    pub fn valid(mut self, valid: bool) -> Self {
        self.data.valid = Some(valid);
        self
    }
}

impl Item {
    /// Create a new item with the provided title.
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            ..Self::default()
        }
    }

    /// Set the subtitle for this item.
    #[must_use]
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// Set the UID for this item.
    ///
    /// This is a unique identifier for the item which allows help Alfred to
    /// learn about this item for subsequent sorting and ordering of the user's
    /// actioned results.
    ///
    /// It is important that you use the same UID throughout subsequent
    /// executions of your script to take advantage of Alfred's knowledge and
    /// sorting. If you would like Alfred to always show the results in the
    /// order you return them from your script, exclude the UID field.
    #[must_use]
    pub fn uid(mut self, uid: impl Into<String>) -> Self {
        self.uid = Some(uid.into());
        self
    }

    /// Set the argument which is passed through the workflow to the connected
    /// output action.
    ///
    /// While this attribute is optional, it's highly recommended that you
    /// populate this as it's the string which is passed to your connected
    /// output actions. If excluded, you won't know which result item the user
    /// has selected.
    #[must_use]
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.arg = Some(Arg::One(arg.into()));
        self
    }

    /// Set the arguments which are passed through the workflow to the connected
    /// output action.
    ///
    /// Same as [`arg`][Self::arg], but allows you to pass multiple arguments.
    #[must_use]
    pub fn args<I, J>(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self
    where
        I: IntoIterator<Item = J>,
        J: Into<String>,
    {
        self.arg = Some(Arg::Many(args.into_iter().map(Into::into).collect()));
        self
    }

    /// Set the icon displayed in the result row.
    ///
    /// Workflows are run from their workflow folder, so you can reference icons
    /// stored in your workflow relatively.
    #[must_use]
    pub fn icon(mut self, icon: Icon) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Set whether this item is valid or not.
    ///
    /// If an item is valid then Alfred will action this item when the user
    /// presses return. If the item is not valid, Alfred will do nothing. This
    /// allows you to intelligently prevent Alfred from actioning a result based
    /// on the current query passed into your script.
    ///
    /// If you exclude the valid attribute, Alfred assumes that your item is
    /// valid.
    #[must_use]
    pub fn valid(mut self, valid: bool) -> Self {
        self.valid = Some(valid);
        self
    }

    /// Set the text that Alfred will match against.
    ///
    /// This field enables you to define what Alfred matches against when the
    /// workflow is set to "Alfred Filters Results". If match is present, it
    /// fully replaces matching on the title property.
    ///
    /// Note that the match field is always treated as case insensitive, and
    /// intelligently treated as diacritic insensitive. If the search query
    /// contains a diacritic, the match becomes diacritic sensitive.
    #[must_use]
    pub fn matches(mut self, matches: impl Into<String>) -> Self {
        self.matches = Some(matches.into());
        self
    }

    /// Set the autocomplete value for this item.
    ///
    /// An optional but recommended string you can provide which is populated
    /// into Alfred's search field if the user auto-complete's the selected
    /// result (⇥ by default).
    #[must_use]
    pub fn autocomplete(mut self, autocomplete: impl Into<String>) -> Self {
        self.autocomplete = Some(autocomplete.into());
        self
    }

    /// Set the type of item.
    #[must_use]
    pub fn kind(mut self, kind: Kind) -> Self {
        self.kind = kind;
        self
    }

    /// Set the text the user will get when copying the selected result row with
    /// ⌘C or displaying large type with ⌘L.
    ///
    /// If these are not defined, you will inherit Alfred's standard behaviour
    /// where the arg is copied to the Clipboard or used for Large Type.
    #[must_use]
    pub fn copy_text(mut self, copy: impl Into<String>) -> Self {
        self.text.get_or_insert_with(Text::default).copy = Some(copy.into());
        self
    }

    /// Set the text the user will get when displaying large type with ⌘L.
    ///
    /// If this is not defined, you will inherit Alfred's standard behaviour
    /// where the arg is used for Large Type.
    #[must_use]
    pub fn large_type_text(mut self, large_type: impl Into<String>) -> Self {
        self.text.get_or_insert_with(Text::default).large_type = Some(large_type.into());
        self
    }

    /// Set the Quick Look URL for the item.
    ///
    /// This will be visible if the user uses the Quick Look feature within
    /// Alfred (tapping shift, or ⌘Y). This field will also accept a file path,
    /// both absolute and relative to home using ~/.
    ///
    /// If absent, Alfred will attempt to use the arg as the quicklook URL.
    #[must_use]
    pub fn quicklook_url(mut self, quicklook_url: impl Into<String>) -> Self {
        self.quicklook_url = Some(quicklook_url.into());
        self
    }

    /// Add a modifier key configuration.
    ///
    /// This gives you control over how the modifier keys react. For example you
    /// can define the valid attribute to mark if the result is valid based on
    /// the modifier selection and set a different arg to be passed out if
    /// actioned with the modifier.
    #[must_use]
    pub fn modifier(mut self, modifier: Modifier) -> Self {
        let Modifier { key, data } = modifier;
        self.modifiers.insert(key, data);
        self
    }

    /// Set the Universal Action item(s).
    ///
    /// This element defines the Universal Action items used when actioning the
    /// result, and overrides the [`arg`][Self::arg] being used for actioning.
    /// The action key can take a string or array for simple types, and the
    /// content type will automatically be derived by Alfred to file, url, or
    /// text.
    ///
    /// # Examples
    ///
    /// Single item:
    ///
    /// ```
    /// # use powerpack::Item;
    /// let item = Item::new("Title").action("Alfred is Great");
    /// ```
    ///
    /// Multiple Items:
    ///
    /// ```
    /// # use powerpack::{value, Item};
    /// let item = Item::new("Title").action(value!(["Alfred is Great", "I use him all day long"]));
    /// ```
    ///
    /// For control over the content type of the action, you can use an object
    /// with typed keys:
    ///
    /// ```
    /// # use powerpack::{value, Item};
    /// let item = Item::new("Title").action(value!({
    ///     "text": ["one", "two", "three"],
    ///     "url": "https://www.alfredapp.com",
    ///     "file": "~/Desktop",
    ///     "auto": "~/Pictures"
    /// }));
    /// ```
    ///
    pub fn action(mut self, action: impl Into<Value>) -> Self {
        self.action = action.into();
        self
    }
}

fn duration_as_secs<S>(duration: &Option<Duration>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match duration {
        Some(d) => s.serialize_f32(d.as_secs_f32()),
        None => unreachable!(),
    }
}

impl Output {
    /// Create a new output.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the rerun value.
    ///
    /// Scripts can be set to re-run automatically after an interval with a
    /// value of 0.1 to 5.0 seconds. The script will only be re-run if the
    /// script filter is still active and the user hasn't changed the state of
    /// the filter by typing and triggering a re-run.
    pub fn rerun(&mut self, duration: Duration) -> &mut Self {
        self.rerun = Some(duration);
        self
    }

    /// Set the skip knowledge value.
    ///
    /// This allows you to set `uid` and preserve the item order while allowing
    /// Alfred to retain knowledge of your items, like your current selection
    /// during a re-run.
    pub fn skip_knowledge(&mut self, skip_knowledge: bool) -> &mut Self {
        self.skip_knowledge = Some(skip_knowledge);
        self
    }

    /// Extend the list of items to output.
    pub fn items<I>(&mut self, iter: I) -> &mut Self
    where
        I: IntoIterator<Item = Item>,
    {
        self.items.extend(iter);
        self
    }

    /// Output this script filter to the given writer.
    pub fn write<W: io::Write>(&self, w: W) -> serde_json::Result<()> {
        serde_json::to_writer(w, self)
    }
}

/// Shortcut function to output a list of items to stdout.
pub fn output<I>(items: I) -> serde_json::Result<()>
where
    I: IntoIterator<Item = Item>,
{
    Output::new().items(items).write(io::stdout())
}