view.go 11 KB

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