application.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package cmd
  2. import (
  3. "log/slog"
  4. "github.com/gdamore/tcell/v2"
  5. "github.com/rivo/tview"
  6. )
  7. type Application struct {
  8. *tview.Application
  9. }
  10. func newApplication() *Application {
  11. app := &Application{
  12. Application: tview.NewApplication(),
  13. }
  14. app.EnableMouse(cfg.Mouse)
  15. app.SetInputCapture(app.onInputCapture)
  16. return app
  17. }
  18. func (app *Application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  19. switch event.Name() {
  20. case cfg.Keys.Quit:
  21. app.Stop()
  22. case "Ctrl+C":
  23. // https://github.com/rivo/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  24. return tcell.NewEventKey(tcell.KeyCtrlC, 0, tcell.ModNone)
  25. }
  26. return event
  27. }
  28. func (app *Application) Show(token string) error {
  29. if token == "" {
  30. loginForm := NewLoginForm(func(token string, err error) {
  31. if err != nil {
  32. slog.Error("failed to login", "err", err)
  33. return
  34. }
  35. if err := app.Show(token); err != nil {
  36. slog.Error("failed to show app", "err", err)
  37. }
  38. })
  39. app.SetRoot(loginForm, true)
  40. } else {
  41. if err := openState(token); err != nil {
  42. return err
  43. }
  44. app.SetRoot(mainFlex, true)
  45. }
  46. return nil
  47. }
  48. func (app *Application) Run(token string) error {
  49. if err := app.Show(token); err != nil {
  50. return err
  51. }
  52. return app.Application.Run()
  53. }