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

+39
View File
@@ -0,0 +1,39 @@
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func complete_actions(completions *cli.Completions, word string, arg_num int) {
if arg_num < 2 {
scanner := utils.NewLineScanner(KittyActionNames)
mg := completions.AddMatchGroup("Actions")
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" && strings.HasPrefix(line, word) {
mg.AddMatch(line)
}
}
}
}
func complete_kitty_override(completions *cli.Completions, word string, arg_num int) {
mg := completions.AddMatchGroup("Config directives")
mg.NoTrailingSpace = true
scanner := utils.NewLineScanner(kitty.OptionNames)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, word) {
mg.AddMatch(line + "=")
}
}
}
+20
View File
@@ -0,0 +1,20 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"strings"
)
func parse_key_val_args(args []string) map[escaped_string]escaped_string {
ans := make(map[escaped_string]escaped_string, len(args))
for _, arg := range args {
key, value, found := strings.Cut(arg, "=")
if found {
ans[escaped_string(key)] = escaped_string(value)
} else {
ans[escaped_string(key+"=")] = ""
}
}
return ans
}
+17
View File
@@ -0,0 +1,17 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"os"
)
var _ = fmt.Print
func copy_local_env(copy_env bool) []string {
if copy_env {
return os.Environ()
}
return nil
}
+425
View File
@@ -0,0 +1,425 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"unicode/utf16"
"golang.org/x/sys/unix"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/crypto"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/base85"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
const lowerhex = "0123456789abcdef"
var ProtocolVersion [3]int = [3]int{0, 26, 0}
type password struct {
val string
is_set bool
}
type GlobalOptions struct {
to_network, to_address string
password password
to_address_is_from_env_var bool
already_setup bool
}
var global_options GlobalOptions
func expand_ansi_c_escapes_in_args(args ...string) (escaped_string, error) {
for i, x := range args {
args[i] = shlex.ExpandANSICEscapes(x)
}
return escaped_string(strings.Join(args, " ")), nil
}
func escape_list_of_strings(args []string) []escaped_string {
ans := make([]escaped_string, len(args))
for i, x := range args {
ans[i] = escaped_string(x)
}
return ans
}
func set_payload_string_field(io_data *rc_io_data, field, data string) {
payload_interface := reflect.ValueOf(&io_data.rc.Payload).Elem()
struct_in_interface := reflect.New(payload_interface.Elem().Type()).Elem()
struct_in_interface.Set(payload_interface.Elem()) // copies the payload to struct_in_interface
struct_in_interface.FieldByName(field).SetString(data)
payload_interface.Set(struct_in_interface) // copies struct_in_interface back to payload
}
func get_pubkey(encoded_key string) (encryption_version string, pubkey []byte, err error) {
if encoded_key == "" {
encoded_key = os.Getenv("KITTY_PUBLIC_KEY")
if encoded_key == "" {
err = fmt.Errorf("Password usage requested but KITTY_PUBLIC_KEY environment variable is not available")
return
}
}
encryption_version, encoded_key, found := strings.Cut(encoded_key, ":")
if !found {
err = fmt.Errorf("KITTY_PUBLIC_KEY environment variable does not have a : in it")
return
}
if encryption_version != kitty.RC_ENCRYPTION_PROTOCOL_VERSION {
err = fmt.Errorf("KITTY_PUBLIC_KEY has unknown version, if you are running on a remote system, update kitty on this system")
return
}
pubkey = make([]byte, base85.DecodedLen(len(encoded_key)))
n, err := base85.Decode(pubkey, []byte(encoded_key))
if err == nil {
pubkey = pubkey[:n]
}
return
}
type escaped_string string
func (s escaped_string) MarshalJSON() ([]byte, error) {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
// we additionally escape all non-ascii chars so they can be safely transmitted inside an escape code
src := utf16.Encode([]rune(s))
buf := make([]byte, 0, len(src)+128)
a := func(x ...byte) {
buf = append(buf, x...)
}
a('"')
for _, r := range src {
if ' ' <= r && r <= 126 {
if r == '\\' || r == '"' {
buf = append(buf, '\\')
}
buf = append(buf, byte(r))
continue
}
switch r {
case '\n':
a('\\', 'n')
case '\t':
a('\\', 't')
case '\r':
a('\\', 'r')
case '\f':
a('\\', 'f')
case '\b':
a('\\', 'b')
default:
a('\\', 'u')
for s := 12; s >= 0; s -= 4 {
a(lowerhex[r>>uint(s)&0xF])
}
}
}
a('"')
return buf, nil
}
func simple_serializer(rc *utils.RemoteControlCmd) (ans []byte, err error) {
return json.Marshal(rc)
}
type serializer_func func(rc *utils.RemoteControlCmd) ([]byte, error)
func create_serializer(password password, encoded_pubkey string, io_data *rc_io_data) (err error) {
io_data.serializer = simple_serializer
if password.is_set {
encryption_version, pubkey, err := get_pubkey(encoded_pubkey)
if err != nil {
return err
}
io_data.serializer = func(rc *utils.RemoteControlCmd) (ans []byte, err error) {
ec, err := crypto.Encrypt_cmd(rc, global_options.password.val, pubkey, encryption_version)
if err != nil {
return
}
return json.Marshal(ec)
}
if io_data.timeout < 120*time.Second {
io_data.timeout = 120 * time.Second
}
}
return nil
}
type ResponseData struct {
as_str string
is_string bool
}
func (self *ResponseData) UnmarshalJSON(data []byte) error {
if bytes.HasPrefix(data, []byte("\"")) {
self.is_string = true
return json.Unmarshal(data, &self.as_str)
}
if bytes.Equal(data, []byte("true")) {
self.as_str = "True"
} else if bytes.Equal(data, []byte("false")) {
self.as_str = "False"
} else {
self.as_str = string(data)
}
return nil
}
type Response struct {
Ok bool `json:"ok"`
Data ResponseData `json:"data"`
Error string `json:"error,omitempty"`
Traceback string `json:"tb,omitempty"`
}
type rc_io_data struct {
cmd *cli.Command
rc *utils.RemoteControlCmd
serializer serializer_func
on_key_event func(lp *loop.Loop, ke *loop.KeyEvent) error
string_response_is_err bool
handle_response func(data []byte) error
timeout time.Duration
multiple_payload_generator func(io_data *rc_io_data) (bool, error)
chunks_done bool
}
func (self *rc_io_data) next_chunk() (chunk []byte, err error) {
if self.chunks_done {
return make([]byte, 0), nil
}
if self.multiple_payload_generator != nil {
is_last, err := self.multiple_payload_generator(self)
if err != nil {
return nil, err
}
if is_last {
self.chunks_done = true
}
return self.serializer(self.rc)
}
self.chunks_done = true
return self.serializer(self.rc)
}
func get_response(do_io func(io_data *rc_io_data) ([]byte, error), io_data *rc_io_data) (ans *Response, err error) {
serialized_response, err := do_io(io_data)
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) && io_data.rc.Async != "" {
io_data.rc.Payload = nil
io_data.rc.CancelAsync = true
io_data.multiple_payload_generator = nil
io_data.rc.NoResponse = true
io_data.chunks_done = false
_, _ = do_io(io_data)
err = fmt.Errorf("Timed out waiting for a response from kitty")
}
return nil, err
}
if len(serialized_response) == 0 {
if io_data.rc.NoResponse {
res := Response{Ok: true}
ans = &res
return
}
err = fmt.Errorf("Received empty response from kitty")
return
}
var response Response
err = json.Unmarshal(serialized_response, &response)
if err != nil {
err = fmt.Errorf("Invalid response received from kitty, unmarshalling error: %w", err)
return
}
ans = &response
return
}
var running_shell = false
type exit_error struct {
exit_code int
}
func (m *exit_error) Error() string {
return fmt.Sprintf("Subprocess exit with code: %d", m.exit_code)
}
func send_rc_command(io_data *rc_io_data) (err error) {
err = setup_global_options(io_data.cmd)
if err != nil {
return err
}
wid, err := strconv.Atoi(os.Getenv("KITTY_WINDOW_ID"))
if err == nil && wid > 0 {
io_data.rc.KittyWindowId = uint(wid)
}
err = create_serializer(global_options.password, "", io_data)
if err != nil {
return
}
var response *Response
response, err = get_response(utils.IfElse(global_options.to_network == "", do_tty_io, do_socket_io), io_data)
if err != nil || response == nil {
return
}
if !response.Ok {
if response.Traceback != "" {
fmt.Fprintln(os.Stderr, response.Traceback)
}
return fmt.Errorf("%s", response.Error)
}
if io_data.handle_response != nil {
return io_data.handle_response(utils.UnsafeStringToBytes(response.Data.as_str))
}
if response.Data.is_string && io_data.string_response_is_err {
return fmt.Errorf("%s", response.Data.as_str)
}
if response.Data.as_str != "" {
fmt.Println(strings.TrimRight(response.Data.as_str, "\n \t"))
}
return
}
func get_password(password string, password_file string, password_env string, use_password string) (ans password, err error) {
if use_password == "never" {
return
}
if password != "" {
ans.is_set, ans.val = true, password
}
if !ans.is_set && password_file != "" {
if password_file == "-" {
if tty.IsTerminal(os.Stdin.Fd()) {
p, err := tui.ReadPassword("Password: ", true)
if err != nil {
return ans, err
}
ans.is_set, ans.val = true, p
} else {
var q []byte
q, err = io.ReadAll(os.Stdin)
if err == nil {
ans.is_set, ans.val = true, strings.TrimRight(string(q), " \n\t")
}
ttyf, err := os.Open(tty.Ctermid())
if err == nil {
err = unix.Dup2(int(ttyf.Fd()), int(os.Stdin.Fd())) //nolint ineffassign err is returned indicating duping failed
ttyf.Close()
}
}
} else if strings.HasPrefix(password_file, "fd:") {
var fd int
if fd, err = strconv.Atoi(password_file[3:]); err == nil {
f := os.NewFile(uintptr(fd), password_file)
var q []byte
if q, err = io.ReadAll(f); err == nil {
ans.is_set = true
ans.val = string(q)
}
f.Close()
}
} else {
var q []byte
if !filepath.IsAbs(password_file) {
password_file = filepath.Join(utils.ConfigDir(), password_file)
}
q, err = os.ReadFile(password_file)
if err == nil {
ans.is_set, ans.val = true, strings.TrimRight(string(q), " \n\t")
} else {
if errors.Is(err, os.ErrNotExist) {
err = nil
}
}
}
if err != nil {
return
}
}
if !ans.is_set && password_env != "" {
ans.val, ans.is_set = os.LookupEnv(password_env)
}
if !ans.is_set && use_password == "always" {
ans.is_set = true
return ans, nil
}
if len(ans.val) > 1024 {
return ans, fmt.Errorf("Specified password is too long")
}
return ans, nil
}
var all_commands []func(*cli.Command) *cli.Command = make([]func(*cli.Command) *cli.Command, 0, 64)
func register_at_cmd(f func(*cli.Command) *cli.Command) {
all_commands = append(all_commands, f)
}
func setup_global_options(cmd *cli.Command) (err error) {
if global_options.already_setup {
return nil
}
err = cmd.GetOptionValues(&rc_global_opts)
if err != nil {
return err
}
if rc_global_opts.To == "" {
rc_global_opts.To = os.Getenv("KITTY_LISTEN_ON")
global_options.to_address_is_from_env_var = true
}
if rc_global_opts.To != "" {
network, address, err := utils.ParseSocketAddress(rc_global_opts.To)
if err != nil {
return err
}
global_options.to_network = network
global_options.to_address = address
}
q, err := get_password(rc_global_opts.Password, rc_global_opts.PasswordFile, rc_global_opts.PasswordEnv, rc_global_opts.UsePassword)
global_options.password = q
global_options.already_setup = true
return err
}
func EntryPoint(tool_root *cli.Command) *cli.Command {
at_root_command := tool_root.AddSubCommand(&cli.Command{
Name: "@",
Usage: "[global options] [sub-command] [sub-command options] [sub-command args]",
ShortDescription: "Control kitty remotely",
HelpText: "Control kitty by sending it commands. Set the allow_remote_control option in :file:`kitty.conf` for this to work. When run without any sub-commands this will start an interactive shell to control kitty.",
Run: shell_main,
})
add_rc_global_opts(at_root_command)
global_options_group := at_root_command.OptionGroups[0]
for _, reg_func := range all_commands {
c := reg_func(at_root_command)
clone := tool_root.AddClone("", c)
clone.Name = "@" + c.Name
clone.Hidden = true
clone.OptionGroups = append(clone.OptionGroups, global_options_group.Clone(clone))
}
return at_root_command
}
+104
View File
@@ -0,0 +1,104 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"encoding/json"
"fmt"
"github.com/kovidgoyal/kitty/tools/crypto"
"github.com/kovidgoyal/kitty/tools/utils"
"testing"
)
func TestEncodeJSON(t *testing.T) {
tests := map[string]string{
"a b\nc\td\a": `a b\nc\td\u0007`,
"•": `\u2022`,
`a"b\c`: `a\"b\\c`,
"\U0001f123": `\ud83c\udd23`,
}
var s escaped_string
for x, expected := range tests {
s = escaped_string(x)
expected = `"` + expected + `"`
actualb, _ := s.MarshalJSON()
actual := string(actualb)
if expected != actual {
t.Fatalf("Failed for %#v\n%#v != %#v", x, expected, actual)
}
}
}
func TestCommandToJSON(t *testing.T) {
pv := fmt.Sprint(ProtocolVersion[0], ",", ProtocolVersion[1], ",", ProtocolVersion[2])
rc, err := create_rc_ls([]string{})
if err != nil {
t.Fatal(err)
}
marshal := func(rc *utils.RemoteControlCmd) string {
q, err := json.Marshal(rc)
if err != nil {
t.Fatal(err)
}
return string(q)
}
test := func(rc *utils.RemoteControlCmd, rest string) {
q := marshal(rc)
expected := `{"cmd":"` + rc.Cmd + `","version":[` + pv + `]`
expected += rest + "}"
if q != expected {
t.Fatalf("expected != actual: %#v != %#v", expected, q)
}
}
test(rc, "")
}
func TestRCSerialization(t *testing.T) {
io_data := rc_io_data{}
err := create_serializer(password{"", false}, "", &io_data)
if err != nil {
t.Fatal(err)
}
var ver = [3]int{1, 2, 3}
rc := utils.RemoteControlCmd{
Cmd: "test", Version: ver,
}
simple := func(expected string) {
actual, err := io_data.serializer(&rc)
if err != nil {
t.Fatal(err)
}
as := string(actual)
if as != expected {
t.Fatalf("Incorrect serialization: %s != %s", expected, as)
}
}
simple(string(`{"cmd":"test","version":[1,2,3]}`))
pubkey_b, _, err := crypto.KeyPair("1")
if err != nil {
t.Fatal(err)
}
pubkey, err := crypto.EncodePublicKey(pubkey_b, "1")
if err != nil {
t.Fatal(err)
}
err = create_serializer(password{"tpw", true}, pubkey, &io_data)
if err != nil {
t.Fatal(err)
}
raw, err := io_data.serializer(&rc)
if err != nil {
t.Fatal(err)
}
var ec utils.EncryptedRemoteControlCmd
err = json.Unmarshal([]byte(raw), &ec)
if err != nil {
t.Fatal(err)
}
if ec.Version != ver {
t.Fatal("Incorrect version in encrypted command: ", ec.Version)
}
}
+81
View File
@@ -0,0 +1,81 @@
package at
import (
"encoding/json"
"fmt"
"io"
"os"
"github.com/emmansun/base64"
"github.com/kovidgoyal/kitty/tools/tty"
)
var _ = fmt.Print
type run_response_data struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Exit_code int `json:"exit_code"`
Exit_status int `json:"exit_status"`
}
func run_handle_response(data []byte) error {
var r run_response_data
if err := json.Unmarshal(data, &r); err != nil {
return err
}
if stdout, err := base64.StdEncoding.DecodeString(r.Stdout); err == nil {
_, _ = os.Stdout.Write(stdout)
} else {
return err
}
if stderr, err := base64.StdEncoding.DecodeString(r.Stderr); err == nil {
_, _ = os.Stderr.Write(stderr)
} else {
return err
}
if r.Exit_code != 0 {
return &exit_error{r.Exit_code}
}
return nil
}
func read_run_data(io_data *rc_io_data, args []string, payload *run_json_type) (func(io_data *rc_io_data) (bool, error), error) {
is_first_call := true
is_tty := tty.IsTerminal(os.Stdin.Fd())
buf := make([]byte, 4096)
cmdline := make([]escaped_string, len(args))
for i, s := range args {
cmdline[i] = escaped_string(s)
}
payload.Cmdline = cmdline
io_data.handle_response = run_handle_response
return func(io_data *rc_io_data) (bool, error) {
if is_first_call {
is_first_call = false
} else {
io_data.rc.Stream = false
}
buf = buf[:cap(buf)]
var n int
var err error
if is_tty {
buf = buf[:0]
err = io.EOF
} else {
n, err = os.Stdin.Read(buf)
if err != nil && err != io.EOF {
return false, err
}
buf = buf[:n]
}
set_payload_data(io_data, base64.StdEncoding.EncodeToString(buf))
if err == io.EOF {
return true, nil
}
return false, nil
}, nil
}
+45
View File
@@ -0,0 +1,45 @@
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"os"
"path/filepath"
"github.com/emmansun/base64"
"github.com/kovidgoyal/kitty/tools/utils"
)
func screenshot_handle_response(data []byte) error {
png_data, err := base64.StdEncoding.DecodeString(string(data))
if err != nil {
return err
}
_, err = os.Stdout.Write(png_data)
return err
}
func read_screenshot_args(io_data *rc_io_data, args []string) (func(io_data *rc_io_data) (bool, error), error) {
if len(args) > 1 {
return nil, fmt.Errorf("%s", "Must specify at most one output file")
}
if len(args) == 0 {
// kitty writes the screenshot directly to the output file when one is
// given (it runs on the same computer as kitty), so a custom response
// handler is only needed to write the PNG data to STDOUT.
io_data.handle_response = screenshot_handle_response
}
return func(io_data *rc_io_data) (bool, error) {
// io_data.rc.Payload is only populated after this generator is created,
// so the payload field must be set here rather than above.
if len(args) == 1 {
path, err := filepath.Abs(utils.Expanduser(args[0]))
if err != nil {
return false, fmt.Errorf("%s is not a valid path with error: %w", args[0], err)
}
set_payload_string_field(io_data, "Output_path", path)
}
return true, nil
}, nil
}
+43
View File
@@ -0,0 +1,43 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"strconv"
"strings"
)
func parse_scroll_amount(amt string) ([]any, error) {
var ans = make([]any, 2)
if amt == "start" || amt == "end" {
ans[0] = amt
ans[1] = nil
} else {
pages := strings.Contains(amt, "p")
unscroll := strings.Contains(amt, "u")
prompt := strings.Contains(amt, "r")
var mult float64 = 1
if strings.HasSuffix(amt, "-") && !unscroll {
mult = -1
}
q, err := strconv.ParseFloat(strings.TrimRight(amt, "+-plur"), 64)
if err != nil {
return ans, err
}
if (unscroll || prompt) && q != float64(int(q)) {
return ans, fmt.Errorf("The number must be an integer")
}
ans[0] = q * mult
if pages {
ans[1] = "p"
} else if unscroll {
ans[1] = "u"
} else if prompt {
ans[1] = "r"
} else {
ans[1] = "l"
}
}
return ans, nil
}
+110
View File
@@ -0,0 +1,110 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"errors"
"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"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
var end_reading_from_stdin = errors.New("end reading from STDIN")
var waiting_on_stdin = errors.New("wait for key events from STDIN")
func make_file_gen(f *os.File) func(*rc_io_data) (bool, error) {
chunk := make([]byte, 2048)
file_gen := func(io_data *rc_io_data) (bool, error) {
n, err := f.Read(chunk)
if err != nil && !errors.Is(err, io.EOF) {
return false, err
}
set_payload_data(io_data, "base64:"+base64.StdEncoding.EncodeToString(chunk[:n]))
return n == 0 || errors.Is(err, io.EOF), nil
}
return file_gen
}
func parse_send_text(io_data *rc_io_data, args []string) error {
generators := make([]func(io_data *rc_io_data) (bool, error), 0, 1)
if len(args) > 0 {
for i, arg := range args {
args[i] = shlex.ExpandANSICEscapes(arg)
}
text := strings.Join(args, " ")
text_gen := func(io_data *rc_io_data) (bool, error) {
limit := min(len(text), 2048)
set_payload_data(io_data, "base64:"+base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text[:limit])))
text = text[limit:]
return len(text) == 0, nil
}
generators = append(generators, text_gen)
}
if options_send_text.FromFile != "" {
f, err := os.Open(options_send_text.FromFile)
if err != nil {
return err
}
generators = append(generators, make_file_gen(f))
}
if options_send_text.Stdin {
if tty.IsTerminal(os.Stdin.Fd()) {
pending_key_events := make([]string, 0, 1)
io_data.on_key_event = func(lp *loop.Loop, ke *loop.KeyEvent) error {
ke.Handled = true
if ke.MatchesPressOrRepeat("ctrl+d") {
return end_reading_from_stdin
}
bs := "kitty-key:" + base64.StdEncoding.EncodeToString([]byte(ke.AsCSI()))
pending_key_events = append(pending_key_events, bs)
if ke.Text != "" {
lp.QueueWriteString(ke.Text)
} else if ke.MatchesPressOrRepeat("backspace") {
lp.QueueWriteString("\x08\x1b[P")
}
return nil
}
key_gen := func(io_data *rc_io_data) (bool, error) {
if len(pending_key_events) > 0 {
payload := io_data.rc.Payload.(send_text_json_type)
payload.Exclude_active = true
io_data.rc.Payload = payload
set_payload_data(io_data, pending_key_events[0])
pending_key_events = pending_key_events[1:]
return false, nil
}
return false, waiting_on_stdin
}
generators = append(generators, key_gen)
} else {
generators = append(generators, make_file_gen(os.Stdin))
}
}
io_data.multiple_payload_generator = func(io_data *rc_io_data) (bool, error) {
if len(generators) == 0 {
set_payload_data(io_data, "text:")
return true, nil
}
finished, err := generators[0](io_data)
if finished {
generators = generators[1:]
finished = len(generators) == 0
}
return finished, err
}
return nil
}
+17
View File
@@ -0,0 +1,17 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"math"
"strconv"
)
func parse_opacity(arg string) (float64, error) {
ans, err := strconv.ParseFloat(arg, 64)
if err != nil || math.IsNaN(ans) {
return 0, fmt.Errorf("Invalid opacity %#v: must be a number between 0 and 1", arg)
}
return max(0, min(ans, 1)), nil
}
@@ -0,0 +1,27 @@
// License: GPLv3 Copyright: 2026, kitty contributors
package at
import (
"testing"
)
func TestParseOpacity(t *testing.T) {
valid := map[string]float64{
"0.5": 0.5, "0": 0, "1": 1, "2": 1, "-1": 0, "inf": 1, "-inf": 0,
}
for arg, expected := range valid {
actual, err := parse_opacity(arg)
if err != nil {
t.Fatalf("parse_opacity(%#v) failed with error: %s", arg, err)
}
if actual != expected {
t.Fatalf("parse_opacity(%#v) = %v != %v", arg, actual, expected)
}
}
for _, arg := range []string{"oops", "", "nan", "NaN", "0.5x"} {
if actual, err := parse_opacity(arg); err == nil {
t.Fatalf("parse_opacity(%#v) accepted an invalid number and returned: %v", arg, actual)
}
}
}
+390
View File
@@ -0,0 +1,390 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/themes"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
)
var nullable_colors = map[string]bool{
// generated by gen-config.py do not edit
// NULLABLE_COLORS_START
"active_border_color": true,
"color100": true,
"color101": true,
"color102": true,
"color103": true,
"color104": true,
"color105": true,
"color106": true,
"color107": true,
"color108": true,
"color109": true,
"color110": true,
"color111": true,
"color112": true,
"color113": true,
"color114": true,
"color115": true,
"color116": true,
"color117": true,
"color118": true,
"color119": true,
"color120": true,
"color121": true,
"color122": true,
"color123": true,
"color124": true,
"color125": true,
"color126": true,
"color127": true,
"color128": true,
"color129": true,
"color130": true,
"color131": true,
"color132": true,
"color133": true,
"color134": true,
"color135": true,
"color136": true,
"color137": true,
"color138": true,
"color139": true,
"color140": true,
"color141": true,
"color142": true,
"color143": true,
"color144": true,
"color145": true,
"color146": true,
"color147": true,
"color148": true,
"color149": true,
"color150": true,
"color151": true,
"color152": true,
"color153": true,
"color154": true,
"color155": true,
"color156": true,
"color157": true,
"color158": true,
"color159": true,
"color16": true,
"color160": true,
"color161": true,
"color162": true,
"color163": true,
"color164": true,
"color165": true,
"color166": true,
"color167": true,
"color168": true,
"color169": true,
"color17": true,
"color170": true,
"color171": true,
"color172": true,
"color173": true,
"color174": true,
"color175": true,
"color176": true,
"color177": true,
"color178": true,
"color179": true,
"color18": true,
"color180": true,
"color181": true,
"color182": true,
"color183": true,
"color184": true,
"color185": true,
"color186": true,
"color187": true,
"color188": true,
"color189": true,
"color19": true,
"color190": true,
"color191": true,
"color192": true,
"color193": true,
"color194": true,
"color195": true,
"color196": true,
"color197": true,
"color198": true,
"color199": true,
"color20": true,
"color200": true,
"color201": true,
"color202": true,
"color203": true,
"color204": true,
"color205": true,
"color206": true,
"color207": true,
"color208": true,
"color209": true,
"color21": true,
"color210": true,
"color211": true,
"color212": true,
"color213": true,
"color214": true,
"color215": true,
"color216": true,
"color217": true,
"color218": true,
"color219": true,
"color22": true,
"color220": true,
"color221": true,
"color222": true,
"color223": true,
"color224": true,
"color225": true,
"color226": true,
"color227": true,
"color228": true,
"color229": true,
"color23": true,
"color230": true,
"color231": true,
"color232": true,
"color233": true,
"color234": true,
"color235": true,
"color236": true,
"color237": true,
"color238": true,
"color239": true,
"color24": true,
"color240": true,
"color241": true,
"color242": true,
"color243": true,
"color244": true,
"color245": true,
"color246": true,
"color247": true,
"color248": true,
"color249": true,
"color25": true,
"color250": true,
"color251": true,
"color252": true,
"color253": true,
"color254": true,
"color255": true,
"color26": true,
"color27": true,
"color28": true,
"color29": true,
"color30": true,
"color31": true,
"color32": true,
"color33": true,
"color34": true,
"color35": true,
"color36": true,
"color37": true,
"color38": true,
"color39": true,
"color40": true,
"color41": true,
"color42": true,
"color43": true,
"color44": true,
"color45": true,
"color46": true,
"color47": true,
"color48": true,
"color49": true,
"color50": true,
"color51": true,
"color52": true,
"color53": true,
"color54": true,
"color55": true,
"color56": true,
"color57": true,
"color58": true,
"color59": true,
"color60": true,
"color61": true,
"color62": true,
"color63": true,
"color64": true,
"color65": true,
"color66": true,
"color67": true,
"color68": true,
"color69": true,
"color70": true,
"color71": true,
"color72": true,
"color73": true,
"color74": true,
"color75": true,
"color76": true,
"color77": true,
"color78": true,
"color79": true,
"color80": true,
"color81": true,
"color82": true,
"color83": true,
"color84": true,
"color85": true,
"color86": true,
"color87": true,
"color88": true,
"color89": true,
"color90": true,
"color91": true,
"color92": true,
"color93": true,
"color94": true,
"color95": true,
"color96": true,
"color97": true,
"color98": true,
"color99": true,
"cursor": true,
"cursor_text_color": true,
"cursor_trail_color": true,
"selection_background": true,
"selection_foreground": true,
"tab_bar_background": true,
"tab_bar_margin_color": true,
"visual_bell_color": true,
"window_title_bar_active_background": true,
"window_title_bar_active_foreground": true,
"window_title_bar_inactive_background": true,
"window_title_bar_inactive_foreground": true,
// NULLABLE_COLORS_END
}
// Colors that also accept special values such as background or system
var special_colors = map[string]bool{
// generated by gen-config.py do not edit
// SPECIAL_COLORS_START
"macos_titlebar_color": true,
"scrollbar_handle_color": true,
"scrollbar_track_color": true,
"wayland_titlebar_color": true,
// SPECIAL_COLORS_END
}
var titlebar_special_values = map[string]int{"system": 0, "background": 1}
var scrollbar_special_values = map[string]int{"foreground": 0, "selection_background": 1}
// The special values each color in special_colors accepts, must match the
// parsers in kitty/options/utils.py
var special_color_values = map[string]map[string]int{
"macos_titlebar_color": titlebar_special_values,
"wayland_titlebar_color": titlebar_special_values,
"scrollbar_handle_color": scrollbar_special_values,
"scrollbar_track_color": scrollbar_special_values,
}
// Encode a color that accepts special values the same way as
// color_with_special_values() in kitty/options/utils.py: special values are
// stored in the lowest byte and actual colors are shifted into the upper bytes.
func encode_special_color(key, val string) (int, error) {
special_values, found := special_color_values[key]
if !found {
return 0, fmt.Errorf("The special values for the color %s are not known", key)
}
val = strings.Trim(val, `"`)
if key == "macos_titlebar_color" {
switch val {
case "light":
return -1, nil
case "dark":
return -2, nil
}
}
if ans, found := special_values[val]; found {
return ans, nil
}
col, err := style.ParseColor(val)
if err != nil {
return 0, fmt.Errorf("%s is not a valid color", val)
}
return int(col.AsRGB())<<8 | len(special_values), nil
}
func set_color_in_color_map(key, val string, ans map[string]any, check_nullable, skip_nullable bool) error {
if val == "none" {
if check_nullable && !nullable_colors[key] {
if skip_nullable {
return nil
}
return fmt.Errorf("The color %s cannot be set to none", key)
}
ans[key] = nil
} else if key == "transparent_background_colors" {
ans[key] = val
} else if special_colors[key] {
col, err := encode_special_color(key, val)
if err != nil {
return err
}
ans[key] = col
} else {
col, err := style.ParseColor(val)
if err != nil {
return fmt.Errorf("%s is not a valid color", val)
}
ans[key] = col.AsRGB()
}
return nil
}
func read_colors_from_conf_file(path string, ans map[string]any) error {
var color_err error
cp := config.ConfigParser{LineHandler: func(key, val string) error {
key = strings.ToLower(key)
if key != "transparent_background_colors" && !themes.AllColorSettingNames[key] {
// conf files can contain non-color settings, ignore them
return nil
}
if err := set_color_in_color_map(key, strings.ToLower(val), ans, true, true); err != nil && color_err == nil {
color_err = fmt.Errorf("Invalid value for %s in %s: %w", key, path, err)
}
return nil
}}
if err := cp.ParseFiles(path); err != nil {
return err
}
return color_err
}
func parse_colors_and_files(args []string, opts options_set_colors_type, payload *set_colors_json_type) error {
// reset implies all and configured and any color arguments are ignored
payload.Reset = opts.Reset
payload.All = opts.All || opts.Reset
payload.Configured = opts.Configured || opts.Reset
if opts.Reset {
return nil
}
ans := make(map[string]any, len(args))
for _, arg := range args {
if key, val, found := strings.Cut(strings.ToLower(arg), "="); found {
if err := set_color_in_color_map(key, val, ans, true, false); err != nil {
return err
}
} else if err := read_colors_from_conf_file(utils.Expanduser(arg), ans); err != nil {
return err
}
}
payload.Colors = ans
return nil
}
+131
View File
@@ -0,0 +1,131 @@
// License: GPLv3 Copyright: 2026, kitty contributors
package at
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSetColorsResetIgnoresArguments(t *testing.T) {
missing_file := filepath.Join(t.TempDir(), "missing.conf")
for _, reset := range []bool{false, true} {
for _, test := range []struct {
name, arg string
invalid bool
}{
{"invalid-color", "foreground=not-a-color", true},
{"missing-file", missing_file, true},
{"valid-color", "foreground=red", false},
} {
t.Run(fmt.Sprintf("%s/reset=%t", test.name, reset), func(t *testing.T) {
payload := set_colors_json_type{}
err := parse_colors_and_files([]string{test.arg}, options_set_colors_type{Reset: reset}, &payload)
want_error := test.invalid && !reset
if (err != nil) != want_error {
t.Fatalf("expected error=%t, got: %v", want_error, err)
}
if err != nil {
return
}
if payload.Reset != reset || payload.All != reset || payload.Configured != reset {
t.Fatalf("reset=%t should set reset, all and configured to the same value, got: %#v", reset, payload)
}
if reset {
if len(payload.Colors) != 0 {
t.Fatalf("--reset did not ignore color arguments: %#v", payload.Colors)
}
} else if payload.Colors["foreground"] != uint32(0xff0000) {
t.Fatalf("foreground was not parsed: %#v", payload.Colors)
}
})
}
}
}
func TestSetColorsConfFiles(t *testing.T) {
tdir := t.TempDir()
write := func(name string, lines ...string) string {
path := filepath.Join(tdir, name)
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o600); err != nil {
t.Fatal(err)
}
return path
}
write("base.conf", "selection_background #00ff00")
good := write("good.conf",
"# a comment",
"foreground\t#ff0000",
" background #0000ff",
"font_size 12",
"cursor none",
"background_opacity 0.5",
"wayland_titlebar_color background",
"include base.conf",
"color1 #"+strings.Repeat("a", 6)+" "+strings.Repeat(" ", 70000),
)
payload := set_colors_json_type{}
if err := parse_colors_and_files([]string{good}, options_set_colors_type{}, &payload); err != nil {
t.Fatal(err)
}
expected := map[string]any{
"foreground": uint32(0xff0000), "background": uint32(0xff), "cursor": nil,
"selection_background": uint32(0xff00), "color1": uint32(0xaaaaaa),
"wayland_titlebar_color": 1,
}
if len(payload.Colors) != len(expected) {
t.Fatalf("unexpected colors parsed from conf file: %#v", payload.Colors)
}
for k, v := range expected {
if actual, found := payload.Colors[k]; !found || actual != v {
t.Fatalf("%s: expected %#v got %#v", k, v, actual)
}
}
bad := write("bad.conf", "background #000000", "foreground #zzzzzz")
err := parse_colors_and_files([]string{bad}, options_set_colors_type{}, &set_colors_json_type{})
if err == nil || !strings.Contains(err.Error(), "foreground") {
t.Fatalf("expected an error for an invalid color in a conf file, got: %v", err)
}
}
func TestSetColorsSpecialColors(t *testing.T) {
for key := range special_colors {
if special_color_values[key] == nil {
t.Fatalf("The special values for %s are not defined", key)
}
}
// expected values are from kitty.colors.parse_colors()
for _, test := range []struct {
arg string
expected int
}{
{"wayland_titlebar_color=#123456", 0x12345602},
{"wayland_titlebar_color=system", 0},
{`wayland_titlebar_color="background"`, 1},
{"macos_titlebar_color=dark", -2},
{"macos_titlebar_color=light", -1},
{"macos_titlebar_color=background", 1},
{"macos_titlebar_color=red", 0xff000002},
{"scrollbar_handle_color=selection_background", 1},
{"scrollbar_track_color=foreground", 0},
{"scrollbar_track_color=#123456", 0x12345602},
} {
payload := set_colors_json_type{}
if err := parse_colors_and_files([]string{test.arg}, options_set_colors_type{}, &payload); err != nil {
t.Fatalf("%s: %s", test.arg, err)
}
key, _, _ := strings.Cut(test.arg, "=")
if actual := payload.Colors[key]; actual != test.expected {
t.Fatalf("%s: expected %#x got %#v", test.arg, test.expected, actual)
}
}
for _, arg := range []string{"wayland_titlebar_color=light", "scrollbar_track_color=system", "macos_titlebar_color=none"} {
if err := parse_colors_and_files([]string{arg}, options_set_colors_type{}, &set_colors_json_type{}); err == nil {
t.Fatalf("%s: expected an error", arg)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"bytes"
"strconv"
)
func parse_set_font_size(arg string, payload *set_font_size_json_type) error {
if len(arg) > 0 && (bytes.IndexByte([]byte{'+', '-', '/', '*'}, arg[0]) > -1) {
payload.Increment_op = arg[:1]
arg = arg[1:]
}
val, err := strconv.ParseFloat(arg, 64)
if err != nil {
return err
}
payload.Size = val
return nil
}
+40
View File
@@ -0,0 +1,40 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"strconv"
"strings"
)
func parse_set_spacing(args []string) (map[string]any, error) {
ans := make(map[string]any, len(args))
for _, arg := range args {
k, v, found := strings.Cut(arg, "=")
if !found {
return nil, fmt.Errorf("%s is not a valid setting", arg)
}
k = strings.ToLower(k)
v = strings.ToLower(v)
which, found := spacing_edge_map[k]
if !found {
return nil, fmt.Errorf("%s is not a valid edge specification", k)
}
if v == "default" {
for _, q := range which {
ans[q] = nil
}
} else {
val, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, fmt.Errorf("%s is not a number", v)
}
for _, q := range which {
ans[q] = val
}
}
}
return ans, nil
}
+33
View File
@@ -0,0 +1,33 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestParseSetSpacing(t *testing.T) {
ten := float64(10)
for args, expected := range map[string]map[string]any{
"padding=default": {"padding-left": nil, "padding-top": nil, "padding-right": nil, "padding-bottom": nil},
"margin-h=10": {"margin-left": ten, "margin-right": ten},
"Margin-Horizontal=10 padding-vertical=default": {"margin-left": ten, "margin-right": ten, "padding-top": nil, "padding-bottom": nil},
"padding-v=10 margin-bottom=10": {"padding-top": ten, "padding-bottom": ten, "margin-bottom": ten},
} {
actual, err := parse_set_spacing(strings.Fields(args))
if err != nil {
t.Fatalf("parse_set_spacing(%#v) failed with error: %s", args, err)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("parse_set_spacing(%#v) returned unexpected result:\n%s", args, diff)
}
}
for _, arg := range []string{"margin", "margin-diagonal=10", "padding=x"} {
if actual, err := parse_set_spacing([]string{arg}); err == nil {
t.Fatalf("parse_set_spacing(%#v) accepted invalid input and returned: %v", arg, actual)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"fmt"
"strings"
)
var valid_color_names = map[string]bool{"active_fg": true, "active_bg": true, "inactive_fg": true, "inactive_bg": true}
func parse_tab_colors(args []string) (map[string]any, error) {
ans := make(map[string]any, len(args))
for _, arg := range args {
key, val, found := strings.Cut(strings.ToLower(arg), "=")
if !found {
return nil, fmt.Errorf("%s is not a valid setting", arg)
}
if !valid_color_names[key] {
return nil, fmt.Errorf("%s is not a valid color name", key)
}
err := set_color_in_color_map(key, val, ans, false, false)
if err != nil {
return nil, err
}
}
return ans, nil
}
+102
View File
@@ -0,0 +1,102 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"bytes"
"fmt"
"image"
"io"
"os"
"strings"
"github.com/emmansun/base64"
"github.com/kovidgoyal/kitty/tools/utils/images"
)
func set_payload_data(io_data *rc_io_data, data string) {
set_payload_string_field(io_data, "Data", data)
}
func read_window_logo(io_data *rc_io_data, path string) (func(io_data *rc_io_data) (bool, error), error) {
if strings.ToLower(path) == "none" {
io_data.rc.Stream = false
return func(io_data *rc_io_data) (bool, error) {
set_payload_data(io_data, "-")
return true, nil
}, nil
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
_, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("%s is not a supported image format", path)
}
var image_data_stream io.Reader = bytes.NewReader(data)
if format != "png" {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("failed to decode the image %s: %w", path, err)
}
b := bytes.Buffer{}
if err = images.Encode(&b, img, "image/png"); err != nil {
return nil, fmt.Errorf("failed to convert the image %s to PNG: %w", path, err)
}
image_data_stream = &b
}
is_first_call := true
buf := make([]byte, 2048)
return func(io_data *rc_io_data) (bool, error) {
if is_first_call {
is_first_call = false
} else {
io_data.rc.Stream = false
}
buf = buf[:cap(buf)]
n, err := image_data_stream.Read(buf)
if err != nil && err != io.EOF {
return false, err
}
buf = buf[:n]
set_payload_data(io_data, base64.StdEncoding.EncodeToString(buf))
if err == io.EOF {
return true, nil
}
return false, nil
}, nil
}
func is_index_arg(s string) bool {
if len(s) == 0 {
return false
}
start := 0
if s[0] == '+' || s[0] == '-' {
start = 1
}
if start >= len(s) {
return false
}
for _, c := range s[start:] {
if c < '0' || c > '9' {
return false
}
}
return true
}
func read_background_image(io_data *rc_io_data, path string) (func(io_data *rc_io_data) (bool, error), error) {
if is_index_arg(path) {
io_data.rc.Stream = false
return func(io_data *rc_io_data) (bool, error) {
set_payload_data(io_data, "index:"+path)
return true, nil
}, nil
}
return read_window_logo(io_data, path)
}
+110
View File
@@ -0,0 +1,110 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"bytes"
"encoding/base64"
"encoding/binary"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kovidgoyal/kitty/tools/utils"
)
// Truncate a JPEG immediately after its SOS segment header so that the
// header (and thus image.DecodeConfig) is valid but there is no image data.
func truncate_jpeg_before_scan_data(t *testing.T, data []byte) []byte {
idx := bytes.Index(data, []byte{0xff, 0xda})
if idx < 0 || idx+4 > len(data) {
t.Fatal("Could not find SOS marker in JPEG data")
}
end := idx + 2 + int(binary.BigEndian.Uint16(data[idx+2:]))
if end > len(data) {
t.Fatal("Invalid SOS segment length in JPEG data")
}
return data[:end]
}
func TestReadRemoteImage(t *testing.T) {
type payload struct{ Data string }
src := image.NewRGBA(image.Rect(0, 0, 4, 4))
var jpeg_data, png_data bytes.Buffer
if err := jpeg.Encode(&jpeg_data, src, nil); err != nil {
t.Fatal(err)
}
if err := png.Encode(&png_data, src); err != nil {
t.Fatal(err)
}
truncated := truncate_jpeg_before_scan_data(t, jpeg_data.Bytes())
if _, _, err := image.DecodeConfig(bytes.NewReader(truncated)); err != nil {
t.Fatalf("Truncated JPEG does not have a valid header: %s", err)
}
tdir := t.TempDir()
for _, tc := range []struct {
name string
data []byte
expected_err string
}{
{"truncated_jpeg", truncated, "failed to decode"},
{"not_an_image", []byte("not an image"), "not a supported image format"},
{"jpeg", jpeg_data.Bytes(), ""},
{"png", png_data.Bytes(), ""},
} {
path := filepath.Join(tdir, tc.name)
if err := os.WriteFile(path, tc.data, 0o600); err != nil {
t.Fatal(err)
}
for _, reader := range []struct {
name string
read func(*rc_io_data, string) (func(*rc_io_data) (bool, error), error)
}{
{"window_logo", read_window_logo},
{"background_image", read_background_image},
} {
t.Run(reader.name+"/"+tc.name, func(t *testing.T) {
io_data := rc_io_data{rc: &utils.RemoteControlCmd{Stream: true, Payload: payload{}}}
next, err := reader.read(&io_data, path)
if tc.expected_err != "" {
if err == nil || next != nil {
t.Fatalf("Expected an error and no image stream, got error: %v", err)
}
if !strings.Contains(err.Error(), tc.expected_err) || !strings.Contains(err.Error(), path) {
t.Fatalf("Error message %q does not contain %q and the path", err, tc.expected_err)
}
return
}
if err != nil {
t.Fatal(err)
}
var received []byte
for done := false; !done; {
if done, err = next(&io_data); err != nil {
t.Fatal(err)
}
chunk, err := base64.StdEncoding.DecodeString(io_data.rc.Payload.(payload).Data)
if err != nil {
t.Fatal(err)
}
received = append(received, chunk...)
}
img, format, err := image.Decode(bytes.NewReader(received))
if err != nil {
t.Fatal(err)
}
if format != "png" || img.Bounds() != src.Bounds() {
t.Fatalf("Incorrect image stream: format=%s, bounds=%v", format, img.Bounds())
}
if tc.name == "png" && !bytes.Equal(received, tc.data) {
t.Fatal("PNG data was not sent unmodified")
}
})
}
}
}
+247
View File
@@ -0,0 +1,247 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/readline"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
var _ = fmt.Print
var formatter *markup.Context
const prompt = "🐱 "
var ErrExec = errors.New("Execute command")
func shell_loop(rl *readline.Readline, kill_if_signaled bool) (int, error) {
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors)
if err != nil {
return 1, err
}
rl.ChangeLoopAndResetText(lp)
lp.OnInitialize = func() (string, error) {
rl.Start()
return "", nil
}
lp.OnFinalize = func() string { rl.End(); return "" }
lp.OnResumeFromStop = func() error {
rl.Start()
return nil
}
lp.OnResize = rl.OnResize
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
err := rl.OnKeyEvent(event)
if err != nil {
if err == io.EOF {
lp.Quit(0)
return nil
}
if err == readline.ErrAcceptInput {
if strings.HasSuffix(rl.TextBeforeCursor(), "\\") && rl.CursorAtEndOfLine() {
rl.OnText("\n", false, false)
rl.Redraw()
return nil
}
rl.MoveCursorToEnd()
rl.Redraw()
lp.ClearToEndOfScreen()
return ErrExec
}
return err
}
if event.Handled {
rl.Redraw()
return nil
}
return nil
}
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
err := rl.OnText(text, from_key_event, in_bracketed_paste)
if err == nil {
rl.Redraw()
}
return err
}
err = lp.Run()
if err != nil {
return 1, err
}
ds := lp.DeathSignalName()
if ds != "" {
if kill_if_signaled {
lp.KillIfSignalled()
return 1, nil
}
return 1, fmt.Errorf("Killed by signal: %s", ds)
}
return 0, nil
}
func show_basic_help() {
output := strings.Builder{}
fmt.Fprintln(&output, "Control kitty by sending it commands.")
fmt.Fprintln(&output)
fmt.Fprintln(&output, formatter.Title("Commands")+":")
r := EntryPoint(cli.NewRootCommand())
for _, g := range r.SubCommandGroups {
for _, sc := range g.SubCommands {
fmt.Fprintln(&output, " ", formatter.Green(sc.Name))
fmt.Fprintln(&output, " ", sc.ShortDescription)
}
}
fmt.Fprintln(&output, " ", formatter.Green("help"))
fmt.Fprintln(&output, " ", "Show this help")
fmt.Fprintln(&output, " ", formatter.Green("exit"))
fmt.Fprintln(&output, " ", "Exit this shell")
cli.ShowHelpInPager(output.String())
}
func exec_command(at_root_command *cli.Command, rl *readline.Readline, cmdline string) bool {
parsed_cmdline, err := shlex.Split(cmdline)
if err != nil {
fmt.Fprintln(os.Stderr, "Could not parse cmdline:", err)
return true
}
if len(parsed_cmdline) == 0 {
return true
}
cwd, _ := os.Getwd()
hi := readline.HistoryItem{Timestamp: time.Now(), Cmd: rl.AllText(), ExitCode: -1, Cwd: cwd}
switch parsed_cmdline[0] {
case "exit":
hi.ExitCode = 0
rl.AddHistoryItem(hi)
return false
case "help":
hi.ExitCode = 0
defer rl.AddHistoryItem(hi)
if len(parsed_cmdline) == 1 {
show_basic_help()
return true
}
switch parsed_cmdline[1] {
case "exit":
fmt.Println("Exit this shell")
case "help":
fmt.Println("Show help")
default:
sc := at_root_command.FindSubCommand(parsed_cmdline[1])
if sc == nil {
hi.ExitCode = 1
fmt.Fprintln(os.Stderr, "No command named", formatter.BrightRed(parsed_cmdline[1])+". Type help for a list of commands")
} else {
sc.ShowHelpWithCommandString(sc.Name)
}
}
return true
default:
if at_root_command.FindSubCommand(parsed_cmdline[0]) == nil {
hi.ExitCode = 1
fmt.Fprintln(os.Stderr, "No command named", formatter.BrightRed(parsed_cmdline[0])+". Type help for a list of commands")
return true
}
cmdline := []string{"kitten", "@"}
cmdline = append(cmdline, parsed_cmdline...)
root := cli.NewRootCommand()
EntryPoint(root)
hi.ExitCode = root.ExecArgs(cmdline)
hi.Duration = time.Now().Sub(hi.Timestamp)
rl.AddHistoryItem(hi)
}
return true
}
func completions(before_cursor, after_cursor string) (ans *cli.Completions) {
const prefix = "kitten @ "
text := prefix + before_cursor
argv, position_of_last_arg := shlex.SplitForCompletion(text)
if len(argv) == 0 || position_of_last_arg < len(prefix) {
return
}
root := cli.NewRootCommand()
c := root.AddSubCommand(&cli.Command{Name: "kitten"})
EntryPoint(c)
a := c.FindSubCommand("@")
add_sc := func(cmd, desc string) {
var x *cli.Command
if x = a.FindSubCommand(cmd); x == nil {
x = a.AddSubCommand(&cli.Command{Name: cmd})
}
x.ShortDescription = desc
}
add_sc("help", "Show help")
add_sc("exit", "Exit the kitty shell")
root.Validate()
ans = root.GetCompletions(argv, nil)
ans.CurrentWordIdx = position_of_last_arg - len(prefix)
return
}
func shell_main(cmd *cli.Command, args []string) (int, error) {
err := setup_global_options(cmd)
if err != nil {
return 1, err
}
running_shell = true
formatter = markup.New(true)
fmt.Println("Welcome to the kitty shell!")
fmt.Println("Use", formatter.Green("help"), "for assistance or", formatter.Green("exit"), "to quit.")
if atwid := os.Getenv("KITTY_SHELL_ACTIVE_WINDOW_ID"); atwid != "" {
amsg := "Previously active window id: " + atwid
os.Unsetenv("KITTY_SHELL_ACTIVE_WINDOW_ID")
if attid := os.Getenv("KITTY_SHELL_ACTIVE_TAB_ID"); attid != "" {
os.Unsetenv("KITTY_SHELL_ACTIVE_TAB_ID")
amsg += " and tab id: " + attid
}
fmt.Println(amsg)
}
var rl *readline.Readline
combined_completer := func(before_cursor, after_cursor string) *cli.Completions {
ans := completions(before_cursor, after_cursor)
history := rl.HistoryCompleter(before_cursor, after_cursor)
for _, group := range history.Groups {
ans.MergeMatchGroup(group)
}
return ans
}
rl = readline.New(nil, readline.RlInit{Prompt: prompt, Completer: combined_completer, HistoryPath: filepath.Join(utils.CacheDir(), "shell.history.json")})
defer func() {
rl.Shutdown()
}()
for {
rc, err := shell_loop(rl, true)
if err != nil {
if err == ErrExec {
cmdline := rl.AllText()
cmdline = strings.ReplaceAll(cmdline, "\\\n", "")
if !exec_command(cmd, rl, cmdline) {
return 0, nil
}
continue
}
}
return rc, err
}
}
+186
View File
@@ -0,0 +1,186 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"time"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
func write_all_to_conn(conn *net.Conn, data []byte) error {
for len(data) > 0 {
n, err := (*conn).Write(data)
if err != nil && errors.Is(err, io.ErrShortWrite) {
err = nil
}
if err != nil {
return err
}
data = data[n:]
}
return nil
}
func write_many_to_conn(conn *net.Conn, datums ...[]byte) error {
for len(datums) > 0 {
err := write_all_to_conn(conn, datums[0])
if err != nil {
return err
}
datums = datums[1:]
}
return nil
}
type response_reader struct {
parser wcswidth.EscapeCodeParser
storage [utils.DEFAULT_IO_BUFFER_SIZE]byte
pending_responses [][]byte
}
func (r *response_reader) read_response_from_conn(conn *net.Conn, timeout time.Duration) (serialized_response []byte, err error) {
keep_going := true
if len(r.pending_responses) == 0 {
r.parser.HandleDCS = func(data []byte) error {
if bytes.HasPrefix(data, []byte("@kitty-cmd")) {
r.pending_responses = append(r.pending_responses, append([]byte{}, data[len("@kitty-cmd"):]...))
keep_going = false
}
return nil
}
buf := r.storage[:]
for keep_going {
var n int
(*conn).SetDeadline(time.Now().Add(timeout))
n, err = (*conn).Read(buf)
if err != nil {
keep_going = false
break
}
r.parser.Parse(buf[:n])
}
}
if len(r.pending_responses) > 0 {
serialized_response = r.pending_responses[0]
r.pending_responses = r.pending_responses[1:]
}
return
}
const cmd_escape_code_prefix = "\x1bP@kitty-cmd"
const cmd_escape_code_suffix = "\x1b\\"
func run_stdin_echo_loop(conn *net.Conn, io_data *rc_io_data) (err error) {
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors)
if err != nil {
return
}
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
event.Handled = true
err = io_data.on_key_event(lp, event)
if err != nil {
if err == end_reading_from_stdin {
lp.Quit(0)
return nil
}
return err
}
chunk, err := io_data.next_chunk()
if err != nil {
if err == waiting_on_stdin {
return nil
}
return err
}
err = write_many_to_conn(conn, []byte(cmd_escape_code_prefix), chunk, []byte(cmd_escape_code_suffix))
if err != nil {
return err
}
return nil
}
err = lp.Run()
if err == nil {
lp.KillIfSignalled()
}
return err
}
func simple_socket_io(conn *net.Conn, io_data *rc_io_data) (serialized_response []byte, err error) {
r := response_reader{}
r.pending_responses = make([][]byte, 0, 2) // we read at most two responses
first_escape_code_sent := false
wants_streaming := io_data.rc.Stream
for {
var chunk []byte
chunk, err = io_data.next_chunk()
if err != nil {
if err == waiting_on_stdin {
err := run_stdin_echo_loop(conn, io_data)
return make([]byte, 0), err
}
return
}
if len(chunk) == 0 {
break
}
err = write_many_to_conn(conn, []byte(cmd_escape_code_prefix), chunk, []byte(cmd_escape_code_suffix))
if err != nil {
return
}
if !first_escape_code_sent {
first_escape_code_sent = true
if wants_streaming {
var streaming_response []byte
streaming_response, err = r.read_response_from_conn(conn, io_data.timeout)
if err != nil {
return
}
if !is_stream_response(streaming_response) {
err = fmt.Errorf("Did not receive expected streaming response")
return
}
}
}
}
if io_data.rc.NoResponse {
return
}
return r.read_response_from_conn(conn, io_data.timeout)
}
func do_socket_io(io_data *rc_io_data) (serialized_response []byte, err error) {
var conn net.Conn
if global_options.to_network == "fd" {
fd, _ := strconv.Atoi(global_options.to_address)
if err != nil {
return nil, err
}
f := os.NewFile(uintptr(fd), "fd:"+global_options.to_address)
conn, err = net.FileConn(f)
if err != nil {
return nil, fmt.Errorf("Failed to open a socket for the remote control file descriptor: %d with error: %w", fd, err)
}
defer f.Close()
} else {
network := utils.IfElse(global_options.to_network == "ip", "tcp", global_options.to_network)
conn, err = net.Dial(network, global_options.to_address)
if err != nil {
err = fmt.Errorf("Failed to connect to %s:%s with error: %w", network, global_options.to_address, err)
return
}
}
defer conn.Close()
return simple_socket_io(&conn, io_data)
}
+113
View File
@@ -0,0 +1,113 @@
//go:build exclude
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
// Code generated by gen-go-code.py; DO NOT EDIT.
package at
import (
"fmt"
"strings"
"time"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
var _ = strings.Join
type options_CMD_NAME_type struct {
OPTIONS_DECLARATION_CODE
}
var options_CMD_NAME options_CMD_NAME_type
type CMD_NAME_json_type struct {
JSON_DECLARATION_CODE
}
func create_payload_CMD_NAME(io_data *rc_io_data, cmd *cli.Command, args []string) (err error) {
payload := CMD_NAME_json_type{}
JSON_INIT_CODE
io_data.rc.Payload = payload
return
}
func create_rc_CMD_NAME(args []string) (*utils.RemoteControlCmd, error) {
rc := utils.RemoteControlCmd{
Cmd: "CLI_NAME",
Version: ProtocolVersion,
NoResponse: NO_RESPONSE_BASE,
Stream: STREAM_WANTED,
}
if rc.Stream {
stream_id, err := utils.HumanRandomId(128)
if err != nil {
return nil, err
}
rc.StreamId = stream_id
}
if IS_ASYNC {
async_id, err := utils.HumanRandomId(128)
if err != nil {
return nil, err
}
rc.Async = async_id
}
return &rc, nil
}
func run_CMD_NAME(cmd *cli.Command, args []string) (return_code int, err error) {
err = cmd.GetOptionValues(&options_CMD_NAME)
if err != nil {
return
}
rc, err := create_rc_CMD_NAME(args)
if err != nil {
return
}
nrv, err := cli.GetOptionValue[bool](cmd, "NoResponse")
if err == nil {
rc.NoResponse = nrv
}
var timeout float64 = WAIT_TIMEOUT
rt, err := cli.GetOptionValue[float64](cmd, "ResponseTimeout")
if err == nil {
timeout = rt
}
io_data := rc_io_data{
cmd: cmd,
rc: rc,
timeout: time.Duration(timeout * float64(time.Second)),
string_response_is_err: STRING_RESPONSE_IS_ERROR,
}
err = create_payload_CMD_NAME(&io_data, cmd, args)
if err != nil {
return
}
err = send_rc_command(&io_data)
if ee, ok := err.(*exit_error); ok && !running_shell {
return ee.exit_code, nil
}
return
}
func setup_CMD_NAME(parent *cli.Command) *cli.Command {
ans := parent.AddSubCommand(&cli.Command{
Name: "CLI_NAME",
Usage: "ARGSPEC",
ShortDescription: "SHORT_DESC",
HelpText: "LONG_DESC",
Run: run_CMD_NAME,
})
ADD_FLAGS_CODE
return ans
}
func init() {
register_at_cmd(setup_CMD_NAME)
}
+175
View File
@@ -0,0 +1,175 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package at
import (
"encoding/json"
"os"
"time"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
type stream_response struct {
Ok bool `json:"ok"`
Stream bool `json:"stream"`
}
func is_stream_response(serialized_response []byte) bool {
var response stream_response
if len(serialized_response) > 32 {
return false
}
err := json.Unmarshal(serialized_response, &response)
return err == nil && response.Stream
}
func do_chunked_io(io_data *rc_io_data) (serialized_response []byte, err error) {
serialized_response = make([]byte, 0)
lp, err := loop.NewForSimpleInteraction()
if err != nil {
return
}
if io_data.on_key_event != nil {
lp.FullKeyboardProtocol()
lp.NoRoundtripToTerminalOnExit()
} else {
lp.NoKeyboardStateChange()
}
const (
BEFORE_FIRST_ESCAPE_CODE_SENT = iota
WAITING_FOR_STREAMING_RESPONSE
SENDING
WAITING_FOR_RESPONSE
)
state := BEFORE_FIRST_ESCAPE_CODE_SENT
var last_received_data_at time.Time
var check_for_timeout func(timer_id loop.IdType) error
wants_streaming := false
check_for_timeout = func(timer_id loop.IdType) (err error) {
if state != WAITING_FOR_RESPONSE && state != WAITING_FOR_STREAMING_RESPONSE {
return
}
if io_data.on_key_event != nil {
return
}
time_since_last_received_data := time.Since(last_received_data_at)
if time_since_last_received_data >= io_data.timeout {
return os.ErrDeadlineExceeded
}
_, err = lp.AddTimer(io_data.timeout-time_since_last_received_data, false, check_for_timeout)
return
}
transition_to_read := func() {
if state == WAITING_FOR_RESPONSE && io_data.rc.NoResponse {
lp.Quit(0)
}
last_received_data_at = time.Now()
_, _ = lp.AddTimer(io_data.timeout, false, check_for_timeout)
}
lp.OnReceivedData = func(data []byte) error {
last_received_data_at = time.Now()
return nil
}
queue_escape_code := func(data []byte) {
lp.QueueWriteString(cmd_escape_code_prefix)
lp.UnsafeQueueWriteBytes(data)
lp.QueueWriteString(cmd_escape_code_suffix)
}
lp.OnInitialize = func() (string, error) {
chunk, err := io_data.next_chunk()
wants_streaming = io_data.rc.Stream
if err != nil {
if err == waiting_on_stdin {
return "", nil
}
return "", err
}
if len(chunk) == 0 {
state = WAITING_FOR_RESPONSE
transition_to_read()
} else {
queue_escape_code(chunk)
}
return "", nil
}
lp.OnWriteComplete = func(completed_write_id loop.IdType, has_pending_writes bool) error {
if state == WAITING_FOR_STREAMING_RESPONSE || state == WAITING_FOR_RESPONSE {
return nil
}
chunk, err := io_data.next_chunk()
if err != nil {
if err == waiting_on_stdin {
return nil
}
return err
}
if len(chunk) == 0 {
state = utils.IfElse(state == BEFORE_FIRST_ESCAPE_CODE_SENT && wants_streaming, WAITING_FOR_STREAMING_RESPONSE, WAITING_FOR_RESPONSE)
transition_to_read()
} else {
queue_escape_code(chunk)
}
if state == BEFORE_FIRST_ESCAPE_CODE_SENT {
if wants_streaming {
state = WAITING_FOR_STREAMING_RESPONSE
transition_to_read()
} else {
state = SENDING
}
}
return nil
}
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
if io_data.on_key_event == nil {
return nil
}
err := io_data.on_key_event(lp, event)
if err == end_reading_from_stdin {
lp.Quit(0)
return nil
}
if err != nil {
return err
}
chunk, err := io_data.next_chunk()
if err != nil {
if err == waiting_on_stdin {
return nil
}
return err
}
queue_escape_code(chunk)
return err
}
lp.OnRCResponse = func(raw []byte) error {
if state == WAITING_FOR_STREAMING_RESPONSE && is_stream_response(raw) {
state = SENDING
return lp.OnWriteComplete(0, false)
}
serialized_response = raw
lp.Quit(0)
return nil
}
err = lp.Run()
if err == nil {
lp.KillIfSignalled()
}
return
}
func do_tty_io(io_data *rc_io_data) (serialized_response []byte, err error) {
return do_chunked_io(io_data)
}