message_input.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. package chat
  2. import (
  3. "bytes"
  4. "io"
  5. "log/slog"
  6. "os"
  7. "path/filepath"
  8. "regexp"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "time"
  13. "unicode"
  14. "github.com/ayn2op/discordo/internal/cache"
  15. "github.com/ayn2op/discordo/internal/clipboard"
  16. "github.com/ayn2op/discordo/internal/config"
  17. "github.com/ayn2op/discordo/internal/consts"
  18. "github.com/ayn2op/discordo/internal/ui"
  19. "github.com/ayn2op/tview"
  20. "github.com/ayn2op/tview/help"
  21. "github.com/ayn2op/tview/keybind"
  22. "github.com/ayn2op/tview/layers"
  23. "github.com/diamondburned/arikawa/v3/api"
  24. "github.com/diamondburned/arikawa/v3/discord"
  25. "github.com/diamondburned/arikawa/v3/state"
  26. "github.com/diamondburned/arikawa/v3/utils/json/option"
  27. "github.com/diamondburned/arikawa/v3/utils/sendpart"
  28. "github.com/diamondburned/ningen/v3"
  29. "github.com/diamondburned/ningen/v3/discordmd"
  30. "github.com/gdamore/tcell/v3"
  31. "github.com/ncruces/zenity"
  32. "github.com/sahilm/fuzzy"
  33. "github.com/yuin/goldmark/ast"
  34. )
  35. const tmpFilePattern = consts.Name + "_*.md"
  36. var mentionRegex = regexp.MustCompile("@[a-zA-Z0-9._]+")
  37. type messageInput struct {
  38. *tview.TextArea
  39. cfg *config.Config
  40. chatView *View
  41. edit bool
  42. sendMessageData *api.SendMessageData
  43. cache *cache.Cache
  44. mentionsList *mentionsList
  45. lastSearch time.Time
  46. typingTimerMu sync.Mutex
  47. typingTimer *time.Timer
  48. }
  49. var _ help.KeyMap = (*messageInput)(nil)
  50. func newMessageInput(cfg *config.Config, chatView *View) *messageInput {
  51. mi := &messageInput{
  52. TextArea: tview.NewTextArea(),
  53. cfg: cfg,
  54. chatView: chatView,
  55. sendMessageData: &api.SendMessageData{},
  56. cache: cache.NewCache(),
  57. mentionsList: newMentionsList(cfg),
  58. }
  59. mi.Box = ui.ConfigureBox(mi.Box, &cfg.Theme)
  60. mi.
  61. SetPlaceholder(tview.NewLine(tview.NewSegment("Select a channel to start chatting", tcell.StyleDefault.Dim(true)))).
  62. SetClipboard(
  63. func(s string) { clipboard.Write(clipboard.FmtText, []byte(s)) },
  64. func() string { return string(clipboard.Read(clipboard.FmtText)) },
  65. ).
  66. SetDisabled(true)
  67. return mi
  68. }
  69. func (mi *messageInput) reset() {
  70. mi.edit = false
  71. mi.sendMessageData = &api.SendMessageData{}
  72. mi.SetTitle("")
  73. mi.SetFooter("")
  74. mi.SetText("", true)
  75. }
  76. func (mi *messageInput) stopTypingTimer() {
  77. if mi.typingTimer != nil {
  78. mi.typingTimer.Stop()
  79. mi.typingTimer = nil
  80. }
  81. }
  82. func (mi *messageInput) InputHandler(event *tcell.EventKey) tview.Command {
  83. consume := tview.ConsumeEventCommand{}
  84. consumeRedraw := tview.BatchCommand{tview.RedrawCommand{}, tview.ConsumeEventCommand{}}
  85. handler := mi.TextArea.InputHandler
  86. switch {
  87. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.Paste.Keybind):
  88. mi.paste()
  89. return handler(tcell.NewEventKey(tcell.KeyCtrlV, "", tcell.ModNone))
  90. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.Send.Keybind):
  91. if mi.chatView.GetVisible(mentionsListLayerName) {
  92. mi.tabComplete()
  93. } else {
  94. mi.send()
  95. }
  96. return consumeRedraw
  97. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.OpenEditor.Keybind):
  98. var cmd tview.Command
  99. mi.stopTabCompletion(func(next tview.Command) { cmd = tview.AppendCommand(cmd, next) })
  100. mi.editor()
  101. return tview.AppendCommand(cmd, consumeRedraw)
  102. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.OpenFilePicker.Keybind):
  103. var cmd tview.Command
  104. mi.stopTabCompletion(func(next tview.Command) { cmd = tview.AppendCommand(cmd, next) })
  105. mi.openFilePicker()
  106. return tview.AppendCommand(cmd, consumeRedraw)
  107. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.Cancel.Keybind):
  108. var cmd tview.Command
  109. if mi.chatView.GetVisible(mentionsListLayerName) {
  110. mi.stopTabCompletion(func(next tview.Command) { cmd = tview.AppendCommand(cmd, next) })
  111. } else {
  112. mi.reset()
  113. }
  114. return tview.AppendCommand(cmd, consumeRedraw)
  115. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.TabComplete.Keybind):
  116. go mi.chatView.app.QueueUpdateDraw(func() { mi.tabComplete() })
  117. return consume
  118. case keybind.Matches(event, mi.cfg.Keybinds.MessageInput.Undo.Keybind):
  119. return handler(tcell.NewEventKey(tcell.KeyCtrlZ, "", tcell.ModNone))
  120. }
  121. if mi.cfg.TypingIndicator.Send && mi.typingTimer == nil {
  122. mi.typingTimer = time.AfterFunc(typingDuration, func() {
  123. mi.typingTimerMu.Lock()
  124. mi.typingTimer = nil
  125. mi.typingTimerMu.Unlock()
  126. })
  127. if selectedChannel := mi.chatView.SelectedChannel(); selectedChannel != nil {
  128. go mi.chatView.state.Typing(selectedChannel.ID)
  129. }
  130. }
  131. if mi.cfg.AutocompleteLimit > 0 {
  132. if mi.chatView.GetVisible(mentionsListLayerName) {
  133. switch {
  134. case keybind.Matches(event, mi.cfg.Keybinds.MentionsList.Up.Keybind):
  135. mi.mentionsList.InputHandler(tcell.NewEventKey(tcell.KeyUp, "", tcell.ModNone))
  136. return consumeRedraw
  137. case keybind.Matches(event, mi.cfg.Keybinds.MentionsList.Down.Keybind):
  138. mi.mentionsList.InputHandler(tcell.NewEventKey(tcell.KeyDown, "", tcell.ModNone))
  139. return consumeRedraw
  140. case keybind.Matches(event, mi.cfg.Keybinds.MentionsList.Top.Keybind):
  141. mi.mentionsList.InputHandler(tcell.NewEventKey(tcell.KeyHome, "", tcell.ModNone))
  142. return consumeRedraw
  143. case keybind.Matches(event, mi.cfg.Keybinds.MentionsList.Bottom.Keybind):
  144. mi.mentionsList.InputHandler(tcell.NewEventKey(tcell.KeyEnd, "", tcell.ModNone))
  145. return consumeRedraw
  146. }
  147. }
  148. go mi.chatView.app.QueueUpdateDraw(func() { mi.tabSuggestion() })
  149. }
  150. return handler(event)
  151. }
  152. func (mi *messageInput) paste() {
  153. if data := clipboard.Read(clipboard.FmtImage); data != nil {
  154. name := "clipboard.png"
  155. mi.attach(name, bytes.NewReader(data))
  156. }
  157. }
  158. func (mi *messageInput) send() {
  159. selected := mi.chatView.SelectedChannel()
  160. if selected == nil {
  161. return
  162. }
  163. text := strings.TrimSpace(mi.GetText())
  164. if text == "" && len(mi.sendMessageData.Files) == 0 {
  165. return
  166. }
  167. // Close attached files on return
  168. defer func() {
  169. for _, file := range mi.sendMessageData.Files {
  170. if closer, ok := file.Reader.(io.Closer); ok {
  171. closer.Close()
  172. }
  173. }
  174. }()
  175. text = mi.processText(selected, []byte(text))
  176. if mi.edit {
  177. m, err := mi.chatView.messagesList.selectedMessage()
  178. if err != nil {
  179. slog.Error("failed to get selected message", "err", err)
  180. return
  181. }
  182. data := api.EditMessageData{Content: option.NewNullableString(text)}
  183. if _, err := mi.chatView.state.EditMessageComplex(m.ChannelID, m.ID, data); err != nil {
  184. slog.Error("failed to edit message", "err", err)
  185. }
  186. mi.edit = false
  187. } else {
  188. data := mi.sendMessageData
  189. data.Content = text
  190. if _, err := mi.chatView.state.SendMessageComplex(selected.ID, *data); err != nil {
  191. slog.Error("failed to send message in channel", "channel_id", selected.ID, "err", err)
  192. }
  193. }
  194. if mi.typingTimer != nil {
  195. mi.typingTimer.Stop()
  196. mi.typingTimer = nil
  197. }
  198. mi.reset()
  199. mi.chatView.messagesList.clearSelection()
  200. mi.chatView.messagesList.ScrollToEnd()
  201. }
  202. func (mi *messageInput) processText(channel *discord.Channel, src []byte) string {
  203. // Fast path: no mentions to expand.
  204. if bytes.IndexByte(src, '@') == -1 {
  205. return string(src)
  206. }
  207. // Fast path: no back ticks (code blocks), so expand mentions directly.
  208. if bytes.IndexByte(src, '`') == -1 {
  209. return string(mi.expandMentions(channel, src))
  210. }
  211. var (
  212. ranges [][2]int
  213. canMention = true
  214. )
  215. ast.Walk(discordmd.Parse(src), func(node ast.Node, enter bool) (ast.WalkStatus, error) {
  216. switch node := node.(type) {
  217. case *ast.CodeBlock, *ast.FencedCodeBlock:
  218. canMention = !enter
  219. case *discordmd.Inline:
  220. if (node.Attr & discordmd.AttrMonospace) != 0 {
  221. canMention = !enter
  222. }
  223. case *ast.Text:
  224. if canMention {
  225. ranges = append(ranges, [2]int{node.Segment.Start,
  226. node.Segment.Stop})
  227. }
  228. }
  229. return ast.WalkContinue, nil
  230. })
  231. for _, rng := range ranges {
  232. src = slices.Replace(src, rng[0], rng[1], mi.expandMentions(channel, src[rng[0]:rng[1]])...)
  233. }
  234. return string(src)
  235. }
  236. func (mi *messageInput) expandMentions(c *discord.Channel, src []byte) []byte {
  237. state := mi.chatView.state
  238. return mentionRegex.ReplaceAllFunc(src, func(input []byte) []byte {
  239. output := input
  240. name := string(input[1:])
  241. if c.Type == discord.DirectMessage || c.Type == discord.GroupDM {
  242. for _, user := range c.DMRecipients {
  243. if strings.EqualFold(user.Username, name) {
  244. return []byte(user.ID.Mention())
  245. }
  246. }
  247. // self ping
  248. me, _ := state.Cabinet.Me()
  249. if strings.EqualFold(me.Username, name) {
  250. return []byte(me.ID.Mention())
  251. }
  252. return output
  253. }
  254. state.MemberStore.Each(c.GuildID, func(m *discord.Member) bool {
  255. if strings.EqualFold(m.User.Username, name) {
  256. if channelHasUser(state, c.ID, m.User.ID) {
  257. output = []byte(m.User.ID.Mention())
  258. }
  259. return true
  260. }
  261. return false
  262. })
  263. return output
  264. })
  265. }
  266. func (mi *messageInput) tabComplete() {
  267. posEnd, name, r := mi.GetWordUnderCursor(func(r rune) bool {
  268. return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.'
  269. })
  270. if r != '@' {
  271. mi.stopTabCompletion(nil)
  272. return
  273. }
  274. pos := posEnd - (len(name) + 1)
  275. selected := mi.chatView.SelectedChannel()
  276. if selected == nil {
  277. return
  278. }
  279. gID := selected.GuildID
  280. if mi.cfg.AutocompleteLimit == 0 {
  281. if !gID.IsValid() {
  282. users := selected.DMRecipients
  283. res := fuzzy.FindFrom(name, userList(users))
  284. if len(res) > 0 {
  285. mi.Replace(pos, posEnd, "@"+users[res[0].Index].Username+" ")
  286. }
  287. } else {
  288. mi.searchMember(gID, name)
  289. members, err := mi.chatView.state.Cabinet.Members(gID)
  290. if err != nil {
  291. slog.Error("failed to get members from state", "guild_id", gID, "err", err)
  292. return
  293. }
  294. res := fuzzy.FindFrom(name, memberList(members))
  295. for _, r := range res {
  296. if channelHasUser(mi.chatView.state, selected.ID, members[r.Index].User.ID) {
  297. mi.Replace(pos, posEnd, "@"+members[r.Index].User.Username+" ")
  298. return
  299. }
  300. }
  301. }
  302. return
  303. }
  304. if mi.mentionsList.itemCount() == 0 {
  305. return
  306. }
  307. name, ok := mi.mentionsList.selectedInsertText()
  308. if !ok {
  309. return
  310. }
  311. mi.Replace(pos, posEnd, "@"+name+" ")
  312. mi.stopTabCompletion(nil)
  313. }
  314. func (mi *messageInput) tabSuggestion() {
  315. _, name, r := mi.GetWordUnderCursor(func(r rune) bool {
  316. return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.'
  317. })
  318. if r != '@' {
  319. mi.stopTabCompletion(nil)
  320. return
  321. }
  322. selected := mi.chatView.SelectedChannel()
  323. if selected == nil {
  324. return
  325. }
  326. gID := selected.GuildID
  327. cID := selected.ID
  328. mi.mentionsList.clear()
  329. var shown map[string]struct{}
  330. var userDone struct{}
  331. if name == "" {
  332. shown = make(map[string]struct{})
  333. // Don't show @me in the list of recent authors
  334. me, _ := mi.chatView.state.Cabinet.Me()
  335. shown[me.Username] = userDone
  336. }
  337. // DMs have recipients, not members
  338. if !gID.IsValid() {
  339. if name == "" { // show recent messages' authors
  340. msgs, err := mi.chatView.state.Cabinet.Messages(cID)
  341. if err != nil {
  342. return
  343. }
  344. for _, m := range msgs {
  345. if _, ok := shown[m.Author.Username]; ok {
  346. continue
  347. }
  348. shown[m.Author.Username] = userDone
  349. mi.addMentionUser(&m.Author)
  350. }
  351. } else {
  352. users := selected.DMRecipients
  353. me, _ := mi.chatView.state.Cabinet.Me()
  354. users = append(users, *me)
  355. res := fuzzy.FindFrom(name, userList(users))
  356. for _, r := range res {
  357. mi.addMentionUser(&users[r.Index])
  358. }
  359. }
  360. } else if name == "" { // show recent messages' authors
  361. msgs, err := mi.chatView.state.Cabinet.Messages(cID)
  362. if err != nil {
  363. return
  364. }
  365. for _, m := range msgs {
  366. if _, ok := shown[m.Author.Username]; ok {
  367. continue
  368. }
  369. shown[m.Author.Username] = userDone
  370. mi.chatView.state.MemberState.RequestMember(gID, m.Author.ID)
  371. if mem, err := mi.chatView.state.Cabinet.Member(gID, m.Author.ID); err == nil {
  372. if mi.addMentionMember(gID, mem) {
  373. break
  374. }
  375. }
  376. }
  377. } else {
  378. mi.searchMember(gID, name)
  379. mems, err := mi.chatView.state.Cabinet.Members(gID)
  380. if err != nil {
  381. slog.Error("fetching members failed", "err", err)
  382. return
  383. }
  384. res := fuzzy.FindFrom(name, memberList(mems))
  385. if len(res) > int(mi.cfg.AutocompleteLimit) {
  386. res = res[:int(mi.cfg.AutocompleteLimit)]
  387. }
  388. for _, r := range res {
  389. if channelHasUser(mi.chatView.state, cID, mems[r.Index].User.ID) &&
  390. mi.addMentionMember(gID, &mems[r.Index]) {
  391. break
  392. }
  393. }
  394. }
  395. if mi.mentionsList.itemCount() == 0 {
  396. mi.stopTabCompletion(nil)
  397. return
  398. }
  399. mi.mentionsList.rebuild()
  400. mi.showMentionList()
  401. }
  402. type memberList []discord.Member
  403. type userList []discord.User
  404. func (ml memberList) String(i int) string {
  405. return ml[i].Nick + ml[i].User.DisplayName + ml[i].User.Tag()
  406. }
  407. func (ml memberList) Len() int {
  408. return len(ml)
  409. }
  410. func (ul userList) String(i int) string {
  411. return ul[i].DisplayName + ul[i].Tag()
  412. }
  413. func (ul userList) Len() int {
  414. return len(ul)
  415. }
  416. // channelHasUser checks if a user has permission to view the specified channel
  417. func channelHasUser(state *ningen.State, channelID discord.ChannelID, userID discord.UserID) bool {
  418. perms, err := state.Permissions(channelID, userID)
  419. if err != nil {
  420. slog.Error("failed to get permissions", "err", err, "channel", channelID, "user", userID)
  421. return false
  422. }
  423. return perms.Has(discord.PermissionViewChannel)
  424. }
  425. func (mi *messageInput) searchMember(gID discord.GuildID, name string) {
  426. key := gID.String() + " " + name
  427. if mi.cache.Exists(key) {
  428. return
  429. }
  430. // If searching for "ab" returns less than SearchLimit,
  431. // then "abc" would not return anything new because we already searched
  432. // everything starting with "ab". This will still be true even if a new
  433. // member joins because arikawa loads new members into the state.
  434. if k := key[:len(key)-1]; mi.cache.Exists(k) {
  435. if c := mi.cache.Get(k); c < mi.chatView.state.MemberState.SearchLimit {
  436. mi.cache.Create(key, c)
  437. return
  438. }
  439. }
  440. // Rate limit on our side because we can't distinguish between a successful search and SearchMember not doing anything because of its internal rate limit that we can't detect
  441. if mi.lastSearch.Add(mi.chatView.state.MemberState.SearchFrequency).After(time.Now()) {
  442. return
  443. }
  444. mi.lastSearch = time.Now()
  445. mi.chatView.messagesList.waitForChunkEvent()
  446. mi.chatView.messagesList.setFetchingChunk(true, 0)
  447. mi.chatView.state.MemberState.SearchMember(gID, name)
  448. mi.cache.Create(key, mi.chatView.messagesList.waitForChunkEvent())
  449. }
  450. func (mi *messageInput) showMentionList() {
  451. borders := 0
  452. if mi.cfg.Theme.Border.Enabled {
  453. borders = 1
  454. }
  455. l := mi.mentionsList
  456. x, _, _, _ := mi.GetInnerRect()
  457. _, y, _, _ := mi.GetRect()
  458. _, _, maxW, maxH := mi.chatView.messagesList.GetInnerRect()
  459. if t := int(mi.cfg.Theme.MentionsList.MaxHeight); t != 0 {
  460. maxH = min(maxH, t)
  461. }
  462. count := mi.mentionsList.itemCount() + borders
  463. h := min(count, maxH) + borders + mi.cfg.Theme.Border.Padding[1]
  464. y -= h
  465. w := int(mi.cfg.Theme.MentionsList.MinWidth)
  466. if w == 0 {
  467. w = maxW
  468. } else {
  469. w = max(w, mi.mentionsList.maxDisplayWidth())
  470. w = min(w+borders*2, maxW)
  471. _, col, _, _ := mi.GetCursor()
  472. x += min(col, maxW-w)
  473. }
  474. l.SetRect(x, y, w, h)
  475. mi.chatView.ShowLayer(mentionsListLayerName).SendToFront(mentionsListLayerName)
  476. mi.chatView.app.SetFocus(mi)
  477. }
  478. func (mi *messageInput) addMentionMember(gID discord.GuildID, m *discord.Member) bool {
  479. if m == nil {
  480. return false
  481. }
  482. name := m.User.DisplayOrUsername()
  483. if m.Nick != "" {
  484. name = m.Nick
  485. }
  486. style := tcell.StyleDefault
  487. // This avoids a slower member color lookup path.
  488. color, ok := state.MemberColor(m, func(id discord.RoleID) *discord.Role {
  489. r, _ := mi.chatView.state.Cabinet.Role(gID, id)
  490. return r
  491. })
  492. if ok {
  493. style = style.Foreground(tcell.NewHexColor(int32(color)))
  494. }
  495. presence, err := mi.chatView.state.Cabinet.Presence(gID, m.User.ID)
  496. if err != nil {
  497. slog.Info("failed to get presence from state", "guild_id", gID, "user_id", m.User.ID, "err", err)
  498. } else if presence.Status == discord.OfflineStatus {
  499. style = style.Dim(true)
  500. }
  501. mi.mentionsList.append(mentionsListItem{
  502. insertText: m.User.Username,
  503. displayText: name,
  504. style: style,
  505. })
  506. return mi.mentionsList.itemCount() > int(mi.cfg.AutocompleteLimit)
  507. }
  508. func (mi *messageInput) addMentionUser(user *discord.User) {
  509. if user == nil {
  510. return
  511. }
  512. name := user.DisplayOrUsername()
  513. style := tcell.StyleDefault
  514. presence, err := mi.chatView.state.Cabinet.Presence(discord.NullGuildID, user.ID)
  515. if err != nil {
  516. slog.Info("failed to get presence from state", "user_id", user.ID, "err", err)
  517. } else if presence.Status == discord.OfflineStatus {
  518. style = style.Dim(true)
  519. }
  520. mi.mentionsList.append(mentionsListItem{
  521. insertText: user.Username,
  522. displayText: name,
  523. style: style,
  524. })
  525. }
  526. // used by chatView
  527. func (mi *messageInput) removeMentionsList() {
  528. mi.chatView.HideLayer(mentionsListLayerName)
  529. }
  530. func (mi *messageInput) stopTabCompletion(emit func(tview.Command)) {
  531. if mi.cfg.AutocompleteLimit > 0 {
  532. mi.mentionsList.clear()
  533. if emit != nil {
  534. emit(layers.CloseLayerCommand{Name: mentionsListLayerName})
  535. emit(tview.SetFocusCommand{Target: mi})
  536. } else {
  537. mi.removeMentionsList()
  538. mi.chatView.app.SetFocus(mi)
  539. }
  540. }
  541. }
  542. func (mi *messageInput) editor() {
  543. file, err := os.CreateTemp("", tmpFilePattern)
  544. if err != nil {
  545. slog.Error("failed to create tmp file", "err", err)
  546. return
  547. }
  548. defer file.Close()
  549. defer os.Remove(file.Name())
  550. file.WriteString(mi.GetText())
  551. if mi.cfg.Editor == "" {
  552. slog.Warn("Attempt to open file with editor, but no editor is set")
  553. return
  554. }
  555. cmd := mi.cfg.CreateEditorCommand(file.Name())
  556. if cmd == nil {
  557. return
  558. }
  559. cmd.Stdin = os.Stdin
  560. cmd.Stdout = os.Stdout
  561. cmd.Stderr = os.Stderr
  562. mi.chatView.app.Suspend(func() {
  563. err := cmd.Run()
  564. if err != nil {
  565. slog.Error("failed to run command", "args", cmd.Args, "err", err)
  566. return
  567. }
  568. })
  569. msg, err := os.ReadFile(file.Name())
  570. if err != nil {
  571. slog.Error("failed to read tmp file", "name", file.Name(), "err", err)
  572. return
  573. }
  574. mi.SetText(strings.TrimSpace(string(msg)), true)
  575. }
  576. func (mi *messageInput) openFilePicker() {
  577. if mi.chatView.SelectedChannel() == nil {
  578. return
  579. }
  580. paths, err := zenity.SelectFileMultiple()
  581. if err != nil {
  582. slog.Error("failed to open file dialog", "err", err)
  583. return
  584. }
  585. for _, path := range paths {
  586. file, err := os.Open(path)
  587. if err != nil {
  588. slog.Error("failed to open file", "path", path, "err", err)
  589. continue
  590. }
  591. name := filepath.Base(path)
  592. mi.attach(name, file)
  593. }
  594. }
  595. func (mi *messageInput) attach(name string, reader io.Reader) {
  596. mi.sendMessageData.Files = append(mi.sendMessageData.Files, sendpart.File{Name: name, Reader: reader})
  597. var names []string
  598. for _, file := range mi.sendMessageData.Files {
  599. names = append(names, file.Name)
  600. }
  601. mi.SetFooter("Attached " + humanJoin(names))
  602. }
  603. func (mi *messageInput) ShortHelp() []keybind.Keybind {
  604. if mi.chatView.GetVisible(mentionsListLayerName) {
  605. cfg := mi.cfg.Keybinds.MentionsList
  606. icfg := mi.cfg.Keybinds.MessageInput
  607. short := []keybind.Keybind{cfg.Up.Keybind, cfg.Down.Keybind, icfg.Cancel.Keybind}
  608. if selected := mi.chatView.SelectedChannel(); selected != nil && mi.chatView.state.HasPermissions(selected.ID, discord.PermissionAttachFiles) {
  609. short = append(short, icfg.OpenFilePicker.Keybind)
  610. }
  611. return short
  612. }
  613. cfg := mi.cfg.Keybinds.MessageInput
  614. short := []keybind.Keybind{cfg.Send.Keybind, cfg.Cancel.Keybind, cfg.Paste.Keybind, cfg.OpenEditor.Keybind}
  615. if selected := mi.chatView.SelectedChannel(); selected != nil && mi.chatView.state.HasPermissions(selected.ID, discord.PermissionAttachFiles) {
  616. short = append(short, cfg.OpenFilePicker.Keybind)
  617. }
  618. return short
  619. }
  620. func (mi *messageInput) FullHelp() [][]keybind.Keybind {
  621. if mi.chatView.GetVisible(mentionsListLayerName) {
  622. mcfg := mi.cfg.Keybinds.MentionsList
  623. icfg := mi.cfg.Keybinds.MessageInput
  624. return [][]keybind.Keybind{
  625. {mcfg.Up.Keybind, mcfg.Down.Keybind, mcfg.Top.Keybind, mcfg.Bottom.Keybind},
  626. {icfg.TabComplete.Keybind, icfg.Cancel.Keybind},
  627. }
  628. }
  629. cfg := mi.cfg.Keybinds.MessageInput
  630. openEditor := []keybind.Keybind{cfg.Paste.Keybind, cfg.OpenEditor.Keybind}
  631. if selected := mi.chatView.SelectedChannel(); selected != nil && mi.chatView.state.HasPermissions(selected.ID, discord.PermissionAttachFiles) {
  632. openEditor = append(openEditor, cfg.OpenFilePicker.Keybind)
  633. }
  634. return [][]keybind.Keybind{
  635. {cfg.Send.Keybind, cfg.Cancel.Keybind, cfg.TabComplete.Keybind, cfg.Undo.Keybind},
  636. openEditor,
  637. }
  638. }