« get me outta code hell

ui.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/ui.js
blob: 5177aed612041236fcf977fc557f3b6c0c55a5ed (plain)
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
const { getDownloaderFor } = require('./downloaders')
const { getPlayer } = require('./players')
const { parentSymbol, isGroup } = require('./playlist-utils')
const ansi = require('./tui-lib/util/ansi')
const Button = require('./tui-lib/ui/form/Button')
const DisplayElement = require('./tui-lib/ui/DisplayElement')
const FocusElement = require('./tui-lib/ui/form/FocusElement')
const Form = require('./tui-lib/ui/form/Form')
const Label = require('./tui-lib/ui/Label')
const ListScrollForm = require('./tui-lib/ui/form/ListScrollForm')
const Pane = require('./tui-lib/ui/Pane')
const RecordStore = require('./record-store')
const telc = require('./tui-lib/util/telchars')

class AppElement extends FocusElement {
  constructor() {
    super()

    this.player = null
    this.recordStore = new RecordStore()
    this.queueGrouplike = {isTheQueue: true, items: []}


    this.form = new Form()
    this.addChild(this.form)

    this.paneLeft = new Pane()
    this.form.addChild(this.paneLeft)

    this.paneRight = new Pane()
    this.form.addChild(this.paneRight)

    this.grouplikeListingElement = new GrouplikeListingElement(this.recordStore)
    this.paneLeft.addChild(this.grouplikeListingElement)
    this.form.addInput(this.grouplikeListingElement, false)

    const handleSelectFromMain = item => {
      if (isGroup(item)) {
        this.grouplikeListingElement.loadGrouplike(item)
      } else {
        this.playGrouplikeItem(item)
      }
    }

    this.grouplikeListingElement.on('download', item => this.downloadGrouplikeItem(item))
    this.grouplikeListingElement.on('select (enter)', item => handleSelectFromMain(item))
    this.grouplikeListingElement.on('select (space)', item => this.handleSpacePressed(
      () => handleSelectFromMain(item)))
    this.grouplikeListingElement.on('queue', item => this.queueGrouplikeItem(item))

    this.queueListingElement = new GrouplikeListingElement(this.recordStore)
    this.queueListingElement.loadGrouplike(this.queueGrouplike)
    this.paneRight.addChild(this.queueListingElement)
    this.form.addInput(this.queueListingElement, false)

    this.queueListingElement.on('select (enter)', item => this.playGrouplikeItem(item))
    this.queueListingElement.on('select (space)', item => this.handleSpacePressed(
      () => this.playGrouplikeItem(item)))

    this.playbackPane = new Pane()
    this.addChild(this.playbackPane)

    this.playbackInfoElement = new PlaybackInfoElement()
    this.playbackPane.addChild(this.playbackInfoElement)
  }

  async setup() {
    this.player = await getPlayer()
    this.player.on('printStatusLine', data => {
      this.playbackInfoElement.updateProgress(data)
    })
  }

  async shutdown() {
    await this.player.kill()
    this.emit('quitRequested')
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = this.parent.contentH

    this.paneLeft.w = Math.max(Math.floor(0.8 * this.contentW), this.contentW - 80)
    this.paneLeft.h = this.contentH - 5
    this.paneRight.x = this.paneLeft.right
    this.paneRight.w = this.contentW - this.paneLeft.right
    this.paneRight.h = this.paneLeft.h
    this.playbackPane.y = this.paneLeft.bottom
    this.playbackPane.w = this.contentW
    this.playbackPane.h = this.contentH - this.playbackPane.y

    this.grouplikeListingElement.fillParent()
    this.queueListingElement.fillParent()
    this.playbackInfoElement.fillParent()
  }

  keyPressed(keyBuf) {
    if (keyBuf[0] === 0x03) {
      this.shutdown()
      return
    }

    if (telc.isRight(keyBuf) || telc.isCaselessLetter(keyBuf, 'l')) {
      this.seekAhead(10)
    } else if (telc.isLeft(keyBuf) || telc.isCaselessLetter(keyBuf, 'j')) {
      this.seekBack(10)
    } else if (telc.isCaselessLetter(keyBuf, 'p') || telc.isCaselessLetter(keyBuf, 'k')) {
      this.togglePause()
    } else if (telc.isShiftUp(keyBuf)) {
      this.playPreviousTrack(this.playingTrack)
    } else if (telc.isShiftDown(keyBuf)) {
      this.playNextTrack(this.playingTrack)
    } else {
      super.keyPressed(keyBuf)
    }
  }

  handleSpacePressed(callback) {
    // Pauses/resumes if a track is currently playing; otherwise, calls the
    // callback function.

    if (this.playingTrack) {
      this.togglePause()
    } else {
      return callback()
    }
  }

  seekAhead(seconds) {
    this.player.seekAhead(seconds)
  }

  seekBack(seconds) {
    this.player.seekBack(seconds)
  }

  togglePause() {
    this.player.togglePause()
  }

