application.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.run(token); err != nil {
  47. slog.Error("failed to run application", "err", err)
  48. }
  49. })
  50. a.SetRoot(loginForm)
  51. } else {
  52. a.chatView = newChatView(a.Application, a.cfg)
  53. if err := openState(token); err != nil {
  54. return err
  55. }
  56. a.SetRoot(a.chatView)
  57. }
  58. return a.Run()
  59. }
  60. func (a *application) quit() {
  61. if discordState != nil {
  62. if err := discordState.Close(); err != nil {
  63. slog.Error("failed to close the session", "err", err)
  64. }
  65. }
  66. a.Stop()
  67. }
  68. func (a *application) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  69. switch event.Name() {
  70. case a.cfg.Keys.Quit:
  71. a.quit()
  72. return nil
  73. case "Ctrl+C":
  74. // https://github.com/ayn2op/tview/blob/a64fc48d7654432f71922c8b908280cdb525805c/application.go#L153
  75. return tcell.NewEventKey(tcell.KeyCtrlC, "", tcell.ModNone)
  76. }
  77. return event
  78. }