application.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // mainFlex must be initialized before opening a new state.
  42. mainFlex = newMainFlex()
  43. if err := openState(token); err != nil {
  44. return err
  45. }
  46. app.SetRoot(mainFlex, true)
  47. }
  48. return nil
  49. }
  50. func (app *Application) Run(token string) error {
  51. if err := app.show(token); err != nil {
  52. return err
  53. }
  54. return app.Application.Run()
  55. }