« 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: a20fb52ae79c1befe50954e2dbc30eb95e520c55 (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
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
const { getDownloaderFor } = require('./downloaders')
const { getPlayer } = require('./players')
const { parentSymbol, isGroup, isTrack, getItemPath, getItemPathString } = require('./playlist-utils')
const { shuffleArray } = require('./general-util')
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 WrapLabel = require('./tui-lib/ui/WrapLabel')
const telc = require('./tui-lib/util/telchars')
const unic = require('./tui-lib/util/unichars')

const fs = require('fs')
const { promisify } = require('util')
const writeFile = promisify(fs.writeFile)

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

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

    this.rootDirectory = process.env.HOME + '/.mtui'

    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))

    const handleSelectFromPathElement = item => {
      this.form.selectInput(this.grouplikeListingElement)
      if (isGroup(item)) {
        this.grouplikeListingElement.loadGrouplike(item)
      } else if (item[parentSymbol]) {
        this.grouplikeListingElement.loadGrouplike(item[parentSymbol])
        this.grouplikeListingElement.selectAndShow(item)
      }
    }

    this.form.addInput(this.grouplikeListingElement.pathElement, false)
    this.grouplikeListingElement.pathElement.on('select', item => handleSelectFromPathElement(item))

    this.queueListingElement = new QueueListingElement(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, false))
    this.queueListingElement.on('select (space)', item => this.handleSpacePressed(
      () => this.playGrouplikeItem(item, false)))
    this.queueListingElement.on('remove', item => this.unqueueGrouplikeItem(item))
    this.queueListingElement.on('shuffle', () => this.shuffleQueue())
    this.queueListingElement.on('clear', () => this.clearQueue())
    this.queueListingElement.on('select main listing',
      () => this.form.selectInput(this.grouplikeListingElement))

    this.form.addInput(this.queueListingElement.pathElement, false)
    this.queueListingElement.pathElement.on('select', item => handleSelectFromPathElement(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.isEscape(keyBuf)) {
      this.clearPlayingTrack()
    } else if (telc.isShiftUp(keyBuf)) {
      this.playPreviousTrack(this.playingTrack)
    } else if (telc.isShiftDown(keyBuf)) {
      this.playNextTrack(this.playingTrack)
    } else if (telc.isCharacter(keyBuf, '1') && this.grouplikeListingElement.selectable) {
      this.form.curIndex = this.form.inputs.indexOf(this.grouplikeListingElement)
      this.form.updateSelectedElement()
    } else if (telc.isCharacter(keyBuf, '2') && this.queueListingElement.selectable) {
      this.form.curIndex = this.form.inputs.indexOf(this.queueListingElement)
      this.form.updateSelectedElement()
    } else {
      super.keyPressed(keyBuf)
    }
  }

  shuffleQueue() {
    const queue = this.queueGrouplike
    const index = queue.items.indexOf(this.playingTrack) + 1 // This is 0 if no track is playing
    const initialItems = queue.items.slice(0, index)
    const remainingItems = queue.items.slice(index)
    const newItems = initialItems.concat(shuffleArray(remainingItems))
    queue.items = newItems
    this.queueListingElement.buildItems()
  }

  clearQueue() {
    this.queueGrouplike.items = []
    this.queueListingElement.buildItems()
    this.queueListingElement.pathElement.showItem(null)
  }

  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()
  }

  stopPlaying() {
    // We emit this so playTrack doesn't immediately start a new track.
    // We aren't *actually* about to play a new track.
    this.emit('playing new track')
    this.player.kill()
  }

  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)
    }
  }

  unqueueGrouplikeItem(topItem) {
    // This function has support to unqueue groups (it removes all tracks in
    // the group recursively), but there's no UI for that yet. That is, there
    // isn't a key to unqueue an item from the main listing. (You can never
    // unqueue a group from the queue listing because groups can't be added
    // directly to the queue.)

    const recursivelyUnqueueTracks = item => {
      // For groups, just unqueue all children. (Groups themselves can't be
      // added to the queue, so we don't need to worry about removing them.)
      if (isGroup(item)) {
        for (const child of item.items) {
          recursivelyUnqueueTracks(child)
        }

        return
      }

      const items = this.queueGrouplike.items
      if (items.includes(item)) {
        items.splice(items.indexOf(item), 1)
      }
    }

    recursivelyUnqueueTracks(topItem)
    this.queueListingElement.buildItems()
  }

  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)
    }

    await Promise.all([
      writeFile(this.rootDirectory + '/current-track.txt',
        getItemPathString(item)),
      writeFile(this.rootDirectory + '/current-track.json',
        JSON.stringify(item, null, 2))
    ])

    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
      if (!this.playNextTrack(item)) {
        this.clearPlayingTrack()
      }
    }
  }

  playNextTrack(track) {
    if (!track) {
      return false
    }

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

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

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

  playPreviousTrack(track) {
    if (!track) {
      return false
    }

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

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

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

  clearPlayingTrack() {
    this.playingTrack = null
    this.stopPlaying()
    this.playbackInfoElement.clearInfo()
  }
}

class GrouplikeListingElement extends FocusElement {
  constructor(recordStore) {
    super()

    this.recordStore = recordStore

    this.grouplike = null
    this.recordStore = recordStore

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

    this.form.on('selected input', input => {
      if (input && this.pathElement) {
        this.pathElement.showItem(input.item)
      }
    })

    this.pathElement = new PathElement()
    this.addChild(this.pathElement)

    this.commentLabel = new WrapLabel()
    this.addChild(this.commentLabel)
  }

  fixLayout() {
    this.commentLabel.w = this.contentW

    this.form.w = this.contentW
    this.form.h = this.contentH
    this.form.y = this.commentLabel.bottom
    this.form.h -= this.commentLabel.h
    this.form.h -= this.pathElement.h

    this.pathElement.y = this.contentH - 1
    this.pathElement.w = this.contentW
  }

  focused() {
    this.root.select(this.form)
  }

  get selectable() {
    return this.form.selectable
  }

  get isSelected() {
    return this.form.isSelected
  }

  keyPressed(keyBuf) {
    if (telc.isBackspace(keyBuf)) {
      this.loadParentGrouplike()
    } else {
      return super.keyPressed(keyBuf)
    }
  }

  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')
    }

    this.commentLabel.text = this.grouplike.comment || ''

    const wasSelected = this.isSelected
    const form = this.form

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

    const parent = this.grouplike[parentSymbol]
    if (parent) {
      const upButton = new Button('Up (to ' + (parent.name || 'unnamed group') + ')')
      upButton.on('pressed', () => this.loadParentGrouplike())
      form.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('remove', () => this.emit('remove', 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))
        form.addInput(itemElement)
      }
    } else if (!this.grouplike.isTheQueue) {
      form.addInput(new Button('(No items in this group)'))
    }

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

    // Just to make the selected-track-info bar fill right away (if it wasn't
    // already filled by a previous this.curIndex set).
    form.curIndex = form.curIndex

    this.fixAllLayout()
  }

  loadParentGrouplike() {
    if (!this.grouplike) {
      return
    }

    const parent = this.grouplike[parentSymbol]
    if (parent) {
      const oldGrouplike = this.grouplike
      this.loadGrouplike(parent)

      const form = this.form
      const index = form.inputs.findIndex(inp => inp.item === oldGrouplike)
      if (typeof index === 'number') {
        form.curIndex = index
      } else {
        form.curIndex = form.firstItemIndex
      }
      form.updateSelectedElement()
      form.scrollSelectedElementIntoView()
    }
  }

  selectAndShow(item) {
    this.form.selectAndShow(item)
  }
}

