set_window_logo.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package at
  3. import (
  4. "bytes"
  5. "encoding/base64"
  6. "fmt"
  7. "image"
  8. "io"
  9. "os"
  10. "strings"
  11. "kitty/tools/utils/images"
  12. )
  13. func set_payload_data(io_data *rc_io_data, data string) {
  14. set_payload_string_field(io_data, "Data", data)
  15. }
  16. func read_window_logo(io_data *rc_io_data, path string) (func(io_data *rc_io_data) (bool, error), error) {
  17. if strings.ToLower(path) == "none" {
  18. io_data.rc.Stream = false
  19. return func(io_data *rc_io_data) (bool, error) {
  20. set_payload_data(io_data, "-")
  21. return true, nil
  22. }, nil
  23. }
  24. f, err := os.Open(path)
  25. if err != nil {
  26. return nil, err
  27. }
  28. var image_data_stream io.Reader
  29. image_data_stream = f
  30. config, format, ierr := image.DecodeConfig(f)
  31. if ierr != nil {
  32. return nil, fmt.Errorf("%s is not a supported image format", path)
  33. }
  34. f.Seek(0, 0)
  35. if format != "png" {
  36. f.Seek(0, 0)
  37. img, _, err := image.Decode(f)
  38. if err != nil {
  39. f.Close()
  40. }
  41. f.Close()
  42. b := bytes.Buffer{}
  43. b.Grow(config.Height * config.Width * 4)
  44. err = images.Encode(&b, img, "image/png")
  45. if err != nil {
  46. return nil, err
  47. }
  48. image_data_stream = &b
  49. }
  50. is_first_call := true
  51. buf := make([]byte, 2048)
  52. return func(io_data *rc_io_data) (bool, error) {
  53. if is_first_call {
  54. is_first_call = false
  55. } else {
  56. io_data.rc.Stream = false
  57. }
  58. buf = buf[:cap(buf)]
  59. n, err := image_data_stream.Read(buf)
  60. if err != nil && err != io.EOF {
  61. return false, err
  62. }
  63. buf = buf[:n]
  64. set_payload_data(io_data, base64.StdEncoding.EncodeToString(buf))
  65. if err == io.EOF {
  66. return true, nil
  67. }
  68. return false, nil
  69. }, nil
  70. }