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. if token == "" {
  37. loginForm := login.NewForm(a.Application, a.cfg, func(token string) {
  38. if err := a.run(token); err != nil {
  39. slog.Error("failed to run application", "err", err)
  40. }
  41. })
  42. return a.SetRoot(loginForm, true).Run()
  43. }
  44. a.chatView = newChatView(a.Application, a.cfg)
  45. if err := openState(token); err != nil {
  46. return err
  47. }
  48. return a.SetRoot(a.chatView, true).Run()
  49. }
  50. func (a *application) quit() {
  51. if discordState != nil {
  52. if err := discordState.Close(); err != nil {
  53. slog.Error("failed to close the session", "err", err)
  54. }
  55. }
  56. a.Stop()
  57. }
  58. func (a *application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  59. switch event.Name() {
  60. case a.cfg.Keys.Quit:
  61. a.quit()
  62. return nil
  63. case "Ctrl+C":
  64. // https://github.com/ayn2op/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  65. return tcell.NewEventKey(tcell.KeyCtrlC, 0, tcell.ModNone)
  66. }
  67. return event
  68. }