subsonic-tui/internal/tui/tui.go
Sagi Dayan 26e526f07e
initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-02-20 19:10:14 +02:00

124 lines
2.8 KiB
Go

package tui
import (
"fmt"
"os"
"git.dayanhub.com/sagi/subsonic-tui/internal/client"
"git.dayanhub.com/sagi/subsonic-tui/internal/config"
"git.dayanhub.com/sagi/subsonic-tui/internal/playback"
"git.dayanhub.com/sagi/subsonic-tui/internal/tui/views"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
type TUI struct {
app *tview.Application
layout views.View
client *client.Client
playbackCtl *playback.Controller
}
func NewLogin() *TUI {
app := tview.NewApplication()
layout := views.NewLoginView(func(u, p, url string) {
c := client.NewClient(url)
err := c.Authenticate(u, p)
if err != nil {
app.Stop()
fmt.Printf("[Error] Failed to login. Aborting %e", err)
os.Exit(1)
}
config.SetURL(url)
config.SetUsername(u)
config.SetPassword(p)
config.SaveConfig()
app.Stop()
}, func() {
app.Stop()
os.Exit(0)
})
app.EnableMouse(true).
SetRoot(layout.GetView(), true)
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if event.Key() == tcell.KeyEsc {
app.Stop()
os.Exit(0)
}
return event
})
return &TUI{
app: app,
layout: layout,
}
}
func NewPlayer(client *client.Client, playbackCtl *playback.Controller) *TUI {
app := tview.NewApplication()
layout := views.NewLayout(client, playbackCtl, func() {
go app.Draw()
})
help := views.NewHelp()
pages := tview.NewPages()
pages.AddPage("app", layout.GetView(), true, true)
pages.AddPage("help", help.GetView(), true, false)
help.SetKeyPressedFunc(func() {
pages.SwitchToPage("app")
})
app.EnableMouse(true).
SetRoot(pages, true)
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if currentPage, _ := pages.GetFrontPage(); currentPage == "help" {
pages.SwitchToPage("app")
help.GetView().Blur()
layout.GetView().Focus(nil)
return nil
}
if layout.Mode() == views.StatusModeSearch {
return event
}
if event.Rune() == 'q' {
app.Stop()
fmt.Println("Exiting..")
return nil
} else if event.Rune() == 'h' {
return tcell.NewEventKey(tcell.KeyLeft, rune(tcell.KeyLeft), event.Modifiers())
} else if event.Rune() == 'j' {
return tcell.NewEventKey(tcell.KeyDown, rune(tcell.KeyDown), event.Modifiers())
} else if event.Rune() == 'k' {
return tcell.NewEventKey(tcell.KeyUp, rune(tcell.KeyUp), event.Modifiers())
} else if event.Rune() == 'l' {
return tcell.NewEventKey(tcell.KeyRight, rune(tcell.KeyRight), event.Modifiers())
} else if event.Rune() == '?' {
pages.SwitchToPage("help")
layout.GetView().Blur()
go app.Draw()
}
return event
})
app.SetAfterDrawFunc(func(screen tcell.Screen) {
layout.Update()
})
app.GetFocus().Blur()
//app.SetFocus(layout.GetView())
return &TUI{
app: app,
layout: layout,
client: client,
playbackCtl: playbackCtl,
}
}
func (t *TUI) Run() error {
return t.app.Run()
}