« 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: 2c74f8e55feecbae7f2c956e27b2c97d84e8bd53 (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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
const { getAllCrawlersForArg } = require('./crawlers')
const { getDownloaderFor } = require('./downloaders')
const { getPlayer } = require('./players')
const { parentSymbol, isGroup, isTrack, getItemPath, getItemPathString, flattenGrouplike, cloneGrouplike } = require('./playlist-utils')
const { shuffleArray } = require('./general-util')
const processSmartPlaylist = require('./smart-playlist')
const UndoManager = require('./undo-manager')

const ansi = require('./tui-lib/util/ansi')
const Button = require('./tui-lib/ui/form/Button')
const Dialog = require('./tui-lib/ui/Dialog')
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 TextInput = require('./tui-lib/ui/form/TextInput')
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.undoManager = new UndoManager()
    this.queueGrouplike = {name: 'Queue', isTheQueue: true, items: []}
    this.markGrouplike = {name: 'Marked', items: []}
    this.editMode = false

    // Crude hack...
    this.recordStore.app = this

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

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

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

    this.tabber = new Tabber()
    this.paneLeft.addChild(this.tabber)

    this.newGrouplikeListing()

    this.queueListingElement = new QueueListingElement(this.recordStore)
    this.setupCommonGrouplikeListingEvents(this.queueListingElement)
    this.queueListingElement.loadGrouplike(this.queueGrouplike)
    this.paneRight.addChild(this.queueListingElement)

    this.queueListingElement.on('queue', item => this.playGrouplikeItem(item))
    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.root.select(this.tabber))

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

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

    // Dialogs

    this.openPlaylistDialog = new OpenPlaylistDialog()
    this.setupDialog(this.openPlaylistDialog)

    this.openPlaylistDialog.on('source selected', source => this.handlePlaylistSource(source))
    this.openPlaylistDialog.on('source selected (new tab)', source => this.handlePlaylistSource(source, true))

    this.alertDialog = new AlertDialog()
    this.setupDialog(this.alertDialog)

    /* Ignore this comment mostly :)  (Because menu isn't a child of pane,
       so we can append it to the app right away. Helps w/ handling ^C and
       stuff too.)
    // If the program were embedded, this.menu should probably be set to the
    // global menu object for that app (and everything should work fine).
    // As is, remember to append app.menu to root.
    */
    this.menu = new ContextMenu()
    this.addChild(this.menu)
  }

  selected() {
    this.root.select(this.tabber)
  }

  newGrouplikeListing() {
    const grouplikeListing = new GrouplikeListingElement(this.recordStore)
    this.tabber.addTab(grouplikeListing)
    this.tabber.selectTab(grouplikeListing)

    grouplikeListing.on('download', item => this.downloadGrouplikeItem(item))
    grouplikeListing.on('browse', item => grouplikeListing.loadGrouplike(item))
    grouplikeListing.on('menu', (item, opts) => this.menu.show(opts))

    grouplikeListing.on('queue', (item, {where = 'end', shuffle = false, play = false} = {}) => {
      if (isGroup(item) && shuffle) {
        item = {items: shuffleArray(flattenGrouplike(item).items)}
      }

      let afterItem = null
      if (where === 'next') {
        afterItem = this.playingTrack
      }

      this.queueGrouplikeItem(item, afterItem)

      if (play) {
        this.playGrouplikeItem(item)
      }
    })

    grouplikeListing.on('unqueue', item => this.unqueueGrouplikeItem(item))

    const updateListingsFor = item => {
      for (const grouplikeListing of this.tabber.tabberElements) {
        if (grouplikeListing.grouplike === item) {
          grouplikeListing.loadGrouplike(item, false)
        }
      }
    }

    grouplikeListing.on('remove', item => {
      if (this.editMode) {
        const parent = item[parentSymbol]
        const index = parent.items.indexOf(item)

        this.undoManager.pushAction({
          activate: () => {
            parent.items.splice(index, 1)
            delete item[parentSymbol]
            updateListingsFor(item)
            updateListingsFor(parent)
          },
          undo: () => {
            parent.items.splice(index, 0, item)
            item[parentSymbol] = parent
            updateListingsFor(item)
            updateListingsFor(parent)
          }
        })
      }
    })

    grouplikeListing.on('mark', item => {
      if (this.editMode) {
        if (!this.markGrouplike.items.includes(item)) {
          this.undoManager.pushAction({
            activate: () => {
              this.markGrouplike.items.push(item)
            },
            undo: () => {
              this.markGrouplike.items.pop()
            }
          })
        } else {
          const index = this.markGrouplike.items.indexOf(item)
          this.undoManager.pushAction({
            activate: () => {
              this.markGrouplike.items.splice(index, 1)
            },
            undo: () => {
              this.markGrouplike.items.splice(index, 0, item)
            }
          })
        }
      }
    })

    grouplikeListing.on('paste', (item, {where = 'below'} = {}) => {
      if (this.editMode && this.markGrouplike.items.length) {
        let parent, index

        if (where === 'above') {
          parent = item[parentSymbol]
          index = parent.items.indexOf(item)
        } else if (where === 'below') {
          parent = item[parentSymbol]
          index = parent.items.indexOf(item) + 1
        }

        this.undoManager.pushAction({
          activate: () => {
            parent.items.splice(index, 0, ...cloneGrouplike(this.markGrouplike).items.map(
              item => Object.assign({}, item, {[parentSymbol]: parent})
            ))
            updateListingsFor(parent)
          },
          undo: () => {
            parent.items.splice(index, this.markGrouplike.items.length)
            updateListingsFor(parent)
          }
        })
      }
    })

    this.setupCommonGrouplikeListingEvents(grouplikeListing)

    return grouplikeListing
  }

  setupCommonGrouplikeListingEvents(grouplikeListing) {
    // Sets up event listeners that are common to ordinary grouplike listings
    // (made by newGrouplikeListing) as well as the queue grouplike listing.

    const handleSelectFromPathElement = item => {
      const tabberListing = this.tabber.currentElement
      this.root.select(tabberListing)
      if (isGroup(item)) {
        tabberListing.loadGrouplike(item)
      } else if (item[parentSymbol]) {
        tabberListing.loadGrouplike(item[parentSymbol])
        tabberListing.selectAndShow(item)
      }
    }

    grouplikeListing.pathElement.on('select', item => handleSelectFromPathElement(item))

  }

  async handlePlaylistSource(source, newTab = false) {
    this.openPlaylistDialog.close()
    this.alertDialog.showMessage('Opening playlist...', false)

    let grouplike
    try {
      grouplike = await this.openPlaylist(source)
    } catch (error) {
      if (error === 'unknown argument') {
        this.alertDialog.showMessage('Could not figure out how to load a playlist from: ' + source)
      } else if (typeof error === 'string') {
        this.alertDialog.showMessage(error)
      } else {
        throw error
      }

      return
    }

    this.alertDialog.close()

    grouplike = await processSmartPlaylist(grouplike)

    if (newTab || !this.tabber.currentElement) {
      const grouplikeListing = this.newGrouplikeListing()
      grouplikeListing.loadGrouplike(grouplike)
    } else {
      this.tabber.currentElement.loadGrouplike(grouplike)
    }
  }

  openPlaylist(arg) {
    const crawlers = getAllCrawlersForArg(arg)

    if (crawlers.length === 0) {
      throw 'unknown argument'
    }

    const crawler = crawlers[0]

    return crawler(arg)
  }

  setupDialog(dialog) {
    dialog.visible = false
    this.addChild(dialog)

    dialog.on('cancelled', () => {
      dialog.close()
    })
  }

  async setup() {
    this.player = await getPlayer()

    if (!this.player) {
      return {
        error: "Sorry, it doesn't look like there's an audio player installed on your computer. Can you try installing MPV (https://mpv.io) or SoX?"
      }
    }

    this.player.on('printStatusLine', data => {
      if (this.playingTrack) {
        this.playbackInfoElement.updateProgress(data)
      }
    })

    return true
  }

  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.tabber.fillParent()
    this.tabber.fixLayout()
    this.queueListingElement.fillParent()
    this.playbackInfoElement.fillParent()
  }

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

    if (telc.isRight(keyBuf)) {
      this.seekAhead(10)
    } else if (telc.isLeft(keyBuf)) {
      this.seekBack(10)
    } else if (telc.isSpace(keyBuf)) {
      this.togglePause()
    } else if (telc.isEscape(keyBuf)) {
      this.clearPlayingTrack()
    } else if (telc.isShiftUp(keyBuf) || telc.isCaselessLetter(keyBuf, 'p')) {
      this.playPreviousTrack(this.playingTrack)
    } else if (telc.isShiftDown(keyBuf) || telc.isCaselessLetter(keyBuf, 'n')) {
      this.playNextTrack(this.playingTrack)
    } else if (telc.isCharacter(keyBuf, '1') && this.tabber.selectable) {
      this.root.select(this.tabber)
    } else if (telc.isCharacter(keyBuf, '2') && this.queueListingElement.selectable) {
      this.root.select(this.queueListingElement)
    } else if (keyBuf.equals(Buffer.from([5]))) { // Ctrl-E
      this.editMode = !this.editMode
    } else if (this.editMode && keyBuf.equals(Buffer.from([14]))) { // ctrl-N
      this.newEmptyTab()
    } else if (keyBuf.equals(Buffer.from([15]))) { // ctrl-O
      this.openPlaylistDialog.open()
    } else if (keyBuf.equals(Buffer.from([20]))) { // ctrl-T
      this.cloneCurrentTab()
    } else if (keyBuf.equals(Buffer.from([23]))) { // ctrl-W
      this.closeCurrentTab()
    } else if (telc.isCharacter(keyBuf, 'u')) {
      this.undoManager.undoLastAction()
    } else if (telc.isCharacter(keyBuf, 'U')) {
      this.undoManager.redoLastUndoneAction()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from(['t'.charCodeAt(0)]))) {
      this.tabber.nextTab()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from(['T'.charCodeAt(0)]))) {
      this.tabber.previousTab()
    } else {
      super.keyPressed(keyBuf)
    }
  }

  newEmptyTab() {
    const listing = this.newGrouplikeListing()
    listing.loadGrouplike({
      name: 'New Playlist',
      items: []
    })
  }

  cloneCurrentTab() {
    const grouplike = this.tabber.currentElement.grouplike
    const listing = this.newGrouplikeListing()
    listing.loadGrouplike(grouplike)
  }

  closeCurrentTab() {
    const listing = this.tabber.currentElement
    let index
    this.undoManager.pushAction({
      activate: () => {
        index = this.tabber.currentElementIndex
        this.tabber.closeTab(this.tabber.currentElement)
      },
      undo: () => {
        this.tabber.addTab(listing, index)
        this.tabber.selectTab(listing)
      }
    })
  }

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

  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, 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]

    return newTrack
  }

  unqueueGrouplikeItem(topItem) {
    // This function has support to unqueue groups - it removes all tracks in
    // the group recursively. (You can never unqueue a group itself 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
    }

    // Don't start downloading an item if we're already downloading it!
    if (this.recordStore.getRecord(item).downloading) {
      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) {
    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 it's a group, play the first track.
    if (isGroup(item)) {
      item = flattenGrouplike(item).items[0]
    }

    // If there is no item (e.g. an empty group), well.. don't do anything.
    if (!item) {
      return
    }

    playTrack: {
      // No downloader argument? That's no good - stop here.
      // TODO: An error icon on this item, or something???
      if (!item.downloaderArg) {
        break playTrack
      }

      // 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 Form {
  // TODO: This is a Form, which means that it captures the tab key. The result
  // of this is that you cannot use Tab to navigate the top-level application.
  // Accordingly, I've made AppElement a FocusElement and not a Form and re-
  // factored calls of addInput to addChild. However, I'm not sure that this is
  // the "correct" or most intuitive behavior. Should the tab key be usable to
  // navigate the entire interface? I don't know. I've gone with the current
  // behavior (GrouplikeListingElement as a Form) because it feels right at the
  // moment, but we'll see, I suppose.
  //
  // In order to let tab navigate through all UI elements (or rather, the top-
  // level application as well as GrouplikeListingElements, which are a sort of
  // nested Form), the AppElement would have to be changed to be a Form again
  // (replacing addChild with addInput where appropriate). Furthermore, while
  // the GrouplikeListingElement should stay as a Form subclass, it should be
  // modified so that it does not capture tab if there is no next element to
  // select, and vice versa for shift-tab and the previous element. This should
  // probably be implemented in tui-lib as a flag on Form (captureTabOnEnds,
  // or something).
  //
  // (PS AppElement apparently used a "this.form" property, instead of directly
  // inheriting from Form, apparently. That's more or less adjacent to the
  // point. It's removed now. You'll have to add it back, if wanted.)
  //
  // August 15th, 2018

  constructor(recordStore) {
    super()

    this.recordStore = recordStore

    this.grouplike = null
    this.recordStore = recordStore

    this.form = this.getNewForm()
    this.addInput(this.form)

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

    this.jumpElement = new ListingJumpElement()
    this.addInput(this.jumpElement)
    this.jumpElement.visible = false
    this.oldFocusedIndex = null // To restore to, if a jump is canceled.

    this.jumpElement.on('cancel', () => this.hideJumpElement(true))
    this.jumpElement.on('change', value => this.handleJumpValue(value, false))
    this.jumpElement.on('confirm', value => this.handleJumpValue(value, true))

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

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

  getNewForm() {
    return new GrouplikeListingForm()
  }

  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 -= 1 // For the path element
    if (this.jumpElement.visible) this.form.h -= 1

    this.form.fixLayout() // Respond to being resized

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

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

  selected() {
    this.curIndex = 0
    this.root.select(this.form)
  }

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

  keyPressed(keyBuf) {
    if (telc.isBackspace(keyBuf)) {
      this.loadParentGrouplike()
    } else if (telc.isCharacter(keyBuf, '/') || keyBuf[0] === 6) { // '/', ctrl-F
      this.showJumpElement()
    } else {
      return super.keyPressed(keyBuf)
    }
  }

  loadGrouplike(grouplike, resetIndex = true) {
    this.grouplike = grouplike
    this.buildItems(resetIndex)
    if (this.root.select) this.hideJumpElement()
  }

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

    let itemElements = []
    if (this.grouplike.items.length) {
      itemElements = this.grouplike.items.map(item => new GrouplikeItemElement(item, this.recordStore))
    } else if (!this.grouplike.isTheQueue) {
      const fakeItem = {
        fake: true,
        name: '(This group is empty)',
        [parentSymbol]: this.grouplike
      }
      itemElements = [new GrouplikeItemElement(fakeItem, this.recordStore)]
    }

    for (const itemElement of itemElements) {
      for (const evtName of ['download', 'remove', 'mark', 'paste', 'browse', 'queue', 'unqueue', 'menu']) {
        itemElement.on(evtName, (...data) => this.emit(evtName, itemElement.item, ...data))
      }
      form.addInput(itemElement)
    }

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

  handleJumpValue(value, isConfirm) {
    // Don't perform the search if the user didn't enter anything.
    if (value.length) {
      const lower = value.toLowerCase()
      const getName = inp => (inp.item && inp.item.name) ? inp.item.name.toLowerCase().trim() : ''
      // TODO: Search past the current index, for repeated searches?
      const startsIndex = this.form.inputs.findIndex(inp => getName(inp).startsWith(lower))
      const includesIndex = this.form.inputs.findIndex(inp => getName(inp).includes(lower))
      const matchedIndex = startsIndex >= 0 ? startsIndex : includesIndex

      if (matchedIndex >= 0) {
        this.form.curIndex = matchedIndex
        this.form.scrollSelectedElementIntoView()
      } else {
        // TODO: Feedback that the search failed.. right now we just close the
        // jump-to menu, which might not be right.
      }
    }

    if (isConfirm) {
      this.hideJumpElement()
    }
  }

  showJumpElement() {
    this.oldFocusedIndex = this.form.curIndex
    this.jumpElement.visible = true
    this.root.select(this.jumpElement)
    this.fixLayout()
  }

  hideJumpElement(isCancel) {
    if (isCancel) {
      this.form.curIndex = this.oldFocusedIndex
      this.form.scrollSelectedElementIntoView()
    }
    this.jumpElement.visible = false
    this.root.select(this)
    this.fixLayout()
  }

  get tabberLabel() {
    if (this.grouplike) {
      return this.grouplike.name || 'Unnamed group'
    } else {
      return 'No group open'
    }
  }

  get currentItem() {
    const element = this.form.inputs[this.form.curIndex] || null
    return element && element.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.max(0, this.inputs.findIndex(el => el instanceof GrouplikeItemElement))
  }

  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) {
    const isCurrentInput = this.parent.inputs[this.parent.curIndex] === this
    // This line's commented out for now, so it'll show as selected (but
    // dimmed) even if you don't have the listing selected. To change that,
    // uncomment this and add it to the isCurrentInput line.
    // const isListingSelected = this.parent.parent.isSelected
    const isSelfSelected = this.isSelected

    if (isSelfSelected) {
      writable.write(ansi.invert())
    } else if (isCurrentInput) {
      writable.write(ansi.setAttributes([ansi.A_INVERT, ansi.A_DIM]))
    }

    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)

    if (this.isMarked) {
      writable.write('M')
    } else {
      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(' ')
  }

  get isMarked() {
    return this.recordStore.app.editMode && this.recordStore.app.markGrouplike.items.includes(this.item)
  }

  get isReal() {
    return !this.item.fake
  }

  get isGroup() {
    return isGroup(this.item) && this.isReal
  }

  get isTrack() {
    return isTrack(this.item) && this.isReal
  }

  keyPressed(keyBuf) {
    if (telc.isCaselessLetter(keyBuf, 'd')) {
      this.emit('download')
    } else if (telc.isCharacter(keyBuf, 'q')) {
      this.emit('queue', {where: 'end'})
    } else if (telc.isCharacter(keyBuf, 'Q')) {
      this.emit('queue', {where: 'next'})
    } else if (telc.isEnter(keyBuf)) {
      if (isGroup(this.item)) {
        this.emit('browse')
      } else {
        this.emit('queue', {where: 'next', play: true})
      }
    } else if (telc.isCaselessLetter(keyBuf, 'x')) {
      this.emit('remove')
    } else if (telc.isCaselessLetter(keyBuf, 'm')) {
      const editMode = this.recordStore.app.editMode
      const anyMarked = editMode && !!this.recordStore.app.markGrouplike.items.length
      this.emit('menu', {
        x: this.absLeft,
        y: this.absTop + 1,
        items: [
          editMode && this.isReal && {label: this.isMarked ? 'Unmark' : 'Mark', action: () => this.emit('mark')},
          anyMarked && this.isReal && {label: 'Paste (above)', action: () => this.emit('paste', {where: 'above'})},
          anyMarked && this.isReal && {label: 'Paste (below)', action: () => this.emit('paste', {where: 'below'})},
          anyMarked && !this.isReal && {label: 'Paste', action: () => this.emit('paste')}, // No "above" or "elow" in the label because the fake item will be replaced (it'll disappear, since there'll be an item in the group)
          this.isReal && {label: 'Play', action: () => this.emit('queue', {where: 'next', play: true})},
          this.isReal && {label: 'Play next', action: () => this.emit('queue', {where: 'next'})},
          this.isReal && {label: 'Play at end', action: () => this.emit('queue', {where: 'end'})},
          this.isGroup && {label: 'Play next, shuffled', action: () => this.emit('queue', {where: 'next', shuffle: true})},
          this.isGroup && {label: 'Play at end, shuffled', action: () => this.emit('queue', {where: 'end', shuffle: true})},
          this.isReal && {label: 'Remove from queue', action: () => this.emit('unqueue')}
        ]
      })
    }
  }
}

class ListingJumpElement extends Form {
  constructor() {
    super()

    this.label = new Label('Jump to: ')
    this.addChild(this.label)

    this.input = new TextInput()
    this.addInput(this.input)

    this.input.on('confirm', value => this.emit('confirm', value))
    this.input.on('change', value => this.emit('change', value))
    this.input.on('cancel', () => this.emit('cancel'))
  }

  selected() {
    this.input.value = ''
    this.input.keepCursorInRange()
    this.root.select(this.input)
  }

  fixLayout() {
    this.input.x = this.label.right
    this.input.w = this.contentW - this.input.x
  }
}

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)
    const parentPath = itemPath.slice(0, -1)

    for (const pathItem of parentPath) {
      const isFirst = pathItem === parentPath[0]
      const element = new PathItemElement(pathItem, isFirst)
      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, isFirst) {
    super()

    this.item = item
    this.isFirst = isFirst

    this.arrowLabel = new Label(isFirst ? 'In: ' : ' > ')
    this.addChild(this.arrowLabel)

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

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

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

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

class QueueListingElement extends GrouplikeListingElement {
  getNewForm() {
    return new QueueListingForm()
  }

  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)

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

    centerX(this.progressTextLabel)
    centerX(this.trackNameLabel)
    centerX(this.downloadLabel)
  }

  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.progressBarLabel.text = ''
    this.progressTextLabel.text = '(Starting..)'
    this.fixLayout()
  }

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

