message_input.go 19 KB

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