view.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. }
  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) handleInput(event *tcell.EventKey) *tcell.EventKey {
  188. switch {
  189. case keybind.Matches(event, v.cfg.Keybinds.ToggleHelp.Keybind):
  190. v.help.SetShowAll(!v.help.ShowAll())
  191. v.updateHelpHeight()
  192. return nil
  193. case keybind.Matches(event, v.cfg.Keybinds.FocusGuildsTree.Keybind):
  194. v.messageInput.removeMentionsList()
  195. v.focusGuildsTree()
  196. return nil
  197. case keybind.Matches(event, v.cfg.Keybinds.FocusMessagesList.Keybind):
  198. v.messageInput.removeMentionsList()
  199. v.app.SetFocus(v.messagesList)
  200. return nil
  201. case keybind.Matches(event, v.cfg.Keybinds.FocusMessageInput.Keybind):
  202. v.focusMessageInput()
  203. return nil
  204. case keybind.Matches(event, v.cfg.Keybinds.FocusPrevious.Keybind):
  205. v.focusPrevious()
  206. return nil
  207. case keybind.Matches(event, v.cfg.Keybinds.FocusNext.Keybind):
  208. v.focusNext()
  209. return nil
  210. case keybind.Matches(event, v.cfg.Keybinds.Logout.Keybind):
  211. if v.onLogout != nil {
  212. v.onLogout()
  213. }
  214. if err := keyring.DeleteToken(); err != nil {
  215. slog.Error("failed to delete token from keyring", "err", err)
  216. return nil
  217. }
  218. return nil
  219. case keybind.Matches(event, v.cfg.Keybinds.ToggleGuildsTree.Keybind):
  220. v.toggleGuildsTree()
  221. return nil
  222. case keybind.Matches(event, v.cfg.Keybinds.ToggleChannelsPicker.Keybind):
  223. v.togglePicker()
  224. return nil
  225. }
  226. return event
  227. }
  228. func (v *View) InputHandler(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
  229. event = v.handleInput(event)
  230. if event == nil {
  231. return
  232. }
  233. v.Layers.InputHandler(event, setFocus)
  234. }
  235. func (v *View) updateHelpHeight() {
  236. height := 1
  237. if v.help.ShowAll() {
  238. height = len(v.help.FullHelpLines(v.FullHelp(), 0))
  239. if height < 1 {
  240. height = 1
  241. }
  242. }
  243. v.rootFlex.ResizeItem(v.help, height, 0)
  244. }
  245. func (v *View) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  246. previousFocus := v.app.GetFocus()
  247. modal := tview.NewModal().
  248. SetText(prompt).
  249. AddButtons(buttons).
  250. SetDoneFunc(func(_ int, buttonLabel string) {
  251. v.RemoveLayer(confirmModalLayerName)
  252. v.app.SetFocus(previousFocus)
  253. if onDone != nil {
  254. onDone(buttonLabel)
  255. }
  256. })
  257. v.
  258. AddLayer(
  259. ui.Centered(modal, 0, 0),
  260. layers.WithName(confirmModalLayerName),
  261. layers.WithResize(true),
  262. layers.WithVisible(true),
  263. layers.WithOverlay(),
  264. ).
  265. SendToFront(confirmModalLayerName)
  266. }
  267. func (v *View) onReadUpdate(event *read.UpdateEvent) {
  268. // Use indexed node lookup to avoid walking the whole tree on every read
  269. // event. This runs frequently while reading/typing across channels.
  270. var updated bool
  271. if event.GuildID.IsValid() {
  272. if guildNode := v.guildsTree.findNodeByReference(event.GuildID); guildNode != nil {
  273. v.guildsTree.setNodeLineStyle(guildNode, v.guildsTree.getGuildNodeStyle(event.GuildID))
  274. updated = true
  275. }
  276. }
  277. // Channel style is always updated for the target channel regardless of
  278. // whether it's in a guild or DM.
  279. if channelNode := v.guildsTree.findNodeByReference(event.ChannelID); channelNode != nil {
  280. v.guildsTree.setNodeLineStyle(channelNode, v.guildsTree.getChannelNodeStyle(event.ChannelID))
  281. updated = true
  282. }
  283. if updated {
  284. v.app.Draw()
  285. }
  286. }
  287. func (v *View) clearTypers() {
  288. v.typersMu.Lock()
  289. for _, timer := range v.typers {
  290. timer.Stop()
  291. }
  292. clear(v.typers)
  293. v.typersMu.Unlock()
  294. v.updateFooter()
  295. }
  296. func (v *View) addTyper(userID discord.UserID) {
  297. v.typersMu.Lock()
  298. typer, ok := v.typers[userID]
  299. if ok {
  300. typer.Reset(typingDuration)
  301. } else {
  302. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  303. v.removeTyper(userID)
  304. })
  305. }
  306. v.typersMu.Unlock()
  307. v.updateFooter()
  308. }
  309. func (v *View) removeTyper(userID discord.UserID) {
  310. v.typersMu.Lock()
  311. if typer, ok := v.typers[userID]; ok {
  312. typer.Stop()
  313. delete(v.typers, userID)
  314. }
  315. v.typersMu.Unlock()
  316. v.updateFooter()
  317. }
  318. func (v *View) updateFooter() {
  319. selectedChannel := v.SelectedChannel()
  320. if selectedChannel == nil {
  321. return
  322. }
  323. guildID := selectedChannel.GuildID
  324. v.typersMu.RLock()
  325. defer v.typersMu.RUnlock()
  326. var footer string
  327. if len(v.typers) > 0 {
  328. var names []string
  329. for userID := range v.typers {
  330. var name string
  331. if guildID.IsValid() {
  332. member, err := v.state.Cabinet.Member(guildID, userID)
  333. if err != nil {
  334. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  335. continue
  336. }
  337. if member.Nick != "" {
  338. name = member.Nick
  339. } else {
  340. name = member.User.DisplayOrUsername()
  341. }
  342. } else {
  343. for _, recipient := range selectedChannel.DMRecipients {
  344. if recipient.ID == userID {
  345. name = recipient.DisplayOrUsername()
  346. break
  347. }
  348. }
  349. }
  350. if name != "" {
  351. names = append(names, name)
  352. }
  353. }
  354. switch len(names) {
  355. case 1:
  356. footer = fmt.Sprintf("%s is typing...", names[0])
  357. case 2:
  358. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  359. case 3:
  360. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  361. default:
  362. footer = "Several people are typing..."
  363. }
  364. }
  365. go v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  366. }