  async queueGrouplikeItem(topItem, play = true, afterItem = null) {
    const newTrackIndex = this.queueGrouplike.items.length

    const recursivelyAddTracks = item => {
      // For groups, just queue all children.
      if (isGroup(item)) {
        for (const child of item.items) {
          recursivelyAddTracks(child)
        }

        return
      }

      const items = this.queueGrouplike.items

      // You can't put the same track in the queue twice - we automatically
      // remove the old entry. (You can't for a variety of technical reasons,
      // but basically you either have the display all bork'd, or new tracks
      // can't be added to the queue in the right order (because Object.assign
      // is needed to fix the display, but then you end up with a new object
      // that doesn't work with indexOf).)
      if (items.includes(item)) {
        items.splice(items.indexOf(item), 1)
      }

      if (afterItem === 'FRONT') {
        items.unshift(item)
      } else if (afterItem && items.includes(afterItem)) {
        items.splice(items.indexOf(afterItem) + 1, 0, item)
      } else {
        items.push(item)
      }
    }

    recursivelyAddTracks(topItem)
    this.queueListingElement.buildItems()

    // This is the first new track, if a group was queued.
    const newTrack = this.queueGrouplike.items[newTrackIndex]
    if (play && !this.playingTrack && newTrack) {
      this.playGrouplikeItem(newTrack, false)
    }
  }

  async downloadGrouplikeItem(item) {
    if (isGroup(item)) {
      // TODO: Download all children (recursively), show a confirmation prompt
      // if there are a lot of items (remember to flatten).
      return
    }

    const arg = item.downloaderArg
    this.recordStore.getRecord(item).downloading = true
    try {
      return await getDownloaderFor(arg)(arg)
    } finally {
      this.recordStore.getRecord(item).downloading = false
    }
  }

  async playGrouplikeItem(item, shouldQueue = true) {
    if (this.player === null) {
      throw new Error('Attempted to play before a player was loaded')
    }

    let playingThisTrack = true
    this.emit('playing new track')
    this.once('playing new track', () => {
      playingThisTrack = false
    })

    if (shouldQueue) {
      this.queueGrouplikeItem(item, false, this.playingTrack)
    }

    // TODO: Check if it's an item or a group

    // If, by the time the track is downloaded, we're playing something
    // different from when the download started, assume that we just want to
    // keep listening to whatever new thing we started.

    const oldTrack = this.playingTrack

    const downloadFile = await this.downloadGrouplikeItem(item)

    if (this.playingTrack !== oldTrack) {
      return
    }

    await this.player.kill()
    this.recordStore.getRecord(item).playing = true
    this.playingTrack = item
    this.playbackInfoElement.updateTrack(item)
    if (!this.queueListingElement.isSelected) {
      this.queueListingElement.selectAndShow(item)
    }
    try {
      await this.player.playFile(downloadFile)
    } finally {
      if (playingThisTrack || this.playingTrack !== item) {
        this.recordStore.getRecord(item).playing = false
      }
    }

    // playingThisTrack now means whether the track played through to the end
    // (true), or was stopped by a different track being started (false).

    if (playingThisTrack) {
      this.playingTrack = null
      this.playNextTrack(item)
    }
  }

  playNextTrack(track) {
    const queue = this.queueGrouplike
    let queueIndex = queue.items.indexOf(track)
    if (queueIndex === -1) {
      queueIndex = queue.items.length
    }
    queueIndex++

    if (queueIndex >= queue.items.length) {
      const parent = track[parentSymbol]
      if (!parent) {
        return
      }
      const index = parent.items.indexOf(track)
      const nextItem = parent.items[index + 1]
      if (!nextItem) {
        return
      }
      this.queueGrouplikeItem(nextItem, false)
      queueIndex = queue.items.length - 1
    }

    this.playGrouplikeItem(queue.items[queueIndex], false)
  }

  playPreviousTrack(track) {
    const queue = this.queueGrouplike
    let queueIndex = queue.items.indexOf(track)
    if (queueIndex === -1) {
      queueIndex = queue.items.length
    }
    queueIndex--

    if (queueIndex < 0) {
      const parent = track[parentSymbol]
      if (!parent) {
        return
      }
      const index = parent.items.indexOf(track)
      const previousItem = parent.items[index - 1]
      if (!previousItem) {
        return
      }
      this.queueGrouplikeItem(previousItem, false, 'FRONT')
      queueIndex = 0
    }

    this.playGrouplikeItem(queue.items[queueIndex], false)
  }
}

class GrouplikeListingElement extends ListScrollForm {
  constructor(recordStore) {
    super('vertical')

    this.captureTab = false

    this.grouplike = null
    this.recordStore = recordStore
  }

  loadGrouplike(grouplike) {
    this.grouplike = grouplike
    this.buildItems(true)
  }

