view.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. return v.logout()
  228. case keybind.Matches(event, v.cfg.Keybinds.ToggleGuildsTree.Keybind):
  229. v.toggleGuildsTree()
  230. return redraw
  231. case keybind.Matches(event, v.cfg.Keybinds.ToggleChannelsPicker.Keybind):
  232. v.togglePicker()
  233. return redraw
  234. }
  235. }
  236. cmd := v.Layers.HandleEvent(event)
  237. return v.consumeLayerCommands(cmd)
  238. }
  239. func (v *View) consumeLayerCommands(command tview.Command) tview.Command {
  240. if command == nil {
  241. return nil
  242. }
  243. var commands []tview.Command
  244. switch c := command.(type) {
  245. case tview.BatchCommand:
  246. commands = c
  247. default:
  248. commands = []tview.Command{c}
  249. }
  250. remaining := make([]tview.Command, 0, len(commands))
  251. for _, cmd := range commands {
  252. switch c := cmd.(type) {
  253. case layers.OpenLayerCommand:
  254. if v.HasLayer(c.Name) {
  255. v.ShowLayer(c.Name).SendToFront(c.Name)
  256. }
  257. continue
  258. case layers.CloseLayerCommand:
  259. if v.HasLayer(c.Name) {
  260. v.HideLayer(c.Name)
  261. }
  262. continue
  263. case layers.ToggleLayerCommand:
  264. if v.HasLayer(c.Name) {
  265. if v.GetVisible(c.Name) {
  266. v.HideLayer(c.Name)
  267. } else {
  268. v.ShowLayer(c.Name).SendToFront(c.Name)
  269. }
  270. }
  271. continue
  272. }
  273. remaining = append(remaining, cmd)
  274. }
  275. if len(remaining) == 0 {
  276. return nil
  277. }
  278. if len(remaining) == 1 {
  279. return remaining[0]
  280. }
  281. return tview.BatchCommand(remaining)
  282. }
  283. func (v *View) updateHelpHeight() {
  284. height := 1
  285. if v.help.ShowAll() {
  286. height = max(len(v.help.FullHelpLines(v.FullHelp(), 0)), 1)
  287. }
  288. v.rootFlex.ResizeItem(v.help, height, 0)
  289. }
  290. func (v *View) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  291. previousFocus := v.app.GetFocus()
  292. modal := tview.NewModal().
  293. SetText(prompt).
  294. AddButtons(buttons).
  295. SetDoneFunc(func(_ int, buttonLabel string) {
  296. v.RemoveLayer(confirmModalLayerName)
  297. v.app.SetFocus(previousFocus)
  298. if onDone != nil {
  299. onDone(buttonLabel)
  300. }
  301. })
  302. v.
  303. AddLayer(
  304. ui.Centered(modal, 0, 0),
  305. layers.WithName(confirmModalLayerName),
  306. layers.WithResize(true),
  307. layers.WithVisible(true),
  308. layers.WithOverlay(),
  309. ).
  310. SendToFront(confirmModalLayerName)
  311. }
  312. func (v *View) onReadUpdate(event *read.UpdateEvent) {
  313. v.app.QueueUpdateDraw(func() {
  314. // Use indexed node lookup to avoid walking the whole tree on every read
  315. // event. This runs frequently while reading/typing across channels.
  316. if event.GuildID.IsValid() {
  317. if guildNode := v.guildsTree.findNodeByReference(event.GuildID); guildNode != nil {
  318. v.guildsTree.setNodeLineStyle(guildNode, v.guildsTree.getGuildNodeStyle(event.GuildID))
  319. }
  320. }
  321. // Channel style is always updated for the target channel regardless of
  322. // whether it's in a guild or DM.
  323. if channelNode := v.guildsTree.findNodeByReference(event.ChannelID); channelNode != nil {
  324. v.guildsTree.setNodeLineStyle(channelNode, v.guildsTree.getChannelNodeStyle(event.ChannelID))
  325. }
  326. })
  327. }
  328. func (v *View) clearTypers() {
  329. v.typersMu.Lock()
  330. for _, timer := range v.typers {
  331. timer.Stop()
  332. }
  333. clear(v.typers)
  334. v.typersMu.Unlock()
  335. v.updateFooter()
  336. }
  337. func (v *View) addTyper(userID discord.UserID) {
  338. v.typersMu.Lock()
  339. typer, ok := v.typers[userID]
  340. if ok {
  341. typer.Reset(typingDuration)
  342. } else {
  343. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  344. v.removeTyper(userID)
  345. })
  346. }
  347. v.typersMu.Unlock()
  348. v.updateFooter()
  349. }
  350. func (v *View) removeTyper(userID discord.UserID) {
  351. v.typersMu.Lock()
  352. if typer, ok := v.typers[userID]; ok {
  353. typer.Stop()
  354. delete(v.typers, userID)
  355. }
  356. v.typersMu.Unlock()
  357. v.updateFooter()
  358. }
  359. func (v *View) updateFooter() {
  360. selectedChannel := v.SelectedChannel()
  361. if selectedChannel == nil {
  362. return
  363. }
  364. guildID := selectedChannel.GuildID
  365. v.typersMu.RLock()
  366. defer v.typersMu.RUnlock()
  367. var footer string
  368. if len(v.typers) > 0 {
  369. var names []string
  370. for userID := range v.typers {
  371. var name string
  372. if guildID.IsValid() {
  373. member, err := v.state.Cabinet.Member(guildID, userID)
  374. if err != nil {
  375. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  376. continue
  377. }
  378. if member.Nick != "" {
  379. name = member.Nick
  380. } else {
  381. name = member.User.DisplayOrUsername()
  382. }
  383. } else {
  384. for _, recipient := range selectedChannel.DMRecipients {
  385. if recipient.ID == userID {
  386. name = recipient.DisplayOrUsername()
  387. break
  388. }
  389. }
  390. }
  391. if name != "" {
  392. names = append(names, name)
  393. }
  394. }
  395. switch len(names) {
  396. case 1:
  397. footer = fmt.Sprintf("%s is typing...", names[0])
  398. case 2:
  399. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  400. case 3:
  401. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  402. default:
  403. footer = "Several people are typing..."
  404. }
  405. }
  406. go v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  407. }