core.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package ui
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/ayntgl/discordo/config"
  6. "github.com/diamondburned/arikawa/v3/api"
  7. "github.com/diamondburned/arikawa/v3/discord"
  8. "github.com/diamondburned/arikawa/v3/gateway"
  9. "github.com/diamondburned/arikawa/v3/state"
  10. "github.com/gdamore/tcell/v2"
  11. "github.com/rivo/tview"
  12. lua "github.com/yuin/gopher-lua"
  13. luar "layeh.com/gopher-luar"
  14. )
  15. type focused int
  16. const (
  17. guildsTree focused = iota
  18. channelsTree
  19. messagesPanel
  20. messageInput
  21. )
  22. // Core is responsible for the following:
  23. // - Initialization of the application, UI elements, configuration, and state.
  24. // - Configuration of the application and state when Run is called.
  25. // - Management of the application and state.
  26. type Core struct {
  27. Application *tview.Application
  28. MainFlex *tview.Flex
  29. GuildsTree *GuildsTree
  30. ChannelsTree *ChannelsTree
  31. MessagesPanel *MessagesPanel
  32. MessageInput *MessageInput
  33. Config *config.Config
  34. State *state.State
  35. focused focused
  36. }
  37. func NewCore(cfg *config.Config) *Core {
  38. c := &Core{
  39. Application: tview.NewApplication(),
  40. MainFlex: tview.NewFlex(),
  41. Config: cfg,
  42. }
  43. c.Application.SetInputCapture(c.onInputCapture)
  44. c.GuildsTree = NewGuildsTree(c)
  45. c.ChannelsTree = NewChannelsTree(c)
  46. c.MessagesPanel = NewMessagesPanel(c)
  47. c.MessageInput = NewMessageInput(c)
  48. return c
  49. }
  50. func (c *Core) Run(token string) error {
  51. c.register()
  52. err := c.Config.State.DoString(string(config.LuaConfig))
  53. if err != nil {
  54. return err
  55. }
  56. c.Application.EnableMouse(lua.LVAsBool(c.Config.State.GetGlobal("mouse")))
  57. identifyProperties, ok := c.Config.State.GetGlobal("identifyProperties").(*lua.LTable)
  58. if !ok {
  59. identifyProperties = c.Config.State.NewTable()
  60. }
  61. userAgent := lua.LVAsString(identifyProperties.RawGetString("userAgent"))
  62. c.State = state.NewWithIdentifier(gateway.NewIdentifier(gateway.IdentifyCommand{
  63. Token: token,
  64. Intents: nil,
  65. Properties: gateway.IdentifyProperties{
  66. Browser: lua.LVAsString(identifyProperties.RawGetString("browser")),
  67. BrowserVersion: lua.LVAsString(identifyProperties.RawGetString("browserVersion")),
  68. BrowserUserAgent: userAgent,
  69. OS: lua.LVAsString(identifyProperties.RawGetString("os")),
  70. },
  71. // The official client sets the compress field as false.
  72. Compress: false,
  73. }))
  74. // For user accounts, all of the guilds, the user is in, are dispatched in the READY gateway event. Whereas, the guilds are dispatched discretely in the GUILD_CREATE gateway events for bot accounts.
  75. if !strings.HasPrefix(c.State.Token, "Bot") {
  76. api.UserAgent = userAgent
  77. c.State.AddHandler(c.onStateReady)
  78. } else {
  79. c.State.AddIntents(gateway.IntentGuilds | gateway.IntentGuildMessages)
  80. }
  81. c.State.AddHandler(c.onStateGuildCreate)
  82. c.State.AddHandler(c.onStateGuildDelete)
  83. c.State.AddHandler(c.onStateMessageCreate)
  84. return c.State.Open(context.Background())
  85. }
  86. func (c *Core) register() {
  87. c.Config.State.SetGlobal("key", c.Config.State.NewFunction(c.Config.KeyLua))
  88. // Messages panel
  89. c.Config.State.SetGlobal("openMessageActionsList", c.Config.State.NewFunction(c.MessagesPanel.openMessageActionsListLua))
  90. c.Config.State.SetGlobal("selectPreviousMessage", c.Config.State.NewFunction(c.MessagesPanel.selectPreviousMessageLua))
  91. c.Config.State.SetGlobal("selectNextMessage", c.Config.State.NewFunction(c.MessagesPanel.selectNextMessageLua))
  92. c.Config.State.SetGlobal("selectFirstMessage", c.Config.State.NewFunction(c.MessagesPanel.selectFirstMessageLua))
  93. c.Config.State.SetGlobal("selectLastMessage", c.Config.State.NewFunction(c.MessagesPanel.selectLastMessageLua))
  94. // Message input
  95. c.Config.State.SetGlobal("openExternalEditor", c.Config.State.NewFunction(c.MessageInput.openExternalEditorLua))
  96. c.Config.State.SetGlobal("pasteClipboardContent", c.Config.State.NewFunction(c.MessageInput.pasteClipboardContentLua))
  97. }
  98. func (c *Core) DrawMainFlex() {
  99. leftFlex := tview.NewFlex().
  100. SetDirection(tview.FlexRow).
  101. AddItem(c.GuildsTree, 10, 1, false).
  102. AddItem(c.ChannelsTree, 0, 1, false)
  103. rightFlex := tview.NewFlex().
  104. SetDirection(tview.FlexRow).
  105. AddItem(c.MessagesPanel, 0, 1, false).
  106. AddItem(c.MessageInput, 3, 1, false)
  107. c.MainFlex.
  108. AddItem(leftFlex, 0, 1, false).
  109. AddItem(rightFlex, 0, 4, false)
  110. }
  111. func (c *Core) onInputCapture(e *tcell.EventKey) *tcell.EventKey {
  112. // If the main flex is nil, that is, it is not initialized yet, then the login form is currently focused.
  113. if c.MainFlex == nil {
  114. return e
  115. }
  116. keysTable, ok := c.Config.State.GetGlobal("keys").(*lua.LTable)
  117. if !ok {
  118. keysTable = c.Config.State.NewTable()
  119. }
  120. applicationTable, ok := keysTable.RawGetString("application").(*lua.LTable)
  121. if !ok {
  122. applicationTable = c.Config.State.NewTable()
  123. }
  124. var fn lua.LValue
  125. applicationTable.ForEach(func(k, v lua.LValue) {
  126. keyTable := v.(*lua.LTable)
  127. if e.Name() == lua.LVAsString(keyTable.RawGetString("name")) {
  128. fn = keyTable.RawGetString("action")
  129. }
  130. })
  131. if fn != nil {
  132. c.Config.State.CallByParam(lua.P{
  133. Fn: fn,
  134. NRet: 1,
  135. Protect: true,
  136. }, luar.New(c.Config.State, c), luar.New(c.Config.State, e))
  137. // Returned value
  138. ret, ok := c.Config.State.Get(-1).(*lua.LUserData)
  139. if !ok {
  140. return e
  141. }
  142. // Remove returned value
  143. c.Config.State.Pop(1)
  144. ev, ok := ret.Value.(*tcell.EventKey)
  145. if ok {
  146. return ev
  147. }
  148. }
  149. // Default
  150. switch e.Key() {
  151. case tcell.KeyEsc:
  152. c.focused = 0
  153. case tcell.KeyBacktab:
  154. // If the currently focused widget is the guilds tree widget (first), then focus the message input widget (last)
  155. if c.focused == 0 {
  156. c.focused = messageInput
  157. } else {
  158. c.focused--
  159. }
  160. c.setFocus()
  161. case tcell.KeyTab:
  162. // If the currently focused widget is the message input widget (last), then focus the guilds tree widget (first)
  163. if c.focused == messageInput {
  164. c.focused = guildsTree
  165. } else {
  166. c.focused++
  167. }
  168. c.setFocus()
  169. }
  170. return e
  171. }
  172. func (c *Core) setFocus() {
  173. var p tview.Primitive
  174. switch c.focused {
  175. case guildsTree:
  176. p = c.GuildsTree
  177. case channelsTree:
  178. p = c.ChannelsTree
  179. case messagesPanel:
  180. p = c.MessagesPanel
  181. case messageInput:
  182. p = c.MessageInput
  183. }
  184. c.Application.SetFocus(p)
  185. }
  186. func (c *Core) onStateReady(r *gateway.ReadyEvent) {
  187. rootNode := c.GuildsTree.GetRoot()
  188. for _, gf := range r.UserSettings.GuildFolders {
  189. if gf.ID == 0 {
  190. for _, gID := range gf.GuildIDs {
  191. g, err := c.State.Cabinet.Guild(gID)
  192. if err != nil {
  193. return
  194. }
  195. guildNode := tview.NewTreeNode(g.Name)
  196. guildNode.SetReference(g.ID)
  197. rootNode.AddChild(guildNode)
  198. }
  199. } else {
  200. var b strings.Builder
  201. if gf.Color != discord.NullColor {
  202. b.WriteByte('[')
  203. b.WriteString(gf.Color.String())
  204. b.WriteByte(']')
  205. } else {
  206. b.WriteString("[#ED4245]")
  207. }
  208. if gf.Name != "" {
  209. b.WriteString(gf.Name)
  210. } else {
  211. b.WriteString("Folder")
  212. }
  213. b.WriteString("[-]")
  214. folderNode := tview.NewTreeNode(b.String())
  215. rootNode.AddChild(folderNode)
  216. for _, gID := range gf.GuildIDs {
  217. g, err := c.State.Cabinet.Guild(gID)
  218. if err != nil {
  219. return
  220. }
  221. guildNode := tview.NewTreeNode(g.Name)
  222. guildNode.SetReference(g.ID)
  223. folderNode.AddChild(guildNode)
  224. }
  225. }
  226. }
  227. c.GuildsTree.SetCurrentNode(rootNode)
  228. c.Application.SetFocus(c.GuildsTree)
  229. }
  230. func (c *Core) onStateGuildCreate(g *gateway.GuildCreateEvent) {
  231. guildNode := tview.NewTreeNode(g.Name)
  232. guildNode.SetReference(g.ID)
  233. rootNode := c.GuildsTree.GetRoot()
  234. rootNode.AddChild(guildNode)
  235. c.GuildsTree.SetCurrentNode(rootNode)
  236. c.Application.SetFocus(c.GuildsTree)
  237. c.Application.Draw()
  238. }
  239. func (c *Core) onStateGuildDelete(g *gateway.GuildDeleteEvent) {
  240. rootNode := c.GuildsTree.GetRoot()
  241. var parentNode *tview.TreeNode
  242. rootNode.Walk(func(node, _ *tview.TreeNode) bool {
  243. if node.GetReference() == g.ID {
  244. parentNode = node
  245. return false
  246. }
  247. return true
  248. })
  249. if parentNode != nil {
  250. rootNode.RemoveChild(parentNode)
  251. }
  252. c.Application.Draw()
  253. }
  254. func (c *Core) onStateMessageCreate(m *gateway.MessageCreateEvent) {
  255. if c.ChannelsTree.SelectedChannel != nil && c.ChannelsTree.SelectedChannel.ID == m.ChannelID {
  256. _, err := c.MessagesPanel.Write(buildMessage(c, m.Message))
  257. if err != nil {
  258. return
  259. }
  260. if len(c.MessagesPanel.GetHighlights()) == 0 {
  261. c.MessagesPanel.ScrollToEnd()
  262. }
  263. }
  264. }