class OpenPlaylistDialog extends Dialog {
  constructor() {
    super()

    this.label = new Label('Enter a playlist source:')
    this.pane.addChild(this.label)

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

    this.input = new TextInput()
    this.form.addInput(this.input)

    this.button = new Button('Open')
    this.form.addInput(this.button)

    this.buttonNewTab = new Button('..in New Tab')
    this.form.addInput(this.buttonNewTab)

    this.button.on('pressed', () => {
      if (this.input.value) {
        this.emit('source selected', this.input.value)
      }
    })

    this.buttonNewTab.on('pressed', () => {
      if (this.input.value) {
        this.emit('source selected (new tab)', this.input.value)
      }
    })
  }

  opened() {
    this.input.setValue('')
    this.form.curIndex = 0
    this.form.updateSelectedElement()
  }

  fixLayout() {
    super.fixLayout()

    this.pane.w = Math.min(60, this.contentW)
    this.pane.h = 6
    this.pane.centerInParent()

    this.label.centerInParent()
    this.label.y = 0

    this.form.w = this.pane.contentW
    this.form.h = 2
    this.form.y = 1

    this.input.w = this.form.contentW

    this.button.centerInParent()
    this.button.y = 1

    this.buttonNewTab.centerInParent()
    this.buttonNewTab.y = 2
  }

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

class AlertDialog extends Dialog {
  constructor() {
    super()

    this.label = new Label()
    this.pane.addChild(this.label)

    this.button = new Button('Close')
    this.button.on('pressed', () => {
      if (this.canClose) {
        this.emit('cancelled')
      }
    })
    this.pane.addChild(this.button)
  }

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

