message_input.go 19 KB

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