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:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
//go:build darwin || freebsd || netbsd
package dnd
import (
"os"
"syscall"
"time"
)
// Return the birth time of the file at path, which must be the file
// described by info, or the zero time if it is unknown.
func birth_time(path string, info os.FileInfo) time.Time {
if st, ok := info.Sys().(*syscall.Stat_t); ok {
return time.Unix(st.Birthtimespec.Unix())
}
return time.Time{}
}
+32
View File
@@ -0,0 +1,32 @@
package dnd
import (
"os"
"time"
"golang.org/x/sys/unix"
)
// Return the birth time of the file at path, which must be the file
// described by info, or the zero time if it is unknown.
func birth_time(path string, info os.FileInfo) time.Time {
var sx unix.Statx_t
for {
err := unix.Statx(unix.AT_FDCWD, path, unix.AT_SYMLINK_NOFOLLOW, unix.STATX_INO|unix.STATX_BTIME, &sx)
if err == nil {
break
}
if err != unix.EINTR {
return time.Time{}
}
}
if sx.Mask&unix.STATX_BTIME == 0 {
return time.Time{}
}
// The path may have been replaced since info was obtained
dev, ino, err := file_identity(info)
if err != nil || ino != sx.Ino || dev != unix.Mkdev(sx.Dev_major, sx.Dev_minor) {
return time.Time{}
}
return time.Unix(sx.Btime.Sec, int64(sx.Btime.Nsec))
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !linux && !darwin && !freebsd && !netbsd
package dnd
import (
"os"
"time"
)
// Return the birth time of the file at path, which must be the file
// described by info, or the zero time if it is unknown.
func birth_time(path string, info os.FileInfo) time.Time {
return time.Time{}
}
+528
View File
@@ -0,0 +1,528 @@
package dnd
import (
"errors"
"fmt"
"image"
"io"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"github.com/emmansun/base64"
"github.com/kovidgoyal/imaging"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/streaming_base64"
)
var _ = fmt.Print
type data_request struct {
drag_source *drag_source
index int
write_id loop.IdType
base64 streaming_base64.StreamingBase64Encoder
}
type remote_data_item struct {
path string
metadata os.FileInfo
file *os.File
write_id loop.IdType
base64 streaming_base64.StreamingBase64Encoder
parent_dir_handle, idx_in_parent int
idx_in_uri_list int
}
type drag_status struct {
active bool
terminal_accepted_drag bool
offered_mimes []string
accepted_mime int
accepted_operation int
dropped bool
data_requests []*data_request
remote_items []*remote_data_item
current_remote_file *remote_data_item
dir_handle_counter int
remote_item_write_id loop.IdType
remote_data_requests []int
}
func find_drag_image(drag_sources map[string]*drag_source) image.Image {
for mime, ds := range drag_sources {
if ds.path != "" {
if strings.HasPrefix(mime, "image/") {
q, err := imaging.Open(ds.path)
if err == nil {
return q
}
}
}
}
var uri_list []string
if ds := drag_sources["text/uri-list"]; ds != nil {
for _, e := range ds.uri_list {
if e.path != "" {
uri_list = append(uri_list, e.path)
}
}
}
for _, path := range uri_list {
q, err := imaging.Open(path)
if err == nil {
return q
}
}
return nil
}
func (dnd *dnd) set_drag_image_text() (err error) {
icon := ""
from_path := func(path string) bool {
if st, err := os.Lstat(path); err == nil {
ans := strings.TrimSpace(icons.IconForFileWithMode(path, st.Mode(), true))
if ans != "" {
icon = ans
return true
}
}
return false
}
for _, ds := range dnd.drag_sources {
if ds.path != "" && from_path(ds.path) {
break
}
}
if icon == "" {
if ds := dnd.drag_sources["text/uri-list"]; ds != nil {
for _, e := range ds.uri_list {
if e.path != "" && from_path(e.path) {
break
}
}
}
}
if icon == "" {
icon = strings.TrimSpace("󰮐 ")
}
cmd := DC{Type: 'p', X: -1, Xp: 6, Yp: 1, Payload: []byte(icon)}
dnd.lp.QueueDnDData(cmd)
cmd.Payload = nil
dnd.lp.QueueDnDData(cmd)
return nil
}
func (dnd *dnd) set_drag_image() (err error) {
img := dnd.drag_thumbnail
if img == nil {
img = find_drag_image(dnd.drag_sources)
}
if img == nil {
return dnd.set_drag_image_text()
}
num_channels := utils.IfElse(imaging.IsOpaque(img), 3, 4)
sz := dnd.opts.DragThumbnailSize
if max(img.Bounds().Dx(), img.Bounds().Dy()) > sz {
w, h := 0, 0
if img.Bounds().Dx() >= img.Bounds().Dy() {
w = sz
} else {
h = sz
}
img = imaging.ResizeWithOpacity(img, w, h, imaging.Lanczos, num_channels == 3)
if dnd.drag_thumbnail != nil {
dnd.drag_thumbnail = img
}
}
var pix []byte
if imaging.IsOpaque(img) {
_, pix = 3, imaging.AsRGBData8(img)
} else {
pix = imaging.AsRGBAData8(img)
}
cmd := DC{
Type: 'p', X: -1, Y: utils.IfElse(num_channels == 3, 24, 32), Xp: img.Bounds().Dx(), Yp: img.Bounds().Dy(),
Payload: pix}
dnd.lp.QueueDnDData(cmd)
cmd.Payload = nil
dnd.lp.QueueDnDData(cmd)
return nil
}
func (dnd *dnd) on_potential_drag_start(cell_x, cell_y int) (err error) {
if !dnd.allow_drags || dnd.drag_status.active {
return
}
mimes := slices.Collect(maps.Keys(dnd.drag_sources))
actions := 3
if dnd.copy_button_region.has(cell_x, cell_y) {
actions = 1
} else if dnd.move_button_region.has(cell_x, cell_y) {
actions = 2
}
dnd.lp.QueueDnDData(DC{Type: 'o', Operation: actions, Payload: utils.UnsafeStringToBytes(strings.Join(mimes, " "))})
total_preloaded_data_sz := 0
for i, mt := range mimes {
s := dnd.drag_sources[mt]
if len(s.data) > 0 && len(s.data)+total_preloaded_data_sz < 64*1024*1024 {
total_preloaded_data_sz += len(s.data)
dnd.lp.QueueDnDData(DC{Type: 'p', X: i, Operation: actions, Payload: s.data})
dnd.lp.QueueDnDData(DC{Type: 'p', X: i, Operation: actions})
}
}
dnd.drag_status.offered_mimes = mimes
err = dnd.set_drag_image()
if err != nil {
dnd.finish_drag("EIO")
return err
}
dnd.lp.QueueDnDData(DC{Type: 'P', X: -1}) // start drag
dnd.drag_status.active = true
return dnd.render_screen()
}
func (dnd *dnd) on_drag_error(cmd DC) (err error) {
payload := string(cmd.Payload)
switch payload {
case "OK":
if dnd.drag_status.active && !dnd.drag_status.terminal_accepted_drag {
dnd.drag_status.terminal_accepted_drag = true
err = dnd.render_screen()
}
default:
err = fmt.Errorf("terminal responded with drag source error: %s", payload)
}
return
}
func (dnd *dnd) reset_drag() {
for _, dr := range dnd.drag_status.data_requests {
if dr.drag_source.file != nil {
dr.drag_source.file.Close()
dr.drag_source.file = nil
}
}
if dnd.drag_status.current_remote_file != nil && dnd.drag_status.current_remote_file.file != nil {
dnd.drag_status.current_remote_file.file.Close()
}
dnd.drag_status = drag_status{}
}
func (dnd *dnd) on_drag_event(x, y, operation int) (err error) {
switch x {
case 1:
dnd.drag_status.accepted_mime = y
case 2:
dnd.drag_status.accepted_operation = operation
case 3:
dnd.drag_status.dropped = true
case 4:
was_dropped := dnd.drag_status.dropped
was_move := dnd.drag_status.accepted_operation == 2
dnd.reset_drag()
if was_dropped && dnd.has_exit_on("drag-finish") {
dnd.lp.Quit(0)
}
if was_dropped && was_move {
if ds := dnd.drag_sources["text/uri-list"]; ds != nil {
for _, item := range ds.uri_list {
if item.was_sent {
if item.metadata.IsDir() {
err = os.RemoveAll(item.path)
} else {
err = os.Remove(item.path)
}
if err != nil {
return err
}
}
}
}
dnd.drag_sources = nil
dnd.allow_drags = false
dnd.lp.StopOfferingDrags()
if !dnd.allow_drops {
dnd.lp.Quit(0)
}
}
case 5:
if err = dnd.handle_data_request(y); err != nil {
return err
}
}
return dnd.render_screen()
}
func (dnd *dnd) finish_drag(errname string) {
if errname == "" { // cancel drag
dnd.lp.QueueDnDData(DC{Type: 'E', Y: -1})
} else {
dnd.lp.QueueDnDData(DC{Type: 'E', Payload: []byte(errname)})
}
dnd.reset_drag()
}
func (dnd *dnd) handle_data_request(idx int) (err error) {
if idx < 0 || idx >= len(dnd.drag_status.offered_mimes) {
dnd.finish_drag("EINVAL")
return fmt.Errorf("terminal asked for drag data from MIME list with out of bounds index: %d", idx)
}
mime := dnd.drag_status.offered_mimes[idx]
ds := dnd.drag_sources[mime]
for _, dr := range dnd.drag_status.data_requests {
if dr.index == idx {
dnd.finish_drag("EINVAL")
return fmt.Errorf("terminal sent a duplicate drag data request")
}
}
dr := &data_request{drag_source: ds, index: idx}
if ds.path == "" {
dnd.lp.QueueDnDData(DC{Type: 'e', Y: idx, Payload: utils.UnsafeStringToBytes(base64.RawStdEncoding.EncodeToString(ds.data))})
dnd.lp.QueueDnDData(DC{Type: 'e', Y: idx}) // EOF
return
} else {
if ds.file != nil {
ds.file.Close()
}
if ds.file, err = os.Open(ds.path); err != nil {
dnd.finish_drag("EIO")
return err
}
}
dnd.drag_status.data_requests = append(dnd.drag_status.data_requests, dr)
return dnd.send_data_for_data_request(len(dnd.drag_status.data_requests) - 1)
}
var read_buf [64 * 1024]byte
var encode_buf [128 * 1024]byte
func (dnd *dnd) send_data_for_data_request(i int) (err error) {
dr := dnd.drag_status.data_requests[i]
n, err := dr.drag_source.file.Read(read_buf[:])
if n > 0 {
for chunk := range dr.base64.Encode(read_buf[:n], encode_buf[:]) {
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index, Payload: chunk})
}
}
if err == nil {
return nil
}
if errors.Is(err, io.EOF) {
chunk := dr.base64.Finish()
if len(chunk) > 0 {
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index, Payload: chunk})
}
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index}) // EOF
return dnd.on_data_request_finished(i)
}
dnd.finish_drag("EIO")
return err
}
func (dnd *dnd) on_send_done(id loop.IdType) (err error) {
for i, dr := range dnd.drag_status.data_requests {
if dr.write_id == id {
return dnd.send_data_for_data_request(i)
}
}
if id == dnd.drag_status.remote_item_write_id {
dnd.drag_status.remote_item_write_id = 0
err = dnd.send_next_file_chunk()
}
return
}
func (dnd *dnd) on_data_request_finished(i int) (err error) {
dr := dnd.drag_status.data_requests[i]
if dr.drag_source.file != nil {
dr.drag_source.file.Close()
dr.drag_source.file = nil
}
dnd.drag_status.data_requests = slices.Delete(dnd.drag_status.data_requests, i, i+1)
if len(dnd.drag_status.data_requests) > 0 {
err = dnd.send_data_for_data_request(0)
}
return
}
func (dnd *dnd) send_remote_item_payload(parent_dir_handle, idx_in_parent, idx_in_uri_list, item_type int, payload []byte) loop.IdType {
cmd := DC{Type: 'k', Xp: item_type, X: idx_in_uri_list + 1}
if len(payload) > 0 {
if item_type == 0 {
cmd.Payload = payload
} else {
cmd.Payload = utils.UnsafeStringToBytes(base64.RawStdEncoding.EncodeToString(payload))
}
}
if parent_dir_handle != 0 {
cmd.Yp = parent_dir_handle
cmd.Y = idx_in_parent + 1
}
return dnd.lp.QueueDnDData(cmd)
}
func (dnd *dnd) send_remote_dir(path string, idx_in_uri_list, parent_dir_handle, idx int) (children []*remote_data_item, err error) {
entries, err := os.ReadDir(path)
if err != nil {
dnd.finish_drag("EIO")
return nil, err
}
for dnd.drag_status.dir_handle_counter < 2 {
dnd.drag_status.dir_handle_counter++
}
handle := dnd.drag_status.dir_handle_counter
dnd.drag_status.dir_handle_counter++
names := make([]string, 0, len(entries))
for i, entry := range entries {
st, err := entry.Info()
if err != nil {
dnd.finish_drag("EIO")
return nil, err
}
x := remote_data_item{
parent_dir_handle: handle, idx_in_parent: i, metadata: st, idx_in_uri_list: idx_in_uri_list,
path: filepath.Join(path, entry.Name())}
children = append(children, &x)
names = append(names, entry.Name())
}
payload := utils.UnsafeStringToBytes(strings.Join(names, "\x00"))
if len(payload) > 0 {
dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, handle, payload)
}
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, handle, nil)
return
}
func (dnd *dnd) send_remote_symlink(path string, idx_in_uri_list, parent_dir_handle, idx int) (err error) {
target, err := os.Readlink(path)
if err != nil {
dnd.finish_drag("EIO")
return err
}
if len(target) > 0 {
dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, 1, utils.UnsafeStringToBytes(target))
}
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, 1, nil)
return
}
func (dnd *dnd) send_next_file_chunk() (err error) {
cr := dnd.drag_status.current_remote_file
if cr == nil {
return dnd.next_remote_item()
}
n, err := cr.file.Read(read_buf[:])
if n > 0 {
encoded_chunk_sent := false
for chunk := range cr.base64.Encode(read_buf[:n], encode_buf[:]) {
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, chunk)
encoded_chunk_sent = true
}
if !encoded_chunk_sent {
return dnd.send_next_file_chunk()
}
}
if err != nil {
if errors.Is(err, io.EOF) {
cr.file.Close()
dnd.drag_status.current_remote_file = nil
if chunk := cr.base64.Finish(); len(chunk) > 0 {
dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, chunk)
}
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, nil)
return nil
}
dnd.finish_drag("EIO")
return err
}
return
}
func (dnd *dnd) next_remote_item() (err error) {
if len(dnd.drag_status.remote_items) < 1 {
// current remote data request finished
dnd.drag_status.remote_data_requests = dnd.drag_status.remote_data_requests[1:]
if len(dnd.drag_status.remote_data_requests) > 0 {
return dnd.send_next_remote_data_request()
}
if len(dnd.drag_status.data_requests) > 0 {
err = dnd.send_data_for_data_request(0)
}
return
}
x := dnd.drag_status.remote_items[0]
dnd.drag_status.remote_items = dnd.drag_status.remote_items[1:]
if x.metadata.IsDir() {
children, err := dnd.send_remote_dir(x.path, x.idx_in_uri_list, x.parent_dir_handle, x.idx_in_parent)
if err != nil {
return err
}
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, children...)
} else if x.metadata.Mode().Type()&os.ModeSymlink != 0 {
if err = dnd.send_remote_symlink(x.path, x.idx_in_uri_list, x.parent_dir_handle, x.idx_in_parent); err != nil {
return
}
} else {
if x.file, err = os.Open(x.path); err != nil {
dnd.finish_drag("EIO")
return err
}
dnd.drag_status.current_remote_file = x
if err = dnd.send_next_file_chunk(); err != nil {
return err
}
}
return
}
func (dnd *dnd) on_drag_remote_data_request(idx int) (err error) {
ds := dnd.drag_sources["text/uri-list"]
if ds == nil || len(ds.uri_list) < 1 {
dnd.finish_drag("EINVAL")
return fmt.Errorf("terminal asked for drag data from URI list but no list present")
}
if idx < 0 || idx >= len(ds.uri_list) {
dnd.finish_drag("EINVAL")
return fmt.Errorf("terminal asked for drag data from URI list with out of bounds index: %d", idx)
}
ds.uri_list[idx].was_sent = true
dnd.drag_status.remote_data_requests = append(dnd.drag_status.remote_data_requests, idx)
if len(dnd.drag_status.remote_data_requests) == 1 {
err = dnd.send_next_remote_data_request()
}
return
}
func (dnd *dnd) send_next_remote_data_request() (err error) {
if len(dnd.drag_status.remote_data_requests) == 0 {
return nil
}
i := dnd.drag_status.remote_data_requests[0]
x := dnd.drag_sources["text/uri-list"].uri_list[i]
items := []*remote_data_item{}
if x.metadata.IsDir() {
if children, err := dnd.send_remote_dir(x.path, i, 0, i); err != nil {
return err
} else {
items = append(items, children...)
}
} else if x.metadata.Mode().Type()&os.ModeSymlink != 0 {
if err = dnd.send_remote_symlink(x.path, i, 0, i); err != nil {
return err
}
} else {
f := remote_data_item{idx_in_parent: i, idx_in_uri_list: i, metadata: x.metadata, path: x.path}
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, &f)
}
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, items...)
if dnd.drag_status.remote_item_write_id == 0 {
return dnd.next_remote_item()
}
return
}
+1262
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+468
View File
@@ -0,0 +1,468 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package dnd
import (
"bytes"
"errors"
"fmt"
"image"
"io"
"io/fs"
"maps"
"net/url"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync/atomic"
"github.com/kovidgoyal/imaging"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Append
var debugprintln = tty.DebugPrintln
var _ = debugprintln
type uri_list_item struct {
path, uri, human_name string
file *os.File
metadata os.FileInfo
was_sent bool
}
type drag_source struct {
human_name, path string
file *os.File
mime_type string
uri_list []uri_list_item
data []byte
}
type bufferWriteCloser struct {
*bytes.Buffer
}
// Close implements the io.Closer interface (as a no-op)
func (bwc *bufferWriteCloser) Close() error {
return nil
}
type DC = loop.DndCommand
type dir_handle struct {
handle *os.File
refcnt atomic.Int32
}
func new_dir_handle(x *os.File) *dir_handle {
ans := dir_handle{x, atomic.Int32{}}
ans.refcnt.Store(1)
return &ans
}
func (d *dir_handle) newref() *dir_handle {
d.refcnt.Add(1)
return d
}
func (d *dir_handle) unref() *dir_handle {
if d.refcnt.Add(-1) <= 0 {
d.handle.Close()
d.handle = nil
}
return nil
}
type dnd struct {
opts *Options
drop_dests map[string]*drop_dest
drag_sources map[string]*drag_source
initial_drag_sources map[string]*drag_source
drag_thumbnail image.Image
allow_drops, allow_drags bool
lp *loop.Loop
drop_status drop_status
drop_output_dir *os.File
base_tempdir *os.File
tdir_counter int
is_case_sensitive_filesystem bool // false if names differing in case or Unicode normalization are aliases
num_dropped_files int
drag_status drag_status
in_test_mode bool
copy_button_region, move_button_region button_region
confirm_drop struct {
overwrites []string
staging_dir *os.File
}
}
func (dnd *dnd) send_test_response(payload string) {
dnd.lp.DebugPrintln(payload)
}
func (dnd *dnd) has_exit_on(event string) bool {
for e := range strings.SplitSeq(dnd.opts.ExitOn, ",") {
if strings.TrimSpace(e) == event {
return true
}
}
return false
}
func (dnd *dnd) setup_base_dir(base_dir string) (err error) {
if dnd.drop_output_dir != nil {
dnd.drop_output_dir.Close()
}
if dnd.drop_output_dir, err = os.Open(base_dir); err != nil {
return err
}
base_tdir, err := os.MkdirTemp(base_dir, ".dnd-kitten-drop-*")
if err != nil {
return err
}
bf, err := os.Open(base_tdir)
if err != nil {
os.RemoveAll(base_tdir)
return err
}
dnd.base_tempdir = bf
dnd.is_case_sensitive_filesystem = names_are_distinct(base_tdir)
return err
}
// Return true if names that differ only in case or Unicode normalization
// refer to different entries in the empty directory dir. Any failure to
// determine this is treated as them being aliases, which is the safe choice.
func names_are_distinct(dir string) bool {
is_absent := func(path string) bool {
_, err := os.Lstat(path)
return errors.Is(err, fs.ErrNotExist)
}
if !is_absent(filepath.Join(filepath.Dir(dir), strings.ToUpper(filepath.Base(dir)))) {
return false
}
probe := filepath.Join(dir, "\u00e9")
if err := os.WriteFile(probe, nil, 0o600); err != nil {
return false
}
defer os.Remove(probe)
return is_absent(filepath.Join(dir, "e\u0301"))
}
func (dnd *dnd) remove_tdir() error {
path := dnd.base_tempdir.Name()
dnd.base_tempdir.Close()
dnd.base_tempdir = nil
return os.RemoveAll(path)
}
func (dnd *dnd) run_loop() (err error) {
defer func() {
if dnd.in_test_mode && err != nil {
debugprintln("dnd kitten exiting with error: ", err)
}
}()
base_dir := dnd.opts.DropDest
if base_dir == "" {
base_dir, err = os.Getwd()
} else {
base_dir, err = filepath.Abs(base_dir)
}
if err != nil {
return err
}
if err = dnd.setup_base_dir(base_dir); err != nil {
return err
}
defer dnd.remove_tdir()
dnd.allow_drops, dnd.allow_drags = len(dnd.drop_dests) > 0, len(dnd.drag_sources) > 0
dnd.initial_drag_sources = dnd.drag_sources
if dnd.lp, err = loop.New(); err != nil {
return err
}
dnd.lp.MouseTrackingMode(loop.BUTTONS_AND_DRAG_MOUSE_TRACKING)
dnd.reset_drop()
dnd.lp.OnInitialize = func() (string, error) {
dnd.lp.AllowLineWrapping(false)
dnd.lp.SetCursorVisible(false)
if dnd.allow_drops {
dnd.lp.StartAcceptingDrops("", slices.Collect(maps.Keys(dnd.drop_dests))...)
}
if dnd.allow_drags {
dnd.lp.StartOfferingDrags("")
}
dnd.lp.SetWindowTitle("Drag and drop")
return "", dnd.render_screen()
}
dnd.lp.OnFinalize = func() string {
dnd.lp.AllowLineWrapping(true)
dnd.lp.SetCursorVisible(true)
if dnd.allow_drops {
dnd.lp.StopAcceptingDrops()
}
if dnd.allow_drags {
dnd.lp.StopOfferingDrags()
}
return ""
}
dnd.lp.OnWakeup = func() error {
if err := dnd.drop_on_wakeup(); err != nil {
return err
}
return nil
}
dnd.lp.OnDnDData = func(cmd loop.DndCommand) error {
switch cmd.Type {
case 'T':
switch string(cmd.Payload) {
case "PING":
dnd.send_test_response("PONG")
case "SETUP_LOCAL", "SETUP_REMOTE":
dnd.in_test_mode = true
dnd.lp.NoRoundtripToTerminalOnExit()
dnd.drop_status.reset()
dnd.lp.StopAcceptingDrops()
dnd.lp.StopOfferingDrags()
dnd.remove_tdir()
dnd.setup_base_dir(base_dir)
dnd.drag_sources = dnd.initial_drag_sources
dnd.allow_drops, dnd.allow_drags = len(dnd.drop_dests) > 0, len(dnd.drag_sources) > 0
machine_id := ""
if string(cmd.Payload) == "SETUP_REMOTE" {
machine_id = "remote-client-for-test"
}
if dnd.allow_drops {
dnd.lp.StartAcceptingDrops(machine_id, slices.Collect(maps.Keys(dnd.drop_dests))...)
}
if dnd.allow_drags {
dnd.lp.StartOfferingDrags(machine_id)
}
dnd.render_screen()
dnd.send_test_response("SETUP_DONE")
case "GEOMETRY":
dnd.send_test_response(fmt.Sprintf("GEOMETRY:%d:%d:%d:%d:%d:%d:%d:%d", dnd.copy_button_region.left, dnd.copy_button_region.top, dnd.copy_button_region.width, dnd.copy_button_region.height, dnd.move_button_region.left, dnd.move_button_region.top, dnd.move_button_region.width, dnd.move_button_region.height))
case "DROP_MIMES":
if dnd.drop_status.offered_mimes != nil {
dnd.send_test_response(strings.Join(dnd.drop_status.offered_mimes, " "))
} else {
dnd.send_test_response("")
}
case "DROP_IS_REMOTE":
dnd.send_test_response(utils.IfElse(dnd.drop_status.is_remote_client, "True", "False"))
case "DROP_URI_LIST":
paths := make([]string, len(dnd.drop_status.uri_list))
for i, u := range dnd.drop_status.uri_list {
paths[i] = u.path
}
dnd.send_test_response(strings.Join(paths, "|"))
case "DRAG_ACTIVE":
dnd.send_test_response(utils.IfElse(dnd.drag_status.active, "DRAG_ACTIVE", "DRAG_INACTIVE"))
case "DRAG_OK":
dnd.send_test_response(utils.IfElse(dnd.drag_status.terminal_accepted_drag, "DRAG_OK", "DRAG_NOT_OK"))
case "DRAG_STATUS":
dnd.send_test_response(fmt.Sprintf("%s:%d:%v", dnd.drag_status.offered_mimes[dnd.drag_status.accepted_mime], dnd.drag_status.accepted_operation, dnd.drag_status.dropped))
default:
dnd.send_test_response("UNKNOWN TEST COMMAND: " + string(cmd.Payload))
}
// Drops
case 'm':
payload := ""
if cmd.Payload != nil {
payload = utils.UnsafeBytesToString(cmd.Payload)
}
if dnd.on_drop_move(cmd.X, cmd.Y, cmd.Has_more, payload, false, cmd.Operation) {
dnd.render_screen()
}
case 'M':
if dnd.on_drop_move(cmd.X, cmd.Y, cmd.Has_more, utils.UnsafeBytesToString(cmd.Payload), true, cmd.Operation) {
dnd.render_screen()
}
case 'R':
return fmt.Errorf("error from the terminal while reading dropped data: %s", string(cmd.Payload))
case 'r':
return dnd.on_drop_data(cmd)
// Drag source
case 'o':
return dnd.on_potential_drag_start(cmd.X, cmd.Y)
case 'E':
return dnd.on_drag_error(cmd)
case 'e':
return dnd.on_drag_event(cmd.X, cmd.Y, cmd.Operation)
case 'k':
return dnd.on_drag_remote_data_request(cmd.X - 1)
}
return nil
}
dnd.lp.OnWriteComplete = func(msg_id loop.IdType, has_pending_writes bool) (err error) {
return dnd.on_send_done(msg_id)
}
dnd.lp.OnKeyEvent = func(e *loop.KeyEvent) (err error) {
e.Handled = true
if len(dnd.confirm_drop.overwrites) > 0 {
if e.MatchesPressOrRepeat("esc") {
return dnd.drop_confirm(false)
}
if e.MatchesPressOrRepeat("enter") {
return dnd.drop_confirm(true)
}
}
if e.MatchesPressOrRepeat("ctrl+c") {
dnd.lp.Quit(0)
return
}
if e.MatchesPressOrRepeat("esc") && dnd.has_exit_on("esc-key") {
dnd.lp.Quit(0)
return
}
return nil
}
dnd.lp.OnResize = func(old_size loop.ScreenSize, new_size loop.ScreenSize) error {
return dnd.render_screen()
}
err = dnd.lp.Run()
if err != nil {
return
}
ds := dnd.lp.DeathSignalName()
if ds != "" {
fmt.Println("Killed by signal: ", ds)
dnd.lp.KillIfSignalled()
return
}
return
}
func dnd_main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
drop_dests := make(map[string]*drop_dest)
if os.Stdout != nil && !tty.IsTerminal(os.Stdout.Fd()) {
drop_dests["text/plain"] = &drop_dest{human_name: "STDOUT", dest: os.Stdout, mime_type: "text/plain"}
}
drop_dests["text/uri-list"] = &drop_dest{
human_name: "Files", mime_type: "text/uri-list", dest: &bufferWriteCloser{&bytes.Buffer{}}}
for _, spec := range opts.Drop {
mime, dest, _ := strings.Cut(spec, ":")
if dest == "" {
delete(drop_dests, mime)
} else {
path, err := filepath.Abs(utils.Expanduser(dest))
if err != nil {
return 1, err
}
drop_dests[mime] = &drop_dest{human_name: dest, path: path, mime_type: mime}
}
}
drag_sources := make(map[string]*drag_source)
var stdin_data []byte
stdin_read := false
for _, spec := range opts.Drag {
mime, src, found := strings.Cut(spec, ":")
if !found {
return 1, fmt.Errorf("invalid drag source %s, must be of the form mime-type:path", spec)
}
s := &drag_source{human_name: src, mime_type: mime}
if src == "-" || src == "/dev/stdin" {
if !stdin_read {
stdin_data, err = io.ReadAll(os.Stdin)
if err != nil {
return 1, err
}
stdin_read = true
}
s.human_name, s.data = "STDIN", stdin_data
} else {
path, err := filepath.Abs(utils.Expanduser(src))
if err != nil {
return 1, err
}
s.path = path
}
drag_sources[mime] = s
}
if _, has_plain := drag_sources["text/plain"]; os.Stdin != nil && !stdin_read && !has_plain && !tty.IsTerminal(os.Stdin.Fd()) {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return 1, err
}
if len(data) > 0 {
drag_sources["text/plain"] = &drag_source{human_name: "STDIN", mime_type: "text/plain", data: data}
}
}
var uri_list []uri_list_item
for _, arg := range args {
arg = utils.Expanduser(arg)
st, err := os.Lstat(arg)
if err != nil {
return 1, err
}
if st.IsDir() || st.Mode().IsRegular() || st.Mode().Type()&os.ModeSymlink != 0 {
path, err := filepath.Abs(arg)
if err != nil {
return 1, err
}
upath := filepath.ToSlash(path)
if runtime.GOOS == "windows" && !strings.HasPrefix(upath, "/") {
upath = "/" + upath
}
if st.IsDir() && !strings.HasSuffix(upath, "/") {
upath += "/"
}
u := &url.URL{Scheme: "file", Path: upath}
uri_list = append(uri_list, uri_list_item{path: path, uri: u.String(), human_name: arg, metadata: st})
} else {
return 1, fmt.Errorf("%s is not a directory or regular file", arg)
}
}
if len(uri_list) > 0 {
uris := make([]string, len(uri_list))
for i, u := range uri_list {
uris[i] = u.uri
}
payload := strings.Join(uris, "\r\n") + "\r\n"
drag_sources["text/uri-list"] = &drag_source{
human_name: "Files", mime_type: "text/uri-list", uri_list: uri_list, data: utils.UnsafeStringToBytes(payload),
}
}
dnd := dnd{opts: opts, drop_dests: drop_dests, drag_sources: drag_sources}
if opts.DragThumbnail != "" {
if dnd.drag_thumbnail, err = imaging.Open(opts.DragThumbnail); err != nil {
return 1, err
}
}
defer func() {
dnd.end_drop(false)
if dnd.confirm_drop.staging_dir != nil {
dnd.confirm_drop.staging_dir.Close()
dnd.confirm_drop.staging_dir = nil
}
if dnd.drop_output_dir != nil {
dnd.drop_output_dir.Close()
}
}()
if err = dnd.run_loop(); err != nil {
return 1, err
}
return 0, nil
}
func EntryPoint(parent *cli.Command) {
create_cmd(parent, dnd_main)
}
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys
OPTIONS = r"""
--drag
type=list
When starting a drag, use the specified file as the data source for the specified
MIME type. Syntax is: mime-type:path/to/file. For example image/jpeg:mypic.jpg
Can be specified multiple times to drag multiple MIME types.
Use :code:`-` or :file:`/dev/stdin` to read from STDIN. The same input can be used for multiple MIME types.
--drop
type=list
When receiving a drop, use the specified file as the data destination for the specified
MIME type. Syntax is: mime-type:path/to/file. For example image/jpeg:mypic.jpg
Can be specified multiple times to enable receiving multiple MIME types. If no path is specified,
it will prevent that MIME type being dropped, useful to disable accepting text/plain and
text/uri-list.
--drop-dest
Path to the directory in which dropped data is saved. Defaults to the current working directory.
--copy-mode
type=choices
choices=auto,independent
default=auto
Control how local files are handled for Copy drops. The default, :code:`auto`, uses hard links
when possible for performance and falls back to copying file data. :code:`independent` always
copies file data, so modifying a dropped file cannot modify its source. Move drops always use
hard links when possible.
--confirm-drop-overwrite
type=bool-set
Ask for confirmation when dropping text/uri-list data if the drop will cause any existing
files to be overwritten. Note that confirmation is asked only for actual file conflicts, non
conflicting files are automatically created.
--drop-anywhere
choices=disallowed,copy,move
default=disallowed
type=choices
Allow dropping anywhere, not just on the Copy or Move drop regions. Dropping anywhere will perform
the specified action.
--drag-thumbnail
Path to an image to use as the drag icon when starting a drag. Must be in PNG/JPEG/GIF/WEBP formats.
Other formats will require the presence of ImageMagick on the system to load the image.
If not specified, an image is derived based on the data being dragged.
--drag-thumbnail-size
default=512
type=int
The thumbnail size for the image used as the drag icon. Images larger than this size are downscaled.
Note that the terminal may reject the drag if the image is too large.
--exit-on
default=esc-key
A comma separated list of events to exit on. Possible events are :code:`drag-finish`,
:code:`drop-finish` and :code:`esc-key`. The first two events refer to a successful
completion of a drag or a drop respectively. :code:`esc-key` means press the :kbd:`Esc`
key.
""".format
help_text = """\
Perform drag and drop operations, even over SSH.
Any arguments on the command line are assumed to be files and directories to drag.
They will be dragged as the text/uri-list MIME type which can then be dropped into any
file manager or similar program to copy the files.
If the text/uri-list MIME type is dropped onto this window, the files and directories in it are
copied into the current working directory. When dragging from this window, if a move operation is
performed when dropping and the drop is to a remote machine, the files and directories to drag and deleted.
If data is present on STDIN it is set as text/plain when dragging, unless STDIN is used explicitly via --drag or text/plain is specified via --drag.
Any text/plain data that is dropped onto this window is output to STDOUT, if STDOUT is connected to a file, otherwise it
is discarded.
Press the Esc or Ctrl+C keys to quit the kitten at any time, cancelling any in progress drag.
"""
usage = '[files to drag]'
if __name__ == '__main__':
raise SystemExit('This should be run as kitten dnd')
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'] = 'Perform drag and drop operations, even over SSH'
cd['args_completion'] = CompletionSpec.from_string('type:file mime:* group:Files')
+182
View File
@@ -0,0 +1,182 @@
package dnd
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type button_region struct {
left, width, top, height int
}
func (r button_region) has(x, y int) bool {
return r.left <= x && x < r.left+r.width && r.top <= y && y < r.top+r.height
}
func truncate_at_space(text string, width int) (string, string) {
truncated := wcswidth.TruncateToVisualLength(text, width)
if len(truncated) == len(text) {
return text, ""
}
p := len(truncated)
i := strings.LastIndexByte(truncated, ' ')
if i > 0 && p-i < 12 {
p = i + 1
}
return text[:p], text[p:]
}
func paragraph_as_lines(text string, width int) (ans []string) {
for text != "" {
var line string
if line, text = truncate_at_space(text, width); line == "" {
// width too small to fit even a single character
ans = append(ans, text)
break
}
ans = append(ans, line)
}
return
}
func (dnd *dnd) render_screen() error {
lp := dnd.lp
if !dnd.in_test_mode {
lp.StartAtomicUpdate()
defer lp.EndAtomicUpdate()
}
lp.ClearScreen()
dnd.copy_button_region, dnd.move_button_region = button_region{}, button_region{}
y := 0
sz, _ := lp.ScreenSize()
render_paragraph := func(text string) {
for _, line := range paragraph_as_lines(text, int(sz.WidthCells)) {
lp.Println(line)
y++
}
}
next_line := func() {
lp.Println()
y++
}
if dnd.drag_status.active {
lp.Println("Dragging data...")
if dnd.drag_status.dropped {
render_paragraph("The dragged data has been dropped, waiting for data transfer requests...")
} else if dnd.drag_status.accepted_operation > 0 {
render_paragraph("Another window is willing to accept the dragged data")
}
return nil
}
if len(dnd.confirm_drop.overwrites) > 0 {
render_paragraph("Some of the dropped files will overwrite existing files, listed below. Press \x1b[32mEnter\x1b[39m to drop anyway or \x1b[31mEsc\x1b[39m to cancel the drop.")
sz, _ := lp.ScreenSize()
next_line()
next_line()
overwrites := dnd.confirm_drop.overwrites[:max(0, min(int(sz.HeightCells)-y-1, len(dnd.confirm_drop.overwrites)))]
for _, x := range overwrites {
lp.Println(x)
}
if left := len(dnd.confirm_drop.overwrites) - len(overwrites); left > 0 {
lp.Printf("... (%d more)", left)
}
return nil
}
if dnd.drop_status.reading_data {
render_paragraph("Reading dropped data, please wait...")
return nil
}
if dnd.drop_status.in_window {
if dnd.drop_status.action == 0 {
render_paragraph("A drag is active. Drop it into one of the boxes below to perform that action on the dragged data. Available MIME types in the drag:")
next_line()
render_paragraph(strings.Join(dnd.drop_status.offered_mimes, " "))
} else {
render_paragraph("The drag can be dropped. Supported MIME types:")
next_line()
render_paragraph(strings.Join(dnd.drop_status.accepted_mimes, " "))
}
} else {
// Neither active drag nor drop over window
if dnd.allow_drags {
render_paragraph(`Start dragging anywhere in this window to initiate a drag and drop. If you start the drag in one of the Copy or Move boxes below, only that action will be allowed when dropping, otherwise, the drop destination can pick either copy or move.`)
next_line()
}
if dnd.allow_drops {
if dnd.num_dropped_files > 0 {
verb := "have"
noun := "files"
if dnd.num_dropped_files == 1 {
verb = "has"
noun = "file"
}
render_paragraph(fmt.Sprintf(`%d %s %s been dropped in the last drop event. You can drop more data or press Esc to quit.`, dnd.num_dropped_files, noun, verb))
} else {
render_paragraph(`Drag some data from another application into this window to transfer the files here.`)
}
}
}
frame_width, padding_width := 4, 8
text_width := len("copymove")
scale := 5
for scale > 1 && frame_width+padding_width+text_width*scale > int(sz.WidthCells) {
scale--
}
height := scale + 4
boxy := 1 + max(0, int(sz.HeightCells)-height)
lp.MoveCursorTo(1, boxy)
lp.ClearToEndOfScreen()
render_box := func(x int, text string, r *button_region) {
width := scale*wcswidth.Stringwidth(text) + 6
r.left = x - 1
r.top = boxy - 1
r.width = width
r.height = height
lp.MoveCursorTo(x, boxy)
for i := range height {
lp.SaveCursorPosition()
switch i {
case 0:
lp.QueueWriteString("╭")
lp.QueueWriteString(strings.Repeat("─", width-2))
lp.QueueWriteString("╮")
case height - 1:
lp.QueueWriteString("╰")
lp.QueueWriteString(strings.Repeat("─", width-2))
lp.QueueWriteString("╯")
default:
lp.QueueWriteString("│")
if i == 2 {
lp.MoveCursorHorizontally(2)
lp.DrawSizedText(text, loop.SizedText{Scale: scale})
}
lp.MoveCursorTo(x+width-1, boxy+i)
lp.QueueWriteString("│")
}
lp.RestoreCursorPosition()
lp.MoveCursorVertically(1)
}
}
const fg = 32
if dnd.drop_status.action == copy_on_drop {
lp.Printf("\x1b[%dm", fg)
}
render_box(1, "Copy", &dnd.copy_button_region)
lp.QueueWriteString("\x1b[39m")
box_width := 6 + len("move")*scale
if dnd.drop_status.action == move_on_drop {
lp.Printf("\x1b[%dm", fg)
}
render_box(1+int(sz.WidthCells)-box_width, "Move", &dnd.move_button_region)
lp.QueueWriteString("\x1b[39m")
return nil
}