chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
@@ -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 + "=")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package atexit
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func main() (rc int, err error) {
|
||||
signal.Ignore()
|
||||
done_channel := make(chan bool)
|
||||
lines := []string{}
|
||||
|
||||
defer os.Stdout.Close()
|
||||
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
fmt.Println(len(lines))
|
||||
}
|
||||
done_channel <- true
|
||||
}()
|
||||
|
||||
<-done_channel
|
||||
rc = 0
|
||||
for _, line := range lines {
|
||||
if action, rest, found := strings.Cut(line, " "); found {
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
switch action {
|
||||
case "unlink":
|
||||
if err := os.Remove(rest); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintln(os.Stderr, "Failed to unlink:", rest, "with error:", err)
|
||||
rc = 1
|
||||
}
|
||||
case "shm_unlink":
|
||||
if err := shm.ShmUnlink(rest); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintln(os.Stderr, "Failed to shm_unlink:", rest, "with error:", err)
|
||||
rc = 1
|
||||
}
|
||||
case "rmtree":
|
||||
if err := os.RemoveAll(rest); err != nil && !os.IsNotExist(err) {
|
||||
fmt.Fprintln(os.Stderr, "Failed to rmtree:", rest, "with error:", err)
|
||||
rc = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func do_test() (err error) {
|
||||
if err = os.WriteFile("file", []byte("moose"), 0o600); err != nil {
|
||||
return
|
||||
}
|
||||
if err = utils.AtExitUnlink("file"); err != nil {
|
||||
return
|
||||
}
|
||||
if err = os.Mkdir("dir", 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
if err = utils.AtExitRmtree("dir"); err != nil {
|
||||
return
|
||||
}
|
||||
if err = os.WriteFile("dir/sf", []byte("cat"), 0o600); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) {
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "__atexit__",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
if len(args) != 0 {
|
||||
if args[0] == "test" {
|
||||
rc = 0
|
||||
if err = do_test(); err != nil {
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
return 1, fmt.Errorf("Usage: __atexit__")
|
||||
}
|
||||
return main()
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package benchmark
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/graphics"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Options struct {
|
||||
Repetitions int
|
||||
WithScrollback bool
|
||||
Render bool
|
||||
}
|
||||
|
||||
const reset = "\x1b]\x1b\\\x1bc"
|
||||
const ascii_printable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ `~!@#$%^&*()_+-=[]{}\\|;:'\",<.>/?"
|
||||
const control_chars = "\n\t"
|
||||
const chinese_lorem_ipsum = "旦海司有幼雞讀松鼻種比門真目怪少:扒裝虎怕您跑綠蝶黃,位香法士錯乙音造活羽詞坡村目園尺封鳥朋;法松夕點我冬停雪因科對只貓息加黃住蝶,明鴨乾春呢風乙時昔孝助?小紅女父故去。" +
|
||||
"飯躲裝個哥害共買去隻把氣年,己你校跟飛百拉!快石牙飽知唱想土人吹象毛吉每浪四又連見、欠耍外豆雞秋鼻。住步帶。" +
|
||||
"打六申幾麼:或皮又荷隻乙犬孝習秋還何氣;幾裏活打能花是入海乙山節會。種第共後陽沒喜姐三拍弟海肖,行知走亮包,他字幾,的木卜流旦乙左杯根毛。" +
|
||||
"您皮買身苦八手牛目地止哥彩第合麻讀午。原朋河乾種果「才波久住這香松」兄主衣快他玉坐要羽和亭但小山吉也吃耳怕,也爪斗斥可害朋許波怎祖葉卜。" +
|
||||
"行花兩耍許車丟學「示想百吃門高事」不耳見室九星枝買裝,枝十新央發旁品丁青給,科房火;事出出孝肉古:北裝愛升幸百東鼻到從會故北「可休笑物勿三游細斗」娘蛋占犬。我羊波雨跳風。" +
|
||||
"牛大燈兆新七馬,叫這牙後戶耳、荷北吃穿停植身玩間告或西丟再呢,他禾七愛干寺服石安:他次唱息它坐屋父見這衣發現來,苗會開條弓世者吃英定豆哭;跳風掃叫美神。" +
|
||||
"寸再了耍休壯植己,燈錯和,蝶幾欠雞定和愛,司紅後弓第樹會金拉快喝夕見往,半瓜日邊出讀雞苦歌許開;發火院爸乙;四帶亮錯鳥洋個讀。"
|
||||
const misc_unicode = "‘’“”‹›«»‚„ 😀😛😇😈😉😍😎😮👍👎 —–§¶†‡©®™ →⇒•·°±−×÷¼½½¾" +
|
||||
"…µ¢£€¿¡¨´¸ˆ˜ ÀÁÂÃÄÅÆÇÈÉÊË ÌÍÎÏÐÑÒÓÔÕÖØ ŒŠÙÚÛÜÝŸÞßàá âãäåæçèéêëìí" +
|
||||
"îïðñòóôõöøœš ùúûüýÿþªºαΩ∞ ū̀n̂o᷵H̨a̠b̡͓̐c̡͓̐X̡͓̐"
|
||||
|
||||
var opts Options
|
||||
|
||||
func benchmark_data(description string, data string, opts Options) (duration time.Duration, sent_data_size int, reps int, err error) {
|
||||
term, err := tty.OpenControllingTerm(tty.SetRaw)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
defer term.RestoreAndClose()
|
||||
write_with_retry := func(data string) (err error) {
|
||||
return term.WriteAllString(data)
|
||||
}
|
||||
state := loop.TerminalStateOptions{Alternate_screen: !opts.WithScrollback}
|
||||
if err = write_with_retry(state.SetStateEscapeCodes() + loop.DECTCEM.EscapeCodeToReset()); err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = write_with_retry(state.ResetStateEscapeCodes() + loop.DECTCEM.EscapeCodeToSet() + reset) }()
|
||||
const count = 3
|
||||
|
||||
const clear_screen = "\x1b[m\x1b[H\x1b[2J"
|
||||
desc := clear_screen + "Running: " + description + "\r\n"
|
||||
const pause_rendering = "\x1b[?2026h"
|
||||
const resume_rendering = "\x1b[?2026l"
|
||||
if !opts.Render {
|
||||
if err = write_with_retry(desc + pause_rendering); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
end_of_loop_reset := desc
|
||||
if !opts.Render {
|
||||
end_of_loop_reset += resume_rendering + pause_rendering
|
||||
}
|
||||
for reps < opts.Repetitions {
|
||||
if err = write_with_retry(data); err != nil {
|
||||
return
|
||||
}
|
||||
sent_data_size += len(data)
|
||||
reps += 1
|
||||
if err = write_with_retry(end_of_loop_reset); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
finalize := clear_screen + "Waiting for response indicating parsing finished\r\n"
|
||||
if !opts.Render {
|
||||
finalize += resume_rendering
|
||||
}
|
||||
finalize += "\x1b[6n" + strings.Repeat("\x1b[5n", count)
|
||||
if err = write_with_retry(finalize); err != nil {
|
||||
return
|
||||
}
|
||||
q := []byte(strings.Repeat("\x1b[0n", count))
|
||||
var read_data []byte
|
||||
buf := make([]byte, 8192)
|
||||
for !bytes.Contains(read_data, q) {
|
||||
n, err := term.Read(buf)
|
||||
if err != nil {
|
||||
if (errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR)) && n == 0 {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
read_data = append(read_data, buf[:n]...)
|
||||
}
|
||||
duration = time.Since(start)
|
||||
return
|
||||
}
|
||||
|
||||
func random_string_of_bytes(n int, alphabet string) string {
|
||||
b := make([]byte, n)
|
||||
al := len(alphabet)
|
||||
for i := range n {
|
||||
b[i] = alphabet[rand.IntN(al)]
|
||||
}
|
||||
return utils.UnsafeBytesToString(b)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
desc string
|
||||
data_sz int
|
||||
duration time.Duration
|
||||
repetitions int
|
||||
}
|
||||
|
||||
func simple_ascii() (r result, err error) {
|
||||
const desc = "Only ASCII chars"
|
||||
data := random_string_of_bytes(1024*2048+13, ascii_printable+control_chars)
|
||||
duration, data_sz, reps, err := benchmark_data(desc, data, opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
func unicode() (r result, err error) {
|
||||
const desc = "Unicode chars"
|
||||
data := strings.Repeat(chinese_lorem_ipsum+misc_unicode+control_chars, 1024)
|
||||
duration, data_sz, reps, err := benchmark_data(desc, data, opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
func unique_unicode() (r result, err error) {
|
||||
const cell_count = 256 * 1024
|
||||
const combining_count = 0x70
|
||||
var data strings.Builder
|
||||
data.Grow(cell_count * 10)
|
||||
for i := range cell_count {
|
||||
q := i
|
||||
data.WriteByte('a')
|
||||
for range 3 {
|
||||
data.WriteRune(rune(0x300 + q%combining_count))
|
||||
q /= combining_count
|
||||
}
|
||||
}
|
||||
const desc = "Unique multi-codepoint Unicode cells"
|
||||
duration, data_sz, reps, err := benchmark_data(desc, data.String(), opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
func ascii_with_csi() (r result, err error) {
|
||||
const sz = 1024*1024 + 17
|
||||
out := make([]byte, 0, sz+48)
|
||||
chunk := ""
|
||||
for len(out) < sz {
|
||||
q := rand.IntN(100)
|
||||
switch {
|
||||
case (q < 10):
|
||||
chunk = random_string_of_bytes(rand.IntN(72)+1, ascii_printable+control_chars)
|
||||
case (10 <= q && q < 30):
|
||||
chunk = "\x1b[m\x1b[?1h\x1b[H"
|
||||
case (30 <= q && q < 40):
|
||||
chunk = "\x1b[1;2;3;4:3;31m"
|
||||
case (40 <= q && q < 50):
|
||||
chunk = "\x1b[38:5:24;48:2:125:136:147m"
|
||||
case (50 <= q && q < 60):
|
||||
chunk = "\x1b[58;5;44;2m"
|
||||
case (60 <= q && q < 80):
|
||||
chunk = "\x1b[m\x1b[10A\x1b[3E\x1b[2K"
|
||||
case (80 <= q && q < 100):
|
||||
chunk = "\x1b[39m\x1b[10`a\x1b[100b\x1b[?1l"
|
||||
}
|
||||
out = append(out, utils.UnsafeStringToBytes(chunk)...)
|
||||
}
|
||||
out = append(out, "\x1b[m"...)
|
||||
const desc = "CSI codes with few chars"
|
||||
duration, data_sz, reps, err := benchmark_data(desc, utils.UnsafeBytesToString(out), opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
func images() (r result, err error) {
|
||||
g := graphics.GraphicsCommand{}
|
||||
g.SetImageId(12345)
|
||||
g.SetQuiet(graphics.GRT_quiet_silent)
|
||||
g.SetAction(graphics.GRT_action_transmit)
|
||||
g.SetFormat(graphics.GRT_format_rgba)
|
||||
const dim = 1024
|
||||
g.SetDataWidth(dim)
|
||||
g.SetDataHeight(dim)
|
||||
g.DisableCompression = true // dont want to measure the speed of zlib
|
||||
b := strings.Builder{}
|
||||
b.Grow(8 * dim * dim)
|
||||
_ = g.WriteWithPayloadTo(&b, make([]byte, 4*dim*dim))
|
||||
g.SetAction(graphics.GRT_action_delete)
|
||||
g.SetDelete(graphics.GRT_free_by_id)
|
||||
_ = g.WriteWithPayloadTo(&b, nil)
|
||||
data := b.String()
|
||||
const desc = "Images"
|
||||
duration, data_sz, reps, err := benchmark_data(desc, data, opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
func long_escape_codes() (r result, err error) {
|
||||
data := random_string_of_bytes(8024, ascii_printable)
|
||||
// OSC 6 is document reporting or XTerm special color which kitty ignores after parsing
|
||||
data = strings.Repeat("\x1b]6;"+data+"\x07", 1024)
|
||||
const desc = "Long escape codes"
|
||||
duration, data_sz, reps, err := benchmark_data(desc, data, opts)
|
||||
if err != nil {
|
||||
return result{}, err
|
||||
}
|
||||
return result{desc, data_sz, duration, reps}, nil
|
||||
}
|
||||
|
||||
var divs = []time.Duration{
|
||||
time.Duration(1), time.Duration(10), time.Duration(100), time.Duration(1000)}
|
||||
|
||||
func round(d time.Duration, digits int) time.Duration {
|
||||
switch {
|
||||
case d > time.Second:
|
||||
d = d.Round(time.Second / divs[digits])
|
||||
case d > time.Millisecond:
|
||||
d = d.Round(time.Millisecond / divs[digits])
|
||||
case d > time.Microsecond:
|
||||
d = d.Round(time.Microsecond / divs[digits])
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func present_result(r result, col_width int) {
|
||||
rate := float64(r.data_sz) / r.duration.Seconds()
|
||||
rate /= 1024. * 1024.
|
||||
f := fmt.Sprintf("%%-%ds", col_width)
|
||||
fmt.Printf(" "+f+" : %-10v @ \x1b[32m%-7.1f\x1b[m MB/s\n", r.desc, round(r.duration, 2), rate)
|
||||
}
|
||||
|
||||
func all_benchamrks() []string {
|
||||
return []string{
|
||||
"ascii", "unicode", "unique_unicode", "csi", "images", "long_escape_codes",
|
||||
}
|
||||
}
|
||||
|
||||
func warmup_data() string {
|
||||
num_colors := 1000 + rand.IntN(1001)
|
||||
type rgb struct{ r, g, b uint8 }
|
||||
colors := make([]rgb, num_colors)
|
||||
for i := range colors {
|
||||
colors[i] = rgb{uint8(rand.IntN(256)), uint8(rand.IntN(256)), uint8(rand.IntN(256))}
|
||||
}
|
||||
colored_text := ascii_printable + control_chars + chinese_lorem_ipsum
|
||||
var b strings.Builder
|
||||
b.Grow(len(colored_text)*20 + len(misc_unicode) + 8)
|
||||
color_idx := 0
|
||||
for _, ch := range colored_text {
|
||||
c := colors[color_idx%num_colors]
|
||||
fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm%c", c.r, c.g, c.b, ch)
|
||||
color_idx++
|
||||
}
|
||||
b.WriteString("\x1b[m")
|
||||
b.WriteString(misc_unicode)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func main(args []string) (err error) {
|
||||
if len(args) == 0 {
|
||||
args = all_benchamrks()
|
||||
}
|
||||
var results []result
|
||||
var r result
|
||||
// First warm up the terminal by getting it to render all chars so that font rendering
|
||||
// time is not polluting the benchmarks.
|
||||
w := Options{Repetitions: 1}
|
||||
if _, _, _, err = benchmark_data("Warmup", warmup_data(), w); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(time.Second / 2)
|
||||
|
||||
if slices.Index(args, "ascii") >= 0 {
|
||||
if r, err = simple_ascii(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
if slices.Index(args, "unicode") >= 0 {
|
||||
if r, err = unicode(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
if slices.Index(args, "unique_unicode") >= 0 {
|
||||
if r, err = unique_unicode(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
if slices.Index(args, "csi") >= 0 {
|
||||
if r, err = ascii_with_csi(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
if slices.Index(args, "long_escape_codes") >= 0 {
|
||||
if r, err = long_escape_codes(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
if slices.Index(args, "images") >= 0 {
|
||||
if r, err = images(); err != nil {
|
||||
return err
|
||||
}
|
||||
results = append(results, r)
|
||||
}
|
||||
|
||||
fmt.Print(reset)
|
||||
fmt.Println(
|
||||
"These results measure the time it takes the terminal to fully parse all the data sent to it.")
|
||||
if opts.Render {
|
||||
fmt.Println("Note that not all data transmitted will be displayed as input parsing is typically asynchronous with rendering in high performance terminals.")
|
||||
} else {
|
||||
fmt.Println("Note that \x1b[31mrendering is suppressed\x1b[m (if the terminal supports the synchronized output escape code) to better benchmark parser performance. Use the --render flag to enable rendering.")
|
||||
}
|
||||
fmt.Println()
|
||||
fmt.Println("Results:")
|
||||
mlen := 10
|
||||
for _, r := range results {
|
||||
mlen = max(mlen, len(r.desc))
|
||||
}
|
||||
for _, r := range results {
|
||||
present_result(r, mlen)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) {
|
||||
sc := root.AddSubCommand(&cli.Command{
|
||||
Name: "__benchmark__",
|
||||
ShortDescription: "Run various benchmarks",
|
||||
HelpText: "To run only particular benchmarks, specify them on the command line from the set: " + strings.Join(all_benchamrks(), ", ") + ". Benchmarking works by sending large amount of data to the TTY device and waiting for the terminal to process the data and respond to queries sent to it in the data. By default rendering is suppressed during benchmarking to focus on parser performance. Use the --render flag to enable it, but be aware that rendering in modern terminals is typically asynchronous so it wont be properly benchmarked by this kitten.",
|
||||
Usage: "[options] [optional benchmark to run ...]",
|
||||
Hidden: true,
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
if err = cmd.GetOptionValues(&opts); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
opts.Repetitions = max(1, opts.Repetitions)
|
||||
if err = main(args); err != nil {
|
||||
ret = 1
|
||||
}
|
||||
return
|
||||
},
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--repetitions",
|
||||
Default: "500",
|
||||
Type: "int",
|
||||
Help: "The number of repetitions of each benchmark",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--with-scrollback",
|
||||
Type: "bool-set",
|
||||
Help: "Use the main screen instead of the alt screen so speed of scrollback is also tested",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--render",
|
||||
Type: "bool-set",
|
||||
Help: "Allow rendering of the data sent during tests. Note that modern terminals render asynchronously, so timings do not generally reflect render performance.",
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package completion
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
kitty_constants "github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/themes"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func complete_kitty_override(completions *cli.Completions, word string, arg_num int) {
|
||||
mg := completions.AddMatchGroup("Config directives")
|
||||
mg.NoTrailingSpace = true
|
||||
scanner := utils.NewLineScanner(kitty_constants.OptionNames)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if strings.HasPrefix(line, word) {
|
||||
mg.AddMatch(line + "=")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func complete_kitty_listen_on(completions *cli.Completions, word string, arg_num int) {
|
||||
if !strings.Contains(word, ":") {
|
||||
mg := completions.AddMatchGroup("Address family")
|
||||
mg.NoTrailingSpace = true
|
||||
for _, q := range []string{"unix:", "tcp:"} {
|
||||
if strings.HasPrefix(q, word) {
|
||||
mg.AddMatch(q)
|
||||
}
|
||||
}
|
||||
} else if strings.HasPrefix(word, "unix:") && !strings.HasPrefix(word, "unix:@") {
|
||||
cli.FnmatchCompleter("UNIX sockets", cli.CWD, "*")(completions, word[len("unix:"):], arg_num)
|
||||
completions.AddPrefixToAllMatches("unix:")
|
||||
}
|
||||
}
|
||||
|
||||
func complete_plus_launch(completions *cli.Completions, word string, arg_num int) {
|
||||
if arg_num == 1 {
|
||||
cli.FnmatchCompleter("Python scripts", cli.CWD, "*.py")(completions, word, arg_num)
|
||||
if strings.HasPrefix(word, ":") {
|
||||
exes := cli.CompleteExecutablesInPath(word[1:])
|
||||
mg := completions.AddMatchGroup("Python scripts in PATH")
|
||||
for _, exe := range exes {
|
||||
mg.AddMatch(":" + exe)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cli.FnmatchCompleter("Files", cli.CWD, "*")(completions, word, arg_num)
|
||||
}
|
||||
}
|
||||
|
||||
func complete_plus_runpy(completions *cli.Completions, word string, arg_num int) {
|
||||
if arg_num > 1 {
|
||||
cli.FnmatchCompleter("Files", cli.CWD, "*")(completions, word, arg_num)
|
||||
}
|
||||
}
|
||||
|
||||
func complete_plus_open(completions *cli.Completions, word string, arg_num int) {
|
||||
cli.FnmatchCompleter("Files", cli.CWD, "*")(completions, word, arg_num)
|
||||
}
|
||||
|
||||
func complete_themes(completions *cli.Completions, word string, arg_num int) {
|
||||
themes.CompleteThemes(completions, word, arg_num)
|
||||
}
|
||||
|
||||
func EntryPoint(tool_root *cli.Command) {
|
||||
tool_root.AddSubCommand(&cli.Command{
|
||||
Name: "__complete__", Hidden: true,
|
||||
Usage: "output_type [shell state...]",
|
||||
ShortDescription: "Generate completions for kitty commands",
|
||||
HelpText: "Generate completion candidates for kitty commands. The command line is read from STDIN. output_type can be one of the supported shells: :code:`zsh`, :code:`fish`, :code:`bash`, or :code:`setup` for completion setup script following with the shell name, or :code:`json` for JSON output.",
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
return ret, cli.GenerateCompletions(args)
|
||||
},
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package edit_in_kitty
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"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/humanize"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func encode(x string) string {
|
||||
return base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(x))
|
||||
}
|
||||
|
||||
type OnDataCallback = func(data_type string, data []byte) error
|
||||
|
||||
func edit_loop(data_to_send string, kill_if_signaled bool, on_data OnDataCallback) (exit_code int, err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
current_text := strings.Builder{}
|
||||
data := strings.Builder{}
|
||||
data.Grow(4096)
|
||||
started := false
|
||||
canceled := false
|
||||
update_type := ""
|
||||
|
||||
handle_line := func(line string) error {
|
||||
if canceled {
|
||||
return nil
|
||||
}
|
||||
if started {
|
||||
if update_type == "" {
|
||||
update_type = line
|
||||
} else {
|
||||
if line == "KITTY_DATA_END" {
|
||||
lp.QueueWriteString(update_type + "\r\n")
|
||||
if update_type == "DONE" {
|
||||
// Parse the editor exit code from the data payload.
|
||||
// Decoding errors are intentionally ignored: if the data is
|
||||
// missing or malformed (e.g. from an older kitty server),
|
||||
// we fall back to exit_code=0 for backward compatibility.
|
||||
if data.Len() > 0 {
|
||||
if b, err2 := base64.StdEncoding.DecodeString(data.String()); err2 == nil {
|
||||
if n, err3 := strconv.Atoi(strings.TrimSpace(string(b))); err3 == nil {
|
||||
exit_code = n
|
||||
}
|
||||
}
|
||||
}
|
||||
lp.Quit(exit_code)
|
||||
return nil
|
||||
}
|
||||
b, err := base64.StdEncoding.DecodeString(data.String())
|
||||
data.Reset()
|
||||
data.Grow(4096)
|
||||
started = false
|
||||
if err == nil {
|
||||
err = on_data(update_type, b)
|
||||
}
|
||||
update_type = ""
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
data.WriteString(line)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if line == "KITTY_DATA_START" {
|
||||
started = true
|
||||
update_type = ""
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
check_for_line := func() error {
|
||||
if canceled {
|
||||
return nil
|
||||
}
|
||||
s := current_text.String()
|
||||
for {
|
||||
idx := strings.Index(s, "\n")
|
||||
if idx < 0 {
|
||||
break
|
||||
}
|
||||
err = handle_line(s[:idx])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = s[idx+1:]
|
||||
}
|
||||
current_text.Reset()
|
||||
current_text.Grow(4096)
|
||||
if s != "" {
|
||||
current_text.WriteString(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
pos, chunk_num := 0, 0
|
||||
for {
|
||||
limit := min(pos+2048, len(data_to_send))
|
||||
if limit <= pos {
|
||||
break
|
||||
}
|
||||
lp.QueueWriteString("\x1bP@kitty-edit|" + strconv.Itoa(chunk_num) + ":")
|
||||
lp.QueueWriteString(data_to_send[pos:limit])
|
||||
lp.QueueWriteString("\x1b\\")
|
||||
chunk_num++
|
||||
pos = limit
|
||||
}
|
||||
lp.QueueWriteString("\x1bP@kitty-edit|\x1b\\")
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, from_key_event bool, in_bracketed_paste bool) error {
|
||||
if !from_key_event {
|
||||
current_text.WriteString(text)
|
||||
err = check_for_line()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const abort_msg = "\x1bP@kitty-edit|0:abort_signaled=interrupt\x1b\\\x1bP@kitty-edit|\x1b\\"
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
canceled = true
|
||||
lp.QueueWriteString(abort_msg)
|
||||
if !started {
|
||||
return tui.Canceled
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if canceled {
|
||||
return 1, tui.Canceled
|
||||
}
|
||||
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Print(abort_msg)
|
||||
if kill_if_signaled {
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
return 1, &tui.KilledBySignal{Msg: fmt.Sprint("Killed by signal: ", ds), SignalName: ds}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func edit_in_kitty(path string, opts *Options) (exit_code int, err error) {
|
||||
read_file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to open %s for reading with error: %w", path, err)
|
||||
}
|
||||
defer read_file.Close()
|
||||
var s unix.Stat_t
|
||||
err = unix.Fstat(int(read_file.Fd()), &s)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to stat %s with error: %w", path, err)
|
||||
}
|
||||
if s.Size > int64(opts.MaxFileSize)*1024*1024 {
|
||||
return 1, fmt.Errorf("File size %s is too large for performant editing", humanize.Bytes(uint64(s.Size)))
|
||||
}
|
||||
|
||||
file_data, err := io.ReadAll(read_file)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to read from %s with error: %w", path, err)
|
||||
}
|
||||
read_file.Close()
|
||||
data := strings.Builder{}
|
||||
data.Grow(len(file_data) * 4)
|
||||
|
||||
add := func(key, val string) {
|
||||
if data.Len() > 0 {
|
||||
data.WriteString(",")
|
||||
}
|
||||
data.WriteString(key)
|
||||
data.WriteString("=")
|
||||
data.WriteString(val)
|
||||
}
|
||||
add_encoded := func(key, val string) { add(key, encode(val)) }
|
||||
|
||||
if unix.Access(path, unix.R_OK|unix.W_OK) != nil {
|
||||
return 1, fmt.Errorf("%s is not readable and writeable", path)
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to get the current working directory with error: %w", err)
|
||||
}
|
||||
add_encoded("cwd", cwd)
|
||||
for _, arg := range os.Args[2:] {
|
||||
add_encoded("a", arg)
|
||||
}
|
||||
add("file_inode", fmt.Sprintf("%d:%d:%d", s.Dev, s.Ino, s.Mtim.Nano()))
|
||||
add_encoded("file_data", utils.UnsafeBytesToString(file_data))
|
||||
fmt.Println("Waiting for editing to be completed, press Esc to abort...")
|
||||
write_data := func(data_type string, rdata []byte) (err error) {
|
||||
err = utils.AtomicWriteFile(path, bytes.NewReader(rdata), fs.FileMode(s.Mode).Perm())
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to write data to %s with error: %w", path, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
exit_code, err = edit_loop(data.String(), true, write_data)
|
||||
if err != nil {
|
||||
if err == tui.Canceled {
|
||||
return 1, err
|
||||
}
|
||||
return 1, fmt.Errorf("Failed to receive edited file back from terminal with error: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
MaxFileSize int
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) *cli.Command {
|
||||
sc := parent.AddSubCommand(&cli.Command{
|
||||
Name: "edit-in-kitty",
|
||||
Usage: "[options] [+lnum] file-to-edit",
|
||||
ShortDescription: "Edit a file in a kitty overlay window",
|
||||
HelpText: "Edit the specified file in a kitty overlay window. Works over SSH as well.\n\n" +
|
||||
"For usage instructions see: https://sw.kovidgoyal.net/kitty/shell-integration/#edit-file",
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "Usage:", cmd.Usage)
|
||||
return 1, fmt.Errorf("No file to edit specified.")
|
||||
}
|
||||
|
||||
var file_path string
|
||||
if len(args) == 1 {
|
||||
file_path = args[0]
|
||||
} else if len(args) == 2 && strings.HasPrefix(args[0], "+") {
|
||||
var lnum string
|
||||
lnum, file_path = args[0][1:], args[1]
|
||||
if _, err := strconv.Atoi(lnum); err != nil {
|
||||
return 1, fmt.Errorf("Invalid line number %s", lnum)
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintln(os.Stderr, "Usage:", cmd.Usage)
|
||||
return 1, fmt.Errorf("Only one file to edit and optionally a line number must be specified")
|
||||
}
|
||||
|
||||
var opts Options
|
||||
err = cmd.GetOptionValues(&opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return edit_in_kitty(file_path, &opts)
|
||||
},
|
||||
})
|
||||
AddCloneSafeOpts(sc)
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--max-file-size",
|
||||
Default: "8",
|
||||
Type: "int",
|
||||
Help: "The maximum allowed size (in MB) of files to edit. Since the file data has to be base64 encoded and transmitted over the tty device, overly large files will not perform well.",
|
||||
})
|
||||
return sc
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/ssh"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/completion"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/tool"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func KittenMain(args ...string) int {
|
||||
defer utils.WaitForAtexitWorkerToFinish()
|
||||
krm := os.Getenv("KITTY_KITTEN_RUN_MODULE")
|
||||
os.Unsetenv("KITTY_KITTEN_RUN_MODULE")
|
||||
switch krm {
|
||||
case "ssh_askpass":
|
||||
return ssh.RunSSHAskpass()
|
||||
}
|
||||
root := cli.NewRootCommand()
|
||||
root.ShortDescription = "Fast, statically compiled implementations of various kittens (command line tools for use with kitty)"
|
||||
root.HelpText = "kitten serves as a launcher for running individual kittens. Each kitten can be run as :code:`kitten command`. The list of available kittens is given below."
|
||||
root.Usage = "command [command options] [command args]"
|
||||
root.Run = func(cmd *cli.Command, args []string) (int, error) {
|
||||
if len(args) == 0 {
|
||||
cmd.ShowHelp()
|
||||
return 0, nil
|
||||
}
|
||||
if strings.HasSuffix(args[0], ".py") {
|
||||
exe := utils.KittyExe()
|
||||
if !filepath.IsAbs(exe) {
|
||||
exe = utils.Which(exe)
|
||||
}
|
||||
if err := unix.Exec(exe, append([]string{filepath.Base(exe), "+kitten"}, args...), os.Environ()); err != nil {
|
||||
return 1, fmt.Errorf("failed to run python kitten: %s as could not run kitty executable, with error: %w", args[0], err)
|
||||
}
|
||||
}
|
||||
return 1, fmt.Errorf(":yellow:`%s` is not a known kitten. Use --help to get a list of known kittens.", args[0])
|
||||
}
|
||||
|
||||
tool.KittyToolEntryPoints(root)
|
||||
completion.EntryPoint(root)
|
||||
|
||||
root.SubCommandIsOptional = true
|
||||
return root.ExecArgs(args)
|
||||
}
|
||||
|
||||
func main() {
|
||||
os.Exit(KittenMain())
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package mouse_demo
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
// file_info holds metadata about a dropped file.
|
||||
type file_info struct {
|
||||
name string
|
||||
size int64
|
||||
is_dir bool
|
||||
is_link bool
|
||||
err_msg string
|
||||
}
|
||||
|
||||
type dnd_state struct {
|
||||
dragging bool
|
||||
drag_mimes []string
|
||||
// Current drag cell position (set from t=m events).
|
||||
drag_cell_x int
|
||||
drag_cell_y int
|
||||
drag_over_box bool // true when the drag is currently over the drop region
|
||||
|
||||
// Drop handling.
|
||||
drop_mimes []string
|
||||
uri_list_mime_idx int // 1-based index of text/uri-list in drop_mimes (0 = not present)
|
||||
is_remote bool // X=1 received in URI list response (client is on different machine)
|
||||
|
||||
// Collection state: what we're currently collecting.
|
||||
// Values: "", "text/plain", "text/uri-list", "file"
|
||||
collecting string
|
||||
collect_buf strings.Builder
|
||||
|
||||
// Results of drop.
|
||||
plain_text string
|
||||
uri_list []string // parsed file:// URIs from text/uri-list
|
||||
file_infos []file_info // one entry per uri_list entry
|
||||
has_drop_data bool
|
||||
|
||||
// File reading state.
|
||||
file_read_idx int // 1-based index of file currently being read (0 = not reading files)
|
||||
file_read_size int64 // bytes accumulated so far for current file
|
||||
|
||||
// Layout: drop box position on screen (set during draw_screen).
|
||||
drop_box_start_row int
|
||||
drop_box_end_row int
|
||||
drop_box_width int
|
||||
}
|
||||
|
||||
func (d *dnd_state) reset_drag() {
|
||||
d.dragging = false
|
||||
d.drag_over_box = false
|
||||
d.drag_mimes = nil
|
||||
}
|
||||
|
||||
func (d *dnd_state) reset_drop_data() {
|
||||
d.drop_mimes = nil
|
||||
d.uri_list_mime_idx = 0
|
||||
d.is_remote = false
|
||||
d.collecting = ""
|
||||
d.collect_buf.Reset()
|
||||
d.plain_text = ""
|
||||
d.uri_list = nil
|
||||
d.file_infos = nil
|
||||
d.has_drop_data = false
|
||||
d.file_read_idx = 0
|
||||
d.file_read_size = 0
|
||||
}
|
||||
|
||||
// is_over_drop_box returns true if the given cell coordinates are within the
|
||||
// drop box region as tracked from the last draw_screen call.
|
||||
func (d *dnd_state) is_over_drop_box(cell_x, cell_y int) bool {
|
||||
// Before the first draw, drop_box_end_row equals drop_box_start_row (both zero).
|
||||
if d.drop_box_end_row <= d.drop_box_start_row {
|
||||
return false
|
||||
}
|
||||
return cell_y >= d.drop_box_start_row && cell_y <= d.drop_box_end_row &&
|
||||
cell_x >= 0 && cell_x < d.drop_box_width
|
||||
}
|
||||
|
||||
// filename_from_uri extracts the base filename from a file:// URI.
|
||||
func filename_from_uri(uri string) string {
|
||||
u, err := url.Parse(uri)
|
||||
if err != nil || u.Scheme != "file" {
|
||||
return uri
|
||||
}
|
||||
return filepath.Base(u.Path)
|
||||
}
|
||||
|
||||
// format_size formats a byte count as a human-readable size string.
|
||||
func format_size(n int64) string {
|
||||
switch {
|
||||
case n < 1024:
|
||||
return fmt.Sprintf("%d B", n)
|
||||
case n < 1024*1024:
|
||||
return fmt.Sprintf("%.1f KiB", float64(n)/1024)
|
||||
case n < 1024*1024*1024:
|
||||
return fmt.Sprintf("%.1f MiB", float64(n)/(1024*1024))
|
||||
default:
|
||||
return fmt.Sprintf("%.1f GiB", float64(n)/(1024*1024*1024))
|
||||
}
|
||||
}
|
||||
|
||||
func draw_rounded_box(lp *loop.Loop, width int, lines []string) {
|
||||
if width < 4 {
|
||||
width = 4
|
||||
}
|
||||
inner_width := width - 2
|
||||
// Top border
|
||||
lp.QueueWriteString("╭" + strings.Repeat("─", inner_width) + "╮\r\n")
|
||||
for _, line := range lines {
|
||||
// Truncate to inner_width runes (not bytes) to handle multi-byte chars safely.
|
||||
runes := []rune(line)
|
||||
if len(runes) > inner_width {
|
||||
runes = runes[:inner_width]
|
||||
}
|
||||
padding := inner_width - len(runes)
|
||||
lp.QueueWriteString("│" + string(runes) + strings.Repeat(" ", padding) + "│\r\n")
|
||||
}
|
||||
// Bottom border
|
||||
lp.QueueWriteString("╰" + strings.Repeat("─", inner_width) + "╯\r\n")
|
||||
}
|
||||
|
||||
func Run(args []string) (rc int, err error) {
|
||||
all_pointer_shapes := []loop.PointerShape{
|
||||
// start all pointer shapes (auto generated by gen-key-constants.py do not edit)
|
||||
loop.DEFAULT_POINTER,
|
||||
loop.TEXT_POINTER,
|
||||
loop.POINTER_POINTER,
|
||||
loop.HELP_POINTER,
|
||||
loop.WAIT_POINTER,
|
||||
loop.PROGRESS_POINTER,
|
||||
loop.CROSSHAIR_POINTER,
|
||||
loop.CELL_POINTER,
|
||||
loop.VERTICAL_TEXT_POINTER,
|
||||
loop.MOVE_POINTER,
|
||||
loop.E_RESIZE_POINTER,
|
||||
loop.NE_RESIZE_POINTER,
|
||||
loop.NW_RESIZE_POINTER,
|
||||
loop.N_RESIZE_POINTER,
|
||||
loop.SE_RESIZE_POINTER,
|
||||
loop.SW_RESIZE_POINTER,
|
||||
loop.S_RESIZE_POINTER,
|
||||
loop.W_RESIZE_POINTER,
|
||||
loop.EW_RESIZE_POINTER,
|
||||
loop.NS_RESIZE_POINTER,
|
||||
loop.NESW_RESIZE_POINTER,
|
||||
loop.NWSE_RESIZE_POINTER,
|
||||
loop.ZOOM_IN_POINTER,
|
||||
loop.ZOOM_OUT_POINTER,
|
||||
loop.ALIAS_POINTER,
|
||||
loop.COPY_POINTER,
|
||||
loop.NOT_ALLOWED_POINTER,
|
||||
loop.NO_DROP_POINTER,
|
||||
loop.GRAB_POINTER,
|
||||
loop.GRABBING_POINTER,
|
||||
// end all pointer shapes
|
||||
}
|
||||
all_pointer_shape_names := make([]string, len(all_pointer_shapes))
|
||||
col_width := 0
|
||||
for i, p := range all_pointer_shapes {
|
||||
all_pointer_shape_names[i] = p.String()
|
||||
col_width = max(col_width, len(all_pointer_shape_names[i]))
|
||||
}
|
||||
col_width += 1
|
||||
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||
var current_mouse_event *loop.MouseEvent
|
||||
var dnd dnd_state
|
||||
|
||||
// build_box_lines computes the drop box content lines based on current state.
|
||||
build_box_lines := func() []string {
|
||||
if dnd.drag_over_box {
|
||||
lines := []string{"Drop here! MIME types:"}
|
||||
for _, m := range dnd.drag_mimes {
|
||||
lines = append(lines, " "+m)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
if dnd.dragging {
|
||||
return []string{"Drag in window — move over this box to drop"}
|
||||
}
|
||||
if dnd.has_drop_data {
|
||||
lines := []string{}
|
||||
if dnd.plain_text != "" {
|
||||
lines = append(lines, "text/plain: "+dnd.plain_text)
|
||||
}
|
||||
if len(dnd.file_infos) > 0 {
|
||||
for i, fi := range dnd.file_infos {
|
||||
if i >= len(dnd.uri_list) {
|
||||
break
|
||||
}
|
||||
name := filename_from_uri(dnd.uri_list[i])
|
||||
if fi.err_msg != "" {
|
||||
lines = append(lines, name+": error: "+fi.err_msg)
|
||||
} else if fi.is_dir {
|
||||
lines = append(lines, name+"/ [directory]")
|
||||
} else if fi.is_link {
|
||||
lines = append(lines, name+" [symlink]")
|
||||
} else {
|
||||
lines = append(lines, name+" "+format_size(fi.size))
|
||||
}
|
||||
}
|
||||
} else if len(dnd.uri_list) > 0 {
|
||||
for _, u := range dnd.uri_list {
|
||||
lines = append(lines, " "+u)
|
||||
}
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
lines = []string{"Drop received (no recognized content)"}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
return []string{"Drop files here"}
|
||||
}
|
||||
|
||||
draw_screen := func() {
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
lp.AllowLineWrapping(false)
|
||||
defer lp.AllowLineWrapping(true)
|
||||
lp.ClearScreen()
|
||||
|
||||
sw := 80
|
||||
sh := 24
|
||||
if s, err := lp.ScreenSize(); err == nil {
|
||||
sw = int(s.WidthCells)
|
||||
sh = int(s.HeightCells)
|
||||
}
|
||||
|
||||
// y tracks the next row to be printed; used for both content drawing
|
||||
// and computing the drop box position.
|
||||
y := 0
|
||||
|
||||
if current_mouse_event == nil {
|
||||
lp.Println(`Move the mouse or click to see mouse events`)
|
||||
y++
|
||||
lp.Println("Hover the mouse over the names below to see the shapes")
|
||||
y++
|
||||
lp.Println()
|
||||
y++
|
||||
num_cols := max(1, sw/col_width)
|
||||
colfmt := "%-" + strconv.Itoa(col_width) + "s"
|
||||
for pos := 0; pos < len(all_pointer_shapes); {
|
||||
for c := 0; c < num_cols && pos < len(all_pointer_shapes); c++ {
|
||||
lp.Printf(colfmt, all_pointer_shape_names[pos])
|
||||
pos++
|
||||
}
|
||||
lp.Println()
|
||||
y++
|
||||
}
|
||||
} else if current_mouse_event.Event_type == loop.MOUSE_LEAVE {
|
||||
lp.Println("Mouse has left the window")
|
||||
y++
|
||||
} else {
|
||||
lp.Printf("Position: %d, %d (pixels)\r\n", current_mouse_event.Pixel.X, current_mouse_event.Pixel.Y)
|
||||
y++
|
||||
lp.Printf("Cell : %d, %d\r\n", current_mouse_event.Cell.X, current_mouse_event.Cell.Y)
|
||||
y++
|
||||
lp.Printf("Type : %s\r\n", current_mouse_event.Event_type)
|
||||
y++
|
||||
if current_mouse_event.Buttons != loop.NO_MOUSE_BUTTON {
|
||||
lp.Println(current_mouse_event.Buttons.String())
|
||||
y++
|
||||
}
|
||||
if mods := current_mouse_event.Mods.String(); mods != "" {
|
||||
lp.Printf("Modifiers: %s\r\n", mods)
|
||||
y++
|
||||
}
|
||||
lp.Println("Hover the mouse over the names below to see the shapes")
|
||||
y++
|
||||
|
||||
num_cols := max(1, sw/col_width)
|
||||
pos := 0
|
||||
colfmt := "%-" + strconv.Itoa(col_width) + "s"
|
||||
is_on_name := false
|
||||
var ps loop.PointerShape
|
||||
for y < sh && pos < len(all_pointer_shapes) {
|
||||
is_row := y == current_mouse_event.Cell.Y
|
||||
for c := 0; c < num_cols && pos < len(all_pointer_shapes); c++ {
|
||||
name := all_pointer_shape_names[pos]
|
||||
is_hovered := false
|
||||
if is_row {
|
||||
start_x := c * col_width
|
||||
x := current_mouse_event.Cell.X
|
||||
if x < start_x+len(name) && x >= start_x {
|
||||
is_on_name = true
|
||||
is_hovered = true
|
||||
ps = all_pointer_shapes[pos]
|
||||
}
|
||||
}
|
||||
if is_hovered {
|
||||
lp.QueueWriteString("\x1b[31m")
|
||||
}
|
||||
lp.Printf(colfmt, name)
|
||||
lp.QueueWriteString("\x1b[m")
|
||||
pos++
|
||||
}
|
||||
y++
|
||||
lp.Println()
|
||||
}
|
||||
lp.PopPointerShape()
|
||||
if is_on_name {
|
||||
lp.PushPointerShape(ps)
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the drop area below the pointer shapes list.
|
||||
// y is now the row where the blank separator will be printed.
|
||||
lp.Println()
|
||||
y++ // blank separator line
|
||||
|
||||
box_width := min(sw, 60)
|
||||
dnd.drop_box_width = box_width
|
||||
box_lines := build_box_lines()
|
||||
dnd.drop_box_start_row = y
|
||||
dnd.drop_box_end_row = y + len(box_lines) + 1 // top border + lines + bottom border
|
||||
|
||||
if dnd.drag_over_box {
|
||||
// Highlight the box in green when drag is over it.
|
||||
lp.QueueWriteString("\x1b[32m")
|
||||
draw_rounded_box(lp, box_width, box_lines)
|
||||
lp.QueueWriteString("\x1b[m")
|
||||
} else {
|
||||
draw_rounded_box(lp, box_width, box_lines)
|
||||
}
|
||||
}
|
||||
|
||||
// start_next_file_request sends a request for the next unread file URI,
|
||||
// or finishes the drop if all files have been read.
|
||||
var start_next_file_request func()
|
||||
start_next_file_request = func() {
|
||||
for dnd.file_read_idx < len(dnd.uri_list) {
|
||||
uri := dnd.uri_list[dnd.file_read_idx]
|
||||
if strings.HasPrefix(uri, "file://") {
|
||||
// Request this file via the protocol.
|
||||
dnd.file_read_size = 0
|
||||
dnd.collecting = "file"
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r', X: dnd.uri_list_mime_idx, Y: dnd.file_read_idx + 1})
|
||||
return
|
||||
}
|
||||
// Non-file URI: record as-is with no size info.
|
||||
dnd.file_infos = append(dnd.file_infos, file_info{name: uri})
|
||||
dnd.file_read_idx++
|
||||
}
|
||||
// All files processed; finish the drop.
|
||||
dnd.collecting = ""
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r'})
|
||||
dnd.has_drop_data = true
|
||||
draw_screen()
|
||||
}
|
||||
|
||||
handle_dnd_cmd := func(cmd loop.DndCommand) error {
|
||||
switch cmd.Type {
|
||||
case 'm':
|
||||
// Drag move event from terminal.
|
||||
// Check if drag has left the window (x=-1, y=-1).
|
||||
if cmd.X == -1 || cmd.Y == -1 {
|
||||
dnd.reset_drag()
|
||||
draw_screen()
|
||||
return nil
|
||||
}
|
||||
mimes := strings.Fields(string(cmd.Payload))
|
||||
if len(mimes) > 0 {
|
||||
dnd.drag_mimes = mimes
|
||||
}
|
||||
dnd.dragging = true
|
||||
dnd.drag_cell_x = cmd.X
|
||||
dnd.drag_cell_y = cmd.Y
|
||||
|
||||
over_box := dnd.is_over_drop_box(cmd.X, cmd.Y)
|
||||
dnd.drag_over_box = over_box
|
||||
|
||||
if over_box {
|
||||
// Accept the drag with copy operation for supported MIME types.
|
||||
accepted_mimes := []string{}
|
||||
for _, m := range dnd.drag_mimes {
|
||||
if m == "text/plain" || m == "text/uri-list" {
|
||||
accepted_mimes = append(accepted_mimes, m)
|
||||
}
|
||||
}
|
||||
if len(accepted_mimes) > 0 {
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'm', Operation: 1, Payload: []byte(strings.Join(accepted_mimes, " "))})
|
||||
}
|
||||
} else {
|
||||
// Not over drop region; reject the drag.
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'm'})
|
||||
}
|
||||
draw_screen()
|
||||
case 'M':
|
||||
// Drop event from terminal.
|
||||
dnd.reset_drag()
|
||||
dnd.reset_drop_data()
|
||||
mimes := strings.Fields(string(cmd.Payload))
|
||||
dnd.drop_mimes = mimes
|
||||
|
||||
// Find the MIME indices we need.
|
||||
for i, m := range mimes {
|
||||
if m == "text/uri-list" {
|
||||
dnd.uri_list_mime_idx = i + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Request data: text/plain first, then text/uri-list.
|
||||
for idx, m := range mimes {
|
||||
if m == "text/plain" {
|
||||
dnd.collecting = "text/plain"
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r', X: idx + 1})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if dnd.uri_list_mime_idx > 0 {
|
||||
dnd.collecting = "text/uri-list"
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r', X: dnd.uri_list_mime_idx})
|
||||
return nil
|
||||
}
|
||||
// Nothing to collect; signal done.
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r'})
|
||||
dnd.has_drop_data = true
|
||||
draw_screen()
|
||||
case 'r':
|
||||
// Data response from terminal.
|
||||
is_file_response := cmd.Y != 0
|
||||
if is_file_response {
|
||||
// Response for an individual file request (t=r:x=idx:y=subidx).
|
||||
if !cmd.Has_more && len(cmd.Payload) == 0 {
|
||||
// End of file data.
|
||||
fi := file_info{}
|
||||
if cmd.Xp > 1 {
|
||||
// Directory: close the handle.
|
||||
fi.is_dir = true
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r', Yp: cmd.Xp})
|
||||
} else if cmd.Xp == 1 {
|
||||
fi.is_link = true
|
||||
fi.size = dnd.file_read_size
|
||||
} else {
|
||||
fi.size = dnd.file_read_size
|
||||
}
|
||||
dnd.file_infos = append(dnd.file_infos, fi)
|
||||
dnd.file_read_idx++
|
||||
draw_screen()
|
||||
start_next_file_request()
|
||||
} else {
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(string(cmd.Payload))
|
||||
if err == nil {
|
||||
dnd.file_read_size += int64(len(decoded))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Response for a MIME type data request.
|
||||
if !cmd.Has_more && len(cmd.Payload) == 0 {
|
||||
// End of MIME type data.
|
||||
switch dnd.collecting {
|
||||
case "text/plain":
|
||||
text := dnd.collect_buf.String()
|
||||
text = strings.TrimRight(text, "\r\n")
|
||||
if before, _, ok := strings.Cut(text, "\n"); ok {
|
||||
dnd.plain_text = strings.TrimRight(before, "\r")
|
||||
} else {
|
||||
dnd.plain_text = text
|
||||
}
|
||||
dnd.collect_buf.Reset()
|
||||
// Now request text/uri-list if available.
|
||||
if dnd.uri_list_mime_idx > 0 {
|
||||
dnd.collecting = "text/uri-list"
|
||||
lp.QueueDnDData(
|
||||
loop.DndCommand{Type: 'r', X: dnd.uri_list_mime_idx})
|
||||
return nil
|
||||
}
|
||||
case "text/uri-list":
|
||||
text := dnd.collect_buf.String()
|
||||
dnd.collect_buf.Reset()
|
||||
// Check if terminal indicated remote files (X=1 in URI list response).
|
||||
if cmd.Xp == 1 {
|
||||
dnd.is_remote = true
|
||||
}
|
||||
// Parse URI list: lines starting with # are comments.
|
||||
for line := range strings.SplitSeq(text, "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if line != "" && !strings.HasPrefix(line, "#") {
|
||||
dnd.uri_list = append(dnd.uri_list, line)
|
||||
}
|
||||
}
|
||||
// Start reading individual files.
|
||||
if len(dnd.uri_list) > 0 && dnd.uri_list_mime_idx > 0 {
|
||||
dnd.file_read_idx = 0
|
||||
start_next_file_request()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
dnd.collecting = ""
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r'})
|
||||
dnd.has_drop_data = true
|
||||
draw_screen()
|
||||
} else {
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(string(cmd.Payload))
|
||||
if err == nil {
|
||||
dnd.collect_buf.Write(decoded)
|
||||
// Capture X from URI list response (may be in first chunk).
|
||||
if dnd.collecting == "text/uri-list" && cmd.Xp != 0 {
|
||||
dnd.is_remote = cmd.Xp == 1
|
||||
}
|
||||
}
|
||||
}
|
||||
case 'R':
|
||||
// Error response from terminal.
|
||||
is_file_response := cmd.Y != 0
|
||||
if is_file_response && dnd.collecting == "file" {
|
||||
// Record the error for this file.
|
||||
dnd.file_infos = append(dnd.file_infos, file_info{err_msg: string(cmd.Payload)})
|
||||
dnd.file_read_idx++
|
||||
draw_screen()
|
||||
start_next_file_request()
|
||||
} else if !is_file_response {
|
||||
// Error getting MIME data; finish the drop with what we have.
|
||||
dnd.collecting = ""
|
||||
lp.QueueDnDData(loop.DndCommand{Type: 'r'})
|
||||
dnd.has_drop_data = true
|
||||
draw_screen()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetWindowTitle("kitty mouse features demo")
|
||||
lp.SetCursorVisible(false)
|
||||
lp.StartAcceptingDrops("", "text/plain", "text/uri-list")
|
||||
draw_screen()
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
lp.StopAcceptingDrops()
|
||||
return ""
|
||||
}
|
||||
|
||||
lp.OnMouseEvent = func(ev *loop.MouseEvent) error {
|
||||
current_mouse_event = ev
|
||||
draw_screen()
|
||||
return nil
|
||||
}
|
||||
lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
|
||||
if ev.MatchesPressOrRepeat("esc") || ev.MatchesPressOrRepeat("ctrl+c") {
|
||||
lp.Quit(0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lp.OnResize = func(old_size loop.ScreenSize, new_size loop.ScreenSize) error {
|
||||
draw_screen()
|
||||
return nil
|
||||
}
|
||||
lp.OnDnDData = handle_dnd_cmd
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package pytest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"github.com/kovidgoyal/kitty/kittens/ssh"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func test_integration_with_python(args []string) (rc int, err error) {
|
||||
switch args[0] {
|
||||
default:
|
||||
return 1, fmt.Errorf("Unknown test type: %s", args[0])
|
||||
case "read":
|
||||
data, err := shm.ReadWithSizeAndUnlink(args[1])
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
_, err = os.Stdout.Write(data)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
case "write":
|
||||
data, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
mmap, err := shm.CreateTemp("shmtest-", uint64(len(data)+shm.NUM_BYTES_FOR_SIZE))
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if err = shm.WriteWithSize(mmap, data, 0); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
mmap.Close()
|
||||
fmt.Println(mmap.Name())
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func shm_entry_point(root *cli.Command) {
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "shm",
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
return test_integration_with_python(args)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) {
|
||||
root = root.AddSubCommand(&cli.Command{
|
||||
Name: "__pytest__",
|
||||
Hidden: true,
|
||||
})
|
||||
shm_entry_point(root)
|
||||
ssh.TestEntryPoint(root)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package run_shell
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/shell_integration"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"golang.org/x/exp/slices"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Options struct {
|
||||
Shell string
|
||||
ShellIntegration string
|
||||
Env []string
|
||||
Cwd string
|
||||
InjectSelfOntoPath string
|
||||
}
|
||||
|
||||
func inject_self_onto_path() {
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
if exe_dir, err := filepath.Abs(exe); err == nil {
|
||||
realpath := func(x string) string {
|
||||
if ans, err := filepath.EvalSymlinks(x); err == nil {
|
||||
return ans
|
||||
}
|
||||
return x
|
||||
}
|
||||
exe_dir = realpath(filepath.Dir(exe_dir))
|
||||
path_items := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))
|
||||
realpath_items := utils.Map(realpath, path_items)
|
||||
done := false
|
||||
changed := false
|
||||
is_executable_file := func(q string) bool {
|
||||
if unix.Access(q, unix.X_OK) != nil {
|
||||
return false
|
||||
}
|
||||
if s, err := os.Stat(q); err == nil && !s.IsDir() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
for i, x := range realpath_items {
|
||||
q := filepath.Join(x, filepath.Base(exe))
|
||||
if is_executable_file(q) {
|
||||
// some kitten already in path
|
||||
if utils.Samefile(q, exe) {
|
||||
done = true
|
||||
break
|
||||
}
|
||||
path_items = slices.Insert(path_items, i, exe_dir)
|
||||
changed, done = true, true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !done {
|
||||
path_items = append(path_items, exe_dir)
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
os.Setenv("PATH", strings.Join(path_items, string(os.PathListSeparator)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main(args []string, opts *Options) (rc int, err error) {
|
||||
if len(args) > 0 {
|
||||
tui.RunCommandRestoringTerminalToSaneStateAfter(args)
|
||||
}
|
||||
env_before := os.Environ()
|
||||
changed := false
|
||||
for _, entry := range opts.Env {
|
||||
k, v, found := strings.Cut(entry, "=")
|
||||
if found {
|
||||
if err := os.Setenv(k, v); err != nil {
|
||||
return 1, fmt.Errorf("Failed to set the env var %s with error: %w", k, err)
|
||||
}
|
||||
} else {
|
||||
if err := os.Unsetenv(k); err != nil {
|
||||
return 1, fmt.Errorf("Failed to unset the env var %s with error: %w", k, err)
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if os.Getenv("TERM") == "" {
|
||||
os.Setenv("TERM", kitty.DefaultTermName)
|
||||
}
|
||||
if opts.InjectSelfOntoPath == "always" || (opts.InjectSelfOntoPath == "unless-root" && os.Geteuid() != 0) {
|
||||
inject_self_onto_path()
|
||||
}
|
||||
if term := os.Getenv("TERM"); term == kitty.DefaultTermName && shell_integration.PathToTerminfoDb(term) == "" {
|
||||
if terminfo_dir, err := shell_integration.EnsureTerminfoFiles(); err == nil {
|
||||
os.Unsetenv("TERMINFO")
|
||||
existing := os.Getenv("TERMINFO_DIRS")
|
||||
if existing != "" {
|
||||
existing = string(os.PathListSeparator) + existing
|
||||
}
|
||||
os.Setenv("TERMINFO_DIRS", terminfo_dir+existing)
|
||||
}
|
||||
}
|
||||
err = tui.RunShell(tui.ResolveShell(opts.Shell), tui.ResolveShellIntegration(opts.ShellIntegration), opts.Cwd)
|
||||
if changed {
|
||||
os.Clearenv()
|
||||
for _, entry := range env_before {
|
||||
k, v, _ := strings.Cut(entry, "=")
|
||||
os.Setenv(k, v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func EntryPoint(root *cli.Command) *cli.Command {
|
||||
sc := root.AddSubCommand(&cli.Command{
|
||||
Name: "run-shell",
|
||||
Usage: "[options] [optional cmd to run before running the shell ...]",
|
||||
ShortDescription: "Run the user's shell with shell integration enabled",
|
||||
HelpText: "Run the users's configured shell. If the shell supports shell integration, enable it based on the user's configured shell_integration setting.",
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
opts := &Options{}
|
||||
err = cmd.GetOptionValues(opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return main(args, opts)
|
||||
},
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--shell-integration",
|
||||
Help: "Specify a value for the :opt:`shell_integration` option, overriding the one from :file:`kitty.conf`.",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--shell",
|
||||
Default: ".",
|
||||
Help: "Specify the shell command to run. The default value of :code:`.` will use the parent shell if recognized, falling back to the value of the :opt:`shell` option from :file:`kitty.conf`.",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--env",
|
||||
Help: "Specify an env var to set before running the shell. Of the form KEY=VAL. Can be specified multiple times. If no = is present KEY is unset.",
|
||||
Type: "list",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--cwd",
|
||||
Help: "The working directory to use when executing the shell.",
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--inject-self-onto-path",
|
||||
Help: "Add the directory containing this kitten binary to PATH. Directory is added only if not already present.",
|
||||
Default: "always",
|
||||
Choices: "always,never,unless-root",
|
||||
})
|
||||
|
||||
return sc
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package show_error
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Options struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Msg string `json:"msg"`
|
||||
Traceback string `json:"tb"`
|
||||
}
|
||||
|
||||
func main(args []string, opts *Options) (rc int, err error) {
|
||||
if tty.IsTerminal(os.Stdin.Fd()) {
|
||||
return 1, fmt.Errorf("Input data for this kitten must be piped as JSON to STDIN")
|
||||
}
|
||||
data, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
m := Message{}
|
||||
err = json.Unmarshal(data, &m)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
f := markup.New(true)
|
||||
if opts.Title != "" {
|
||||
fmt.Println(f.Err(opts.Title))
|
||||
fmt.Println(loop.EscapeCodeToSetWindowTitle(opts.Title))
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Println(m.Msg)
|
||||
show_traceback := false
|
||||
if m.Traceback != "" {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
lp.QueueWriteString("\n\r\x1b[1;32mPress e to see detailed traceback or any other key to exit\x1b[m\r\n")
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.Type == loop.PRESS || event.Type == loop.REPEAT {
|
||||
if event.MatchesPressOrRepeat("e") || event.MatchesPressOrRepeat("shift+e") || event.MatchesPressOrRepeat("E") {
|
||||
show_traceback = true
|
||||
lp.Quit(0)
|
||||
} else {
|
||||
lp.Quit(1)
|
||||
}
|
||||
}
|
||||
if event.MatchesPressOrRepeat("enter") || event.MatchesPressOrRepeat("kp_enter") || event.MatchesPressOrRepeat("esc") || event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("ctrl+d") {
|
||||
event.Handled = true
|
||||
lp.Quit(0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lp.Run()
|
||||
if lp.ExitCode() == 1 {
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
if show_traceback {
|
||||
fmt.Println(m.Traceback)
|
||||
fmt.Println()
|
||||
}
|
||||
tui.HoldTillEnter(true)
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) *cli.Command {
|
||||
sc := root.AddSubCommand(&cli.Command{
|
||||
Name: "__show_error__",
|
||||
Hidden: true,
|
||||
Usage: "[options]",
|
||||
ShortDescription: "Show an error message. Internal use.",
|
||||
HelpText: "Show an error message. Used internally by kitty.",
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
opts := &Options{}
|
||||
err = cmd.GetOptionValues(opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return main(args, opts)
|
||||
},
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--title",
|
||||
Default: "ERROR",
|
||||
Help: "The title for the error message",
|
||||
})
|
||||
return sc
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tool
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/ask"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ConfirmPolicy uint8
|
||||
|
||||
const (
|
||||
ConfirmAlways = iota
|
||||
ConfirmNever
|
||||
ConfirmIfNeeded
|
||||
)
|
||||
|
||||
func ask_for_permission(script_path string) (response string, err error) {
|
||||
opts := &ask.Options{Type: "choices", Default: "n", Choices: []string{"y;green:Yes", "n;red:No", "v;yellow:View", "e;magenta:Edit"}}
|
||||
|
||||
ctx := markup.New(true)
|
||||
opts.Message = ctx.Prettify(fmt.Sprintf(
|
||||
"Attempting to execute the script: :yellow:`%s`\nExecuting untrusted scripts can be dangerous. Proceed anyway?", script_path))
|
||||
response, err = ask.GetChoices(opts)
|
||||
return response, err
|
||||
}
|
||||
|
||||
func ask_if_exe_allowed(exe_path string) (ok bool, err error) {
|
||||
opts := &ask.Options{Type: "yesno", Default: "n"}
|
||||
ctx := markup.New(true)
|
||||
opts.Message = ctx.Prettify(fmt.Sprintf(
|
||||
"Attempting to execute the program: :yellow:`%s`\nExecuting untrusted programs can be dangerous. Proceed anyway?", exe_path))
|
||||
response, err := ask.GetChoices(opts)
|
||||
return response == "y", err
|
||||
}
|
||||
|
||||
func permission_denied(script_path string) error {
|
||||
return fmt.Errorf("Execution of %s was denied by user", script_path)
|
||||
}
|
||||
|
||||
func confirm_and_run_exe(args []string) (rc int, err error) {
|
||||
exe := args[len(args)-1]
|
||||
ok, err := ask_if_exe_allowed(exe)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if ok {
|
||||
exe = utils.FindExe(args[0])
|
||||
if exe == "" {
|
||||
return 1, fmt.Errorf("Failed to find the script interpreter: %s", args[0])
|
||||
}
|
||||
if err = unix.Exec(exe, []string{exe}, os.Environ()); err != nil {
|
||||
rc = 1
|
||||
}
|
||||
} else {
|
||||
return 1, permission_denied(exe)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func confirm_and_run_shebang(args []string, confirm_policy ConfirmPolicy) (rc int, err error) {
|
||||
script_path := args[len(args)-1]
|
||||
do_confirm := true
|
||||
switch confirm_policy {
|
||||
case ConfirmNever:
|
||||
do_confirm = false
|
||||
case ConfirmAlways:
|
||||
do_confirm = true
|
||||
case ConfirmIfNeeded:
|
||||
do_confirm = unix.Access(script_path, unix.X_OK) != nil
|
||||
}
|
||||
if do_confirm {
|
||||
response, err := ask_for_permission(script_path)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
switch response {
|
||||
default:
|
||||
return 1, permission_denied(script_path)
|
||||
case "v":
|
||||
raw, err := os.ReadFile(script_path)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
cli.ShowHelpInPager(utils.UnsafeBytesToString(raw))
|
||||
// The pager might have exited automatically if there is less than
|
||||
// one screen of text, so confirm manually, here, where output from
|
||||
// pager will still be visible.
|
||||
fmt.Print("Execute the script? (y/n): ")
|
||||
q, err := tty.ReadSingleByteFromTerminal()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if q != 'y' && q != 'Y' {
|
||||
fmt.Println()
|
||||
return 1, permission_denied(script_path)
|
||||
}
|
||||
fmt.Print("\x1b[H\x1b[2J") // clear screen
|
||||
case "e":
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
editor := exec.Command(exe, "edit-in-kitty", script_path)
|
||||
editor.Stdin = os.Stdin
|
||||
editor.Stdout = os.Stdout
|
||||
editor.Stderr = os.Stderr
|
||||
if err = editor.Run(); err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return exitErr.ExitCode(), nil
|
||||
}
|
||||
return 1, err
|
||||
}
|
||||
return confirm_and_run_shebang(args, ConfirmIfNeeded)
|
||||
case "y":
|
||||
}
|
||||
}
|
||||
exe := utils.FindExe(args[0])
|
||||
if exe == "" {
|
||||
return 1, fmt.Errorf("Failed to find the script interpreter: %s", args[0])
|
||||
}
|
||||
err = unix.Exec(exe, args, os.Environ())
|
||||
if err != nil {
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func run_shebang(args []string) (rc int, err error) {
|
||||
if len(args) < 3 {
|
||||
return 1, fmt.Errorf("Usage: kitten __shebang__ confirm-exe path_to_script cmd...")
|
||||
}
|
||||
var confirm_policy ConfirmPolicy
|
||||
switch args[0] {
|
||||
case "confirm-always":
|
||||
confirm_policy = ConfirmAlways
|
||||
case "confirm-never":
|
||||
confirm_policy = ConfirmNever
|
||||
case "confirm-if-needed":
|
||||
confirm_policy = ConfirmIfNeeded
|
||||
default:
|
||||
return 1, fmt.Errorf("Unknown confirmation policy: %s", args[1])
|
||||
}
|
||||
script_path := args[1]
|
||||
cmd := args[2:]
|
||||
if len(cmd) == 1 && cmd[0] == "__ext__" {
|
||||
ext := filepath.Ext(script_path)
|
||||
if ext == "" || ext == "." {
|
||||
return 1, fmt.Errorf("%s has no file extension so cannot be used in __ext__ mode", script_path)
|
||||
}
|
||||
cmd = []string{ext[1:]}
|
||||
}
|
||||
f, err := os.Open(script_path)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
scanner := bufio.NewScanner(f)
|
||||
first_line := ""
|
||||
if scanner.Scan() {
|
||||
first_line = scanner.Text()
|
||||
} else if err = scanner.Err(); err != nil {
|
||||
f.Close()
|
||||
return 1, fmt.Errorf("Failed to read from %s with error: %w", script_path, err)
|
||||
}
|
||||
f.Close()
|
||||
if strings.HasPrefix(first_line, "#!") {
|
||||
first_line = strings.TrimSpace(first_line[2:])
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
cmd = strings.Split(first_line, " ")
|
||||
default:
|
||||
cmd = strings.SplitN(first_line, " ", 2)
|
||||
}
|
||||
}
|
||||
cmd = append(cmd, script_path)
|
||||
return confirm_and_run_shebang(cmd, confirm_policy)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/ask"
|
||||
"github.com/kovidgoyal/kitty/kittens/broadcast"
|
||||
"github.com/kovidgoyal/kitty/kittens/choose_files"
|
||||
"github.com/kovidgoyal/kitty/kittens/choose_fonts"
|
||||
"github.com/kovidgoyal/kitty/kittens/clipboard"
|
||||
"github.com/kovidgoyal/kitty/kittens/command_palette"
|
||||
"github.com/kovidgoyal/kitty/kittens/desktop_ui"
|
||||
"github.com/kovidgoyal/kitty/kittens/diff"
|
||||
"github.com/kovidgoyal/kitty/kittens/dnd"
|
||||
"github.com/kovidgoyal/kitty/kittens/hints"
|
||||
"github.com/kovidgoyal/kitty/kittens/hyperlinked_grep"
|
||||
"github.com/kovidgoyal/kitty/kittens/icat"
|
||||
"github.com/kovidgoyal/kitty/kittens/notify"
|
||||
"github.com/kovidgoyal/kitty/kittens/panel"
|
||||
"github.com/kovidgoyal/kitty/kittens/query_terminal"
|
||||
"github.com/kovidgoyal/kitty/kittens/quick_access_terminal"
|
||||
"github.com/kovidgoyal/kitty/kittens/remote_file"
|
||||
"github.com/kovidgoyal/kitty/kittens/resize_window"
|
||||
"github.com/kovidgoyal/kitty/kittens/show_key"
|
||||
"github.com/kovidgoyal/kitty/kittens/ssh"
|
||||
"github.com/kovidgoyal/kitty/kittens/themes"
|
||||
"github.com/kovidgoyal/kitty/kittens/transfer"
|
||||
"github.com/kovidgoyal/kitty/kittens/unicode_input"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/at"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/atexit"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/benchmark"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/edit_in_kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/mouse_demo"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/pytest"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/run_shell"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/show_error"
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/update_self"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
"github.com/kovidgoyal/kitty/tools/watch"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func KittyToolEntryPoints(root *cli.Command) {
|
||||
root.Add(cli.OptionSpec{
|
||||
Name: "--version", Type: "bool-set", Help: "The current kitten version."})
|
||||
tui.PrepareRootCmd(root)
|
||||
// @
|
||||
at.EntryPoint(root)
|
||||
// update-self
|
||||
update_self.EntryPoint(root)
|
||||
// edit-in-kitty
|
||||
edit_in_kitty.EntryPoint(root)
|
||||
// clipboard
|
||||
clipboard.EntryPoint(root)
|
||||
// dnd
|
||||
dnd.EntryPoint(root)
|
||||
// icat
|
||||
icat.EntryPoint(root)
|
||||
// ssh
|
||||
ssh.EntryPoint(root)
|
||||
// transfer
|
||||
transfer.EntryPoint(root)
|
||||
// panel
|
||||
panel.EntryPoint(root)
|
||||
// quick_access_terminal
|
||||
quick_access_terminal.EntryPoint(root)
|
||||
// resize_window
|
||||
resize_window.EntryPoint(root)
|
||||
// broadcast
|
||||
broadcast.EntryPoint(root)
|
||||
// remote_file
|
||||
remote_file.EntryPoint(root)
|
||||
// unicode_input
|
||||
unicode_input.EntryPoint(root)
|
||||
// show_key
|
||||
show_key.EntryPoint(root)
|
||||
// desktop_ui
|
||||
desktop_ui.EntryPoint(root)
|
||||
// mouse_demo
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "mouse-demo",
|
||||
ShortDescription: "Demo the mouse handling kitty implements for terminal programs",
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
return mouse_demo.Run(args)
|
||||
},
|
||||
})
|
||||
// hyperlinked_grep
|
||||
hyperlinked_grep.EntryPoint(root)
|
||||
// ask
|
||||
ask.EntryPoint(root)
|
||||
// hints
|
||||
hints.EntryPoint(root)
|
||||
// diff
|
||||
diff.EntryPoint(root)
|
||||
// notify
|
||||
notify.EntryPoint(root)
|
||||
// themes
|
||||
themes.EntryPoint(root)
|
||||
themes.ParseEntryPoint(root)
|
||||
// run-shell
|
||||
run_shell.EntryPoint(root)
|
||||
// show_error
|
||||
show_error.EntryPoint(root)
|
||||
// choose-fonts
|
||||
choose_fonts.EntryPoint(root)
|
||||
// choose-files
|
||||
choose_files.EntryPoint(root)
|
||||
// command-palette
|
||||
command_palette.EntryPoint(root)
|
||||
// query-terminal
|
||||
query_terminal.EntryPoint(root)
|
||||
// __pytest__
|
||||
pytest.EntryPoint(root)
|
||||
// __hold_till_enter__
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "__hold_till_enter__",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
return tui.ExecAndHoldTillEnter(args)
|
||||
},
|
||||
})
|
||||
// __shebang__
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "__shebang__",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
return run_shebang(args)
|
||||
},
|
||||
})
|
||||
// __confirm_and_run_exe__
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "__confirm_and_run_exe__",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
return confirm_and_run_exe(args)
|
||||
},
|
||||
})
|
||||
// __watch_conf__
|
||||
watch.EntryPoint(root)
|
||||
// __convert_image__
|
||||
images.ConvertEntryPoint(root)
|
||||
// __atexit__
|
||||
atexit.EntryPoint(root)
|
||||
// __width_test__
|
||||
cli.WcswidthKittenEntryPoint(root)
|
||||
// __generate_man_pages__
|
||||
root.AddSubCommand(&cli.Command{
|
||||
Name: "__generate_man_pages__",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
q := root
|
||||
if len(args) > 0 {
|
||||
for _, scname := range args {
|
||||
sc := q.FindSubCommand(scname)
|
||||
if sc == nil {
|
||||
return 1, fmt.Errorf("No sub command named: %s found", scname)
|
||||
}
|
||||
if err = sc.GenerateManPages(1, true); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if err = q.GenerateManPages(1, false); err != nil {
|
||||
rc = 1
|
||||
}
|
||||
}
|
||||
return
|
||||
},
|
||||
})
|
||||
benchmark.EntryPoint(root)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package update_self
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Options struct {
|
||||
FetchVersion string
|
||||
}
|
||||
|
||||
func update_self(version string) (err error) {
|
||||
exe := ""
|
||||
exe, err = os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to determine path to kitten: %w", err)
|
||||
}
|
||||
exe, err = filepath.EvalSymlinks(exe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if kitty.IsStandaloneBuild == "" {
|
||||
return fmt.Errorf("This is not a standalone kitten executable. You must update all of kitty instead.")
|
||||
}
|
||||
rv := "v" + version
|
||||
if version == "nightly" {
|
||||
rv = version
|
||||
}
|
||||
url_base := fmt.Sprintf("https://github.com/kovidgoyal/kitty/releases/download/%s", rv)
|
||||
if version == "latest" {
|
||||
url_base = "https://github.com/kovidgoyal/kitty/releases/latest/download"
|
||||
}
|
||||
url := fmt.Sprintf("%s/kitten-%s-%s", url_base, runtime.GOOS, runtime.GOARCH)
|
||||
dest, err := os.CreateTemp(filepath.Dir(exe), "kitten.")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { os.Remove(dest.Name()) }()
|
||||
|
||||
if !tty.IsTerminal(os.Stdout.Fd()) {
|
||||
fmt.Println("Downloading:", url)
|
||||
err = utils.DownloadToFile(exe, url, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Downloaded to:", exe)
|
||||
} else {
|
||||
err = tui.DownloadFileWithProgress(exe, url, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Print("Updated to: ")
|
||||
return unix.Exec(exe, []string{"kitten", "--version"}, os.Environ())
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) *cli.Command {
|
||||
sc := root.AddSubCommand(&cli.Command{
|
||||
Name: "update-self",
|
||||
Usage: "[options]",
|
||||
ShortDescription: "Update this kitten binary",
|
||||
HelpText: "Update this kitten binary in place to the latest available version.",
|
||||
Run: func(cmd *cli.Command, args []string) (ret int, err error) {
|
||||
if len(args) != 0 {
|
||||
return 1, fmt.Errorf("No command line arguments are allowed")
|
||||
}
|
||||
opts := &Options{}
|
||||
err = cmd.GetOptionValues(opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, update_self(opts.FetchVersion)
|
||||
},
|
||||
})
|
||||
sc.Add(cli.OptionSpec{
|
||||
Name: "--fetch-version",
|
||||
Default: "latest",
|
||||
Help: fmt.Sprintf("The version to fetch. The special words :code:`latest` and :code:`nightly` fetch the latest stable and nightly release respectively. Other values can be, for example: :code:`%s`.", kitty.VersionString),
|
||||
})
|
||||
return sc
|
||||
}
|
||||
Reference in new issue
Block a user