attachment_image.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "image"
  4. _ "image/jpeg"
  5. _ "image/png"
  6. "net/http"
  7. "github.com/diamondburned/arikawa/v3/discord"
  8. "github.com/gdamore/tcell/v2"
  9. "github.com/rivo/tview"
  10. )
  11. type AttachmentImage struct {
  12. *tview.Image
  13. }
  14. func newAttachmentImage(a discord.Attachment) (*AttachmentImage, error) {
  15. ai := &AttachmentImage{
  16. Image: tview.NewImage(),
  17. }
  18. ai.SetInputCapture(ai.onInputCapture)
  19. ai.SetBackgroundColor(tcell.GetColor(cfg.Theme.BackgroundColor))
  20. ai.SetTitleColor(tcell.GetColor(cfg.Theme.TitleColor))
  21. ai.SetTitleAlign(tview.AlignLeft)
  22. p := cfg.Theme.BorderPadding
  23. ai.SetBorder(cfg.Theme.Border)
  24. ai.SetBorderColor(tcell.GetColor(cfg.Theme.BorderColor))
  25. ai.SetBorderPadding(p[0], p[1], p[2], p[3])
  26. resp, err := http.Get(a.URL)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer resp.Body.Close()
  31. i, _, err := image.Decode(resp.Body)
  32. if err != nil {
  33. return nil, err
  34. }
  35. ai.SetTitle(a.Filename)
  36. ai.SetImage(i)
  37. return ai, nil
  38. }
  39. func (ai *AttachmentImage) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  40. if event.Name() == cfg.Keys.Cancel {
  41. app.SetRoot(mainFlex, true)
  42. app.SetFocus(messagesText)
  43. return nil
  44. }
  45. return event
  46. }