  showMessage(message, canClose = true) {
    this.canClose = canClose
    this.label.text = message
    this.button.text = canClose ? 'Close' : '(Hold on...)'
    this.open()
  }

  fixLayout() {
    super.fixLayout()

    this.pane.w = Math.min(this.label.w + 4, this.contentW)
    this.pane.h = 4
    this.pane.centerInParent()

    this.label.centerInParent()
    this.label.y = 0

    this.button.fixLayout()
    this.button.centerInParent()
    this.button.y = 1
  }

  keyPressed() {
    // Don't handle the escape key.
  }
}

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

    this.tabberElements = []
    this.currentElementIndex = 0

    this.listElement = new TabberList(this)
    this.addChild(this.listElement)
  }

  fixLayout() {
    const el = this.currentElement
    if (el) {
      // Only make space for the tab list if there's more than one tab visible.
      // (The tab list isn't shown if there's only one.)
      if (this.tabberElements.length > 1) {
        el.w = this.contentW
        el.h = this.contentH - 1
        el.x = 0
        el.y = 1
      } else {
        el.fillParent()
        el.x = 0
        el.y = 0
      }
      el.fixLayout()
    }

    if (this.tabberElements.length > 1) {
      this.listElement.visible = true
      this.listElement.w = this.contentW
      this.listElement.h = 1
      this.listElement.fixLayout()
    } else {
      this.listElement.visible = false
    }
  }

  addTab(element, index = this.currentElementIndex) {
    element.visible = false
    this.tabberElements.splice(index + 1, 0, element)
    this.addChild(element, index + 1)
    this.listElement.buildItems()
  }

  nextTab() {
    this.currentElementIndex++
    this.updateVisibleElement()
  }

  previousTab() {
    this.currentElementIndex--
    this.updateVisibleElement()
  }

  selectTab(element) {
    if (!this.tabberElements.includes(element)) {
      throw new Error('That tab does not exist! (Perhaps it was removed, somehow, or was never added?)')
    }

    this.currentElementIndex = this.tabberElements.indexOf(element)
    this.updateVisibleElement()
  }

  closeTab(element) {
    if (!this.tabberElements.includes(element)) {
      return
    }

    const index = this.tabberElements.indexOf(element)
    this.tabberElements.splice(index, 1)
    if (index <= this.currentElementIndex) {
      this.currentElementIndex--
    }

    // Deliberately update the visible element before removing the child. If we
    // remove the child first, the isSelected in updateVisibleElement will be
    // false, so the new currentElement won't actually be root.select()'ed.
    this.updateVisibleElement()
    this.removeChild(element)
    this.listElement.buildItems()
  }

  updateVisibleElement() {
    const len = this.tabberElements.length - 1
    this.currentElementIndex = Math.min(len, Math.max(0, this.currentElementIndex))

    this.tabberElements.forEach((el, i) => {
      el.visible = (i === this.currentElementIndex)
    })

    if (this.isSelected) {
      if (this.currentElement) {
        this.root.select(this.currentElement)
      } else {
        this.root.select(this)
      }
    }

    this.fixLayout()
  }

  selected() {
    if (this.currentElement) {
      this.root.select(this.currentElement)
    }
  }

  get selectable() {
    return this.currentElement && this.currentElement.selectable
  }

  get currentElement() {
    return this.tabberElements[this.currentElementIndex] || null
  }
}

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

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

    for (const item of this.tabber.tabberElements) {
      const element = new TabberListItem(item, this.tabber)
      this.addInput(element)
      element.fixLayout()
    }

    this.scrollToEnd()
    this.fixLayout()
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = 1
    this.x = 0
    this.y = 0
    this.scrollElementIntoEndOfView(this.inputs[this.curIndex])
    super.fixLayout()
  }

  drawTo() {
    let changed = false
    for (const input of this.inputs) {
      input.fixLayout()
      if (input._oldW !== input.w) {
        input._oldW = input.w
        changed = true
      }
    }
    if (changed) {
      this.fixLayout()
    }
  }

  // TODO: Be less hacky about these! Right now the tabber list is totally not
  // interactive.
  get curIndex() { return this.tabber.currentElementIndex }
  set curIndex(newVal) {}
}

