message_input.go 19 KB

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