class GrouplikeListingForm extends ListScrollForm {
  constructor() {
    super('vertical')

    this.captureTab = false
  }

  set curIndex(newIndex) {
    this._curIndex = newIndex
    this.emit('selected input', this.inputs[this.curIndex])
  }

  get curIndex() {
    return this._curIndex
  }

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

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

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

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.isBackspace(keyBuf)) {
      this.emit('remove')
    } else if (telc.isSpace(keyBuf)) {
      this.emit('select (space)')
    } else if (telc.isEnter(keyBuf)) {
      this.emit('select (enter)')
    }
  }
}

class PathElement extends ListScrollForm {
  constructor() {
    super('horizontal')
    this.captureTab = false
  }

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

    if (!isTrack(item) && !isGroup(item)) {
      return
    }

    const itemPath = getItemPath(item)

    for (const pathItem of itemPath) {
      const isLast = pathItem === itemPath[itemPath.length - 1]
      const element = new PathItemElement(pathItem, isLast)
      element.on('select', () => this.emit('select', pathItem))
      element.fixLayout()
      this.addInput(element)
    }

    this.curIndex = this.inputs.length - 1

    this.scrollToEnd()
    this.fixLayout()
  }
}

class PathItemElement extends FocusElement {
  constructor(item, isLast) {
    super()

    this.item = item
    this.isLast = isLast

    this.button = new Button(item.name || '(Unnamed)')
    this.addChild(this.button)

    this.button.on('pressed', () => {
      this.emit('select')
    })

    this.arrowLabel = new Label(isLast ? '' : ' > ')
    this.addChild(this.arrowLabel)
  }

  focused() {
    this.root.select(this.button)
  }

  fixLayout() {
    this.button.fixLayout()
    this.arrowLabel.fixLayout()
    this.w = this.button.w + this.arrowLabel.w
    this.arrowLabel.x = this.button.right
  }
}

class QueueListingElement extends GrouplikeListingElement {
  constructor(...args) {
    super(...args)

    this.removeChild(this.form)
    this.form = new QueueListingForm()
    this.addChild(this.form)
  }

  keyPressed(keyBuf) {
    if (telc.isCaselessLetter(keyBuf, 's')) {
      this.emit('shuffle')
    } else if (telc.isCaselessLetter(keyBuf, 'c')) {
      this.emit('clear')
    } else {
      return super.keyPressed(keyBuf)
    }
  }
}

class QueueListingForm extends GrouplikeListingForm {
  updateSelectedElement() {
    if (this.inputs.length) {
      super.updateSelectedElement()
    } else {
      this.emit('select main listing')
    }
  }
}

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

    if (this.currentTrack) {
      const dl = this.currentTrack.downloaderArg
      let dlText = dl.slice(Math.max(dl.length - this.w + 20, 0))
      if (dlText !== dl) {
        dlText = unic.ELLIPSIS + dlText
      }
      this.downloadLabel.text = `(From: ${dlText})`
    }
  }

  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.currentTrack = track
    this.trackNameLabel.text = track.name
    this.fixLayout()
  }

  clearInfo() {
    this.currentTrack = null
    this.progressBarLabel.text = ''
    this.progressTextLabel.text = ''
    this.trackNameLabel.text = ''
    this.downloadLabel.text = ''
    this.fixLayout()
  }
}

module.exports.AppElement = AppElement