application.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package cmd
  2. import (
  3. "log/slog"
  4. "github.com/ayn2op/discordo/internal/config"
  5. "github.com/ayn2op/discordo/internal/login"
  6. "github.com/ayn2op/tview"
  7. "github.com/gdamore/tcell/v2"
  8. "golang.design/x/clipboard"
  9. )
  10. const (
  11. flexPageName = "flex"
  12. mentionsListPageName = "mentionsList"
  13. attachmentsListPageName = "attachmentsList"
  14. confirmModalPageName = "confirmModal"
  15. )
  16. type application struct {
  17. *tview.Application
  18. chatView *chatView
  19. cfg *config.Config
  20. }
  21. func newApplication(cfg *config.Config) *application {
  22. app := &application{
  23. Application: tview.NewApplication(),
  24. cfg: cfg,
  25. }
  26. if err := clipboard.Init(); err != nil {
  27. slog.Error("failed to init clipboard", "err", err)
  28. }
  29. app.
  30. EnableMouse(cfg.Mouse).
  31. SetInputCapture(app.onInputCapture).
  32. EnablePaste(true)
  33. return app
  34. }
  35. func (a *application) run(token string) error {
  36. var root tview.Primitive
  37. if token == "" {
  38. root = login.NewForm(a.Application, a.cfg, func(token string) {
  39. if err := a.run(token); err != nil {
  40. slog.Error("failed to run application", "err", err)
  41. }
  42. })
  43. } else {
  44. a.chatView = newChatView(a.Application, a.cfg)
  45. root = a.chatView
  46. if err := openState(token); err != nil {
  47. return err
  48. }
  49. }
  50. return a.SetRoot(root, true).Run()
  51. }
  52. func (a *application) quit() {
  53. if discordState != nil {
  54. if err := discordState.Close(); err != nil {
  55. slog.Error("failed to close the session", "err", err)
  56. }
  57. }
  58. a.Stop()
  59. }
  60. func (a *application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  61. switch event.Name() {
  62. case a.cfg.Keys.Quit:
  63. a.quit()
  64. return nil
  65. case "Ctrl+C":
  66. // https://github.com/ayn2op/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  67. return tcell.NewEventKey(tcell.KeyCtrlC, 0, tcell.ModNone)
  68. }
  69. return event
  70. }