application.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. tview.Styles = tview.Theme{}
  23. app := &application{
  24. Application: tview.NewApplication(),
  25. cfg: cfg,
  26. }
  27. if err := clipboard.Init(); err != nil {
  28. slog.Error("failed to init clipboard", "err", err)
  29. }
  30. app.
  31. EnableMouse(cfg.Mouse).
  32. SetInputCapture(app.onInputCapture).
  33. EnablePaste(true)
  34. return app
  35. }
  36. func (a *application) run(token string) error {
  37. var root tview.Primitive
  38. if token == "" {
  39. root = login.NewForm(a.Application, a.cfg, func(token string) {
  40. if err := a.run(token); err != nil {
  41. slog.Error("failed to run application", "err", err)
  42. }
  43. })
  44. } else {
  45. a.chatView = newChatView(a.Application, a.cfg)
  46. root = a.chatView
  47. if err := openState(token); err != nil {
  48. return err
  49. }
  50. }
  51. return a.SetRoot(root, true).Run()
  52. }
  53. func (a *application) quit() {
  54. if discordState != nil {
  55. if err := discordState.Close(); err != nil {
  56. slog.Error("failed to close the session", "err", err)
  57. }
  58. }
  59. a.Stop()
  60. }
  61. func (a *application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  62. switch event.Name() {
  63. case a.cfg.Keys.Quit:
  64. a.quit()
  65. return nil
  66. case "Ctrl+C":
  67. // https://github.com/ayn2op/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  68. return tcell.NewEventKey(tcell.KeyCtrlC, 0, tcell.ModNone)
  69. }
  70. return event
  71. }