message_input.go 20 KB

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