application.go 1.6 KB

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