Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
664 lines
17 KiB
Go
664 lines
17 KiB
Go
// 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
|
|
}
|