chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,245 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func encode_read_from_clipboard(use_primary bool) string {
|
||||
dest := "c"
|
||||
if use_primary {
|
||||
dest = "p"
|
||||
}
|
||||
return fmt.Sprintf("\x1b]52;%s;?\x1b\\", dest)
|
||||
}
|
||||
|
||||
type base64_streaming_enc struct {
|
||||
output func(string) loop.IdType
|
||||
last_written_id loop.IdType
|
||||
}
|
||||
|
||||
func (self *base64_streaming_enc) Write(p []byte) (int, error) {
|
||||
if len(p) > 0 {
|
||||
self.last_written_id = self.output(string(p))
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
var ErrTooMuchPipedData = errors.New("Too much piped data")
|
||||
|
||||
func read_all_with_max_size(r io.Reader, max_size int) ([]byte, error) {
|
||||
b := make([]byte, 0, utils.Min(8192, max_size))
|
||||
for {
|
||||
if len(b) == cap(b) {
|
||||
new_size := utils.Min(2*cap(b), max_size)
|
||||
if new_size <= cap(b) {
|
||||
return b, ErrTooMuchPipedData
|
||||
}
|
||||
b = append(make([]byte, 0, new_size), b...)
|
||||
}
|
||||
n, err := r.Read(b[len(b):cap(b)])
|
||||
b = b[:len(b)+n]
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func preread_stdin() (data_src io.Reader, tempfile *os.File, err error) {
|
||||
// we pre-read STDIN because otherwise if the output of a command is being piped in
|
||||
// and that command itself transmits on the tty we will break. For example
|
||||
// kitten @ ls | kitten clipboard
|
||||
var stdin_data []byte
|
||||
stdin_data, err = read_all_with_max_size(os.Stdin, 2*1024*1024)
|
||||
if err == nil {
|
||||
os.Stdin.Close()
|
||||
} else if err != ErrTooMuchPipedData {
|
||||
os.Stdin.Close()
|
||||
err = fmt.Errorf("Failed to read from STDIN pipe with error: %w", err)
|
||||
return
|
||||
}
|
||||
if err == ErrTooMuchPipedData {
|
||||
tempfile, err = utils.CreateAnonymousTemp("")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("Failed to create a temporary from STDIN pipe with error: %w", err)
|
||||
}
|
||||
tempfile.Write(stdin_data)
|
||||
_, err = io.Copy(tempfile, os.Stdin)
|
||||
os.Stdin.Close()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("Failed to copy data from STDIN pipe to temp file with error: %w", err)
|
||||
}
|
||||
tempfile.Seek(0, io.SeekStart)
|
||||
data_src = tempfile
|
||||
} else if stdin_data != nil {
|
||||
data_src = bytes.NewBuffer(stdin_data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func run_plain_text_loop(opts *Options) (err error) {
|
||||
stdin_is_tty := tty.IsTerminal(os.Stdin.Fd())
|
||||
var data_src io.Reader
|
||||
var tempfile *os.File
|
||||
if !stdin_is_tty && !opts.GetClipboard {
|
||||
// we dont read STDIN when getting clipboard as it makes it hard to use the kitten in contexts where
|
||||
// the user does not control STDIN such as being execed from other programs.
|
||||
data_src, tempfile, err = preread_stdin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tempfile != nil {
|
||||
defer tempfile.Close()
|
||||
}
|
||||
}
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dest := "c"
|
||||
if opts.UsePrimary {
|
||||
dest = "p"
|
||||
}
|
||||
|
||||
send_to_loop := func(data string) loop.IdType {
|
||||
return lp.QueueWriteString(data)
|
||||
}
|
||||
enc_writer := base64_streaming_enc{output: send_to_loop}
|
||||
enc := base64.NewEncoder(base64.StdEncoding, &enc_writer)
|
||||
transmitting := true
|
||||
|
||||
after_read_from_stdin := func() {
|
||||
transmitting = false
|
||||
if opts.GetClipboard {
|
||||
lp.QueueWriteString(encode_read_from_clipboard(opts.UsePrimary))
|
||||
} else if opts.WaitForCompletion {
|
||||
lp.QueueWriteString("\x1bP+q544e\x1b\\")
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
}
|
||||
|
||||
buf := make([]byte, 8192)
|
||||
write_one_chunk := func() error {
|
||||
orig := enc_writer.last_written_id
|
||||
for enc_writer.last_written_id == orig {
|
||||
n, err := data_src.Read(buf[:cap(buf)])
|
||||
if n > 0 {
|
||||
enc.Write(buf[:n])
|
||||
}
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
enc.Close()
|
||||
send_to_loop("\x1b\\")
|
||||
after_read_from_stdin()
|
||||
return nil
|
||||
}
|
||||
send_to_loop("\x1b\\")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
if data_src != nil {
|
||||
send_to_loop(fmt.Sprintf("\x1b]52;%s;", dest))
|
||||
return "", write_one_chunk()
|
||||
}
|
||||
after_read_from_stdin()
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnWriteComplete = func(id loop.IdType, has_pending_writes bool) error {
|
||||
if id == enc_writer.last_written_id {
|
||||
return write_one_chunk()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var clipboard_contents []byte
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
switch etype {
|
||||
case loop.DCS:
|
||||
if strings.HasPrefix(utils.UnsafeBytesToString(data), "1+r") {
|
||||
lp.Quit(0)
|
||||
}
|
||||
case loop.OSC:
|
||||
q := utils.UnsafeBytesToString(data)
|
||||
if strings.HasPrefix(q, "52;") {
|
||||
parts := strings.SplitN(q, ";", 3)
|
||||
if len(parts) < 3 {
|
||||
lp.Quit(0)
|
||||
return
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return fmt.Errorf("Invalid base64 encoded data from terminal with error: %w", err)
|
||||
}
|
||||
clipboard_contents = data
|
||||
lp.Quit(0)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
if transmitting {
|
||||
return nil
|
||||
}
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
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))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
if len(clipboard_contents) > 0 {
|
||||
_, err = os.Stdout.Write(clipboard_contents)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to write to STDOUT with error: %w", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
)
|
||||
|
||||
func run_mime_loop(opts *Options, args []string) (err error) {
|
||||
cwd, err = os.Getwd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.GetClipboard {
|
||||
return run_get_loop(opts, args)
|
||||
}
|
||||
return run_set_loop(opts, args)
|
||||
}
|
||||
|
||||
func clipboard_main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
if opts.Password != "" {
|
||||
if opts.HumanName == "" {
|
||||
return 1, fmt.Errorf("must specify --human-name when using a password")
|
||||
}
|
||||
ptype, val, found := strings.Cut(opts.Password, ":")
|
||||
if !found {
|
||||
return 1, fmt.Errorf("invalid password: %#v no password type specified", opts.Password)
|
||||
}
|
||||
switch ptype {
|
||||
case "text":
|
||||
opts.Password = val
|
||||
case "fd":
|
||||
if fd, err := strconv.Atoi(val); err == nil {
|
||||
if f := os.NewFile(uintptr(fd), "password-fd"); f == nil {
|
||||
return 1, fmt.Errorf("invalid file descriptor: %d", fd)
|
||||
} else {
|
||||
data, err := io.ReadAll(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("failed to read from file descriptor: %d with error: %w", fd, err)
|
||||
}
|
||||
opts.Password = strings.TrimRightFunc(string(data), unicode.IsSpace)
|
||||
}
|
||||
|
||||
} else {
|
||||
return 1, fmt.Errorf("not a valid file descriptor number: %#v", val)
|
||||
}
|
||||
case "file":
|
||||
if data, err := os.ReadFile(val); err == nil {
|
||||
opts.Password = strings.TrimRightFunc(string(data), unicode.IsSpace)
|
||||
} else {
|
||||
return 1, fmt.Errorf("failed to read from file: %#v with error: %w", val, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(args) > 0 {
|
||||
return 0, run_mime_loop(opts, args)
|
||||
}
|
||||
if opts.Password != "" || opts.HumanName != "" {
|
||||
return 1, fmt.Errorf("cannot use --human-name or --password in filter mode")
|
||||
}
|
||||
return 0, run_plain_text_loop(opts)
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, clipboard_main)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
OPTIONS = r"""
|
||||
--get-clipboard -g
|
||||
type=bool-set
|
||||
Output the current contents of the clipboard to STDOUT. Note that by default
|
||||
kitty will prompt for permission to access the clipboard. Can be controlled
|
||||
by :opt:`clipboard_control`.
|
||||
|
||||
|
||||
--use-primary -p
|
||||
type=bool-set
|
||||
Use the primary selection rather than the clipboard on systems that support it,
|
||||
such as Linux.
|
||||
|
||||
|
||||
--mime -m
|
||||
type=list
|
||||
The mimetype of the specified file. Useful when the auto-detected mimetype is
|
||||
likely to be incorrect or the filename has no extension and therefore no mimetype
|
||||
can be detected. If more than one file is specified, this option should be specified multiple
|
||||
times, once for each specified file. When copying data from the clipboard, you can use wildcards
|
||||
to match MIME types. For example: :code:`--mime 'text/*'` will match any textual MIME type
|
||||
available on the clipboard, usually the first matching MIME type is copied. The special MIME
|
||||
type :code:`.` will return the list of available MIME types currently on the system clipboard.
|
||||
|
||||
|
||||
--alias -a
|
||||
type=list
|
||||
Specify aliases for MIME types. Aliased MIME types are considered equivalent.
|
||||
When copying to clipboard both the original and alias are made available on the
|
||||
clipboard. When copying from clipboard if the original is not found, the alias
|
||||
is used, as a fallback. Can be specified multiple times to create multiple
|
||||
aliases. For example: :code:`--alias text/plain=text/x-rst` makes :code:`text/plain` an alias
|
||||
of :code:`text/x-rst`. Aliases are not used in filter mode. An alias for
|
||||
:code:`text/plain` is automatically created if :code:`text/plain` is not present in the input data, but some
|
||||
other :code:`text/*` MIME is present.
|
||||
|
||||
|
||||
--wait-for-completion
|
||||
type=bool-set
|
||||
Wait till the copy to clipboard is complete before exiting. Useful if running
|
||||
the kitten in a dedicated, ephemeral window. Only needed in filter mode.
|
||||
|
||||
|
||||
--password
|
||||
A password to use when accessing the clipboard. If the user chooses to accept the password
|
||||
future invocations of the kitten will not have a permission prompt in this tty session. Does not
|
||||
work in filter mode. Must be of the form: text:actual-password or fd:integer (a file descriptor
|
||||
number to read the password from) or file:path-to-file (a file from which to read the password).
|
||||
Note that you must also specify a human friendly name using the :option:`--human-name` flag.
|
||||
|
||||
|
||||
--human-name
|
||||
A human friendly name to show the user when asking for permission to access the clipboard.
|
||||
""".format
|
||||
help_text = """\
|
||||
Read or write to the system clipboard.
|
||||
|
||||
This kitten operates most simply in :italic:`filter mode`.
|
||||
To set the clipboard text, pipe in the new text on :file:`STDIN`. Use the
|
||||
:option:`--get-clipboard` option to instead output the current clipboard text content to
|
||||
:file:`STDOUT`. Note that copying from the clipboard will cause a permission
|
||||
popup, see :opt:`clipboard_control` for details.
|
||||
|
||||
For more control, specify filename arguments. Then, different MIME types can be copied to/from
|
||||
the clipboard. Some examples:
|
||||
|
||||
.. code:: sh
|
||||
|
||||
# Copy an image to the clipboard:
|
||||
kitten clipboard picture.png
|
||||
|
||||
# Copy an image and some text to the clipboard:
|
||||
kitten clipboard picture.jpg text.txt
|
||||
|
||||
# Copy text from STDIN and an image to the clipboard:
|
||||
echo hello | kitten clipboard picture.png /dev/stdin
|
||||
|
||||
# Copy any raster image available on the clipboard to a PNG file:
|
||||
kitten clipboard -g picture.png
|
||||
|
||||
# Copy an image to a file and text to STDOUT:
|
||||
kitten clipboard -g picture.png /dev/stdout
|
||||
|
||||
# List the formats available on the system clipboard
|
||||
kitten clipboard -g -m . /dev/stdout
|
||||
"""
|
||||
|
||||
usage = '[files to copy to/from]'
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit('This should be run as kitten clipboard')
|
||||
elif __name__ == '__doc__':
|
||||
from kitty.simple_cli_definitions import CompletionSpec
|
||||
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Copy/paste with the system clipboard, even over SSH'
|
||||
cd['args_completion'] = CompletionSpec.from_string('type:file mime:* group:Files')
|
||||
@@ -0,0 +1,663 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var cwd string
|
||||
|
||||
const OSC_NUMBER = "5522"
|
||||
|
||||
type Output struct {
|
||||
arg string
|
||||
ext string
|
||||
arg_is_stream bool
|
||||
mime_type string
|
||||
remote_mime_type string
|
||||
image_needs_conversion bool
|
||||
is_stream bool
|
||||
dest_is_tty bool
|
||||
dest *os.File
|
||||
err error
|
||||
started bool
|
||||
all_data_received bool
|
||||
}
|
||||
|
||||
func (self *Output) cleanup() {
|
||||
if self.dest != nil {
|
||||
self.dest.Close()
|
||||
if !self.is_stream {
|
||||
os.Remove(self.dest.Name())
|
||||
}
|
||||
self.dest = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Output) add_data(data []byte) {
|
||||
if self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.dest == nil {
|
||||
if !self.image_needs_conversion && self.arg_is_stream {
|
||||
self.is_stream = true
|
||||
self.dest = os.Stdout
|
||||
if self.arg == "/dev/stderr" {
|
||||
self.dest = os.Stderr
|
||||
}
|
||||
self.dest_is_tty = tty.IsTerminal(self.dest.Fd())
|
||||
} else {
|
||||
d := cwd
|
||||
if strings.ContainsRune(self.arg, os.PathSeparator) && !self.arg_is_stream {
|
||||
d = filepath.Dir(self.arg)
|
||||
}
|
||||
f, err := os.CreateTemp(d, "."+filepath.Base(self.arg))
|
||||
if err != nil {
|
||||
self.err = err
|
||||
return
|
||||
}
|
||||
self.dest = f
|
||||
}
|
||||
self.started = true
|
||||
}
|
||||
if self.dest_is_tty {
|
||||
data = bytes.ReplaceAll(data, utils.UnsafeStringToBytes("\n"), utils.UnsafeStringToBytes("\r\n"))
|
||||
}
|
||||
_, self.err = self.dest.Write(data)
|
||||
}
|
||||
|
||||
func (self *Output) write_image(img image.Image) (err error) {
|
||||
if self.arg_is_stream {
|
||||
output := os.Stdout
|
||||
if self.arg == "/dev/stderr" {
|
||||
output = os.Stderr
|
||||
}
|
||||
return images.Encode(output, img, self.mime_type)
|
||||
}
|
||||
// Encode into memory first so that an encoding failure leaves any
|
||||
// existing destination file untouched.
|
||||
var buf bytes.Buffer
|
||||
if err = images.Encode(&buf, img, self.mime_type); err != nil {
|
||||
return err
|
||||
}
|
||||
return utils.AtomicUpdateFile(self.arg, &buf)
|
||||
}
|
||||
|
||||
// The downloaded data for a remote MIME type, shared by all outputs saved from it
|
||||
type downloaded_data struct {
|
||||
file *os.File
|
||||
img image.Image
|
||||
img_err error
|
||||
img_decoded bool
|
||||
}
|
||||
|
||||
func (self *downloaded_data) image() (image.Image, error) {
|
||||
if !self.img_decoded {
|
||||
self.img_decoded = true
|
||||
if _, self.img_err = self.file.Seek(0, io.SeekStart); self.img_err == nil {
|
||||
self.img, _, self.img_err = image.Decode(self.file)
|
||||
}
|
||||
}
|
||||
return self.img, self.img_err
|
||||
}
|
||||
|
||||
func (self *Output) save(src *downloaded_data) {
|
||||
if self.image_needs_conversion {
|
||||
img, err := src.image()
|
||||
if err == nil {
|
||||
err = self.write_image(img)
|
||||
}
|
||||
if err != nil {
|
||||
self.err = fmt.Errorf("Failed to encode image data to %s with error: %w", self.mime_type, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Copy the downloaded data into place atomically, preserving the
|
||||
// permissions of and following symlinks at the destination.
|
||||
_, err := src.file.Seek(0, io.SeekStart)
|
||||
if err == nil {
|
||||
err = utils.AtomicUpdateFile(self.arg, src.file)
|
||||
}
|
||||
if err != nil {
|
||||
self.err = fmt.Errorf("Failed to write downloaded data to destination: %s with error: %w", self.arg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Output) commit() {
|
||||
if self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.is_stream {
|
||||
self.dest = nil
|
||||
return
|
||||
}
|
||||
self.save(&downloaded_data{file: self.dest})
|
||||
self.cleanup()
|
||||
}
|
||||
|
||||
func (self *Output) write_mime_list(available_mimes []string) {
|
||||
self.add_data(utils.UnsafeStringToBytes(strings.Join(available_mimes, "\n")))
|
||||
self.all_data_received = true
|
||||
self.commit()
|
||||
}
|
||||
|
||||
func (self *Output) assign_mime_type(available_mimes []string, aliases map[string][]string) (err error) {
|
||||
if self.mime_type == "." {
|
||||
self.remote_mime_type = "."
|
||||
return
|
||||
}
|
||||
if slices.Contains(available_mimes, self.mime_type) {
|
||||
self.remote_mime_type = self.mime_type
|
||||
return
|
||||
}
|
||||
if len(aliases[self.mime_type]) > 0 {
|
||||
for _, alias := range aliases[self.mime_type] {
|
||||
if slices.Contains(available_mimes, alias) {
|
||||
self.remote_mime_type = alias
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, mt := range available_mimes {
|
||||
if matched, _ := filepath.Match(self.mime_type, mt); matched {
|
||||
self.remote_mime_type = mt
|
||||
return
|
||||
}
|
||||
}
|
||||
if images.EncodableImageTypes[self.mime_type] {
|
||||
for _, mt := range available_mimes {
|
||||
if images.DecodableImageTypes[mt] {
|
||||
self.remote_mime_type = mt
|
||||
self.image_needs_conversion = true
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_textual_mime(self.mime_type) {
|
||||
for _, mt := range available_mimes {
|
||||
if mt == "text/plain" {
|
||||
self.remote_mime_type = mt
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("The MIME type %s for %s not available on the clipboard", self.mime_type, self.arg)
|
||||
}
|
||||
|
||||
func escape_metadata_value(k, x string) (ans string) {
|
||||
if k == "mime" {
|
||||
x = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(x))
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func unescape_metadata_value(k, x string) (ans string) {
|
||||
if k == "mime" {
|
||||
b, err := base64.StdEncoding.DecodeString(x)
|
||||
if err == nil {
|
||||
x = string(b)
|
||||
}
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func Encode_bytes(metadata map[string]string, payload []byte) string {
|
||||
ans := strings.Builder{}
|
||||
enc_payload := ""
|
||||
if len(payload) > 0 {
|
||||
enc_payload = base64.StdEncoding.EncodeToString(payload)
|
||||
}
|
||||
ans.Grow(2048 + len(enc_payload))
|
||||
ans.WriteString("\x1b]")
|
||||
ans.WriteString(OSC_NUMBER)
|
||||
ans.WriteString(";")
|
||||
for k, v := range metadata {
|
||||
if !strings.HasSuffix(ans.String(), ";") {
|
||||
ans.WriteString(":")
|
||||
}
|
||||
ans.WriteString(k)
|
||||
ans.WriteString("=")
|
||||
ans.WriteString(escape_metadata_value(k, v))
|
||||
}
|
||||
if len(payload) > 0 {
|
||||
ans.WriteString(";")
|
||||
ans.WriteString(enc_payload)
|
||||
}
|
||||
ans.WriteString("\x1b\\")
|
||||
return ans.String()
|
||||
}
|
||||
|
||||
func encode(metadata map[string]string, payload string) string {
|
||||
return Encode_bytes(metadata, utils.UnsafeStringToBytes(payload))
|
||||
}
|
||||
|
||||
func error_from_status(status string) error {
|
||||
switch status {
|
||||
case "ENOSYS":
|
||||
return fmt.Errorf("no primary selection available on this system")
|
||||
case "EPERM":
|
||||
return fmt.Errorf("permission denied")
|
||||
case "EBUSY":
|
||||
return fmt.Errorf("a temporary error occurred, try again later.")
|
||||
default:
|
||||
return fmt.Errorf("%s", status)
|
||||
}
|
||||
}
|
||||
|
||||
func parse_escape_code(etype loop.EscapeCodeType, data []byte) (metadata map[string]string, payload []byte, err error) {
|
||||
if etype != loop.OSC || !bytes.HasPrefix(data, utils.UnsafeStringToBytes(OSC_NUMBER+";")) {
|
||||
return
|
||||
}
|
||||
parts := bytes.SplitN(data, utils.UnsafeStringToBytes(";"), 3)
|
||||
metadata = make(map[string]string)
|
||||
if len(parts) > 2 && len(parts[2]) > 0 {
|
||||
payload, err = base64.StdEncoding.DecodeString(utils.UnsafeBytesToString(parts[2]))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Received OSC %s packet from terminal with invalid base64 encoded payload", OSC_NUMBER)
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(parts) > 1 {
|
||||
for record := range bytes.SplitSeq(parts[1], utils.UnsafeStringToBytes(":")) {
|
||||
rp := bytes.SplitN(record, utils.UnsafeStringToBytes("="), 2)
|
||||
v := ""
|
||||
if len(rp) == 2 {
|
||||
v = string(rp[1])
|
||||
}
|
||||
k := string(rp[0])
|
||||
metadata[k] = unescape_metadata_value(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func parse_aliases(raw []string) (map[string][]string, error) {
|
||||
ans := make(map[string][]string, len(raw))
|
||||
for _, x := range raw {
|
||||
k, v, found := strings.Cut(x, "=")
|
||||
if !found {
|
||||
return nil, fmt.Errorf("%s is not valid MIME alias specification", x)
|
||||
}
|
||||
ans[k] = append(ans[k], v)
|
||||
ans[v] = append(ans[v], k)
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func (self *Output) writes_directly_to_stream() bool {
|
||||
return self.arg_is_stream && !self.image_needs_conversion
|
||||
}
|
||||
|
||||
// All the outputs for a single remote MIME type. Outputs that write directly
|
||||
// to a stream receive data as it arrives, all others are saved from a single
|
||||
// temporary file holding the downloaded data, once all of it is received.
|
||||
type read_group struct {
|
||||
outputs []*Output
|
||||
downloaded *os.File
|
||||
err error
|
||||
all_data_received bool
|
||||
}
|
||||
|
||||
// Create the temporary file in the directory of the first output where that
|
||||
// is possible, so a missing output directory does not affect other outputs
|
||||
func (self *read_group) create_download_file() (f *os.File, err error) {
|
||||
for _, o := range self.outputs {
|
||||
if o.writes_directly_to_stream() {
|
||||
continue
|
||||
}
|
||||
d := cwd
|
||||
if strings.ContainsRune(o.arg, os.PathSeparator) && !o.arg_is_stream {
|
||||
d = filepath.Dir(o.arg)
|
||||
}
|
||||
if f, err = os.CreateTemp(d, "."+filepath.Base(o.arg)); err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *read_group) add_data(data []byte) {
|
||||
if self.all_data_received {
|
||||
return
|
||||
}
|
||||
needs_download := false
|
||||
for _, o := range self.outputs {
|
||||
if o.writes_directly_to_stream() {
|
||||
o.add_data(data)
|
||||
} else {
|
||||
// Any errors are reported for this output when committing
|
||||
o.started = true
|
||||
needs_download = true
|
||||
}
|
||||
}
|
||||
if !needs_download || self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.downloaded == nil {
|
||||
if self.downloaded, self.err = self.create_download_file(); self.err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_, self.err = self.downloaded.Write(data)
|
||||
}
|
||||
|
||||
func (self *read_group) commit() {
|
||||
defer self.cleanup()
|
||||
src := downloaded_data{file: self.downloaded}
|
||||
for _, o := range self.outputs {
|
||||
switch {
|
||||
case o.writes_directly_to_stream():
|
||||
case self.err != nil:
|
||||
o.err = self.err
|
||||
case self.downloaded != nil:
|
||||
o.save(&src)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *read_group) cleanup() {
|
||||
if self.downloaded != nil {
|
||||
self.downloaded.Close()
|
||||
os.Remove(self.downloaded.Name())
|
||||
self.downloaded = nil
|
||||
}
|
||||
}
|
||||
|
||||
type read_outputs map[string]*read_group
|
||||
|
||||
func (self read_outputs) add(o *Output) error {
|
||||
g := self[o.remote_mime_type]
|
||||
if g == nil {
|
||||
g = &read_group{}
|
||||
self[o.remote_mime_type] = g
|
||||
}
|
||||
if o.arg_is_stream {
|
||||
// Stream outputs write data as it arrives, so two of them sharing a
|
||||
// remote MIME type would interleave their data in the same stream.
|
||||
for _, x := range g.outputs {
|
||||
if x.arg_is_stream && x.arg == o.arg {
|
||||
return fmt.Errorf("Cannot write the clipboard MIME type %s to %s more than once", o.remote_mime_type, o.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
g.outputs = append(g.outputs, o)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self read_outputs) add_data(mime_type string, data []byte) {
|
||||
if g := self[mime_type]; g != nil {
|
||||
g.add_data(data)
|
||||
}
|
||||
}
|
||||
|
||||
func (self read_outputs) commit(mime_type string, wg *sync.WaitGroup) {
|
||||
if g := self[mime_type]; g != nil && !g.all_data_received {
|
||||
g.all_data_received = true
|
||||
for _, o := range g.outputs {
|
||||
o.all_data_received = true
|
||||
}
|
||||
wg.Go(g.commit)
|
||||
}
|
||||
}
|
||||
|
||||
func (self read_outputs) cleanup() {
|
||||
for _, g := range self {
|
||||
g.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the path in the same order as utils.AtomicUpdateFile, then resolve
|
||||
// symlinks in the absolute working-directory prefix as well.
|
||||
func resolved_output_path(path string) (string, error) {
|
||||
path, err := utils.EvalSymlinksThatExist(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path, err = filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return utils.EvalSymlinksThatExist(path)
|
||||
}
|
||||
|
||||
func check_for_duplicate_output_files(outputs []*Output) error {
|
||||
type resolved_output struct {
|
||||
path, arg string
|
||||
}
|
||||
seen := make(map[string]string, len(outputs))
|
||||
resolved := make([]resolved_output, 0, len(outputs))
|
||||
for _, o := range outputs {
|
||||
if o.arg_is_stream {
|
||||
continue
|
||||
}
|
||||
path, err := resolved_output_path(o.arg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to resolve the output path %s with error: %w", o.arg, err)
|
||||
}
|
||||
if prev, found := seen[path]; found {
|
||||
return fmt.Errorf("The output files %s and %s are the same file", prev, o.arg)
|
||||
}
|
||||
seen[path] = o.arg
|
||||
resolved = append(resolved, resolved_output{path, o.arg})
|
||||
}
|
||||
if len(resolved) < 2 {
|
||||
// Avoid creating probe files when there is nothing to compare
|
||||
return nil
|
||||
}
|
||||
|
||||
// Let the destination filesystem compare the names, including case
|
||||
// and Unicode normalization, without touching the output files.
|
||||
type created_probe struct {
|
||||
info os.FileInfo
|
||||
arg string
|
||||
}
|
||||
probe_prefix := "." + utils.RandomFilename() + "-"
|
||||
probes := make([]created_probe, 0, len(resolved))
|
||||
for _, r := range resolved {
|
||||
probe := filepath.Join(filepath.Dir(r.path), probe_prefix+filepath.Base(r.path))
|
||||
f, err := os.OpenFile(probe, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
if os.IsExist(err) {
|
||||
if s, serr := os.Stat(probe); serr == nil {
|
||||
for _, p := range probes {
|
||||
if os.SameFile(p.info, s) {
|
||||
return fmt.Errorf("The output files %s and %s are the same file", p.arg, r.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("The output file %s refers to the same file as another output", r.arg)
|
||||
}
|
||||
// If no temporary file can be created, let this output report
|
||||
// its write error without preventing other outputs.
|
||||
continue
|
||||
}
|
||||
defer os.Remove(probe)
|
||||
s, err := f.Stat()
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to stat the temporary file %s with error: %w", probe, err)
|
||||
}
|
||||
probes = append(probes, created_probe{s, r.arg})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func run_get_loop(opts *Options, args []string) (err error) {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var available_mimes []string
|
||||
var wg sync.WaitGroup
|
||||
var getting_data_for string
|
||||
requested_mimes := make(read_outputs)
|
||||
reading_available_mimes := true
|
||||
outputs := make([]*Output, len(args))
|
||||
aliases, merr := parse_aliases(opts.Alias)
|
||||
if merr != nil {
|
||||
return merr
|
||||
}
|
||||
|
||||
for i, arg := range args {
|
||||
outputs[i] = &Output{arg: arg, arg_is_stream: arg == "/dev/stdout" || arg == "/dev/stderr", ext: filepath.Ext(arg)}
|
||||
if len(opts.Mime) > i {
|
||||
outputs[i].mime_type = opts.Mime[i]
|
||||
} else {
|
||||
if outputs[i].arg_is_stream {
|
||||
outputs[i].mime_type = "text/plain"
|
||||
} else {
|
||||
outputs[i].mime_type = utils.GuessMimeType(outputs[i].arg)
|
||||
}
|
||||
}
|
||||
if outputs[i].mime_type == "" {
|
||||
return fmt.Errorf("Could not detect the MIME type for: %s use --mime to specify it manually", arg)
|
||||
}
|
||||
}
|
||||
if err = check_for_duplicate_output_files(outputs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
requested_mimes.cleanup()
|
||||
for _, o := range outputs {
|
||||
if o.dest != nil {
|
||||
o.cleanup()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
basic_metadata := map[string]string{"type": "read"}
|
||||
if opts.UsePrimary {
|
||||
basic_metadata["loc"] = "primary"
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.QueueWriteString(encode(basic_metadata, "."))
|
||||
if opts.Password != "" {
|
||||
basic_metadata["pw"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.Password))
|
||||
}
|
||||
if opts.HumanName != "" {
|
||||
basic_metadata["name"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.HumanName))
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
metadata, payload, err := parse_escape_code(etype, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
if reading_available_mimes {
|
||||
switch metadata["status"] {
|
||||
case "DATA":
|
||||
available_mimes = utils.Map(strings.TrimSpace, strings.Split(utils.UnsafeBytesToString(payload), " "))
|
||||
case "OK":
|
||||
case "DONE":
|
||||
reading_available_mimes = false
|
||||
if len(available_mimes) == 0 {
|
||||
return fmt.Errorf("The clipboard is empty")
|
||||
}
|
||||
for _, o := range outputs {
|
||||
err = o.assign_mime_type(available_mimes, aliases)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.remote_mime_type == "." {
|
||||
o.write_mime_list(available_mimes)
|
||||
} else if err = requested_mimes.add(o); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(requested_mimes) > 0 {
|
||||
lp.QueueWriteString(encode(basic_metadata, strings.Join(utils.Keys(requested_mimes), " ")))
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("Failed to read list of available data types in the clipboard with error: %w", error_from_status(metadata["status"]))
|
||||
}
|
||||
} else {
|
||||
switch metadata["status"] {
|
||||
case "DATA":
|
||||
current_mime := metadata["mime"]
|
||||
if _, found := requested_mimes[current_mime]; found {
|
||||
if getting_data_for != current_mime {
|
||||
requested_mimes.commit(getting_data_for, &wg)
|
||||
getting_data_for = current_mime
|
||||
}
|
||||
requested_mimes.add_data(current_mime, payload)
|
||||
}
|
||||
case "OK":
|
||||
case "DONE":
|
||||
requested_mimes.commit(getting_data_for, &wg)
|
||||
getting_data_for = ""
|
||||
lp.Quit(0)
|
||||
default:
|
||||
return fmt.Errorf("Failed to read data from the clipboard with error: %w", error_from_status(metadata["status"]))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
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))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
err = fmt.Errorf("Failed to get %s with error: %w", o.arg, o.err)
|
||||
return
|
||||
}
|
||||
if !o.started {
|
||||
err = fmt.Errorf("No data for %s with MIME type: %s", o.arg, o.mime_type)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClipboardReadMultipleOutputs(t *testing.T) {
|
||||
var png_data bytes.Buffer
|
||||
bounds := image.Rect(0, 0, 2, 3)
|
||||
if err := png.Encode(&png_data, image.NewRGBA(bounds)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
available_mimes []string
|
||||
output_mimes []string
|
||||
aliases []string
|
||||
}{
|
||||
{"text", []string{"text/plain"}, []string{"text/plain", "text/plain"}, nil},
|
||||
{"images", []string{"image/png"}, []string{"image/png", "image/jpeg"}, nil},
|
||||
{"images reversed", []string{"image/png"}, []string{"image/jpeg", "image/png"}, nil},
|
||||
{"mixed", []string{"image/png", "text/plain"}, []string{"text/plain", "image/png", "text/plain", "image/jpeg"}, nil},
|
||||
{"alias", []string{"text/x-custom"}, []string{"text/plain", "text/x-custom"}, []string{"text/plain=text/x-custom"}},
|
||||
{"wildcard", []string{"text/plain"}, []string{"text/*", "text/plain"}, nil},
|
||||
{"text fallback", []string{"text/plain"}, []string{"text/html", "text/plain"}, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
aliases, err := parse_aliases(tc.aliases)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var outputs []*Output
|
||||
var names []string
|
||||
for i, mime_type := range tc.output_mimes {
|
||||
name := fmt.Sprintf("output-%d", i)
|
||||
names = append(names, name)
|
||||
o := &Output{arg: filepath.Join(dir, name), mime_type: mime_type}
|
||||
defer o.cleanup()
|
||||
if err := o.assign_mime_type(tc.available_mimes, aliases); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs = append(outputs, o)
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(requested) != len(tc.available_mimes) {
|
||||
t.Fatalf("Expected one request per remote MIME type, got %d", len(requested))
|
||||
}
|
||||
text_data := []byte("first line\nsecond line\n")
|
||||
var wg sync.WaitGroup
|
||||
for _, mime_type := range tc.available_mimes {
|
||||
data := text_data
|
||||
if mime_type == "image/png" {
|
||||
data = png_data.Bytes()
|
||||
}
|
||||
for chunk := range slices.Chunk(data, 7) {
|
||||
requested.add_data(mime_type, chunk)
|
||||
}
|
||||
requested.commit(mime_type, &wg)
|
||||
// Completed outputs must ignore further data and not be committed twice.
|
||||
requested.add_data(mime_type, []byte("ignored"))
|
||||
requested.commit(mime_type, &wg)
|
||||
}
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
t.Fatal(o.err)
|
||||
}
|
||||
if !o.started || !o.all_data_received {
|
||||
t.Fatalf("Output %s was not completed", o.arg)
|
||||
}
|
||||
data, err := os.ReadFile(o.arg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch o.mime_type {
|
||||
case "image/jpeg":
|
||||
img, format, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format != "jpeg" || img.Bounds() != bounds {
|
||||
t.Fatalf("Incorrect converted image: %s %v", format, img.Bounds())
|
||||
}
|
||||
case "image/png":
|
||||
if !bytes.Equal(data, png_data.Bytes()) {
|
||||
t.Fatal("PNG output differs from clipboard data")
|
||||
}
|
||||
default:
|
||||
if !bytes.Equal(data, text_data) {
|
||||
t.Fatalf("Incorrect text output: %q", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, names) {
|
||||
t.Fatalf("Unexpected output files: %v", actual)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadOutputFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
failed := &Output{arg: filepath.Join(dir, "missing", "output"), remote_mime_type: "text/plain"}
|
||||
succeeded := &Output{arg: filepath.Join(dir, "output"), remote_mime_type: "text/plain"}
|
||||
defer failed.cleanup()
|
||||
defer succeeded.cleanup()
|
||||
if err := check_for_duplicate_output_files([]*Output{failed, succeeded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
for _, o := range []*Output{failed, succeeded} {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
if failed.err == nil {
|
||||
t.Fatal("Expected an error writing to a missing directory")
|
||||
}
|
||||
if succeeded.err != nil {
|
||||
t.Fatal(succeeded.err)
|
||||
}
|
||||
if data, err := os.ReadFile(succeeded.arg); err != nil || string(data) != "clipboard contents" {
|
||||
t.Fatalf("Other output was not saved after a write failure: %q %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateStreamOutputs(t *testing.T) {
|
||||
stream := func(arg, remote_mime_type string) *Output {
|
||||
return &Output{arg: arg, arg_is_stream: true, remote_mime_type: remote_mime_type}
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
for _, o := range []*Output{
|
||||
stream("/dev/stdout", "text/plain"),
|
||||
stream("/dev/stderr", "text/plain"),
|
||||
stream("/dev/stdout", "text/html"),
|
||||
{arg: filepath.Join(t.TempDir(), "output"), remote_mime_type: "text/plain"},
|
||||
} {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, o := range []*Output{stream("/dev/stdout", "text/plain"), stream("/dev/stderr", "text/plain")} {
|
||||
if err := requested.add(o); err == nil {
|
||||
t.Fatalf("Duplicate stream output to %s for %s was not rejected", o.arg, o.remote_mime_type)
|
||||
}
|
||||
}
|
||||
if len(requested["text/plain"].outputs) != 3 || len(requested["text/html"].outputs) != 1 {
|
||||
t.Fatalf("Rejected outputs were added: %d %d", len(requested["text/plain"].outputs), len(requested["text/html"].outputs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadSharedDownload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
var outputs []*Output
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
o := &Output{arg: filepath.Join(dir, name), remote_mime_type: "text/plain"}
|
||||
outputs = append(outputs, o)
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard "))
|
||||
// All outputs share a single temporary file for the downloaded data
|
||||
if actual := list_dir(t, dir); len(actual) != 1 {
|
||||
t.Fatalf("Expected a single temporary file, got: %v", actual)
|
||||
}
|
||||
requested.add_data("text/plain", []byte("contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
t.Fatal(o.err)
|
||||
}
|
||||
if data, err := os.ReadFile(o.arg); err != nil || string(data) != "clipboard contents" {
|
||||
t.Fatalf("Incorrect contents for %s: %q %v", o.arg, data, err)
|
||||
}
|
||||
}
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("Temporary file not removed: %v", actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDownloadFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
outputs := []*Output{
|
||||
{arg: filepath.Join(dir, "missing", "a"), remote_mime_type: "text/plain"},
|
||||
{arg: filepath.Join(dir, "missing", "b"), remote_mime_type: "text/plain"},
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
for _, o := range outputs {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err == nil {
|
||||
t.Fatalf("Expected an error for %s when no temporary file can be created", o.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
if err := os.Symlink("target", "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir("sub", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs := func(args ...string) (ans []*Output) {
|
||||
for _, arg := range args {
|
||||
ans = append(ans, &Output{arg: arg, arg_is_stream: arg == "/dev/stdout" || arg == "/dev/stderr"})
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"a", "b", "sub/a", "/dev/stdout", "/dev/stdout", "/dev/stderr"},
|
||||
{"link", "sub/target"},
|
||||
} {
|
||||
if err := check_for_duplicate_output_files(outputs(args...)); err != nil {
|
||||
t.Fatalf("Unexpected error for %v: %s", args, err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"a", "a"},
|
||||
{"a", "./a"},
|
||||
{"a", filepath.Join(dir, "a")},
|
||||
{"sub/../a", "a"},
|
||||
{"link", "target"},
|
||||
{"target", filepath.Join(dir, "link")},
|
||||
} {
|
||||
if err := check_for_duplicate_output_files(outputs(args...)); err == nil {
|
||||
t.Fatalf("Duplicate output files not rejected: %v", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadCaseAliasedOutputFiles(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t", existing), func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
for _, dir := range []string{"destination", "DESTINATION"} {
|
||||
if err := os.Mkdir(dir, 0o755); err != nil && !os.IsExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
lower, err := os.Stat("destination")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upper, err := os.Stat("DESTINATION")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case_insensitive := os.SameFile(lower, upper)
|
||||
if err := os.Symlink("destination/OUTPUT.TXT", "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := []string{"destination/output.txt", "destination/OUTPUT.TXT", "DESTINATION/output.txt", "DESTINATION/OUTPUT.TXT"}
|
||||
if existing {
|
||||
for _, path := range paths {
|
||||
if err := os.WriteFile(path, []byte("original contents"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
before := map[string][]string{"destination": list_dir(t, "destination"), "DESTINATION": list_dir(t, "DESTINATION")}
|
||||
for _, path := range append(paths[1:], "link") {
|
||||
err := check_for_duplicate_output_files([]*Output{{arg: paths[0]}, {arg: path}})
|
||||
if (err != nil) != case_insensitive {
|
||||
t.Errorf("Incorrect duplicate detection for %s and %s: case_insensitive=%t error=%v", paths[0], path, case_insensitive, err)
|
||||
}
|
||||
if err != nil {
|
||||
if expected := fmt.Sprintf("The output files %s and %s are the same file", paths[0], path); err.Error() != expected {
|
||||
t.Errorf("Incorrect error message: %q != %q", err.Error(), expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir, files := range before {
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, files) {
|
||||
t.Errorf("Duplicate detection left files behind in %s: %v", dir, actual)
|
||||
}
|
||||
}
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if existing {
|
||||
if err != nil || string(data) != "original contents" {
|
||||
t.Errorf("Duplicate detection changed %s: %q %v", path, data, err)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Errorf("Duplicate detection created %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadHardLinkedOutputFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "output.txt"), filepath.Join(dir, "hardlink.txt")
|
||||
if err := os.WriteFile(a, []byte("original contents"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(a, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Atomic replacement writes to distinct directory entries even when the
|
||||
// original files share an inode.
|
||||
if err := check_for_duplicate_output_files([]*Output{{arg: a}, {arg: b}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFilesSymlinkParent(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
for _, absolute_link := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t/absolute_link=%t", existing, absolute_link), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
if err := os.MkdirAll("real/sub", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := "real/sub"
|
||||
if absolute_link {
|
||||
link = filepath.Join(dir, link)
|
||||
}
|
||||
if err := os.Symlink(link, "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if existing {
|
||||
for _, path := range []string{"target", "real/target"} {
|
||||
if err := os.WriteFile(path, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Concatenate to preserve link/.. in the absolute path as well.
|
||||
for _, path := range []string{"link/../target", dir + "/link/../target"} {
|
||||
outputs := []*Output{{arg: path}, {arg: "real/target"}}
|
||||
if err := check_for_duplicate_output_files(outputs); err == nil {
|
||||
t.Errorf("Duplicate output files not rejected: %s and real/target", path)
|
||||
}
|
||||
outputs[1].arg = "target"
|
||||
if err := check_for_duplicate_output_files(outputs); err != nil {
|
||||
t.Errorf("Distinct output files rejected: %s and target: %s", path, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFilesSymlinkCwd(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t", existing), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, "real", "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(dir, "link")
|
||||
if err := os.Symlink("real/sub", link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(link)
|
||||
t.Setenv("PWD", link)
|
||||
paths := []string{filepath.Join(dir, "target"), filepath.Join(dir, "real", "target")}
|
||||
if existing {
|
||||
for _, path := range paths {
|
||||
if err := os.WriteFile(path, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
output := &Output{arg: "../target"}
|
||||
defer output.cleanup()
|
||||
output.add_data([]byte("clipboard contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
// Compare detection with the actual write, including when PWD
|
||||
// names a symlink rather than the physical working directory.
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written := string(data) == "clipboard contents"
|
||||
err = check_for_duplicate_output_files([]*Output{output, {arg: path}})
|
||||
if (err != nil) != written {
|
||||
t.Errorf("Duplicate detection disagrees with write to %s: written=%t error=%v", path, written, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitAtomic(t *testing.T) {
|
||||
dest := filepath.Join(t.TempDir(), "output")
|
||||
old_data := bytes.Repeat([]byte("old contents\n"), 1024)
|
||||
new_data := bytes.Repeat([]byte("new contents\n"), 1024)
|
||||
if err := os.WriteFile(dest, old_data, 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
started, stop := make(chan struct{}), make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
data, err := os.ReadFile(dest)
|
||||
close(started)
|
||||
for {
|
||||
if err != nil {
|
||||
result <- fmt.Errorf("Concurrent read failed: %w", err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(data, old_data) && !bytes.Equal(data, new_data) {
|
||||
result <- fmt.Errorf("Concurrent read returned incomplete contents: %q", data)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-stop:
|
||||
result <- nil
|
||||
return
|
||||
default:
|
||||
}
|
||||
data, err = os.ReadFile(dest)
|
||||
}
|
||||
}()
|
||||
<-started
|
||||
t.Cleanup(func() {
|
||||
close(stop)
|
||||
if err := <-result; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
|
||||
for i := range 100 {
|
||||
data := new_data
|
||||
if i%2 != 0 {
|
||||
data = old_data
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
output.add_data(data)
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
temp_name := output.dest.Name()
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
actual, err := os.ReadFile(dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(actual, data) {
|
||||
t.Fatal("Committed file has incorrect contents")
|
||||
}
|
||||
if st, err := os.Stat(dest); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if st.Mode().Perm() != 0o640 {
|
||||
t.Fatalf("Committed file has incorrect permissions: %o", st.Mode().Perm())
|
||||
}
|
||||
if _, err := os.Stat(temp_name); !os.IsNotExist(err) {
|
||||
t.Fatalf("Temporary file still exists after commit: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func list_dir(t *testing.T, dir string) (ans []string) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
ans = append(ans, e.Name())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// Renaming a file over a non-empty directory fails even when running as root
|
||||
dest := filepath.Join(dir, "output")
|
||||
if err := os.MkdirAll(filepath.Join(dest, "child"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
defer output.cleanup()
|
||||
output.add_data([]byte("new contents"))
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
output.commit()
|
||||
if output.err == nil {
|
||||
t.Fatal("Expected commit to fail when destination is a non-empty directory")
|
||||
}
|
||||
if st, err := os.Stat(filepath.Join(dest, "child")); err != nil || !st.IsDir() {
|
||||
t.Fatalf("Original destination changed after failed commit: %v", err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"output"}) {
|
||||
t.Fatalf("Stray files left behind after failed commit: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitNewFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dest := filepath.Join(dir, "output")
|
||||
output := Output{arg: dest}
|
||||
output.add_data([]byte("new contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != "new contents" {
|
||||
t.Fatalf("Incorrect contents in new file: %q %v", actual, err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"output"}) {
|
||||
t.Fatalf("Stray files left behind after commit: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitSymlink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target")
|
||||
dest := filepath.Join(dir, "link")
|
||||
if err := os.WriteFile(target, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
output.add_data([]byte("new contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if st, err := os.Lstat(dest); err != nil || st.Mode()&os.ModeSymlink == 0 {
|
||||
t.Fatalf("Symlink at destination was replaced: %v", err)
|
||||
}
|
||||
if actual, err := os.ReadFile(target); err != nil || string(actual) != "new contents" {
|
||||
t.Fatalf("Symlink target not updated: %q %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitDanglingSymlink(t *testing.T) {
|
||||
for _, link_type := range []string{"absolute", "relative"} {
|
||||
for _, data_type := range []string{"text", "image"} {
|
||||
t.Run(link_type+"/"+data_type, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target")
|
||||
dest := filepath.Join(dir, "link")
|
||||
link := target
|
||||
if link_type == "relative" {
|
||||
link = "target"
|
||||
}
|
||||
if err := os.Symlink(link, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte("new contents")
|
||||
output := Output{arg: dest}
|
||||
defer output.cleanup()
|
||||
if data_type == "image" {
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data = buf.Bytes()
|
||||
output.image_needs_conversion = true
|
||||
output.mime_type = "image/jpeg"
|
||||
}
|
||||
output.add_data(data)
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if actual, err := os.Readlink(dest); err != nil || actual != link {
|
||||
t.Errorf("Symlink at destination changed: %q %v", actual, err)
|
||||
}
|
||||
actual, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
t.Fatalf("Symlink target not created: %v", err)
|
||||
}
|
||||
if data_type == "image" {
|
||||
img, format, err := image.Decode(bytes.NewReader(actual))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format != "jpeg" || img.Bounds() != image.Rect(0, 0, 2, 3) {
|
||||
t.Fatalf("Incorrect converted image: %s %v", format, img.Bounds())
|
||||
}
|
||||
} else if !bytes.Equal(actual, data) {
|
||||
t.Fatalf("Incorrect contents in symlink target: %q", actual)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"link", "target"}) {
|
||||
t.Fatalf("Stray files left behind after commit: %v", names)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputImageEncodeFailure(t *testing.T) {
|
||||
dest := filepath.Join(t.TempDir(), "output")
|
||||
old_data := []byte("old contents")
|
||||
if err := os.WriteFile(dest, old_data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var png_data bytes.Buffer
|
||||
if err := png.Encode(&png_data, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest, image_needs_conversion: true, mime_type: "image/x-unsupported"}
|
||||
defer output.cleanup()
|
||||
output.add_data(png_data.Bytes())
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
output.commit()
|
||||
if output.err == nil {
|
||||
t.Fatal("Expected commit to fail with an unsupported image type")
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || !bytes.Equal(actual, old_data) {
|
||||
t.Fatalf("Original destination changed after failed image encode: %q %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputMimeList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dest := filepath.Join(dir, "formats.txt")
|
||||
output := Output{arg: dest, mime_type: ".", remote_mime_type: "."}
|
||||
defer output.cleanup()
|
||||
output.write_mime_list([]string{"text/plain", "image/png"})
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if !output.started || !output.all_data_received {
|
||||
t.Fatal("MIME list output not marked as complete")
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != "text/plain\nimage/png" {
|
||||
t.Fatalf("Incorrect MIME list saved: %q %v", actual, err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"formats.txt"}) {
|
||||
t.Fatalf("Stray files left behind after saving MIME list: %v", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Input struct {
|
||||
src io.Reader
|
||||
arg string
|
||||
ext string
|
||||
is_stream bool
|
||||
mime_type string
|
||||
extra_mime_types []string
|
||||
}
|
||||
|
||||
func is_textual_mime(x string) bool {
|
||||
return strings.HasPrefix(x, "text/") || utils.KnownTextualMimes[x]
|
||||
}
|
||||
|
||||
func is_text_plain_mime(x string) bool {
|
||||
return x == "text/plain"
|
||||
}
|
||||
|
||||
func (self *Input) has_mime_matching(predicate func(string) bool) bool {
|
||||
if predicate(self.mime_type) {
|
||||
return true
|
||||
}
|
||||
return slices.ContainsFunc(self.extra_mime_types, predicate)
|
||||
}
|
||||
|
||||
func write_loop(inputs []*Input, opts *Options) (err error) {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var waiting_for_write loop.IdType
|
||||
var buf [4096]byte
|
||||
aliases, aerr := parse_aliases(opts.Alias)
|
||||
if aerr != nil {
|
||||
return aerr
|
||||
}
|
||||
num_text_mimes := 0
|
||||
has_text_plain := false
|
||||
for _, i := range inputs {
|
||||
i.extra_mime_types = aliases[i.mime_type]
|
||||
if i.has_mime_matching(is_textual_mime) {
|
||||
num_text_mimes++
|
||||
if !has_text_plain && i.has_mime_matching(is_text_plain_mime) {
|
||||
has_text_plain = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if num_text_mimes > 0 && !has_text_plain {
|
||||
for _, i := range inputs {
|
||||
if i.has_mime_matching(is_textual_mime) {
|
||||
i.extra_mime_types = append(i.extra_mime_types, "text/plain")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
make_metadata := func(ptype, mime string) map[string]string {
|
||||
ans := map[string]string{"type": ptype}
|
||||
if opts.UsePrimary {
|
||||
ans["loc"] = "primary"
|
||||
}
|
||||
if mime != "" {
|
||||
ans["mime"] = mime
|
||||
}
|
||||
if ptype == "write" {
|
||||
if opts.Password != "" {
|
||||
ans["pw"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.Password))
|
||||
}
|
||||
if opts.HumanName != "" {
|
||||
ans["name"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.HumanName))
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
waiting_for_write = lp.QueueWriteString(encode(make_metadata("write", ""), ""))
|
||||
return "", nil
|
||||
}
|
||||
|
||||
write_chunk := func() error {
|
||||
if len(inputs) == 0 {
|
||||
return nil
|
||||
}
|
||||
i := inputs[0]
|
||||
n, err := i.src.Read(buf[:])
|
||||
if n > 0 {
|
||||
waiting_for_write = lp.QueueWriteString(Encode_bytes(make_metadata("wdata", i.mime_type), buf[:n]))
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if len(i.extra_mime_types) > 0 {
|
||||
lp.QueueWriteString(encode(make_metadata("walias", i.mime_type), strings.Join(i.extra_mime_types, " ")))
|
||||
}
|
||||
inputs = inputs[1:]
|
||||
if len(inputs) == 0 {
|
||||
lp.QueueWriteString(encode(make_metadata("wdata", ""), ""))
|
||||
waiting_for_write = 0
|
||||
}
|
||||
return lp.OnWriteComplete(waiting_for_write, false)
|
||||
}
|
||||
return fmt.Errorf("Failed to read from %s with error: %w", i.arg, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnWriteComplete = func(msg_id loop.IdType, has_pending_writes bool) error {
|
||||
if waiting_for_write == msg_id {
|
||||
return write_chunk()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
metadata, _, err := parse_escape_code(etype, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata != nil && metadata["type"] == "write" {
|
||||
switch metadata["status"] {
|
||||
case "DONE":
|
||||
lp.Quit(0)
|
||||
case "EIO":
|
||||
return fmt.Errorf("Could not write to clipboard an I/O error occurred while the terminal was processing the data")
|
||||
case "EINVAL":
|
||||
return fmt.Errorf("Could not write to clipboard base64 encoding invalid")
|
||||
case "ENOSYS":
|
||||
return fmt.Errorf("Could not write to primary selection as the system does not support it")
|
||||
case "EPERM":
|
||||
return fmt.Errorf("Could not write to clipboard as permission was denied")
|
||||
case "EBUSY":
|
||||
return fmt.Errorf("Could not write to clipboard, a temporary error occurred, try again later.")
|
||||
case "EFBIG":
|
||||
return fmt.Errorf("Could not write to clipboard as there is too much data, see the clipboard_max_size option in the terminal")
|
||||
default:
|
||||
return fmt.Errorf("Could not write to clipboard unknowns status returned from terminal: %#v", metadata["status"])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
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))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func run_set_loop(opts *Options, args []string) (err error) {
|
||||
inputs := make([]*Input, len(args))
|
||||
to_process := make([]*Input, len(args))
|
||||
defer func() {
|
||||
for _, i := range inputs {
|
||||
if i != nil && i.src != nil {
|
||||
rc, ok := i.src.(io.Closer)
|
||||
if ok {
|
||||
rc.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for i, arg := range args {
|
||||
if arg == "/dev/stdin" {
|
||||
f, _, err := preread_stdin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inputs[i] = &Input{arg: arg, src: f, is_stream: true}
|
||||
} else {
|
||||
f, err := os.Open(arg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to open %s with error: %w", arg, err)
|
||||
}
|
||||
inputs[i] = &Input{arg: arg, src: f, ext: filepath.Ext(arg)}
|
||||
}
|
||||
if i < len(opts.Mime) {
|
||||
inputs[i].mime_type = opts.Mime[i]
|
||||
} else if inputs[i].is_stream {
|
||||
inputs[i].mime_type = "text/plain"
|
||||
} else if inputs[i].ext != "" {
|
||||
inputs[i].mime_type = utils.GuessMimeType(inputs[i].arg)
|
||||
}
|
||||
if inputs[i].mime_type == "" {
|
||||
return fmt.Errorf("Could not guess MIME type for %s use the --mime option to specify a MIME type", arg)
|
||||
}
|
||||
to_process[i] = inputs[i]
|
||||
}
|
||||
return write_loop(to_process, opts)
|
||||
}
|
||||
Reference in new issue
Block a user