view.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "sync"
  6. "time"
  7. "github.com/ayn2op/discordo/internal/config"
  8. "github.com/ayn2op/discordo/internal/ui"
  9. "github.com/ayn2op/tview"
  10. "github.com/ayn2op/tview/help"
  11. "github.com/ayn2op/tview/keybind"
  12. "github.com/ayn2op/tview/layers"
  13. "github.com/diamondburned/arikawa/v3/discord"
  14. "github.com/diamondburned/ningen/v3"
  15. "github.com/diamondburned/ningen/v3/states/read"
  16. "github.com/gdamore/tcell/v3"
  17. )
  18. const typingDuration = 10 * time.Second
  19. const (
  20. flexLayerName = "flex"
  21. mentionsListLayerName = "mentionsList"
  22. attachmentsListLayerName = "attachmentsList"
  23. confirmModalLayerName = "confirmModal"
  24. channelsPickerLayerName = "channelsPicker"
  25. )
  26. type View struct {
  27. *layers.Layers
  28. rootFlex *tview.Flex
  29. mainFlex *tview.Flex
  30. rightFlex *tview.Flex
  31. guildsTree *guildsTree
  32. messagesList *messagesList
  33. messageInput *messageInput
  34. channelsPicker *channelsPicker
  35. help *help.Help
  36. selectedChannel *discord.Channel
  37. selectedChannelMu sync.RWMutex
  38. typersMu sync.RWMutex
  39. typers map[discord.UserID]*time.Timer
  40. app *tview.Application
  41. cfg *config.Config
  42. state *ningen.State
  43. token string
  44. }
  45. func NewView(app *tview.Application, cfg *config.Config, token string) *View {
  46. v := &View{
  47. Layers: layers.New(),
  48. rootFlex: tview.NewFlex(),
  49. mainFlex: tview.NewFlex(),
  50. rightFlex: tview.NewFlex(),
  51. typers: make(map[discord.UserID]*time.Timer),
  52. app: app,
  53. cfg: cfg,
  54. token: token,
  55. }
  56. v.guildsTree = newGuildsTree(cfg, v)
  57. v.messagesList = newMessagesList(cfg, v)
  58. v.messageInput = newMessageInput(cfg, v)
  59. v.channelsPicker = newChannelsPicker(cfg, v)
  60. v.channelsPicker.SetCancelFunc(v.closePicker)
  61. v.help = help.New()
  62. styles := help.DefaultStyles()
  63. styles.ShortKeyStyle = cfg.Theme.Help.ShortKeyStyle.Style
  64. styles.ShortDescStyle = cfg.Theme.Help.ShortDescStyle.Style
  65. styles.FullKeyStyle = cfg.Theme.Help.FullKeyStyle.Style
  66. styles.FullDescStyle = cfg.Theme.Help.FullDescStyle.Style
  67. v.help.SetStyles(styles)
  68. v.help.SetKeyMap(v)
  69. v.help.SetCompactModifiers(cfg.Help.CompactModifiers)
  70. v.help.SetShortSeparator(cfg.Help.Separator)
  71. v.help.SetBorderPadding(0, 0, cfg.Help.Padding[0], cfg.Help.Padding[1])
  72. v.SetBackgroundLayerStyle(v.cfg.Theme.Dialog.BackgroundStyle.Style)
  73. v.buildLayout()
  74. return v
  75. }
  76. func (v *View) SelectedChannel() *discord.Channel {
  77. v.selectedChannelMu.RLock()
  78. defer v.selectedChannelMu.RUnlock()
  79. return v.selectedChannel
  80. }
  81. func (v *View) SetSelectedChannel(channel *discord.Channel) {
  82. v.selectedChannelMu.Lock()
  83. v.selectedChannel = channel
  84. v.selectedChannelMu.Unlock()
  85. }
  86. func (v *View) buildLayout() {
  87. v.Clear()
  88. v.rootFlex.Clear()
  89. v.rightFlex.Clear()
  90. v.mainFlex.Clear()
  91. v.rightFlex.
  92. SetDirection(tview.FlexRow).
  93. AddItem(v.messagesList, 0, 1, false).
  94. AddItem(v.messageInput, 3, 1, false)
  95. // The guilds tree is always focused first at start-up.
  96. v.mainFlex.
  97. AddItem(v.guildsTree, 0, 1, true).
  98. AddItem(v.rightFlex, 0, 4, false)
  99. v.rootFlex.
  100. SetDirection(tview.FlexRow).
  101. AddItem(v.mainFlex, 0, 1, true).
  102. AddItem(v.help, 1, 0, false)
  103. v.updateHelpHeight()
  104. v.AddLayer(v.rootFlex, layers.WithName(flexLayerName), layers.WithResize(true), layers.WithVisible(true))
  105. v.AddLayer(v.messageInput.mentionsList, layers.WithName(mentionsListLayerName), layers.WithResize(false), layers.WithVisible(false))
  106. }
  107. func (v *View) togglePicker() {
  108. if v.HasLayer(channelsPickerLayerName) {
  109. v.closePicker()
  110. } else {
  111. v.openPicker()
  112. }
  113. }
  114. func (v *View) openPicker() {
  115. v.AddLayer(
  116. ui.Centered(v.channelsPicker, v.cfg.Picker.Width, v.cfg.Picker.Height),
  117. layers.WithName(channelsPickerLayerName),
  118. layers.WithResize(true),
  119. layers.WithVisible(true),
  120. layers.WithOverlay(),
  121. ).SendToFront(channelsPickerLayerName)
  122. v.channelsPicker.update()
  123. }
  124. func (v *View) closePicker() {
  125. v.RemoveLayer(channelsPickerLayerName)
  126. v.channelsPicker.Update()
  127. }
  128. func (v *View) toggleGuildsTree() {
  129. // The guilds tree is visible if the number of items is two.
  130. if v.mainFlex.GetItemCount() == 2 {
  131. v.mainFlex.RemoveItem(v.guildsTree)
  132. if v.guildsTree.HasFocus() {
  133. v.app.SetFocus(v.mainFlex)
  134. }
  135. } else {
  136. v.buildLayout()
  137. v.app.SetFocus(v.guildsTree)
  138. }
  139. }
  140. func (v *View) focusGuildsTree() bool {
  141. // The guilds tree is not hidden if the number of items is two.
  142. if v.mainFlex.GetItemCount() == 2 {
  143. v.app.SetFocus(v.guildsTree)
  144. return true
  145. }
  146. return false
  147. }
  148. func (v *View) focusMessageInput() bool {
  149. if !v.messageInput.GetDisabled() {
  150. v.app.SetFocus(v.messageInput)
  151. return true
  152. }
  153. return false
  154. }
  155. func (v *View) focusPrevious() {
  156. switch v.app.GetFocus() {
  157. case v.messagesList: // Handle both a.messagesList and a.flex as well as other edge cases (if there is).
  158. if v.focusGuildsTree() {
  159. return
  160. }
  161. fallthrough
  162. case v.guildsTree:
  163. if v.focusMessageInput() {
  164. return
  165. }
  166. fallthrough
  167. case v.messageInput:
  168. v.app.SetFocus(v.messagesList)
  169. }
  170. }
  171. func (v *View) focusNext() {
  172. switch v.app.GetFocus() {
  173. case v.messagesList:
  174. if v.focusMessageInput() {
  175. return
  176. }
  177. fallthrough
  178. case v.messageInput: // Handle both a.messageInput and a.flex as well as other edge cases (if there is).
  179. if v.focusGuildsTree() {
  180. return
  181. }
  182. fallthrough
  183. case v.guildsTree:
  184. v.app.SetFocus(v.messagesList)
  185. }
  186. }
  187. func (v *View) HandleEvent(event tcell.Event) tview.Command {
  188. switch event := event.(type) {
  189. case *tview.InitEvent:
  190. return tview.EventCommand(func() tcell.Event {
  191. if err := v.OpenState(v.token); err != nil {
  192. slog.Error("failed to open chat state", "err", err)
  193. return tcell.NewEventError(err)
  194. }
  195. return nil
  196. })
  197. case *QuitEvent:
  198. if err := v.CloseState(); err != nil {
  199. slog.Error("failed to close the session", "err", err)
  200. }
  201. return tview.QuitCommand{}
  202. case *tview.KeyEvent:
  203. redraw := tview.RedrawCommand{}
  204. switch {
  205. case keybind.Matches(event, v.cfg.Keybinds.ToggleHelp.Keybind):
  206. v.help.SetShowAll(!v.help.ShowAll())
  207. v.updateHelpHeight()
  208. return redraw
  209. case keybind.Matches(event, v.cfg.Keybinds.FocusGuildsTree.Keybind):
  210. v.messageInput.removeMentionsList()
  211. v.focusGuildsTree()
  212. return redraw
  213. case keybind.Matches(event, v.cfg.Keybinds.FocusMessagesList.Keybind):
  214. v.messageInput.removeMentionsList()
  215. v.app.SetFocus(v.messagesList)
  216. return redraw
  217. case keybind.Matches(event, v.cfg.Keybinds.FocusMessageInput.Keybind):
  218. v.focusMessageInput()
  219. return redraw
  220. case keybind.Matches(event, v.cfg.Keybinds.FocusPrevious.Keybind):
  221. v.focusPrevious()
  222. return redraw
  223. case keybind.Matches(event, v.cfg.Keybinds.FocusNext.Keybind):
  224. v.focusNext()
  225. return redraw
  226. case keybind.Matches(event, v.cfg.Keybinds.Logout.Keybind):
  227. if err := v.CloseState(); err != nil {
  228. slog.Error("failed to close the session", "err", err)
  229. }
  230. return tview.EventCommand(func() tcell.Event { return NewLogoutEvent() })
  231. case keybind.Matches(event, v.cfg.Keybinds.ToggleGuildsTree.Keybind):
  232. v.toggleGuildsTree()
  233. return redraw
  234. case keybind.Matches(event, v.cfg.Keybinds.ToggleChannelsPicker.Keybind):
  235. v.togglePicker()
  236. return redraw
  237. }
  238. }
  239. cmd := v.Layers.HandleEvent(event)
  240. return v.consumeLayerCommands(cmd)
  241. }
  242. func (v *View) consumeLayerCommands(command tview.Command) tview.Command {
  243. if command == nil {
  244. return nil
  245. }
  246. var commands []tview.Command
  247. switch c := command.(type) {
  248. case tview.BatchCommand:
  249. commands = c
  250. default:
  251. commands = []tview.Command{c}
  252. }
  253. remaining := make([]tview.Command, 0, len(commands))
  254. for _, cmd := range commands {
  255. switch c := cmd.(type) {
  256. case layers.OpenLayerCommand:
  257. if v.HasLayer(c.Name) {
  258. v.ShowLayer(c.Name).SendToFront(c.Name)
  259. }
  260. continue
  261. case layers.CloseLayerCommand:
  262. if v.HasLayer(c.Name) {
  263. v.HideLayer(c.Name)
  264. }
  265. continue
  266. case layers.ToggleLayerCommand:
  267. if v.HasLayer(c.Name) {
  268. if v.GetVisible(c.Name) {
  269. v.HideLayer(c.Name)
  270. } else {
  271. v.ShowLayer(c.Name).SendToFront(c.Name)
  272. }
  273. }
  274. continue
  275. }
  276. remaining = append(remaining, cmd)
  277. }
  278. if len(remaining) == 0 {
  279. return nil
  280. }
  281. if len(remaining) == 1 {
  282. return remaining[0]
  283. }
  284. return tview.BatchCommand(remaining)
  285. }
  286. func (v *View) updateHelpHeight() {
  287. height := 1
  288. if v.help.ShowAll() {
  289. height = max(len(v.help.FullHelpLines(v.FullHelp(), 0)), 1)
  290. }
  291. v.rootFlex.ResizeItem(v.help, height, 0)
  292. }
  293. func (v *View) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  294. previousFocus := v.app.GetFocus()
  295. modal := tview.NewModal().
  296. SetText(prompt).
  297. AddButtons(buttons).
  298. SetDoneFunc(func(_ int, buttonLabel string) {
  299. v.RemoveLayer(confirmModalLayerName)
  300. v.app.SetFocus(previousFocus)
  301. if onDone != nil {
  302. onDone(buttonLabel)
  303. }
  304. })
  305. v.
  306. AddLayer(
  307. ui.Centered(modal, 0, 0),
  308. layers.WithName(confirmModalLayerName),
  309. layers.WithResize(true),
  310. layers.WithVisible(true),
  311. layers.WithOverlay(),
  312. ).
  313. SendToFront(confirmModalLayerName)
  314. }
  315. func (v *View) onReadUpdate(event *read.UpdateEvent) {
  316. v.app.QueueUpdateDraw(func() {
  317. // Use indexed node lookup to avoid walking the whole tree on every read
  318. // event. This runs frequently while reading/typing across channels.
  319. if event.GuildID.IsValid() {
  320. if guildNode := v.guildsTree.findNodeByReference(event.GuildID); guildNode != nil {
  321. v.guildsTree.setNodeLineStyle(guildNode, v.guildsTree.getGuildNodeStyle(event.GuildID))
  322. }
  323. }
  324. // Channel style is always updated for the target channel regardless of
  325. // whether it's in a guild or DM.
  326. if channelNode := v.guildsTree.findNodeByReference(event.ChannelID); channelNode != nil {
  327. v.guildsTree.setNodeLineStyle(channelNode, v.guildsTree.getChannelNodeStyle(event.ChannelID))
  328. }
  329. })
  330. }
  331. func (v *View) clearTypers() {
  332. v.typersMu.Lock()
  333. for _, timer := range v.typers {
  334. timer.Stop()
  335. }
  336. clear(v.typers)
  337. v.typersMu.Unlock()
  338. v.updateFooter()
  339. }
  340. func (v *View) addTyper(userID discord.UserID) {
  341. v.typersMu.Lock()
  342. typer, ok := v.typers[userID]
  343. if ok {
  344. typer.Reset(typingDuration)
  345. } else {
  346. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  347. v.removeTyper(userID)
  348. })
  349. }
  350. v.typersMu.Unlock()
  351. v.updateFooter()
  352. }
  353. func (v *View) removeTyper(userID discord.UserID) {
  354. v.typersMu.Lock()
  355. if typer, ok := v.typers[userID]; ok {
  356. typer.Stop()
  357. delete(v.typers, userID)
  358. }
  359. v.typersMu.Unlock()
  360. v.updateFooter()
  361. }
  362. func (v *View) updateFooter() {
  363. selectedChannel := v.SelectedChannel()
  364. if selectedChannel == nil {
  365. return
  366. }
  367. guildID := selectedChannel.GuildID
  368. v.typersMu.RLock()
  369. defer v.typersMu.RUnlock()
  370. var footer string
  371. if len(v.typers) > 0 {
  372. var names []string
  373. for userID := range v.typers {
  374. var name string
  375. if guildID.IsValid() {
  376. member, err := v.state.Cabinet.Member(guildID, userID)
  377. if err != nil {
  378. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  379. continue
  380. }
  381. if member.Nick != "" {
  382. name = member.Nick
  383. } else {
  384. name = member.User.DisplayOrUsername()
  385. }
  386. } else {
  387. for _, recipient := range selectedChannel.DMRecipients {
  388. if recipient.ID == userID {
  389. name = recipient.DisplayOrUsername()
  390. break
  391. }
  392. }
  393. }
  394. if name != "" {
  395. names = append(names, name)
  396. }
  397. }
  398. switch len(names) {
  399. case 1:
  400. footer = fmt.Sprintf("%s is typing...", names[0])
  401. case 2:
  402. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  403. case 3:
  404. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  405. default:
  406. footer = "Several people are typing..."
  407. }
  408. }
  409. go v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  410. }