write.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package clipboard
  3. import (
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "kitty/tools/tui/loop"
  11. "kitty/tools/utils"
  12. )
  13. var _ = fmt.Print
  14. type Input struct {
  15. src io.Reader
  16. arg string
  17. ext string
  18. is_stream bool
  19. mime_type string
  20. extra_mime_types []string
  21. }
  22. func is_textual_mime(x string) bool {
  23. return strings.HasPrefix(x, "text/") || utils.KnownTextualMimes[x]
  24. }
  25. func is_text_plain_mime(x string) bool {
  26. return x == "text/plain"
  27. }
  28. func (self *Input) has_mime_matching(predicate func(string) bool) bool {
  29. if predicate(self.mime_type) {
  30. return true
  31. }
  32. for _, i := range self.extra_mime_types {
  33. if predicate(i) {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. func write_loop(inputs []*Input, opts *Options) (err error) {
  40. lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking, loop.NoInBandResizeNotifications)
  41. if err != nil {
  42. return err
  43. }
  44. var waiting_for_write loop.IdType
  45. var buf [4096]byte
  46. aliases, aerr := parse_aliases(opts.Alias)
  47. if aerr != nil {
  48. return aerr
  49. }
  50. num_text_mimes := 0
  51. has_text_plain := false
  52. for _, i := range inputs {
  53. i.extra_mime_types = aliases[i.mime_type]
  54. if i.has_mime_matching(is_textual_mime) {
  55. num_text_mimes++
  56. if !has_text_plain && i.has_mime_matching(is_text_plain_mime) {
  57. has_text_plain = true
  58. }
  59. }
  60. }
  61. if num_text_mimes > 0 && !has_text_plain {
  62. for _, i := range inputs {
  63. if i.has_mime_matching(is_textual_mime) {
  64. i.extra_mime_types = append(i.extra_mime_types, "text/plain")
  65. break
  66. }
  67. }
  68. }
  69. make_metadata := func(ptype, mime string) map[string]string {
  70. ans := map[string]string{"type": ptype}
  71. if opts.UsePrimary {
  72. ans["loc"] = "primary"
  73. }
  74. if mime != "" {
  75. ans["mime"] = mime
  76. }
  77. return ans
  78. }
  79. lp.OnInitialize = func() (string, error) {
  80. waiting_for_write = lp.QueueWriteString(encode(make_metadata("write", ""), ""))
  81. return "", nil
  82. }
  83. write_chunk := func() error {
  84. if len(inputs) == 0 {
  85. return nil
  86. }
  87. i := inputs[0]
  88. n, err := i.src.Read(buf[:])
  89. if n > 0 {
  90. waiting_for_write = lp.QueueWriteString(encode_bytes(make_metadata("wdata", i.mime_type), buf[:n]))
  91. }
  92. if err != nil {
  93. if errors.Is(err, io.EOF) {
  94. if len(i.extra_mime_types) > 0 {
  95. lp.QueueWriteString(encode(make_metadata("walias", i.mime_type), strings.Join(i.extra_mime_types, " ")))
  96. }
  97. inputs = inputs[1:]
  98. if len(inputs) == 0 {
  99. lp.QueueWriteString(encode(make_metadata("wdata", ""), ""))
  100. waiting_for_write = 0
  101. }
  102. return lp.OnWriteComplete(waiting_for_write, false)
  103. }
  104. return fmt.Errorf("Failed to read from %s with error: %w", i.arg, err)
  105. }
  106. return nil
  107. }
  108. lp.OnWriteComplete = func(msg_id loop.IdType, has_pending_writes bool) error {
  109. if waiting_for_write == msg_id {
  110. return write_chunk()
  111. }
  112. return nil
  113. }
  114. lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
  115. metadata, _, err := parse_escape_code(etype, data)
  116. if err != nil {
  117. return err
  118. }
  119. if metadata != nil && metadata["type"] == "write" {
  120. switch metadata["status"] {
  121. case "DONE":
  122. lp.Quit(0)
  123. case "EIO":
  124. return fmt.Errorf("Could not write to clipboard an I/O error occurred while the terminal was processing the data")
  125. case "EINVAL":
  126. return fmt.Errorf("Could not write to clipboard base64 encoding invalid")
  127. case "ENOSYS":
  128. return fmt.Errorf("Could not write to primary selection as the system does not support it")
  129. case "EPERM":
  130. return fmt.Errorf("Could not write to clipboard as permission was denied")
  131. case "EBUSY":
  132. return fmt.Errorf("Could not write to clipboard, a temporary error occurred, try again later.")
  133. default:
  134. return fmt.Errorf("Could not write to clipboard unknowns status returned from terminal: %#v", metadata["status"])
  135. }
  136. }
  137. return
  138. }
  139. esc_count := 0
  140. lp.OnKeyEvent = func(event *loop.KeyEvent) error {
  141. if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
  142. event.Handled = true
  143. esc_count++
  144. if esc_count < 2 {
  145. key := "Esc"
  146. if event.MatchesPressOrRepeat("ctrl+c") {
  147. key = "Ctrl+C"
  148. }
  149. lp.QueueWriteString(fmt.Sprintf("Waiting for response from terminal, press %s again to abort. This could cause garbage to be spewed to the screen.\r\n", key))
  150. } else {
  151. return fmt.Errorf("Aborted by user!")
  152. }
  153. }
  154. return nil
  155. }
  156. err = lp.Run()
  157. if err != nil {
  158. return
  159. }
  160. ds := lp.DeathSignalName()
  161. if ds != "" {
  162. fmt.Println("Killed by signal: ", ds)
  163. lp.KillIfSignalled()
  164. return
  165. }
  166. return
  167. }
  168. func run_set_loop(opts *Options, args []string) (err error) {
  169. inputs := make([]*Input, len(args))
  170. to_process := make([]*Input, len(args))
  171. defer func() {
  172. for _, i := range inputs {
  173. if i != nil && i.src != nil {
  174. rc, ok := i.src.(io.Closer)
  175. if ok {
  176. rc.Close()
  177. }
  178. }
  179. }
  180. }()
  181. for i, arg := range args {
  182. if arg == "/dev/stdin" {
  183. f, _, err := preread_stdin()
  184. if err != nil {
  185. return err
  186. }
  187. inputs[i] = &Input{arg: arg, src: f, is_stream: true}
  188. } else {
  189. f, err := os.Open(arg)
  190. if err != nil {
  191. return fmt.Errorf("Failed to open %s with error: %w", arg, err)
  192. }
  193. inputs[i] = &Input{arg: arg, src: f, ext: filepath.Ext(arg)}
  194. }
  195. if i < len(opts.Mime) {
  196. inputs[i].mime_type = opts.Mime[i]
  197. } else if inputs[i].is_stream {
  198. inputs[i].mime_type = "text/plain"
  199. } else if inputs[i].ext != "" {
  200. inputs[i].mime_type = utils.GuessMimeType(inputs[i].arg)
  201. }
  202. if inputs[i].mime_type == "" {
  203. return fmt.Errorf("Could not guess MIME type for %s use the --mime option to specify a MIME type", arg)
  204. }
  205. to_process[i] = inputs[i]
  206. }
  207. return write_loop(to_process, opts)
  208. }