core.go 7.9 KB

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