gomu/playlist.go

143 lines
2.5 KiB
Go
Raw Normal View History

2020-06-19 16:22:20 +08:00
package main
import (
"io/ioutil"
"path/filepath"
"github.com/gdamore/tcell"
"github.com/rivo/tview"
)
type AudioFile struct {
2020-06-19 16:42:30 +08:00
Name string
Path string
2020-06-19 16:22:20 +08:00
IsAudioFile bool
2020-06-19 16:42:30 +08:00
Parent *tview.TreeNode
2020-06-19 16:22:20 +08:00
}
2020-06-21 00:00:17 +08:00
func Playlist(list *tview.List, player *Player) *tview.TreeView {
2020-06-19 16:22:20 +08:00
musicDir := "./music"
rootDir, err := filepath.Abs(musicDir)
if err != nil {
panic(err)
}
root := tview.NewTreeNode(musicDir)
tree := tview.NewTreeView().SetRoot(root)
tree.SetTitle("Playlist").SetBorder(true)
tree.SetGraphicsColor(tcell.ColorWhite)
textColor := tcell.ColorAntiqueWhite
backGroundColor := tcell.ColorDarkCyan
var prevNode *tview.TreeNode
go func() {
populate(root, rootDir)
firstChild := root.GetChildren()[0]
firstChild.SetColor(textColor)
tree.SetCurrentNode(firstChild)
// keep track of prev node so we can remove the color of highlight
prevNode = firstChild.SetColor(backGroundColor)
2020-06-19 16:42:30 +08:00
tree.SetChangedFunc(func(node *tview.TreeNode) {
2020-06-19 16:22:20 +08:00
prevNode.SetColor(textColor)
root.SetColor(textColor)
node.SetColor(backGroundColor)
prevNode = node
})
2020-06-19 16:42:30 +08:00
}()
2020-06-19 16:22:20 +08:00
tree.SetInputCapture(func(e *tcell.EventKey) *tcell.EventKey {
currNode := tree.GetCurrentNode()
if currNode == root {
return e
}
audioFile := currNode.GetReference().(*AudioFile)
switch e.Rune() {
case 'l':
if audioFile.IsAudioFile {
list.AddItem(audioFile.Name, audioFile.Path, 0, nil)
2020-06-21 00:00:17 +08:00
player.Push(audioFile.Path)
2020-06-19 16:42:30 +08:00
2020-06-21 00:00:17 +08:00
if !player.IsRunning {
go player.Run()
}
2020-06-19 16:22:20 +08:00
}
2020-06-21 00:00:17 +08:00
2020-06-19 16:22:20 +08:00
currNode.SetExpanded(true)
case 'h':
// if closing node with no children
2020-06-19 16:42:30 +08:00
// close the node's parent
2020-06-19 16:22:20 +08:00
// remove the color of the node
if audioFile.IsAudioFile {
parent := audioFile.Parent
currNode.SetColor(textColor)
parent.SetExpanded(false)
parent.SetColor(backGroundColor)
prevNode = parent
tree.SetCurrentNode(parent)
} else {
currNode.Collapse()
}
}
return e
})
tree.SetSelectedFunc(func(node *tview.TreeNode) {
node.SetExpanded(!node.IsExpanded())
})
return tree
}
func populate(root *tview.TreeNode, rootPath string) {
files, err := ioutil.ReadDir(rootPath)
if err != nil {
panic(err)
}
for _, file := range files {
path := filepath.Join(rootPath, file.Name())
child := tview.NewTreeNode(file.Name())
root.AddChild(child)
audioFile := &AudioFile{
2020-06-19 16:42:30 +08:00
Name: file.Name(),
Path: path,
2020-06-19 16:22:20 +08:00
IsAudioFile: true,
2020-06-19 16:42:30 +08:00
Parent: root,
2020-06-19 16:22:20 +08:00
}
child.SetReference(audioFile)
if file.IsDir() {
audioFile.IsAudioFile = false
populate(child, path)
}
}
}