class TabberListItem extends FocusElement {
  constructor(tab, tabber) {
    super()

    this.tab = tab
    this.tabber = tabber
  }

  fixLayout() {
    this.w = this.text.length + 3
  }

  drawTo(writable) {
    if (this.tabber.currentElement === this.tab) {
      writable.write(ansi.setAttributes([ansi.A_BRIGHT]))
      writable.write(ansi.moveCursor(this.absTop, this.absLeft))
      writable.write('<' + this.text + '>')
      writable.write(ansi.resetAttributes())
    } else {
      writable.write(ansi.moveCursor(this.absTop, this.absLeft + 1))
      writable.write(this.text)
    }
  }

  get text() {
    return this.tab.tabberLabel || 'a(n) ' + this.tab.constructor.name
  }
}

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

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

    this.form = new ListScrollForm()
    this.pane.addChild(this.form)

    this.visible = false
  }

  show({x = 0, y = 0, items}) {
    items = items.filter(Boolean)
    if (!items.length) {
      return
    }

    // This *should* work with a menu action which opens the menu again,
    // because the selected element will be restored before the menu is
    // opened the second time.
    this.selectedBefore = this.root.selectedElement

    this.clearItems()

    this.x = x
    this.y = y
    this.visible = true

    // TODO: Actions, that sorta thing
    for (const { label, action } of items.filter(Boolean)) {
      const button = new Button(label)
      if (action) {
        button.on('pressed', () => {
          this.close()
          action()
        })
      }
      this.form.addInput(button)
    }

    this.fixLayout()

    this.form.firstInput()
  }

  keyPressed(keyBuf) {
    if (telc.isEscape(keyBuf) || telc.isBackspace(keyBuf)) {
      this.close()
    } else {
      super.keyPressed(keyBuf)
    }
  }

  close() {
    this.clearItems()
    this.visible = false
    this.root.select(this.selectedBefore)
  }

  clearItems() {
    const inputs = this.form.inputs.slice()
    for (const input of inputs) {
      this.form.removeInput(input)
    }
  }

  fixLayout() {
    let width = 10
    for (const input of this.form.inputs) {
      input.fixLayout()
      width = Math.max(width, input.w)
    }

    let height = Math.min(10, this.form.inputs.length)

    width += 3 // Space for the pane border and scrollbar
    height += 2 // Space for the pane border
    this.w = width
    this.h = height

    this.fitToParent()

    this.pane.fillParent()
    this.form.fillParent()
  }

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

module.exports.AppElement = AppElement