application.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package cmd
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "github.com/ayn2op/discordo/internal/clipboard"
  6. "github.com/ayn2op/discordo/internal/config"
  7. "github.com/ayn2op/discordo/internal/consts"
  8. "github.com/ayn2op/discordo/internal/login"
  9. "github.com/ayn2op/tview"
  10. "github.com/gdamore/tcell/v3"
  11. )
  12. type application struct {
  13. *tview.Application
  14. chatView *chatView
  15. cfg *config.Config
  16. }
  17. func newApplication(cfg *config.Config) *application {
  18. tview.Styles = tview.Theme{}
  19. app := &application{
  20. Application: tview.NewApplication(),
  21. cfg: cfg,
  22. }
  23. if err := clipboard.Init(); err != nil {
  24. slog.Error("failed to init clipboard", "err", err)
  25. }
  26. app.SetInputCapture(app.onInputCapture)
  27. return app
  28. }
  29. func (a *application) run(token string) error {
  30. screen, err := tcell.NewScreen()
  31. if err != nil {
  32. return fmt.Errorf("failed to create screen: %w", err)
  33. }
  34. if err := screen.Init(); err != nil {
  35. return fmt.Errorf("failed to init screen: %w", err)
  36. }
  37. if a.cfg.Mouse {
  38. screen.EnableMouse()
  39. }
  40. screen.SetTitle(consts.Name)
  41. screen.EnablePaste()
  42. screen.EnableFocus()
  43. a.SetScreen(screen)
  44. if token == "" {
  45. loginForm := login.NewForm(a.Application, a.cfg, func(token string) {
  46. if err := a.showChatView(token); err != nil {
  47. slog.Error("failed to show chat view", "err", err)
  48. }
  49. })
  50. a.SetRoot(loginForm)
  51. } else {
  52. if err := a.showChatView(token); err != nil {
  53. return err
  54. }
  55. }
  56. return a.Run()
  57. }
  58. func (a *application) showChatView(token string) error {
  59. a.chatView = newChatView(a.Application, a.cfg)
  60. if err := openState(token); err != nil {
  61. return err
  62. }
  63. a.SetRoot(a.chatView)
  64. return nil
  65. }
  66. func (a *application) quit() {
  67. if discordState != nil {
  68. if err := discordState.Close(); err != nil {
  69. slog.Error("failed to close the session", "err", err)
  70. }
  71. }
  72. a.Stop()
  73. }
  74. func (a *application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  75. switch event.Name() {
  76. case a.cfg.Keys.Quit:
  77. a.quit()
  78. return nil
  79. case "Ctrl+C":
  80. // https://github.com/ayn2op/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  81. return tcell.NewEventKey(tcell.KeyCtrlC, "", tcell.ModNone)
  82. }
  83. return event
  84. }