forked from deanishe/awgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feedback.go
624 lines (547 loc) · 16.9 KB
/
feedback.go
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
// Copyright (c) 2018 Dean Jackson <[email protected]>
// MIT Licence - http://opensource.org/licenses/MIT
package aw
import (
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"go.deanishe.net/fuzzy"
)
// ModKey is a modifier key pressed by the user to run an alternate
// item action in Alfred (in combination with ↩). It is passed
// to Item.NewModifier().
//
// Alfred 3 only permits one modifier at a time, but in Alfred 4+
// you can combine them arbitrarily.
type ModKey string
// Valid modifier keys used to specify alternate actions in Script Filters.
const (
ModCmd ModKey = "cmd" // Alternate action for ⌘↩
ModAlt ModKey = "alt" // Alternate action for ⌥↩
ModOpt ModKey = "alt" // Synonym for ModAlt
ModCtrl ModKey = "ctrl" // Alternate action for ^↩
ModShift ModKey = "shift" // Alternate action for ⇧↩
ModFn ModKey = "fn" // Alternate action for fn↩
)
// Item is a single Alfred Script Filter result.
// Together with Feedback & Modifier, Item generates Script Filter feedback
// for Alfred.
//
// Create Items via NewItem(), so they are bound to their parent Feedback.
type Item struct {
title string
subtitle *string
match *string
uid *string
autocomplete *string
arg []string
valid bool
file bool
copytext *string
largetype *string
ql *string
vars map[string]string
mods map[ModKey]*Modifier
icon *Icon
noUID bool // Suppress UID in JSON
}
// Title sets the title of the item in Alfred's results.
func (it *Item) Title(s string) *Item {
it.title = s
return it
}
// Subtitle sets the subtitle of the item in Alfred's results.
func (it *Item) Subtitle(s string) *Item {
it.subtitle = &s
return it
}
// Match sets Item's match field for filtering.
// If present, this field is preferred over the item's title for fuzzy sorting
// via Feedback, and by Alfred's "Alfred filters results" feature.
func (it *Item) Match(s string) *Item {
it.match = &s
return it
}
// Arg sets Item's arg, the value(s) passed as {query} to the next workflow action.
// Multiple values are allowed in Alfred 4.1 and later.
func (it *Item) Arg(s ...string) *Item {
it.arg = s
return it
}
// UID sets Item's unique ID, which is used by Alfred to remember your choices.
// Use a blank string to force results to appear in the order you add them.
//
// You can also use the SuppressUIDs() Option to (temporarily) suppress output of UIDs.
func (it *Item) UID(s string) *Item {
if it.noUID {
return it
}
it.uid = &s
return it
}
// Autocomplete sets what Alfred's query expands to when the user TABs result.
// (or hits RETURN on a result where valid is false)
func (it *Item) Autocomplete(s string) *Item {
it.autocomplete = &s
return it
}
// Valid tells Alfred whether the result is "actionable", i.e. ENTER will
// pass Arg to subsequent action.
func (it *Item) Valid(b bool) *Item {
it.valid = b
return it
}
// IsFile tells Alfred that this Item is a file, i.e. Arg is a path
// and Alfred's File Actions should be made available.
func (it *Item) IsFile(b bool) *Item {
it.file = b
return it
}
// Copytext is what CMD+C should copy instead of Arg (the default).
func (it *Item) Copytext(s string) *Item {
it.copytext = &s
return it
}
// Largetype is what is shown in Alfred's Large Text window on CMD+L
// instead of Arg (the default).
func (it *Item) Largetype(s string) *Item {
it.largetype = &s
return it
}
// Quicklook is a path or URL shown in a macOS Quicklook window on SHIFT
// or CMD+Y.
func (it *Item) Quicklook(s string) *Item {
it.ql = &s
return it
}
// Icon sets the icon for the Item.
// Can point to an image file, a filepath of a file whose icon should be used,
// or a UTI.
//
// See the documentation for Icon for more details.
func (it *Item) Icon(icon *Icon) *Item {
it.icon = icon
return it
}
// Var sets an Alfred variable for subsequent workflow elements.
func (it *Item) Var(k, v string) *Item {
if it.vars == nil {
it.vars = make(map[string]string, 1)
}
it.vars[k] = v
return it
}
// NewModifier returns an initialised Modifier bound to this Item.
// It also populates the Modifier with any workflow variables set in the Item.
//
// You must specify at least one modifier key. Alfred 3 only supports
// a single modifier, but Alfred 4+ allow them to be arbitrarily combined.
// Any invalid modifier keys are ignored. If you specify an unusable set of
// modifiers (i.e. they evaluate to ""), although a Modifier is returned,
// it is not retained by Item and will not be sent to Alfred. An error message
// is also logged.
func (it *Item) NewModifier(key ...ModKey) *Modifier {
m := newModifier(key...)
// Add Item variables to Modifier
if it.vars != nil {
for k, v := range it.vars {
m.Var(k, v)
}
}
it.SetModifier(m)
return m
}
// SetModifier sets a Modifier for a modifier key.
func (it *Item) SetModifier(m *Modifier) {
if m.Key == "" {
log.Printf("[ERROR] modifier has no key: %#v", m)
return
}
if it.mods == nil {
it.mods = map[ModKey]*Modifier{}
}
it.mods[m.Key] = m
}
// Cmd returns an initialised Modifier bound to this Item and the CMD (⌘) key.
func (it *Item) Cmd() *Modifier { return it.NewModifier(ModCmd) }
// Alt returns an initialised Modifier bound to this Item and the ALT/OPT (⌥) key.
func (it *Item) Alt() *Modifier { return it.NewModifier(ModAlt) }
// Opt is a synonym for Alt().
func (it *Item) Opt() *Modifier { return it.Alt() }
// Ctrl returns an initialised Modifier bound to this Item and the CTRL (^) key.
func (it *Item) Ctrl() *Modifier { return it.NewModifier(ModCtrl) }
// Shift returns an initialised Modifier bound to this Item and the SHIFT (⇧) key.
func (it *Item) Shift() *Modifier { return it.NewModifier(ModShift) }
// Fn returns an initialised Modifier bound to this Item and the fn key.
func (it *Item) Fn() *Modifier { return it.NewModifier(ModFn) }
// Vars returns the Item's workflow variables.
func (it *Item) Vars() map[string]string {
return it.vars
}
// MarshalJSON serializes Item to Alfred's JSON format.
// You shouldn't need to call this directly: use SendFeedback() instead.
func (it *Item) MarshalJSON() ([]byte, error) {
var (
typ string
ql string
text *itemText
)
if it.file {
typ = "file"
}
if it.ql != nil {
ql = *it.ql
}
if it.copytext != nil || it.largetype != nil {
text = &itemText{Copy: it.copytext, Large: it.largetype}
}
// Serialise Item
v := struct {
Title string `json:"title"`
Subtitle *string `json:"subtitle,omitempty"`
Match *string `json:"match,omitempty"`
Auto *string `json:"autocomplete,omitempty"`
Arg interface{} `json:"arg,omitempty"`
UID *string `json:"uid,omitempty"`
Valid bool `json:"valid"`
Type string `json:"type,omitempty"`
Text *itemText `json:"text,omitempty"`
Icon *Icon `json:"icon,omitempty"`
Quicklook string `json:"quicklookurl,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
Mods map[ModKey]*Modifier `json:"mods,omitempty"`
}{
Title: it.title,
Subtitle: it.subtitle,
Match: it.match,
Auto: it.autocomplete,
UID: it.uid,
Valid: it.valid,
Type: typ,
Text: text,
Icon: it.icon,
Quicklook: ql,
Variables: it.vars,
Mods: it.mods,
}
// serialise single arg as string
if len(it.arg) == 1 {
v.Arg = it.arg[0]
} else if len(it.arg) > 1 {
v.Arg = it.arg
}
return json.Marshal(v)
}
// itemText encapsulates the copytext and largetext values for a result Item.
type itemText struct {
// Copied to the clipboard on CMD+C
Copy *string `json:"copy,omitempty"`
// Shown in Alfred's Large Type window on CMD+L
Large *string `json:"largetype,omitempty"`
}
// Modifier encapsulates alterations to Item when a modifier key is held when
// the user actions the item.
//
// Create new Modifiers via Item.NewModifier(). This binds the Modifier to the
// Item, initializes Modifier's map and inherits Item's workflow variables.
// Variables are inherited at creation time, so any Item variables you set
// after creating the Modifier are not inherited.
type Modifier struct {
// The modifier key, e.g. "cmd", "alt".
// With Alfred 4+, modifiers can be combined, e.g. "cmd+alt", "ctrl+shift+cmd"
Key ModKey
arg []string
subtitle *string
valid bool
icon *Icon
vars map[string]string
}
// newModifier creates a Modifier, validating key.
func newModifier(key ...ModKey) *Modifier {
l := []string{}
for _, k := range key {
s := strings.TrimSpace(strings.ToLower(string(k)))
if s == "opt" {
s = "alt"
}
if s == "" {
continue
}
if s != "alt" && s != "cmd" && s != "ctrl" && s != "fn" && s != "shift" {
log.Printf("[warning] ignored invalid modifier %q", k)
continue
}
l = append(l, s)
}
sort.Strings(l)
s := strings.Join(l, "+")
return &Modifier{Key: ModKey(s), vars: map[string]string{}}
}
// Arg sets the arg for the Modifier. Multiple values are allowed in Alfred 4.1 and later.
func (m *Modifier) Arg(s ...string) *Modifier {
m.arg = s
return m
}
// Subtitle sets the subtitle for the Modifier.
func (m *Modifier) Subtitle(s string) *Modifier {
m.subtitle = &s
return m
}
// Valid sets the valid status for the Modifier.
func (m *Modifier) Valid(v bool) *Modifier {
m.valid = v
return m
}
// Icon sets an icon for the Modifier.
func (m *Modifier) Icon(i *Icon) *Modifier {
m.icon = i
return m
}
// Var sets a variable for the Modifier.
func (m *Modifier) Var(k, v string) *Modifier {
m.vars[k] = v
return m
}
// Vars returns all Modifier variables.
func (m *Modifier) Vars() map[string]string {
return m.vars
}
// MarshalJSON serializes Item to Alfred 3's JSON format.
// You shouldn't need to call this directly: use SendFeedback() instead.
func (m *Modifier) MarshalJSON() ([]byte, error) {
v := struct {
Arg interface{} `json:"arg,omitempty"`
Subtitle *string `json:"subtitle,omitempty"`
Valid bool `json:"valid,omitempty"`
Icon *Icon `json:"icon,omitempty"`
Variables map[string]string `json:"variables,omitempty"`
}{
Subtitle: m.subtitle,
Valid: m.valid,
Icon: m.icon,
Variables: m.vars,
}
// serialise single arg as string
if len(m.arg) == 1 {
v.Arg = m.arg[0]
} else if len(m.arg) > 1 {
v.Arg = m.arg
}
return json.Marshal(v)
}
// Feedback represents the results for an Alfred Script Filter.
//
// Normally, you won't use this struct directly, but via the Workflow methods
// NewItem(), SendFeedback(), etc. It is important to use the constructor
// functions for Feedback, Item and Modifier structs so they are properly
// initialised and bound to their parent.
type Feedback struct {
Items []*Item // The results to be sent to Alfred.
NoUIDs bool // If true, suppress Item UIDs.
rerun float64 // Tell Alfred to re-run Script Filter.
sent bool // Set to true when feedback has been sent.
vars map[string]string // Top-level feedback variables.
}
// NewFeedback creates a new, initialised Feedback struct.
func NewFeedback() *Feedback {
return &Feedback{Items: []*Item{}, vars: map[string]string{}}
}
// Var sets an Alfred variable for subsequent workflow elements.
func (fb *Feedback) Var(k, v string) *Feedback {
if fb.vars == nil {
fb.vars = make(map[string]string, 1)
}
fb.vars[k] = v
return fb
}
// Rerun tells Alfred to re-run the Script Filter after `secs` seconds.
func (fb *Feedback) Rerun(secs float64) *Feedback {
fb.rerun = secs
return fb
}
// Vars returns the Feedback's workflow variables.
func (fb *Feedback) Vars() map[string]string {
return fb.vars
}
// Clear removes any items.
func (fb *Feedback) Clear() {
if len(fb.Items) > 0 {
fb.Items = []*Item{}
}
}
// IsEmpty returns true if Feedback contains no items.
func (fb *Feedback) IsEmpty() bool { return len(fb.Items) == 0 }
// NewItem adds a new Item and returns a pointer to it.
//
// The Item inherits any workflow variables set on the Feedback parent at
// time of creation.
func (fb *Feedback) NewItem(title string) *Item {
it := &Item{title: title, vars: map[string]string{}, noUID: fb.NoUIDs}
// Add top-level variables to Item. The reason for this is
// that Alfred drops all item- and top-level variables on the
// floor if a modifier has any variables set (i.e. only the
// modifier's variables are retained).
// So, add top-level variables to Item (and in turn to any Modifiers)
// to enforce more sensible behaviour.
for k, v := range fb.vars {
it.vars[k] = v
}
fb.Items = append(fb.Items, it)
return it
}
// MarshalJSON serializes Feedback to Alfred's JSON format.
// You shouldn't need to call this: use Send() instead.
func (fb *Feedback) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Variables map[string]string `json:"variables,omitempty"`
Rerun float64 `json:"rerun,omitempty"`
Items []*Item `json:"items"`
}{
Items: fb.Items,
Rerun: fb.rerun,
Variables: fb.vars,
})
}
// Send generates JSON from this struct and sends it to Alfred
// (by writing the JSON to STDOUT).
//
// You shouldn't need to call this directly: use SendFeedback() instead.
func (fb *Feedback) Send() error {
if fb.sent {
log.Printf("Feedback already sent. Ignoring.")
return nil
}
output, err := json.MarshalIndent(fb, "", " ")
if err != nil {
return fmt.Errorf("Error generating JSON : %w", err)
}
os.Stdout.Write(output)
fb.sent = true
log.Printf("Sent %d result(s) to Alfred", len(fb.Items))
return nil
}
// Sort sorts Items against query. Uses a fuzzy.Sorter with the specified
// options.
func (fb *Feedback) Sort(query string, opts ...fuzzy.Option) []*fuzzy.Result {
s := fuzzy.New(fb, opts...)
return s.Sort(query)
}
// Filter fuzzy-sorts Items against query and deletes Items that don't match.
// It returns a slice of Result structs, which contain the results of the
// fuzzy sorting.
func (fb *Feedback) Filter(query string, opts ...fuzzy.Option) []*fuzzy.Result {
var items []*Item
var res []*fuzzy.Result
r := fb.Sort(query, opts...)
for i, it := range fb.Items {
if r[i].Match {
items = append(items, it)
res = append(res, r[i])
}
}
fb.Items = items
return res
}
// Keywords implements fuzzy.Sortable.
//
// Returns the match or title field for Item i.
func (fb *Feedback) Keywords(i int) string {
it := fb.Items[i]
// Sort on title if match isn't set
if it.match != nil {
return *it.match
}
return it.title
}
// Len implements sort.Interface.
func (fb *Feedback) Len() int { return len(fb.Items) }
// Less implements sort.Interface.
func (fb *Feedback) Less(i, j int) bool { return fb.Keywords(i) < fb.Keywords(j) }
// Swap implements sort.Interface.
func (fb *Feedback) Swap(i, j int) { fb.Items[i], fb.Items[j] = fb.Items[j], fb.Items[i] }
// ArgVars lets you set workflow variables from Run Script actions.
// It emits the arg and variables you set in the format required by Alfred.
//
// Use ArgVars.Send() to pass variables to downstream workflow elements.
type ArgVars struct {
arg []string
vars map[string]string
}
// NewArgVars returns an initialised ArgVars object.
func NewArgVars() *ArgVars {
return &ArgVars{vars: map[string]string{}}
}
// Arg sets the arg(s)/query to be passed to the next workflow action.
// Multiple values are allowed in Alfred 4.1 and later.
func (a *ArgVars) Arg(s ...string) *ArgVars {
a.arg = s
return a
}
// Vars returns ArgVars' variables.
func (a *ArgVars) Vars() map[string]string {
return a.vars
}
// Var sets the value of a workflow variable.
func (a *ArgVars) Var(k, v string) *ArgVars {
a.vars[k] = v
return a
}
// String returns a string representation.
//
// If any variables are set, JSON is returned. Otherwise, a plain string
// is returned.
func (a *ArgVars) String() (string, error) {
if len(a.vars) == 0 && len(a.arg) < 2 {
if len(a.arg) == 0 {
return "", nil
}
return a.arg[0], nil
}
// Vars set, so return as JSON
data, err := a.MarshalJSON()
if err != nil {
return "", err
}
return string(data), nil
}
// Send outputs arg and variables to Alfred by printing a response to STDOUT.
func (a *ArgVars) Send() error {
data, err := a.MarshalJSON()
if err != nil {
return err
}
_, err = fmt.Print(string(data))
return err
}
// MarshalJSON serialises ArgVars to JSON.
// You probably don't need to call this: use ArgVars.Send() instead.
func (a *ArgVars) MarshalJSON() ([]byte, error) {
// Return arg regardless of whether it's empty or not:
// we have to return *something*
if len(a.vars) == 0 && len(a.arg) < 2 {
// Want empty string, i.e. "", not null
if len(a.arg) == 0 {
return []byte(`""`), nil
}
return json.Marshal(a.arg[0])
}
v := struct {
Arg interface{} `json:"arg,omitempty"`
Vars map[string]string `json:"variables,omitempty"`
}{
Vars: a.vars,
}
if len(a.arg) == 1 {
v.Arg = a.arg[0]
} else if len(a.arg) > 1 {
v.Arg = a.arg
}
return json.Marshal(&struct {
Root interface{} `json:"alfredworkflow"`
}{
Root: v,
})
}