-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtui.go
More file actions
591 lines (484 loc) · 14.8 KB
/
tui.go
File metadata and controls
591 lines (484 loc) · 14.8 KB
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
// TUI for basic file/directory navigation
//
// The Browser can exist in one of three states (Modes). Each state leverages
// the same list-based TUI to present a (different) set of items to the user:
//
// 1. Queue: paths of depth 2, typically loaded from a (local) file
// 2. Artists: immediate children directories of root, generated via traversal
// 3. Albums: directories under an artist (i.e. depth 2)
//
// The lists are implemented as a simple fzf-like menu with basic non-fuzzy
// substring matching.
//
// For simplicity of rendering, all items must be valid directories, relative
// to the library root. On selecting an item, the Browser transitions to the
// next state, crudely represented by the following finite state machine:
//
// ┌──────┐
// │start │
// │ │
// └──────┘
// │
// ▼
// ┌────────┐
// │ queue │
// │ │
// └────────┘
// │ │ ▲
// ┌─────┘ │ └─┐
// │ │ │
// (tab) │ │
// │ │ │
// ▼ │ add
// ┌────────┐ play │
// │artists │ │ │
// │ │ │ │
// └────────┘ │ │
// │ │ │
// play │ │
// │ │ │
// └─────┐ │ ┌┘
// │ │ │
// ▼ ▼ │
// ┌─────────┐
// │ albums │
// │ │
// └─────────┘
//
// - playback (and the associated post-playback actions) is always blocking
// - on startup, Queue and Artists modes are available
// - only Queue mode can (and must) transition to playback
// - Artists mode transitions to Albums mode, then always exits
// - the program can be gracefully exited in any Mode
// start -> queue
// queue -> artists: (tab)
// albums -> queue: add
// queue -> albums: play
// artists -> albums: play
package main
import (
"log"
"os"
"path"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/list"
"github.com/charmbracelet/x/term"
)
// https://leg100.github.io/en/posts/building-bubbletea-programs/
var IsSelected = map[bool]string{
true: "→",
false: " ",
}
var IsQueued = map[bool]string{
true: "Q",
false: " ",
}
type Mode int
const (
Queue Mode = iota
Artists
Albums
)
// mostly copied from https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics
type Browser struct {
mode Mode
items []string // valid relpaths
queued map[string]bool // keys correspond to items
previews map[string][]string // keys correspond to items
// c chan string
// if true, the user is allowed to back out of a Queue selection
// without quitting the program
noQuit bool // may only be true in Albums mode?
width int
height int
offset int
cursor int
input string
matches []int
}
// All items must be valid relpaths (relative to root)
func newBrowser(items []string, mode Mode) *Browser {
// t := time.Now()
// defer logTime(t, "newBrowser") // microseconds
// TODO: on cold start, slow os.Stat prevents View from being called
defer timer("cold stat")()
// putting this in a goroutine does not prevent blocking (unless the
// newBrowser call itself is also async). in any case, this is just a
// guard rail which i intend to remove sooner or later
go checkRelPaths(items)
// init window correctly; a "recursively" spawned Browser is
// initialised with zeroed dimensions!
width, height, err := term.GetSize(os.Stdout.Fd())
if err != nil {
panic("failed to get terminal size")
}
return &Browser{
mode: mode,
items: items,
matches: intRange(len(items)),
// c: make(chan string),
width: width,
height: height,
}
}
// TODO: group the 3 funcs into one: notice that Albums needs a string arg, and
// Queue needs an int arg. these args could be passed as a struct
// type BrowserOpts struct {
// mode Mode
// queue int // number of items to sample
// artist string
// }
var firstRun = true
// waitMsg sync.Once
// This is almost always the first Browser to be loaded.
func queueBrowser() *Browser {
// waitMsg.Do(func() {
// timer := time.NewTimer(time.Second * 2)
// defer timer.Stop()
// go func() {
// fmt.Println("please wait...", <-timer.C)
// }()
// })
var b *Browser
if firstRun {
firstRun = false
// resume should only be true on the first invocation (i.e. on startup)
if resumes := getResumes(); len(resumes) > 0 { // TODO: Once.Do
// TODO: reduce latency in newBrowser
b = newBrowser(resumes, Queue)
b.noQuit = true
return b
}
}
return newBrowser(getQueue(config.NQueue), Queue)
}
func artistBrowser() *Browser {
// always finishes within 5 ms, because bigrams are constructed in
// background
// note: we never want to dump the directory tree into a separate db,
// because of staleness concerns
items, _ := descend(config.Library.Root)
bigramOnce.Do(func() { go func() { Bigrams = makeBigrams(items) }() })
return newBrowser(items, Artists)
}
// Browser.items will be sorted by year.
func albumsBrowser(artist string) *Browser {
// more complex since we need to check queue and populate the `queued`
// field
allQueued := make(map[string]any)
for _, x := range getQueue(0) {
allQueued[x] = nil
}
// TODO: the rest is i/o; could be goroutine'd?
albums, err := descend(filepath.Join(config.Library.Root, artist))
if err != nil {
panic(err)
}
sortByYear(albums)
items := []string{}
// int keys are much easier to index (for View), but require correct sort
// // queued := make(map[int]bool)
queued := make(map[string]bool)
previews := make(map[string][]string)
for _, alb := range albums {
// newBrowser requires valid relpaths
relpath := filepath.Join(artist, alb)
fullpath := filepath.Join(config.Library.Root, relpath)
items = append(items, relpath) // small len, growing slice is probably fine
_, q := allQueued[relpath]
queued[relpath] = q
p, err := descend(fullpath)
if err != nil {
panic(err)
}
previews[relpath] = p
}
b := newBrowser(items, Albums)
b.queued = queued
b.previews = previews
return b
}
func (b *Browser) updateSearch() {
// https://github.com/antonmedv/walk/blob/ba821ed78f31e0ebd46eeef19cfe642fc1ec4330/main.go#L427
// note the pointer; we are mutating Browser
switch {
case b.input == "":
// return all indices
b.matches = intRange(len(b.items))
return
case b.mode == Albums:
// b.items is relpath, but we want basenames
b.matches = searchSubstring(Map(b.items, filepath.Base), b.input)
case len(b.items) > 10000 && len(Bigrams) == 676:
// note: strings.Contains uses Rabin-Karp (O(n)). without
// resorting to faster string search algos (e.g. KMP/BM/AC), a
// simple cached map of bigrams is a fairly easy 8x speedup
b.matches = searchSubstringBigram(b.items, b.input)
default:
b.matches = searchSubstring(b.items, b.input)
}
if len(b.matches) > 0 {
b.cursor = 0
}
}
// Init initialises Browser. items must already have been initialised.
func (b *Browser) Init() tea.Cmd {
// t := time.Now()
// defer logTime(t, "Browser.Init") // micro
if b.mode == Queue {
go func() {
previews := make(map[string][]string)
for _, item := range b.items {
p, err := descend(item)
if err != nil {
continue
}
previews[item] = p
}
b.previews = previews
}()
}
return nil
}
func (b *Browser) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // {{{
// log.Println("msg:", msg) // not terribly informative
// artist may have been deleted after playback
if b.mode == Albums {
sel := b.items[0]
artist := strings.Split(sel, "/")[0]
if _, err := os.Stat(filepath.Join(config.Library.Root, artist)); err != nil {
return queueBrowser(), tea.ClearScreen
}
}
// // https://leg100.github.io/en/posts/building-bubbletea-programs/
// spew.Fdump(b.dump, msg)
// notice this (subtle) reassignment
switch msg := msg.(type) {
// https://github.com/charmbracelet/bubbletea/discussions/818#discussioncomment-6914769
case tea.WindowSizeMsg:
if msg.Width != b.width {
// first Update call always involves a WindowSizeMsg,
// even when dims are correctly initialised. allowing a
// ClearScreen leads to an unnecessary (and unsightly)
// re-render
// TODO: when we are in a new state, should also
// ClearScreen
b.width = msg.Width
b.height = msg.Height
return b, tea.ClearScreen
}
case tea.KeyMsg:
if len(b.matches) > 0 && // prevent further input when no matches
msg.Type == tea.KeyRunes || msg.String() == " " {
b.input += string(msg.Runes)
b.updateSearch()
return b, nil
}
// TODO: consider using `bubbles/key` for key.Matches()
// https://github.com/antonmedv/walk/blob/ba821ed78f31e0ebd46eeef19cfe642fc1ec4330/main.go#L252
switch msg.String() {
case "ctrl+t", "tab":
// TODO: else -> queue?
if !mpvRunning() && b.mode == Queue {
return artistBrowser(), nil
}
case "ctrl+w": // delete last word
i := strings.LastIndex(b.input, " ")
if i+1 == len(b.input) { // only one word (with trailing space)
b.input = ""
} else {
b.input = b.input[:i+1]
}
b.updateSearch()
return b, nil
case "ctrl+c", "esc", "ctrl+\\":
// os.Exit(0) // ungraceful exit
// return nil, tea.Quit // bad pointer!
// allow just going back to Queue
if b.noQuit {
return queueBrowser(), nil
}
// TODO: why so slow?
// log.Println("quitting", os.Getpid())
return b, tea.Quit // graceful exit
case "backspace":
if len(b.input) > 0 {
b.input = b.input[:len(b.input)-1]
b.updateSearch()
}
case "up", "ctrl+k":
b.cursor--
if b.cursor < 0 {
b.cursor = len(b.matches) - 1
}
// note: pgup/pgdown still janky, but ime it is usually
// faster/more intuitive to just filter until the results fit
// in a page
case "pgup":
b.cursor = 0
b.offset -= b.height
case "pgdown":
b.cursor = 0
b.offset += b.height
case "down", "ctrl+j":
b.cursor++
if b.cursor > len(b.matches)-1 {
b.cursor = 0
}
// if b.cursor > b.height {
// b.offset = b.cursor - b.height
// }
// https://github.com/antonmedv/walk/blob/ba821ed78f31e0ebd46eeef19cfe642fc1ec4330/main.go#L259 (?)
case "enter":
if len(b.matches) == 0 {
return b, nil // do nothing
}
return b.getNewState()
}
// default:
// return b, nil
}
// panic("unreachable")
return b, nil
} // }}}
// Artists -> Albums
// Queue -> Albums
// Albums -> play -> Queue
func (b *Browser) getNewState() (*Browser, tea.Cmd) {
pos := b.matches[b.cursor]
// TODO: sel may not end with newline?
sel := b.items[pos] // relpath
switch b.mode {
case Artists:
return albumsBrowser(sel), tea.ClearScreen
case Queue: // `play` album, then start View in Albums mode
// note: we need to split artist here (even though we do it
// again in `play`)
ensure(strings.Contains(sel, "/"))
artist := strings.Split(sel, "/")[0]
nb := albumsBrowser(artist)
nb.noQuit = true
// sel will be removed from queue file -after- play, but since
// we don't re-read the queue file, need to remove here
// TODO: the queue is not recalculated, so new additions will
// not appear
nb.queued[sel] = false
if !exists(filepath.Join(config.Library.Root, sel)) {
log.Println("dir was deleted:", sel)
q := getQueue(0)
nq := remove(&q, sel)
writeQueue(*nq)
return queueBrowser(), tea.ClearScreen
}
return nb, play(sel)
// // this will not play!
// return nb, func() tea.Msg {
// play(sel)
// // update queue?
// return nil
// }
case Albums:
queueSelectedAlbum := func() {
if exists(filepath.Join(config.Library.Root, sel)) {
q := getQueue(0)
nq := append(q, sel)
ensure(len(nq)-len(q) == 1)
writeQueue(nq)
log.Println("queued:", sel)
}
}
if mpvRunning() {
queueSelectedAlbum()
return b, tea.Quit
}
if firstRun { // only reachable via <tab> in queue mode
log.Println("playing on demand:", sel)
firstRun = false
return queueBrowser(), play(sel)
}
queueSelectedAlbum()
return queueBrowser(), tea.ClearScreen
default:
panic("Invalid state")
}
}
// View constructs a screen split into 2 vertical panes, with preview window on
// right.
func (b *Browser) View() string {
// t := time.Now()
// defer logTime(t, "Browser.View") // 0.0001 s
// The TUI is not very appealing, but this is ~by design~, as 1) I
// really don't care about styling, 2) most of the time is spent in
// mpv, and 3) the program is meant to just get out of the way and not
// be distracting.
//
// [input]
// [item1]|[preview1]
// [item2]|[preview2]
// ... |...
// (where | represents the border)
// log.Println("view:", b)
// https://github.com/charmbracelet/bubbletea/blob/master/examples/split-editors/main.go
if len(b.matches) == 0 {
return "no matches; please clear input"
}
sel := b.items[b.matches[b.cursor]]
// TODO: another struct field?
enu := func(_ list.Items, index int) string {
return IsSelected[index == b.cursor]
}
// note: we use the simpler lipgloss/list; consider trying the more
// feature-rich bubbles/list. filtering is built in to the list itself,
// so we don't have to keep it in the Browser
// https://github.com/charmbracelet/bubbles/blob/master/list/list.go
leftItems := list.New().Enumerator(enu)
anyQueued := b.mode == Albums && anyValue(b.queued)
for i, idx := range b.matches {
if i < b.offset {
continue
}
item := b.items[idx] // idx is the actual index that points to the item
switch {
case anyQueued:
base := path.Base(item)
item = IsQueued[b.queued[item]] + " " + base
leftItems.Item(item) // inplace
case b.mode == Albums:
base := path.Base(item)
leftItems.Item(base)
default:
leftItems.Item(item)
}
}
rightItems := list.New().Enumerator(func(_ list.Items, _ int) string { return "" })
preview, ok := b.previews[sel]
p := filepath.Join(config.Library.Root, sel)
previews, err := descend(p)
switch {
case ok: // usually only in Albums mode
rightItems.Items(preview)
case err != nil:
rightItems.Item("error")
default:
rightItems.Items(previews)
}
panes := lipgloss.JoinHorizontal(
lipgloss.Top,
lipgloss.NewStyle().
// Inline(true). // forces multiline string back to single line
Width(b.width*3/5). // takes priority over right
// important: Height prioritises displaying last items,
// MaxHeight prioritises displaying first items
MaxHeight(b.height-3).
Render(leftItems.String()),
lipgloss.NewStyle().
MaxHeight(b.height-3). // should always be MaxHeight, never Height
BorderLeft(true). // if omitted, assumes full border
BorderStyle(lipgloss.NormalBorder()).
Render(rightItems.String()),
)
return lipgloss.JoinVertical(lipgloss.Left, b.input, panes)
}