  buildItems(resetIndex = false) {
    if (!this.grouplike) {
      throw new Error('Attempted to call buildItems before a grouplike was loaded')
    }

    const wasSelected = this.isSelected

    while (this.inputs.length) {
      this.removeInput(this.inputs[0])
    }

    const parent = this.grouplike[parentSymbol]
    if (parent) {
      const upButton = new Button('Up (to ' + (parent.name || 'unnamed group') + ')')
      upButton.on('pressed', () => {
        const oldGrouplike = this.grouplike
        this.loadGrouplike(parent)
        this.curIndex = this.inputs.findIndex(inp => inp.item === oldGrouplike) || this.firstItemIndex
        this.updateSelectedElement()
        this.scrollSelectedElementIntoView()
      })
      this.addInput(upButton)
    }

    if (this.grouplike.items.length) {
      for (const item of this.grouplike.items) {
        const itemElement = new GrouplikeItemElement(item, this.recordStore)
        itemElement.on('download', () => this.emit('download', item))
        itemElement.on('select (space)', () => this.emit('select (space)', item))
        itemElement.on('select (enter)', () => this.emit('select (enter)', item))
        itemElement.on('queue', () => this.emit('queue', item))
        this.addInput(itemElement)
      }
    } else if (!this.grouplike.isTheQueue) {
      this.addInput(new Button('(No items in this group)'))
    }

    if (wasSelected) {
      if (resetIndex) {
        this.curIndex = this.firstItemIndex
        this.scrollItems = 0
        this.updateSelectedElement()
      } else {
        this.root.select(this)
      }
    }

    this.fixLayout()
  }

  selectAndShow(item) {
    const index = this.inputs.findIndex(inp => inp.item === item)
    if (index >= 0) {
      this.curIndex = index
      if (this.isSelected) {
        this.updateSelectedElement()
      }
      this.scrollSelectedElementIntoView()
    }
  }

  get firstItemIndex() {
    return Math.min(this.inputs.length, 1)
  }

  get isSelected() {
    return this.root.selected && this.root.selected.directAncestors.includes(this)
  }

}

class GrouplikeItemElement extends Button {
  constructor(item, recordStore) {
    super()

    this.item = item
    this.recordStore = recordStore
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = 1
  }

  drawTo(writable) {
    if (this.isFocused) {
      writable.write(ansi.invert())
    }

    writable.write(ansi.moveCursor(this.absTop, this.absLeft))

    if (isGroup(this.item)) {
      writable.write(ansi.setAttributes([ansi.C_BLUE, ansi.A_BRIGHT]))
    }

    this.drawX = this.x
    this.writeStatus(writable)
    writable.write(this.item.name.slice(0, this.w - this.drawX))
    this.drawX += this.item.name.length
    writable.write(' '.repeat(Math.max(0, this.w - this.drawX)))

    writable.write(ansi.resetAttributes())
  }

  writeStatus(writable) {
    this.drawX += 3

    const braille = '⠈⠐⠠⠄⠂⠁'
    const brailleChar = braille[Math.floor(Date.now() / 250) % 6]

    const record = this.recordStore.getRecord(this.item)

    writable.write(' ')
    if (isGroup(this.item)) {
      writable.write('G')
    } else if (record.downloading) {
      writable.write(braille[Math.floor(Date.now() / 250) % 6])
    } else if (record.playing) {
      writable.write('\u25B6')
    } else {
      writable.write(' ')
    }
    writable.write(' ')
  }

  keyPressed(keyBuf) {
    // TODO: Helper function for this
    if (telc.isCaselessLetter(keyBuf, 'd')) {
      this.emit('download')
    } else if (telc.isCaselessLetter(keyBuf, 'q')) {
      this.emit('queue')
    } else if (telc.isSpace(keyBuf)) {
      this.emit('select (space)')
    } else if (telc.isEnter(keyBuf)) {
      this.emit('select (enter)')
    }
  }
}

class PlaybackInfoElement extends DisplayElement {
  constructor() {
    super()

    this.progressBarLabel = new Label('')
    this.addChild(this.progressBarLabel)

    this.progressTextLabel = new Label('')
    this.addChild(this.progressTextLabel)

    this.trackNameLabel = new Label('')
    this.addChild(this.trackNameLabel)

    this.downloadLabel = new Label('')
    this.addChild(this.downloadLabel)
  }

  fixLayout() {
    const centerX = el => el.x = Math.round((this.w - el.w) / 2)
    centerX(this.progressTextLabel)
    centerX(this.trackNameLabel)
    centerX(this.downloadLabel)

    this.trackNameLabel.y = 0
    this.progressBarLabel.y = 1
    this.progressTextLabel.y = this.progressBarLabel.y
    this.downloadLabel.y = 2
  }

  updateProgress({timeDone, timeLeft, duration, lenSecTotal, curSecTotal}) {
    this.progressBarLabel.text = '-'.repeat(Math.floor(this.w / lenSecTotal * curSecTotal))
    this.progressTextLabel.text = timeDone + ' / ' + duration
    this.fixLayout()
  }

  updateTrack(track) {
    this.trackNameLabel.text = track.name
    this.downloadLabel.text = `(From: ${track.downloaderArg})`
    this.fixLayout()
  }
}

module.exports.AppElement = AppElement