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:
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,4 @@
|
||||
This folder contains library and utility code for the various "kittens". Small
|
||||
terminal programs compiled statically for doing things like kitty remote
|
||||
control, icat etc. These are often re-implementations of earlier kittens that
|
||||
were written in Python.
|
||||
@@ -0,0 +1,78 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func bash_completion_script(commands []string) (string, error) {
|
||||
return `_ksi_completions() {
|
||||
builtin local src
|
||||
builtin local limit
|
||||
# Send all words up to the word the cursor is currently on
|
||||
builtin let limit=1+$COMP_CWORD
|
||||
src=$(builtin printf "%s\n" "${COMP_WORDS[@]:0:$limit}" | builtin command kitten __complete__ bash)
|
||||
if [[ $? == 0 ]]; then
|
||||
builtin eval "${src}"
|
||||
fi
|
||||
}
|
||||
|
||||
builtin complete -F _ksi_completions kitty
|
||||
builtin complete -F _ksi_completions edit-in-kitty
|
||||
builtin complete -F _ksi_completions clone-in-kitty
|
||||
builtin complete -F _ksi_completions kitten
|
||||
`, nil
|
||||
}
|
||||
|
||||
func bash_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
|
||||
output := strings.Builder{}
|
||||
f := func(format string, args ...any) { fmt.Fprintf(&output, format+"\n", args...) }
|
||||
n := completions[0].Delegate.NumToRemove
|
||||
if n > 0 {
|
||||
f("if builtin declare -F _command_offset >/dev/null; then")
|
||||
f(" compopt +o nospace")
|
||||
f(" COMP_WORDS[%d]=%s", n, utils.QuoteStringForSH(completions[0].Delegate.Command))
|
||||
f(" _command_offset %d", n)
|
||||
f("fi")
|
||||
} else {
|
||||
for _, mg := range completions[0].Groups {
|
||||
if mg.NoTrailingSpace {
|
||||
f("compopt -o nospace")
|
||||
} else {
|
||||
f("compopt +o nospace")
|
||||
}
|
||||
if mg.IsFiles {
|
||||
f("compopt -o filenames")
|
||||
for _, m := range mg.Matches {
|
||||
if strings.HasSuffix(m.Word, utils.Sep) {
|
||||
m.Word = m.Word[:len(m.Word)-1]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
f("compopt +o filenames")
|
||||
}
|
||||
for _, m := range mg.Matches {
|
||||
f("COMPREPLY+=(%s)", utils.QuoteStringForSH(m.Word))
|
||||
}
|
||||
}
|
||||
}
|
||||
// debugf("%#v", output.String())
|
||||
return []byte(output.String()), nil
|
||||
}
|
||||
|
||||
func bash_init_completions(completions *Completions) {
|
||||
completions.split_on_equals = true
|
||||
}
|
||||
|
||||
func init() {
|
||||
completion_scripts["bash"] = bash_completion_script
|
||||
input_parsers["bash"] = shell_input_parser
|
||||
output_serializers["bash"] = bash_output_serializer
|
||||
init_completions["bash"] = bash_init_completions
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type RunFunc = func(cmd *Command, args []string) (int, error)
|
||||
|
||||
type Command struct {
|
||||
Name, Group string
|
||||
Usage, ShortDescription, HelpText string
|
||||
Hidden bool
|
||||
|
||||
// Number of non-option arguments after which to stop parsing options. 0 means no options after the first non-option arg.
|
||||
AllowOptionsAfterArgs int
|
||||
// If true does not fail if the first non-option arg is not a sub-command
|
||||
SubCommandIsOptional bool
|
||||
// If true subcommands are ignored unless they are the first non-option argument
|
||||
SubCommandMustBeFirst bool
|
||||
// The entry point for this command
|
||||
Run RunFunc
|
||||
// The completer for args
|
||||
ArgCompleter CompletionFunc
|
||||
// Stop completion processing at this arg num
|
||||
StopCompletingAtArg int
|
||||
// Consider all args as non-options args when parsing for completion
|
||||
OnlyArgsAllowed bool
|
||||
// Pass through all args, useful for wrapper commands
|
||||
IgnoreAllArgs bool
|
||||
// Specialised arg parsing
|
||||
ParseArgsForCompletion func(cmd *Command, args []string, completions *Completions)
|
||||
// Callback that is called on error
|
||||
CallbackOnError func(cmd *Command, err error, during_parsing bool, exit_code int) (final_exit_code int)
|
||||
|
||||
SubCommandGroups []*CommandGroup
|
||||
OptionGroups []*OptionGroup
|
||||
Parent *Command
|
||||
|
||||
Args []string
|
||||
|
||||
option_map map[string]*Option
|
||||
IndexOfFirstArg int
|
||||
}
|
||||
|
||||
func (self *Command) Clone(parent *Command) *Command {
|
||||
ans := *self
|
||||
ans.Args = make([]string, 0, 8)
|
||||
ans.Parent = parent
|
||||
ans.SubCommandGroups = make([]*CommandGroup, len(self.SubCommandGroups))
|
||||
ans.OptionGroups = make([]*OptionGroup, len(self.OptionGroups))
|
||||
ans.option_map = nil
|
||||
|
||||
for i, o := range self.OptionGroups {
|
||||
ans.OptionGroups[i] = o.Clone(&ans)
|
||||
}
|
||||
for i, g := range self.SubCommandGroups {
|
||||
ans.SubCommandGroups[i] = g.Clone(&ans)
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Command) AddClone(group string, src *Command) *Command {
|
||||
c := src.Clone(self)
|
||||
g := self.AddSubCommandGroup(group)
|
||||
c.Group = g.Title
|
||||
g.SubCommands = append(g.SubCommands, c)
|
||||
return c
|
||||
}
|
||||
|
||||
func init_cmd(c *Command) {
|
||||
c.SubCommandGroups = make([]*CommandGroup, 0, 8)
|
||||
c.OptionGroups = make([]*OptionGroup, 0, 8)
|
||||
c.Args = make([]string, 0, 8)
|
||||
c.option_map = nil
|
||||
}
|
||||
|
||||
func NewRootCommand() *Command {
|
||||
ans := Command{
|
||||
Name: filepath.Base(os.Args[0]),
|
||||
}
|
||||
init_cmd(&ans)
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Command) AddSubCommandGroup(title string) *CommandGroup {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
if g.Title == title {
|
||||
return g
|
||||
}
|
||||
}
|
||||
ans := CommandGroup{Title: title, SubCommands: make([]*Command, 0, 8)}
|
||||
self.SubCommandGroups = append(self.SubCommandGroups, &ans)
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Command) AddSubCommand(ans *Command) *Command {
|
||||
g := self.AddSubCommandGroup(ans.Group)
|
||||
g.SubCommands = append(g.SubCommands, ans)
|
||||
init_cmd(ans)
|
||||
ans.Parent = self
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) Validate() error {
|
||||
seen_sc := make(map[string]bool)
|
||||
for _, g := range self.SubCommandGroups {
|
||||
for _, sc := range g.SubCommands {
|
||||
if seen_sc[sc.Name] {
|
||||
return &ParseError{Message: fmt.Sprintf("The sub-command :yellow:`%s` occurs twice inside %s", sc.Name, self.Name)}
|
||||
}
|
||||
seen_sc[sc.Name] = true
|
||||
err := sc.Validate()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
seen_flags := make(map[string]bool)
|
||||
|
||||
self.option_map = make(map[string]*Option, 128)
|
||||
validate_options := func(opt *Option) error {
|
||||
if self.option_map[opt.Name] != nil {
|
||||
return &ParseError{Message: fmt.Sprintf("The option :yellow:`%s` occurs twice inside %s", opt.Name, self.Name)}
|
||||
}
|
||||
for _, a := range opt.Aliases {
|
||||
q := a.String()
|
||||
if seen_flags[q] {
|
||||
return &ParseError{Message: fmt.Sprintf("The option :yellow:`%s` occurs twice inside %s", q, self.Name)}
|
||||
}
|
||||
seen_flags[q] = true
|
||||
}
|
||||
self.option_map[opt.Name] = opt
|
||||
return nil
|
||||
}
|
||||
err := self.VisitAllOptions(validate_options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if self.option_map["Help"] == nil {
|
||||
if seen_flags["-h"] || seen_flags["--help"] {
|
||||
return &ParseError{Message: fmt.Sprintf("The --help or -h flags are assigned to an option other than Help in %s", self.Name)}
|
||||
}
|
||||
self.option_map["Help"] = self.Add(OptionSpec{Name: "--help -h", Type: "bool-set", Help: "Show help for this command"})
|
||||
}
|
||||
|
||||
if self.Parent == nil && self.option_map["Version"] == nil {
|
||||
if seen_flags["--version"] {
|
||||
return &ParseError{Message: fmt.Sprintf("The --version flag is assigned to an option other than Version in %s", self.Name)}
|
||||
}
|
||||
self.option_map["Version"] = self.Add(OptionSpec{Name: "--version", Type: "bool-set", Help: "Show version"})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Command) Root() *Command {
|
||||
p := self
|
||||
for p.Parent != nil {
|
||||
p = p.Parent
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (self *Command) CommandStringForUsage() string {
|
||||
names := make([]string, 0, 8)
|
||||
p := self
|
||||
for p != nil {
|
||||
if p.Name != "" {
|
||||
names = append(names, p.Name)
|
||||
}
|
||||
p = p.Parent
|
||||
}
|
||||
return strings.Join(utils.Reverse(names), " ")
|
||||
}
|
||||
|
||||
func (self *Command) ParseArgs(args []string) (*Command, error) {
|
||||
for ; self.Parent != nil; self = self.Parent {
|
||||
}
|
||||
err := self.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args == nil {
|
||||
args = os.Args
|
||||
}
|
||||
if len(args) < 1 {
|
||||
return nil, &ParseError{Message: "At least one arg must be supplied"}
|
||||
}
|
||||
ctx := Context{SeenCommands: make([]*Command, 0, 4)}
|
||||
err = self.parse_args(&ctx, args[1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ctx.SeenCommands[len(ctx.SeenCommands)-1], nil
|
||||
}
|
||||
|
||||
func (self *Command) ResetAfterParseArgs() {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
for _, sc := range g.SubCommands {
|
||||
sc.ResetAfterParseArgs()
|
||||
}
|
||||
}
|
||||
|
||||
for _, g := range self.OptionGroups {
|
||||
for _, o := range g.Options {
|
||||
o.reset()
|
||||
}
|
||||
}
|
||||
self.option_map = nil
|
||||
self.IndexOfFirstArg = 0
|
||||
self.Args = make([]string, 0, 8)
|
||||
}
|
||||
|
||||
func (self *Command) HasSubCommands() bool {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
if len(g.SubCommands) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Command) HasVisibleSubCommands() bool {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
if g.HasVisibleSubCommands() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Command) VisitAllOptions(callback func(*Option) error) error {
|
||||
depth := 0
|
||||
iter_opts := func(cmd *Command) error {
|
||||
for _, g := range cmd.OptionGroups {
|
||||
for _, o := range g.Options {
|
||||
if o.Depth >= depth {
|
||||
err := callback(o)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for p := self; p != nil; p = p.Parent {
|
||||
err := iter_opts(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
depth++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Command) AllOptions() []*Option {
|
||||
ans := make([]*Option, 0, 64)
|
||||
_ = self.VisitAllOptions(func(o *Option) error { ans = append(ans, o); return nil })
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) GetVisibleOptions() ([]string, map[string][]*Option) {
|
||||
group_titles := make([]string, 0, len(self.OptionGroups))
|
||||
gmap := make(map[string][]*Option)
|
||||
|
||||
add_options := func(group_title string, opts []*Option) {
|
||||
if len(opts) == 0 {
|
||||
return
|
||||
}
|
||||
x := gmap[group_title]
|
||||
if x == nil {
|
||||
group_titles = append(group_titles, group_title)
|
||||
gmap[group_title] = opts
|
||||
} else {
|
||||
gmap[group_title] = append(x, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
depth := 0
|
||||
process_cmd := func(cmd *Command) {
|
||||
for _, g := range cmd.OptionGroups {
|
||||
gopts := make([]*Option, 0, len(g.Options))
|
||||
for _, o := range g.Options {
|
||||
if !o.Hidden && o.Depth >= depth {
|
||||
gopts = append(gopts, o)
|
||||
}
|
||||
}
|
||||
add_options(g.Title, gopts)
|
||||
}
|
||||
}
|
||||
for p := self; p != nil; p = p.Parent {
|
||||
process_cmd(p)
|
||||
depth++
|
||||
}
|
||||
return group_titles, gmap
|
||||
}
|
||||
|
||||
func sort_levenshtein_matches(q string, matches []string) {
|
||||
utils.StableSort(matches, func(a, b string) int {
|
||||
la, lb := utils.LevenshteinDistance(a, q, true), utils.LevenshteinDistance(b, q, true)
|
||||
if la != lb {
|
||||
return la - lb
|
||||
}
|
||||
return strings.Compare(a, b)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func (self *Command) SuggestionsForCommand(name string, max_distance int /* good default is 2 */) []string {
|
||||
ans := make([]string, 0, 8)
|
||||
q := strings.ToLower(name)
|
||||
for _, g := range self.SubCommandGroups {
|
||||
for _, sc := range g.SubCommands {
|
||||
if utils.LevenshteinDistance(sc.Name, q, true) <= max_distance {
|
||||
ans = append(ans, sc.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort_levenshtein_matches(q, ans)
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) SuggestionsForOption(name_with_hyphens string, max_distance int /* good default is 2 */) []string {
|
||||
ans := make([]string, 0, 8)
|
||||
q := strings.ToLower(name_with_hyphens)
|
||||
_ = self.VisitAllOptions(func(opt *Option) error {
|
||||
for _, a := range opt.Aliases {
|
||||
as := a.String()
|
||||
if utils.LevenshteinDistance(as, q, true) <= max_distance {
|
||||
ans = append(ans, as)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort_levenshtein_matches(q, ans)
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) FindSubCommand(name string) *Command {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
c := g.FindSubCommand(name)
|
||||
if c != nil {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Command) FindSubCommands(prefix string) []*Command {
|
||||
c := self.FindSubCommand(prefix)
|
||||
if c != nil {
|
||||
return []*Command{c}
|
||||
}
|
||||
ans := make([]*Command, 0, 4)
|
||||
for _, g := range self.SubCommandGroups {
|
||||
ans = g.FindSubCommands(prefix, ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) AddOptionGroup(title string) *OptionGroup {
|
||||
for _, g := range self.OptionGroups {
|
||||
if g.Title == title {
|
||||
return g
|
||||
}
|
||||
}
|
||||
ans := OptionGroup{Title: title, Options: make([]*Option, 0, 8)}
|
||||
self.OptionGroups = append(self.OptionGroups, &ans)
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Command) AddOptionToGroupFromString(group string, items ...string) *Option {
|
||||
ans, err := self.AddOptionGroup(group).AddOptionFromString(self, items...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ans
|
||||
|
||||
}
|
||||
|
||||
func (self *Command) AddToGroup(group string, s OptionSpec) *Option {
|
||||
ans, err := self.AddOptionGroup(group).AddOption(self, s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) AddOptionFromString(items ...string) *Option {
|
||||
return self.AddOptionToGroupFromString("", items...)
|
||||
}
|
||||
|
||||
func (self *Command) Add(s OptionSpec) *Option {
|
||||
return self.AddToGroup("", s)
|
||||
}
|
||||
|
||||
func (self *Command) FindOptions(name_with_hyphens string) []*Option {
|
||||
ans := make([]*Option, 0, 4)
|
||||
for _, g := range self.OptionGroups {
|
||||
x := g.FindOptions(name_with_hyphens)
|
||||
if x != nil {
|
||||
ans = append(ans, x...)
|
||||
}
|
||||
}
|
||||
depth := 0
|
||||
for p := self.Parent; p != nil; p = p.Parent {
|
||||
depth++
|
||||
for _, po := range p.FindOptions(name_with_hyphens) {
|
||||
if po.Depth >= depth {
|
||||
ans = append(ans, po)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans
|
||||
|
||||
}
|
||||
|
||||
func (self *Command) FindOption(name_with_hyphens string) *Option {
|
||||
for _, g := range self.OptionGroups {
|
||||
q := g.FindOption(name_with_hyphens)
|
||||
if q != nil {
|
||||
return q
|
||||
}
|
||||
}
|
||||
depth := 0
|
||||
for p := self.Parent; p != nil; p = p.Parent {
|
||||
depth++
|
||||
q := p.FindOption(name_with_hyphens)
|
||||
if q != nil && q.Depth >= depth {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Context struct {
|
||||
SeenCommands []*Command
|
||||
}
|
||||
|
||||
func GetOptionValue[T any](self *Command, name string) (ans T, err error) {
|
||||
opt := self.option_map[name]
|
||||
if opt == nil {
|
||||
err = fmt.Errorf("No option with the name: %s", name)
|
||||
return
|
||||
}
|
||||
ans, ok := opt.parsed_value().(T)
|
||||
if !ok {
|
||||
err = fmt.Errorf("The option %s is not of the correct type", name)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Command) OptionsSeenOnCommandLine() map[string]bool {
|
||||
ans := make(map[string]bool)
|
||||
for name, opt := range self.option_map {
|
||||
ans[name] = opt != nil && len(opt.values_from_cmdline) > 0
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Command) GetOptionValues(pointer_to_options_struct any) error {
|
||||
val := reflect.ValueOf(pointer_to_options_struct).Elem()
|
||||
if val.Kind() != reflect.Struct {
|
||||
return fmt.Errorf("Need a pointer to a struct to set option values on")
|
||||
}
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
f := val.Field(i)
|
||||
field_name := val.Type().Field(i).Name
|
||||
if utils.Capitalize(field_name) != field_name || !f.CanSet() {
|
||||
continue
|
||||
}
|
||||
opt := self.option_map[field_name]
|
||||
if opt == nil {
|
||||
return fmt.Errorf("No option with the name: %s", field_name)
|
||||
}
|
||||
switch opt.OptionType {
|
||||
case IntegerOption, CountOption:
|
||||
if f.Kind() != reflect.Int {
|
||||
return fmt.Errorf("The field: %s must be an integer", field_name)
|
||||
}
|
||||
v := int64(opt.parsed_value().(int))
|
||||
if f.OverflowInt(v) {
|
||||
return fmt.Errorf("The value: %d is too large for the integer type used for the option: %s", v, field_name)
|
||||
}
|
||||
f.SetInt(v)
|
||||
case FloatOption:
|
||||
if f.Kind() != reflect.Float64 {
|
||||
return fmt.Errorf("The field: %s must be a float64", field_name)
|
||||
}
|
||||
v := opt.parsed_value().(float64)
|
||||
if f.OverflowFloat(v) {
|
||||
return fmt.Errorf("The value: %f is too large for the integer type used for the option: %s", v, field_name)
|
||||
}
|
||||
f.SetFloat(v)
|
||||
case BoolOption:
|
||||
if f.Kind() != reflect.Bool {
|
||||
return fmt.Errorf("The field: %s must be a boolean", field_name)
|
||||
}
|
||||
v := opt.parsed_value().(bool)
|
||||
f.SetBool(v)
|
||||
case StringOption:
|
||||
if opt.IsList {
|
||||
if !is_string_slice(f) {
|
||||
return fmt.Errorf("The field: %s must be a []string", field_name)
|
||||
}
|
||||
v := opt.parsed_value().([]string)
|
||||
f.Set(reflect.ValueOf(v))
|
||||
} else {
|
||||
if f.Kind() != reflect.String {
|
||||
return fmt.Errorf("The field: %s must be a string", field_name)
|
||||
}
|
||||
v := opt.parsed_value().(string)
|
||||
f.SetString(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Command) ExecArgs(args []string) (exit_code int) {
|
||||
root := self
|
||||
for root.Parent != nil {
|
||||
root = root.Parent
|
||||
}
|
||||
cmd, err := root.ParseArgs(args)
|
||||
if err != nil {
|
||||
if self.CallbackOnError != nil {
|
||||
return self.CallbackOnError(cmd, err, true, 1)
|
||||
}
|
||||
ShowError(err)
|
||||
return 1
|
||||
}
|
||||
help_opt := cmd.option_map["Help"]
|
||||
version_opt := root.option_map["Version"]
|
||||
if help_opt != nil && help_opt.parsed_value().(bool) {
|
||||
cmd.ShowHelp()
|
||||
return
|
||||
} else if version_opt != nil && version_opt.parsed_value().(bool) {
|
||||
root.ShowVersion()
|
||||
return
|
||||
} else if cmd.Run != nil {
|
||||
exit_code, err = cmd.Run(cmd, cmd.Args)
|
||||
if err != nil {
|
||||
if exit_code == 0 {
|
||||
exit_code = 1
|
||||
}
|
||||
if self.CallbackOnError != nil {
|
||||
return self.CallbackOnError(cmd, err, false, exit_code)
|
||||
}
|
||||
ShowError(err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Command) GetCompletions(argv []string, init_completions func(*Completions)) *Completions {
|
||||
ans := NewCompletions()
|
||||
if init_completions != nil {
|
||||
init_completions(ans)
|
||||
}
|
||||
if len(argv) > 0 {
|
||||
exe := argv[0]
|
||||
exe = filepath.Base(exe) // zsh completion script passes full path to exe when using aliases
|
||||
cmd := self.FindSubCommand(exe)
|
||||
if cmd != nil {
|
||||
if cmd.ParseArgsForCompletion != nil {
|
||||
cmd.ParseArgsForCompletion(cmd, argv[1:], ans)
|
||||
} else {
|
||||
completion_parse_args(cmd, argv[1:], ans)
|
||||
}
|
||||
}
|
||||
}
|
||||
non_empty_groups := make([]*MatchGroup, 0, len(ans.Groups))
|
||||
for _, gr := range ans.Groups {
|
||||
if len(gr.Matches) > 0 {
|
||||
non_empty_groups = append(non_empty_groups, gr)
|
||||
}
|
||||
}
|
||||
ans.Groups = non_empty_groups
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func json_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
|
||||
ans := make([][]string, 0, 32)
|
||||
err := json.Unmarshal(data, &ans)
|
||||
return ans, err
|
||||
}
|
||||
|
||||
func json_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
|
||||
return json.Marshal(completions)
|
||||
}
|
||||
|
||||
type completion_script_func func(commands []string) (string, error)
|
||||
type parser_func func(data []byte, shell_state map[string]string) ([][]string, error)
|
||||
type serializer_func func(completions []*Completions, shell_state map[string]string) ([]byte, error)
|
||||
|
||||
var completion_scripts = make(map[string]completion_script_func, 4)
|
||||
var input_parsers = make(map[string]parser_func, 4)
|
||||
var output_serializers = make(map[string]serializer_func, 4)
|
||||
var init_completions = make(map[string]func(*Completions), 4)
|
||||
|
||||
func init() {
|
||||
input_parsers["json"] = json_input_parser
|
||||
output_serializers["json"] = json_output_serializer
|
||||
}
|
||||
|
||||
var registered_exes []func(root *Command)
|
||||
|
||||
func RegisterExeForCompletion(x func(root *Command)) {
|
||||
if registered_exes == nil {
|
||||
registered_exes = make([]func(root *Command), 0, 4)
|
||||
}
|
||||
registered_exes = append(registered_exes, x)
|
||||
}
|
||||
|
||||
func GenerateCompletions(args []string) error {
|
||||
output_type := "json"
|
||||
if len(args) > 0 {
|
||||
output_type = args[0]
|
||||
args = args[1:]
|
||||
}
|
||||
n := max(1, len(args))
|
||||
if output_type == "setup" {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("The shell must be specified")
|
||||
}
|
||||
shell_name := args[0]
|
||||
args = args[1:]
|
||||
completion_script := completion_scripts[shell_name]
|
||||
if completion_script == nil {
|
||||
return fmt.Errorf("Unsupported shell: %s", shell_name)
|
||||
}
|
||||
output, err := completion_script(args)
|
||||
if err == nil {
|
||||
_, err = os.Stdout.WriteString(output)
|
||||
}
|
||||
return err
|
||||
}
|
||||
shell_state := make(map[string]string, n)
|
||||
for _, arg := range args {
|
||||
k, v, found := strings.Cut(arg, "=")
|
||||
if !found {
|
||||
return fmt.Errorf("Invalid shell state specification: %s", arg)
|
||||
}
|
||||
shell_state[k] = v
|
||||
}
|
||||
input_parser := input_parsers[output_type]
|
||||
output_serializer := output_serializers[output_type]
|
||||
if input_parser == nil || output_serializer == nil {
|
||||
return fmt.Errorf("Unknown output type: %s", output_type)
|
||||
}
|
||||
data, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// debugf("%#v", string(data))
|
||||
all_argv, err := input_parser(data, shell_state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var root = NewRootCommand()
|
||||
for _, re := range registered_exes {
|
||||
re(root)
|
||||
}
|
||||
|
||||
err = root.Validate()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
all_completions := make([]*Completions, 0, 1)
|
||||
for _, argv := range all_argv {
|
||||
all_completions = append(all_completions, root.GetCompletions(argv, init_completions[output_type]))
|
||||
root.ResetAfterParseArgs()
|
||||
}
|
||||
output, err := output_serializer(all_completions, shell_state)
|
||||
if err == nil {
|
||||
_, err = os.Stdout.Write(output)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var _ = os.Getenv
|
||||
|
||||
func (self *Completions) add_options_group(options []*Option, word string) {
|
||||
group := self.AddMatchGroup("Options")
|
||||
if strings.HasPrefix(word, "--") {
|
||||
if word == "--" {
|
||||
group.Matches = append(group.Matches, &Match{Word: "--", Description: "End of options"})
|
||||
}
|
||||
for _, opt := range options {
|
||||
for _, q := range opt.Aliases {
|
||||
if strings.HasPrefix(q.String(), word) {
|
||||
group.Matches = append(group.Matches, &Match{Word: q.String(), Description: opt.Help})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if word == "-" {
|
||||
group.Matches = append(group.Matches, &Match{Word: "--", Description: "End of options"})
|
||||
for _, opt := range options {
|
||||
has_single_letter_alias := false
|
||||
for _, q := range opt.Aliases {
|
||||
if q.IsShort {
|
||||
group.AddMatch("-"+q.NameWithoutHyphens, opt.Help)
|
||||
has_single_letter_alias = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !has_single_letter_alias {
|
||||
for _, q := range opt.Aliases {
|
||||
if !q.IsShort {
|
||||
group.AddMatch(q.String(), opt.Help)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
runes := []rune(word)
|
||||
last_letter := string(runes[len(runes)-1])
|
||||
for _, opt := range options {
|
||||
for _, q := range opt.Aliases {
|
||||
if q.IsShort && q.NameWithoutHyphens == last_letter {
|
||||
group.AddMatch(word, opt.Help)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Command) sub_command_allowed_at(completions *Completions, arg_num int) bool {
|
||||
if self.SubCommandMustBeFirst {
|
||||
return arg_num == 1 && completions.CurrentWordIdxInParent == 1
|
||||
}
|
||||
return arg_num == 1
|
||||
}
|
||||
|
||||
func complete_word(word string, completions *Completions, only_args_allowed bool, expecting_arg_for *Option, arg_num int) {
|
||||
cmd := completions.CurrentCmd
|
||||
if expecting_arg_for != nil {
|
||||
if expecting_arg_for.Completer != nil {
|
||||
expecting_arg_for.Completer(completions, word, arg_num)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !only_args_allowed && strings.HasPrefix(word, "-") {
|
||||
if strings.HasPrefix(word, "--") && strings.Contains(word, "=") {
|
||||
idx := strings.Index(word, "=")
|
||||
option := cmd.FindOption(word[:idx])
|
||||
if option != nil {
|
||||
if option.Completer != nil {
|
||||
option.Completer(completions, word[idx+1:], arg_num)
|
||||
completions.AddPrefixToAllMatches(word[:idx+1])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
completions.add_options_group(cmd.AllOptions(), word)
|
||||
}
|
||||
return
|
||||
}
|
||||
if cmd.HasVisibleSubCommands() && cmd.sub_command_allowed_at(completions, arg_num) {
|
||||
for _, cg := range cmd.SubCommandGroups {
|
||||
group := completions.AddMatchGroup(cg.Title)
|
||||
if group.Title == "" {
|
||||
group.Title = "Sub-commands"
|
||||
}
|
||||
for _, sc := range cg.SubCommands {
|
||||
if !sc.Hidden && strings.HasPrefix(sc.Name, word) {
|
||||
t := sc.ShortDescription
|
||||
if t == "" {
|
||||
t = sc.HelpText
|
||||
}
|
||||
group.AddMatch(sc.Name, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cmd.SubCommandIsOptional && cmd.ArgCompleter != nil {
|
||||
cmd.ArgCompleter(completions, word, arg_num)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if cmd.ArgCompleter != nil {
|
||||
cmd.ArgCompleter(completions, word, arg_num)
|
||||
}
|
||||
}
|
||||
|
||||
func completion_parse_args(cmd *Command, words []string, completions *Completions) {
|
||||
completions.CurrentCmd = cmd
|
||||
if len(words) == 0 {
|
||||
complete_word("", completions, false, nil, 0)
|
||||
return
|
||||
}
|
||||
completions.AllWords = words
|
||||
|
||||
var expecting_arg_for *Option
|
||||
only_args_allowed := false
|
||||
arg_num := 0
|
||||
|
||||
for i, word := range words {
|
||||
cmd = completions.CurrentCmd
|
||||
completions.CurrentWordIdx = i
|
||||
completions.CurrentWordIdxInParent++
|
||||
is_last_word := i == len(words)-1
|
||||
is_option_equal := completions.split_on_equals && word == "=" && expecting_arg_for != nil
|
||||
if only_args_allowed || (expecting_arg_for == nil && !strings.HasPrefix(word, "-")) {
|
||||
if !is_option_equal {
|
||||
arg_num++
|
||||
}
|
||||
if arg_num == 1 {
|
||||
cmd.IndexOfFirstArg = completions.CurrentWordIdx
|
||||
}
|
||||
}
|
||||
if is_last_word {
|
||||
if is_option_equal {
|
||||
word = ""
|
||||
}
|
||||
complete_word(word, completions, only_args_allowed, expecting_arg_for, arg_num)
|
||||
} else {
|
||||
if expecting_arg_for != nil {
|
||||
if is_option_equal {
|
||||
continue
|
||||
}
|
||||
expecting_arg_for = nil
|
||||
continue
|
||||
}
|
||||
if word == "--" {
|
||||
only_args_allowed = true
|
||||
continue
|
||||
}
|
||||
if !only_args_allowed && strings.HasPrefix(word, "-") {
|
||||
if !strings.Contains(word, "=") {
|
||||
option := cmd.FindOption(word)
|
||||
if option != nil && option.needs_argument() {
|
||||
expecting_arg_for = option
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if cmd.HasVisibleSubCommands() && cmd.sub_command_allowed_at(completions, arg_num) {
|
||||
sc := cmd.FindSubCommand(word)
|
||||
if sc == nil {
|
||||
only_args_allowed = true
|
||||
continue
|
||||
}
|
||||
completions.CurrentCmd = sc
|
||||
cmd = sc
|
||||
arg_num = 0
|
||||
completions.CurrentWordIdxInParent = 0
|
||||
only_args_allowed = cmd.OnlyArgsAllowed
|
||||
if cmd.ParseArgsForCompletion != nil {
|
||||
cmd.ParseArgsForCompletion(cmd, words[i+1:], completions)
|
||||
return
|
||||
}
|
||||
} else if cmd.StopCompletingAtArg > 0 && arg_num >= cmd.StopCompletingAtArg {
|
||||
return
|
||||
} else {
|
||||
only_args_allowed = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Match struct {
|
||||
Word string `json:"word,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type MatchGroup struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
NoTrailingSpace bool `json:"no_trailing_space,omitempty"`
|
||||
IsFiles bool `json:"is_files,omitempty"`
|
||||
Matches []*Match `json:"matches,omitempty"`
|
||||
}
|
||||
|
||||
func (self *MatchGroup) remove_common_prefix() string {
|
||||
if self.IsFiles {
|
||||
if len(self.Matches) > 1 {
|
||||
lcp := self.longest_common_prefix()
|
||||
if strings.Contains(lcp, utils.Sep) {
|
||||
lcp = strings.TrimRight(filepath.Dir(lcp), utils.Sep) + utils.Sep
|
||||
self.remove_prefix_from_all_matches(lcp)
|
||||
return lcp
|
||||
}
|
||||
}
|
||||
} else if len(self.Matches) > 1 && strings.HasPrefix(self.Matches[0].Word, "--") && strings.Contains(self.Matches[0].Word, "=") {
|
||||
lcp, _, _ := strings.Cut(self.longest_common_prefix(), "=")
|
||||
lcp += "="
|
||||
if len(lcp) > 3 {
|
||||
self.remove_prefix_from_all_matches(lcp)
|
||||
return lcp
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *MatchGroup) AddMatch(word string, description ...string) *Match {
|
||||
ans := Match{Word: word, Description: strings.Join(description, " ")}
|
||||
self.Matches = append(self.Matches, &ans)
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *MatchGroup) AddPrefixToAllMatches(prefix string) {
|
||||
for _, m := range self.Matches {
|
||||
m.Word = prefix + m.Word
|
||||
}
|
||||
}
|
||||
|
||||
func (self *MatchGroup) remove_prefix_from_all_matches(prefix string) {
|
||||
for _, m := range self.Matches {
|
||||
m.Word = m.Word[len(prefix):]
|
||||
}
|
||||
}
|
||||
|
||||
func (self *MatchGroup) has_descriptions() bool {
|
||||
for _, m := range self.Matches {
|
||||
if m.Description != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *MatchGroup) max_visual_word_length(limit int) int {
|
||||
ans := 0
|
||||
for _, m := range self.Matches {
|
||||
if q := wcswidth.Stringwidth(m.Word); q > ans {
|
||||
ans = q
|
||||
if ans > limit {
|
||||
return limit
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *MatchGroup) longest_common_prefix() string {
|
||||
limit := len(self.Matches)
|
||||
i := 0
|
||||
return utils.LongestCommon(func() (string, bool) {
|
||||
if i < limit {
|
||||
i++
|
||||
return self.Matches[i-1].Word, false
|
||||
}
|
||||
return "", true
|
||||
}, true)
|
||||
}
|
||||
|
||||
type Delegate struct {
|
||||
NumToRemove int `json:"num_to_remove,omitempty"`
|
||||
Command string `json:"command,omitempty"`
|
||||
}
|
||||
|
||||
type Completions struct {
|
||||
Groups []*MatchGroup `json:"groups,omitempty"`
|
||||
Delegate Delegate `json:"delegate"`
|
||||
|
||||
CurrentCmd *Command `json:"-"`
|
||||
AllWords []string `json:"-"` // all words passed to parse_args()
|
||||
CurrentWordIdx int `json:"-"` // index of current word in all_words
|
||||
CurrentWordIdxInParent int `json:"-"` // index of current word in parents command line 1 for first word after parent
|
||||
|
||||
split_on_equals bool // true if the cmdline is split on = (BASH does this because readline does this)
|
||||
}
|
||||
|
||||
func NewCompletions() *Completions {
|
||||
return &Completions{Groups: make([]*MatchGroup, 0, 4)}
|
||||
}
|
||||
|
||||
func (self *Completions) AddPrefixToAllMatches(prefix string) {
|
||||
for _, mg := range self.Groups {
|
||||
mg.AddPrefixToAllMatches(prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Completions) MergeMatchGroup(mg *MatchGroup) {
|
||||
if len(mg.Matches) == 0 {
|
||||
return
|
||||
}
|
||||
var dest *MatchGroup
|
||||
for _, q := range self.Groups {
|
||||
if q.Title == mg.Title {
|
||||
dest = q
|
||||
break
|
||||
}
|
||||
}
|
||||
if dest == nil {
|
||||
dest = self.AddMatchGroup(mg.Title)
|
||||
dest.NoTrailingSpace = mg.NoTrailingSpace
|
||||
dest.IsFiles = mg.IsFiles
|
||||
}
|
||||
seen := utils.NewSet[string](64)
|
||||
for _, q := range self.Groups {
|
||||
for _, m := range q.Matches {
|
||||
seen.Add(m.Word)
|
||||
}
|
||||
}
|
||||
for _, m := range mg.Matches {
|
||||
if !seen.Has(m.Word) {
|
||||
seen.Add(m.Word)
|
||||
dest.Matches = append(dest.Matches, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Completions) AddMatchGroup(title string) *MatchGroup {
|
||||
for _, q := range self.Groups {
|
||||
if q.Title == title {
|
||||
return q
|
||||
}
|
||||
}
|
||||
ans := MatchGroup{Title: title, Matches: make([]*Match, 0, 8)}
|
||||
self.Groups = append(self.Groups, &ans)
|
||||
return &ans
|
||||
}
|
||||
|
||||
type CompletionFunc = func(completions *Completions, word string, arg_num int)
|
||||
|
||||
func NamesCompleter(title string, names ...string) CompletionFunc {
|
||||
return func(completions *Completions, word string, arg_num int) {
|
||||
mg := completions.AddMatchGroup(title)
|
||||
for _, q := range names {
|
||||
if strings.HasPrefix(q, word) {
|
||||
mg.AddMatch(q)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ChainCompleters(completers ...CompletionFunc) CompletionFunc {
|
||||
return func(completions *Completions, word string, arg_num int) {
|
||||
for _, f := range completers {
|
||||
f(completions, word, arg_num)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func CompletionForWrapper(wrapped_cmd string) func(completions *Completions, word string, arg_num int) {
|
||||
return func(completions *Completions, word string, arg_num int) {
|
||||
completions.Delegate.NumToRemove = completions.CurrentWordIdx
|
||||
completions.Delegate.Command = wrapped_cmd
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func absolutize_path(path string) string {
|
||||
path = utils.Expanduser(path)
|
||||
q, err := filepath.Abs(path)
|
||||
if err == nil {
|
||||
path = q
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
type FileEntry struct {
|
||||
Name, CompletionCandidate, Abspath string
|
||||
Mode os.FileMode
|
||||
IsDir, IsSymlink, IsEmptyDir bool
|
||||
}
|
||||
|
||||
func CompleteFiles(prefix string, callback func(*FileEntry), cwd string) error {
|
||||
if cwd == "" {
|
||||
var err error
|
||||
cwd, err = os.Getwd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
location := absolutize_path(prefix)
|
||||
base_dir := ""
|
||||
joinable_prefix := ""
|
||||
switch prefix {
|
||||
case ".":
|
||||
base_dir = "."
|
||||
joinable_prefix = ""
|
||||
case "./":
|
||||
base_dir = "."
|
||||
joinable_prefix = "./"
|
||||
case "/":
|
||||
base_dir = "/"
|
||||
joinable_prefix = "/"
|
||||
case "~":
|
||||
base_dir = location
|
||||
joinable_prefix = "~/"
|
||||
case "":
|
||||
base_dir = cwd
|
||||
joinable_prefix = ""
|
||||
default:
|
||||
if strings.HasSuffix(prefix, utils.Sep) {
|
||||
base_dir = location
|
||||
joinable_prefix = prefix
|
||||
} else {
|
||||
idx := strings.LastIndex(prefix, utils.Sep)
|
||||
if idx > -1 {
|
||||
joinable_prefix = prefix[:idx+1]
|
||||
base_dir = filepath.Dir(location)
|
||||
}
|
||||
}
|
||||
}
|
||||
if base_dir == "" {
|
||||
base_dir = cwd
|
||||
}
|
||||
if !strings.HasPrefix(base_dir, "~") && !filepath.IsAbs(base_dir) {
|
||||
base_dir = filepath.Join(cwd, base_dir)
|
||||
}
|
||||
// fmt.Printf("prefix=%#v base_dir=%#v joinable_prefix=%#v\n", prefix, base_dir, joinable_prefix)
|
||||
entries, err := os.ReadDir(base_dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
q := joinable_prefix + entry.Name()
|
||||
if !strings.HasPrefix(q, prefix) {
|
||||
continue
|
||||
}
|
||||
abspath := filepath.Join(base_dir, entry.Name())
|
||||
dir_to_check := ""
|
||||
data := FileEntry{
|
||||
Name: entry.Name(), Abspath: abspath, Mode: entry.Type(), IsDir: entry.IsDir(),
|
||||
IsSymlink: entry.Type()&os.ModeSymlink == os.ModeSymlink, CompletionCandidate: q}
|
||||
if data.IsSymlink {
|
||||
target, err := filepath.EvalSymlinks(abspath)
|
||||
if err == nil && target != base_dir {
|
||||
td, err := os.Stat(target)
|
||||
if err == nil && td.IsDir() {
|
||||
dir_to_check = target
|
||||
data.IsDir = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if dir_to_check != "" {
|
||||
subentries, err := os.ReadDir(dir_to_check)
|
||||
data.IsEmptyDir = err != nil || len(subentries) == 0
|
||||
}
|
||||
if data.IsDir {
|
||||
data.CompletionCandidate += utils.Sep
|
||||
}
|
||||
callback(&data)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CompleteExecutablesInPath(prefix string, paths ...string) []string {
|
||||
ans := make([]string, 0, 1024)
|
||||
if len(paths) == 0 {
|
||||
paths = filepath.SplitList(os.Getenv("PATH"))
|
||||
}
|
||||
for _, dir := range paths {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err == nil {
|
||||
for _, e := range entries {
|
||||
if strings.HasPrefix(e.Name(), prefix) {
|
||||
// A symlink to a directory has IsDir() false but still passes the X_OK
|
||||
// check, since directories are executable in the access(2) sense.
|
||||
p := filepath.Join(dir, e.Name())
|
||||
if unix.Access(p, unix.X_OK) == nil && !is_dir_or_symlink_to_dir(e, p) {
|
||||
ans = append(ans, e.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func is_dir_or_symlink_to_dir(entry os.DirEntry, path string) bool {
|
||||
if entry.IsDir() {
|
||||
return true
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink == os.ModeSymlink {
|
||||
p, err := filepath.EvalSymlinks(path)
|
||||
if err == nil {
|
||||
s, err := os.Stat(p)
|
||||
if err == nil && s.IsDir() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func fname_based_completer(prefix, cwd string, is_match func(string) bool) []string {
|
||||
ans := make([]string, 0, 1024)
|
||||
_ = CompleteFiles(prefix, func(entry *FileEntry) {
|
||||
if entry.IsDir && !entry.IsEmptyDir {
|
||||
entries, err := os.ReadDir(entry.Abspath)
|
||||
if err == nil {
|
||||
for _, e := range entries {
|
||||
if is_match(strings.ToLower(e.Name())) || is_dir_or_symlink_to_dir(e, filepath.Join(entry.Abspath, e.Name())) {
|
||||
ans = append(ans, entry.CompletionCandidate)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
q := strings.ToLower(entry.Name)
|
||||
if is_match(q) {
|
||||
ans = append(ans, entry.CompletionCandidate)
|
||||
}
|
||||
}, cwd)
|
||||
return ans
|
||||
|
||||
}
|
||||
|
||||
func complete_by_fnmatch(prefix, cwd string, patterns []string) []string {
|
||||
return fname_based_completer(prefix, cwd, func(name string) bool {
|
||||
for _, pat := range patterns {
|
||||
matched, err := filepath.Match(pat, name)
|
||||
if err == nil && matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func complete_by_mimepat(prefix, cwd string, patterns []string) []string {
|
||||
all_allowed := slices.Contains(patterns, "*")
|
||||
return fname_based_completer(prefix, cwd, func(name string) bool {
|
||||
if all_allowed {
|
||||
return true
|
||||
}
|
||||
mt := utils.GuessMimeType(name)
|
||||
if mt == "" {
|
||||
return false
|
||||
}
|
||||
for _, pat := range patterns {
|
||||
matched, err := filepath.Match(pat, mt)
|
||||
if err == nil && matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
type relative_to int
|
||||
|
||||
const (
|
||||
CWD relative_to = iota
|
||||
CONFIG
|
||||
)
|
||||
|
||||
func get_cwd_for_completion(relative_to relative_to) string {
|
||||
switch relative_to {
|
||||
case CONFIG:
|
||||
return utils.ConfigDir()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func make_completer(title string, relative_to relative_to, patterns []string, f func(string, string, []string) []string) CompletionFunc {
|
||||
lpats := make([]string, 0, len(patterns))
|
||||
for _, p := range patterns {
|
||||
lpats = append(lpats, strings.ToLower(p))
|
||||
}
|
||||
cwd := get_cwd_for_completion(relative_to)
|
||||
|
||||
return func(completions *Completions, word string, arg_num int) {
|
||||
q := f(word, cwd, lpats)
|
||||
if len(q) > 0 {
|
||||
dirs, files := make([]string, 0, len(q)), make([]string, 0, len(q))
|
||||
for _, x := range q {
|
||||
if strings.HasSuffix(x, "/") {
|
||||
dirs = append(dirs, x)
|
||||
} else {
|
||||
files = append(files, x)
|
||||
}
|
||||
}
|
||||
if len(dirs) > 0 {
|
||||
mg := completions.AddMatchGroup("Directories")
|
||||
mg.IsFiles = true
|
||||
mg.NoTrailingSpace = true
|
||||
for _, c := range dirs {
|
||||
mg.AddMatch(c)
|
||||
}
|
||||
}
|
||||
mg := completions.AddMatchGroup(title)
|
||||
mg.IsFiles = true
|
||||
for _, c := range files {
|
||||
mg.AddMatch(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func CompleteExecutableFirstArg(completions *Completions, word string, arg_num int) {
|
||||
if arg_num > 1 {
|
||||
completions.Delegate.NumToRemove = completions.CurrentCmd.IndexOfFirstArg + 1 // +1 because the first word is not present in all_words
|
||||
completions.Delegate.Command = completions.AllWords[completions.CurrentCmd.IndexOfFirstArg]
|
||||
return
|
||||
}
|
||||
exes := CompleteExecutablesInPath(word)
|
||||
if len(exes) > 0 {
|
||||
mg := completions.AddMatchGroup("Executables in PATH")
|
||||
for _, exe := range exes {
|
||||
mg.AddMatch(exe)
|
||||
}
|
||||
}
|
||||
|
||||
if len(word) > 0 {
|
||||
mg := completions.AddMatchGroup("Executables")
|
||||
mg.IsFiles = true
|
||||
|
||||
_ = CompleteFiles(word, func(entry *FileEntry) {
|
||||
if entry.IsDir && !entry.IsEmptyDir {
|
||||
// only allow directories that have sub-dirs or executable files in them
|
||||
entries, err := os.ReadDir(entry.Abspath)
|
||||
if err == nil {
|
||||
for _, x := range entries {
|
||||
if x.IsDir() || unix.Access(filepath.Join(entry.Abspath, x.Name()), unix.X_OK) == nil {
|
||||
mg.AddMatch(entry.CompletionCandidate)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if unix.Access(entry.Abspath, unix.X_OK) == nil {
|
||||
mg.AddMatch(entry.CompletionCandidate)
|
||||
}
|
||||
}, "")
|
||||
}
|
||||
}
|
||||
|
||||
func FnmatchCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
|
||||
return make_completer(title, relative_to, patterns, complete_by_fnmatch)
|
||||
}
|
||||
|
||||
func MimepatCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
|
||||
return make_completer(title, relative_to, patterns, complete_by_mimepat)
|
||||
}
|
||||
|
||||
func DirectoryCompleter(title string, relative_to relative_to) CompletionFunc {
|
||||
if title == "" {
|
||||
title = "Directories"
|
||||
}
|
||||
cwd := get_cwd_for_completion(relative_to)
|
||||
|
||||
return func(completions *Completions, word string, arg_num int) {
|
||||
mg := completions.AddMatchGroup(title)
|
||||
mg.NoTrailingSpace = true
|
||||
mg.IsFiles = true
|
||||
_ = CompleteFiles(word, func(entry *FileEntry) {
|
||||
if entry.IsDir {
|
||||
mg.AddMatch(entry.CompletionCandidate)
|
||||
}
|
||||
}, cwd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestCompleteFiles(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
cwd, _ := os.Getwd()
|
||||
if cwd != "" {
|
||||
defer os.Chdir(cwd)
|
||||
}
|
||||
os.Chdir(tdir)
|
||||
|
||||
create := func(parts ...string) {
|
||||
f, _ := os.Create(filepath.Join(tdir, filepath.Join(parts...)))
|
||||
f.Close()
|
||||
}
|
||||
create("one.txt")
|
||||
create("two.txt")
|
||||
os.Mkdir(filepath.Join(tdir, "odir"), 0700)
|
||||
create("odir", "three.txt")
|
||||
create("odir", "four.txt")
|
||||
|
||||
test_candidates := func(prefix string, expected ...string) {
|
||||
if expected == nil {
|
||||
expected = make([]string, 0)
|
||||
}
|
||||
sort.Strings(expected)
|
||||
actual := make([]string, 0, len(expected))
|
||||
CompleteFiles(prefix, func(entry *FileEntry) {
|
||||
actual = append(actual, entry.CompletionCandidate)
|
||||
if _, err := os.Stat(entry.Abspath); err != nil {
|
||||
t.Fatalf("Abspath does not exist: %#v", entry.Abspath)
|
||||
}
|
||||
}, "")
|
||||
sort.Strings(actual)
|
||||
if !reflect.DeepEqual(expected, actual) {
|
||||
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)
|
||||
}
|
||||
}
|
||||
|
||||
test_abs_candidates := func(prefix string, expected ...string) {
|
||||
e := make([]string, len(expected))
|
||||
for i, x := range expected {
|
||||
if filepath.IsAbs(x) {
|
||||
e[i] = x
|
||||
} else {
|
||||
e[i] = filepath.Join(tdir, x)
|
||||
if strings.HasSuffix(x, utils.Sep) {
|
||||
e[i] += utils.Sep
|
||||
}
|
||||
}
|
||||
}
|
||||
test_candidates(prefix, e...)
|
||||
}
|
||||
|
||||
test_cwd_prefix := func(prefix string, expected ...string) {
|
||||
e := make([]string, len(expected))
|
||||
for i, x := range expected {
|
||||
e[i] = "./" + x
|
||||
}
|
||||
test_candidates("./"+prefix, e...)
|
||||
}
|
||||
|
||||
test_cwd_prefix("", "one.txt", "two.txt", "odir/")
|
||||
test_cwd_prefix("t", "two.txt")
|
||||
test_cwd_prefix("x")
|
||||
|
||||
test_abs_candidates(tdir+utils.Sep, "one.txt", "two.txt", "odir/")
|
||||
test_abs_candidates(filepath.Join(tdir, "o"), "one.txt", "odir/")
|
||||
|
||||
test_candidates("", "one.txt", "two.txt", "odir/")
|
||||
test_candidates("t", "two.txt")
|
||||
test_candidates("o", "one.txt", "odir/")
|
||||
test_candidates("odir", "odir/")
|
||||
test_candidates("odir/", "odir/three.txt", "odir/four.txt")
|
||||
test_candidates("odir/f", "odir/four.txt")
|
||||
test_candidates("x")
|
||||
|
||||
// a prefix whose only separator is the leading one, such as /us
|
||||
if entries, err := os.ReadDir(utils.Sep); err == nil && len(entries) > 0 {
|
||||
name := entries[0].Name()
|
||||
prefix := utils.Sep + name[:1]
|
||||
found := false
|
||||
CompleteFiles(prefix, func(entry *FileEntry) {
|
||||
found = found || strings.TrimSuffix(entry.CompletionCandidate, utils.Sep) == utils.Sep+name
|
||||
}, "")
|
||||
if !found {
|
||||
t.Fatalf("Did not get %#v as a completion candidate for prefix: %#v", utils.Sep+name, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
// symlinks to directories are directories
|
||||
os.Symlink(filepath.Join(tdir, "odir"), filepath.Join(tdir, "slink"))
|
||||
c := NewCompletions()
|
||||
DirectoryCompleter("", CWD)(c, "s", 0)
|
||||
if len(c.Groups) != 1 || len(c.Groups[0].Matches) != 1 || c.Groups[0].Matches[0].Word != "slink/" {
|
||||
t.Fatalf("Symlink to directory not completed by DirectoryCompleter: %#v", c.Groups)
|
||||
}
|
||||
|
||||
// filenames inside a directory are matched case-insensitively against patterns
|
||||
os.Mkdir(filepath.Join(tdir, "cdir"), 0700)
|
||||
create("cdir", "B.CONF")
|
||||
c = NewCompletions()
|
||||
FnmatchCompleter("", CWD, "*.conf")(c, "c", 0)
|
||||
found := false
|
||||
for _, g := range c.Groups {
|
||||
for _, m := range g.Matches {
|
||||
found = found || m.Word == "cdir/"
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("Directory containing only an uppercase extension match not completed by FnmatchCompleter: %#v", c.Groups)
|
||||
}
|
||||
|
||||
// mime types kitty knows about but the Go stdlib does not
|
||||
create("zz.py")
|
||||
c = NewCompletions()
|
||||
MimepatCompleter("", CWD, "text/*")(c, "zz", 0)
|
||||
found = false
|
||||
for _, g := range c.Groups {
|
||||
for _, m := range g.Matches {
|
||||
found = found || m.Word == "zz.py"
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("File with a mime type known only to kitty not completed by MimepatCompleter: %#v", c.Groups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteExecutables(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
create := func(base string, name string, mode os.FileMode) {
|
||||
f, _ := os.OpenFile(filepath.Join(tdir, base, name), os.O_CREATE, mode)
|
||||
f.Close()
|
||||
}
|
||||
os.Mkdir(filepath.Join(tdir, "one"), 0700)
|
||||
os.Mkdir(filepath.Join(tdir, "two"), 0700)
|
||||
|
||||
create("", "not-in-path", 0700)
|
||||
create("one", "one-exec", 0700)
|
||||
create("one", "one-not-exec", 0600)
|
||||
create("two", "two-exec", 0700)
|
||||
os.Symlink(filepath.Join(tdir, "two", "two-exec"), filepath.Join(tdir, "one", "s"))
|
||||
os.Symlink(filepath.Join(tdir, "one", "one-not-exec"), filepath.Join(tdir, "one", "n"))
|
||||
// A symlink to a directory passes the X_OK check, so it must not be offered as a command.
|
||||
os.Mkdir(filepath.Join(tdir, "two", "subdir"), 0700)
|
||||
os.Symlink(filepath.Join(tdir, "two", "subdir"), filepath.Join(tdir, "one", "d"))
|
||||
|
||||
t.Setenv("PATH", strings.Join([]string{filepath.Join(tdir, "one"), filepath.Join(tdir, "two")}, string(os.PathListSeparator)))
|
||||
test_candidates := func(prefix string, expected ...string) {
|
||||
if expected == nil {
|
||||
expected = make([]string, 0)
|
||||
}
|
||||
actual := CompleteExecutablesInPath(prefix)
|
||||
sort.Strings(expected)
|
||||
sort.Strings(actual)
|
||||
if !reflect.DeepEqual(expected, actual) {
|
||||
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)
|
||||
}
|
||||
}
|
||||
test_candidates("", "one-exec", "two-exec", "s")
|
||||
test_candidates("o", "one-exec")
|
||||
test_candidates("x")
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func fish_completion_script(commands []string) (string, error) {
|
||||
// One command in fish requires one completion script.
|
||||
// Usage: kitten __complete__ setup fish [kitty|kitten|clone-in-kitty]
|
||||
all_commands := map[string]bool{
|
||||
"kitty": true,
|
||||
"clone-in-kitty": true,
|
||||
"kitten": true,
|
||||
}
|
||||
if len(commands) == 0 {
|
||||
commands = append(commands, utils.Keys(all_commands)...)
|
||||
}
|
||||
script := strings.Builder{}
|
||||
script.WriteString(`function __ksi_completions
|
||||
set --local ct (commandline --current-token)
|
||||
set --local tokens (commandline --tokenize --cut-at-cursor --current-process)
|
||||
printf "%s\n" $tokens $ct | command kitten __complete__ fish | source -
|
||||
end
|
||||
|
||||
`)
|
||||
slices.Sort(commands)
|
||||
for _, cmd := range commands {
|
||||
if all_commands[cmd] {
|
||||
fmt.Fprintf(&script, "complete -f -c %s -a \"(__ksi_completions)\"\n", cmd)
|
||||
} else if strings.Contains(cmd, "=") {
|
||||
// Reserved for `setup SHELL [KEY=VALUE ...]`, not used now.
|
||||
continue
|
||||
} else {
|
||||
return "", fmt.Errorf("No fish completion script for command: %s", cmd)
|
||||
}
|
||||
}
|
||||
return script.String(), nil
|
||||
}
|
||||
|
||||
func fish_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
|
||||
output := strings.Builder{}
|
||||
f := func(format string, args ...any) { fmt.Fprintf(&output, format+"\n", args...) }
|
||||
n := completions[0].Delegate.NumToRemove
|
||||
fm := markup.New(false) // fish freaks out if there are escape codes in the description strings
|
||||
legacy_completion := shell_state["_legacy_completion"]
|
||||
// fish splits the output of the completion function on newlines, so a description
|
||||
// spanning multiple lines adds its continuation lines as spurious candidates.
|
||||
candidate := func(m *Match) string {
|
||||
return strings.ReplaceAll(m.Word+"\t"+fm.Prettify(m.Description), "\n", " ")
|
||||
}
|
||||
if legacy_completion == "fish2" {
|
||||
for _, mg := range completions[0].Groups {
|
||||
for _, m := range mg.Matches {
|
||||
f("%s", candidate(m))
|
||||
}
|
||||
}
|
||||
} else if n > 0 {
|
||||
words := make([]string, len(completions[0].AllWords)-n+1)
|
||||
words[0] = completions[0].Delegate.Command
|
||||
copy(words[1:], completions[0].AllWords[n:])
|
||||
for i, w := range words {
|
||||
words[i] = fmt.Sprintf("(string escape -- %s)", utils.QuoteStringForFish(w))
|
||||
}
|
||||
cmdline := strings.Join(words, " ")
|
||||
f("set __ksi_cmdline " + cmdline)
|
||||
f("complete -C \"$__ksi_cmdline\"")
|
||||
f("set --erase __ksi_cmdline")
|
||||
} else {
|
||||
for _, mg := range completions[0].Groups {
|
||||
for _, m := range mg.Matches {
|
||||
f("echo -- %s", utils.QuoteStringForFish(candidate(m)))
|
||||
}
|
||||
}
|
||||
}
|
||||
// debugf("%#v", output.String())
|
||||
return []byte(output.String()), nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
completion_scripts["fish"] = fish_completion_script
|
||||
input_parsers["fish"] = shell_input_parser
|
||||
output_serializers["fish"] = fish_output_serializer
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFishCompletionMultilineDescription(t *testing.T) {
|
||||
completions := []*Completions{{Groups: []*MatchGroup{{Title: "Options", Matches: []*Match{
|
||||
{Word: "--config", Description: "Specify a path to the configuration file.\n\nIf it is not specified, config files are searched for."},
|
||||
}}}}}
|
||||
for _, shell_state := range []map[string]string{{}, {"_legacy_completion": "fish2"}} {
|
||||
data, err := fish_output_serializer(completions, shell_state)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// each candidate must be a single line, since fish splits the output of the
|
||||
// completion function on newlines to get the candidate list
|
||||
if q := strings.TrimRight(string(data), "\n"); strings.Contains(q, "\n") {
|
||||
t.Fatalf("A multi line description produced more than one candidate with shell state %#v:\n%s", shell_state, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type CommandGroup struct {
|
||||
SubCommands []*Command
|
||||
Title string
|
||||
}
|
||||
|
||||
func (self *CommandGroup) HasVisibleSubCommands() bool {
|
||||
for _, c := range self.SubCommands {
|
||||
if !c.Hidden {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *CommandGroup) Clone(parent *Command) *CommandGroup {
|
||||
ans := CommandGroup{Title: self.Title, SubCommands: make([]*Command, len(self.SubCommands))}
|
||||
for i, o := range self.SubCommands {
|
||||
ans.SubCommands[i] = o.Clone(parent)
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *CommandGroup) AddSubCommand(parent *Command, name string) *Command {
|
||||
ans := NewRootCommand()
|
||||
ans.Parent = parent
|
||||
ans.Name = name
|
||||
self.SubCommands = append(self.SubCommands, ans)
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *CommandGroup) FindSubCommand(name string) *Command {
|
||||
for _, c := range self.SubCommands {
|
||||
if c.Name == name {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *CommandGroup) FindSubCommands(prefix string, matches []*Command) []*Command {
|
||||
for _, c := range self.SubCommands {
|
||||
if strings.HasPrefix(c.Name, prefix) {
|
||||
matches = append(matches, c)
|
||||
}
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
type OptionGroup struct {
|
||||
Options []*Option
|
||||
Title string
|
||||
}
|
||||
|
||||
func (self *OptionGroup) Clone(parent *Command) *OptionGroup {
|
||||
ans := OptionGroup{Title: self.Title, Options: make([]*Option, len(self.Options))}
|
||||
for i, o := range self.Options {
|
||||
c := *o
|
||||
c.init_option()
|
||||
c.Parent = parent
|
||||
ans.Options[i] = &c
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *OptionGroup) AddOption(parent *Command, spec OptionSpec) (*Option, error) {
|
||||
ans, err := option_from_spec(spec)
|
||||
if err == nil {
|
||||
ans.Parent = parent
|
||||
self.Options = append(self.Options, ans)
|
||||
}
|
||||
return ans, err
|
||||
}
|
||||
|
||||
func (self *OptionGroup) AddOptionFromString(parent *Command, items ...string) (*Option, error) {
|
||||
ans, err := OptionFromString(items...)
|
||||
if err == nil {
|
||||
ans.Parent = parent
|
||||
self.Options = append(self.Options, ans)
|
||||
}
|
||||
return ans, err
|
||||
}
|
||||
|
||||
func (self *OptionGroup) FindOptions(prefix_with_hyphens string) []*Option {
|
||||
is_short := !strings.HasPrefix(prefix_with_hyphens, "--")
|
||||
option_name := NormalizeOptionName(prefix_with_hyphens)
|
||||
ans := make([]*Option, 0, 4)
|
||||
for _, q := range self.Options {
|
||||
if q.MatchingAlias(option_name, is_short) != "" {
|
||||
ans = append(ans, q)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
|
||||
}
|
||||
|
||||
func (self *OptionGroup) FindOption(name_with_hyphens string) *Option {
|
||||
is_short := !strings.HasPrefix(name_with_hyphens, "--")
|
||||
option_name := NormalizeOptionName(name_with_hyphens)
|
||||
for _, q := range self.Options {
|
||||
if q.HasAlias(option_name, is_short) {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func ShowError(err error) {
|
||||
formatter := markup.New(tty.IsTerminal(os.Stderr.Fd()))
|
||||
msg := formatter.Prettify(err.Error())
|
||||
fmt.Fprintln(os.Stderr, formatter.Err("Error")+":", msg)
|
||||
}
|
||||
|
||||
func (self *Command) version_string(formatter *markup.Context) string {
|
||||
return fmt.Sprintln(formatter.Italic(self.CommandStringForUsage()), formatter.Opt(kitty.VersionString+kitty.VersionSuffix), "created by", formatter.Title("Kovid Goyal"))
|
||||
}
|
||||
|
||||
func (self *Command) ShowVersion() {
|
||||
formatter := markup.New(tty.IsTerminal(os.Stdout.Fd()))
|
||||
fmt.Fprint(os.Stdout, self.version_string(formatter))
|
||||
}
|
||||
|
||||
func format_with_indent(output io.Writer, text string, indent string, screen_width int) {
|
||||
indented := style.WrapText(text, screen_width, style.WrapOptions{Indent: indent, Ignore_lines_containing: "#placeholder_for_formatting#", Trim_whitespace: true})
|
||||
io.WriteString(output, indented)
|
||||
io.WriteString(output, "\n")
|
||||
}
|
||||
|
||||
func (self *Command) FormatSubCommands(output io.Writer, formatter *markup.Context, screen_width int) {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
if !g.HasVisibleSubCommands() {
|
||||
continue
|
||||
}
|
||||
title := g.Title
|
||||
if title == "" {
|
||||
title = "Commands"
|
||||
}
|
||||
fmt.Fprintln(output)
|
||||
fmt.Fprintln(output, formatter.Title(title)+":")
|
||||
for _, c := range g.SubCommands {
|
||||
if c.Hidden {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintln(output, " ", formatter.Opt(c.Name))
|
||||
format_with_indent(output, formatter.Prettify(c.ShortDescription), " ", screen_width)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (self *Option) FormatOptionForMan(output io.Writer) {
|
||||
fmt.Fprintln(output, ".TP")
|
||||
fmt.Fprint(output, ".BI \"")
|
||||
for i, a := range self.Aliases {
|
||||
fmt.Fprint(output, a.String())
|
||||
if i != len(self.Aliases)-1 {
|
||||
fmt.Fprint(output, ", ")
|
||||
}
|
||||
}
|
||||
fmt.Fprint(output, "\" ")
|
||||
defval := self.Default
|
||||
switch self.OptionType {
|
||||
case CountOption:
|
||||
defval = ""
|
||||
case BoolOption:
|
||||
defval = utils.IfElse(self.Default == "true", "yes", "no")
|
||||
}
|
||||
|
||||
if defval != "" {
|
||||
fmt.Fprintf(output, "\" [=%s]\"", escape_text_for_man(defval))
|
||||
}
|
||||
fmt.Fprintln(output)
|
||||
fmt.Fprintln(output, escape_help_for_man(self.Help))
|
||||
if self.Choices != nil {
|
||||
fmt.Fprintln(output)
|
||||
fmt.Fprintln(output, "Choices: "+strings.Join(self.Choices, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Option) FormatOption(output io.Writer, formatter *markup.Context, screen_width int) {
|
||||
fmt.Fprint(output, " ")
|
||||
for i, a := range self.Aliases {
|
||||
fmt.Fprint(output, formatter.Opt(a.String()))
|
||||
if i != len(self.Aliases)-1 {
|
||||
fmt.Fprint(output, ", ")
|
||||
}
|
||||
}
|
||||
defval := self.Default
|
||||
switch self.OptionType {
|
||||
case CountOption:
|
||||
defval = ""
|
||||
case BoolOption:
|
||||
yn := utils.IfElse(self.Default == "true", "yes", "no")
|
||||
fmt.Fprintf(output, " %s", formatter.Italic("[="+yn+"]"))
|
||||
defval = ""
|
||||
}
|
||||
if defval != "" {
|
||||
fmt.Fprintf(output, " [=%s]", formatter.Italic(defval))
|
||||
}
|
||||
fmt.Fprintln(output)
|
||||
format_with_indent(output, formatter.Prettify(prepare_help_text_for_display(self.Help)), " ", screen_width)
|
||||
if self.Choices != nil {
|
||||
format_with_indent(output, "Choices: "+strings.Join(self.Choices, ", "), " ", screen_width)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Command) ShowHelp() {
|
||||
self.ShowHelpWithCommandString(strings.TrimSpace(self.CommandStringForUsage()))
|
||||
}
|
||||
|
||||
func ShowHelpInPager(text string) {
|
||||
pager := exec.Command(kitty.DefaultPager[0], kitty.DefaultPager[1:]...)
|
||||
pager.Stdin = strings.NewReader(text)
|
||||
pager.Stdout = os.Stdout
|
||||
pager.Stderr = os.Stderr
|
||||
if err := pager.Run(); err != nil {
|
||||
os.Stdout.WriteString(text)
|
||||
}
|
||||
}
|
||||
|
||||
func getDeterministicTimestamp() time.Time {
|
||||
if epoch, err := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); err == nil {
|
||||
return time.Unix(epoch, 0).UTC()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (self *Command) GenerateManPages(level int, recurse bool) (err error) {
|
||||
var names []string
|
||||
p := self
|
||||
for p != nil {
|
||||
names = append(names, p.Name)
|
||||
p = p.Parent
|
||||
}
|
||||
slices.Reverse(names)
|
||||
name := strings.Join(names, "-")
|
||||
outf, err := os.Create(fmt.Sprintf("%s.%d", name, level))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outf.Close()
|
||||
fmt.Fprintf(outf, `.TH "%s" "1" "%s" "%s" "%s"`, name, getDeterministicTimestamp().Format("Jan 02, 2006"), kitty.VersionString, "kitten Manual")
|
||||
fmt.Fprintln(outf)
|
||||
fmt.Fprintln(outf, ".SH Name")
|
||||
fmt.Fprintln(outf, name, "\\-", escape_text_for_man(self.ShortDescription))
|
||||
fmt.Fprintln(outf, ".SH Usage")
|
||||
fmt.Fprintln(outf, ".SY", `"`+self.CommandStringForUsage()+` `+self.Usage+`"`)
|
||||
fmt.Fprintln(outf, ".YS")
|
||||
if self.HelpText != "" {
|
||||
fmt.Fprintln(outf, ".SH Description")
|
||||
fmt.Fprintln(outf, escape_help_for_man(self.HelpText))
|
||||
}
|
||||
|
||||
if self.HasVisibleSubCommands() {
|
||||
for _, g := range self.SubCommandGroups {
|
||||
if !g.HasVisibleSubCommands() {
|
||||
continue
|
||||
}
|
||||
title := g.Title
|
||||
if title == "" {
|
||||
title = "Commands"
|
||||
}
|
||||
fmt.Fprintln(outf, ".SH", title)
|
||||
|
||||
for _, c := range utils.Sort(g.SubCommands, func(a, b *Command) int { return strings.Compare(a.Name, b.Name) }) {
|
||||
if c.Hidden {
|
||||
continue
|
||||
}
|
||||
if recurse {
|
||||
if err = c.GenerateManPages(level, recurse); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(outf, ".TP", "2")
|
||||
fmt.Fprintln(outf, c.Name)
|
||||
fmt.Fprintln(outf, escape_text_for_man(c.ShortDescription)+".", "See: ")
|
||||
fmt.Fprintf(outf, ".MR %s %d\n", name+"-"+c.Name, level)
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(outf, ".PP")
|
||||
fmt.Fprintln(outf, "Get help for an individual command by running:")
|
||||
fmt.Fprintln(outf, ".SY", self.CommandStringForUsage())
|
||||
fmt.Fprintln(outf, "command", "-h")
|
||||
fmt.Fprintln(outf, ".YS")
|
||||
}
|
||||
|
||||
group_titles, gmap := self.GetVisibleOptions()
|
||||
if len(group_titles) > 0 {
|
||||
for _, title := range group_titles {
|
||||
ptitle := title
|
||||
if title == "" {
|
||||
ptitle = "Options"
|
||||
}
|
||||
fmt.Fprintln(outf, ".SH", ptitle)
|
||||
for _, opt := range gmap[title] {
|
||||
opt.FormatOptionForMan(outf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Command) ShowHelpWithCommandString(cs string) {
|
||||
formatter := markup.New(tty.IsTerminal(os.Stdout.Fd()))
|
||||
screen_width := 80
|
||||
if formatter.EscapeCodesAllowed() {
|
||||
var sz *unix.Winsize
|
||||
var tty_size_err error
|
||||
for {
|
||||
sz, tty_size_err = unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
|
||||
if tty_size_err != unix.EINTR {
|
||||
break
|
||||
}
|
||||
}
|
||||
if tty_size_err == nil && sz.Col < 80 {
|
||||
screen_width = int(sz.Col)
|
||||
}
|
||||
}
|
||||
var output strings.Builder
|
||||
|
||||
fmt.Fprintln(&output, formatter.Title("Usage")+":", formatter.Exe(cs), strings.TrimSpace(formatter.Prettify(self.Usage)))
|
||||
fmt.Fprintln(&output)
|
||||
if self.HelpText != "" {
|
||||
format_with_indent(&output, formatter.Prettify(prepare_help_text_for_display(self.HelpText)), "", screen_width)
|
||||
} else if self.ShortDescription != "" {
|
||||
format_with_indent(&output, formatter.Prettify(self.ShortDescription), "", screen_width)
|
||||
}
|
||||
|
||||
if self.HasVisibleSubCommands() {
|
||||
self.FormatSubCommands(&output, formatter, screen_width)
|
||||
fmt.Fprintln(&output)
|
||||
format_with_indent(&output, "Get help for an individual command by running:", "", screen_width)
|
||||
fmt.Fprintln(&output, " ", strings.TrimSpace(self.CommandStringForUsage()), formatter.Italic("command"), "-h")
|
||||
}
|
||||
|
||||
group_titles, gmap := self.GetVisibleOptions()
|
||||
if len(group_titles) > 0 {
|
||||
fmt.Fprintln(&output)
|
||||
for _, title := range group_titles {
|
||||
ptitle := title
|
||||
if title == "" {
|
||||
ptitle = "Options"
|
||||
}
|
||||
fmt.Fprintln(&output, formatter.Title(ptitle)+":")
|
||||
for _, opt := range gmap[title] {
|
||||
opt.FormatOption(&output, formatter, screen_width)
|
||||
fmt.Fprintln(&output)
|
||||
}
|
||||
}
|
||||
}
|
||||
output.WriteString(self.version_string(formatter))
|
||||
output_text := output.String()
|
||||
// fmt.Printf("%#v\n", output_text)
|
||||
if formatter.EscapeCodesAllowed() {
|
||||
ShowHelpInPager(output_text)
|
||||
} else {
|
||||
os.Stdout.WriteString(output_text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package markup
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Context struct {
|
||||
fmt_ctx style.Context
|
||||
|
||||
Cyan, Green, Blue, Magenta, Red, BrightRed, Yellow, Italic, Bold, Dim, Title, Exe, Opt, Emph, Err, Code func(args ...any) string
|
||||
Url func(string, string) string
|
||||
}
|
||||
|
||||
var (
|
||||
fmt_ctx = style.Context{}
|
||||
)
|
||||
|
||||
func New(allow_escape_codes bool) *Context {
|
||||
ans := Context{}
|
||||
ans.fmt_ctx.AllowEscapeCodes = allow_escape_codes
|
||||
fmt_ctx := &ans.fmt_ctx
|
||||
|
||||
ans.Cyan = fmt_ctx.SprintFunc("fg=bright-cyan")
|
||||
ans.Red = fmt_ctx.SprintFunc("fg=red")
|
||||
ans.Magenta = fmt_ctx.SprintFunc("fg=magenta")
|
||||
ans.Green = fmt_ctx.SprintFunc("fg=green")
|
||||
ans.Blue = fmt_ctx.SprintFunc("fg=blue")
|
||||
ans.BrightRed = fmt_ctx.SprintFunc("fg=bright-red")
|
||||
ans.Yellow = fmt_ctx.SprintFunc("fg=bright-yellow")
|
||||
ans.Italic = fmt_ctx.SprintFunc("italic")
|
||||
ans.Bold = fmt_ctx.SprintFunc("bold")
|
||||
ans.Dim = fmt_ctx.SprintFunc("dim")
|
||||
ans.Title = fmt_ctx.SprintFunc("bold fg=blue")
|
||||
ans.Exe = fmt_ctx.SprintFunc("bold fg=bright-yellow")
|
||||
ans.Opt = ans.Green
|
||||
ans.Emph = ans.BrightRed
|
||||
ans.Err = fmt_ctx.SprintFunc("bold fg=bright-red")
|
||||
ans.Code = ans.Cyan
|
||||
ans.Url = fmt_ctx.UrlFunc("u=curly uc=cyan")
|
||||
|
||||
return &ans
|
||||
}
|
||||
|
||||
func Remove_backslash_escapes(text string) string {
|
||||
// see https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#escaping-mechanism
|
||||
out := strings.Builder{}
|
||||
prev_was_slash := false
|
||||
out.Grow(len(text))
|
||||
for _, ch := range text {
|
||||
if prev_was_slash {
|
||||
if !unicode.IsSpace(ch) {
|
||||
out.WriteRune(ch)
|
||||
}
|
||||
prev_was_slash = false
|
||||
} else {
|
||||
if ch == '\\' {
|
||||
prev_was_slash = true
|
||||
} else {
|
||||
out.WriteRune(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func ReplaceAllRSTRoles(str string, repl func(Rst_format_match) string) string {
|
||||
var m Rst_format_match
|
||||
rf := func(full_match string, groupdict map[string]utils.SubMatch) string {
|
||||
m.Payload = groupdict["payload"].Text
|
||||
m.Role = groupdict["role"].Text
|
||||
return repl(m)
|
||||
}
|
||||
return utils.ReplaceAll(utils.MustCompile(":(?P<role>[a-z]+):(?:(?:`(?P<payload>[^`]+)`)|(?:'(?P<payload>[^']+)'))"), str, rf)
|
||||
}
|
||||
|
||||
func (self *Context) hyperlink_for_url(url string, text string) string {
|
||||
return self.Url(url, text)
|
||||
}
|
||||
|
||||
func (self *Context) hyperlink_for_path(path string, text string) string {
|
||||
if !fmt_ctx.AllowEscapeCodes {
|
||||
return text
|
||||
}
|
||||
path = strings.ReplaceAll(utils.Abspath(path), string(os.PathSeparator), "/")
|
||||
fi, err := os.Stat(path)
|
||||
if err == nil && fi.IsDir() {
|
||||
path = strings.TrimSuffix(path, "/") + "/"
|
||||
}
|
||||
host := utils.Hostname()
|
||||
url := "file://" + host + path
|
||||
return self.hyperlink_for_url(url, text)
|
||||
}
|
||||
|
||||
func Text_and_target(x string) (text string, target string) {
|
||||
parts := strings.SplitN(x, "<", 2)
|
||||
text = strings.TrimSpace(parts[0])
|
||||
target = strings.TrimRight(parts[len(parts)-1], ">")
|
||||
return
|
||||
}
|
||||
|
||||
type Rst_format_match struct {
|
||||
Role, Payload string
|
||||
}
|
||||
|
||||
func (self *Context) link(x string) string {
|
||||
text, url := Text_and_target(x)
|
||||
return self.hyperlink_for_url(url, text)
|
||||
}
|
||||
|
||||
func (self *Context) ref_hyperlink(x string, prefix string) string {
|
||||
text, target := Text_and_target(x)
|
||||
url := "kitty+doc://" + utils.Hostname() + "/#ref=" + prefix + target
|
||||
text = ReplaceAllRSTRoles(text, func(group Rst_format_match) string {
|
||||
return group.Payload
|
||||
})
|
||||
return self.hyperlink_for_url(url, text)
|
||||
}
|
||||
|
||||
func (self *Context) Prettify(text string) string {
|
||||
return ReplaceAllRSTRoles(text, func(group Rst_format_match) string {
|
||||
val := group.Payload
|
||||
switch group.Role {
|
||||
case "file":
|
||||
if val == "kitty.conf" && self.fmt_ctx.AllowEscapeCodes {
|
||||
path := filepath.Join(utils.ConfigDir(), val)
|
||||
val = self.hyperlink_for_path(path, val)
|
||||
}
|
||||
return self.Italic(val)
|
||||
case "env", "envvar":
|
||||
return self.ref_hyperlink(val, "envvar-")
|
||||
case "doc":
|
||||
text, target := Text_and_target(val)
|
||||
no_title := text == target
|
||||
target = strings.Trim(target, "/")
|
||||
if title, ok := kitty.DocTitleMap[target]; ok && no_title {
|
||||
val = title + " <" + target + ">"
|
||||
} else {
|
||||
val = text + " <" + target + ">"
|
||||
}
|
||||
return self.ref_hyperlink(val, "doc-")
|
||||
case "iss":
|
||||
return self.ref_hyperlink(val, "issues-")
|
||||
case "pull":
|
||||
return self.ref_hyperlink(val, "pull-")
|
||||
case "disc":
|
||||
return self.ref_hyperlink(val, "discussions-")
|
||||
case "ref":
|
||||
return self.ref_hyperlink(val, "")
|
||||
case "ac":
|
||||
return self.ref_hyperlink(val, "action-")
|
||||
case "term":
|
||||
return self.ref_hyperlink(val, "term-")
|
||||
case "code":
|
||||
return self.Code(Remove_backslash_escapes(val))
|
||||
case "link":
|
||||
return self.link(val)
|
||||
case "option":
|
||||
idx := strings.LastIndex(val, "--")
|
||||
if idx < 0 {
|
||||
idx = strings.Index(val, "-")
|
||||
}
|
||||
if idx > -1 {
|
||||
val = strings.TrimSuffix(val[idx:], ">")
|
||||
}
|
||||
return self.Bold(val)
|
||||
case "opt":
|
||||
return self.Bold(val)
|
||||
case "yellow":
|
||||
return self.Yellow(val)
|
||||
case "blue":
|
||||
return self.Blue(val)
|
||||
case "green":
|
||||
return self.Green(val)
|
||||
case "cyan":
|
||||
return self.Cyan(val)
|
||||
case "magenta":
|
||||
return self.Magenta(val)
|
||||
case "emph":
|
||||
return self.Italic(val)
|
||||
default:
|
||||
return val
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (self *Context) SetAllowEscapeCodes(allow_escape_codes bool) {
|
||||
self.fmt_ctx.AllowEscapeCodes = allow_escape_codes
|
||||
}
|
||||
|
||||
func (self *Context) EscapeCodesAllowed() bool {
|
||||
return self.fmt_ctx.AllowEscapeCodes
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func camel_case_dest(x string) string {
|
||||
x = strings.ReplaceAll(strings.ReplaceAll(x, "-", "_"), ",", "")
|
||||
parts := strings.Split(x, "_")
|
||||
for i, p := range parts {
|
||||
parts[i] = utils.Capitalize(p)
|
||||
}
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
/*
|
||||
Create an [Option] from a string. Syntax is:
|
||||
|
||||
--option-name, --option-alias, -s
|
||||
type: string
|
||||
dest: destination
|
||||
choices: choice1, choice2, choice 3
|
||||
depth: 0
|
||||
default: something
|
||||
Help text on multiple lines. Indented lines are preserved as indented blocks. Blank lines
|
||||
are preserved as blank lines. #placeholder_for_formatting# is replaced by the empty string.
|
||||
.. code:: blocks are handled specially. Lines in them starting with "$ " have the $ colored
|
||||
to indicate a prompt.
|
||||
|
||||
Available types are: string, str, list, int, float, count, bool-set, bool-reset, choices
|
||||
The default dest is the first --option-name which must be a long option. The destination is automatically CamelCased from snake_case.
|
||||
If choices are specified type is set to choices automatically.
|
||||
If depth is negative option is added to all subcommands. If depth is positive option is added to sub-commands upto
|
||||
the specified depth.
|
||||
Set the help text to "!" to have an option hidden.
|
||||
*/
|
||||
func OptionFromString(entries ...string) (*Option, error) {
|
||||
return option_from_string(map[string]string{}, entries...)
|
||||
}
|
||||
|
||||
func is_string_slice(f reflect.Value) bool {
|
||||
if f.Kind() != reflect.Slice {
|
||||
return false
|
||||
}
|
||||
return f.Type().Elem().Kind() == reflect.String
|
||||
}
|
||||
|
||||
func OptionsFromStruct(pointer_to_options_struct any) ([]*Option, error) {
|
||||
val := reflect.ValueOf(pointer_to_options_struct).Elem()
|
||||
if val.Kind() != reflect.Struct {
|
||||
return nil, fmt.Errorf("Need a pointer to a struct to set option values on")
|
||||
}
|
||||
ans := make([]*Option, 0, val.NumField())
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
f := val.Field(i)
|
||||
field_name := val.Type().Field(i).Name
|
||||
tag := val.Type().Field(i).Tag
|
||||
if utils.Capitalize(field_name) != field_name || !f.CanSet() {
|
||||
continue
|
||||
}
|
||||
typ := "str"
|
||||
switch f.Kind() {
|
||||
case reflect.Slice:
|
||||
if !is_string_slice(f) {
|
||||
return nil, fmt.Errorf("The field %s is not a slice of strings", field_name)
|
||||
}
|
||||
typ = "list"
|
||||
case reflect.Int:
|
||||
typ = "int"
|
||||
case reflect.Float64:
|
||||
typ = "float"
|
||||
case reflect.Bool:
|
||||
typ = "bool-set"
|
||||
}
|
||||
overrides := map[string]string{"dest": field_name, "type": typ}
|
||||
opt, err := option_from_string(overrides, string(tag))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opt.OptionType == CountOption && f.Kind() != reflect.Int {
|
||||
return nil, fmt.Errorf("The field %s is of count type but in the options struct it does not have type int", field_name)
|
||||
}
|
||||
ans = append(ans, opt)
|
||||
}
|
||||
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
type multi_scan struct {
|
||||
entries []string
|
||||
}
|
||||
|
||||
var mpat *regexp.Regexp
|
||||
|
||||
func (self *Option) init_option() {
|
||||
self.values_from_cmdline = make([]string, 0, 1)
|
||||
self.parsed_values_from_cmdline = make([]any, 0, 1)
|
||||
}
|
||||
func option_from_spec(spec OptionSpec) (*Option, error) {
|
||||
ans := Option{
|
||||
Help: spec.Help,
|
||||
}
|
||||
ans.init_option()
|
||||
parts := strings.Split(spec.Name, " ")
|
||||
ans.Name = camel_case_dest(parts[0])
|
||||
ans.Aliases = make([]Alias, len(parts))
|
||||
for i, x := range parts {
|
||||
ans.Aliases[i] = Alias{NameWithoutHyphens: strings.TrimLeft(x, "-"), IsShort: !strings.HasPrefix(x, "--")}
|
||||
}
|
||||
if spec.Dest != "" {
|
||||
ans.Name = spec.Dest
|
||||
}
|
||||
ans.Depth = spec.Depth
|
||||
if spec.Choices != "" {
|
||||
parts := strings.Split(spec.Choices, ",")
|
||||
if len(parts) == 1 {
|
||||
parts = strings.Split(spec.Choices, " ")
|
||||
} else {
|
||||
for i, x := range parts {
|
||||
parts[i] = strings.TrimSpace(x)
|
||||
}
|
||||
}
|
||||
ans.Choices = parts
|
||||
ans.OptionType = StringOption
|
||||
if ans.Default == "" {
|
||||
ans.Default = parts[0]
|
||||
}
|
||||
} else {
|
||||
switch spec.Type {
|
||||
case "choice", "choices":
|
||||
ans.OptionType = StringOption
|
||||
case "int":
|
||||
ans.OptionType = IntegerOption
|
||||
ans.Default = "0"
|
||||
case "float":
|
||||
ans.OptionType = FloatOption
|
||||
ans.Default = "0"
|
||||
case "count":
|
||||
ans.OptionType = CountOption
|
||||
ans.Default = "0"
|
||||
case "bool-set":
|
||||
ans.OptionType = BoolOption
|
||||
ans.Default = "false"
|
||||
case "bool-reset":
|
||||
ans.OptionType = BoolOption
|
||||
ans.Default = "true"
|
||||
for _, a := range ans.Aliases {
|
||||
a.IsUnset = true
|
||||
}
|
||||
case "list":
|
||||
ans.IsList = true
|
||||
fallthrough
|
||||
case "str", "string", "":
|
||||
ans.OptionType = StringOption
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown option type: %s", spec.Type)
|
||||
}
|
||||
}
|
||||
if spec.Default != "" {
|
||||
ans.Default = spec.Default
|
||||
}
|
||||
ans.Help = spec.Help
|
||||
ans.Hidden = spec.Help == "!"
|
||||
pval, err := ans.parse_value(ans.Default)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ans.parsed_default = pval
|
||||
if ans.IsList {
|
||||
if ans.Default == "" {
|
||||
ans.parsed_default = nil
|
||||
} else if ans.parsed_default, err = shlex.Split(ans.Default); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ans.Completer = spec.Completer
|
||||
if ans.Aliases == nil || len(ans.Aliases) == 0 {
|
||||
return nil, fmt.Errorf("No --aliases specified for option")
|
||||
}
|
||||
if ans.Name == "" {
|
||||
return nil, fmt.Errorf("No dest specified for option")
|
||||
}
|
||||
return &ans, nil
|
||||
}
|
||||
|
||||
func indent_of_line(x string) int {
|
||||
return len(x) - len(strings.TrimLeft(x, " \n\t\v\f"))
|
||||
}
|
||||
|
||||
func escape_text_for_man(raw string) string {
|
||||
italic := func(x string) string {
|
||||
return "\n.I " + x
|
||||
}
|
||||
bold := func(x string) string {
|
||||
return "\n.B " + x
|
||||
}
|
||||
text_without_target := func(val string) string {
|
||||
text, target := markup.Text_and_target(val)
|
||||
no_title := text == target
|
||||
if no_title {
|
||||
return val
|
||||
}
|
||||
return text
|
||||
}
|
||||
ref_hyperlink := func(val, prefix string) string {
|
||||
return text_without_target(val)
|
||||
}
|
||||
|
||||
raw = markup.ReplaceAllRSTRoles(raw, func(group markup.Rst_format_match) string {
|
||||
val := group.Payload
|
||||
switch group.Role {
|
||||
case "file":
|
||||
return italic(val)
|
||||
case "env", "envvar":
|
||||
return bold(val)
|
||||
case "doc":
|
||||
return text_without_target(val)
|
||||
case "iss":
|
||||
return "Issue #" + val
|
||||
case "pull":
|
||||
return "PR #" + val
|
||||
case "disc":
|
||||
return "Discussion #" + val
|
||||
case "ref":
|
||||
return ref_hyperlink(val, "")
|
||||
case "ac":
|
||||
return ref_hyperlink(val, "action-")
|
||||
case "term":
|
||||
return ref_hyperlink(val, "term-")
|
||||
case "code":
|
||||
return markup.Remove_backslash_escapes(val)
|
||||
case "link":
|
||||
return text_without_target(val)
|
||||
case "option":
|
||||
idx := strings.LastIndex(val, "--")
|
||||
if idx < 0 {
|
||||
idx = strings.Index(val, "-")
|
||||
}
|
||||
if idx > -1 {
|
||||
val = strings.TrimSuffix(val[idx:], ">")
|
||||
}
|
||||
return bold(val)
|
||||
case "opt":
|
||||
return bold(val)
|
||||
case "yellow":
|
||||
return val
|
||||
case "blue":
|
||||
return val
|
||||
case "green":
|
||||
return val
|
||||
case "cyan":
|
||||
return val
|
||||
case "magenta":
|
||||
return val
|
||||
case "emph":
|
||||
return val
|
||||
default:
|
||||
return val
|
||||
}
|
||||
})
|
||||
sb := strings.Builder{}
|
||||
sb.Grow(2 * len(raw))
|
||||
replacements := map[rune]string{
|
||||
'"': `\[dq]`, '\'': `\[aq]`, '-': `\-`, '\\': `\e`, '^': `\(ha`, '`': `\(ga`, '~': `\(ti`,
|
||||
}
|
||||
for _, ch := range raw {
|
||||
if rep, found := replacements[ch]; found {
|
||||
sb.WriteString(rep)
|
||||
} else {
|
||||
sb.WriteRune(ch)
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func escape_help_for_man(raw string) string {
|
||||
help := strings.Builder{}
|
||||
help.Grow(len(raw) + 256)
|
||||
prev_indent := 0
|
||||
in_code_block := false
|
||||
lines := utils.Splitlines(raw)
|
||||
|
||||
handle_non_empty_line := func(i int, line string) int {
|
||||
if strings.TrimSpace(line) == "#placeholder_for_formatting#" {
|
||||
return i + 1
|
||||
}
|
||||
if strings.HasPrefix(line, ".. code::") {
|
||||
in_code_block = true
|
||||
return i + 1
|
||||
}
|
||||
current_indent := indent_of_line(line)
|
||||
if current_indent > 1 {
|
||||
if prev_indent == 0 {
|
||||
help.WriteString("\n")
|
||||
} else {
|
||||
line = strings.TrimSpace(line)
|
||||
}
|
||||
}
|
||||
prev_indent = current_indent
|
||||
if help.Len() > 0 && !strings.HasSuffix(help.String(), "\n") {
|
||||
help.WriteString(" ")
|
||||
}
|
||||
help.WriteString(line)
|
||||
return i
|
||||
}
|
||||
|
||||
handle_empty_line := func(i int, line string) int {
|
||||
prev_indent = 0
|
||||
help.WriteString("\n")
|
||||
if !strings.HasSuffix(help.String(), "::") {
|
||||
help.WriteString("\n")
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
handle_code_block_line := func(i int, line string) int {
|
||||
if line == "" {
|
||||
help.WriteString("\n")
|
||||
return i
|
||||
}
|
||||
current_indent := indent_of_line(line)
|
||||
if current_indent == 0 {
|
||||
in_code_block = false
|
||||
return handle_non_empty_line(i, line)
|
||||
}
|
||||
line = line[4:]
|
||||
is_prompt := strings.HasPrefix(line, "$ ")
|
||||
if is_prompt {
|
||||
help.WriteString(":yellow:`$ `")
|
||||
line = line[2:]
|
||||
}
|
||||
help.WriteString(line)
|
||||
help.WriteString("\n")
|
||||
return i
|
||||
}
|
||||
|
||||
for i := 0; i < len(lines); i++ {
|
||||
line := lines[i]
|
||||
if in_code_block {
|
||||
i = handle_code_block_line(i, line)
|
||||
continue
|
||||
}
|
||||
if line != "" {
|
||||
i = handle_non_empty_line(i, line)
|
||||
} else {
|
||||
i = handle_empty_line(i, line)
|
||||
}
|
||||
}
|
||||
return escape_text_for_man(help.String())
|
||||
}
|
||||
|
||||
func prepare_help_text_for_display(raw string) string {
|
||||
help := strings.Builder{}
|
||||
help.Grow(len(raw) + 256)
|
||||
prev_indent := 0
|
||||
in_code_block := false
|
||||
lines := utils.Splitlines(raw)
|
||||
|
||||
handle_non_empty_line := func(i int, line string) int {
|
||||
if strings.HasPrefix(line, ".. code::") {
|
||||
in_code_block = true
|
||||
return i + 1
|
||||
}
|
||||
current_indent := indent_of_line(line)
|
||||
if current_indent > 1 {
|
||||
if prev_indent == 0 {
|
||||
help.WriteString("\n")
|
||||
} else {
|
||||
line = strings.TrimSpace(line)
|
||||
}
|
||||
}
|
||||
prev_indent = current_indent
|
||||
if help.Len() > 0 && !strings.HasSuffix(help.String(), "\n") {
|
||||
help.WriteString(" ")
|
||||
}
|
||||
help.WriteString(line)
|
||||
return i
|
||||
}
|
||||
|
||||
handle_empty_line := func(i int, line string) int {
|
||||
prev_indent = 0
|
||||
help.WriteString("\n")
|
||||
if !strings.HasSuffix(help.String(), "::") {
|
||||
help.WriteString("\n")
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
handle_code_block_line := func(i int, line string) int {
|
||||
if line == "" {
|
||||
help.WriteString("\n")
|
||||
return i
|
||||
}
|
||||
current_indent := indent_of_line(line)
|
||||
if current_indent == 0 {
|
||||
in_code_block = false
|
||||
return handle_non_empty_line(i, line)
|
||||
}
|
||||
line = line[4:]
|
||||
is_prompt := strings.HasPrefix(line, "$ ")
|
||||
if is_prompt {
|
||||
help.WriteString(":yellow:`$ `")
|
||||
line = line[2:]
|
||||
}
|
||||
help.WriteString(line)
|
||||
help.WriteString("\n")
|
||||
return i
|
||||
}
|
||||
|
||||
for i := 0; i < len(lines); i++ {
|
||||
line := lines[i]
|
||||
if in_code_block {
|
||||
i = handle_code_block_line(i, line)
|
||||
continue
|
||||
}
|
||||
if line != "" {
|
||||
i = handle_non_empty_line(i, line)
|
||||
} else {
|
||||
i = handle_empty_line(i, line)
|
||||
}
|
||||
}
|
||||
return help.String()
|
||||
}
|
||||
|
||||
func option_from_string(overrides map[string]string, entries ...string) (*Option, error) {
|
||||
if mpat == nil {
|
||||
mpat = regexp.MustCompile("^([a-z]+)=(.+)")
|
||||
}
|
||||
spec := OptionSpec{}
|
||||
scanner := utils.NewScanLines(entries...)
|
||||
in_help := false
|
||||
help := strings.Builder{}
|
||||
help.Grow(2048)
|
||||
|
||||
if dq, found := overrides["type"]; found {
|
||||
spec.Type = dq
|
||||
}
|
||||
if dq, found := overrides["dest"]; found {
|
||||
spec.Dest = dq
|
||||
}
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if spec.Name == "" {
|
||||
if strings.HasPrefix(line, "--") {
|
||||
spec.Name = line
|
||||
}
|
||||
} else if in_help {
|
||||
spec.Help += line + "\n"
|
||||
} else {
|
||||
line = strings.TrimSpace(line)
|
||||
matches := mpat.FindStringSubmatch(line)
|
||||
if matches == nil {
|
||||
continue
|
||||
}
|
||||
k, v := matches[1], matches[2]
|
||||
switch k {
|
||||
case "choices":
|
||||
spec.Choices = v
|
||||
case "default":
|
||||
if overrides["default"] == "" {
|
||||
spec.Default = v
|
||||
}
|
||||
case "dest":
|
||||
if overrides["dest"] == "" {
|
||||
spec.Dest = v
|
||||
}
|
||||
case "depth":
|
||||
depth, err := strconv.ParseInt(v, 0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
spec.Depth = int(depth)
|
||||
case "condition", "completion":
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown option metadata key: %s", k)
|
||||
case "type":
|
||||
spec.Type = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return option_from_spec(spec)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type OptionType int
|
||||
|
||||
const (
|
||||
StringOption OptionType = iota
|
||||
IntegerOption
|
||||
FloatOption
|
||||
BoolOption
|
||||
CountOption
|
||||
)
|
||||
|
||||
type Alias struct {
|
||||
NameWithoutHyphens string
|
||||
IsShort bool
|
||||
IsUnset bool
|
||||
}
|
||||
|
||||
func (self *Alias) String() string {
|
||||
if self.IsShort {
|
||||
return "-" + self.NameWithoutHyphens
|
||||
}
|
||||
return "--" + self.NameWithoutHyphens
|
||||
}
|
||||
|
||||
type OptionSpec struct {
|
||||
Name string
|
||||
Type string
|
||||
Dest string
|
||||
Choices string
|
||||
Depth int
|
||||
Default string
|
||||
Help string
|
||||
Completer CompletionFunc
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
Name string
|
||||
Aliases []Alias
|
||||
Choices []string
|
||||
Default string
|
||||
OptionType OptionType
|
||||
Hidden bool
|
||||
Depth int
|
||||
Help string
|
||||
IsList bool
|
||||
Parent *Command
|
||||
Completer CompletionFunc
|
||||
|
||||
values_from_cmdline []string
|
||||
parsed_values_from_cmdline []any
|
||||
parsed_default any
|
||||
seen_option string
|
||||
}
|
||||
|
||||
func (self *Option) reset() {
|
||||
self.values_from_cmdline = self.values_from_cmdline[:0]
|
||||
self.parsed_values_from_cmdline = self.parsed_values_from_cmdline[:0]
|
||||
self.seen_option = ""
|
||||
}
|
||||
|
||||
func (self *Option) needs_argument() bool {
|
||||
return self.OptionType != BoolOption && self.OptionType != CountOption
|
||||
}
|
||||
|
||||
func (self *Option) MatchingAlias(prefix_without_hyphens string, is_short bool) string {
|
||||
for _, a := range self.Aliases {
|
||||
if a.IsShort == is_short && strings.HasPrefix(a.NameWithoutHyphens, prefix_without_hyphens) {
|
||||
return a.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *Option) HasAlias(name_without_hyphens string, is_short bool) bool {
|
||||
for _, a := range self.Aliases {
|
||||
if a.IsShort == is_short && a.NameWithoutHyphens == name_without_hyphens {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ParseError struct {
|
||||
Option *Option
|
||||
Message string
|
||||
}
|
||||
|
||||
func (self *ParseError) Error() string { return self.Message }
|
||||
|
||||
func NormalizeOptionName(name string) string {
|
||||
return strings.ReplaceAll(strings.TrimLeft(name, "-"), "_", "-")
|
||||
}
|
||||
|
||||
func (self *Option) parsed_value() any {
|
||||
if len(self.values_from_cmdline) == 0 {
|
||||
if self.IsList {
|
||||
if self.parsed_default == nil {
|
||||
return []string{}
|
||||
}
|
||||
}
|
||||
return self.parsed_default
|
||||
}
|
||||
switch self.OptionType {
|
||||
case CountOption:
|
||||
return len(self.parsed_values_from_cmdline)
|
||||
case StringOption:
|
||||
if self.IsList {
|
||||
ans := make([]string, 0, len(self.parsed_values_from_cmdline)+2)
|
||||
if self.parsed_default != nil {
|
||||
ans = append(ans, self.parsed_default.([]string)...)
|
||||
}
|
||||
for _, x := range self.parsed_values_from_cmdline {
|
||||
ans = append(ans, x.(string))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
fallthrough
|
||||
default:
|
||||
return self.parsed_values_from_cmdline[len(self.parsed_values_from_cmdline)-1]
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Option) parse_value(val string) (any, error) {
|
||||
switch self.OptionType {
|
||||
case BoolOption:
|
||||
switch val {
|
||||
case "y", "yes", "true":
|
||||
return true, nil
|
||||
case "n", "no", "false":
|
||||
return false, nil
|
||||
default:
|
||||
return nil, &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`.", val, self.seen_option)}
|
||||
}
|
||||
case StringOption:
|
||||
return val, nil
|
||||
case IntegerOption, CountOption:
|
||||
pval, err := strconv.ParseInt(val, 0, 0)
|
||||
if err != nil {
|
||||
return nil, &ParseError{Option: self, Message: fmt.Sprintf(
|
||||
":yellow:`%s` is not a valid number for :bold:`%s`. Only integers in decimal, hexadecimal, binary or octal notation are accepted.", val, self.seen_option)}
|
||||
}
|
||||
return int(pval), nil
|
||||
case FloatOption:
|
||||
pval, err := strconv.ParseFloat(val, 64)
|
||||
if err != nil {
|
||||
return nil, &ParseError{Option: self, Message: fmt.Sprintf(
|
||||
":yellow:`%s` is not a valid number for :bold:`%s`. Only floats in decimal and hexadecimal notation are accepted.", val, self.seen_option)}
|
||||
}
|
||||
return pval, nil
|
||||
default:
|
||||
return nil, &ParseError{Option: self, Message: fmt.Sprintf("Unknown option type for %s", self.Name)}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Option) add_value(val string) error {
|
||||
name_without_hyphens := NormalizeOptionName(self.seen_option)
|
||||
switch self.OptionType {
|
||||
case BoolOption:
|
||||
if val == "" {
|
||||
for _, x := range self.Aliases {
|
||||
if x.NameWithoutHyphens == name_without_hyphens {
|
||||
if x.IsUnset {
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, "false")
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, false)
|
||||
} else {
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, "true")
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
} else {
|
||||
switch val {
|
||||
case "y", "yes", "true":
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, "true")
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, true)
|
||||
case "n", "no", "false":
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, "false")
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, false)
|
||||
default:
|
||||
return &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`. Valid values: %s",
|
||||
val, self.seen_option, "y, yes, true, n, no and false",
|
||||
)}
|
||||
|
||||
}
|
||||
}
|
||||
case StringOption:
|
||||
if self.Choices != nil && !slices.Contains(self.Choices, val) {
|
||||
return &ParseError{Option: self, Message: fmt.Sprintf(":yellow:`%s` is not a valid value for :bold:`%s`. Valid values: %s",
|
||||
val, self.seen_option, strings.Join(self.Choices, ", "),
|
||||
)}
|
||||
}
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, val)
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, val)
|
||||
case IntegerOption, FloatOption:
|
||||
pval, err := self.parse_value(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, val)
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, pval)
|
||||
case CountOption:
|
||||
self.values_from_cmdline = append(self.values_from_cmdline, val)
|
||||
self.parsed_values_from_cmdline = append(self.parsed_values_from_cmdline, 1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *Command) parse_args(ctx *Context, args []string) error {
|
||||
args_to_parse := make([]string, len(args))
|
||||
copy(args_to_parse, args)
|
||||
ctx.SeenCommands = append(ctx.SeenCommands, self)
|
||||
if self.IgnoreAllArgs {
|
||||
self.Args = args
|
||||
return nil
|
||||
}
|
||||
|
||||
var expecting_arg_for *Option
|
||||
options_allowed := true
|
||||
|
||||
consume_arg := func() string { ans := args_to_parse[0]; args_to_parse = args_to_parse[1:]; return ans }
|
||||
|
||||
handle_option := func(opt_str string, has_val bool, opt_val string, val_not_allowed bool) error {
|
||||
possible_options := self.FindOptions(opt_str)
|
||||
var opt *Option
|
||||
if len(possible_options) == 1 {
|
||||
opt = possible_options[0]
|
||||
opt_str = opt.MatchingAlias(NormalizeOptionName(opt_str), !strings.HasPrefix(opt_str, "--"))
|
||||
} else if len(possible_options) == 0 {
|
||||
possibles := self.SuggestionsForOption(opt_str, 2)
|
||||
if len(possibles) > 0 {
|
||||
return &ParseError{Message: fmt.Sprintf("Unknown option: :yellow:`%s`. Did you mean:\n\t%s", opt_str, strings.Join(possibles, "\n\t"))}
|
||||
}
|
||||
return &ParseError{Message: fmt.Sprintf("Unknown option: :yellow:`%s`", opt_str)}
|
||||
} else {
|
||||
ambi := make([]string, len(possible_options))
|
||||
for i, o := range possible_options {
|
||||
ambi[i] = o.MatchingAlias(NormalizeOptionName(opt_str), !strings.HasPrefix(opt_str, "--"))
|
||||
if ambi[i] == opt_str {
|
||||
opt = o
|
||||
break
|
||||
}
|
||||
}
|
||||
if opt == nil {
|
||||
return &ParseError{Message: fmt.Sprintf("Ambiguous option: :yellow:`%s` could be any of: %s", opt_str, strings.Join(ambi, ", "))}
|
||||
}
|
||||
}
|
||||
opt.seen_option = opt_str
|
||||
needs_arg := opt.needs_argument()
|
||||
if needs_arg && val_not_allowed {
|
||||
return &ParseError{Message: fmt.Sprintf("The option: :yellow:`%s` must be followed by a value not another option", opt_str)}
|
||||
}
|
||||
if has_val {
|
||||
if !needs_arg {
|
||||
if opt.OptionType == BoolOption {
|
||||
if err := opt.add_value(opt_val); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return &ParseError{Message: fmt.Sprintf("The option: :yellow:`%s` does not take values", opt_str)}
|
||||
}
|
||||
}
|
||||
return opt.add_value(opt_val)
|
||||
} else if needs_arg {
|
||||
expecting_arg_for = opt
|
||||
} else {
|
||||
opt.add_value("")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for len(args_to_parse) > 0 {
|
||||
arg := consume_arg()
|
||||
|
||||
if expecting_arg_for == nil {
|
||||
if options_allowed && strings.HasPrefix(arg, "-") && arg != "-" {
|
||||
// handle option arg
|
||||
if arg == "--" {
|
||||
options_allowed = false
|
||||
continue
|
||||
}
|
||||
opt_str, opt_val, has_val := strings.Cut(arg, "=")
|
||||
if strings.HasPrefix(opt_str, "--") {
|
||||
err := handle_option(opt_str, has_val, opt_val, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
runes := []rune(opt_str[1:])
|
||||
for i, sl := range runes {
|
||||
var err error
|
||||
if i == len(runes)-1 {
|
||||
err = handle_option("-"+string(sl), has_val, opt_val, false)
|
||||
} else {
|
||||
err = handle_option("-"+string(sl), false, "", true)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// handle non option arg
|
||||
if self.AllowOptionsAfterArgs <= len(self.Args) {
|
||||
options_allowed = false
|
||||
}
|
||||
if self.HasSubCommands() {
|
||||
possible_cmds := self.FindSubCommands(arg)
|
||||
if len(possible_cmds) == 1 {
|
||||
return possible_cmds[0].parse_args(ctx, args_to_parse)
|
||||
}
|
||||
if !self.SubCommandIsOptional {
|
||||
if len(possible_cmds) == 0 {
|
||||
possibles := self.SuggestionsForCommand(arg, 2)
|
||||
if len(possibles) > 0 {
|
||||
return &ParseError{Message: fmt.Sprintf("Unknown subcommand: :yellow:`%s`. Did you mean:\n\t%s", arg, strings.Join(possibles, "\n\t"))}
|
||||
}
|
||||
return &ParseError{Message: fmt.Sprintf(":yellow:`%s` is not a known subcommand for :emph:`%s`. Use --help to get a list of valid subcommands.", arg, self.Name)}
|
||||
}
|
||||
cn := make([]string, len(possible_cmds))
|
||||
for i, x := range possible_cmds {
|
||||
cn[i] = x.Name
|
||||
}
|
||||
return &ParseError{Message: fmt.Sprintf(
|
||||
":yellow:`%s` is not a known subcommand for :emph:`%s`. Did you mean:\n\t%s", arg, self.Name, strings.Join(cn, "\n\t"))}
|
||||
}
|
||||
}
|
||||
self.Args = append(self.Args, arg)
|
||||
}
|
||||
} else {
|
||||
// handle option value
|
||||
err := expecting_arg_for.add_value(arg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expecting_arg_for = nil
|
||||
}
|
||||
}
|
||||
if expecting_arg_for != nil {
|
||||
return &ParseError{Option: expecting_arg_for, Message: fmt.Sprintf("The option: :yellow:`%s` requires a value", expecting_arg_for.seen_option)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type empty_options struct {
|
||||
}
|
||||
|
||||
type base_options struct {
|
||||
FromParent int
|
||||
}
|
||||
|
||||
type options struct {
|
||||
FromParent int
|
||||
SimpleString string
|
||||
Choices string
|
||||
SetMe bool
|
||||
Int int
|
||||
Float float64
|
||||
List []string
|
||||
ListWithDefault []string
|
||||
}
|
||||
|
||||
func TestCLIRequiredOptionValues(t *testing.T) {
|
||||
for _, typ := range []string{"string", "int", "float", "list", "choices"} {
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
option string
|
||||
}{
|
||||
{[]string{"--value"}, "--value"},
|
||||
{[]string{"-v"}, "-v"},
|
||||
{[]string{"-bv"}, "-v"},
|
||||
{[]string{"--value", "1", "--value"}, "--value"},
|
||||
} {
|
||||
for _, child := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/%s/child=%t", typ, strings.Join(tc.args, " "), child), func(t *testing.T) {
|
||||
root := NewRootCommand()
|
||||
root.Add(OptionSpec{Name: "--bool -b", Type: "bool-set", Depth: 1})
|
||||
spec := OptionSpec{Name: "--value -v", Type: typ, Depth: 1}
|
||||
if typ == "choices" {
|
||||
spec.Choices = "1 2"
|
||||
}
|
||||
root.Add(spec)
|
||||
args := []string{"test"}
|
||||
if child {
|
||||
root.AddSubCommand(&Command{Name: "child"})
|
||||
args = append(args, "child")
|
||||
}
|
||||
_, err := root.ParseArgs(append(args, tc.args...))
|
||||
var pe *ParseError
|
||||
if !errors.As(err, &pe) || pe.Option == nil || !strings.Contains(pe.Error(), tc.option) || !strings.Contains(pe.Error(), "requires a value") {
|
||||
t.Fatalf("Expected missing-value error for %s, got %v", tc.option, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIParsing(t *testing.T) {
|
||||
|
||||
rt := func(expected_cmd *Command, cmdline string, expected_options any, expected_args ...string) {
|
||||
if opts, ok := expected_options.(*options); ok && opts.ListWithDefault == nil {
|
||||
opts.ListWithDefault = []string{`1`, `2`}
|
||||
}
|
||||
cp, err := shlex.Split(cmdline)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd, err := expected_cmd.ParseArgs(cp)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, ok := expected_options.(*options); ok {
|
||||
if s.Choices == "" {
|
||||
s.Choices = "a"
|
||||
}
|
||||
if s.List == nil {
|
||||
s.List = make([]string, 0)
|
||||
}
|
||||
}
|
||||
actual_options := reflect.New(reflect.TypeOf(expected_options).Elem()).Interface()
|
||||
err = cmd.GetOptionValues(actual_options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff := cmp.Diff(expected_options, actual_options); diff != "" {
|
||||
t.Fatalf("Option values incorrect (expected != actual):\nCommand line: %s\n%s", cmdline, diff)
|
||||
}
|
||||
if expected_args == nil {
|
||||
expected_args = []string{}
|
||||
}
|
||||
if diff := cmp.Diff(expected_args, cmd.Args); diff != "" {
|
||||
t.Fatalf("Argument values incorrect (expected != actual):\nCommand line: %s\n%s", cmdline, diff)
|
||||
}
|
||||
cmd.Root().ResetAfterParseArgs()
|
||||
}
|
||||
|
||||
root := NewRootCommand()
|
||||
root.Add(OptionSpec{Name: "--from-parent -p", Type: "count", Depth: 1})
|
||||
child1 := root.AddSubCommand(&Command{Name: "child1"})
|
||||
child1.Add(OptionSpec{Name: "--choices", Choices: "a b c"})
|
||||
child1.Add(OptionSpec{Name: "--simple-string -s"})
|
||||
child1.Add(OptionSpec{Name: "--set-me -b", Type: "bool-set"})
|
||||
child1.Add(OptionSpec{Name: "--int -i", Type: "int"})
|
||||
child1.Add(OptionSpec{Name: "--float", Type: "float"})
|
||||
child1.Add(OptionSpec{Name: "--list", Type: "list"})
|
||||
child1.Add(OptionSpec{Name: "--list-with-default -L", Type: "list", Default: "1 2"})
|
||||
child1.SubCommandIsOptional = true
|
||||
gc1 := child1.AddSubCommand(&Command{Name: "gc1"})
|
||||
|
||||
rt(
|
||||
child1, "test --from-parent child1 -ps ss --choices b --from-parent one two",
|
||||
&options{SimpleString: "ss", Choices: "b", FromParent: 3},
|
||||
"one", "two",
|
||||
)
|
||||
rt(child1, "test child1", &options{})
|
||||
rt(child1, "test child1 --set-me one", &options{SetMe: true}, "one")
|
||||
rt(child1, "test child1 --set-me=y one", &options{SetMe: true}, "one")
|
||||
rt(child1, "test child1 --set-me=n one", &options{SetMe: false}, "one")
|
||||
rt(child1, "test child1 --set-me=n --set-me one", &options{SetMe: true}, "one")
|
||||
rt(child1, "test child1 --set-me=y -b=n one", &options{SetMe: false}, "one")
|
||||
rt(child1, "test child1 --set-me --simple-string=foo one", &options{SimpleString: "foo", SetMe: true}, "one")
|
||||
rt(child1, "test child1 --set-me --simp=foo one", &options{SimpleString: "foo", SetMe: true}, "one")
|
||||
rt(child1, "test child1 --set-me --simple-string= one", &options{SetMe: true}, "one")
|
||||
rt(child1, "test child1 --simple-string ''", &options{})
|
||||
rt(child1, "test child1 -bs ''", &options{SetMe: true})
|
||||
rt(child1, "test child1 -bp", &options{SetMe: true, FromParent: 1})
|
||||
rt(child1, "test child1 --simple-string --", &options{SimpleString: "--"})
|
||||
rt(child1, "test child1 --int -3 --simple-s -s --float=3.3", &options{SimpleString: "-s", Int: -3, Float: 3.3})
|
||||
rt(child1, "test child1 -bi=3 --float=3.3", &options{SetMe: true, Int: 3, Float: 3.3})
|
||||
rt(child1, "test child1 --list -3 -p --list one", &options{FromParent: 1, List: []string{"-3", "one"}})
|
||||
rt(child1, "test child1 -L 3 -L 4", &options{ListWithDefault: []string{`1`, `2`, `3`, `4`}})
|
||||
rt(gc1, "test -p child1 -p gc1 xxx", &empty_options{}, "xxx")
|
||||
|
||||
_, err := child1.ParseArgs(strings.Split("test child1 --choices x", " "))
|
||||
if err == nil {
|
||||
t.Fatalf("Invalid choice not caught")
|
||||
}
|
||||
root.ResetAfterParseArgs()
|
||||
gc1.ParseArgs(strings.Split("test child1 -p gc1 xxx", " "))
|
||||
err = gc1.GetOptionValues(&base_options{})
|
||||
if err == nil {
|
||||
t.Fatalf("Invalid choice not caught")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"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/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type cpos struct {
|
||||
x, y int
|
||||
}
|
||||
|
||||
func cpos_from_report(csi string) (ans cpos, err error) {
|
||||
before, after, found := strings.Cut(csi, ";")
|
||||
if !found {
|
||||
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal with no ;")
|
||||
}
|
||||
if ans.y, err = strconv.Atoi(before); err != nil {
|
||||
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal: %s", csi)
|
||||
}
|
||||
if ans.x, err = strconv.Atoi(after); err != nil {
|
||||
return ans, fmt.Errorf("Malformed Cursor Position Report from terminal: %s", csi)
|
||||
}
|
||||
// convert 1-based indexing to zero based indexing
|
||||
ans.x--
|
||||
ans.y--
|
||||
return
|
||||
}
|
||||
|
||||
type test_struct struct {
|
||||
description string
|
||||
num int
|
||||
expected_cursor_positions []int
|
||||
actual_cursor_positions []cpos
|
||||
payload string
|
||||
tester func(actual_cursor_positions []cpos, screen_width int) string
|
||||
payload_gen func(width_in_cells int) string
|
||||
}
|
||||
|
||||
const cursor_position_report = "\x1b[6n"
|
||||
const reset_line = "\r\x1b[K"
|
||||
|
||||
func wrap_gen(width_in_cells int) string {
|
||||
return strings.Repeat(" ", width_in_cells-2) + "\U0001f1ee" + cursor_position_report + "\U0001f1f3" + cursor_position_report
|
||||
}
|
||||
|
||||
func wrap_tester(actual_cursor_positions []cpos, screen_width int) string {
|
||||
if actual_cursor_positions[0].x != actual_cursor_positions[1].x {
|
||||
return fmt.Sprintf("The cursor moved after adding a combining char from: %v -> %v", actual_cursor_positions[0], actual_cursor_positions[1])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func run_tests(tests []*test_struct) (err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
num_reports := 0
|
||||
expected_num_reports := 0
|
||||
gen_payload := func(screen_width int) string {
|
||||
buf := strings.Builder{}
|
||||
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToSet())
|
||||
for _, t := range tests {
|
||||
payload := t.payload
|
||||
if t.payload_gen != nil {
|
||||
payload = t.payload_gen(screen_width)
|
||||
}
|
||||
expected_num_reports += strings.Count(payload, cursor_position_report)
|
||||
buf.WriteString(payload)
|
||||
buf.WriteString(reset_line)
|
||||
if buf.Len() > 512*1024 {
|
||||
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToReset())
|
||||
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToSet())
|
||||
}
|
||||
}
|
||||
buf.WriteString(loop.PENDING_UPDATE.EscapeCodeToReset())
|
||||
buf.WriteString("\x1b[c")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
print_para := func(text string) {
|
||||
sz, _ := lp.ScreenSize()
|
||||
for _, line := range style.WrapTextAsLines(text, int(sz.WidthCells), style.WrapOptions{Trim_whitespace: true}) {
|
||||
lp.Println(line)
|
||||
}
|
||||
lp.Println()
|
||||
}
|
||||
screen_width := 80
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
sz, _ := lp.ScreenSize()
|
||||
screen_width = int(sz.WidthCells)
|
||||
print_para("These tests work by sending text to the terminal and then querying it for its cursor position. Every test is thus different strings sent to the terminal along with a list of expected cursor positions after each string. A failure means the actual cursor position was different from the expected one. A failure where the first expected cursor position is correct but subsequent ones are not, means that the complete string was rendered at the correct width but individual graphemes from the string were not.")
|
||||
print_para("The individual test descriptions use the character ÷ to indicate a position where a break is expected to occur and the character × to indicate a position where no break should happen. ")
|
||||
lp.Printf("Running %d tests, please wait...\n", len(tests))
|
||||
lp.SaveCursorPosition()
|
||||
lp.SetCursorVisible(false)
|
||||
|
||||
lp.QueueWriteString(gen_payload(screen_width))
|
||||
return "", err
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
lp.RestoreCursorPosition()
|
||||
lp.ClearToEndOfScreen()
|
||||
return ""
|
||||
}
|
||||
current_test_idx := 0
|
||||
lp.OnEscapeCode = func(typ loop.EscapeCodeType, data []byte) error {
|
||||
if typ == loop.CSI {
|
||||
switch data[len(data)-1] {
|
||||
case 'c':
|
||||
lp.Quit(0)
|
||||
case 'R':
|
||||
if found := bytes.Contains(data, []byte{';'}); found {
|
||||
if cpos, err := cpos_from_report(utils.UnsafeBytesToString(data[:len(data)-1])); err != nil {
|
||||
return err
|
||||
} else {
|
||||
num_reports++
|
||||
t := tests[current_test_idx]
|
||||
if len(t.actual_cursor_positions) >= len(t.expected_cursor_positions) && current_test_idx+1 < len(tests) {
|
||||
current_test_idx += 1
|
||||
t = tests[current_test_idx]
|
||||
}
|
||||
t.actual_cursor_positions = append(t.actual_cursor_positions, cpos)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err = lp.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
if num_reports != expected_num_reports {
|
||||
return fmt.Errorf("Terminal did not report the cursor position as many times as expected. %d != %d", expected_num_reports, num_reports)
|
||||
}
|
||||
return show_results(tests, screen_width)
|
||||
}
|
||||
|
||||
func show_results(tests []*test_struct, screen_width int) (err error) {
|
||||
num_failures := 0
|
||||
for _, t := range tests {
|
||||
diff := ""
|
||||
if t.tester == nil {
|
||||
ac := make([]int, len(t.actual_cursor_positions))
|
||||
for i, cp := range t.actual_cursor_positions {
|
||||
ac[i] = cp.x
|
||||
}
|
||||
diff = cmp.Diff(t.expected_cursor_positions, ac)
|
||||
} else {
|
||||
diff = t.tester(t.actual_cursor_positions, screen_width)
|
||||
}
|
||||
if diff != "" {
|
||||
fmt.Printf("\x1b[31mTest number %d failed\x1b[39m: %s\n", t.num, t.description)
|
||||
fmt.Println(diff)
|
||||
num_failures++
|
||||
}
|
||||
}
|
||||
if num_failures > 0 {
|
||||
err = fmt.Errorf("%d out of %d tests failed.", num_failures, len(tests))
|
||||
} else {
|
||||
fmt.Println("All tests passed!")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func has_control_chars(text string) bool {
|
||||
for _, ch := range text {
|
||||
if ch < ' ' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func create_tests(gb_tests []kitty.GraphemeBreakTest, width_in_cells int) (tests []*test_struct) {
|
||||
for _, t := range gb_tests {
|
||||
text := strings.Join(t.Data, "")
|
||||
rt, _ := json.Marshal(text)
|
||||
desc := fmt.Sprintf("Unicode GraphemeBreakTest: Text: %s Expected breaks:\n%s", string(rt), t.Comment)
|
||||
if has_control_chars(text) {
|
||||
continue
|
||||
}
|
||||
buf := strings.Builder{}
|
||||
buf.WriteString(" " + text + cursor_position_report + reset_line + " ")
|
||||
expected_cursor_positions := []int{1 + wcswidth.Stringwidth(text)}
|
||||
// Now test cursor position after each individual grapheme
|
||||
pos := 0
|
||||
for _, grapheme := range t.Data {
|
||||
buf.WriteString(grapheme + cursor_position_report)
|
||||
pos += wcswidth.Stringwidth(grapheme)
|
||||
expected_cursor_positions = append(expected_cursor_positions, 1+pos)
|
||||
}
|
||||
test := test_struct{num: len(tests) + 1, description: desc, payload: buf.String(), expected_cursor_positions: expected_cursor_positions}
|
||||
tests = append(tests, &test)
|
||||
}
|
||||
test := test_struct{
|
||||
num: len(tests) + 1, description: "Check that combining characters are merged into last cell even when cursor is on the next line",
|
||||
payload_gen: wrap_gen, tester: wrap_tester}
|
||||
tests = append(tests, &test)
|
||||
return
|
||||
}
|
||||
|
||||
func main(allowed_tests *utils.Set[int]) (rc int, err error) {
|
||||
term, err := tty.OpenControllingTerm()
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Could not open controlling terminal with error: %w", err)
|
||||
}
|
||||
sz, err := term.GetSize()
|
||||
term.Close()
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Could not get size of controlling terminal with error: %w", err)
|
||||
}
|
||||
width_in_cells := int(sz.Col)
|
||||
if gb_tests, err := kitty.LoadGraphemeBreakTests(); err == nil {
|
||||
tests := create_tests(gb_tests, width_in_cells)
|
||||
if allowed_tests.Len() > 0 {
|
||||
temp := make([]*test_struct, 0, len(tests))
|
||||
for _, t := range tests {
|
||||
if allowed_tests.Has(t.num) {
|
||||
temp = append(temp, t)
|
||||
}
|
||||
}
|
||||
tests = temp
|
||||
}
|
||||
if err = run_tests(tests); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
} else {
|
||||
return 1, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func WcswidthKittenEntryPoint(root *Command) {
|
||||
root.AddSubCommand(&Command{
|
||||
Name: "__width_test__",
|
||||
Usage: "[test number to run...]",
|
||||
HelpText: "Test the terminal for compliance with the kitty text-sizing specification's splitting of text into cells. You can optionally specify specific test numbers to run.",
|
||||
Hidden: true,
|
||||
OnlyArgsAllowed: true,
|
||||
Run: func(cmd *Command, args []string) (rc int, err error) {
|
||||
allowed_tests := utils.NewSet[int]()
|
||||
for _, arg := range args {
|
||||
if x, err := strconv.Atoi(arg); err == nil {
|
||||
allowed_tests.Add(x)
|
||||
} else {
|
||||
return 1, fmt.Errorf("%s is not a valid test number", arg)
|
||||
}
|
||||
}
|
||||
return main(allowed_tests)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func zsh_completion_script(commands []string) (string, error) {
|
||||
return `#compdef kitty
|
||||
|
||||
_kitty() {
|
||||
(( ${+commands[kitten]} )) || builtin return
|
||||
builtin local src cmd=${(F)words:0:$CURRENT}
|
||||
# Send all words up to the word the cursor is currently on.
|
||||
src=$(builtin command kitten __complete__ zsh "_matcher=$_matcher" <<<$cmd) || builtin return
|
||||
builtin eval "$src"
|
||||
}
|
||||
|
||||
if (( $+functions[compdef] )); then
|
||||
compdef _kitty kitty
|
||||
compdef _kitty clone-in-kitty
|
||||
compdef _kitty kitten
|
||||
fi
|
||||
`, nil
|
||||
}
|
||||
|
||||
func shell_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
|
||||
raw := string(data)
|
||||
new_word := strings.HasSuffix(raw, "\n\n")
|
||||
raw = strings.TrimRight(raw, "\n \t")
|
||||
scanner := utils.NewLineScanner(raw)
|
||||
words := make([]string, 0, 32)
|
||||
for scanner.Scan() {
|
||||
words = append(words, scanner.Text())
|
||||
}
|
||||
if new_word {
|
||||
words = append(words, "")
|
||||
}
|
||||
return [][]string{words}, nil
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func zsh_input_parser(data []byte, shell_state map[string]string) ([][]string, error) {
|
||||
matcher := shell_state["_matcher"]
|
||||
q := ""
|
||||
if matcher != "" {
|
||||
q = strings.Split(strings.ToLower(matcher), ":")[0][:1]
|
||||
}
|
||||
if q != "" && strings.Contains("lrbe", q) {
|
||||
// this is zsh anchor based matching
|
||||
// https://zsh.sourceforge.io/Doc/Release/Completion-Widgets.html#Completion-Matching-Control
|
||||
// can be specified with matcher-list and some systems do it by default,
|
||||
// for example, Debian, which adds the following to zshrc
|
||||
// zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=* l:|=*'
|
||||
// For some reason that I dont have the
|
||||
// time/interest to figure out, returning completion candidates for
|
||||
// these matcher types break completion, so just abort in this case.
|
||||
return nil, fmt.Errorf("ZSH anchor based matching active, cannot complete. Turn it off by setting zstyle :completion: to something that does not use anchors in your ~/.zshrc")
|
||||
}
|
||||
return shell_input_parser(data, shell_state)
|
||||
}
|
||||
|
||||
func (self *Match) FormatForCompletionList(max_word_len int, f *markup.Context, screen_width int) string {
|
||||
word := self.Word
|
||||
desc := self.Description
|
||||
if desc == "" {
|
||||
return word
|
||||
}
|
||||
word_len := wcswidth.Stringwidth(word)
|
||||
line, _, _ := strings.Cut(strings.TrimSpace(desc), "\n")
|
||||
desc = f.Prettify(line)
|
||||
|
||||
multiline := false
|
||||
max_desc_len := screen_width - max_word_len - 3
|
||||
if word_len > max_word_len {
|
||||
multiline = true
|
||||
} else {
|
||||
word += strings.Repeat(" ", max_word_len-word_len)
|
||||
}
|
||||
if wcswidth.Stringwidth(desc) > max_desc_len {
|
||||
desc = style.WrapTextAsLines(desc, max_desc_len-2, style.WrapOptions{})[0] + "…"
|
||||
}
|
||||
if multiline {
|
||||
return word + "\n" + strings.Repeat(" ", max_word_len+2) + desc
|
||||
}
|
||||
return word + " " + desc
|
||||
}
|
||||
|
||||
func serialize(completions *Completions, f *markup.Context, screen_width int) ([]byte, error) {
|
||||
output := strings.Builder{}
|
||||
if completions.Delegate.NumToRemove > 0 {
|
||||
for i := 0; i < completions.Delegate.NumToRemove; i++ {
|
||||
fmt.Fprintln(&output, "shift words")
|
||||
fmt.Fprintln(&output, "(( CURRENT-- ))")
|
||||
}
|
||||
service := utils.QuoteStringForSH(completions.Delegate.Command)
|
||||
fmt.Fprintln(&output, "words[1]="+service)
|
||||
fmt.Fprintln(&output, "_normal -p", service)
|
||||
} else {
|
||||
if len(completions.Groups) > 0 {
|
||||
// Respect the user's description format, falling back to bold group titles
|
||||
fmt.Fprintln(&output, "builtin local _kitty_fmt _kitty_expl")
|
||||
output.WriteString(`builtin zstyle -s ":completion:${curcontext}:descriptions" format _kitty_fmt || _kitty_fmt='%B%d%b'` + "\n")
|
||||
}
|
||||
for _, mg := range completions.Groups {
|
||||
fmt.Fprintln(&output, "builtin zformat -f _kitty_expl \"$_kitty_fmt\"", utils.QuoteStringForSH("d:"+mg.Title))
|
||||
cmd := strings.Builder{}
|
||||
escape_ourselves := mg.IsFiles // zsh quoting quotes a leading ~/ in filenames which is wrong
|
||||
cmd.WriteString("compadd -U ")
|
||||
if escape_ourselves {
|
||||
cmd.WriteString("-Q ")
|
||||
}
|
||||
cmd.WriteString("-J ")
|
||||
cmd.WriteString(utils.QuoteStringForSH(mg.Title))
|
||||
cmd.WriteString(` -X "$_kitty_expl"`)
|
||||
if mg.NoTrailingSpace {
|
||||
cmd.WriteString(" -S ''")
|
||||
}
|
||||
if mg.IsFiles {
|
||||
cmd.WriteString(" -f")
|
||||
}
|
||||
lcp := mg.remove_common_prefix()
|
||||
if lcp != "" {
|
||||
cmd.WriteString(" -p ")
|
||||
cmd.WriteString(utils.QuoteStringForSH(lcp))
|
||||
}
|
||||
if mg.has_descriptions() {
|
||||
fmt.Fprintln(&output, "compdescriptions=(")
|
||||
limit := mg.max_visual_word_length(16)
|
||||
for _, m := range mg.Matches {
|
||||
fmt.Fprintln(&output, utils.QuoteStringForSH(wcswidth.StripEscapeCodes(m.FormatForCompletionList(limit, f, screen_width))))
|
||||
}
|
||||
fmt.Fprintln(&output, ")")
|
||||
cmd.WriteString(" -l -d compdescriptions")
|
||||
}
|
||||
cmd.WriteString(" --")
|
||||
for _, m := range mg.Matches {
|
||||
cmd.WriteString(" ")
|
||||
w := m.Word
|
||||
if escape_ourselves {
|
||||
w = utils.EscapeSHMetaCharacters(m.Word)
|
||||
}
|
||||
cmd.WriteString(utils.QuoteStringForSH(w))
|
||||
}
|
||||
fmt.Fprintln(&output, cmd.String(), ";")
|
||||
}
|
||||
}
|
||||
// debugf("%#v", output.String())
|
||||
return []byte(output.String()), nil
|
||||
}
|
||||
|
||||
func zsh_output_serializer(completions []*Completions, shell_state map[string]string) ([]byte, error) {
|
||||
var f *markup.Context
|
||||
screen_width := 80
|
||||
ctty, err := tty.OpenControllingTerm()
|
||||
if err == nil {
|
||||
sz, err := ctty.GetSize()
|
||||
ctty.Close()
|
||||
if err == nil {
|
||||
screen_width = int(sz.Col)
|
||||
}
|
||||
}
|
||||
f = markup.New(false) // ZSH freaks out if there are escape codes in the description strings
|
||||
return serialize(completions[0], f, screen_width)
|
||||
}
|
||||
|
||||
func init() {
|
||||
completion_scripts["zsh"] = zsh_completion_script
|
||||
input_parsers["zsh"] = zsh_input_parser
|
||||
output_serializers["zsh"] = zsh_output_serializer
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/process"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func StringToBool(x string) bool {
|
||||
x = strings.ToLower(x)
|
||||
return x == "y" || x == "yes" || x == "true"
|
||||
}
|
||||
|
||||
type ConfigLine struct {
|
||||
Src_file, Line string
|
||||
Line_number int
|
||||
Err error
|
||||
}
|
||||
|
||||
type ConfigParser struct {
|
||||
LineHandler func(key, val string) error
|
||||
CommentsHandler func(line string) error
|
||||
SourceHandler func(text, path string)
|
||||
AllIncludedFiles *utils.Set[string]
|
||||
|
||||
bad_lines []ConfigLine
|
||||
seen_includes map[string]bool
|
||||
override_env []string
|
||||
}
|
||||
|
||||
type Scanner interface {
|
||||
Scan() bool
|
||||
Text() string
|
||||
Err() error
|
||||
}
|
||||
|
||||
func (self *ConfigParser) BadLines() []ConfigLine {
|
||||
return self.bad_lines
|
||||
}
|
||||
|
||||
var key_pat = sync.OnceValue(func() *regexp.Regexp {
|
||||
return regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9_-]*)\s+(.+)$`)
|
||||
})
|
||||
|
||||
var kitty_os = sync.OnceValue(func() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
return "linux"
|
||||
case "freebsd", "netbsd", "openbsd":
|
||||
return "bsd"
|
||||
case "darwin":
|
||||
return "macos"
|
||||
}
|
||||
return "unknown"
|
||||
})
|
||||
|
||||
func geninclude(path string) (string, error) {
|
||||
cmd := exec.Command(path)
|
||||
cmd.Env = os.Environ()
|
||||
cmd.Env = append(cmd.Env, "KITTY_OS="+kitty_os())
|
||||
if strings.HasSuffix(path, ".py") && unix.Access(path, unix.X_OK) != nil {
|
||||
if utils.KittyExe() == "" || strings.HasPrefix(path, ":") {
|
||||
cmd = exec.Command("python", path)
|
||||
} else {
|
||||
cmd = exec.Command(utils.KittyExe(), "+launch", path)
|
||||
}
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = cmd.Start(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := io.ReadAll(stdout)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = cmd.Wait(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return utils.UnsafeBytesToString(data), nil
|
||||
}
|
||||
|
||||
func ExpandVars(x string) string {
|
||||
return os.Expand(x, func(k string) string {
|
||||
if k == "KITTY_OS" {
|
||||
return kitty_os()
|
||||
}
|
||||
return os.Getenv(k)
|
||||
})
|
||||
}
|
||||
|
||||
const OverridesFileName = "<overrides>"
|
||||
|
||||
func (self *ConfigParser) parse(scanner Scanner, name, base_path_for_includes string, depth int) error {
|
||||
if self.seen_includes[name] { // avoid include loops
|
||||
return nil
|
||||
}
|
||||
self.seen_includes[name] = true
|
||||
if self.AllIncludedFiles != nil && name != OverridesFileName {
|
||||
self.AllIncludedFiles.Add(name)
|
||||
}
|
||||
|
||||
recurse := func(r io.Reader, nname, base_path_for_includes string) error {
|
||||
if depth > 32 {
|
||||
return fmt.Errorf("Too many nested include directives while processing config file: %s", name)
|
||||
}
|
||||
escanner := bufio.NewScanner(r)
|
||||
return self.parse(escanner, nname, base_path_for_includes, depth+1)
|
||||
}
|
||||
|
||||
make_absolute := func(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("Empty include paths not allowed")
|
||||
}
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(base_path_for_includes, path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
lnum := 0
|
||||
next_line_num := 0
|
||||
next_line := ""
|
||||
var line string
|
||||
|
||||
add_bad_line := func(err error) {
|
||||
self.bad_lines = append(self.bad_lines, ConfigLine{Src_file: name, Line: line, Line_number: lnum, Err: err})
|
||||
}
|
||||
|
||||
for {
|
||||
if next_line != "" {
|
||||
line = next_line
|
||||
} else {
|
||||
if scanner.Scan() {
|
||||
line = strings.TrimLeft(scanner.Text(), " \t")
|
||||
next_line_num++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
lnum = next_line_num
|
||||
if scanner.Scan() {
|
||||
next_line = strings.TrimLeft(scanner.Text(), " \t")
|
||||
next_line_num++
|
||||
|
||||
for strings.HasPrefix(next_line, `\`) {
|
||||
line += next_line[1:]
|
||||
if scanner.Scan() {
|
||||
next_line = strings.TrimLeft(scanner.Text(), " \t")
|
||||
next_line_num++
|
||||
} else {
|
||||
next_line = ""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
next_line = ""
|
||||
}
|
||||
|
||||
if line[0] == '#' {
|
||||
if self.CommentsHandler != nil {
|
||||
if err := self.CommentsHandler(line); err != nil {
|
||||
add_bad_line(err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
m := key_pat().FindStringSubmatch(line)
|
||||
if len(m) < 3 {
|
||||
add_bad_line(fmt.Errorf("Invalid config line: %#v", line))
|
||||
continue
|
||||
}
|
||||
key, val := m[1], m[2]
|
||||
for i, ch := range line {
|
||||
if ch == ' ' || ch == '\t' {
|
||||
key = line[:i]
|
||||
val = strings.TrimSpace(line[i+1:])
|
||||
break
|
||||
}
|
||||
}
|
||||
switch key {
|
||||
default:
|
||||
if err := self.LineHandler(key, val); err != nil {
|
||||
add_bad_line(err)
|
||||
}
|
||||
case "include", "globinclude", "envinclude", "geninclude":
|
||||
var includes []string
|
||||
val = ExpandVars(val)
|
||||
switch key {
|
||||
case "include":
|
||||
if aval, err := make_absolute(val); err == nil {
|
||||
includes = []string{aval}
|
||||
} else {
|
||||
add_bad_line(err)
|
||||
}
|
||||
case "globinclude":
|
||||
aval, err := make_absolute(val)
|
||||
if err == nil {
|
||||
matches, err := filepath.Glob(aval)
|
||||
if err == nil {
|
||||
includes = matches
|
||||
} else {
|
||||
add_bad_line(err)
|
||||
}
|
||||
} else {
|
||||
add_bad_line(err)
|
||||
}
|
||||
case "geninclude":
|
||||
if aval, err := make_absolute(val); err == nil {
|
||||
if g, err := geninclude(aval); err == nil {
|
||||
if err := recurse(strings.NewReader(g), "<gen: "+val+">", base_path_for_includes); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
add_bad_line(err)
|
||||
}
|
||||
} else {
|
||||
add_bad_line(err)
|
||||
}
|
||||
case "envinclude":
|
||||
env := utils.IfElse(self.override_env == nil, os.Environ(), self.override_env)
|
||||
for _, x := range env {
|
||||
key, eval, _ := strings.Cut(x, "=")
|
||||
is_match, err := filepath.Match(val, key)
|
||||
if is_match && err == nil {
|
||||
err := recurse(strings.NewReader(eval), "<env var: "+key+">", base_path_for_includes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(includes) > 0 {
|
||||
for _, incpath := range includes {
|
||||
if raw, err := os.ReadFile(incpath); err == nil {
|
||||
if err := recurse(bytes.NewReader(raw), incpath, filepath.Dir(incpath)); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
add_bad_line(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ConfigParser) ParseFiles(paths ...string) error {
|
||||
for _, path := range paths {
|
||||
apath, err := filepath.Abs(path)
|
||||
if err == nil {
|
||||
path = apath
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scanner := utils.NewLineScanner(utils.UnsafeBytesToString(raw))
|
||||
self.seen_includes = make(map[string]bool)
|
||||
err = self.parse(scanner, path, filepath.Dir(path), 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if self.SourceHandler != nil {
|
||||
self.SourceHandler(utils.UnsafeBytesToString(raw), path)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ConfigParser) LoadConfig(name string, paths []string, overrides []string) (err error) {
|
||||
const SYSTEM_CONF = "/etc/xdg/kitty"
|
||||
system_conf := filepath.Join(SYSTEM_CONF, name)
|
||||
add_if_exists := func(q string) {
|
||||
err = self.ParseFiles(q)
|
||||
if err != nil && errors.Is(err, fs.ErrNotExist) {
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
if add_if_exists(system_conf); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(paths) > 0 {
|
||||
for _, path := range paths {
|
||||
if add_if_exists(path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if add_if_exists(filepath.Join(utils.ConfigDirForName(name), name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(overrides) > 0 {
|
||||
err = self.ParseOverrides(overrides...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type LinesScanner struct {
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (self *LinesScanner) Scan() bool {
|
||||
return len(self.lines) > 0
|
||||
}
|
||||
|
||||
func (self *LinesScanner) Text() string {
|
||||
ans := self.lines[0]
|
||||
self.lines = self.lines[1:]
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *LinesScanner) Err() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ConfigParser) ParseOverrides(overrides ...string) error {
|
||||
s := LinesScanner{lines: utils.Map(func(x string) string {
|
||||
return strings.Replace(x, "=", " ", 1)
|
||||
}, overrides)}
|
||||
self.seen_includes = make(map[string]bool)
|
||||
return self.parse(&s, "<overrides>", utils.ConfigDir(), 0)
|
||||
}
|
||||
|
||||
func is_kitty_gui_cmdline(exe string, cmd ...string) bool {
|
||||
if len(cmd) == 0 {
|
||||
return false
|
||||
}
|
||||
if filepath.Base(exe) != "kitty" {
|
||||
return false
|
||||
}
|
||||
if len(cmd) == 1 {
|
||||
return true
|
||||
}
|
||||
s := cmd[1][:1]
|
||||
switch s {
|
||||
case `@`:
|
||||
return false
|
||||
case `+`:
|
||||
if cmd[1] == `+` {
|
||||
return len(cmd) > 2 && cmd[2] == `open`
|
||||
}
|
||||
return cmd[1] == `+open`
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type Patcher struct {
|
||||
Write_backup bool
|
||||
Mode fs.FileMode
|
||||
}
|
||||
|
||||
func (self Patcher) Patch(path, sentinel, content string, settings_to_comment_out ...string) (updated bool, err error) {
|
||||
if self.Mode == 0 {
|
||||
self.Mode = 0o644
|
||||
}
|
||||
backup_path := path
|
||||
if q, err := filepath.EvalSymlinks(path); err == nil {
|
||||
path = q
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return false, err
|
||||
}
|
||||
add_at_top := ""
|
||||
backup := true
|
||||
if raw == nil {
|
||||
cc := kitty.CommentedOutDefaultConfig
|
||||
if idx := strings.Index(cc, "\n\n"); idx > 0 {
|
||||
add_at_top = cc[:idx+2]
|
||||
raw = []byte(cc[idx+2:])
|
||||
backup = false
|
||||
}
|
||||
}
|
||||
pat := utils.MustCompile(fmt.Sprintf(`(?m)^\s*(%s)\b`, strings.Join(settings_to_comment_out, "|")))
|
||||
text := pat.ReplaceAllString(utils.UnsafeBytesToString(raw), `# $1`)
|
||||
|
||||
pat = utils.MustCompile(fmt.Sprintf(`(?ms)^# BEGIN_%s.+?# END_%s`, sentinel, sentinel))
|
||||
replaced := false
|
||||
addition := fmt.Sprintf("# BEGIN_%s\n%s\n# END_%s", sentinel, content, sentinel)
|
||||
ntext := pat.ReplaceAllStringFunc(text, func(string) string {
|
||||
replaced = true
|
||||
return addition
|
||||
})
|
||||
if !replaced {
|
||||
if add_at_top != "" {
|
||||
ntext = add_at_top + addition
|
||||
if text != "" {
|
||||
ntext += "\n\n" + text
|
||||
}
|
||||
} else {
|
||||
if text != "" {
|
||||
text += "\n\n"
|
||||
}
|
||||
ntext = text + addition
|
||||
}
|
||||
}
|
||||
nraw := utils.UnsafeStringToBytes(ntext)
|
||||
if !bytes.Equal(raw, nraw) {
|
||||
if len(raw) > 0 && self.Write_backup && backup {
|
||||
_ = os.WriteFile(backup_path+".bak", raw, self.Mode)
|
||||
}
|
||||
|
||||
return true, utils.AtomicUpdateFile(path, bytes.NewReader(nraw), self.Mode)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func ReloadConfigInKitty(in_parent_only bool) error {
|
||||
if in_parent_only {
|
||||
if pid, err := strconv.ParseInt(os.Getenv("KITTY_PID"), 10, 32); err == nil {
|
||||
if p, err := process.NewProcess(int32(pid)); err == nil {
|
||||
if exe, eerr := p.Exe(); eerr == nil {
|
||||
if c, err := p.CmdlineSlice(); err == nil && is_kitty_gui_cmdline(exe, c...) {
|
||||
return p.SendSignal(unix.SIGUSR1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// process.Processes() followed by filtering by getting the process
|
||||
// exe and cmdline is very slow on non-Linux systems as CGO is not allowed
|
||||
// which means getting exe works by calling lsof on every process. So instead do
|
||||
// initial filtering based on ps output.
|
||||
if ps_out, err := exec.Command("ps", "-x", "-o", "pid=,comm=").Output(); err == nil {
|
||||
for _, line := range utils.Splitlines(utils.UnsafeBytesToString(ps_out)) {
|
||||
line = strings.TrimSpace(line)
|
||||
if pid_string, argv0, found := strings.Cut(line, " "); found {
|
||||
if pid, err := strconv.ParseInt(strings.TrimSpace(pid_string), 10, 32); err == nil && strings.Contains(argv0, "kitty") {
|
||||
if p, err := process.NewProcess(int32(pid)); err == nil {
|
||||
if cmdline, err := p.CmdlineSlice(); err == nil {
|
||||
if exe, err := p.Exe(); err == nil && is_kitty_gui_cmdline(exe, cmdline...) {
|
||||
_ = p.SendSignal(unix.SIGUSR1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var OverrideEffectiveConfigPath string
|
||||
|
||||
func ReadKittyConfig(line_handler func(key, val string) error, override_effective_config_path ...string) error {
|
||||
kp := os.Getenv("KITTY_PID")
|
||||
kitty_conf_path := ""
|
||||
if len(override_effective_config_path) > 0 {
|
||||
kitty_conf_path = override_effective_config_path[0]
|
||||
}
|
||||
if _, err := strconv.Atoi(kp); err == nil && kitty_conf_path == "" {
|
||||
effective_config_path := filepath.Join(utils.CacheDir(), "effective-config", kp)
|
||||
if unix.Access(effective_config_path, unix.R_OK) == nil {
|
||||
kitty_conf_path = effective_config_path
|
||||
}
|
||||
}
|
||||
if kitty_conf_path == "" {
|
||||
kitty_conf_path = filepath.Join(utils.ConfigDir(), "kitty.conf")
|
||||
}
|
||||
cp := ConfigParser{LineHandler: line_handler}
|
||||
return cp.ParseFiles(kitty_conf_path)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestConfigParsing(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
conf_file := filepath.Join(tdir, "a.conf")
|
||||
if err := os.Mkdir(filepath.Join(tdir, "sub"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := func(path string, data []byte) {
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
w(filepath.Join(tdir, "g.py"), []byte(`
|
||||
print('gpy 1')
|
||||
print('gpy 2')
|
||||
`))
|
||||
w(conf_file, []byte(
|
||||
`error main
|
||||
# igno
|
||||
\re me
|
||||
a one
|
||||
#: other
|
||||
include
|
||||
\ sub/b.conf
|
||||
b x
|
||||
include non-exis
|
||||
\tent
|
||||
globin
|
||||
\clude sub/c?.c
|
||||
\onf
|
||||
badline
|
||||
geninclude g.py
|
||||
`))
|
||||
w(filepath.Join(tdir, "sub/b.conf"), []byte("incb cool\ninclude a.conf"))
|
||||
w(filepath.Join(tdir, "sub/c1.conf"), []byte("inc1 cool"))
|
||||
w(filepath.Join(tdir, "sub/c2.conf"), []byte("inc2 cool\nenvinclude ENVINCLUDE"))
|
||||
w(filepath.Join(tdir, "sub/c.conf"), []byte("inc notcool\nerror sub"))
|
||||
|
||||
var parsed_lines []string
|
||||
pl := func(key, val string) error {
|
||||
if key == "error" {
|
||||
return fmt.Errorf("%s", val)
|
||||
}
|
||||
parsed_lines = append(parsed_lines, key+" "+val)
|
||||
return nil
|
||||
}
|
||||
|
||||
p := ConfigParser{LineHandler: pl, override_env: []string{"ENVINCLUDE=env cool\ninclude c.conf"}}
|
||||
err := p.ParseFiles(conf_file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = p.ParseOverrides("over one", "over two"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diff := cmp.Diff([]string{"a one", "incb cool", "b x", "inc1 cool", "inc2 cool", "env cool", "inc notcool", "gpy 1", "gpy 2", "over one", "over two"}, parsed_lines)
|
||||
if diff != "" {
|
||||
t.Fatalf("Unexpected parsed config values:\n%s", diff)
|
||||
}
|
||||
bad_lines := []string{}
|
||||
for _, bl := range p.BadLines() {
|
||||
bad_lines = append(bad_lines, fmt.Sprintf("%s: %d", filepath.Base(bl.Src_file), bl.Line_number))
|
||||
}
|
||||
diff = cmp.Diff([]string{"a.conf: 1", "c.conf: 2", "a.conf: 14"}, bad_lines)
|
||||
if diff != "" {
|
||||
t.Fatalf("Unexpected bad lines:\n%s", diff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func ParseStrDict(val, record_sep, field_sep string) (map[string]string, error) {
|
||||
ans := make(map[string]string)
|
||||
for record := range strings.SplitSeq(val, record_sep) {
|
||||
key, val, found := strings.Cut(record, field_sep)
|
||||
if found {
|
||||
ans[key] = val
|
||||
}
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func PositiveFloat(val string) (ans float64, err error) {
|
||||
ans, err = strconv.ParseFloat(val, 64)
|
||||
if err == nil {
|
||||
ans = max(0, ans)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func UnitFloat(val string) (ans float64, err error) {
|
||||
ans, err = strconv.ParseFloat(val, 64)
|
||||
if err == nil {
|
||||
ans = max(0, min(ans, 1))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func StringLiteral(val string) (string, error) {
|
||||
ans := strings.Builder{}
|
||||
ans.Grow(len(val))
|
||||
var buf [8]rune
|
||||
bufcount := 0
|
||||
buflimit := 0
|
||||
var prefix rune
|
||||
type State int
|
||||
const (
|
||||
normal State = iota
|
||||
backslash
|
||||
octal
|
||||
hex
|
||||
)
|
||||
var state State
|
||||
decode := func(base int) {
|
||||
text := string(buf[:bufcount])
|
||||
if num, err := strconv.ParseUint(text, base, 32); err == nil && num <= utf8.MaxRune {
|
||||
ans.WriteRune(rune(num))
|
||||
}
|
||||
state = normal
|
||||
bufcount = 0
|
||||
buflimit = 0
|
||||
prefix = 0
|
||||
}
|
||||
|
||||
write_invalid_buf := func() {
|
||||
ans.WriteByte('\\')
|
||||
ans.WriteRune(prefix)
|
||||
for _, r := range buf[:bufcount] {
|
||||
ans.WriteRune(r)
|
||||
}
|
||||
state = normal
|
||||
bufcount = 0
|
||||
buflimit = 0
|
||||
prefix = 0
|
||||
}
|
||||
|
||||
var dispatch_ch_recurse func(rune)
|
||||
|
||||
dispatch_ch := func(ch rune) {
|
||||
switch state {
|
||||
case normal:
|
||||
switch ch {
|
||||
case '\\':
|
||||
state = backslash
|
||||
default:
|
||||
ans.WriteRune(ch)
|
||||
}
|
||||
case octal:
|
||||
switch ch {
|
||||
case '0', '1', '2', '3', '4', '5', '6', '7':
|
||||
if bufcount >= buflimit {
|
||||
decode(8)
|
||||
dispatch_ch_recurse(ch)
|
||||
} else {
|
||||
buf[bufcount] = ch
|
||||
bufcount++
|
||||
}
|
||||
default:
|
||||
decode(8)
|
||||
dispatch_ch_recurse(ch)
|
||||
}
|
||||
case hex:
|
||||
switch ch {
|
||||
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F':
|
||||
buf[bufcount] = ch
|
||||
bufcount++
|
||||
if bufcount >= buflimit {
|
||||
decode(16)
|
||||
}
|
||||
default:
|
||||
write_invalid_buf()
|
||||
dispatch_ch_recurse(ch)
|
||||
}
|
||||
case backslash:
|
||||
switch ch {
|
||||
case '\n':
|
||||
state = normal
|
||||
case '\\':
|
||||
ans.WriteRune('\\')
|
||||
state = normal
|
||||
case '\'', '"':
|
||||
ans.WriteRune(ch)
|
||||
state = normal
|
||||
case 'a':
|
||||
ans.WriteRune('\a')
|
||||
state = normal
|
||||
case 'b':
|
||||
ans.WriteRune('\b')
|
||||
state = normal
|
||||
case 'f':
|
||||
ans.WriteRune('\f')
|
||||
state = normal
|
||||
case 'n':
|
||||
ans.WriteRune('\n')
|
||||
state = normal
|
||||
case 'r':
|
||||
ans.WriteRune('\r')
|
||||
state = normal
|
||||
case 't':
|
||||
ans.WriteRune('\t')
|
||||
state = normal
|
||||
case 'v':
|
||||
ans.WriteRune('\v')
|
||||
state = normal
|
||||
case '0', '1', '2', '3', '4', '5', '6', '7':
|
||||
buf[0] = ch
|
||||
bufcount = 1
|
||||
buflimit = 3
|
||||
state = octal
|
||||
case 'x':
|
||||
bufcount = 0
|
||||
buflimit = 2
|
||||
state = hex
|
||||
prefix = ch
|
||||
case 'u':
|
||||
bufcount = 0
|
||||
buflimit = 4
|
||||
state = hex
|
||||
prefix = ch
|
||||
case 'U':
|
||||
bufcount = 0
|
||||
buflimit = 8
|
||||
state = hex
|
||||
prefix = ch
|
||||
default:
|
||||
ans.WriteByte('\\')
|
||||
ans.WriteRune(ch)
|
||||
state = normal
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatch_ch_recurse = dispatch_ch
|
||||
for _, ch := range val {
|
||||
dispatch_ch(ch)
|
||||
}
|
||||
switch state {
|
||||
case octal:
|
||||
decode(8)
|
||||
case hex:
|
||||
write_invalid_buf()
|
||||
case backslash:
|
||||
ans.WriteRune('\\')
|
||||
}
|
||||
return ans.String(), nil
|
||||
}
|
||||
|
||||
var ModMap = sync.OnceValue(func() map[string]string {
|
||||
return map[string]string{
|
||||
"shift": "shift",
|
||||
"⇧": "shift",
|
||||
"alt": "alt",
|
||||
"option": "alt",
|
||||
"opt": "alt",
|
||||
"⌥": "alt",
|
||||
"super": "super",
|
||||
"command": "super",
|
||||
"cmd": "super",
|
||||
"⌘": "super",
|
||||
"control": "ctrl",
|
||||
"ctrl": "ctrl",
|
||||
"⌃": "ctrl",
|
||||
"hyper": "hyper",
|
||||
"meta": "meta",
|
||||
"num_lock": "num_lock",
|
||||
"caps_lock": "caps_lock",
|
||||
}
|
||||
})
|
||||
|
||||
var ShortcutSpecPat = sync.OnceValue(func() *regexp.Regexp {
|
||||
return regexp.MustCompile(`([^+])>`)
|
||||
})
|
||||
|
||||
func NormalizeShortcut(spec string) string {
|
||||
parts := strings.Split(strings.ToLower(spec), "+")
|
||||
key := parts[len(parts)-1]
|
||||
if len(parts) == 1 {
|
||||
return key
|
||||
}
|
||||
mods := parts[:len(parts)-1]
|
||||
mmap := ModMap()
|
||||
mods = utils.Map(func(x string) string {
|
||||
ans := mmap[x]
|
||||
if ans == "" {
|
||||
ans = x
|
||||
}
|
||||
return ans
|
||||
}, mods)
|
||||
slices.Sort(mods)
|
||||
return strings.Join(mods, "+") + "+" + key
|
||||
}
|
||||
|
||||
func NormalizeShortcuts(spec string) []string {
|
||||
if strings.HasSuffix(spec, "+") {
|
||||
spec = spec[:len(spec)-1] + "plus"
|
||||
}
|
||||
spec = strings.ReplaceAll(spec, "++", "+plus")
|
||||
spec = ShortcutSpecPat().ReplaceAllString(spec, "$1\x00")
|
||||
return utils.Map(NormalizeShortcut, strings.Split(spec, "\x00"))
|
||||
}
|
||||
|
||||
type KeyAction struct {
|
||||
Normalized_keys []string
|
||||
Name string
|
||||
Args string
|
||||
AllowFallback string
|
||||
}
|
||||
|
||||
func (self *KeyAction) String() string {
|
||||
return fmt.Sprintf("map %#v %#v %#v\n", strings.Join(self.Normalized_keys, ">"), self.Name, self.Args)
|
||||
}
|
||||
|
||||
func validateAllowFallback(value string) error {
|
||||
if value == "" || value == "none" {
|
||||
return nil
|
||||
}
|
||||
for part := range strings.SplitSeq(value, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part != "shifted" && part != "ascii" {
|
||||
return fmt.Errorf("Invalid allow-fallback value %#v, allowed values: shifted, ascii, none", part)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ParseMap(val string) (*KeyAction, error) {
|
||||
allow_fallback := "shifted"
|
||||
for strings.HasPrefix(val, "--") {
|
||||
flag, rest, found := strings.Cut(val, " ")
|
||||
if !found {
|
||||
return nil, fmt.Errorf("No key specified after flag %s", flag)
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if name, value, ok := strings.Cut(flag, "="); ok {
|
||||
// --flag=value form
|
||||
name = strings.ReplaceAll(name[2:], "-", "_")
|
||||
switch name {
|
||||
case "allow_fallback":
|
||||
if err := validateAllowFallback(value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == "none" {
|
||||
allow_fallback = ""
|
||||
} else {
|
||||
allow_fallback = value
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown map option: %s", flag)
|
||||
}
|
||||
} else {
|
||||
// --flag value form (space-separated)
|
||||
name := strings.ReplaceAll(flag[2:], "-", "_")
|
||||
switch name {
|
||||
case "allow_fallback":
|
||||
value, after, has_more := strings.Cut(rest, " ")
|
||||
if !has_more {
|
||||
return nil, fmt.Errorf("No key specified after %s %s", flag, value)
|
||||
}
|
||||
if err := validateAllowFallback(value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == "none" {
|
||||
allow_fallback = ""
|
||||
} else {
|
||||
allow_fallback = value
|
||||
}
|
||||
rest = strings.TrimSpace(after)
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown map option: %s", flag)
|
||||
}
|
||||
}
|
||||
val = rest
|
||||
}
|
||||
spec, action, found := strings.Cut(val, " ")
|
||||
if !found {
|
||||
return nil, fmt.Errorf("No action specified for shortcut %s", val)
|
||||
}
|
||||
action = strings.TrimSpace(action)
|
||||
action_name, action_args, _ := strings.Cut(action, " ")
|
||||
action_args = strings.TrimSpace(action_args)
|
||||
return &KeyAction{Name: action_name, Args: action_args, Normalized_keys: NormalizeShortcuts(spec), AllowFallback: allow_fallback}, nil
|
||||
}
|
||||
|
||||
type partialMatch struct {
|
||||
action *KeyAction
|
||||
priority int
|
||||
}
|
||||
|
||||
type ShortcutTracker struct {
|
||||
partial_matches []partialMatch
|
||||
partial_num_consumed int
|
||||
}
|
||||
|
||||
func (self *ShortcutTracker) Match(ev *loop.KeyEvent, all_actions []*KeyAction) *KeyAction {
|
||||
if self.partial_num_consumed > 0 {
|
||||
ev.Handled = true
|
||||
new_matches := self.partial_matches[:0]
|
||||
for _, pm := range self.partial_matches {
|
||||
if self.partial_num_consumed >= len(pm.action.Normalized_keys) {
|
||||
continue
|
||||
}
|
||||
p := ev.MatchesPressOrRepeatPriorityWithFallback(pm.action.Normalized_keys[self.partial_num_consumed], pm.action.AllowFallback)
|
||||
if p >= 0 {
|
||||
if p > pm.priority {
|
||||
pm.priority = p
|
||||
}
|
||||
new_matches = append(new_matches, pm)
|
||||
}
|
||||
}
|
||||
self.partial_matches = new_matches
|
||||
if len(self.partial_matches) == 0 {
|
||||
self.partial_num_consumed = 0
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
new_matches := self.partial_matches[:0]
|
||||
for _, ac := range all_actions {
|
||||
p := ev.MatchesPressOrRepeatPriorityWithFallback(ac.Normalized_keys[0], ac.AllowFallback)
|
||||
if p >= 0 {
|
||||
new_matches = append(new_matches, partialMatch{action: ac, priority: p})
|
||||
}
|
||||
}
|
||||
self.partial_matches = new_matches
|
||||
if len(self.partial_matches) == 0 {
|
||||
return nil
|
||||
}
|
||||
ev.Handled = true
|
||||
}
|
||||
self.partial_num_consumed++
|
||||
var best *partialMatch
|
||||
for i := range self.partial_matches {
|
||||
pm := &self.partial_matches[i]
|
||||
if self.partial_num_consumed >= len(pm.action.Normalized_keys) {
|
||||
if best == nil || pm.priority < best.priority {
|
||||
best = pm
|
||||
}
|
||||
}
|
||||
}
|
||||
if best != nil {
|
||||
self.partial_num_consumed = 0
|
||||
self.partial_matches = nil
|
||||
return best.action
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ResolveShortcuts(actions []*KeyAction) []*KeyAction {
|
||||
action_map := make(map[string]*KeyAction, len(actions))
|
||||
for _, ac := range actions {
|
||||
key := strings.Join(ac.Normalized_keys, "\x00")
|
||||
if ac.Name == "no_op" || ac.Name == "no-op" {
|
||||
delete(action_map, key)
|
||||
} else {
|
||||
action_map[key] = ac
|
||||
}
|
||||
}
|
||||
return utils.Values(action_map)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestStringLiteralParsing(t *testing.T) {
|
||||
for q, expected := range map[string]string{
|
||||
`abc`: `abc`,
|
||||
`a\nb\M`: "a\nb\\M",
|
||||
`a\x20\x1\u1234\123\12|`: "a \\x1\u1234\123\x0a|",
|
||||
"a\\\nnb": "anb",
|
||||
"a\\\n\\tb": "a\tb",
|
||||
} {
|
||||
actual, err := StringLiteral(q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expected != actual {
|
||||
t.Fatalf("Failed with input: %#v\n%#v != %#v", q, expected, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMap(t *testing.T) {
|
||||
// Test without --allow-fallback (default "shifted")
|
||||
ka, err := ParseMap("ctrl+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "shifted" {
|
||||
t.Fatalf("Expected AllowFallback 'shifted', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
if diff := cmp.Diff([]string{"ctrl+c"}, ka.Normalized_keys); diff != "" {
|
||||
t.Fatalf("Keys mismatch:\n%s", diff)
|
||||
}
|
||||
|
||||
// Test with --allow-fallback=ascii
|
||||
ka, err = ParseMap("--allow-fallback=ascii ctrl+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "ascii" {
|
||||
t.Fatalf("Expected AllowFallback 'ascii', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
|
||||
// Test with --allow-fallback=shifted,ascii
|
||||
ka, err = ParseMap("--allow-fallback=shifted,ascii cmd+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "shifted,ascii" {
|
||||
t.Fatalf("Expected AllowFallback 'shifted,ascii', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
if diff := cmp.Diff([]string{"super+c"}, ka.Normalized_keys); diff != "" {
|
||||
t.Fatalf("Keys mismatch:\n%s", diff)
|
||||
}
|
||||
|
||||
// Test with --allow-fallback and action args
|
||||
ka, err = ParseMap("--allow-fallback=shifted,ascii ctrl+shift+f launch --type=tab grep")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "shifted,ascii" {
|
||||
t.Fatalf("Expected AllowFallback 'shifted,ascii', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "launch" {
|
||||
t.Fatalf("Expected Name 'launch', got %#v", ka.Name)
|
||||
}
|
||||
if ka.Args != "--type=tab grep" {
|
||||
t.Fatalf("Expected Args '--type=tab grep', got %#v", ka.Args)
|
||||
}
|
||||
|
||||
// Test space form: --allow-fallback ascii (without =)
|
||||
ka, err = ParseMap("--allow-fallback ascii ctrl+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "ascii" {
|
||||
t.Fatalf("Expected AllowFallback 'ascii', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
if diff := cmp.Diff([]string{"ctrl+c"}, ka.Normalized_keys); diff != "" {
|
||||
t.Fatalf("Keys mismatch:\n%s", diff)
|
||||
}
|
||||
|
||||
// Test space form: --allow-fallback shifted,ascii
|
||||
ka, err = ParseMap("--allow-fallback shifted,ascii cmd+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "shifted,ascii" {
|
||||
t.Fatalf("Expected AllowFallback 'shifted,ascii', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
|
||||
// Test --allow-fallback=none (equals form)
|
||||
ka, err = ParseMap("--allow-fallback=none ctrl+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "" {
|
||||
t.Fatalf("Expected AllowFallback '', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
|
||||
// Test --allow-fallback none (space form)
|
||||
ka, err = ParseMap("--allow-fallback none ctrl+c copy_to_clipboard")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ka.AllowFallback != "" {
|
||||
t.Fatalf("Expected AllowFallback '', got %#v", ka.AllowFallback)
|
||||
}
|
||||
if ka.Name != "copy_to_clipboard" {
|
||||
t.Fatalf("Expected Name 'copy_to_clipboard', got %#v", ka.Name)
|
||||
}
|
||||
|
||||
// Test error: unknown flag
|
||||
_, err = ParseMap("--allow-fallbak=ascii ctrl+c copy")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for unknown flag --allow-fallbak")
|
||||
}
|
||||
|
||||
// Test error: unknown flag without =
|
||||
_, err = ParseMap("--unknown ctrl+c copy")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for unknown flag --unknown")
|
||||
}
|
||||
|
||||
// Test error: invalid allow-fallback value
|
||||
_, err = ParseMap("--allow-fallback=typo ctrl+c copy")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for invalid allow-fallback value 'typo'")
|
||||
}
|
||||
|
||||
// Test error: invalid allow-fallback value in space form
|
||||
_, err = ParseMap("--allow-fallback typo ctrl+c copy")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for invalid allow-fallback value 'typo' in space form")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeShortcuts(t *testing.T) {
|
||||
for q, expected_ := range map[string]string{
|
||||
`a`: `a`,
|
||||
`+`: `plus`,
|
||||
`cmd+b>opt+>`: `super+b alt+>`,
|
||||
`cmd+>>opt+>`: `super+> alt+>`,
|
||||
} {
|
||||
expected := strings.Split(expected_, " ")
|
||||
actual := NormalizeShortcuts(q)
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("failed with input: %#v\n%s", q, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortcutTrackerMatchPriority(t *testing.T) {
|
||||
// Helper to create a KeyAction with a given spec and AllowFallback.
|
||||
makeAction := func(name, spec, allowFallback string) *KeyAction {
|
||||
return &KeyAction{Name: name, Normalized_keys: NormalizeShortcuts(spec), AllowFallback: allowFallback}
|
||||
}
|
||||
// Helper to simulate a key press event.
|
||||
makeEv := func(key, shiftedKey, alternateKey string, mods loop.KeyModifiers) *loop.KeyEvent {
|
||||
return &loop.KeyEvent{Type: loop.PRESS, Key: key, ShiftedKey: shiftedKey, AlternateKey: alternateKey, Mods: mods}
|
||||
}
|
||||
|
||||
// Scenario 1: shifted key event — "shifted,ascii" shortcut wins over "ascii,shifted"
|
||||
actions := []*KeyAction{
|
||||
makeAction("ascii_shifted", "a", "ascii,shifted"),
|
||||
makeAction("shifted_ascii", "a", "shifted,ascii"),
|
||||
}
|
||||
// Shift+A with ShiftedKey="a": matches via shifted fallback for both
|
||||
tracker := ShortcutTracker{}
|
||||
ev := makeEv("A", "a", "", loop.SHIFT)
|
||||
result := tracker.Match(ev, actions)
|
||||
if result == nil || result.Name != "shifted_ascii" {
|
||||
name := "<nil>"
|
||||
if result != nil {
|
||||
name = result.Name
|
||||
}
|
||||
t.Fatalf("shifted key: expected 'shifted_ascii' (shifted first), got %q", name)
|
||||
}
|
||||
|
||||
// Scenario 2: alternate (non-ASCII) key event — "ascii,shifted" shortcut wins over "shifted,ascii"
|
||||
actions2 := []*KeyAction{
|
||||
makeAction("shifted_ascii", "ctrl+c", "shifted,ascii"),
|
||||
makeAction("ascii_shifted", "ctrl+c", "ascii,shifted"),
|
||||
}
|
||||
// Cyrillic "с" with AlternateKey="c": matches via ascii fallback for both
|
||||
tracker2 := ShortcutTracker{}
|
||||
ev2 := makeEv("с", "", "c", loop.CTRL)
|
||||
result2 := tracker2.Match(ev2, actions2)
|
||||
if result2 == nil || result2.Name != "ascii_shifted" {
|
||||
name := "<nil>"
|
||||
if result2 != nil {
|
||||
name = result2.Name
|
||||
}
|
||||
t.Fatalf("ascii key: expected 'ascii_shifted' (ascii first), got %q", name)
|
||||
}
|
||||
|
||||
// Scenario 3: direct match wins over any fallback match
|
||||
// Event: Cyrillic "с" with ctrl + AlternateKey="c"; two shortcuts: one direct match for Cyrillic key,
|
||||
// one matching via ascii fallback.
|
||||
actions3 := []*KeyAction{
|
||||
makeAction("fallback", "ctrl+c", "ascii"),
|
||||
makeAction("direct", "ctrl+с", ""),
|
||||
}
|
||||
tracker3 := ShortcutTracker{}
|
||||
ev3 := makeEv("с", "", "c", loop.CTRL)
|
||||
result3 := tracker3.Match(ev3, actions3)
|
||||
if result3 == nil || result3.Name != "direct" {
|
||||
name := "<nil>"
|
||||
if result3 != nil {
|
||||
name = result3.Name
|
||||
}
|
||||
t.Fatalf("direct match: expected 'direct', got %q", name)
|
||||
}
|
||||
|
||||
// Scenario 4: single-type AllowFallback has same priority as first position in two-type AllowFallback
|
||||
// "shifted" only vs "shifted,ascii" — when matching via shifted key, both have priority 1, so first in list wins
|
||||
actions4 := []*KeyAction{
|
||||
makeAction("shifted_only", "a", "shifted"),
|
||||
makeAction("shifted_ascii", "a", "shifted,ascii"),
|
||||
}
|
||||
tracker4 := ShortcutTracker{}
|
||||
ev4 := makeEv("A", "a", "", loop.SHIFT)
|
||||
result4 := tracker4.Match(ev4, actions4)
|
||||
// Both have priority 1 (shifted at position 0); first encountered wins
|
||||
if result4 == nil || result4.Name != "shifted_only" {
|
||||
name := "<nil>"
|
||||
if result4 != nil {
|
||||
name = result4.Name
|
||||
}
|
||||
t.Fatalf("single vs two-type (shifted): expected 'shifted_only', got %q", name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/base85"
|
||||
)
|
||||
|
||||
func curve25519_key_pair() (private_key []byte, public_key []byte, err error) {
|
||||
curve := ecdh.X25519()
|
||||
privkey, err := curve.GenerateKey(rand.Reader)
|
||||
if err == nil {
|
||||
pubkey := privkey.PublicKey()
|
||||
return privkey.Bytes(), pubkey.Bytes(), nil
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
func curve25519_derive_shared_secret(private_key []byte, public_key []byte) (secret []byte, err error) {
|
||||
prkey, err := ecdh.X25519().NewPrivateKey(private_key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Invalid X25519 private key: %w", err)
|
||||
}
|
||||
pubkey, err := ecdh.X25519().NewPublicKey(public_key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Invalid X25519 public key: %w", err)
|
||||
}
|
||||
secret, err = prkey.ECDH(pubkey)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to perform ECDH shared secret derivation: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func b85_encode(data []byte) (encoded string) {
|
||||
encoded = base85.EncodeToString(data)
|
||||
return
|
||||
}
|
||||
|
||||
func b85_decode(data string) (decoded []byte, err error) {
|
||||
decoded, err = base85.DecodeString(data)
|
||||
return
|
||||
}
|
||||
|
||||
func encrypt(plaintext []byte, alice_public_key []byte, encryption_protocol string) (iv []byte, tag []byte, ciphertext []byte, bob_public_key []byte, err error) {
|
||||
bob_private_key, bob_public_key, err := KeyPair(encryption_protocol)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
shared_secret_raw, err := curve25519_derive_shared_secret(bob_private_key, alice_public_key)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
shared_secret_hashed := sha256.Sum256(shared_secret_raw)
|
||||
shared_secret := shared_secret_hashed[:]
|
||||
block, err := aes.NewCipher(shared_secret)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
aesgcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
iv = make([]byte, aesgcm.NonceSize())
|
||||
_, err = rand.Read(iv)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
output := aesgcm.Seal(nil, iv, plaintext, nil)
|
||||
ciphertext = output[0 : len(output)-16]
|
||||
tag = output[len(output)-16:]
|
||||
return
|
||||
}
|
||||
|
||||
func KeyPair(encryption_protocol string) (private_key []byte, public_key []byte, err error) {
|
||||
switch encryption_protocol {
|
||||
case "1":
|
||||
return curve25519_key_pair()
|
||||
default:
|
||||
err = fmt.Errorf("Unknown encryption protocol: %s", encryption_protocol)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func EncodePublicKey(pubkey []byte, encryption_protocol string) (ans string, err error) {
|
||||
switch encryption_protocol {
|
||||
case "1":
|
||||
ans = fmt.Sprintf("1:%s", b85_encode(pubkey))
|
||||
default:
|
||||
err = fmt.Errorf("Unknown encryption protocol: %s", encryption_protocol)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func DecodePublicKey(raw string) (encryption_protocol string, pubkey []byte, err error) {
|
||||
encryption_protocol, encoded_pubkey, found := strings.Cut(raw, ":")
|
||||
if !found {
|
||||
return "", nil, fmt.Errorf("Invalid encoded pubkey, no : in string")
|
||||
}
|
||||
pubkey, err = b85_decode(encoded_pubkey)
|
||||
return
|
||||
}
|
||||
|
||||
func Encrypt_cmd(cmd *utils.RemoteControlCmd, password string, other_pubkey []byte, encryption_protocol string) (encrypted_cmd utils.EncryptedRemoteControlCmd, err error) {
|
||||
cmd.Password = password
|
||||
cmd.Timestamp = time.Now().UnixNano()
|
||||
plaintext, err := json.Marshal(cmd)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
iv, tag, ciphertext, pubkey, err := encrypt(plaintext, other_pubkey, encryption_protocol)
|
||||
encrypted_cmd = utils.EncryptedRemoteControlCmd{
|
||||
Version: cmd.Version, IV: b85_encode(iv), Tag: b85_encode(tag), Pubkey: b85_encode(pubkey), Encrypted: b85_encode(ciphertext)}
|
||||
if encryption_protocol != "1" {
|
||||
encrypted_cmd.EncProto = encryption_protocol
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func Encrypt_data(data []byte, other_pubkey []byte, encryption_protocol string) (ans []byte, err error) {
|
||||
d := make([]byte, 0, uint64(len(data))+32)
|
||||
d = fmt.Appendf(d, "%s:", strconv.FormatInt(time.Now().UnixNano(), 10))
|
||||
d = append(d, data...)
|
||||
iv, tag, ciphertext, pubkey, err := encrypt(d, other_pubkey, encryption_protocol)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ec := utils.EncryptedRemoteControlCmd{
|
||||
IV: b85_encode(iv), Tag: b85_encode(tag), Pubkey: b85_encode(pubkey), Encrypted: b85_encode(ciphertext)}
|
||||
if encryption_protocol != "1" {
|
||||
ec.EncProto = encryption_protocol
|
||||
}
|
||||
ans, err = json.Marshal(ec)
|
||||
return
|
||||
}
|
||||
|
||||
// }}}
|
||||
@@ -0,0 +1,102 @@
|
||||
package disk_cache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Entry struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastUsed time.Time
|
||||
}
|
||||
|
||||
type Metadata struct {
|
||||
TotalSize int64
|
||||
PathMap map[string]string
|
||||
SortedEntries []*Entry
|
||||
}
|
||||
|
||||
type DiskCache struct {
|
||||
Path string
|
||||
MaxSize int64
|
||||
|
||||
lock_file *os.File
|
||||
lock_mutex sync.Mutex
|
||||
entries Metadata
|
||||
entry_map map[string]*Entry
|
||||
entries_last_read_state *file_state
|
||||
entries_dirty bool
|
||||
get_dir string
|
||||
read_count int
|
||||
}
|
||||
|
||||
func NewDiskCache(path string, max_size int64) (dc *DiskCache, err error) {
|
||||
return new_disk_cache(path, max_size)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) ResultsDir() string {
|
||||
return dc.get_dir
|
||||
}
|
||||
|
||||
func (dc *DiskCache) unlock_and_set_err(err *error) {
|
||||
if ue := dc.unlock(); ue != nil && *err == nil {
|
||||
*err = ue
|
||||
}
|
||||
}
|
||||
|
||||
func (dc *DiskCache) Get(key string, items ...string) (ans map[string]string, err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
return dc.get(key, items)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) GetPath(path string, items ...string) (key string, ans map[string]string, err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
if key, err = key_for_path(path); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
ans, err = dc.get(key, items)
|
||||
return
|
||||
}
|
||||
|
||||
func (dc *DiskCache) Remove(key string) (err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
return dc.remove(key)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) Clear() (err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
return dc.clear()
|
||||
}
|
||||
|
||||
func (dc *DiskCache) AddPath(path, key string, items map[string][]byte) (ans map[string]string, err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
return dc.add_path(path, key, items)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) Add(key string, items map[string][]byte) (ans map[string]string, err error) {
|
||||
if err = dc.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer dc.unlock_and_set_err(&err)
|
||||
return dc.add(key, items)
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
package disk_cache
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type file_state struct {
|
||||
Size int64
|
||||
ModTime time.Time
|
||||
Inode uint64
|
||||
}
|
||||
|
||||
func (s file_state) String() string {
|
||||
return fmt.Sprintf("fs{Size: %d, Inode: %d, ModTime: %s}", s.Size, s.Inode, s.ModTime)
|
||||
}
|
||||
|
||||
func (s *file_state) equal(o *file_state) bool {
|
||||
return o != nil && s.Size == o.Size && s.ModTime.Equal(o.ModTime) && s.Inode == o.Inode
|
||||
}
|
||||
|
||||
func get_file_state(fi fs.FileInfo) *file_state {
|
||||
// The Sys() method returns the underlying data source (can be nil).
|
||||
// For Unix-like systems, it's a *syscall.Stat_t.
|
||||
stat, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
// For non-Unix systems, you might not have an inode.
|
||||
// In that case, you can fall back to using only size and mod time.
|
||||
return &file_state{
|
||||
Size: fi.Size(),
|
||||
ModTime: fi.ModTime(),
|
||||
Inode: 0, // Inode not available
|
||||
}
|
||||
}
|
||||
return &file_state{
|
||||
Size: fi.Size(),
|
||||
ModTime: fi.ModTime(),
|
||||
Inode: stat.Ino,
|
||||
}
|
||||
}
|
||||
|
||||
func get_file_state_from_path(path string) (*file_state, error) {
|
||||
if s, err := os.Stat(path); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return get_file_state(s), nil
|
||||
}
|
||||
}
|
||||
|
||||
const GET_DIR_PREFIX = "getdir-"
|
||||
|
||||
func new_disk_cache(path string, max_size int64) (dc *DiskCache, err error) {
|
||||
if path, err = filepath.Abs(path); err != nil {
|
||||
return
|
||||
}
|
||||
if err = os.MkdirAll(path, 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
ans := &DiskCache{Path: path, MaxSize: max_size}
|
||||
if err = ans.lock(); err != nil {
|
||||
return
|
||||
}
|
||||
defer ans.unlock_and_set_err(&err)
|
||||
if err = ans.ensure_entries(); err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if we := ans.write_entries_if_dirty(); we != nil && err == nil {
|
||||
err = we
|
||||
}
|
||||
}()
|
||||
if _, err := ans.prune(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ans.get_dir, err = os.MkdirTemp(ans.Path, GET_DIR_PREFIX+"*"); err != nil {
|
||||
return
|
||||
}
|
||||
if err = utils.AtExitRmtree(ans.get_dir); err != nil {
|
||||
return
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func key_for_path(path string) (key string, err error) {
|
||||
if path, err = filepath.EvalSymlinks(path); err != nil {
|
||||
return
|
||||
}
|
||||
if path, err = filepath.Abs(path); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
s, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
data := fmt.Sprintf("%s\x00%d\x00%d", path, s.Size(), s.ModTime().UnixNano())
|
||||
sum := sha256.Sum256(utils.UnsafeStringToBytes(data))
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
// lock() and unlock() must be paired: unlock() must only be called after a
|
||||
// successful lock(). lock() is not re-entrant, so it must not be called while
|
||||
// the lock is already held, that will deadlock.
|
||||
func (dc *DiskCache) lock() (err error) {
|
||||
dc.lock_mutex.Lock()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = dc.unlock()
|
||||
}
|
||||
}()
|
||||
if dc.lock_file, err = os.OpenFile(filepath.Join(dc.Path, "lockfile"), os.O_RDWR|os.O_CREATE, 0o600); err != nil {
|
||||
return
|
||||
}
|
||||
return utils.LockFileExclusive(dc.lock_file)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) unlock() (err error) {
|
||||
defer dc.lock_mutex.Unlock()
|
||||
if dc.lock_file != nil {
|
||||
err = utils.UnlockFile(dc.lock_file)
|
||||
if ce := dc.lock_file.Close(); ce != nil && err == nil {
|
||||
err = ce
|
||||
}
|
||||
dc.lock_file = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const ENTRIES_NAME = "entries.json"
|
||||
|
||||
func (dc *DiskCache) entries_path() string { return filepath.Join(dc.Path, ENTRIES_NAME) }
|
||||
|
||||
func (dc *DiskCache) write_entries_if_dirty() (err error) {
|
||||
if !dc.entries_dirty {
|
||||
return
|
||||
}
|
||||
path := dc.entries_path()
|
||||
defer func() {
|
||||
if err == nil {
|
||||
dc.entries_dirty = false
|
||||
if s, serr := get_file_state_from_path(path); serr == nil {
|
||||
dc.entries_last_read_state = s
|
||||
}
|
||||
}
|
||||
}()
|
||||
if d, err := json.Marshal(dc.entries); err != nil {
|
||||
return err
|
||||
} else {
|
||||
// use a rename so that the inode number changes
|
||||
// dont bother with full utils.AtomicWriteFile() as it is slower
|
||||
temp := path + ".temp"
|
||||
removed := false
|
||||
defer func() {
|
||||
if !removed {
|
||||
_ = os.Remove(temp)
|
||||
removed = true
|
||||
}
|
||||
}()
|
||||
if err = os.WriteFile(temp, d, 0o600); err == nil {
|
||||
if err = os.Rename(temp, path); err == nil {
|
||||
removed = true
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (e Entry) String() string {
|
||||
return fmt.Sprintf("Entry{Key: %s, Size: %d, LastUsed: %s}", e.Key, e.Size, e.LastUsed)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) entries_from_folders() (total_size int64, ans map[string]*Entry, sorted []*Entry, err error) {
|
||||
if entries, err := os.ReadDir(dc.Path); err != nil {
|
||||
return 0, nil, nil, err
|
||||
} else {
|
||||
ans = make(map[string]*Entry)
|
||||
var total int64
|
||||
for _, x := range entries {
|
||||
if x.IsDir() {
|
||||
if sub_entries, err := os.ReadDir(filepath.Join(dc.Path, x.Name())); err == nil && len(sub_entries) == 1 {
|
||||
key := sub_entries[0].Name()
|
||||
path := dc.folder_for_key(key)
|
||||
if file_entries, err := os.ReadDir(path); err == nil {
|
||||
e := Entry{Key: key}
|
||||
for _, f := range file_entries {
|
||||
if fi, err := f.Info(); err == nil {
|
||||
e.Size += fi.Size()
|
||||
if fi.ModTime().After(e.LastUsed) {
|
||||
e.LastUsed = fi.ModTime()
|
||||
}
|
||||
}
|
||||
}
|
||||
ans[key] = &e
|
||||
total += e.Size
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sorted = utils.Values(ans)
|
||||
slices.SortFunc(sorted, func(a, b *Entry) int {
|
||||
return a.LastUsed.Compare(b.LastUsed)
|
||||
})
|
||||
return total, ans, sorted, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (dc *DiskCache) rebuild_entries() error {
|
||||
total, ans, sorted, err := dc.entries_from_folders()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dc.entries = Metadata{TotalSize: total, SortedEntries: sorted, PathMap: make(map[string]string)}
|
||||
dc.entry_map = ans
|
||||
dc.entries_dirty = true
|
||||
return dc.write_entries_if_dirty()
|
||||
}
|
||||
|
||||
func (dc *DiskCache) ensure_entries() error {
|
||||
needed := dc.entry_map == nil || dc.entries_last_read_state == nil
|
||||
path := dc.entries_path()
|
||||
var fstate *file_state
|
||||
if !needed {
|
||||
if s, err := get_file_state_from_path(path); err == nil {
|
||||
fstate = s
|
||||
if !s.equal(dc.entries_last_read_state) {
|
||||
needed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if needed {
|
||||
if data, err := os.ReadFile(path); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
dc.entry_map = make(map[string]*Entry)
|
||||
dc.entries = Metadata{SortedEntries: make([]*Entry, 0), PathMap: make(map[string]string)}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
dc.read_count += 1
|
||||
dc.entries = Metadata{SortedEntries: make([]*Entry, 0), PathMap: make(map[string]string)}
|
||||
if err := json.Unmarshal(data, &dc.entries); err != nil {
|
||||
// corrupted data
|
||||
dc.rebuild_entries()
|
||||
} else {
|
||||
if fstate == nil {
|
||||
if s, err := get_file_state_from_path(path); err == nil {
|
||||
fstate = s
|
||||
}
|
||||
}
|
||||
dc.entries_last_read_state = fstate
|
||||
}
|
||||
dc.entry_map = make(map[string]*Entry)
|
||||
for _, e := range dc.entries.SortedEntries {
|
||||
dc.entry_map[e.Key] = e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dc *DiskCache) folder_for_key(key string) (ans string) {
|
||||
if len(key) < 5 {
|
||||
ans = filepath.Join(key, key)
|
||||
} else {
|
||||
ans = filepath.Join(key[:4], key)
|
||||
}
|
||||
return filepath.Join(dc.Path, ans)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) export_to_get_dir(key, path string) (string, error) {
|
||||
dest := filepath.Join(dc.get_dir, key+"-"+filepath.Base(path))
|
||||
if err := os.Link(path, dest); err == nil {
|
||||
return dest, nil
|
||||
} else if !os.IsExist(err) {
|
||||
return "", err
|
||||
}
|
||||
src_info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if dest_info, err := os.Stat(dest); err == nil && os.SameFile(src_info, dest_info) {
|
||||
return dest, nil
|
||||
}
|
||||
// Replace dest atomically so that a path previously returned to a
|
||||
// caller is never missing, even momentarily.
|
||||
temp := dest + ".temp"
|
||||
_ = os.Remove(temp)
|
||||
if err := os.Link(path, temp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := os.Rename(temp, dest); err != nil {
|
||||
_ = os.Remove(temp)
|
||||
return "", err
|
||||
}
|
||||
return dest, nil
|
||||
}
|
||||
|
||||
func (dc *DiskCache) get(key string, items []string) (map[string]string, error) {
|
||||
if err := dc.ensure_entries(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := dc.folder_for_key(key)
|
||||
if len(items) == 0 {
|
||||
if entries, err := os.ReadDir(base); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
err = nil
|
||||
}
|
||||
return nil, err
|
||||
} else {
|
||||
for _, e := range entries {
|
||||
items = append(items, e.Name())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if s, err := os.Stat(base); err != nil || !s.IsDir() {
|
||||
if os.IsNotExist(err) {
|
||||
err = nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ans := make(map[string]string, len(items))
|
||||
for _, x := range items {
|
||||
p := filepath.Join(base, x)
|
||||
if s, err := os.Stat(p); err != nil || s.IsDir() {
|
||||
continue
|
||||
}
|
||||
dest, _ := dc.export_to_get_dir(key, p)
|
||||
if dest != "" {
|
||||
ans[x] = dest
|
||||
}
|
||||
}
|
||||
if len(items) > 0 {
|
||||
dc.update_timestamp(key)
|
||||
}
|
||||
return ans, dc.write_entries_if_dirty()
|
||||
}
|
||||
|
||||
func (dc *DiskCache) clear() (err error) {
|
||||
if entries, err := os.ReadDir(dc.Path); err != nil {
|
||||
return err
|
||||
} else {
|
||||
defer func() {
|
||||
if we := dc.write_entries_if_dirty(); we != nil && err == nil {
|
||||
err = we
|
||||
}
|
||||
}()
|
||||
for _, x := range entries {
|
||||
if x.IsDir() && !strings.HasPrefix(x.Name(), GET_DIR_PREFIX) {
|
||||
_ = os.RemoveAll(filepath.Join(dc.Path, x.Name()))
|
||||
}
|
||||
}
|
||||
dc.entries_dirty = true
|
||||
dc.entry_map = make(map[string]*Entry)
|
||||
dc.entries.SortedEntries = make([]*Entry, 0)
|
||||
dc.entries.TotalSize = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dc *DiskCache) remove(key string) (err error) {
|
||||
if err = dc.ensure_entries(); err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if we := dc.write_entries_if_dirty(); we != nil && err == nil {
|
||||
err = we
|
||||
}
|
||||
}()
|
||||
base := dc.folder_for_key(key)
|
||||
if err = os.RemoveAll(base); err == nil {
|
||||
t := dc.entry_map[key]
|
||||
if t != nil {
|
||||
delete(dc.entry_map, key)
|
||||
dc.entries.TotalSize = max(0, dc.entries.TotalSize-t.Size)
|
||||
dc.entries.SortedEntries = utils.Filter(dc.entries.SortedEntries, func(x *Entry) bool { return x.Key != key })
|
||||
dc.entries_dirty = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dc *DiskCache) prune() (bool, error) {
|
||||
if dc.MaxSize < 1 || dc.entries.TotalSize <= dc.MaxSize {
|
||||
return false, nil
|
||||
}
|
||||
for dc.entries.TotalSize > dc.MaxSize && len(dc.entries.SortedEntries) > 0 {
|
||||
base := dc.folder_for_key(dc.entries.SortedEntries[0].Key)
|
||||
if err := os.RemoveAll(base); err == nil {
|
||||
t := dc.entries.SortedEntries[0]
|
||||
delete(dc.entry_map, t.Key)
|
||||
maps.DeleteFunc(dc.entries.PathMap, func(path, key string) bool { return key == t.Key })
|
||||
dc.entries.TotalSize = max(0, dc.entries.TotalSize-t.Size)
|
||||
dc.entries.SortedEntries = dc.entries.SortedEntries[1:]
|
||||
dc.entries_dirty = true
|
||||
} else {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (dc *DiskCache) update_timestamp(key string) {
|
||||
t := dc.entry_map[key]
|
||||
if t == nil {
|
||||
// the folder for key exists but is not in the metadata, can happen
|
||||
// if entries.json was written by an older, racy version
|
||||
return
|
||||
}
|
||||
t.LastUsed = time.Now()
|
||||
if idx := slices.Index(dc.entries.SortedEntries, t); idx < 0 {
|
||||
dc.entries.SortedEntries = append(dc.entries.SortedEntries, t)
|
||||
} else {
|
||||
copy(dc.entries.SortedEntries[idx:], dc.entries.SortedEntries[idx+1:])
|
||||
dc.entries.SortedEntries[len(dc.entries.SortedEntries)-1] = t
|
||||
}
|
||||
dc.entries_dirty = true
|
||||
}
|
||||
|
||||
func (dc *DiskCache) update_accounting(key string, changed int64) (err error) {
|
||||
t := dc.entry_map[key]
|
||||
if t == nil {
|
||||
t = &Entry{Key: key}
|
||||
dc.entry_map[key] = t
|
||||
dc.entries.SortedEntries = append(dc.entries.SortedEntries, t)
|
||||
}
|
||||
old_size := t.Size
|
||||
t.Size += changed
|
||||
t.Size = max(0, t.Size)
|
||||
dc.entries.TotalSize += t.Size - old_size
|
||||
dc.entries_dirty = true
|
||||
dc.update_timestamp(key)
|
||||
dc.prune()
|
||||
return dc.write_entries_if_dirty()
|
||||
}
|
||||
|
||||
func (dc *DiskCache) keys() (ans []string, err error) {
|
||||
if err = dc.ensure_entries(); err != nil {
|
||||
return
|
||||
}
|
||||
ans = make([]string, len(dc.entries.SortedEntries))
|
||||
for i, e := range dc.entries.SortedEntries {
|
||||
ans[i] = e.Key
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dc *DiskCache) add_path(path, key string, items map[string][]byte) (ans map[string]string, err error) {
|
||||
if err = dc.ensure_entries(); err != nil {
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if we := dc.write_entries_if_dirty(); we != nil && err == nil {
|
||||
err = we
|
||||
}
|
||||
}()
|
||||
|
||||
if existing := dc.entries.PathMap[path]; existing != "" && existing != key {
|
||||
delete(dc.entries.PathMap, path)
|
||||
dc.entries_dirty = true
|
||||
if err = dc.remove(existing); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
dc.entries.PathMap[path] = key
|
||||
dc.entries_dirty = true
|
||||
return dc.add(key, items)
|
||||
}
|
||||
|
||||
func (dc *DiskCache) add(key string, items map[string][]byte) (ans map[string]string, err error) {
|
||||
if err = dc.ensure_entries(); err != nil {
|
||||
return
|
||||
}
|
||||
base := dc.folder_for_key(key)
|
||||
if err = os.MkdirAll(base, 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
var changed int64
|
||||
defer func() {
|
||||
e := dc.update_accounting(key, changed)
|
||||
if err == nil {
|
||||
err = e
|
||||
}
|
||||
}()
|
||||
ans = make(map[string]string, len(items))
|
||||
for x, data := range items {
|
||||
p := filepath.Join(base, x)
|
||||
var before int64
|
||||
exists := false
|
||||
if s, err := os.Stat(p); err == nil {
|
||||
before = s.Size()
|
||||
exists = true
|
||||
}
|
||||
if len(data) == 0 {
|
||||
if exists {
|
||||
if err = os.Remove(p); err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
err = nil
|
||||
}
|
||||
changed -= before
|
||||
}
|
||||
} else {
|
||||
// unlink the file so that writing to it does not change a
|
||||
// previously linked copy created by get()
|
||||
if exists {
|
||||
_ = os.Remove(p)
|
||||
}
|
||||
if err = os.WriteFile(p, data, 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
changed += int64(len(data)) - before
|
||||
if dest, err := dc.export_to_get_dir(key, p); err != nil {
|
||||
return ans, err
|
||||
} else {
|
||||
ans[x] = dest
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package disk_cache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestDiskCache(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
dc, err := NewDiskCache(tdir, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dc2, err := NewDiskCache(tdir, dc.MaxSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ensure_entries := func() {
|
||||
for _, x := range []*DiskCache{dc, dc2} {
|
||||
if err = x.ensure_entries(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
arc := func(counts ...int) {
|
||||
ensure_entries()
|
||||
if diff := cmp.Diff(counts, []int{dc.read_count, dc2.read_count}); diff != "" {
|
||||
t.Fatalf("disk cache has unexpected read count\n%s\n%s", diff, debug.Stack())
|
||||
}
|
||||
}
|
||||
add := func(dc *DiskCache, key string, data map[string]string) {
|
||||
d := make(map[string][]byte, len(data))
|
||||
for k, v := range data {
|
||||
d[k] = []byte(v)
|
||||
}
|
||||
if _, err := dc.Add(key, d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ensure_entries()
|
||||
}
|
||||
|
||||
m, err := dc.Get("missing", "one", "two")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m) > 0 {
|
||||
t.Fatalf("Unexpected return from missing: %s", m)
|
||||
}
|
||||
|
||||
ad := func(key string, expected map[string]string) {
|
||||
for _, x := range []*DiskCache{dc, dc2} {
|
||||
actual, err := x.Get(key, utils.Keys(expected)...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for k, path := range actual {
|
||||
d, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual[k] = string(d)
|
||||
}
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Data for %s not equal: %s", key, diff)
|
||||
}
|
||||
ensure_entries()
|
||||
}
|
||||
}
|
||||
ak := func(keys ...string) {
|
||||
for i, x := range []*DiskCache{dc, dc2} {
|
||||
kk, err := x.keys()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff := cmp.Diff(keys, kk); diff != "" {
|
||||
t.Fatalf("wrong keys in %d: %s", i+1, diff)
|
||||
}
|
||||
}
|
||||
ensure_entries()
|
||||
}
|
||||
add(dc, "k1", map[string]string{"1": "abcd", "2": "efgh"})
|
||||
arc(0, 1)
|
||||
ad("k1", map[string]string{"1": "abcd", "2": "efgh"})
|
||||
arc(1, 2) // the two gets cause two updates
|
||||
add(dc, "k1", map[string]string{"3": "ijk", "4": "lmo"})
|
||||
arc(1, 3) // dc.Add() causes re-read in dc2
|
||||
ak("k1")
|
||||
arc(1, 3)
|
||||
add(dc2, "k2", map[string]string{"1": "123456789"})
|
||||
arc(2, 3) // dc2.Add() causes re-read in dc
|
||||
ak("k1", "k2")
|
||||
arc(2, 3)
|
||||
ad("k1", map[string]string{"1": "abcd", "2": "efgh", "3": "ijk"})
|
||||
if dc.entries.TotalSize != 14+9 {
|
||||
t.Fatalf("TotalSize: %d != %d", dc.entries.TotalSize, 14+9)
|
||||
}
|
||||
arc(3, 4) // the two gets cause two updates
|
||||
ak("k2", "k1")
|
||||
dc.Get("k2")
|
||||
arc(3, 5) // dc.Get() causes dc2 to read
|
||||
ak("k1", "k2")
|
||||
add(dc, "k3", map[string]string{"1": strings.Repeat("a", int(dc.MaxSize)-10)})
|
||||
arc(3, 6) // dc.Add() causes dc2 to read
|
||||
ak("k2", "k3")
|
||||
// check that creating a new disk cache prunes
|
||||
_, err = NewDiskCache(tdir, dc.MaxSize-8)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ak("k3")
|
||||
arc(4, 7) // NewDiskCache()
|
||||
|
||||
// test the path api
|
||||
path := filepath.Join(tdir, "source")
|
||||
if err = os.WriteFile(path, []byte("abcdfjrof"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, _, err := dc.GetPath(path)
|
||||
if _, err = dc.AddPath(path, key, map[string][]byte{"1": []byte("1")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, entries_before, _ := dc.entries_from_folders()
|
||||
if diff := cmp.Diff(1, len(dc.entries.PathMap)); diff != "" {
|
||||
t.Fatalf("unexpected pathmap count: %s", diff)
|
||||
}
|
||||
if err = os.WriteFile(path, []byte("changed contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = dc.AddPath(path, key, map[string][]byte{"1": []byte("2")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff := cmp.Diff(1, len(dc.entries.PathMap)); diff != "" {
|
||||
t.Fatalf("unexpected pathmap count: %s", diff)
|
||||
}
|
||||
_, _, entries_after, _ := dc.entries_from_folders()
|
||||
if len(entries_before) != len(entries_after) {
|
||||
t.Fatalf("unexpected entries: %s", entries_after)
|
||||
}
|
||||
arc(4, 8) // dc.AddPath() causes dc2 to read
|
||||
}
|
||||
|
||||
func TestDiskCacheLock(t *testing.T) {
|
||||
dc, err := NewDiskCache(t.TempDir(), 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = dc.lock(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dc.unlock()
|
||||
if dc.lock_mutex.TryLock() {
|
||||
dc.lock_mutex.Unlock()
|
||||
t.Fatal("cache mutex released before the cache operation finished")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskCacheConcurrentGet(t *testing.T) {
|
||||
dc, err := NewDiskCache(t.TempDir(), 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = dc.Add("sharedkey", map[string][]byte{"data": []byte("cached")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range 6 {
|
||||
workers.Go(func() {
|
||||
<-start
|
||||
for range 8 {
|
||||
paths, err := dc.Get("sharedkey", "data")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if paths["data"] == "" {
|
||||
t.Error("concurrent Get lost cached data")
|
||||
return
|
||||
}
|
||||
if data, err := os.ReadFile(paths["data"]); err != nil || string(data) != "cached" {
|
||||
t.Errorf("path returned by concurrent Get is not readable: %q, %v", data, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
}
|
||||
|
||||
func TestDiskCacheExportReplacesAtomically(t *testing.T) {
|
||||
dc, err := NewDiskCache(t.TempDir(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths, err := dc.Add("key", map[string][]byte{"data": []byte("old")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exported := paths["data"]
|
||||
// a Get of unchanged data must not touch the previously exported path
|
||||
before, err := os.Stat(exported)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if paths, err = dc.Get("key", "data"); err != nil || paths["data"] != exported {
|
||||
t.Fatalf("Get returned unexpected paths: %v, %v", paths, err)
|
||||
}
|
||||
if after, err := os.Stat(exported); err != nil || !os.SameFile(before, after) {
|
||||
t.Fatalf("Get replaced an already exported file: %v", err)
|
||||
}
|
||||
// updated data must replace the exported path, leaving no temp files
|
||||
if paths, err = dc.Add("key", map[string][]byte{"data": []byte("new")}); err != nil || paths["data"] != exported {
|
||||
t.Fatalf("Add returned unexpected paths: %v, %v", paths, err)
|
||||
}
|
||||
if data, err := os.ReadFile(exported); err != nil || string(data) != "new" {
|
||||
t.Fatalf("exported file not updated: %q, %v", data, err)
|
||||
}
|
||||
entries, err := os.ReadDir(dc.ResultsDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
t.Fatalf("unexpected files in results dir: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskCacheGetUntrackedKey(t *testing.T) {
|
||||
dc, err := NewDiskCache(t.TempDir(), 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// simulate a key folder that is missing from entries.json
|
||||
base := dc.folder_for_key("untracked")
|
||||
if err = os.MkdirAll(base, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(base, "data"), []byte("orphan"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths, err := dc.Get("untracked", "data")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data, err := os.ReadFile(paths["data"]); err != nil || string(data) != "orphan" {
|
||||
t.Fatalf("could not read untracked key: %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskCacheLockErrors(t *testing.T) {
|
||||
source := filepath.Join(t.TempDir(), "source")
|
||||
if err := os.WriteFile(source, []byte("source"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
run func(*DiskCache) error
|
||||
// whether run() locks dc itself, rather than some other DiskCache
|
||||
uses_dc bool
|
||||
}{
|
||||
{"Get", func(dc *DiskCache) error {
|
||||
_, err := dc.Get("key", "data")
|
||||
return err
|
||||
}, true},
|
||||
{"GetPath", func(dc *DiskCache) error {
|
||||
_, _, err := dc.GetPath(source, "data")
|
||||
return err
|
||||
}, true},
|
||||
{"Remove", func(dc *DiskCache) error { return dc.Remove("key") }, true},
|
||||
{"Clear", func(dc *DiskCache) error { return dc.Clear() }, true},
|
||||
{"AddPath", func(dc *DiskCache) error {
|
||||
_, err := dc.AddPath(source, "key", map[string][]byte{"data": []byte("updated")})
|
||||
return err
|
||||
}, true},
|
||||
{"Add", func(dc *DiskCache) error {
|
||||
_, err := dc.Add("key", map[string][]byte{"data": []byte("updated")})
|
||||
return err
|
||||
}, true},
|
||||
{"NewDiskCache", func(dc *DiskCache) error {
|
||||
_, err := NewDiskCache(dc.Path, dc.MaxSize)
|
||||
return err
|
||||
}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dc, err := NewDiskCache(t.TempDir(), 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = dc.Add("key", map[string][]byte{"data": []byte("cached")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lock_path := filepath.Join(dc.Path, "lockfile")
|
||||
if err = os.Remove(lock_path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.Mkdir(lock_path, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tc.run(dc); err == nil {
|
||||
t.Error("cache operation ignored failure to acquire the lock")
|
||||
}
|
||||
if tc.uses_dc {
|
||||
if !dc.lock_mutex.TryLock() {
|
||||
t.Fatal("failed lock attempt did not release the mutex")
|
||||
}
|
||||
dc.lock_mutex.Unlock()
|
||||
if dc.lock_file != nil {
|
||||
t.Fatal("failed lock attempt did not close the lock file")
|
||||
}
|
||||
}
|
||||
if err = os.Remove(lock_path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths, err := dc.Get("key", "data")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(paths["data"])
|
||||
if err != nil || string(data) != "cached" {
|
||||
t.Fatalf("cache data changed after a failed lock attempt: %q, %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
/*
|
||||
|
||||
Algorithm
|
||||
---------
|
||||
|
||||
Based on code from fzf (MIT licensed):
|
||||
https://github.com/junegunn/fzf
|
||||
|
||||
FuzzyMatch implements a modified version of Smith-Waterman algorithm to find
|
||||
the optimal solution (highest score) according to the scoring criteria. Unlike
|
||||
the original algorithm, omission or mismatch of a character in the pattern is
|
||||
not allowed.
|
||||
|
||||
Scoring criteria
|
||||
----------------
|
||||
|
||||
- We prefer matches at special positions, such as the start of a word, or
|
||||
uppercase character in camelCase words.
|
||||
|
||||
- That is, we prefer an occurrence of the pattern with more characters
|
||||
matching at special positions, even if the total match length is longer.
|
||||
e.g. "fuzzyfinder" vs. "fuzzy-finder" on "ff"
|
||||
````````````
|
||||
- Also, if the first character in the pattern appears at one of the special
|
||||
positions, the bonus point for the position is multiplied by a constant
|
||||
as it is extremely likely that the first character in the typed pattern
|
||||
has more significance than the rest.
|
||||
e.g. "fo-bar" vs. "foob-r" on "br"
|
||||
``````
|
||||
- But since fzf is still a fuzzy finder, not an acronym finder, we should also
|
||||
consider the total length of the matched substring. This is why we have the
|
||||
gap penalty. The gap penalty increases as the length of the gap (distance
|
||||
between the matching characters) increases, so the effect of the bonus is
|
||||
eventually cancelled at some point.
|
||||
e.g. "fuzzyfinder" vs. "fuzzy-blurry-finder" on "ff"
|
||||
```````````
|
||||
- Consequently, it is crucial to find the right balance between the bonus
|
||||
and the gap penalty. The parameters were chosen that the bonus is cancelled
|
||||
when the gap size increases beyond 8 characters.
|
||||
|
||||
- The bonus mechanism can have the undesirable side effect where consecutive
|
||||
matches are ranked lower than the ones with gaps.
|
||||
e.g. "foobar" vs. "foo-bar" on "foob"
|
||||
```````
|
||||
- To correct this anomaly, we also give extra bonus point to each character
|
||||
in a consecutive matching chunk.
|
||||
e.g. "foobar" vs. "foo-bar" on "foob"
|
||||
``````
|
||||
- The amount of consecutive bonus is primarily determined by the bonus of the
|
||||
first character in the chunk.
|
||||
e.g. "foobar" vs. "out-of-bound" on "oob"
|
||||
````````````
|
||||
*/
|
||||
|
||||
func try_skip(input *Chars, case_sensitive bool, b byte, from int) int {
|
||||
byteArray := input.Bytes()[from:]
|
||||
idx := bytes.IndexByte(byteArray, b)
|
||||
if idx == 0 {
|
||||
// Can't skip any further
|
||||
return from
|
||||
}
|
||||
// We may need to search for the uppercase letter again. We don't have to
|
||||
// consider normalization as we can be sure that this is an ASCII string.
|
||||
if !case_sensitive && b >= 'a' && b <= 'z' {
|
||||
if idx > 0 {
|
||||
byteArray = byteArray[:idx]
|
||||
}
|
||||
uidx := bytes.IndexByte(byteArray, b-32)
|
||||
if uidx >= 0 {
|
||||
idx = uidx
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
return -1
|
||||
}
|
||||
return from + idx
|
||||
}
|
||||
|
||||
func ascii_fuzzy_index(input *Chars, pattern []rune, pattern_is_ascii bool, case_sensitive bool) (int, int) {
|
||||
// Can't determine
|
||||
if !input.Is_ASCII() {
|
||||
return 0, input.Length()
|
||||
}
|
||||
// Can't match
|
||||
if !pattern_is_ascii {
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
firstIdx, idx, lastIdx := 0, 0, 0
|
||||
var b byte
|
||||
for pidx := range len(pattern) {
|
||||
b = byte(pattern[pidx])
|
||||
idx = try_skip(input, case_sensitive, b, idx)
|
||||
if idx < 0 {
|
||||
return -1, -1
|
||||
}
|
||||
if pidx == 0 && idx > 0 {
|
||||
// Step back to find the right bonus point
|
||||
firstIdx = idx - 1
|
||||
}
|
||||
lastIdx = idx
|
||||
idx++
|
||||
}
|
||||
|
||||
// Find the last appearance of the last character of the pattern to limit the search scope
|
||||
bu := b
|
||||
if !case_sensitive && b >= 'a' && b <= 'z' {
|
||||
bu = b - 32
|
||||
}
|
||||
scope := input.Bytes()[lastIdx:]
|
||||
for offset := len(scope) - 1; offset > 0; offset-- {
|
||||
if scope[offset] == b || scope[offset] == bu {
|
||||
return firstIdx, lastIdx + offset + 1
|
||||
}
|
||||
}
|
||||
return firstIdx, lastIdx + 1
|
||||
}
|
||||
|
||||
func (m *FuzzyMatcher) charClassOfNonAscii(char rune) charClass {
|
||||
if unicode.IsLower(char) {
|
||||
return charLower
|
||||
} else if unicode.IsUpper(char) {
|
||||
return charUpper
|
||||
} else if unicode.IsNumber(char) {
|
||||
return charNumber
|
||||
} else if unicode.IsLetter(char) {
|
||||
return charLetter
|
||||
} else if unicode.IsSpace(char) {
|
||||
return charWhite
|
||||
} else if strings.ContainsRune(m.delimiterChars, char) {
|
||||
return charDelimiter
|
||||
}
|
||||
return charNonWord
|
||||
}
|
||||
|
||||
// Score the input against pattern. If !m.Case_sensitive pattern must be
|
||||
// lowercased already. pattern must be non-empty. When m.Ignore_accents
|
||||
// accents must already be removed from both pattern and input.
|
||||
func (m *FuzzyMatcher) score_one(input *Chars, pattern []rune, pattern_is_ascii bool, slab *slab) (ans Result) {
|
||||
M := len(pattern)
|
||||
N := input.Length()
|
||||
if M > N {
|
||||
return
|
||||
}
|
||||
|
||||
// Phase 1. Optimized search for ASCII string
|
||||
minIdx, maxIdx := ascii_fuzzy_index(input, pattern, pattern_is_ascii, m.Case_sensitive)
|
||||
if minIdx < 0 {
|
||||
return
|
||||
}
|
||||
// fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString())
|
||||
N = maxIdx - minIdx
|
||||
|
||||
slab.reset()
|
||||
|
||||
H0 := slab.alloc16(N)
|
||||
C0 := slab.alloc16(N)
|
||||
// Bonus point for each position
|
||||
B := slab.alloc16(N)
|
||||
// The first occurrence of each character in the pattern
|
||||
F := slab.alloc32(M)
|
||||
// Rune array
|
||||
T := slab.alloc32(N)
|
||||
input.CopyRunes(T, minIdx)
|
||||
|
||||
// Phase 2. Calculate bonus for each point
|
||||
maxScore, maxScorePos := int16(0), 0
|
||||
pidx, lastIdx := 0, 0
|
||||
pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), m.initialCharClass, false
|
||||
for off, char := range T {
|
||||
var class charClass
|
||||
if char <= unicode.MaxASCII {
|
||||
class = m.asciiCharClasses[char]
|
||||
if !m.Case_sensitive && class == charUpper {
|
||||
char += 32
|
||||
T[off] = char
|
||||
}
|
||||
} else {
|
||||
class = m.charClassOfNonAscii(char)
|
||||
if !m.Case_sensitive && class == charUpper {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
T[off] = char
|
||||
}
|
||||
|
||||
bonus := m.bonusMatrix[prevClass][class]
|
||||
B[off] = bonus
|
||||
prevClass = class
|
||||
|
||||
if char == pchar {
|
||||
if pidx < M {
|
||||
F[pidx] = int32(off)
|
||||
pidx++
|
||||
pchar = pattern[min(pidx, M-1)]
|
||||
}
|
||||
lastIdx = off
|
||||
}
|
||||
|
||||
if char == pchar0 {
|
||||
score := scoreMatch + bonus*bonusFirstCharMultiplier
|
||||
H0[off] = score
|
||||
C0[off] = 1
|
||||
if M == 1 && (!m.Backwards && score > maxScore || m.Backwards && score >= maxScore) {
|
||||
maxScore, maxScorePos = score, off
|
||||
if !m.Backwards && bonus >= bonusBoundary {
|
||||
break
|
||||
}
|
||||
}
|
||||
inGap = false
|
||||
} else {
|
||||
if inGap {
|
||||
H0[off] = max(prevH0+scoreGapExtension, 0)
|
||||
} else {
|
||||
H0[off] = max(prevH0+scoreGapStart, 0)
|
||||
}
|
||||
C0[off] = 0
|
||||
inGap = true
|
||||
}
|
||||
prevH0 = H0[off]
|
||||
}
|
||||
if pidx != M {
|
||||
return
|
||||
}
|
||||
if M == 1 {
|
||||
if m.Without_positions {
|
||||
return Result{Score: uint(maxScore)}
|
||||
}
|
||||
return Result{Score: uint(maxScore), Positions: []int{minIdx + maxScorePos}}
|
||||
}
|
||||
|
||||
// Phase 3. Fill in score matrix (H)
|
||||
// Unlike the original algorithm, we do not allow omission.
|
||||
f0 := int(F[0])
|
||||
width := lastIdx - f0 + 1
|
||||
H := slab.alloc16(width * M)
|
||||
copy(H, H0[f0:lastIdx+1])
|
||||
|
||||
// Possible length of consecutive chunk at each position.
|
||||
C := slab.alloc16(width * M)
|
||||
copy(C, C0[f0:lastIdx+1])
|
||||
|
||||
Fsub := F[1:]
|
||||
Psub := pattern[1:][:len(Fsub)]
|
||||
for off, f := range Fsub {
|
||||
f := int(f)
|
||||
pchar := Psub[off]
|
||||
pidx := off + 1
|
||||
row := pidx * width
|
||||
inGap := false
|
||||
Tsub := T[f : lastIdx+1]
|
||||
Bsub := B[f:][:len(Tsub)]
|
||||
Csub := C[row+f-f0:][:len(Tsub)]
|
||||
Cdiag := C[row+f-f0-1-width:][:len(Tsub)]
|
||||
Hsub := H[row+f-f0:][:len(Tsub)]
|
||||
Hdiag := H[row+f-f0-1-width:][:len(Tsub)]
|
||||
Hleft := H[row+f-f0-1:][:len(Tsub)]
|
||||
Hleft[0] = 0
|
||||
for off, char := range Tsub {
|
||||
col := off + f
|
||||
var s1, s2, consecutive int16
|
||||
|
||||
if inGap {
|
||||
s2 = Hleft[off] + scoreGapExtension
|
||||
} else {
|
||||
s2 = Hleft[off] + scoreGapStart
|
||||
}
|
||||
|
||||
if pchar == char {
|
||||
s1 = Hdiag[off] + scoreMatch
|
||||
b := Bsub[off]
|
||||
consecutive = Cdiag[off] + 1
|
||||
if consecutive > 1 {
|
||||
fb := B[col-int(consecutive)+1]
|
||||
// Break consecutive chunk
|
||||
if b >= bonusBoundary && b > fb {
|
||||
consecutive = 1
|
||||
} else {
|
||||
b = max(b, max(bonusConsecutive, fb))
|
||||
}
|
||||
}
|
||||
if s1+b < s2 {
|
||||
s1 += Bsub[off]
|
||||
consecutive = 0
|
||||
} else {
|
||||
s1 += b
|
||||
}
|
||||
}
|
||||
Csub[off] = consecutive
|
||||
|
||||
inGap = s1 < s2
|
||||
score := max(max(s1, s2), 0)
|
||||
if pidx == M-1 && (!m.Backwards && score > maxScore || m.Backwards && score >= maxScore) {
|
||||
maxScore, maxScorePos = score, col
|
||||
}
|
||||
Hsub[off] = score
|
||||
}
|
||||
}
|
||||
// Phase 4. (Optional) Backtrace to find character positions
|
||||
var pos []int
|
||||
j := f0
|
||||
if !m.Without_positions {
|
||||
pos = make([]int, 0, M)
|
||||
i := M - 1
|
||||
j = maxScorePos
|
||||
preferMatch := true
|
||||
for {
|
||||
I := i * width
|
||||
j0 := j - f0
|
||||
s := H[I+j0]
|
||||
|
||||
var s1, s2 int16
|
||||
if i > 0 && j >= int(F[i]) {
|
||||
s1 = H[I-width+j0-1]
|
||||
}
|
||||
if j > int(F[i]) {
|
||||
s2 = H[I+j0-1]
|
||||
}
|
||||
|
||||
if s > s1 && (s > s2 || s == s2 && preferMatch) {
|
||||
pos = append(pos, j+minIdx)
|
||||
if i == 0 {
|
||||
break
|
||||
}
|
||||
i--
|
||||
}
|
||||
preferMatch = C[I+j0] > 1 || I+width+j0+1 < len(C) && C[I+width+j0+1] > 0
|
||||
j--
|
||||
}
|
||||
}
|
||||
return Result{Score: uint(maxScore), Positions: pos}
|
||||
}
|
||||
|
||||
func (m *FuzzyMatcher) score(items []string, pattern string, scoring_func func(string, []rune, bool, *slab, func(string) Chars) Result) (ans []Result, err error) {
|
||||
if pattern == "" || len(items) < 1 {
|
||||
return make([]Result, len(items)), nil
|
||||
}
|
||||
as_chars := CharsFromString
|
||||
if m.Ignore_accents {
|
||||
pattern = string(CharsFromStringWithoutAccents(pattern).runes)
|
||||
as_chars = CharsFromStringWithoutAccents
|
||||
}
|
||||
pattern = norm.NFC.String(pattern)
|
||||
if !m.Case_sensitive {
|
||||
pattern = strings.ToLower(pattern)
|
||||
}
|
||||
pat := []rune(pattern)
|
||||
pattern_is_ascii := !slices.ContainsFunc(pat, func(r rune) bool { return r >= utf8.RuneSelf })
|
||||
ans = make([]Result, len(items))
|
||||
err = parallel.Run_in_parallel_over_range(0, func(start, end int) {
|
||||
s := slab{}
|
||||
for i := start; i < end; i++ {
|
||||
ans[i] = scoring_func(items[i], pat, pattern_is_ascii, &s, as_chars)
|
||||
}
|
||||
}, 0, len(items))
|
||||
return
|
||||
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
gcmp "github.com/google/go-cmp/cmp"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func assertMatch(t *testing.T, m *FuzzyMatcher, item string, query string, start, end, score int) {
|
||||
r, err := m.Score([]string{item}, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r[0].Score != uint(score) {
|
||||
t.Fatalf("Score of %#v in %#v is %d instead of %d", query, item, r[0].Score, score)
|
||||
}
|
||||
if start > -1 && end > -1 {
|
||||
p := r[0].Positions
|
||||
sort.Ints(p)
|
||||
if len(p) < 1 {
|
||||
t.Fatalf("Got no positions for %#v in %#v", query, item)
|
||||
}
|
||||
if p[0] != start {
|
||||
t.Fatalf("First char of %#v in %#v at %d instead of %d", query, item, p[0], start)
|
||||
}
|
||||
if p[len(p)-1]+1 != end {
|
||||
t.Fatalf("Last char of %#v in %#v at %d instead of %d", query, item, p[len(p)-1], end-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFZFAlgo(t *testing.T) {
|
||||
fn := NewFuzzyMatcher(DEFAULT_SCHEME)
|
||||
for _, forward := range []bool{true, false} {
|
||||
fn.Backwards = !forward
|
||||
fn.Case_sensitive = false
|
||||
assertMatch(t, fn, "fooBarbaz1", "oBZ", 2, 9,
|
||||
scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3)
|
||||
assertMatch(t, fn, "foo bar baz", "fbb", 0, 9,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+
|
||||
int(fn.bonusBoundaryWhite)*2+2*scoreGapStart+4*scoreGapExtension)
|
||||
assertMatch(t, fn, "/AutomatorDocument.icns", "rdoc", 9, 13,
|
||||
scoreMatch*4+bonusCamel123+bonusConsecutive*2)
|
||||
assertMatch(t, fn, "/man1/zshcompctl.1", "zshc", 6, 10,
|
||||
scoreMatch*4+int(fn.bonusBoundaryDelimiter)*bonusFirstCharMultiplier+int(fn.bonusBoundaryDelimiter)*3)
|
||||
assertMatch(t, fn, "/.oh-my-zsh/cache", "zshc", 8, 13,
|
||||
scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*2+scoreGapStart+int(fn.bonusBoundaryDelimiter))
|
||||
assertMatch(t, fn, "ab0123 456", "12356", 3, 10,
|
||||
scoreMatch*5+bonusConsecutive*3+scoreGapStart+scoreGapExtension)
|
||||
assertMatch(t, fn, "abc123 456", "12356", 3, 10,
|
||||
scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+bonusConsecutive+scoreGapStart+scoreGapExtension)
|
||||
assertMatch(t, fn, "foo/bar/baz", "fbb", 0, 9,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+
|
||||
int(fn.bonusBoundaryDelimiter)*2+2*scoreGapStart+4*scoreGapExtension)
|
||||
assertMatch(t, fn, "fooBarBaz", "fbb", 0, 7,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+
|
||||
bonusCamel123*2+2*scoreGapStart+2*scoreGapExtension)
|
||||
assertMatch(t, fn, "foo barbaz", "fbb", 0, 8,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+int(fn.bonusBoundaryWhite)+
|
||||
scoreGapStart*2+scoreGapExtension*3)
|
||||
assertMatch(t, fn, "fooBar Baz", "foob", 0, 4,
|
||||
scoreMatch*4+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+int(fn.bonusBoundaryWhite)*3)
|
||||
assertMatch(t, fn, "xFoo-Bar Baz", "foo-b", 1, 6,
|
||||
scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+
|
||||
bonusNonWord+bonusBoundary)
|
||||
|
||||
fn.Case_sensitive = true
|
||||
assertMatch(t, fn, "fooBarbaz", "oBz", 2, 9,
|
||||
scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3)
|
||||
assertMatch(t, fn, "Foo/Bar/Baz", "FBB", 0, 9,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+int(fn.bonusBoundaryDelimiter)*2+
|
||||
scoreGapStart*2+scoreGapExtension*4)
|
||||
assertMatch(t, fn, "FooBarBaz", "FBB", 0, 7,
|
||||
scoreMatch*3+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+bonusCamel123*2+
|
||||
scoreGapStart*2+scoreGapExtension*2)
|
||||
assertMatch(t, fn, "FooBar Baz", "FooB", 0, 4,
|
||||
scoreMatch*4+int(fn.bonusBoundaryWhite)*bonusFirstCharMultiplier+int(fn.bonusBoundaryWhite)*2+
|
||||
max(bonusCamel123, int(fn.bonusBoundaryWhite)))
|
||||
|
||||
// Consecutive bonus updated
|
||||
assertMatch(t, fn, "foo-bar", "o-ba", 2, 6, scoreMatch*4+bonusBoundary*3)
|
||||
|
||||
// Non-match
|
||||
assertMatch(t, fn, "fooBarbaz", "oBZ", -1, -1, 0)
|
||||
assertMatch(t, fn, "Foo Bar Baz", "fbb", -1, -1, 0)
|
||||
assertMatch(t, fn, "fooBarbaz", "fooBarbazz", -1, -1, 0)
|
||||
}
|
||||
|
||||
var positions [][]int
|
||||
sort_by_score := false
|
||||
fn.Case_sensitive = false
|
||||
|
||||
simple := func(items, query string, expected ...string) {
|
||||
ilist := utils.Splitlines(items)
|
||||
matches, err := fn.Score(ilist, query)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sort_by_score {
|
||||
slist := make([]int, len(matches))
|
||||
for i := range len(slist) {
|
||||
slist[i] = i
|
||||
}
|
||||
utils.StableSort(slist, func(a, b int) int {
|
||||
return cmp.Compare(matches[b].Score, matches[a].Score)
|
||||
})
|
||||
nlist, nmatches := make([]string, len(ilist)), make([]Result, len(matches))
|
||||
for i, j := range slist {
|
||||
nlist[i] = ilist[j]
|
||||
nmatches[i] = matches[j]
|
||||
}
|
||||
ilist = nlist
|
||||
matches = nmatches
|
||||
}
|
||||
actual := make([]string, 0, len(matches))
|
||||
actual_positions := make([][]int, 0, len(matches))
|
||||
for i, m := range matches {
|
||||
if m.Score > 0 {
|
||||
sort.Ints(m.Positions)
|
||||
actual = append(actual, ilist[i])
|
||||
actual_positions = append(actual_positions, m.Positions)
|
||||
}
|
||||
}
|
||||
if expected == nil {
|
||||
expected = []string{}
|
||||
}
|
||||
|
||||
if diff := gcmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Failed for items: %#v\nQuery: %#v\nMatches: %#v\n%s", ilist, query, matches, diff)
|
||||
}
|
||||
if positions != nil {
|
||||
if diff := gcmp.Diff(positions, actual_positions); diff != "" {
|
||||
t.Fatalf("Failed positions for items: %v\n%s", ilist, diff)
|
||||
}
|
||||
positions = nil
|
||||
}
|
||||
}
|
||||
simple("test\nxyz", "te", "test")
|
||||
simple("abc\nxyz", "ba")
|
||||
simple("abc\n123", "abc", "abc")
|
||||
simple("test\nxyz", "Te", "test")
|
||||
simple("test\nxyz", "XY", "xyz")
|
||||
simple("test\nXYZ", "xy", "XYZ")
|
||||
simple("test\nXYZ", "mn")
|
||||
|
||||
positions = [][]int{{0, 2}, {0, 1}}
|
||||
simple("abc\nac", "ac", "abc", "ac")
|
||||
positions = [][]int{{0}}
|
||||
simple("abc\nv", "a", "abc")
|
||||
positions = [][]int{{1, 3}}
|
||||
simple("汉a字b\nxyz", "ab", "汉a字b")
|
||||
|
||||
sort_by_score = true
|
||||
// Match at start
|
||||
simple("archer\nelementary", "e", "elementary", "archer")
|
||||
// Match at level factor
|
||||
simple("xxxy\nxx/y", "y", "xx/y", "xxxy")
|
||||
// CamelCase
|
||||
simple("xxxy\nxxxY", "y", "xxxY", "xxxy")
|
||||
// Distance
|
||||
simple("abbc\nabc", "ac", "abc", "abbc")
|
||||
// Extreme chars
|
||||
simple("xxa\naxx", "a", "axx", "xxa")
|
||||
// Highest score
|
||||
positions = [][]int{{3}}
|
||||
simple("xa/a", "a", "xa/a")
|
||||
|
||||
sort_by_score = false
|
||||
items := make([]string, 256)
|
||||
|
||||
for i := range items {
|
||||
items[i] = strconv.Itoa(i)
|
||||
}
|
||||
expected := make([]string, 0, len(items))
|
||||
for _, x := range items {
|
||||
if strings.ContainsRune(x, rune('2')) {
|
||||
expected = append(expected, x)
|
||||
}
|
||||
}
|
||||
simple(strings.Join(items, "\n"), "2", expected...)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func NewFuzzyMatcher(scheme Scheme) (ans *FuzzyMatcher) {
|
||||
return new_fuzzy_matcher(scheme)
|
||||
}
|
||||
|
||||
// Score the specified items using runtime.NumCPU() go routines. This function
|
||||
// reports a panic in any worker go routine as a regular error.
|
||||
func (m *FuzzyMatcher) Score(items []string, pattern string) (ans []Result, err error) {
|
||||
return m.score(items, pattern, func(item string, pat []rune, pattern_is_ascii bool, slab *slab, as_chars func(string) Chars) Result {
|
||||
c := as_chars(item)
|
||||
return m.score_one(&c, pat, pattern_is_ascii, slab)
|
||||
})
|
||||
}
|
||||
|
||||
// Clear the cache used ScoreWithCache(). Useful if you change some of the
|
||||
// settings used for scoring.
|
||||
func (m *FuzzyMatcher) ClearScoreCache() {
|
||||
m.cache_mutex.Lock()
|
||||
m.cache = make(map[string]Result)
|
||||
m.cache_mutex.Unlock()
|
||||
}
|
||||
|
||||
// Same as Score, except that it uses a cache. Remember to call
|
||||
// ClearScoreCache() if you change any scoring settings on this FuzzyMatcher.
|
||||
func (m *FuzzyMatcher) ScoreWithCache(items []string, pattern string) (ans []Result, err error) {
|
||||
key_prefix := pattern + "\x00"
|
||||
return m.score(items, pattern, func(item string, pat []rune, pattern_is_ascii bool, slab *slab, as_chars func(string) Chars) Result {
|
||||
key := key_prefix + item
|
||||
m.cache_mutex.Lock()
|
||||
res, found := m.cache[key]
|
||||
m.cache_mutex.Unlock()
|
||||
if !found {
|
||||
c := as_chars(item)
|
||||
res = m.score_one(&c, pat, pattern_is_ascii, slab)
|
||||
m.cache_mutex.Lock()
|
||||
m.cache[key] = res
|
||||
m.cache_mutex.Unlock()
|
||||
}
|
||||
return res
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"unsafe"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Chars struct {
|
||||
bytes []byte
|
||||
runes []rune
|
||||
}
|
||||
|
||||
func check_ascii(bytes []byte) (ascii_until int) {
|
||||
slen := len(bytes)
|
||||
// Process 8 bytes at a time
|
||||
i := 0
|
||||
for ; i+8 <= slen; i += 8 {
|
||||
v := *(*uint64)(unsafe.Pointer(&bytes[i]))
|
||||
// If any byte has its high bit set, v & 0x8080808080808080 != 0
|
||||
if v&0x8080808080808080 != 0 {
|
||||
// At least one non-ASCII byte in this chunk, find which
|
||||
for j := range 8 {
|
||||
if bytes[i+j]&utf8.RuneSelf != 0 {
|
||||
return i + j
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Handle remaining bytes
|
||||
for ; i < slen; i++ {
|
||||
if bytes[i]&utf8.RuneSelf != 0 {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func CharsFromString(text string) (ans Chars) {
|
||||
ans.bytes = utils.UnsafeStringToBytes(text)
|
||||
ascii_until := check_ascii(ans.bytes)
|
||||
if ascii_until > -1 {
|
||||
runes := []rune(norm.NFC.String(text[ascii_until:]))
|
||||
ans.runes = make([]rune, ascii_until+len(runes))
|
||||
for i := range ascii_until {
|
||||
ans.runes[i] = rune(ans.bytes[i])
|
||||
}
|
||||
copy(ans.runes[ascii_until:], runes)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CharsFromStringWithoutAccents(text string) (ans Chars) {
|
||||
ans.bytes = utils.UnsafeStringToBytes(text)
|
||||
ascii_until := check_ascii(ans.bytes)
|
||||
if ascii_until > -1 {
|
||||
runes := []rune(norm.NFD.String(text[ascii_until:]))
|
||||
ans.runes = make([]rune, ascii_until, ascii_until+len(runes))
|
||||
for i := range ascii_until {
|
||||
ans.runes[i] = rune(ans.bytes[i])
|
||||
}
|
||||
for _, r := range runes {
|
||||
if !unicode.Is(unicode.Mn, r) {
|
||||
ans.runes = append(ans.runes, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Chars) Bytes() []byte { return c.bytes }
|
||||
func (c *Chars) Is_ASCII() bool { return c.runes == nil }
|
||||
func (c *Chars) Get(i int) rune {
|
||||
if c.runes != nil {
|
||||
return c.runes[i]
|
||||
}
|
||||
return rune(c.bytes[i])
|
||||
}
|
||||
func (c *Chars) Length() int {
|
||||
if c.runes != nil {
|
||||
return len(c.runes)
|
||||
}
|
||||
return len(c.bytes)
|
||||
}
|
||||
|
||||
func (c *Chars) CopyRunes(dest []rune, from int) {
|
||||
if c.runes != nil {
|
||||
copy(dest, c.runes[from:])
|
||||
return
|
||||
}
|
||||
for idx, b := range c.bytes[from:][:len(dest)] {
|
||||
dest[idx] = rune(b)
|
||||
}
|
||||
}
|
||||
|
||||
type charClass int
|
||||
|
||||
const (
|
||||
charWhite charClass = iota
|
||||
charNonWord
|
||||
charDelimiter
|
||||
charLower
|
||||
charUpper
|
||||
charLetter
|
||||
charNumber
|
||||
)
|
||||
|
||||
const (
|
||||
scoreMatch = 16
|
||||
scoreGapStart = -3
|
||||
scoreGapExtension = -1
|
||||
|
||||
// We prefer matches at the beginning of a word, but the bonus should not be
|
||||
// too great to prevent the longer acronym matches from always winning over
|
||||
// shorter fuzzy matches. The bonus point here was specifically chosen that
|
||||
// the bonus is cancelled when the gap between the acronyms grows over
|
||||
// 8 characters, which is approximately the average length of the words found
|
||||
// in web2 dictionary and my file system.
|
||||
bonusBoundary = scoreMatch / 2
|
||||
|
||||
// Although bonus point for non-word characters is non-contextual, we need it
|
||||
// for computing bonus points for consecutive chunks starting with a non-word
|
||||
// character.
|
||||
bonusNonWord = scoreMatch / 2
|
||||
|
||||
// Edge-triggered bonus for matches in camelCase words.
|
||||
// Compared to word-boundary case, they don't accompany single-character gaps
|
||||
// (e.g. FooBar vs. foo-bar), so we deduct bonus point accordingly.
|
||||
bonusCamel123 = bonusBoundary + scoreGapExtension
|
||||
|
||||
// Minimum bonus point given to characters in consecutive chunks.
|
||||
// Note that bonus points for consecutive matches shouldn't have needed if we
|
||||
// used fixed match score as in the original algorithm.
|
||||
bonusConsecutive = -(scoreGapStart + scoreGapExtension)
|
||||
|
||||
// The first character in the typed pattern usually has more significance
|
||||
// than the rest so it's important that it appears at special positions where
|
||||
// bonus points are given, e.g. "to-go" vs. "ongoing" on "og" or on "ogo".
|
||||
// The amount of the extra bonus should be limited so that the gap penalty is
|
||||
// still respected.
|
||||
bonusFirstCharMultiplier = 2
|
||||
)
|
||||
|
||||
const whiteChars = " \t\n\v\f\r\x85\xA0"
|
||||
|
||||
type Result struct {
|
||||
Score uint // A value of zero means did not match
|
||||
Positions []int
|
||||
}
|
||||
|
||||
type FuzzyMatcher struct {
|
||||
Case_sensitive, Ignore_accents, Backwards, Without_positions bool
|
||||
|
||||
// Extra bonus for word boundary after whitespace character or beginning of the string
|
||||
bonusBoundaryWhite int16
|
||||
|
||||
// Extra bonus for word boundary after slash, colon, semi-colon, and comma
|
||||
bonusBoundaryDelimiter int16
|
||||
|
||||
initialCharClass charClass
|
||||
|
||||
// A minor optimization that can give 15%+ performance boost
|
||||
asciiCharClasses [unicode.MaxASCII + 1]charClass
|
||||
|
||||
// A minor optimization that can give yet another 5% performance boost
|
||||
bonusMatrix [charNumber + 1][charNumber + 1]int16
|
||||
|
||||
delimiterChars string
|
||||
|
||||
cache map[string]Result
|
||||
cache_mutex sync.Mutex
|
||||
}
|
||||
|
||||
func (m *FuzzyMatcher) bonusFor(prevClass charClass, class charClass) int16 {
|
||||
if class > charNonWord {
|
||||
switch prevClass {
|
||||
case charWhite:
|
||||
// Word boundary after whitespace
|
||||
return m.bonusBoundaryWhite
|
||||
case charDelimiter:
|
||||
// Word boundary after a delimiter character
|
||||
return m.bonusBoundaryDelimiter
|
||||
case charNonWord:
|
||||
// Word boundary
|
||||
return bonusBoundary
|
||||
}
|
||||
}
|
||||
|
||||
if prevClass == charLower && class == charUpper ||
|
||||
prevClass != charNumber && class == charNumber {
|
||||
// camelCase letter123
|
||||
return bonusCamel123
|
||||
}
|
||||
|
||||
switch class {
|
||||
case charNonWord, charDelimiter:
|
||||
return bonusNonWord
|
||||
case charWhite:
|
||||
return m.bonusBoundaryWhite
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type Scheme string
|
||||
|
||||
const (
|
||||
DEFAULT_SCHEME Scheme = "default"
|
||||
PATH_SCHEME Scheme = "path"
|
||||
HISTORY_SCHEME Scheme = "history"
|
||||
)
|
||||
|
||||
func new_fuzzy_matcher(scheme Scheme) (ans *FuzzyMatcher) {
|
||||
ans = &FuzzyMatcher{
|
||||
bonusBoundaryWhite: bonusBoundary + 2,
|
||||
bonusBoundaryDelimiter: bonusBoundary + 1,
|
||||
delimiterChars: "/,:;|",
|
||||
cache: make(map[string]Result),
|
||||
}
|
||||
switch scheme {
|
||||
case PATH_SCHEME:
|
||||
ans.bonusBoundaryWhite = bonusBoundary
|
||||
ans.initialCharClass = charDelimiter
|
||||
if os.PathSeparator == '/' {
|
||||
ans.delimiterChars = "/"
|
||||
} else {
|
||||
ans.delimiterChars = "/" + string(os.PathSeparator)
|
||||
}
|
||||
case HISTORY_SCHEME:
|
||||
ans.bonusBoundaryWhite = bonusBoundary
|
||||
ans.bonusBoundaryDelimiter = bonusBoundary
|
||||
}
|
||||
for i := 0; i <= unicode.MaxASCII; i++ {
|
||||
char := rune(i)
|
||||
c := charNonWord
|
||||
if char >= 'a' && char <= 'z' {
|
||||
c = charLower
|
||||
} else if char >= 'A' && char <= 'Z' {
|
||||
c = charUpper
|
||||
} else if char >= '0' && char <= '9' {
|
||||
c = charNumber
|
||||
} else if strings.ContainsRune(whiteChars, char) {
|
||||
c = charWhite
|
||||
} else if strings.ContainsRune(ans.delimiterChars, char) {
|
||||
c = charDelimiter
|
||||
}
|
||||
ans.asciiCharClasses[i] = c
|
||||
}
|
||||
for i := 0; i <= int(charNumber); i++ {
|
||||
for j := 0; j <= int(charNumber); j++ {
|
||||
ans.bonusMatrix[i][j] = ans.bonusFor(charClass(i), charClass(j))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type slab struct {
|
||||
i16 []int16
|
||||
i32 []int32
|
||||
i16_used, i32_used int
|
||||
}
|
||||
|
||||
const slab_initial_size = 8192
|
||||
|
||||
func (s *slab) reset() {
|
||||
if s.i16 == nil {
|
||||
s.i16 = make([]int16, slab_initial_size)
|
||||
}
|
||||
if s.i32 == nil {
|
||||
s.i32 = make([]int32, slab_initial_size)
|
||||
}
|
||||
s.i16_used, s.i32_used = 0, 0
|
||||
}
|
||||
|
||||
func (s *slab) alloc16(sz int) []int16 {
|
||||
if sz+s.i16_used < len(s.i16) {
|
||||
s.i16 = make([]int16, max(slab_initial_size, 2*(s.i16_used+sz)))
|
||||
s.i16_used = 0
|
||||
}
|
||||
pos := s.i16_used
|
||||
s.i16_used += sz
|
||||
return s.i16[pos:s.i16_used]
|
||||
}
|
||||
|
||||
func (s *slab) alloc32(sz int) []int32 {
|
||||
if sz+s.i32_used < len(s.i32) {
|
||||
s.i32 = make([]int32, max(slab_initial_size, 2*(s.i32_used+sz)))
|
||||
s.i32_used = 0
|
||||
}
|
||||
pos := s.i32_used
|
||||
s.i32_used += sz
|
||||
return s.i32[pos:s.i32_used]
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package highlight
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/alecthomas/chroma/v2"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var ErrNoLexer = errors.New("No lexer available for this format")
|
||||
|
||||
type StyleResolveData interface {
|
||||
StyleName() string
|
||||
UseLightColors() bool
|
||||
SyntaxAliases() map[string]string
|
||||
TextForPath(string) (string, error)
|
||||
}
|
||||
|
||||
type Highlighter interface {
|
||||
HighlightFile(path string, srd StyleResolveData) (highlighted_string string, err error)
|
||||
Sanitize(string) string
|
||||
}
|
||||
|
||||
func NewHighlighter(sanitize func(string) string) Highlighter {
|
||||
if sanitize == nil {
|
||||
sanitize = func(text string) string { return utils.ReplaceControlCodes(text, " ", "\n") }
|
||||
}
|
||||
return &highlighter{sanitize: sanitize, tokens_map: make(map[string][]chroma.Token)}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package highlight
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/alecthomas/chroma/v2"
|
||||
"github.com/alecthomas/chroma/v2/lexers"
|
||||
"github.com/alecthomas/chroma/v2/styles"
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var default_style = sync.OnceValue(func() *chroma.Style {
|
||||
// Default style generated by python style.py default pygments.styles.default.DefaultStyle
|
||||
// with https://raw.githubusercontent.com/alecthomas/chroma/master/_tools/style.py
|
||||
return styles.Register(chroma.MustNewStyle("default", chroma.StyleEntries{
|
||||
chroma.TextWhitespace: "#bbbbbb",
|
||||
chroma.Comment: "italic #3D7B7B",
|
||||
chroma.CommentPreproc: "noitalic #9C6500",
|
||||
chroma.Keyword: "bold #008000",
|
||||
chroma.KeywordPseudo: "nobold",
|
||||
chroma.KeywordType: "nobold #B00040",
|
||||
chroma.Operator: "#666666",
|
||||
chroma.OperatorWord: "bold #AA22FF",
|
||||
chroma.NameBuiltin: "#008000",
|
||||
chroma.NameFunction: "#0000FF",
|
||||
chroma.NameClass: "bold #0000FF",
|
||||
chroma.NameNamespace: "bold #0000FF",
|
||||
chroma.NameException: "bold #CB3F38",
|
||||
chroma.NameVariable: "#19177C",
|
||||
chroma.NameConstant: "#880000",
|
||||
chroma.NameLabel: "#767600",
|
||||
chroma.NameEntity: "bold #717171",
|
||||
chroma.NameAttribute: "#687822",
|
||||
chroma.NameTag: "bold #008000",
|
||||
chroma.NameDecorator: "#AA22FF",
|
||||
chroma.LiteralString: "#BA2121",
|
||||
chroma.LiteralStringDoc: "italic",
|
||||
chroma.LiteralStringInterpol: "bold #A45A77",
|
||||
chroma.LiteralStringEscape: "bold #AA5D1F",
|
||||
chroma.LiteralStringRegex: "#A45A77",
|
||||
chroma.LiteralStringSymbol: "#19177C",
|
||||
chroma.LiteralStringOther: "#008000",
|
||||
chroma.LiteralNumber: "#666666",
|
||||
chroma.GenericHeading: "bold #000080",
|
||||
chroma.GenericSubheading: "bold #800080",
|
||||
chroma.GenericDeleted: "#A00000",
|
||||
chroma.GenericInserted: "#008400",
|
||||
chroma.GenericError: "#E40000",
|
||||
chroma.GenericEmph: "italic",
|
||||
chroma.GenericStrong: "bold",
|
||||
chroma.GenericPrompt: "bold #000080",
|
||||
chroma.GenericOutput: "#717171",
|
||||
chroma.GenericTraceback: "#04D",
|
||||
chroma.Error: "border:#FF0000",
|
||||
chroma.Background: " bg:#f8f8f8",
|
||||
}))
|
||||
})
|
||||
|
||||
// Clear the background colour.
|
||||
func clear_background(style *chroma.Style) *chroma.Style {
|
||||
builder := style.Builder()
|
||||
bg := builder.Get(chroma.Background)
|
||||
bg.Background = 0
|
||||
bg.NoInherit = true
|
||||
builder.AddEntry(chroma.Background, bg)
|
||||
style, _ = builder.Build()
|
||||
return style
|
||||
}
|
||||
|
||||
func ansi_formatter(w io.Writer, style *chroma.Style, sanitize func(string) string, it chroma.Iterator) (err error) {
|
||||
const SGR_PREFIX = "\033["
|
||||
const SGR_SUFFIX = "m"
|
||||
style = clear_background(style)
|
||||
before, after := make([]byte, 0, 64), make([]byte, 0, 64)
|
||||
nl := []byte{'\n'}
|
||||
write_sgr := func(which []byte) (err error) {
|
||||
if len(which) > 1 {
|
||||
if _, err = w.Write(utils.UnsafeStringToBytes(SGR_PREFIX)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = w.Write(which[:len(which)-1]); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = w.Write(utils.UnsafeStringToBytes(SGR_SUFFIX)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
write := func(text string) (err error) {
|
||||
if err = write_sgr(before); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = w.Write(utils.UnsafeStringToBytes(text)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = write_sgr(after); err != nil {
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for token := it(); token != chroma.EOF; token = it() {
|
||||
entry := style.Get(token.Type)
|
||||
before, after = before[:0], after[:0]
|
||||
if !entry.IsZero() {
|
||||
if entry.Bold == chroma.Yes {
|
||||
before = append(before, '1', ';')
|
||||
after = append(after, '2', '2', '1', ';')
|
||||
}
|
||||
if entry.Underline == chroma.Yes {
|
||||
before = append(before, '4', ';')
|
||||
after = append(after, '2', '4', ';')
|
||||
}
|
||||
if entry.Italic == chroma.Yes {
|
||||
before = append(before, '3', ';')
|
||||
after = append(after, '2', '3', ';')
|
||||
}
|
||||
if entry.Colour.IsSet() {
|
||||
before = append(before, fmt.Sprintf("38:2:%d:%d:%d;", entry.Colour.Red(), entry.Colour.Green(), entry.Colour.Blue())...)
|
||||
after = append(after, '3', '9', ';')
|
||||
}
|
||||
}
|
||||
// independently format each line in a multiline token, needed for the diff kitten highlighting to work, also
|
||||
// pagers like less reset SGR formatting at line boundaries
|
||||
text := sanitize(token.Value)
|
||||
for text != "" {
|
||||
idx := strings.IndexByte(text, '\n')
|
||||
if idx < 0 {
|
||||
if err = write(text); err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
}
|
||||
if err = write(text[:idx]); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = w.Write(nl); err != nil {
|
||||
return err
|
||||
}
|
||||
text = text[idx+1:]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func resolved_chroma_style(srd StyleResolveData) *chroma.Style {
|
||||
name := srd.StyleName()
|
||||
var style *chroma.Style
|
||||
if name == "default" {
|
||||
style = default_style()
|
||||
} else {
|
||||
style = styles.Get(name)
|
||||
}
|
||||
if style == nil {
|
||||
if srd.UseLightColors() {
|
||||
style = default_style()
|
||||
} else {
|
||||
style = styles.Get("monokai")
|
||||
if style == nil {
|
||||
style = styles.Get("github-dark")
|
||||
}
|
||||
}
|
||||
if style == nil {
|
||||
style = styles.Fallback
|
||||
}
|
||||
}
|
||||
return style
|
||||
}
|
||||
|
||||
type highlighter struct {
|
||||
tokens_map map[string][]chroma.Token
|
||||
lock sync.Mutex
|
||||
sanitize func(string) string
|
||||
}
|
||||
|
||||
func (h *highlighter) Sanitize(x string) string { return h.sanitize(x) }
|
||||
|
||||
func (h *highlighter) HighlightFile(path string, srd StyleResolveData) (highlighted_string string, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = parallel.Format_stacktrace_on_panic(r, 1)
|
||||
}
|
||||
}()
|
||||
filename_for_detection := filepath.Base(path)
|
||||
ext := filepath.Ext(filename_for_detection)
|
||||
if ext != "" {
|
||||
ext = strings.ToLower(ext[1:])
|
||||
r := srd.SyntaxAliases()[ext]
|
||||
if r != "" {
|
||||
filename_for_detection = "file." + r
|
||||
}
|
||||
}
|
||||
text, err := srd.TextForPath(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
h.lock.Lock()
|
||||
tokens := h.tokens_map[path]
|
||||
h.lock.Unlock()
|
||||
if tokens == nil {
|
||||
lexer := lexers.Match(filename_for_detection)
|
||||
if lexer == nil {
|
||||
lexer = lexers.Analyse(text)
|
||||
}
|
||||
if lexer == nil {
|
||||
return "", fmt.Errorf("Cannot highlight %#v: %w", path, ErrNoLexer)
|
||||
}
|
||||
lexer = chroma.Coalesce(lexer)
|
||||
iterator, err := lexer.Tokenise(nil, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tokens = iterator.Tokens()
|
||||
h.lock.Lock()
|
||||
h.tokens_map[path] = tokens
|
||||
h.lock.Unlock()
|
||||
}
|
||||
w := strings.Builder{}
|
||||
w.Grow(len(text) * 2)
|
||||
err = ansi_formatter(&w, resolved_chroma_style(srd), h.sanitize, chroma.Literator(tokens...))
|
||||
return w.String(), err
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
||||
package ignorefiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type IgnoreFile interface {
|
||||
Len() int // number of rules
|
||||
LoadString(string) error
|
||||
LoadBytes([]byte) error
|
||||
LoadLines(...string) error
|
||||
LoadFile(io.Reader) error
|
||||
LoadPath(string) error
|
||||
|
||||
// relpath is the path relative to the directory containing the ignorefile.
|
||||
// When the result is due to a rule matching, linenum_of_matching_rule is
|
||||
// >=0 and pattern is the textual representation of the rule. Otherwise
|
||||
// linenum_of_matching_rule is -1 and pattern is the empty string.
|
||||
IsIgnored(relpath string, ftype fs.FileMode) (is_ignored bool, linenum_of_matching_rule int, pattern string)
|
||||
}
|
||||
|
||||
func NewGitignore() IgnoreFile { return &Gitignore{index_of_last_negated_rule: -1} }
|
||||
|
||||
// The global gitignore from ~/.config/git/ignore
|
||||
var GlobalGitignore = sync.OnceValue(func() IgnoreFile {
|
||||
return get_global_gitignore()
|
||||
})
|
||||
@@ -0,0 +1,313 @@
|
||||
package ignorefiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type GitPattern struct {
|
||||
line_number int
|
||||
only_dirs bool
|
||||
negated bool
|
||||
pattern string
|
||||
parts []string
|
||||
matcher func(path string) bool
|
||||
}
|
||||
|
||||
type Gitignore struct {
|
||||
patterns []GitPattern
|
||||
index_of_last_negated_rule int
|
||||
line_number_offset int
|
||||
}
|
||||
|
||||
func (g Gitignore) Len() int { return len(g.patterns) }
|
||||
|
||||
func (g Gitignore) IsIgnored(relpath string, ftype os.FileMode) (is_ignored bool, linenum_of_matching_rule int, pattern string) {
|
||||
if os.PathSeparator != '/' {
|
||||
relpath = strings.ReplaceAll(relpath, string(os.PathSeparator), "/")
|
||||
}
|
||||
linenum_of_matching_rule = -1
|
||||
for i, pat := range g.patterns {
|
||||
if is_ignored {
|
||||
if i > g.index_of_last_negated_rule {
|
||||
break
|
||||
}
|
||||
if pat.negated && pat.Match(relpath, ftype) {
|
||||
is_ignored = false
|
||||
linenum_of_matching_rule = pat.line_number
|
||||
pattern = pat.pattern
|
||||
}
|
||||
} else {
|
||||
if !pat.negated && pat.Match(relpath, ftype) {
|
||||
is_ignored = true
|
||||
linenum_of_matching_rule = pat.line_number
|
||||
pattern = pat.pattern
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (g *Gitignore) load_line(line string, line_number int) {
|
||||
if p, skipped_line := CompileGitIgnoreLine(line); !skipped_line {
|
||||
p.line_number = g.line_number_offset + line_number
|
||||
g.patterns = append(g.patterns, p)
|
||||
if p.negated {
|
||||
g.index_of_last_negated_rule = len(g.patterns) - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gitignore) LoadLines(lines ...string) error {
|
||||
for i, line := range lines {
|
||||
g.load_line(line, i)
|
||||
}
|
||||
g.line_number_offset += len(lines)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Gitignore) LoadString(text string) error {
|
||||
s := utils.NewLineScanner(text)
|
||||
lnum := 0
|
||||
for s.Scan() {
|
||||
g.load_line(s.Text(), lnum)
|
||||
lnum++
|
||||
}
|
||||
g.line_number_offset += lnum
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Gitignore) LoadBytes(text []byte) error {
|
||||
return g.LoadString(string(text))
|
||||
}
|
||||
|
||||
func (g *Gitignore) LoadPath(path string) error {
|
||||
if data, err := os.ReadFile(path); err == nil {
|
||||
return g.LoadString(utils.UnsafeBytesToString(data))
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gitignore) LoadFile(f io.Reader) error {
|
||||
if data, err := io.ReadAll(f); err == nil {
|
||||
return g.LoadString(utils.UnsafeBytesToString(data))
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (p GitPattern) Match(path string, ftype fs.FileMode) bool {
|
||||
if p.only_dirs && ftype&fs.ModeDir == 0 {
|
||||
return false
|
||||
}
|
||||
return p.matcher(path)
|
||||
}
|
||||
|
||||
func anchored_single_match(path string, pattern string) bool {
|
||||
name, _, _ := strings.Cut(path, "/")
|
||||
matches, err := filepath.Match(pattern, name)
|
||||
return err == nil && matches
|
||||
}
|
||||
|
||||
func unanchored_single_match(path string, pattern string) bool {
|
||||
for path != "" {
|
||||
var name string
|
||||
name, path, _ = strings.Cut(path, "/")
|
||||
matches, err := filepath.Match(pattern, name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if matches {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func anchored_simple_match(path string, parts []string) bool {
|
||||
for ; path != "" && len(parts) > 0; parts = parts[1:] {
|
||||
var name string
|
||||
name, path, _ = strings.Cut(path, "/")
|
||||
if matches, err := filepath.Match(parts[0], name); err != nil || !matches {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return path == "" && len(parts) == 0
|
||||
}
|
||||
|
||||
func anchored_full_match(path string, parts []string) bool {
|
||||
pos, last := 0, len(parts)-1
|
||||
for pos <= last && path != "" {
|
||||
var name string
|
||||
name, path, _ = strings.Cut(path, "/")
|
||||
switch parts[pos] {
|
||||
case "**":
|
||||
for pos+1 < len(parts) && parts[pos+1] == "**" {
|
||||
pos++
|
||||
}
|
||||
if pos == last {
|
||||
return true
|
||||
}
|
||||
pos++
|
||||
for {
|
||||
matches, err := filepath.Match(parts[pos], name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if matches {
|
||||
return anchored_full_match(path, parts[pos+1:])
|
||||
}
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
name, path, _ = strings.Cut(path, "/")
|
||||
}
|
||||
default:
|
||||
if matches, err := filepath.Match(parts[pos], name); err != nil || !matches {
|
||||
return false
|
||||
}
|
||||
pos++
|
||||
}
|
||||
}
|
||||
return path == "" && pos > last
|
||||
}
|
||||
|
||||
// Parse a line from a .gitignore file, see man gitignore for the syntax
|
||||
func CompileGitIgnoreLine(line string) (ans GitPattern, skipped_line bool) {
|
||||
// Strip comments
|
||||
if strings.HasPrefix(line, `#`) {
|
||||
skipped_line = true
|
||||
return
|
||||
}
|
||||
|
||||
// Trim OS-specific carriage returns.
|
||||
line = strings.TrimRight(line, "\r")
|
||||
|
||||
// Trim trailing spaces unless backslash escaped
|
||||
for strings.HasSuffix(line, " ") {
|
||||
if strings.HasSuffix(line, `\ `) {
|
||||
line = line[:len(line)-2] + " "
|
||||
break
|
||||
}
|
||||
line = line[:len(line)-1]
|
||||
}
|
||||
|
||||
// Empty lines are ignored
|
||||
if line == "" {
|
||||
skipped_line = true
|
||||
return
|
||||
}
|
||||
ans.pattern = line
|
||||
|
||||
// Handle negated (accept) patterns
|
||||
if line[0] == '!' {
|
||||
line = line[1:]
|
||||
ans.negated = true
|
||||
}
|
||||
|
||||
// Handle leading slash used to escape leading # or !
|
||||
if strings.HasPrefix(line, `\#`) || strings.HasPrefix(line, `\!`) {
|
||||
line = line[1:]
|
||||
}
|
||||
if strings.HasSuffix(line, "/") {
|
||||
ans.only_dirs = true
|
||||
line = strings.TrimRight(line, "/")
|
||||
if line == "" {
|
||||
skipped_line = true
|
||||
return
|
||||
}
|
||||
}
|
||||
starts_with_slash := strings.HasPrefix(line, "/")
|
||||
if starts_with_slash {
|
||||
line = strings.TrimLeft(line, "/")
|
||||
}
|
||||
ans.parts = strings.Split(line, "/")
|
||||
if slices.Contains(ans.parts, "") {
|
||||
ans.parts = slices.DeleteFunc(ans.parts, func(x string) bool { return x == "" })
|
||||
}
|
||||
if len(ans.parts) == 0 {
|
||||
skipped_line = true
|
||||
return
|
||||
}
|
||||
if len(ans.parts) == 1 {
|
||||
pattern := ans.parts[0]
|
||||
if pattern == "**" {
|
||||
ans.matcher = func(string) bool { return true }
|
||||
} else {
|
||||
if starts_with_slash {
|
||||
ans.matcher = func(path string) bool { return anchored_single_match(path, pattern) }
|
||||
} else {
|
||||
ans.matcher = func(path string) bool { return unanchored_single_match(path, pattern) }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if slices.Contains(ans.parts, "**") {
|
||||
ans.matcher = func(path string) bool { return anchored_full_match(path, ans.parts) }
|
||||
} else {
|
||||
ans.matcher = func(path string) bool { return anchored_simple_match(path, ans.parts) }
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func get_global_gitconfig_excludesfile() (ans string) {
|
||||
return _get_global_gitconfig_excludesfile(utils.Expanduser("~/.gitconfig"))
|
||||
}
|
||||
|
||||
func _get_global_gitconfig_excludesfile(home_gitconfig string) (ans string) {
|
||||
cfhome := os.Getenv("XDG_CONFIG_HOME")
|
||||
if cfhome == "" {
|
||||
cfhome = utils.Expanduser("~/.config")
|
||||
}
|
||||
for _, candidate := range []string{"/etc/gitconfig", filepath.Join(cfhome, "git", "config"), home_gitconfig} {
|
||||
if data, err := os.ReadFile(candidate); err == nil {
|
||||
s := utils.NewLineScanner(utils.UnsafeBytesToString(data))
|
||||
in_core := false
|
||||
for s.Scan() {
|
||||
line := strings.TrimSpace(s.Text())
|
||||
if in_core {
|
||||
if strings.HasPrefix(line, "[") {
|
||||
in_core = line == "[core]"
|
||||
continue
|
||||
}
|
||||
if k, rest, found := strings.Cut(line, "="); found && strings.ToLower(strings.TrimSpace(k)) == `excludesfile` {
|
||||
ans = strings.TrimSpace(rest)
|
||||
ans = utils.Expanduser(ans)
|
||||
if !filepath.IsAbs(ans) {
|
||||
if a, err := filepath.Abs(ans); err != nil {
|
||||
ans = a
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if strings.ToLower(line) == "[core]" {
|
||||
in_core = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ans == "" {
|
||||
ans = filepath.Join(cfhome, "git", "ignore")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func get_global_gitignore() (ans IgnoreFile) {
|
||||
excludesfile := get_global_gitconfig_excludesfile()
|
||||
if data, err := os.ReadFile(excludesfile); err == nil {
|
||||
q := NewGitignore()
|
||||
if q.LoadString(utils.UnsafeBytesToString(data)) == nil {
|
||||
ans = q
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package ignorefiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestGitignore(t *testing.T) {
|
||||
for line, expected := range map[string]struct {
|
||||
skipped, negated, only_dirs bool
|
||||
parts []string
|
||||
}{
|
||||
"": {skipped: true},
|
||||
" ": {skipped: true},
|
||||
" ": {skipped: true},
|
||||
"/": {skipped: true},
|
||||
"//": {skipped: true},
|
||||
"# abc": {skipped: true},
|
||||
"!": {skipped: true},
|
||||
"! ": {skipped: true},
|
||||
`\!moose \ `: {parts: []string{`!moose `}},
|
||||
`\#m\oose `: {parts: []string{`#m\oose`}},
|
||||
} {
|
||||
p, skipped := CompileGitIgnoreLine(line)
|
||||
if skipped != expected.skipped {
|
||||
t.Fatalf("skipped: %v != %v for line: %s", expected.skipped, skipped, line)
|
||||
}
|
||||
if !skipped {
|
||||
if p.negated != expected.negated {
|
||||
t.Fatalf("negated: %v != %v for line: %s", expected.negated, p.negated, line)
|
||||
}
|
||||
if p.only_dirs != expected.only_dirs {
|
||||
t.Fatalf("only_dirs: %v != %v for line: %s", expected.only_dirs, p.only_dirs, line)
|
||||
}
|
||||
if diff := cmp.Diff(expected.parts, p.parts); diff != "" {
|
||||
t.Fatalf("parts not equal for line: %s\n%s", line, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
type ptest struct {
|
||||
path string
|
||||
expected bool
|
||||
}
|
||||
for _, x := range []struct {
|
||||
line string
|
||||
tests []ptest
|
||||
}{
|
||||
{"foo", []ptest{
|
||||
{"foo", true}, {"x/foo", true}, {"foo/x", true},
|
||||
}},
|
||||
{"/foo", []ptest{
|
||||
{"foo", true}, {"x/foo", false},
|
||||
}},
|
||||
{"doc/frotz/", []ptest{
|
||||
{"doc/frotz/", true}, {"a/doc/frotz/", false}, {"doc/frotz", false},
|
||||
}},
|
||||
{"frotz/", []ptest{
|
||||
{"frotz/", true}, {"a/doc/frotz/", true}, {"doc/frotz", false}, {"frotz/", true},
|
||||
}},
|
||||
{"foo.*", []ptest{
|
||||
{"foo.txt", true}, {"foo", false}, {"a/foo.x", true}, {"foo.", true},
|
||||
}},
|
||||
|
||||
{"**", []ptest{
|
||||
{"foo", true}, {"x/foo", true}, {"foo/x", true},
|
||||
}},
|
||||
|
||||
{"**/foo", []ptest{
|
||||
{"foo", true}, {"x/foo", true}, {"foo/x", false},
|
||||
}},
|
||||
{"**/foo/bar", []ptest{
|
||||
{"foo", false}, {"x/foo", false}, {"foo/bar", true}, {"a/foo/bar", true}, {"foo/bar/a", false},
|
||||
}},
|
||||
{"foo/**", []ptest{
|
||||
{"foo", false}, {"x/foo", false}, {"foo/bar", true}, {"foo/bar/a", true}, {"foo/bar/a/", true},
|
||||
}},
|
||||
{"a/**/b", []ptest{
|
||||
{"a/b", true}, {"a/x/b", true}, {"a/x/y/b", true}, {"x/a/b", false}, {"a/b/x", false},
|
||||
}},
|
||||
{"a/**/b/**/c", []ptest{
|
||||
{"a/b/c", true}, {"a/x/b/c", true}, {"a/x/y/b/m/n/c", true},
|
||||
}},
|
||||
} {
|
||||
p, skipped := CompileGitIgnoreLine(x.line)
|
||||
if skipped {
|
||||
t.Fatalf("Unexpectedly failed to compile: %#v", x.line)
|
||||
}
|
||||
for _, test := range x.tests {
|
||||
path := strings.TrimRight(test.path, "/")
|
||||
ftype := utils.IfElse(len(path) < len(test.path), fs.ModeDir, 0)
|
||||
if actual := p.Match(path, ftype); actual != test.expected {
|
||||
t.Fatalf("matched: %v != %v for pattern: %#v and path: %#v", test.expected, actual, x.line, test.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
for text, tests := range map[string]map[string]bool{
|
||||
``: {"foo": false},
|
||||
`
|
||||
# exclude everything except directory foo/bar
|
||||
/*
|
||||
!/foo
|
||||
/foo/*
|
||||
!/foo/bar`: {
|
||||
"a": true, "foo": false, "foo/x": true, "foo/bar": false, "foo/bar/": false,
|
||||
},
|
||||
`
|
||||
**/foo
|
||||
bar `: {
|
||||
"foo": true, "baz/foo": true, "bar": true, "baz/bar": true, "a": false,
|
||||
},
|
||||
`/*.c`: {"a.c": true, "b/a.c": false},
|
||||
`
|
||||
**/external/**/*.json
|
||||
**/external/**/.*ignore
|
||||
**/external/foobar/*.css`: {
|
||||
"external/foobar/angular.foo.css": true, "external/barfoo/.gitignore": true, "external/barfoo/.bower.json": true,
|
||||
},
|
||||
"abc/def\r\nxyz": {"abc/def": true, "a/xyz": true},
|
||||
`/**/foo`: {"foo": true, "foo/": true, "a/b/foo": true, "fooo": false, "ofoo": false},
|
||||
"/.js": {".js": true, ".js/": true, ".js/a": true, ".jsa": false},
|
||||
"*.js": {".js": true, ".js/": true, ".js/a": true, "a.js/a": true, "a.js/a.js": true, ".jsa": false, "a.jsa": false},
|
||||
"foo/**/": {"foo/": false, "foo": false, "foo/abc/": true, "foo/a/b/c/": true, "foo/a": false},
|
||||
"foo/**/*.bar": {"foo/": false, "abc.bar": false, "foo/abc.bar": true, "foo/a.bar/": true, "foo/x/y/z.bar": true},
|
||||
`\#abc`: {"abc": false, "#abc": true},
|
||||
"abc\n!abc/x": {"abc": true, "abc/x": false, "abc/y": true},
|
||||
`abc/*`: {"abc": false, "abc/": false, "abc/x": true},
|
||||
} {
|
||||
p := NewGitignore()
|
||||
if err := p.LoadString(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for tpath, expected := range tests {
|
||||
path := strings.TrimRight(tpath, "/")
|
||||
ftype := utils.IfElse(len(path) < len(tpath), fs.ModeDir, 0)
|
||||
if actual, _, _ := p.IsIgnored(path, ftype); actual != expected {
|
||||
t.Fatalf("ignored: %v != %v for path: %#v and ignorefile:\n%s", expected, actual, tpath, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
tdir := t.TempDir()
|
||||
gc := filepath.Join(tdir, ".gitconfig")
|
||||
os.WriteFile(gc, []byte(`
|
||||
[core]
|
||||
something
|
||||
[else]
|
||||
...
|
||||
[core]
|
||||
...
|
||||
[core]
|
||||
excludesfile = one
|
||||
[core]
|
||||
excludesfile = ~/global-gitignore
|
||||
`), 0600)
|
||||
if ef := _get_global_gitconfig_excludesfile(gc); ef != utils.Expanduser("~/global-gitignore") {
|
||||
t.Fatalf("global gitconfig excludes file incorrect: %s != %s", utils.Expanduser("~/global-gitignore"), ef)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
// Algorithm found at: https://rsync.samba.org/tech_report/tech_report.html
|
||||
// Code in this file is inspired by: https://github.com/jbreiding/rsync-go
|
||||
//
|
||||
// Definitions
|
||||
//
|
||||
// Source: The final content.
|
||||
// Target: The content to be made into final content.
|
||||
// Signature: The sequence of hashes used to identify the content.
|
||||
package rsync
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/zeebo/xxh3"
|
||||
)
|
||||
|
||||
// If no BlockSize is specified in the rsync instance, this value is used.
|
||||
const DefaultBlockSize = 1024 * 6
|
||||
|
||||
// Internal constant used in rolling checksum.
|
||||
const _M = 1 << 16
|
||||
|
||||
// Operation Types.
|
||||
type OpType byte // enum
|
||||
|
||||
const (
|
||||
OpBlock OpType = iota
|
||||
OpData
|
||||
OpHash
|
||||
OpBlockRange
|
||||
)
|
||||
|
||||
type xxh3_128 struct {
|
||||
xxh3.Hasher
|
||||
}
|
||||
|
||||
func (self *xxh3_128) Sum(b []byte) []byte {
|
||||
s := self.Sum128()
|
||||
pos := len(b)
|
||||
limit := pos + 16
|
||||
if limit > cap(b) {
|
||||
var x [16]byte
|
||||
b = append(b, x[:]...)
|
||||
} else {
|
||||
b = b[:limit]
|
||||
}
|
||||
binary.BigEndian.PutUint64(b[pos:], s.Hi)
|
||||
binary.BigEndian.PutUint64(b[pos+8:], s.Lo)
|
||||
return b
|
||||
}
|
||||
|
||||
func new_xxh3_64() hash.Hash64 {
|
||||
ans := xxh3.New()
|
||||
ans.Reset()
|
||||
return ans
|
||||
}
|
||||
|
||||
func new_xxh3_128() hash.Hash {
|
||||
ans := new(xxh3_128)
|
||||
ans.Reset()
|
||||
return ans
|
||||
}
|
||||
|
||||
// Instruction to mutate target to align to source.
|
||||
type Operation struct {
|
||||
Type OpType
|
||||
BlockIndex uint64
|
||||
BlockIndexEnd uint64
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func (self Operation) String() string {
|
||||
ans := "{" + self.Type.String() + " "
|
||||
switch self.Type {
|
||||
case OpBlock:
|
||||
ans += strconv.FormatUint(self.BlockIndex, 10)
|
||||
case OpBlockRange:
|
||||
ans += strconv.FormatUint(self.BlockIndex, 10) + " to " + strconv.FormatUint(self.BlockIndexEnd, 10)
|
||||
case OpData:
|
||||
ans += strconv.Itoa(len(self.Data))
|
||||
case OpHash:
|
||||
ans += hex.EncodeToString(self.Data)
|
||||
}
|
||||
return ans + "}"
|
||||
}
|
||||
|
||||
var bin = binary.LittleEndian
|
||||
|
||||
func (self Operation) SerializeSize() int {
|
||||
switch self.Type {
|
||||
case OpBlock:
|
||||
return 9
|
||||
case OpBlockRange:
|
||||
return 13
|
||||
case OpHash:
|
||||
return 3 + len(self.Data)
|
||||
case OpData:
|
||||
return 5 + len(self.Data)
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func (self Operation) Serialize(ans []byte) {
|
||||
switch self.Type {
|
||||
case OpBlock:
|
||||
bin.PutUint64(ans[1:], self.BlockIndex)
|
||||
case OpBlockRange:
|
||||
bin.PutUint64(ans[1:], self.BlockIndex)
|
||||
bin.PutUint32(ans[9:], uint32(self.BlockIndexEnd-self.BlockIndex))
|
||||
case OpHash:
|
||||
bin.PutUint16(ans[1:], uint16(len(self.Data)))
|
||||
copy(ans[3:], self.Data)
|
||||
case OpData:
|
||||
bin.PutUint32(ans[1:], uint32(len(self.Data)))
|
||||
copy(ans[5:], self.Data)
|
||||
}
|
||||
ans[0] = byte(self.Type)
|
||||
}
|
||||
|
||||
func (self *Operation) Unserialize(data []byte) (n int, err error) {
|
||||
if len(data) < 1 {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
switch OpType(data[0]) {
|
||||
case OpBlock:
|
||||
n = 9
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
self.BlockIndex = bin.Uint64(data[1:])
|
||||
self.Data = nil
|
||||
case OpBlockRange:
|
||||
n = 13
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
self.BlockIndex = bin.Uint64(data[1:])
|
||||
self.BlockIndexEnd = self.BlockIndex + uint64(bin.Uint32(data[9:]))
|
||||
self.Data = nil
|
||||
case OpHash:
|
||||
n = 3
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
sz := int(bin.Uint16(data[1:]))
|
||||
n += sz
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
self.Data = data[3:n]
|
||||
case OpData:
|
||||
n = 5
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
sz := int(bin.Uint32(data[1:]))
|
||||
n += sz
|
||||
if len(data) < n {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
self.Data = data[5:n]
|
||||
default:
|
||||
return 0, fmt.Errorf("record has unknown operation type: %d", data[0])
|
||||
}
|
||||
self.Type = OpType(data[0])
|
||||
return
|
||||
}
|
||||
|
||||
// Signature hash item generated from target.
|
||||
type BlockHash struct {
|
||||
Index uint64
|
||||
WeakHash uint32
|
||||
StrongHash uint64
|
||||
}
|
||||
|
||||
const BlockHashSize = 20
|
||||
|
||||
// Put the serialization of this BlockHash to output
|
||||
func (self BlockHash) Serialize(output []byte) {
|
||||
bin.PutUint64(output, self.Index)
|
||||
bin.PutUint32(output[8:], self.WeakHash)
|
||||
bin.PutUint64(output[12:], self.StrongHash)
|
||||
}
|
||||
|
||||
func (self *BlockHash) Unserialize(data []byte) (err error) {
|
||||
if len(data) < 20 {
|
||||
return fmt.Errorf("record too small to be a BlockHash: %d < %d", len(data), 20)
|
||||
}
|
||||
self.Index = bin.Uint64(data)
|
||||
self.WeakHash = bin.Uint32(data[8:])
|
||||
self.StrongHash = bin.Uint64(data[12:])
|
||||
return
|
||||
}
|
||||
|
||||
// Properties to use while working with the rsync algorithm.
|
||||
// A single rsync should not be used concurrently as it may contain
|
||||
// internal buffers and hash sums.
|
||||
type rsync struct {
|
||||
BlockSize int
|
||||
|
||||
// This must be non-nil before using any functions
|
||||
hasher hash.Hash64
|
||||
hasher_constructor func() hash.Hash64
|
||||
checksummer_constructor func() hash.Hash
|
||||
checksummer hash.Hash
|
||||
checksum_done bool
|
||||
buffer []byte
|
||||
}
|
||||
|
||||
func (r *rsync) SetHasher(c func() hash.Hash64) {
|
||||
r.hasher_constructor = c
|
||||
r.hasher = c()
|
||||
}
|
||||
|
||||
func (r *rsync) SetChecksummer(c func() hash.Hash) {
|
||||
r.checksummer_constructor = c
|
||||
r.checksummer = c()
|
||||
}
|
||||
|
||||
// If the target length is known the number of hashes in the
|
||||
// signature can be determined.
|
||||
func (r *rsync) BlockHashCount(targetLength int64) (count int64) {
|
||||
bs := int64(r.BlockSize)
|
||||
count = targetLength / bs
|
||||
if targetLength%bs != 0 {
|
||||
count++
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type signature_iterator struct {
|
||||
hasher hash.Hash64
|
||||
buffer []byte
|
||||
src io.Reader
|
||||
rc rolling_checksum
|
||||
index uint64
|
||||
}
|
||||
|
||||
// ans is valid iff err == nil
|
||||
func (self *signature_iterator) next() (ans BlockHash, err error) {
|
||||
n, err := io.ReadAtLeast(self.src, self.buffer, cap(self.buffer))
|
||||
switch err {
|
||||
case io.ErrUnexpectedEOF, io.EOF, nil:
|
||||
err = nil
|
||||
default:
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
return ans, io.EOF
|
||||
}
|
||||
b := self.buffer[:n]
|
||||
self.hasher.Reset()
|
||||
self.hasher.Write(b)
|
||||
ans = BlockHash{Index: self.index, WeakHash: self.rc.full(b), StrongHash: self.hasher.Sum64()}
|
||||
self.index++
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// Calculate the signature of target.
|
||||
func (r *rsync) CreateSignatureIterator(target io.Reader) func() (BlockHash, error) {
|
||||
return (&signature_iterator{
|
||||
hasher: r.hasher_constructor(), buffer: make([]byte, r.BlockSize), src: target,
|
||||
}).next
|
||||
}
|
||||
|
||||
// Apply the difference to the target.
|
||||
func (r *rsync) ApplyDelta(output io.Writer, target io.ReadSeeker, op Operation) error {
|
||||
var err error
|
||||
var n int
|
||||
var block []byte
|
||||
|
||||
r.set_buffer_to_size(r.BlockSize)
|
||||
buffer := r.buffer
|
||||
if r.checksummer == nil {
|
||||
r.checksummer = r.checksummer_constructor()
|
||||
}
|
||||
|
||||
write := func(b []byte) (err error) {
|
||||
if _, err = r.checksummer.Write(b); err == nil {
|
||||
_, err = output.Write(b)
|
||||
}
|
||||
return err
|
||||
}
|
||||
write_block := func(op Operation) (err error) {
|
||||
if _, err = target.Seek(int64(r.BlockSize*int(op.BlockIndex)), io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
if n, err = io.ReadAtLeast(target, buffer, r.BlockSize); err != nil && err != io.ErrUnexpectedEOF {
|
||||
return err
|
||||
}
|
||||
block = buffer[:n]
|
||||
return write(block)
|
||||
}
|
||||
|
||||
switch op.Type {
|
||||
case OpBlockRange:
|
||||
for i := op.BlockIndex; i <= op.BlockIndexEnd; i++ {
|
||||
if err = write_block(Operation{
|
||||
Type: OpBlock,
|
||||
BlockIndex: i,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case OpBlock:
|
||||
return write_block(op)
|
||||
case OpData:
|
||||
return write(op.Data)
|
||||
case OpHash:
|
||||
actual := r.checksummer.Sum(nil)
|
||||
if !bytes.Equal(actual, op.Data) {
|
||||
return fmt.Errorf("Failed to verify overall file checksum actual: %s != expected: %s. This usually happens if some data was corrupted in transit or one of the involved files was altered while the transfer was in progress.", hex.EncodeToString(actual), hex.EncodeToString(op.Data))
|
||||
}
|
||||
r.checksum_done = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *rsync) set_buffer_to_size(sz int) {
|
||||
if cap(r.buffer) < sz {
|
||||
r.buffer = make([]byte, sz)
|
||||
} else {
|
||||
r.buffer = r.buffer[:sz]
|
||||
}
|
||||
}
|
||||
|
||||
// see https://rsync.samba.org/tech_report/node3.html
|
||||
type rolling_checksum struct {
|
||||
alpha, beta, val, l uint32
|
||||
first_byte_of_previous_window uint32
|
||||
}
|
||||
|
||||
func (self *rolling_checksum) full(data []byte) uint32 {
|
||||
var alpha, beta uint32
|
||||
self.l = uint32(len(data)) // actually should be len(data) - 1 but the equations always use l+1
|
||||
for i, b := range data {
|
||||
alpha += uint32(b)
|
||||
beta += (self.l - uint32(i)) * uint32(b)
|
||||
}
|
||||
self.first_byte_of_previous_window = uint32(data[0])
|
||||
self.alpha = alpha % _M
|
||||
self.beta = beta % _M
|
||||
self.val = self.alpha + _M*self.beta
|
||||
return self.val
|
||||
}
|
||||
|
||||
func (self *rolling_checksum) add_one_byte(first_byte, last_byte byte) {
|
||||
self.alpha = (self.alpha - self.first_byte_of_previous_window + uint32(last_byte)) % _M
|
||||
self.beta = (self.beta - (self.l)*self.first_byte_of_previous_window + self.alpha) % _M
|
||||
self.val = self.alpha + _M*self.beta
|
||||
self.first_byte_of_previous_window = uint32(first_byte)
|
||||
}
|
||||
|
||||
type diff struct {
|
||||
buffer []byte
|
||||
op_write_buf [32]byte
|
||||
// A single β hash may correlate with many unique hashes.
|
||||
hash_lookup map[uint32][]BlockHash
|
||||
source io.Reader
|
||||
hasher hash.Hash64
|
||||
checksummer hash.Hash
|
||||
output io.Writer
|
||||
|
||||
window, data struct{ pos, sz int }
|
||||
block_size int
|
||||
finished, written bool
|
||||
rc rolling_checksum
|
||||
|
||||
pending_op *Operation
|
||||
}
|
||||
|
||||
func (self *diff) Next() (err error) {
|
||||
return self.pump_till_op_written()
|
||||
}
|
||||
|
||||
func (self *diff) hash(b []byte) uint64 {
|
||||
self.hasher.Reset()
|
||||
self.hasher.Write(b)
|
||||
return self.hasher.Sum64()
|
||||
}
|
||||
|
||||
// Combine OpBlock into OpBlockRange. To do this store the previous
|
||||
// non-data operation and determine if it can be extended.
|
||||
func (self *diff) send_pending() (err error) {
|
||||
if self.pending_op != nil {
|
||||
err = self.send_op(self.pending_op)
|
||||
self.pending_op = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *diff) enqueue(op Operation) (err error) {
|
||||
switch op.Type {
|
||||
case OpBlock:
|
||||
if self.pending_op != nil {
|
||||
switch self.pending_op.Type {
|
||||
case OpBlock:
|
||||
if self.pending_op.BlockIndex+1 == op.BlockIndex {
|
||||
self.pending_op = &Operation{
|
||||
Type: OpBlockRange,
|
||||
BlockIndex: self.pending_op.BlockIndex,
|
||||
BlockIndexEnd: op.BlockIndex,
|
||||
}
|
||||
return
|
||||
}
|
||||
case OpBlockRange:
|
||||
if self.pending_op.BlockIndexEnd+1 == op.BlockIndex {
|
||||
self.pending_op.BlockIndexEnd = op.BlockIndex
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = self.send_pending(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
self.pending_op = &op
|
||||
case OpHash:
|
||||
if err = self.send_pending(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = self.send_op(&op); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
func (self *diff) send_op(op *Operation) error {
|
||||
b := self.op_write_buf[:op.SerializeSize()]
|
||||
op.Serialize(b)
|
||||
self.written = true
|
||||
_, err := self.output.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *diff) send_data() error {
|
||||
if self.data.sz > 0 {
|
||||
if err := self.send_pending(); err != nil {
|
||||
return err
|
||||
}
|
||||
self.written = true
|
||||
data := self.buffer[self.data.pos : self.data.pos+self.data.sz]
|
||||
var buf [5]byte
|
||||
bin.PutUint32(buf[1:], uint32(len(data)))
|
||||
buf[0] = byte(OpData)
|
||||
if _, err := self.output.Write(buf[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := self.output.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
self.data.pos += self.data.sz
|
||||
self.data.sz = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *diff) pump_till_op_written() error {
|
||||
self.written = false
|
||||
for !self.finished && !self.written {
|
||||
if err := self.read_next(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if self.finished {
|
||||
if err := self.send_pending(); err != nil {
|
||||
return err
|
||||
}
|
||||
return io.EOF
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *diff) ensure_idx_valid(idx int) (ok bool, err error) {
|
||||
if idx < len(self.buffer) {
|
||||
return true, nil
|
||||
}
|
||||
if idx >= cap(self.buffer) {
|
||||
// need to wrap the buffer, so send off any data present behind the window
|
||||
if err = self.send_data(); err != nil {
|
||||
return
|
||||
}
|
||||
// copy the window and any data present after it to the start of the buffer
|
||||
distance_from_window_pos := idx - self.window.pos
|
||||
amt_to_copy := len(self.buffer) - self.window.pos
|
||||
copy(self.buffer, self.buffer[self.window.pos:self.window.pos+amt_to_copy])
|
||||
self.buffer = self.buffer[:amt_to_copy]
|
||||
self.window.pos = 0
|
||||
self.data.pos = 0
|
||||
return self.ensure_idx_valid(distance_from_window_pos)
|
||||
}
|
||||
extra := idx - len(self.buffer) + 1
|
||||
var n int
|
||||
n, err = io.ReadAtLeast(self.source, self.buffer[len(self.buffer):cap(self.buffer)], extra)
|
||||
block := self.buffer[len(self.buffer):][:n]
|
||||
switch err {
|
||||
case nil:
|
||||
ok = true
|
||||
self.buffer = self.buffer[:len(self.buffer)+n]
|
||||
self.checksummer.Write(block)
|
||||
case io.ErrUnexpectedEOF, io.EOF:
|
||||
err = nil
|
||||
self.buffer = self.buffer[:len(self.buffer)+n]
|
||||
self.checksummer.Write(block)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *diff) finish_up() (err error) {
|
||||
if err = self.send_data(); err != nil {
|
||||
return
|
||||
}
|
||||
self.data.pos = self.window.pos
|
||||
self.data.sz = len(self.buffer) - self.window.pos
|
||||
if err = self.send_data(); err != nil {
|
||||
return
|
||||
}
|
||||
self.enqueue(Operation{Type: OpHash, Data: self.checksummer.Sum(nil)})
|
||||
self.finished = true
|
||||
return
|
||||
}
|
||||
|
||||
// See https://rsync.samba.org/tech_report/node4.html for the design of this algorithm
|
||||
func (self *diff) read_next() (err error) {
|
||||
if self.window.sz > 0 {
|
||||
if ok, err := self.ensure_idx_valid(self.window.pos + self.window.sz); !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return self.finish_up()
|
||||
}
|
||||
self.window.pos++
|
||||
self.data.sz++
|
||||
self.rc.add_one_byte(self.buffer[self.window.pos], self.buffer[self.window.pos+self.window.sz-1])
|
||||
} else {
|
||||
if ok, err := self.ensure_idx_valid(self.window.pos + self.block_size - 1); !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return self.finish_up()
|
||||
}
|
||||
self.window.sz = self.block_size
|
||||
self.rc.full(self.buffer[self.window.pos : self.window.pos+self.window.sz])
|
||||
}
|
||||
found_hash := false
|
||||
var block_index uint64
|
||||
if hh, ok := self.hash_lookup[self.rc.val]; ok {
|
||||
block_index, found_hash = find_hash(hh, self.hash(self.buffer[self.window.pos:self.window.pos+self.window.sz]))
|
||||
}
|
||||
if found_hash {
|
||||
if err = self.send_data(); err != nil {
|
||||
return
|
||||
}
|
||||
self.enqueue(Operation{Type: OpBlock, BlockIndex: block_index})
|
||||
self.window.pos += self.window.sz
|
||||
self.data.pos = self.window.pos
|
||||
self.window.sz = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type OperationWriter struct {
|
||||
Operations []Operation
|
||||
expecting_data bool
|
||||
}
|
||||
|
||||
func (self *OperationWriter) Write(p []byte) (n int, err error) {
|
||||
if self.expecting_data {
|
||||
self.expecting_data = false
|
||||
self.Operations = append(self.Operations, Operation{Type: OpData, Data: slices.Clone(p)})
|
||||
} else {
|
||||
switch OpType(p[0]) {
|
||||
case OpData:
|
||||
self.expecting_data = true
|
||||
case OpBlock, OpBlockRange, OpHash:
|
||||
op := Operation{}
|
||||
if n, err = op.Unserialize(p); err != nil {
|
||||
return 0, err
|
||||
} else if n < len(p) {
|
||||
return 0, io.ErrShortWrite
|
||||
}
|
||||
self.Operations = append(self.Operations, op)
|
||||
default:
|
||||
return 0, fmt.Errorf("Unknown OpType: %d", p[0])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (r *rsync) CreateDelta(source io.Reader, signature []BlockHash) ([]Operation, error) {
|
||||
w := OperationWriter{}
|
||||
it := r.CreateDiff(source, signature, &w)
|
||||
for {
|
||||
if err := it(); err != nil {
|
||||
if err == io.EOF {
|
||||
return w.Operations, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DataSizeMultiple int = 8
|
||||
|
||||
func (r *rsync) CreateDiff(source io.Reader, signature []BlockHash, output io.Writer) func() error {
|
||||
ans := &diff{
|
||||
block_size: r.BlockSize, buffer: make([]byte, 0, (r.BlockSize * DataSizeMultiple)),
|
||||
hash_lookup: make(map[uint32][]BlockHash, len(signature)),
|
||||
source: source, hasher: r.hasher_constructor(),
|
||||
checksummer: r.checksummer_constructor(), output: output,
|
||||
}
|
||||
for _, h := range signature {
|
||||
key := h.WeakHash
|
||||
ans.hash_lookup[key] = append(ans.hash_lookup[key], h)
|
||||
}
|
||||
|
||||
return ans.Next
|
||||
}
|
||||
|
||||
// Use a more unique way to identify a set of bytes.
|
||||
func (r *rsync) hash(v []byte) uint64 {
|
||||
r.hasher.Reset()
|
||||
r.hasher.Write(v)
|
||||
return r.hasher.Sum64()
|
||||
}
|
||||
|
||||
func (r *rsync) HashSize() int { return r.hasher.Size() }
|
||||
func (r *rsync) HashBlockSize() int { return r.hasher.BlockSize() }
|
||||
func (r *rsync) HasHasher() bool { return r.hasher != nil }
|
||||
|
||||
// Searches for a given strong hash among all strong hashes in this bucket.
|
||||
func find_hash(hh []BlockHash, hv uint64) (uint64, bool) {
|
||||
for _, block := range hh {
|
||||
if block.StrongHash == hv {
|
||||
return block.Index, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
// First create a patcher with:
|
||||
// p = NewPatcher()
|
||||
// Create a signature for the file you want to update using
|
||||
// p.CreateSignatureIterator(file_to_update)
|
||||
// Now create a Differ with the created signature
|
||||
// d = NewDiffer()
|
||||
// d.AddSignatureData(signature_data_from_previous_step)
|
||||
// Now create a delta based on the signature and the reference file
|
||||
// d.CreateDelta(reference_file)
|
||||
// Finally, apply this delta using the patcher to produce a file identical to reference_file
|
||||
// based ont he delta data and file_to_update
|
||||
// p.StartDelta(output_file, file_to_update)
|
||||
// p.UpdateDelta(...)
|
||||
// p.FinishDelta()
|
||||
package rsync
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const MaxBlockSize int = 1024 * 1024 // sqrt of 1TB
|
||||
|
||||
type StrongHashType uint16
|
||||
type WeakHashType uint16
|
||||
type ChecksumType uint16
|
||||
|
||||
const (
|
||||
XXH3 StrongHashType = iota
|
||||
)
|
||||
const (
|
||||
XXH3128Sum ChecksumType = iota
|
||||
)
|
||||
const (
|
||||
Rsync WeakHashType = iota
|
||||
)
|
||||
|
||||
type GrowBufferFunction = func(slice []byte, sz int) []byte
|
||||
|
||||
type Api struct {
|
||||
rsync rsync
|
||||
signature []BlockHash
|
||||
|
||||
Checksum_type ChecksumType
|
||||
Strong_hash_type StrongHashType
|
||||
Weak_hash_type WeakHashType
|
||||
}
|
||||
|
||||
type Differ struct {
|
||||
Api
|
||||
unconsumed_signature_data []byte
|
||||
}
|
||||
|
||||
type Patcher struct {
|
||||
Api
|
||||
unconsumed_delta_data []byte
|
||||
expected_input_size_for_signature_generation int64
|
||||
delta_output io.Writer
|
||||
delta_input io.ReadSeeker
|
||||
total_data_in_delta int
|
||||
}
|
||||
|
||||
// internal implementation {{{
|
||||
func (self *Api) read_signature_header(data []byte) (consumed int, err error) {
|
||||
if len(data) < 12 {
|
||||
return -1, io.ErrShortBuffer
|
||||
}
|
||||
if version := bin.Uint16(data); version != 0 {
|
||||
return consumed, fmt.Errorf("Invalid version in signature header: %d", version)
|
||||
}
|
||||
switch csum := ChecksumType(bin.Uint16(data[2:])); csum {
|
||||
case XXH3128Sum:
|
||||
self.Checksum_type = XXH3128Sum
|
||||
self.rsync.SetChecksummer(new_xxh3_128)
|
||||
default:
|
||||
return consumed, fmt.Errorf("Invalid checksum_type in signature header: %d", csum)
|
||||
}
|
||||
switch strong_hash := StrongHashType(bin.Uint16(data[4:])); strong_hash {
|
||||
case XXH3:
|
||||
self.Strong_hash_type = strong_hash
|
||||
self.rsync.SetHasher(new_xxh3_64)
|
||||
default:
|
||||
return consumed, fmt.Errorf("Invalid strong_hash in signature header: %d", strong_hash)
|
||||
}
|
||||
switch weak_hash := WeakHashType(bin.Uint16(data[6:])); weak_hash {
|
||||
case Rsync:
|
||||
self.Weak_hash_type = weak_hash
|
||||
default:
|
||||
return consumed, fmt.Errorf("Invalid weak_hash in signature header: %d", weak_hash)
|
||||
}
|
||||
block_size := int(bin.Uint32(data[8:]))
|
||||
consumed = 12
|
||||
if block_size == 0 {
|
||||
return consumed, fmt.Errorf("rsync signature header has zero block size")
|
||||
}
|
||||
if block_size > MaxBlockSize {
|
||||
return consumed, fmt.Errorf("rsync signature header has too large block size %d > %d", block_size, MaxBlockSize)
|
||||
}
|
||||
self.rsync.BlockSize = block_size
|
||||
self.signature = make([]BlockHash, 0, 1024)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Api) read_signature_blocks(data []byte) (consumed int) {
|
||||
block_hash_size := self.rsync.HashSize() + 12
|
||||
for ; len(data) >= block_hash_size; data = data[block_hash_size:] {
|
||||
bl := BlockHash{}
|
||||
bl.Unserialize(data[:block_hash_size])
|
||||
self.signature = append(self.signature, bl)
|
||||
consumed += block_hash_size
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Differ) FinishSignatureData() (err error) {
|
||||
if len(self.unconsumed_signature_data) > 0 {
|
||||
return fmt.Errorf("There were %d leftover bytes in the signature data", len(self.unconsumed_signature_data))
|
||||
}
|
||||
self.unconsumed_signature_data = nil
|
||||
if !self.rsync.HasHasher() {
|
||||
return fmt.Errorf("No header was found in the signature data")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Patcher) update_delta(data []byte) (consumed int, err error) {
|
||||
op := Operation{}
|
||||
for len(data) > 0 {
|
||||
n, uerr := op.Unserialize(data)
|
||||
if uerr == nil {
|
||||
consumed += n
|
||||
data = data[n:]
|
||||
if err = self.rsync.ApplyDelta(self.delta_output, self.delta_input, op); err != nil {
|
||||
return
|
||||
}
|
||||
if op.Type == OpData {
|
||||
self.total_data_in_delta += len(op.Data)
|
||||
}
|
||||
} else {
|
||||
if n < 0 {
|
||||
return consumed, nil
|
||||
}
|
||||
return consumed, uerr
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// }}}
|
||||
|
||||
// Start applying serialized delta
|
||||
func (self *Patcher) StartDelta(delta_output io.Writer, delta_input io.ReadSeeker) {
|
||||
self.delta_output = delta_output
|
||||
self.delta_input = delta_input
|
||||
self.total_data_in_delta = 0
|
||||
self.unconsumed_delta_data = nil
|
||||
}
|
||||
|
||||
// Apply a chunk of delta data
|
||||
func (self *Patcher) UpdateDelta(data []byte) (err error) {
|
||||
self.unconsumed_delta_data = append(self.unconsumed_delta_data, data...)
|
||||
consumed, err := self.update_delta(self.unconsumed_delta_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.unconsumed_delta_data = utils.ShiftLeft(self.unconsumed_delta_data, consumed)
|
||||
return
|
||||
}
|
||||
|
||||
// Finish applying delta data
|
||||
func (self *Patcher) FinishDelta() (err error) {
|
||||
if err = self.UpdateDelta([]byte{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(self.unconsumed_delta_data) > 0 {
|
||||
return fmt.Errorf("There are %d leftover bytes in the delta", len(self.unconsumed_delta_data))
|
||||
}
|
||||
self.delta_input = nil
|
||||
self.delta_output = nil
|
||||
self.unconsumed_delta_data = nil
|
||||
if !self.rsync.checksum_done {
|
||||
return fmt.Errorf("The checksum was not received at the end of the delta data")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Create a signature for the data source in src.
|
||||
func (self *Patcher) CreateSignatureIterator(src io.Reader, output io.Writer) func() error {
|
||||
var it func() (BlockHash, error)
|
||||
finished := false
|
||||
var b [BlockHashSize]byte
|
||||
return func() error {
|
||||
if finished {
|
||||
return io.EOF
|
||||
}
|
||||
if it == nil { // write signature header
|
||||
it = self.rsync.CreateSignatureIterator(src)
|
||||
bin.PutUint16(b[:], 0)
|
||||
bin.PutUint16(b[2:], uint16(self.Checksum_type))
|
||||
bin.PutUint16(b[4:], uint16(self.Strong_hash_type))
|
||||
bin.PutUint16(b[6:], uint16(self.Weak_hash_type))
|
||||
bin.PutUint32(b[8:], uint32(self.rsync.BlockSize))
|
||||
if _, err := output.Write(b[:12]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
bl, err := it()
|
||||
switch err {
|
||||
case io.EOF:
|
||||
finished = true
|
||||
return io.EOF
|
||||
case nil:
|
||||
bl.Serialize(b[:BlockHashSize])
|
||||
_, err = output.Write(b[:BlockHashSize])
|
||||
return err
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create a serialized delta based on the previously loaded signature
|
||||
func (self *Differ) CreateDelta(src io.Reader, output io.Writer) func() error {
|
||||
if err := self.FinishSignatureData(); err != nil {
|
||||
return func() error { return err }
|
||||
}
|
||||
if self.signature == nil {
|
||||
return func() error {
|
||||
return fmt.Errorf("Cannot call CreateDelta() before loading a signature")
|
||||
}
|
||||
}
|
||||
return self.rsync.CreateDiff(src, self.signature, output)
|
||||
}
|
||||
|
||||
func (self *Differ) BlockSize() int {
|
||||
return self.rsync.BlockSize
|
||||
}
|
||||
|
||||
// Add more external signature data
|
||||
func (self *Differ) AddSignatureData(data []byte) (err error) {
|
||||
self.unconsumed_signature_data = append(self.unconsumed_signature_data, data...)
|
||||
if !self.rsync.HasHasher() {
|
||||
consumed, err := self.read_signature_header(self.unconsumed_signature_data)
|
||||
if err != nil {
|
||||
if consumed < 0 {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
self.unconsumed_signature_data = utils.ShiftLeft(self.unconsumed_signature_data, consumed)
|
||||
}
|
||||
consumed := self.read_signature_blocks(self.unconsumed_signature_data)
|
||||
self.unconsumed_signature_data = utils.ShiftLeft(self.unconsumed_signature_data, consumed)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use to calculate a delta based on a supplied signature, via AddSignatureData
|
||||
func NewDiffer() *Differ {
|
||||
return &Differ{}
|
||||
}
|
||||
|
||||
// Use to create a signature and possibly apply a delta
|
||||
func NewPatcher(expected_input_size int64) (ans *Patcher) {
|
||||
bs := DefaultBlockSize
|
||||
sz := max(0, expected_input_size)
|
||||
if sz > 0 {
|
||||
bs = int(math.Round(math.Sqrt(float64(sz))))
|
||||
}
|
||||
ans = &Patcher{}
|
||||
ans.rsync.BlockSize = min(bs, MaxBlockSize)
|
||||
ans.rsync.SetHasher(new_xxh3_64)
|
||||
ans.rsync.SetChecksummer(new_xxh3_128)
|
||||
|
||||
if ans.rsync.HashBlockSize() > 0 && ans.rsync.HashBlockSize() < ans.rsync.BlockSize {
|
||||
ans.rsync.BlockSize = (ans.rsync.BlockSize / ans.rsync.HashBlockSize()) * ans.rsync.HashBlockSize()
|
||||
}
|
||||
|
||||
ans.expected_input_size_for_signature_generation = sz
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package rsync
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var _ = cmp.Diff
|
||||
|
||||
func run_roundtrip_test(t *testing.T, src_data, changed []byte, num_of_patches, total_patch_size int) {
|
||||
using_serialization := false
|
||||
t.Helper()
|
||||
prefix_msg := func() string {
|
||||
q := utils.IfElse(using_serialization, "with", "without")
|
||||
return fmt.Sprintf("Running %s serialization: src size: %d changed size: %d difference: %d\n",
|
||||
q, len(src_data), len(changed), len(changed)-len(src_data))
|
||||
}
|
||||
|
||||
test_equal := func(src_data, output []byte) {
|
||||
if !bytes.Equal(src_data, output) {
|
||||
first_diff := min(len(src_data), len(output))
|
||||
for i := 0; i < first_diff; i++ {
|
||||
if src_data[i] != output[i] {
|
||||
first_diff = i
|
||||
break
|
||||
}
|
||||
}
|
||||
t.Fatalf("%sPatching failed: %d extra_bytes first different byte at: %d\nsrc:\n%s\nchanged:\n%s\noutput:\n%s\n",
|
||||
prefix_msg(), len(output)-len(src_data), first_diff, string(src_data), string(changed), string(output))
|
||||
}
|
||||
}
|
||||
|
||||
// first try just the engine without serialization
|
||||
p := NewPatcher(int64(len(src_data)))
|
||||
signature := make([]BlockHash, 0, 128)
|
||||
s_it := p.rsync.CreateSignatureIterator(bytes.NewReader(changed))
|
||||
for {
|
||||
s, err := s_it()
|
||||
if err == nil {
|
||||
signature = append(signature, s)
|
||||
} else if err == io.EOF {
|
||||
break
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
total_data_in_delta := 0
|
||||
apply_delta := func(signature []BlockHash) []byte {
|
||||
delta_ops, err := p.rsync.CreateDelta(bytes.NewReader(src_data), signature)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if delta_ops[len(delta_ops)-1].Type != OpHash {
|
||||
t.Fatalf("Last operation was not OpHash")
|
||||
}
|
||||
total_data_in_delta = 0
|
||||
outputbuf := bytes.Buffer{}
|
||||
for _, op := range delta_ops {
|
||||
if op.Type == OpData {
|
||||
total_data_in_delta += len(op.Data)
|
||||
}
|
||||
p.rsync.ApplyDelta(&outputbuf, bytes.NewReader(changed), op)
|
||||
}
|
||||
return outputbuf.Bytes()
|
||||
}
|
||||
test_equal(src_data, apply_delta(signature))
|
||||
limit := 2 * (p.rsync.BlockSize * num_of_patches)
|
||||
if limit > -1 && total_data_in_delta > limit {
|
||||
t.Fatalf("%sUnexpectedly poor delta performance: total_patch_size: %d total_delta_size: %d limit: %d", prefix_msg(), total_patch_size, total_data_in_delta, limit)
|
||||
}
|
||||
|
||||
// Now try with serialization
|
||||
using_serialization = true
|
||||
p = NewPatcher(int64(len(changed)))
|
||||
signature_of_changed := bytes.Buffer{}
|
||||
ss_it := p.CreateSignatureIterator(bytes.NewReader(changed), &signature_of_changed)
|
||||
var err error
|
||||
for {
|
||||
err = ss_it()
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
d := NewDiffer()
|
||||
if err := d.AddSignatureData(signature_of_changed.Bytes()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := bytes.Buffer{}
|
||||
it := d.CreateDelta(bytes.NewBuffer(src_data), &db)
|
||||
for {
|
||||
if err := it(); err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
deltabuf := db.Bytes()
|
||||
outputbuf := bytes.Buffer{}
|
||||
p.StartDelta(&outputbuf, bytes.NewReader(changed))
|
||||
for len(deltabuf) > 0 {
|
||||
n := min(123, len(deltabuf))
|
||||
if err := p.UpdateDelta(deltabuf[:n]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deltabuf = deltabuf[n:]
|
||||
}
|
||||
if err := p.FinishDelta(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
test_equal(src_data, outputbuf.Bytes())
|
||||
if limit > -1 && p.total_data_in_delta > limit {
|
||||
t.Fatalf("%sUnexpectedly poor delta performance: total_patch_size: %d total_delta_size: %d limit: %d", prefix_msg(), total_patch_size, p.total_data_in_delta, limit)
|
||||
}
|
||||
}
|
||||
|
||||
func generate_data(block_size, num_of_blocks int, extra ...string) []byte {
|
||||
e := strings.Join(extra, "")
|
||||
ans := make([]byte, num_of_blocks*block_size+len(e))
|
||||
utils.Memset(ans, '_')
|
||||
for i := range num_of_blocks {
|
||||
offset := i * block_size
|
||||
copy(ans[offset:], strconv.Itoa(i))
|
||||
}
|
||||
copy(ans[num_of_blocks*block_size:], e)
|
||||
return ans
|
||||
}
|
||||
|
||||
func patch_data(data []byte, patches ...string) (num_of_patches, total_patch_size int) {
|
||||
num_of_patches = len(patches)
|
||||
for _, patch := range patches {
|
||||
o, r, _ := strings.Cut(patch, ":")
|
||||
total_patch_size += len(r)
|
||||
if offset, err := strconv.Atoi(o); err == nil {
|
||||
copy(data[offset:], r)
|
||||
} else {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func TestRsyncRoundtrip(t *testing.T) {
|
||||
block_size := 16
|
||||
src_data := generate_data(block_size, 16)
|
||||
changed := slices.Clone(src_data)
|
||||
num_of_patches, total_patch_size := patch_data(changed, "3:patch1", "16:patch2", "130:ptch3", "176:patch4", "222:XXYY")
|
||||
|
||||
run_roundtrip_test(t, src_data, src_data[block_size:], 1, block_size)
|
||||
run_roundtrip_test(t, src_data, changed, num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(t, src_data, []byte{}, -1, 0)
|
||||
run_roundtrip_test(t, src_data, src_data, 0, 0)
|
||||
run_roundtrip_test(t, src_data, changed[:len(changed)-3], num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(t, src_data, append(changed[:37], changed[81:]...), num_of_patches, total_patch_size)
|
||||
|
||||
block_size = 13
|
||||
src_data = generate_data(block_size, 17, "trailer")
|
||||
changed = slices.Clone(src_data)
|
||||
num_of_patches, total_patch_size = patch_data(changed, "0:patch1", "19:patch2")
|
||||
run_roundtrip_test(t, src_data, changed, num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(t, src_data, changed[:len(changed)-3], num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(t, src_data, append(changed, "xyz..."...), num_of_patches, total_patch_size)
|
||||
}
|
||||
|
||||
func TestRsyncHashers(t *testing.T) {
|
||||
h := new_xxh3_64()
|
||||
h.Write([]byte("abcd"))
|
||||
if diff := cmp.Diff(hex.EncodeToString(h.Sum(nil)), `6497a96f53a89890`); diff != "" {
|
||||
t.Fatalf("%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(h.Sum64(), uint64(7248448420886124688)); diff != "" {
|
||||
t.Fatalf("%s", diff)
|
||||
}
|
||||
h2 := new_xxh3_128()
|
||||
h2.Write([]byte("abcd"))
|
||||
if diff := cmp.Diff(hex.EncodeToString(h2.Sum(nil)), `8d6b60383dfa90c21be79eecd1b1353d`); diff != "" {
|
||||
t.Fatalf("%s", diff)
|
||||
}
|
||||
}
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# test.sh
|
||||
# Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the MIT license.
|
||||
#
|
||||
|
||||
go run generate.go && go test -bench=.
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package simdstring
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func haystack(filler, needle byte, pos int) []byte {
|
||||
var data []byte
|
||||
if pos > 0 {
|
||||
data = append(bytes.Repeat([]byte{filler}, pos-1), needle)
|
||||
} else {
|
||||
data = []byte{needle}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
var sizes = []int{6, 327, 9875, 1198673}
|
||||
|
||||
func BenchmarkIndexByte(b *testing.B) {
|
||||
t := func(pos int, which string) {
|
||||
data := haystack('a', 'q', pos)
|
||||
f := IndexByte
|
||||
switch which {
|
||||
case "scalar":
|
||||
f = index_byte_scalar
|
||||
case "stdlib":
|
||||
f = bytes.IndexByte
|
||||
}
|
||||
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
f(data, 'q')
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, pos := range sizes {
|
||||
t(pos, "simdstring")
|
||||
t(pos, "scalar")
|
||||
t(pos, "stdlib")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIndexByte2(b *testing.B) {
|
||||
t := func(pos int, which string) {
|
||||
data := haystack('a', 'q', pos)
|
||||
f := IndexByte2
|
||||
switch which {
|
||||
case "scalar":
|
||||
f = index_byte2_scalar
|
||||
}
|
||||
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
f(data, 'q', 'x')
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, pos := range sizes {
|
||||
t(pos, "simdstring")
|
||||
t(pos, "scalar")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNotIndexByte(b *testing.B) {
|
||||
t := func(pos int, which string) {
|
||||
// Fill with 'a' and place 'q' (a non-matching byte) at the target position
|
||||
data := haystack('a', 'q', pos)
|
||||
f := NotIndexByte
|
||||
switch which {
|
||||
case "scalar":
|
||||
f = not_index_byte_scalar
|
||||
}
|
||||
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
f(data, 'a')
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, pos := range sizes {
|
||||
t(pos, "simdstring")
|
||||
t(pos, "scalar")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNotIndexByte2(b *testing.B) {
|
||||
t := func(pos int, which string) {
|
||||
// Fill with 'a' and place 'q' (neither 'a' nor 'x') at the target position
|
||||
data := haystack('a', 'q', pos)
|
||||
f := NotIndexByte2
|
||||
switch which {
|
||||
case "scalar":
|
||||
f = not_index_byte2_scalar
|
||||
}
|
||||
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
f(data, 'a', 'x')
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, pos := range sizes {
|
||||
t(pos, "simdstring")
|
||||
t(pos, "scalar")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# generate.sh
|
||||
# Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the MIT license.
|
||||
#
|
||||
go run generate.go && GOARCH=amd64 go vet ./... && GOARCH=arm64 go vet ./...
|
||||
@@ -0,0 +1,83 @@
|
||||
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package simdstring
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/sys/cpu"
|
||||
)
|
||||
|
||||
var Have128bit = false
|
||||
var Have256bit = false
|
||||
var VectorSize = 1
|
||||
|
||||
// Return the index at which b first occurs in data. If not found -1 is returned.
|
||||
var IndexByte func(data []byte, b byte) int = index_byte_scalar
|
||||
|
||||
// Return the index at which b first occurs in text. If not found -1 is returned.
|
||||
var IndexByteString func(text string, b byte) int = index_byte_string_scalar
|
||||
|
||||
// Return the index at which either a or b first occurs in data. If neither is
|
||||
// found -1 is returned.
|
||||
var IndexByte2 func(data []byte, a, b byte) int = index_byte2_scalar
|
||||
|
||||
// Return the index at which either a or b first occurs in text. If neither is
|
||||
// found -1 is returned.
|
||||
var IndexByte2String func(text string, a, b byte) int = index_byte2_string_scalar
|
||||
|
||||
// Return the index at which the first C0 byte is found or -1 when no such bytes are present.
|
||||
var IndexC0 func(data []byte) int = index_c0_scalar
|
||||
|
||||
// Return the index at which the first C0 byte is found or -1 when no such bytes are present.
|
||||
var IndexC0String func(data string) int = index_c0_string_scalar
|
||||
|
||||
// Return the index of the first byte in data that is not equal to b. If all bytes equal b, -1 is returned.
|
||||
var NotIndexByte func(data []byte, b byte) int = not_index_byte_scalar
|
||||
|
||||
// Return the index of the first byte in text that is not equal to b. If all bytes equal b, -1 is returned.
|
||||
var NotIndexByteString func(text string, b byte) int = not_index_byte_string_scalar
|
||||
|
||||
// Return the index of the first byte in data that is neither a nor b. If all bytes are a or b, -1 is returned.
|
||||
var NotIndexByte2 func(data []byte, a, b byte) int = not_index_byte2_scalar
|
||||
|
||||
// Return the index of the first byte in text that is neither a nor b. If all bytes are a or b, -1 is returned.
|
||||
var NotIndexByte2String func(text string, a, b byte) int = not_index_byte2_string_scalar
|
||||
|
||||
func init() {
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
if cpu.Initialized {
|
||||
Have128bit = cpu.X86.HasSSE42 && HasSIMD128Code
|
||||
Have256bit = cpu.X86.HasAVX2 && HasSIMD256Code
|
||||
}
|
||||
case "arm64":
|
||||
Have128bit = HasSIMD128Code
|
||||
Have256bit = HasSIMD256Code
|
||||
}
|
||||
if Have256bit {
|
||||
IndexByte = index_byte_asm_256
|
||||
IndexByteString = index_byte_string_asm_256
|
||||
IndexByte2 = index_byte2_asm_256
|
||||
IndexByte2String = index_byte2_string_asm_256
|
||||
IndexC0 = index_c0_asm_256
|
||||
IndexC0String = index_c0_string_asm_256
|
||||
NotIndexByte = not_index_byte_asm_256
|
||||
NotIndexByteString = not_index_byte_string_asm_256
|
||||
NotIndexByte2 = not_index_byte2_asm_256
|
||||
NotIndexByte2String = not_index_byte2_string_asm_256
|
||||
VectorSize = 32
|
||||
} else if Have128bit {
|
||||
IndexByte = index_byte_asm_128
|
||||
IndexByteString = index_byte_string_asm_128
|
||||
IndexByte2 = index_byte2_asm_128
|
||||
IndexByte2String = index_byte2_string_asm_128
|
||||
IndexC0 = index_c0_asm_128
|
||||
IndexC0String = index_c0_string_asm_128
|
||||
NotIndexByte = not_index_byte_asm_128
|
||||
NotIndexByteString = not_index_byte_string_asm_128
|
||||
NotIndexByte2 = not_index_byte2_asm_128
|
||||
NotIndexByte2String = not_index_byte2_string_asm_128
|
||||
VectorSize = 16
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package simdstring
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func test_load(src []byte) []byte {
|
||||
ans := make([]byte, len(src))
|
||||
if len(src) == 16 {
|
||||
test_load_asm_128(src, ans)
|
||||
} else {
|
||||
test_load_asm_256(src, ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func test_set1_epi8(b byte, sz int) []byte {
|
||||
ans := make([]byte, sz)
|
||||
if sz == 16 {
|
||||
test_set1_epi8_asm_128(b, ans)
|
||||
} else {
|
||||
test_set1_epi8_asm_256(b, ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func test_cmpeq_epi8(a, b []byte) []byte {
|
||||
ans := make([]byte, len(a))
|
||||
if len(ans) == 16 {
|
||||
test_cmpeq_epi8_asm_128(a, b, ans)
|
||||
} else {
|
||||
test_cmpeq_epi8_asm_256(a, b, ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func test_cmplt_epi8(t *testing.T, a, b []byte) []byte {
|
||||
ans := make([]byte, len(a))
|
||||
var prev []byte
|
||||
for which := range 3 {
|
||||
if len(ans) == 16 {
|
||||
test_cmplt_epi8_asm_128(a, b, which, ans)
|
||||
} else {
|
||||
test_cmplt_epi8_asm_256(a, b, which, ans)
|
||||
}
|
||||
if prev != nil {
|
||||
if s := cmp.Diff(prev, ans); s != "" {
|
||||
t.Fatalf("cmplt returned different result for which=%d\n%s", which, s)
|
||||
}
|
||||
}
|
||||
prev = bytes.Clone(ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func test_or(a, b []byte) []byte {
|
||||
ans := make([]byte, len(a))
|
||||
if len(ans) == 16 {
|
||||
test_or_asm_128(a, b, ans)
|
||||
} else {
|
||||
test_or_asm_256(a, b, ans)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func test_jump_if_zero(a []byte) int {
|
||||
if len(a) == 16 {
|
||||
return test_jump_if_zero_asm_128(a)
|
||||
}
|
||||
return test_jump_if_zero_asm_256(a)
|
||||
}
|
||||
|
||||
func test_count_to_match(a []byte, b byte) int {
|
||||
if len(a) == 16 {
|
||||
return test_count_to_match_asm_128(a, b)
|
||||
}
|
||||
return test_count_to_match_asm_256(a, b)
|
||||
}
|
||||
|
||||
func ordered_bytes(size int) []byte {
|
||||
ans := make([]byte, size)
|
||||
for i := range ans {
|
||||
ans[i] = byte(i)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func broadcast_byte(b byte, size int) []byte {
|
||||
return bytes.Repeat([]byte{b}, size)
|
||||
}
|
||||
|
||||
func get_sizes(t *testing.T) []int {
|
||||
sizes := []int{}
|
||||
if Have128bit {
|
||||
sizes = append(sizes, 16)
|
||||
}
|
||||
if Have256bit {
|
||||
sizes = append(sizes, 32)
|
||||
}
|
||||
|
||||
if len(sizes) == 0 {
|
||||
t.Skip("skipping as no SIMD available at runtime")
|
||||
}
|
||||
return sizes
|
||||
}
|
||||
|
||||
func addressof_data(b []byte) uintptr {
|
||||
return uintptr(unsafe.Pointer(&b[0]))
|
||||
}
|
||||
|
||||
func memset(ans []byte, val byte) {
|
||||
for i := range ans {
|
||||
ans[i] = val
|
||||
}
|
||||
}
|
||||
|
||||
func aligned_slice(sz, alignment int) ([]byte, []byte) {
|
||||
ans := make([]byte, sz+alignment+512)
|
||||
a := addressof_data(ans)
|
||||
a &= uintptr(alignment - 1)
|
||||
extra := uintptr(alignment) - a
|
||||
memset(ans, '<')
|
||||
memset(ans[extra+uintptr(sz):], '>')
|
||||
return ans[extra : extra+uintptr(sz)], ans
|
||||
}
|
||||
|
||||
func TestSIMDStringOps(t *testing.T) {
|
||||
sizes := get_sizes(t)
|
||||
test := func(haystack []byte, a, b byte, align_offset int) {
|
||||
var actual int
|
||||
sh, _ := aligned_slice(len(haystack)+align_offset, 64)
|
||||
sh = sh[align_offset:]
|
||||
copy(sh, haystack)
|
||||
haystack = sh
|
||||
expected := index_byte2_scalar(haystack, a, b)
|
||||
|
||||
for _, sz := range sizes {
|
||||
switch sz {
|
||||
case 16:
|
||||
actual = index_byte2_asm_128(haystack, a, b)
|
||||
case 32:
|
||||
actual = index_byte2_asm_256(haystack, a, b)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("Failed to find '%c' or '%c' in: %#v at align: %d (expected: %d != actual: %d) at size: %d",
|
||||
a, b, string(haystack), addressof_data(haystack)&uintptr(sz-1), expected, actual, sz)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// test alignment issues
|
||||
q := []byte("abc")
|
||||
for sz := range 32 {
|
||||
test(q, '<', '>', sz)
|
||||
test(q, ' ', 'b', sz)
|
||||
test(q, '<', 'a', sz)
|
||||
test(q, '<', 'b', sz)
|
||||
test(q, 'c', '>', sz)
|
||||
}
|
||||
|
||||
tests := func(h string, a, b byte) {
|
||||
for _, sz := range []int{0, 16, 32, 64, 79} {
|
||||
q := strings.Repeat(" ", sz) + h
|
||||
for sz := range 32 {
|
||||
test([]byte(q), a, b, sz)
|
||||
}
|
||||
}
|
||||
}
|
||||
test(nil, '<', '>', 1)
|
||||
test([]byte{}, '<', '>', 1)
|
||||
|
||||
tests("", '<', '>')
|
||||
tests("a", 0, 0)
|
||||
tests("a", '<', '>')
|
||||
tests("dsdfsfa", '1', 'a')
|
||||
tests("xa", 'a', 'a')
|
||||
tests("bbb", 'a', '1')
|
||||
tests("bba", 'a', '<')
|
||||
tests("baa", '>', 'a')
|
||||
|
||||
c0test := func(haystack []byte) {
|
||||
var actual int
|
||||
safe_haystack := append(bytes.Repeat([]byte{'<'}, 64), haystack...)
|
||||
safe_haystack = append(safe_haystack, bytes.Repeat([]byte{'>'}, 64)...)
|
||||
haystack = safe_haystack[64 : 64+len(haystack)]
|
||||
expected := index_c0_scalar(haystack)
|
||||
|
||||
for _, sz := range sizes {
|
||||
switch sz {
|
||||
case 16:
|
||||
actual = index_c0_asm_128(haystack)
|
||||
case 32:
|
||||
actual = index_c0_asm_256(haystack)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("C0 char index failed in: %#v (%d != %d) at size: %d", string(haystack), expected, actual, sz)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
c0tests := func(h string) {
|
||||
c0test([]byte(h))
|
||||
for _, sz := range []int{16, 32, 64, 79} {
|
||||
q := strings.Repeat(" ", sz) + h
|
||||
c0test([]byte(q))
|
||||
}
|
||||
}
|
||||
|
||||
c0tests("a\nfgdfgd\r")
|
||||
c0tests("")
|
||||
c0tests("abcdef")
|
||||
c0tests("afsgdfg\x7f")
|
||||
c0tests("afgd\x1bfgd\t")
|
||||
c0tests("a\x00")
|
||||
|
||||
index_test := func(haystack []byte, needle byte) {
|
||||
var actual int
|
||||
expected := index_byte_scalar(haystack, needle)
|
||||
|
||||
for _, sz := range sizes {
|
||||
switch sz {
|
||||
case 16:
|
||||
actual = index_byte_asm_128(haystack, needle)
|
||||
case 32:
|
||||
actual = index_byte_asm_256(haystack, needle)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("index failed in: %#v (%d != %d) at size: %d with needle: %#v", string(haystack), expected, actual, sz, needle)
|
||||
}
|
||||
}
|
||||
}
|
||||
index_test([]byte("abc"), 'x')
|
||||
index_test([]byte("abc"), 'b')
|
||||
|
||||
not_index_test := func(haystack []byte, needle byte) {
|
||||
var actual int
|
||||
expected := not_index_byte_scalar(haystack, needle)
|
||||
|
||||
for _, sz := range sizes {
|
||||
switch sz {
|
||||
case 16:
|
||||
actual = not_index_byte_asm_128(haystack, needle)
|
||||
case 32:
|
||||
actual = not_index_byte_asm_256(haystack, needle)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("not_index failed in: %#v (%d != %d) at size: %d with needle: %#v", string(haystack), expected, actual, sz, needle)
|
||||
}
|
||||
}
|
||||
}
|
||||
not_index_test(nil, 'a')
|
||||
not_index_test([]byte{}, 'a')
|
||||
not_index_test([]byte("aaa"), 'a')
|
||||
not_index_test([]byte("aaab"), 'a')
|
||||
not_index_test([]byte("baaa"), 'a')
|
||||
not_index_test([]byte("abc"), 'a')
|
||||
for _, sz := range []int{0, 16, 32, 64, 79} {
|
||||
q := strings.Repeat("a", sz) + "b"
|
||||
not_index_test([]byte(q), 'a')
|
||||
not_index_test([]byte(q), 'b')
|
||||
not_index_test([]byte(strings.Repeat("a", sz)), 'a')
|
||||
}
|
||||
|
||||
not_index2_test := func(haystack []byte, a, b byte) {
|
||||
var actual int
|
||||
expected := not_index_byte2_scalar(haystack, a, b)
|
||||
|
||||
for _, sz := range sizes {
|
||||
switch sz {
|
||||
case 16:
|
||||
actual = not_index_byte2_asm_128(haystack, a, b)
|
||||
case 32:
|
||||
actual = not_index_byte2_asm_256(haystack, a, b)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("not_index2 failed in: %#v (%d != %d) at size: %d with needles: %#v %#v", string(haystack), expected, actual, sz, a, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
not_index2_test(nil, 'a', 'b')
|
||||
not_index2_test([]byte{}, 'a', 'b')
|
||||
not_index2_test([]byte("aabb"), 'a', 'b')
|
||||
not_index2_test([]byte("aabbc"), 'a', 'b')
|
||||
not_index2_test([]byte("caabb"), 'a', 'b')
|
||||
for _, sz := range []int{0, 16, 32, 64, 79} {
|
||||
q := strings.Repeat("ab", sz) + "c"
|
||||
not_index2_test([]byte(q), 'a', 'b')
|
||||
not_index2_test([]byte(strings.Repeat("ab", sz)), 'a', 'b')
|
||||
for align := range 32 {
|
||||
not_index2_test([]byte(strings.Repeat(" ", align)+q), 'a', 'b')
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestIntrinsics(t *testing.T) {
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
if !HasSIMD128Code {
|
||||
t.Fatal("SIMD 128bit code not built")
|
||||
}
|
||||
if !HasSIMD256Code {
|
||||
t.Fatal("SIMD 256bit code not built")
|
||||
}
|
||||
case "arm64":
|
||||
if !HasSIMD128Code {
|
||||
t.Fatal("SIMD 128bit code not built")
|
||||
}
|
||||
if !Have128bit {
|
||||
t.Fatal("SIMD 128bit support not available at runtime")
|
||||
}
|
||||
}
|
||||
ae := func(sz int, func_name string, a, b any) {
|
||||
if s := cmp.Diff(a, b); s != "" {
|
||||
t.Fatalf("%s failed with size: %d\n%s", func_name, sz, s)
|
||||
}
|
||||
}
|
||||
tests := []func(int){}
|
||||
|
||||
tests = append(tests, func(sz int) {
|
||||
a := ordered_bytes(sz)
|
||||
ae(sz, `load_test`, a, test_load(a))
|
||||
})
|
||||
tests = append(tests, func(sz int) {
|
||||
for _, b := range []byte{1, 0b110111, 0xff, 0, ' '} {
|
||||
ae(sz, `set1_epi8_test`, broadcast_byte(b, sz), test_set1_epi8(b, sz))
|
||||
}
|
||||
ae(sz, `set1_epi8_test`, broadcast_byte(0xff, sz), test_set1_epi8(11, sz))
|
||||
})
|
||||
tests = append(tests, func(sz int) {
|
||||
a := ordered_bytes(sz)
|
||||
b := ordered_bytes(sz)
|
||||
ans := test_cmpeq_epi8(a, b)
|
||||
ae(sz, `cmpeq_epi8_test`, broadcast_byte(0xff, sz), ans)
|
||||
|
||||
lt := func(a, b []byte) []byte {
|
||||
ans := make([]byte, len(a))
|
||||
for i := range ans {
|
||||
if int8(a[i]) < int8(b[i]) {
|
||||
ans[i] = 0xff
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
ae(sz, "cmplt_epi8_test with equal vecs of non-negative numbers", lt(a, b), test_cmplt_epi8(t, a, b))
|
||||
a = broadcast_byte(1, sz)
|
||||
b = broadcast_byte(2, sz)
|
||||
ae(sz, "cmplt_epi8_test with 1 and 2", lt(a, b), test_cmplt_epi8(t, a, b))
|
||||
ae(sz, "cmplt_epi8_test with 2 and 1", lt(b, a), test_cmplt_epi8(t, b, a))
|
||||
a = broadcast_byte(0xff, sz)
|
||||
b = broadcast_byte(0, sz)
|
||||
ae(sz, "cmplt_epi8_test with -1 and 0", lt(a, b), test_cmplt_epi8(t, a, b))
|
||||
})
|
||||
tests = append(tests, func(sz int) {
|
||||
a := make([]byte, sz)
|
||||
b := make([]byte, sz)
|
||||
c := make([]byte, sz)
|
||||
a[0] = 0xff
|
||||
b[0] = 0xff
|
||||
b[1] = 0xff
|
||||
a[sz-1] = 1
|
||||
b[sz-1] = 2
|
||||
for i := range c {
|
||||
c[i] = a[i] | b[i]
|
||||
}
|
||||
ans := test_or(a, b)
|
||||
ae(sz, `or_test`, c, ans)
|
||||
})
|
||||
|
||||
tests = append(tests, func(sz int) {
|
||||
a := make([]byte, sz)
|
||||
if e := test_jump_if_zero(a); e != 0 {
|
||||
t.Fatalf("Did not detect zero register")
|
||||
}
|
||||
for i := range sz {
|
||||
a = make([]byte, sz)
|
||||
a[i] = 1
|
||||
if e := test_jump_if_zero(a); e != 1 {
|
||||
t.Fatalf("Did not detect non-zero register")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
tests = append(tests, func(sz int) {
|
||||
a := ordered_bytes(sz)
|
||||
if e := test_count_to_match(a, 77); e != -1 {
|
||||
t.Fatalf("Unexpectedly found byte at: %d", e)
|
||||
}
|
||||
for i := range sz {
|
||||
if e := test_count_to_match(a, byte(i)); e != i {
|
||||
t.Fatalf("Failed to find the byte: %d (%d != %d)", i, i, e)
|
||||
}
|
||||
}
|
||||
a[7] = 0x34
|
||||
if e := test_count_to_match(a, 0x34); e != 7 {
|
||||
t.Fatalf("Failed to find the byte: %d (%d != %d)", 0x34, 7, e)
|
||||
}
|
||||
})
|
||||
|
||||
sizes := get_sizes(t)
|
||||
for _, sz := range sizes {
|
||||
for _, test := range tests {
|
||||
test(sz)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package simdstring
|
||||
|
||||
func index_byte_scalar(data []byte, b byte) int {
|
||||
for i, ch := range data {
|
||||
if ch == b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func index_byte_string_scalar(data string, b byte) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if data[i] == b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func index_byte2_scalar(data []byte, a, b byte) int {
|
||||
for i, ch := range data {
|
||||
switch ch {
|
||||
case a, b:
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func index_byte2_string_scalar(data string, a, b byte) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
switch data[i] {
|
||||
case a, b:
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func index_c0_scalar(data []byte) int {
|
||||
for i := range data {
|
||||
if data[i] == 0x7f || data[i] < ' ' {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func index_c0_string_scalar(data string) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if data[i] == 0x7f || data[i] < ' ' {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func not_index_byte_scalar(data []byte, b byte) int {
|
||||
for i, ch := range data {
|
||||
if ch != b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func not_index_byte_string_scalar(data string, b byte) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if data[i] != b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func not_index_byte2_scalar(data []byte, a, b byte) int {
|
||||
for i, ch := range data {
|
||||
if ch != a && ch != b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func not_index_byte2_string_scalar(data string, a, b byte) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if data[i] != a && data[i] != b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# test.sh
|
||||
# Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
#
|
||||
# Distributed under terms of the MIT license.
|
||||
#
|
||||
|
||||
echo -e "\x1b[32mtesting amd64\x1b[m" && go test -v &&
|
||||
echo -e "\x1b[32mtesting arm64\x1b[m" && GOARCH=arm64 go test -v -exec qemu-aarch64-static
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,209 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package themes
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestThemeCollections(t *testing.T) {
|
||||
for fname, expected := range map[string]string{
|
||||
"moose": "Moose",
|
||||
"mooseCat": "Moose Cat",
|
||||
"a_bC": "A B C",
|
||||
} {
|
||||
actual := ThemeNameFromFileName(fname)
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Unexpected theme name for %s:\n%s", fname, diff)
|
||||
}
|
||||
}
|
||||
|
||||
tdir := t.TempDir()
|
||||
|
||||
pt := func(expected ThemeMetadata, lines ...string) {
|
||||
if err := os.WriteFile(filepath.Join(tdir, "temp.conf"), []byte(strings.Join(lines, "\n")), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, _, err := ParseThemeMetadata(filepath.Join(tdir, "temp.conf"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff := cmp.Diff(&expected, actual); diff != "" {
|
||||
t.Fatalf("Failed to parse:\n%s\n\n%s", strings.Join(lines, "\n"), diff)
|
||||
}
|
||||
}
|
||||
pt(ThemeMetadata{Name: "XYZ", Blurb: "a b", Author: "A", Is_dark: true, Num_settings: 2},
|
||||
"# some crap", " ", "## ", "## author: A", "## name: XYZ", "## blurb: a", "## b", "", "color red", "background black", "include inc.conf")
|
||||
if err := os.WriteFile(filepath.Join(tdir, "inc.conf"), []byte("background white"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pt(ThemeMetadata{Name: "XYZ", Blurb: "a b", Author: "A", Num_settings: 2},
|
||||
"# some crap", " ", "## ", "## author: A", "## name: XYZ", "## blurb: a", "## b", "", "color red", "background black", "include inc.conf")
|
||||
|
||||
buf := bytes.Buffer{}
|
||||
zw := zip.NewWriter(&buf)
|
||||
fw, _ := zw.Create("x/themes.json")
|
||||
if _, err := fw.Write([]byte(`[
|
||||
{
|
||||
"author": "X Y",
|
||||
"blurb": "A dark color scheme for the kitty terminal.",
|
||||
"file": "themes/Alabaster_Dark.conf",
|
||||
"is_dark": true,
|
||||
"license": "MIT",
|
||||
"name": "Alabaster Dark",
|
||||
"num_settings": 30,
|
||||
"upstream": "https://xxx.com"
|
||||
},
|
||||
{
|
||||
"name": "Empty", "file": "empty.conf"
|
||||
}
|
||||
]`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fw, _ = zw.Create("x/empty.conf")
|
||||
if _, err := fw.Write([]byte("empty")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fw, _ = zw.Create("x/themes/Alabaster_Dark.conf")
|
||||
if _, err := fw.Write([]byte("alabaster")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
zw.Close()
|
||||
|
||||
received_etag := ""
|
||||
request_count := 0
|
||||
send_count := 0
|
||||
check_etag := true
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
request_count++
|
||||
received_etag = r.Header.Get("If-None-Match")
|
||||
if check_etag && received_etag == `"xxx"` {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
send_count++
|
||||
w.Header().Add("ETag", `"xxx"`)
|
||||
w.Write(buf.Bytes())
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
if _, err := fetch_cached("test", ts.URL, tdir, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := zip.OpenReader(filepath.Join(tdir, "test.zip"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var jm JSONMetadata
|
||||
err = json.Unmarshal([]byte(r.Comment), &jm)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if jm.Etag != `"xxx"` {
|
||||
t.Fatalf("Unexpected ETag: %#v", jm.Etag)
|
||||
}
|
||||
_, err = fetch_cached("test", ts.URL, tdir, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request_count != 1 {
|
||||
t.Fatalf("Cached zip file was not used: %d", request_count)
|
||||
}
|
||||
_, err = fetch_cached("test", ts.URL, tdir, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request_count != 2 {
|
||||
t.Fatalf("Cached zip file was incorrectly used: %d", request_count)
|
||||
}
|
||||
if received_etag != `"xxx"` {
|
||||
t.Fatalf("Got invalid ETag: %#v", received_etag)
|
||||
}
|
||||
if send_count != 1 {
|
||||
t.Fatalf("Cached zip file was incorrectly re-downloaded: %d", send_count)
|
||||
}
|
||||
check_etag = false
|
||||
_, err = fetch_cached("test", ts.URL, tdir, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if send_count != 2 {
|
||||
t.Fatalf("Cached zip file was incorrectly not re-downloaded. %d", send_count)
|
||||
}
|
||||
coll := Themes{name_map: map[string]*Theme{}}
|
||||
closer, err := coll.add_from_zip_file(filepath.Join(tdir, "test.zip"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closer.Close()
|
||||
if code, err := coll.ThemeByName("Empty").load_code(); code != "empty" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Fatal("failed to load code for empty theme")
|
||||
}
|
||||
if code, err := coll.ThemeByName("Alabaster Dark").load_code(); code != "alabaster" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Fatal("failed to load code for alabaster theme")
|
||||
}
|
||||
}
|
||||
|
||||
func TestColorSettingsAsEscapeCodes(t *testing.T) {
|
||||
ans := ColorSettingsAsEscapeCodes(map[string]string{"color1": "#ff0000", "color17": "#00ff00"})
|
||||
for _, q := range []string{";1;#ff0000;", ";17;#00ff00;", ";16;#000000;", ";255;#eeeeee\x1b\\"} {
|
||||
if !strings.Contains(ans, q) {
|
||||
t.Fatalf("%#v not found in %#v", q, ans)
|
||||
}
|
||||
}
|
||||
if strings.Contains(ans, ";16;#ffffff") {
|
||||
t.Fatalf("Unset color 16 was set to white: %#v", ans)
|
||||
}
|
||||
_, osc21, found := strings.Cut(ans, "\x1b]21;")
|
||||
if !found {
|
||||
t.Fatalf("No OSC 21 in %#v", ans)
|
||||
}
|
||||
if !strings.HasPrefix(osc21, "16=;18=;") || !strings.HasSuffix(osc21, ";255=\x1b\\") || strings.Contains(osc21, ";17=") {
|
||||
t.Fatalf("Incorrect OSC 21: %#v", osc21)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColorSettingsAsSpec(t *testing.T) {
|
||||
settings := map[string]string{"color1": "#ff0000", "color17": "#00ff00", "background": "#010203", "cursor": "", "foreground": "invalid"}
|
||||
ans := ColorSettingsAsSpec(settings)
|
||||
expected := map[string]any{"background": uint32(0x010203), "color1": uint32(0xff0000), "color17": uint32(0x00ff00), "color16": nil, "color255": nil}
|
||||
for k, v := range expected {
|
||||
if actual, found := ans[k]; !found || actual != v {
|
||||
t.Fatalf("Incorrect value for %s: %#v != %#v", k, actual, v)
|
||||
}
|
||||
}
|
||||
// colors reset to their configured value by the escape codes are not present
|
||||
for _, k := range []string{"cursor", "foreground"} {
|
||||
if _, found := ans[k]; found {
|
||||
t.Fatalf("%s should not be present in %#v", k, ans)
|
||||
}
|
||||
}
|
||||
// colors not specified by the theme get the same defaults as with escape codes
|
||||
if ans["selection_background"] != uint32(0xfffacd) || ans["color0"] != uint32(0) || len(ans) != 256+3 {
|
||||
t.Fatalf("Incorrect default colors in: %#v", ans)
|
||||
}
|
||||
if codes := ColorSettingsAsEscapeCodes(settings); !strings.Contains(codes, "\x1b]11;#010203\x1b\\") || !strings.Contains(codes, "\x1b]112\x1b\\") ||
|
||||
!strings.Contains(codes, "\x1b]4;0;#000000;") {
|
||||
t.Fatalf("Escape codes not consistent with spec: %#v", codes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tty
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
TCSANOW = 0
|
||||
TCSADRAIN = 1
|
||||
TCSAFLUSH = 2
|
||||
)
|
||||
|
||||
type Term struct {
|
||||
os_file *os.File
|
||||
states []unix.Termios
|
||||
}
|
||||
|
||||
func eintr_retry_noret(f func() error) error {
|
||||
for {
|
||||
qerr := f()
|
||||
if qerr == unix.EINTR {
|
||||
continue
|
||||
}
|
||||
return qerr
|
||||
}
|
||||
}
|
||||
|
||||
func eintr_retry_intret(f func() (int, error)) (int, error) {
|
||||
for {
|
||||
q, qerr := f()
|
||||
if qerr == unix.EINTR {
|
||||
continue
|
||||
}
|
||||
return q, qerr
|
||||
}
|
||||
}
|
||||
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var t unix.Termios
|
||||
err := eintr_retry_noret(func() error { return Tcgetattr(int(fd), &t) })
|
||||
return err == nil
|
||||
}
|
||||
|
||||
type TermiosOperation func(t *unix.Termios)
|
||||
|
||||
func get_vmin_and_vtime(d time.Duration) (uint8, uint8) {
|
||||
if d > 0 {
|
||||
// VTIME is expressed in terms of deciseconds
|
||||
vtimeDeci := d.Milliseconds() / 100
|
||||
// ensure valid range
|
||||
vtime := uint8(clamp(vtimeDeci, 1, 0xff))
|
||||
return 0, vtime
|
||||
}
|
||||
// block indefinitely until we receive at least 1 byte
|
||||
return 1, 0
|
||||
}
|
||||
|
||||
func SetReadTimeout(d time.Duration) TermiosOperation {
|
||||
vmin, vtime := get_vmin_and_vtime(d)
|
||||
return func(t *unix.Termios) {
|
||||
t.Cc[unix.VMIN] = vmin
|
||||
t.Cc[unix.VTIME] = vtime
|
||||
}
|
||||
}
|
||||
|
||||
var SetBlockingRead TermiosOperation = SetReadTimeout(0)
|
||||
|
||||
var SetNoCanonical TermiosOperation = func(t *unix.Termios) {
|
||||
t.Lflag &^= unix.ICANON
|
||||
}
|
||||
|
||||
var SetRaw TermiosOperation = func(t *unix.Termios) {
|
||||
// This attempts to replicate the behaviour documented for cfmakeraw in
|
||||
// the termios(3) manpage, as Go doesn't wrap cfmakeraw probably because its not in POSIX
|
||||
t.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
|
||||
t.Oflag &^= unix.OPOST
|
||||
t.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
|
||||
t.Cflag &^= unix.CSIZE | unix.PARENB
|
||||
t.Cflag |= unix.CS8
|
||||
t.Cc[unix.VMIN] = 1
|
||||
t.Cc[unix.VTIME] = 0
|
||||
}
|
||||
var SetNoEcho TermiosOperation = func(t *unix.Termios) {
|
||||
t.Lflag &^= unix.ECHO
|
||||
}
|
||||
|
||||
var SetReadPassword TermiosOperation = func(t *unix.Termios) {
|
||||
t.Lflag &^= unix.ECHO
|
||||
t.Lflag |= unix.ISIG
|
||||
t.Lflag &^= unix.ICANON
|
||||
t.Iflag |= unix.ICRNL
|
||||
t.Cc[unix.VMIN] = 1
|
||||
t.Cc[unix.VTIME] = 0
|
||||
}
|
||||
|
||||
func WrapTerm(fd int, name string, operations ...TermiosOperation) (self *Term, err error) {
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("<fd: %d>", fd)
|
||||
}
|
||||
os_file := os.NewFile(uintptr(fd), name)
|
||||
if os_file == nil {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
self = &Term{os_file: os_file}
|
||||
err = self.ApplyOperations(TCSANOW, operations...)
|
||||
if err != nil {
|
||||
self.Close()
|
||||
self = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func OpenTerm(name string, operations ...TermiosOperation) (self *Term, err error) {
|
||||
fd, err := eintr_retry_intret(func() (int, error) {
|
||||
return unix.Open(name, unix.O_NOCTTY|unix.O_CLOEXEC|unix.O_NDELAY|unix.O_RDWR, 0666)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, &os.PathError{Op: "open", Path: name, Err: err}
|
||||
}
|
||||
self, err = WrapTerm(fd, name, operations...)
|
||||
return
|
||||
}
|
||||
|
||||
func OpenControllingTerm(operations ...TermiosOperation) (self *Term, err error) {
|
||||
return OpenTerm(Ctermid(), operations...)
|
||||
}
|
||||
|
||||
func (self *Term) Fd() int {
|
||||
if self.os_file == nil {
|
||||
return -1
|
||||
}
|
||||
return int(self.os_file.Fd())
|
||||
}
|
||||
|
||||
func (self *Term) Close() error {
|
||||
if self.os_file == nil {
|
||||
return nil
|
||||
}
|
||||
err := eintr_retry_noret(func() error { return self.os_file.Close() })
|
||||
self.os_file = nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *Term) WasEchoOnOriginally() bool {
|
||||
if len(self.states) > 0 {
|
||||
return self.states[0].Lflag&unix.ECHO != 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Term) Tcgetattr(ans *unix.Termios) error {
|
||||
return eintr_retry_noret(func() error { return Tcgetattr(self.Fd(), ans) })
|
||||
}
|
||||
|
||||
func (self *Term) Tcsetattr(when uintptr, ans *unix.Termios) error {
|
||||
return eintr_retry_noret(func() error { return Tcsetattr(self.Fd(), when, ans) })
|
||||
}
|
||||
|
||||
func (self *Term) set_termios_attrs(when uintptr, modify func(*unix.Termios)) (err error) {
|
||||
var state unix.Termios
|
||||
if err = self.Tcgetattr(&state); err != nil {
|
||||
return
|
||||
}
|
||||
new_state := state
|
||||
modify(&new_state)
|
||||
if err = self.Tcsetattr(when, &new_state); err == nil {
|
||||
self.states = append(self.states, state)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Term) ApplyOperations(when uintptr, operations ...TermiosOperation) (err error) {
|
||||
if len(operations) == 0 {
|
||||
return
|
||||
}
|
||||
return self.set_termios_attrs(when, func(t *unix.Termios) {
|
||||
for _, op := range operations {
|
||||
op(t)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (self *Term) PopStateWhen(when uintptr) (err error) {
|
||||
if len(self.states) == 0 {
|
||||
return nil
|
||||
}
|
||||
idx := len(self.states) - 1
|
||||
if err = self.Tcsetattr(when, &self.states[idx]); err == nil {
|
||||
self.states = self.states[:idx]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Term) PopState() error {
|
||||
return self.PopStateWhen(TCSAFLUSH)
|
||||
}
|
||||
|
||||
func (self *Term) RestoreWhen(when uintptr) (err error) {
|
||||
if len(self.states) == 0 {
|
||||
return nil
|
||||
}
|
||||
self.states = self.states[:1]
|
||||
return self.PopStateWhen(when)
|
||||
}
|
||||
|
||||
func (self *Term) Restore() error {
|
||||
return self.RestoreWhen(TCSAFLUSH)
|
||||
}
|
||||
|
||||
func (self *Term) RestoreAndClose() error {
|
||||
_ = self.Restore()
|
||||
return self.Close()
|
||||
}
|
||||
|
||||
func (self *Term) Suspend() (resume func() error, err error) {
|
||||
var state unix.Termios
|
||||
err = self.Tcgetattr(&state)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(self.states) > 0 {
|
||||
err := self.Tcsetattr(TCSANOW, &self.states[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return func() error { return self.Tcsetattr(TCSANOW, &state) }, nil
|
||||
|
||||
}
|
||||
|
||||
func (self *Term) SuspendAndRun(callback func() error) error {
|
||||
resume, err := self.Suspend()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = callback()
|
||||
if rerr := resume(); rerr != nil {
|
||||
err = rerr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func clamp(v, lo, hi int64) int64 {
|
||||
if v < lo {
|
||||
return lo
|
||||
}
|
||||
if v > hi {
|
||||
return hi
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (self *Term) ReadWithTimeout(b []byte, d time.Duration) (n int, err error) {
|
||||
var read, write, in_err unix.FdSet
|
||||
pselect := func() (int, error) {
|
||||
read.Zero()
|
||||
write.Zero()
|
||||
in_err.Zero()
|
||||
read.Set(self.Fd())
|
||||
return utils.Select(self.Fd()+1, &read, &write, &in_err, d)
|
||||
}
|
||||
num_ready, err := pselect()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if num_ready == 0 {
|
||||
err = os.ErrDeadlineExceeded
|
||||
return 0, err
|
||||
}
|
||||
for {
|
||||
n, err = self.Read(b)
|
||||
if errors.Is(err, unix.EINTR) {
|
||||
continue
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
func is_temporary_read_error(err error) bool {
|
||||
return errors.Is(err, unix.EINTR) || errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EWOULDBLOCK)
|
||||
}
|
||||
|
||||
func (self *Term) Read(b []byte) (n int, err error) {
|
||||
for {
|
||||
n, err = self.os_file.Read(b)
|
||||
// On macOS we get EAGAIN if another thread is writing to the tty at the same time
|
||||
if err != nil && is_temporary_read_error(err) && n <= 0 {
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Term) Write(b []byte) (int, error) {
|
||||
return self.os_file.Write(b)
|
||||
}
|
||||
|
||||
func is_temporary_error(err error) bool {
|
||||
return errors.Is(err, unix.EINTR) || errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, io.ErrShortWrite)
|
||||
}
|
||||
|
||||
func (self *Term) WriteAll(b []byte) error {
|
||||
for len(b) > 0 {
|
||||
n, err := self.os_file.Write(b)
|
||||
if err != nil && !is_temporary_error(err) {
|
||||
return err
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Term) WriteAllString(s string) error {
|
||||
return self.WriteAll(utils.UnsafeStringToBytes(s))
|
||||
}
|
||||
|
||||
func (self *Term) WriteString(b string) (int, error) {
|
||||
return self.os_file.WriteString(b)
|
||||
}
|
||||
|
||||
func (self *Term) DebugPrintln(a ...any) {
|
||||
msg := fmt.Appendln(nil, a...)
|
||||
const limit = 2048
|
||||
encoded := make([]byte, limit*2)
|
||||
for i := 0; i < len(msg); i += limit {
|
||||
end := min(i+limit, len(msg))
|
||||
chunk := msg[i:end]
|
||||
encoded = encoded[:cap(encoded)]
|
||||
base64.StdEncoding.Encode(encoded, chunk)
|
||||
_, _ = self.WriteString("\x1bP@kitty-print|")
|
||||
_, _ = self.Write(encoded)
|
||||
_, _ = self.WriteString("\x1b\\")
|
||||
}
|
||||
}
|
||||
|
||||
func GetSize(fd int) (*unix.Winsize, error) {
|
||||
for {
|
||||
sz, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
|
||||
if err != unix.EINTR {
|
||||
return sz, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Term) GetSize() (*unix.Winsize, error) {
|
||||
return GetSize(self.Fd())
|
||||
}
|
||||
|
||||
// go doesn't have a wrapper for ctermid()
|
||||
func Ctermid() string { return "/dev/tty" }
|
||||
|
||||
var KittyStdout = sync.OnceValue(func() *os.File {
|
||||
if fds := os.Getenv(`KITTY_STDIO_FORWARDED`); fds != "" {
|
||||
if fd, err := strconv.Atoi(fds); err == nil && fd > -1 {
|
||||
if f := os.NewFile(uintptr(fd), "<kitty_stdout>"); f != nil {
|
||||
return f
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
func DebugPrintln(a ...any) {
|
||||
if f := KittyStdout(); f != nil {
|
||||
fmt.Fprintln(f, a...)
|
||||
return
|
||||
}
|
||||
term, err := OpenControllingTerm()
|
||||
if err == nil {
|
||||
defer term.Close()
|
||||
term.DebugPrintln(a...)
|
||||
}
|
||||
}
|
||||
|
||||
func ReadSingleByteFromTerminal() (b byte, err error) {
|
||||
term, err := OpenControllingTerm(SetBlockingRead, SetNoCanonical)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer term.Close()
|
||||
ans := []byte{b}
|
||||
for {
|
||||
n, err := term.Read(ans)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if n > 0 {
|
||||
return ans[0], nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
//go:build darwin || freebsd || openbsd || netbsd || dragonfly
|
||||
|
||||
package tty
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func Tcgetattr(fd int, argp *unix.Termios) error {
|
||||
return unix.IoctlSetTermios(fd, unix.TIOCGETA, argp)
|
||||
}
|
||||
|
||||
func Tcsetattr(fd int, opt uintptr, argp *unix.Termios) error {
|
||||
switch opt {
|
||||
case TCSANOW:
|
||||
opt = unix.TIOCSETA
|
||||
case TCSADRAIN:
|
||||
opt = unix.TIOCSETAW
|
||||
case TCSAFLUSH:
|
||||
opt = unix.TIOCSETAF
|
||||
default:
|
||||
return unix.EINVAL
|
||||
}
|
||||
return unix.IoctlSetTermios(fd, uint(opt), argp)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tty
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func Tcgetattr(fd int, argp *unix.Termios) error {
|
||||
return unix.IoctlSetTermios(fd, unix.TCGETS, argp)
|
||||
}
|
||||
|
||||
func Tcsetattr(fd int, action uintptr, argp *unix.Termios) error {
|
||||
var request uint
|
||||
switch action {
|
||||
case TCSANOW:
|
||||
request = unix.TCSETS
|
||||
case TCSADRAIN:
|
||||
request = unix.TCSETSW
|
||||
case TCSAFLUSH:
|
||||
request = unix.TCSETSF
|
||||
default:
|
||||
return unix.EINVAL
|
||||
}
|
||||
return unix.IoctlSetTermios(fd, request, argp)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func DCSToKitty(msgtype, payload string) (string, error) {
|
||||
data := base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(payload))
|
||||
ans := "\x1bP@kitty-" + msgtype + "|" + data
|
||||
tmux := TmuxSocketAddress()
|
||||
if tmux != "" {
|
||||
err := TmuxAllowPassthrough()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ans = "\033Ptmux;\033" + ans + "\033\033\\\033\\"
|
||||
} else {
|
||||
ans += "\033\\"
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/humanize"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type dl_data struct {
|
||||
mutex sync.Mutex
|
||||
canceled_by_user bool
|
||||
error_from_download error
|
||||
done, total uint64
|
||||
download_started bool
|
||||
download_finished bool
|
||||
temp_file_path string
|
||||
}
|
||||
|
||||
type render_data struct {
|
||||
done, total uint64
|
||||
screen_width int
|
||||
spinner *Spinner
|
||||
started_at time.Time
|
||||
}
|
||||
|
||||
func render_without_total(rd *render_data) string {
|
||||
return fmt.Sprint(rd.spinner.Tick(), humanize.Bytes(rd.done), " downloaded so far. Started %s", humanize.Time(rd.started_at))
|
||||
}
|
||||
|
||||
func format_time(d time.Duration) string {
|
||||
d = d.Round(time.Second)
|
||||
ans := ""
|
||||
if d.Hours() > 1 {
|
||||
h := d / time.Hour
|
||||
d -= h * time.Hour
|
||||
ans += fmt.Sprintf("%02d:", h)
|
||||
}
|
||||
m := d / time.Minute
|
||||
d -= m * time.Minute
|
||||
s := d / time.Second
|
||||
return fmt.Sprintf("%s%02d:%02d", ans, m, s)
|
||||
}
|
||||
|
||||
func render_progress(rd *render_data) string {
|
||||
if rd.total == 0 {
|
||||
return render_without_total(rd)
|
||||
}
|
||||
now := time.Now()
|
||||
duration := now.Sub(rd.started_at)
|
||||
rate := float64(rd.done) / float64(duration)
|
||||
frac := float64(rd.done) / float64(rd.total)
|
||||
bytes_left := rd.total - rd.done
|
||||
time_left := time.Duration(float64(bytes_left) / rate)
|
||||
speed := rate * float64(time.Second)
|
||||
before := rd.spinner.Tick()
|
||||
after := fmt.Sprintf(" %d%% %s/s %s", int(frac*100), strings.ReplaceAll(humanize.Bytes(uint64(speed)), " ", ""), format_time(time_left))
|
||||
available_width := rd.screen_width - len("T 100% 1000 MB/s 11:11:11")
|
||||
// fmt.Println("\r\n", frac, available_width)
|
||||
progress_bar := ""
|
||||
if available_width > 10 {
|
||||
progress_bar = " " + RenderProgressBar(frac, available_width)
|
||||
}
|
||||
return before + progress_bar + after
|
||||
}
|
||||
|
||||
func DownloadFileWithProgress(destpath, url string, kill_if_signaled bool) (err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dl_data := dl_data{}
|
||||
rd := render_data{spinner: NewSpinner("dots"), started_at: time.Now()}
|
||||
|
||||
register_temp_file_path := func(path string) {
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.temp_file_path = path
|
||||
dl_data.mutex.Unlock()
|
||||
}
|
||||
|
||||
report_progress := func(done, total uint64) error {
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.done = done
|
||||
dl_data.total = total
|
||||
canceled := dl_data.canceled_by_user
|
||||
dl_data.mutex.Unlock()
|
||||
if canceled {
|
||||
return Canceled
|
||||
}
|
||||
lp.WakeupMainThread()
|
||||
return nil
|
||||
}
|
||||
|
||||
do_download := func() {
|
||||
lp.RecoverFromPanicInGoRoutine()
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.download_started = true
|
||||
dl_data.mutex.Unlock()
|
||||
err := utils.DownloadToFile(destpath, url, report_progress, register_temp_file_path)
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.download_finished = true
|
||||
if err != Canceled && err != nil {
|
||||
dl_data.error_from_download = err
|
||||
}
|
||||
dl_data.mutex.Unlock()
|
||||
lp.WakeupMainThread()
|
||||
}
|
||||
|
||||
redraw := func() {
|
||||
lp.StartAtomicUpdate()
|
||||
lp.AllowLineWrapping(false)
|
||||
defer func() {
|
||||
lp.AllowLineWrapping(true)
|
||||
lp.EndAtomicUpdate()
|
||||
}()
|
||||
lp.QueueWriteString("\r")
|
||||
lp.ClearToEndOfLine()
|
||||
dl_data.mutex.Lock()
|
||||
rd.done, rd.total = dl_data.done, dl_data.total
|
||||
dl_data.mutex.Unlock()
|
||||
if rd.done+rd.total == 0 {
|
||||
lp.QueueWriteString("Waiting for download to start...")
|
||||
} else {
|
||||
sz, err := lp.ScreenSize()
|
||||
w := sz.WidthCells
|
||||
if err != nil {
|
||||
w = 80
|
||||
}
|
||||
rd.screen_width = int(w)
|
||||
lp.QueueWriteString(render_progress(&rd))
|
||||
}
|
||||
}
|
||||
|
||||
on_timer_tick := func(timer_id loop.IdType) error {
|
||||
return lp.OnWakeup()
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
if _, err = lp.AddTimer(rd.spinner.interval, true, on_timer_tick); err != nil {
|
||||
return "", err
|
||||
}
|
||||
go do_download()
|
||||
lp.QueueWriteString("Downloading: " + url + "\r\n")
|
||||
return "\r\n", nil
|
||||
}
|
||||
|
||||
lp.OnResumeFromStop = func() error {
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnResize = func(old_size, new_size loop.ScreenSize) error {
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnWakeup = func() error {
|
||||
dl_data.mutex.Lock()
|
||||
err := dl_data.error_from_download
|
||||
finished := dl_data.download_finished
|
||||
dl_data.mutex.Unlock()
|
||||
if err != nil {
|
||||
return dl_data.error_from_download
|
||||
}
|
||||
if finished {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.canceled_by_user = true
|
||||
dl_data.mutex.Unlock()
|
||||
return Canceled
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
dl_data.mutex.Lock()
|
||||
if dl_data.temp_file_path != "" && !dl_data.download_finished {
|
||||
os.Remove(dl_data.temp_file_path)
|
||||
}
|
||||
dl_data.mutex.Unlock()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
if kill_if_signaled {
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
return &KilledBySignal{Msg: fmt.Sprint("Killed by signal: ", ds), SignalName: ds}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"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/images"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Size struct{ Width, Height int }
|
||||
|
||||
type rendering struct {
|
||||
img *images.ImageData
|
||||
image_id uint32
|
||||
}
|
||||
|
||||
type temp_resource struct {
|
||||
path string
|
||||
mmap shm.MMap
|
||||
}
|
||||
|
||||
func (self *temp_resource) remove() {
|
||||
if self.path != "" {
|
||||
os.Remove(self.path)
|
||||
self.path = ""
|
||||
}
|
||||
if self.mmap != nil {
|
||||
_ = self.mmap.Unlink()
|
||||
self.mmap = nil
|
||||
}
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
src struct {
|
||||
path string
|
||||
data *images.ImageData
|
||||
size Size
|
||||
loaded bool
|
||||
}
|
||||
renderings map[Size]*rendering
|
||||
err error
|
||||
}
|
||||
|
||||
func NewImage() *Image {
|
||||
return &Image{
|
||||
renderings: make(map[Size]*rendering),
|
||||
}
|
||||
}
|
||||
|
||||
type ImageCollection struct {
|
||||
Shm_supported, Files_supported atomic.Bool
|
||||
detection_file_id, detection_shm_id uint32
|
||||
temp_file_map map[uint32]*temp_resource
|
||||
running_in_tmux bool
|
||||
|
||||
mutex sync.Mutex
|
||||
image_id_counter uint32
|
||||
|
||||
images map[string]*Image
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
func (self *ImageCollection) GetSizeIfAvailable(key string, page_size Size) (Size, error) {
|
||||
if !self.mutex.TryLock() {
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
defer self.mutex.Unlock()
|
||||
img := self.images[key]
|
||||
if img == nil {
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
ans := img.renderings[page_size]
|
||||
if ans == nil {
|
||||
if img.err != nil {
|
||||
return Size{}, img.err
|
||||
}
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
return Size{ans.img.Width, ans.img.Height}, img.err
|
||||
}
|
||||
|
||||
func (self *ImageCollection) ResolutionOf(key string) Size {
|
||||
if !self.mutex.TryLock() {
|
||||
return Size{-1, -1}
|
||||
}
|
||||
defer self.mutex.Unlock()
|
||||
i := self.images[key]
|
||||
if i == nil {
|
||||
return Size{-2, -2}
|
||||
}
|
||||
return i.src.size
|
||||
}
|
||||
|
||||
func (self *ImageCollection) AddPaths(paths ...string) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
for _, path := range paths {
|
||||
if self.images[path] == nil {
|
||||
i := NewImage()
|
||||
i.src.path = path
|
||||
self.images[path] = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Image) ResizeForPageSize(width, height int) {
|
||||
sz := Size{width, height}
|
||||
if self.renderings[sz] != nil {
|
||||
return
|
||||
}
|
||||
final_width, final_height := images.FitImage(self.src.size.Width, self.src.size.Height, width, height)
|
||||
if final_width == self.src.size.Width && final_height == self.src.data.Height {
|
||||
self.renderings[sz] = &rendering{img: self.src.data}
|
||||
return
|
||||
}
|
||||
x_frac, y_frac := float64(final_width)/float64(self.src.size.Width), float64(final_height)/float64(self.src.size.Height)
|
||||
self.renderings[sz] = &rendering{img: self.src.data.Resize(x_frac, y_frac)}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) ResizeForPageSize(width, height int) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
ctx := images.Context{}
|
||||
keys := utils.Keys(self.images)
|
||||
if err := ctx.SafeParallel(0, len(keys), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
img := self.images[keys[i]]
|
||||
if img.src.loaded && img.err == nil {
|
||||
img.ResizeForPageSize(width, height)
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) DeleteAllVisiblePlacements(lp *loop.Loop) {
|
||||
g := self.new_graphics_command()
|
||||
g.SetAction(GRT_action_delete).SetDelete(GRT_delete_visible)
|
||||
_ = g.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
|
||||
func (self *ImageCollection) PlaceImageSubRect(lp *loop.Loop, key string, page_size Size, left, top, width, height int) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
img := self.images[key]
|
||||
if img == nil {
|
||||
return
|
||||
}
|
||||
r := img.renderings[page_size]
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if r.image_id == 0 {
|
||||
self.transmit_rendering(lp, r)
|
||||
}
|
||||
if width < 0 {
|
||||
width = r.img.Width
|
||||
}
|
||||
if height < 0 {
|
||||
height = r.img.Height
|
||||
}
|
||||
width = utils.Max(0, utils.Min(r.img.Width-left, width))
|
||||
height = utils.Max(0, utils.Min(r.img.Height-top, height))
|
||||
gc := self.new_graphics_command()
|
||||
gc.SetAction(GRT_action_display).SetLeftEdge(uint64(left)).SetTopEdge(uint64(top)).SetWidth(uint64(width)).SetHeight(uint64(height))
|
||||
gc.SetImageId(r.image_id).SetPlacementId(1).SetCursorMovement(GRT_cursor_static)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
|
||||
func (self *ImageCollection) Initialize(lp *loop.Loop) {
|
||||
tmux := tui.TmuxSocketAddress()
|
||||
if tmux != "" && tui.TmuxAllowPassthrough() == nil {
|
||||
self.running_in_tmux = true
|
||||
}
|
||||
if !self.running_in_tmux {
|
||||
g := func(t GRT_t, payload string) uint32 {
|
||||
self.image_id_counter++
|
||||
g1 := self.new_graphics_command()
|
||||
g1.SetTransmission(t).SetAction(GRT_action_query).SetImageId(self.image_id_counter).SetDataWidth(1).SetDataHeight(1).SetFormat(
|
||||
GRT_format_rgb).SetDataSize(uint64(len(payload)))
|
||||
_ = g1.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(payload))
|
||||
return self.image_id_counter
|
||||
}
|
||||
tf, err := images.CreateTempInRAM()
|
||||
if err == nil {
|
||||
if _, err = tf.Write([]byte{1, 2, 3}); err == nil {
|
||||
self.detection_file_id = g(GRT_transmission_tempfile, tf.Name())
|
||||
self.temp_file_map[self.detection_file_id] = &temp_resource{path: tf.Name()}
|
||||
}
|
||||
tf.Close()
|
||||
}
|
||||
sf, err := shm.CreateTemp("icat-", 3)
|
||||
if err == nil {
|
||||
copy(sf.Slice(), []byte{1, 2, 3})
|
||||
sf.Close()
|
||||
self.detection_shm_id = g(GRT_transmission_sharedmem, sf.Name())
|
||||
self.temp_file_map[self.detection_shm_id] = &temp_resource{mmap: sf}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) Finalize(lp *loop.Loop) {
|
||||
for _, tr := range self.temp_file_map {
|
||||
tr.remove()
|
||||
}
|
||||
for _, img := range self.images {
|
||||
for _, r := range img.renderings {
|
||||
if r.image_id > 0 {
|
||||
g := self.new_graphics_command()
|
||||
g.SetAction(GRT_action_delete).SetDelete(GRT_free_by_id).SetImageId(r.image_id)
|
||||
_ = g.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
}
|
||||
img.renderings = nil
|
||||
}
|
||||
self.images = nil
|
||||
}
|
||||
|
||||
func (self *ImageCollection) mark_img_as_needing_transmission(id uint32) bool {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
for _, img := range self.images {
|
||||
for _, r := range img.renderings {
|
||||
if r.image_id == id {
|
||||
r.image_id = 0
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Handle graphics response. Returns false if an image needs re-transmission because
|
||||
// the terminal replied with ENOENT for a placement
|
||||
func (self *ImageCollection) HandleGraphicsCommand(gc *GraphicsCommand) bool {
|
||||
switch gc.ImageId() {
|
||||
case self.detection_file_id:
|
||||
if gc.ResponseMessage() == "OK" {
|
||||
self.Files_supported.Store(true)
|
||||
} else {
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
}
|
||||
}
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
self.detection_file_id = 0
|
||||
return true
|
||||
case self.detection_shm_id:
|
||||
if gc.ResponseMessage() == "OK" {
|
||||
self.Shm_supported.Store(true)
|
||||
} else {
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
}
|
||||
}
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
self.detection_shm_id = 0
|
||||
return true
|
||||
}
|
||||
if is_transmission_response := gc.PlacementId() == 0; is_transmission_response {
|
||||
if gc.ResponseMessage() != "OK" {
|
||||
// this should never happen but lets cleanup anyway
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if gc.ResponseMessage() != "OK" && gc.PlacementId() != 0 {
|
||||
if self.mark_img_as_needing_transmission(gc.ImageId()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *ImageCollection) LoadAll() {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
ctx := images.Context{}
|
||||
all := utils.Values(self.images)
|
||||
if err := ctx.SafeParallel(0, len(self.images), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
img := all[i]
|
||||
if !img.src.loaded {
|
||||
img.src.data, img.err = images.OpenImageFromPath(img.src.path)
|
||||
if img.err == nil {
|
||||
img.src.size.Width, img.src.size.Height = img.src.data.Width, img.src.data.Height
|
||||
}
|
||||
img.src.loaded = true
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func NewImageCollection(paths ...string) *ImageCollection {
|
||||
items := make(map[string]*Image, len(paths))
|
||||
for _, path := range paths {
|
||||
i := NewImage()
|
||||
i.src.path = path
|
||||
items[path] = i
|
||||
}
|
||||
return &ImageCollection{images: items, temp_file_map: make(map[uint32]*temp_resource)}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) new_graphics_command() *GraphicsCommand {
|
||||
gc := GraphicsCommand{}
|
||||
if self.running_in_tmux {
|
||||
gc.WrapPrefix = "\033Ptmux;"
|
||||
gc.WrapSuffix = "\033\\"
|
||||
gc.EncodeSerializedDataFunc = func(x string) string { return strings.ReplaceAll(x, "\033", "\033\033") }
|
||||
}
|
||||
return &gc
|
||||
}
|
||||
|
||||
func transmit_by_escape_code(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
atomic := lp.IsAtomicUpdateActive()
|
||||
lp.EndAtomicUpdate()
|
||||
gc.SetTransmission(GRT_transmission_direct)
|
||||
_, _, _, data := frame.Data()
|
||||
_ = gc.WriteWithPayloadToLoop(lp, data)
|
||||
if atomic {
|
||||
lp.StartAtomicUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
func transmit_by_shm(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
mmap, err := frame.DataAsSHM("kdiff-img-*")
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
mmap.Close()
|
||||
temp_file_map[image_id] = &temp_resource{mmap: mmap}
|
||||
gc.SetTransmission(GRT_transmission_sharedmem)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(mmap.Name()))
|
||||
}
|
||||
|
||||
func transmit_by_file(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
f, err := images.CreateTempInRAM()
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
temp_file_map[image_id] = &temp_resource{path: f.Name()}
|
||||
_, _, _, data := frame.Data()
|
||||
_, err = f.Write(data)
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
gc.SetTransmission(GRT_transmission_tempfile)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(f.Name()))
|
||||
}
|
||||
|
||||
func (self *ImageCollection) transmit_rendering(lp *loop.Loop, r *rendering) {
|
||||
if r.image_id == 0 {
|
||||
self.image_id_counter++
|
||||
r.image_id = self.image_id_counter
|
||||
}
|
||||
is_animated := len(r.img.Frames) > 0
|
||||
transmit := transmit_by_escape_code
|
||||
if self.Shm_supported.Load() {
|
||||
transmit = transmit_by_shm
|
||||
} else if self.Files_supported.Load() {
|
||||
transmit = transmit_by_file
|
||||
}
|
||||
|
||||
frame_control_cmd := self.new_graphics_command()
|
||||
frame_control_cmd.SetAction(GRT_action_animate).SetImageId(r.image_id)
|
||||
for frame_num, frame := range r.img.Frames {
|
||||
gc := self.new_graphics_command()
|
||||
gc.SetImageId(r.image_id)
|
||||
gc.SetDataWidth(uint64(frame.Width)).SetDataHeight(uint64(frame.Height))
|
||||
if frame.Is_opaque {
|
||||
gc.SetFormat(GRT_format_rgb)
|
||||
}
|
||||
switch frame_num {
|
||||
case 0:
|
||||
gc.SetAction(GRT_action_transmit)
|
||||
gc.SetCursorMovement(GRT_cursor_static)
|
||||
default:
|
||||
gc.SetAction(GRT_action_frame)
|
||||
gc.SetGap(frame.Delay_ms)
|
||||
if frame.Compose_onto > 0 {
|
||||
gc.SetOverlaidFrame(uint64(frame.Compose_onto))
|
||||
}
|
||||
if frame.Replace {
|
||||
gc.SetCompositionMode(Overwrite)
|
||||
}
|
||||
gc.SetLeftEdge(uint64(frame.Left)).SetTopEdge(uint64(frame.Top))
|
||||
}
|
||||
transmit(lp, r.image_id, self.temp_file_map, frame, gc)
|
||||
if is_animated {
|
||||
switch frame_num {
|
||||
case 0:
|
||||
// set gap for the first frame and number of loops for the animation
|
||||
c := frame_control_cmd
|
||||
c.SetTargetFrame(uint64(frame.Number))
|
||||
c.SetGap(int32(frame.Delay_ms))
|
||||
c.SetNumberOfLoops(1)
|
||||
_ = c.WriteWithPayloadToLoop(lp, nil)
|
||||
case 1:
|
||||
c := frame_control_cmd
|
||||
c.SetAnimationControl(2) // set animation to loading mode
|
||||
_ = c.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_animated {
|
||||
c := frame_control_cmd
|
||||
c.SetAnimationControl(3) // set animation to normal mode
|
||||
_ = c.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,847 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// Enums {{{
|
||||
type GRT_a int // enum
|
||||
|
||||
const (
|
||||
GRT_action_transmit GRT_a = iota // t
|
||||
GRT_action_transmit_and_display // T
|
||||
GRT_action_query // q
|
||||
GRT_action_display // p
|
||||
GRT_action_delete // d
|
||||
GRT_action_frame // f
|
||||
GRT_action_animate // a
|
||||
GRT_action_compose // c
|
||||
)
|
||||
|
||||
type GRT_q int // enum
|
||||
|
||||
const (
|
||||
GRT_quiet_noisy GRT_q = iota // 0
|
||||
GRT_quiet_only_errors // 1
|
||||
GRT_quiet_silent // 2
|
||||
)
|
||||
|
||||
type GRT_f int // enum
|
||||
|
||||
const (
|
||||
GRT_format_rgba GRT_f = iota // 32
|
||||
GRT_format_rgb // 24
|
||||
GRT_format_png // 100
|
||||
GRT_format_indexed // 8
|
||||
GRT_format_indexed_alpha // 16
|
||||
)
|
||||
|
||||
type GRT_t int // enum
|
||||
|
||||
const (
|
||||
GRT_transmission_direct GRT_t = iota // d
|
||||
GRT_transmission_file // f
|
||||
GRT_transmission_tempfile // t
|
||||
GRT_transmission_sharedmem // s
|
||||
)
|
||||
|
||||
type GRT_o int // enum
|
||||
|
||||
const (
|
||||
GRT_compression_none GRT_o = iota //
|
||||
GRT_compression_zlib // z
|
||||
)
|
||||
|
||||
type GRT_m int // enum
|
||||
|
||||
const (
|
||||
GRT_more_nomore GRT_m = iota // 0
|
||||
GRT_more_more // 1
|
||||
)
|
||||
|
||||
type GRT_C int // enum
|
||||
|
||||
const (
|
||||
GRT_cursor_move GRT_C = iota // 0
|
||||
GRT_cursor_static // 1
|
||||
)
|
||||
|
||||
type GRT_U int // enum
|
||||
|
||||
const (
|
||||
GRT_no_unicode_placeholder GRT_U = iota // 0
|
||||
GRT_create_unicode_placeholder // 1
|
||||
)
|
||||
|
||||
type CompositionMode int // enum
|
||||
|
||||
const (
|
||||
AlphaBlend CompositionMode = iota // 0
|
||||
Overwrite // 1
|
||||
)
|
||||
|
||||
type GRT_d int // enum
|
||||
|
||||
const (
|
||||
GRT_delete_visible GRT_d = iota // a
|
||||
GRT_free_visible // A
|
||||
|
||||
GRT_delete_by_id // i
|
||||
GRT_free_by_id // I
|
||||
|
||||
GRT_delete_by_number // n
|
||||
GRT_free_by_number // N
|
||||
|
||||
GRT_delete_by_cursor // c
|
||||
GRT_free_by_cursor // C
|
||||
|
||||
GRT_delete_by_frame // f
|
||||
GRT_free_by_frame // F
|
||||
|
||||
GRT_delete_by_cell // p
|
||||
GRT_free_by_cell // P
|
||||
|
||||
GRT_delete_by_cell_zindex // q
|
||||
GRT_free_by_cell_zindex // Q
|
||||
|
||||
GRT_delete_by_range // r
|
||||
GRT_free_by_range // R
|
||||
|
||||
GRT_delete_by_column // x
|
||||
GRT_free_by_column // X
|
||||
|
||||
GRT_delete_by_row // y
|
||||
GRT_free_by_row // Y
|
||||
|
||||
GRT_delete_by_zindex // z
|
||||
GRT_free_by_zindex // Z
|
||||
)
|
||||
|
||||
// }}}
|
||||
|
||||
type GraphicsCommand struct {
|
||||
a GRT_a
|
||||
q GRT_q
|
||||
f GRT_f
|
||||
t GRT_t
|
||||
o GRT_o
|
||||
m GRT_m
|
||||
C GRT_C
|
||||
d GRT_d
|
||||
U GRT_U
|
||||
|
||||
s, v, S, O, x, y, w, h, X, Y, c, r, N uint64
|
||||
|
||||
i, I, p uint32
|
||||
|
||||
z int32
|
||||
|
||||
DisableCompression bool
|
||||
WrapPrefix, WrapSuffix string
|
||||
EncodeSerializedDataFunc func(string) string
|
||||
|
||||
response_message string
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) serialize_non_default_fields() (ans []string) {
|
||||
var null GraphicsCommand
|
||||
ans = make([]string, 0, 16)
|
||||
|
||||
write_key := func(k byte, val, defval any) {
|
||||
if val != defval {
|
||||
ans = append(ans, fmt.Sprintf("%c=%v", k, val))
|
||||
}
|
||||
}
|
||||
|
||||
write_key('a', self.a, null.a)
|
||||
write_key('q', self.q, null.q)
|
||||
write_key('f', self.f, null.f)
|
||||
write_key('t', self.t, null.t)
|
||||
write_key('o', self.o, null.o)
|
||||
write_key('m', self.m, null.m)
|
||||
write_key('C', self.C, null.C)
|
||||
write_key('U', self.U, null.U)
|
||||
write_key('d', self.d, null.d)
|
||||
|
||||
write_key('N', self.N, null.N)
|
||||
write_key('s', self.s, null.s)
|
||||
write_key('v', self.v, null.v)
|
||||
write_key('S', self.S, null.S)
|
||||
write_key('O', self.O, null.O)
|
||||
write_key('x', self.x, null.x)
|
||||
write_key('y', self.y, null.y)
|
||||
write_key('w', self.w, null.w)
|
||||
write_key('h', self.h, null.h)
|
||||
write_key('X', self.X, null.X)
|
||||
write_key('Y', self.Y, null.Y)
|
||||
write_key('c', self.c, null.c)
|
||||
write_key('r', self.r, null.r)
|
||||
|
||||
write_key('i', self.i, null.i)
|
||||
write_key('I', self.I, null.I)
|
||||
write_key('p', self.p, null.p)
|
||||
|
||||
write_key('z', self.z, null.z)
|
||||
return
|
||||
}
|
||||
|
||||
func (self GraphicsCommand) String() string {
|
||||
ans := "GraphicsCommand(" + strings.Join(self.serialize_non_default_fields(), ", ")
|
||||
if self.response_message != "" {
|
||||
ans += fmt.Sprintf(", response=%#v", self.response_message)
|
||||
}
|
||||
return ans + ")"
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func (self *GraphicsCommand) serialize_to(buf io.StringWriter, chunk string) (err error) {
|
||||
var ws func(string)
|
||||
if self.EncodeSerializedDataFunc == nil {
|
||||
ws = func(s string) {
|
||||
_, err = buf.WriteString(s)
|
||||
}
|
||||
} else {
|
||||
ws = func(s string) {
|
||||
_, err = buf.WriteString(self.EncodeSerializedDataFunc(s))
|
||||
}
|
||||
}
|
||||
if self.WrapPrefix != "" {
|
||||
_, err = buf.WriteString(self.WrapPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if self.WrapSuffix != "" {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
_, err = buf.WriteString(self.WrapSuffix)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
ws("\033_G")
|
||||
if err == nil {
|
||||
items := self.serialize_non_default_fields()
|
||||
ws(strings.Join(items, ","))
|
||||
if err == nil {
|
||||
if len(chunk) > 0 {
|
||||
ws(";")
|
||||
if err == nil {
|
||||
ws(chunk)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
ws("\033\\")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func compress_with_zlib(data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
b.Grow(len(data) + 128)
|
||||
w := zlib.NewWriter(&b)
|
||||
_, _ = w.Write(data)
|
||||
w.Close()
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) AsAPC(payload []byte) string {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(1024)
|
||||
_ = self.WriteWithPayloadTo(&buf, payload)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) WriteWithPayloadTo(o io.StringWriter, payload []byte) (err error) {
|
||||
const compression_threshold = 2048
|
||||
if len(payload) == 0 {
|
||||
return self.serialize_to(o, "")
|
||||
}
|
||||
if len(payload) <= compression_threshold {
|
||||
return self.serialize_to(o, base64.RawStdEncoding.EncodeToString(payload))
|
||||
}
|
||||
gc := *self
|
||||
if !self.DisableCompression && self.Format() != GRT_format_png {
|
||||
compressed := compress_with_zlib(payload)
|
||||
if len(compressed) < len(payload) {
|
||||
gc.SetCompression(GRT_compression_zlib)
|
||||
payload = compressed
|
||||
}
|
||||
}
|
||||
const chunk_size = 128 * 1024
|
||||
data := base64.RawStdEncoding.EncodeToString(payload)
|
||||
for len(data) > 0 && err == nil {
|
||||
chunk := data
|
||||
if len(data) > chunk_size {
|
||||
chunk = data[:chunk_size]
|
||||
data = data[chunk_size:]
|
||||
} else {
|
||||
data = ""
|
||||
}
|
||||
if len(data) > 0 {
|
||||
gc.m = GRT_more_more
|
||||
} else {
|
||||
gc.m = GRT_more_nomore
|
||||
}
|
||||
err = gc.serialize_to(o, chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gc = GraphicsCommand{
|
||||
q: self.q, a: self.a, WrapPrefix: self.WrapPrefix, WrapSuffix: self.WrapSuffix,
|
||||
EncodeSerializedDataFunc: self.EncodeSerializedDataFunc}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type loop_io_writer struct {
|
||||
lp *loop.Loop
|
||||
}
|
||||
|
||||
func (self *loop_io_writer) WriteString(data string) (n int, err error) {
|
||||
self.lp.QueueWriteString(data)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) WriteWithPayloadToLoop(lp *loop.Loop, payload []byte) (err error) {
|
||||
w := loop_io_writer{lp}
|
||||
return self.WriteWithPayloadTo(&w, payload)
|
||||
}
|
||||
|
||||
func set_val[T any](loc *T, parser func(string) (T, error), value string) (err error) {
|
||||
var temp T
|
||||
temp, err = parser(value)
|
||||
if err == nil {
|
||||
*loc = temp
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_uval(loc *uint64, value string) (err error) {
|
||||
temp, err := strconv.ParseUint(value, 10, 64)
|
||||
if err == nil {
|
||||
*loc = temp
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_u32val(loc *uint32, value string) (err error) {
|
||||
temp, err := strconv.ParseUint(value, 10, 32)
|
||||
if err == nil {
|
||||
*loc = uint32(temp)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_i32val(loc *int32, value string) (err error) {
|
||||
temp, err := strconv.ParseInt(value, 10, 32)
|
||||
if err == nil {
|
||||
*loc = int32(temp)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetString(key byte, value string) (err error) {
|
||||
switch key {
|
||||
case 'a':
|
||||
err = set_val(&self.a, GRT_a_from_string, value)
|
||||
case 'q':
|
||||
err = set_val(&self.q, GRT_q_from_string, value)
|
||||
case 'f':
|
||||
err = set_val(&self.f, GRT_f_from_string, value)
|
||||
case 't':
|
||||
err = set_val(&self.t, GRT_t_from_string, value)
|
||||
case 'o':
|
||||
err = set_val(&self.o, GRT_o_from_string, value)
|
||||
case 'm':
|
||||
err = set_val(&self.m, GRT_m_from_string, value)
|
||||
case 'C':
|
||||
err = set_val(&self.C, GRT_C_from_string, value)
|
||||
case 'U':
|
||||
err = set_val(&self.U, GRT_U_from_string, value)
|
||||
case 'd':
|
||||
err = set_val(&self.d, GRT_d_from_string, value)
|
||||
case 'N':
|
||||
err = set_uval(&self.N, value)
|
||||
case 's':
|
||||
err = set_uval(&self.s, value)
|
||||
case 'v':
|
||||
err = set_uval(&self.v, value)
|
||||
case 'S':
|
||||
err = set_uval(&self.S, value)
|
||||
case 'O':
|
||||
err = set_uval(&self.O, value)
|
||||
case 'x':
|
||||
err = set_uval(&self.x, value)
|
||||
case 'y':
|
||||
err = set_uval(&self.y, value)
|
||||
case 'w':
|
||||
err = set_uval(&self.w, value)
|
||||
case 'h':
|
||||
err = set_uval(&self.h, value)
|
||||
case 'X':
|
||||
err = set_uval(&self.X, value)
|
||||
case 'Y':
|
||||
err = set_uval(&self.Y, value)
|
||||
case 'c':
|
||||
err = set_uval(&self.c, value)
|
||||
case 'r':
|
||||
err = set_uval(&self.r, value)
|
||||
case 'i':
|
||||
err = set_u32val(&self.i, value)
|
||||
case 'I':
|
||||
err = set_u32val(&self.I, value)
|
||||
case 'p':
|
||||
err = set_u32val(&self.p, value)
|
||||
case 'z':
|
||||
err = set_i32val(&self.z, value)
|
||||
default:
|
||||
return fmt.Errorf("Unknown key: %c", key)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func GraphicsCommandFromAPCPayload(raw []byte) *GraphicsCommand {
|
||||
const (
|
||||
expecting_key int = iota
|
||||
expecting_equals
|
||||
expecting_value
|
||||
)
|
||||
state := expecting_key
|
||||
var current_key byte
|
||||
var value_start_at int
|
||||
var payload_start_at int = -1
|
||||
var gc GraphicsCommand
|
||||
|
||||
add_key := func(pos int) {
|
||||
_ = gc.SetString(current_key, utils.UnsafeBytesToString(raw[value_start_at:pos]))
|
||||
}
|
||||
|
||||
for pos, ch := range raw {
|
||||
if ch == ';' {
|
||||
if state == expecting_value {
|
||||
add_key(pos)
|
||||
}
|
||||
state = expecting_key
|
||||
payload_start_at = pos + 1
|
||||
break
|
||||
}
|
||||
switch state {
|
||||
case expecting_key:
|
||||
current_key = ch
|
||||
state = expecting_equals
|
||||
case expecting_equals:
|
||||
if ch == '=' {
|
||||
state = expecting_value
|
||||
value_start_at = pos + 1
|
||||
} else {
|
||||
state = expecting_key
|
||||
}
|
||||
case expecting_value:
|
||||
if ch == ',' {
|
||||
add_key(pos)
|
||||
state = expecting_key
|
||||
}
|
||||
}
|
||||
}
|
||||
if state == expecting_value {
|
||||
add_key(len(raw))
|
||||
}
|
||||
if payload_start_at > -1 {
|
||||
payload := raw[payload_start_at:]
|
||||
if len(payload) > 0 {
|
||||
gc.response_message = string(payload)
|
||||
}
|
||||
}
|
||||
return &gc
|
||||
}
|
||||
|
||||
func GraphicsCommandFromAPC(raw []byte) *GraphicsCommand {
|
||||
if len(raw) < 1 || raw[0] != 'G' {
|
||||
return nil
|
||||
}
|
||||
return GraphicsCommandFromAPCPayload(raw[1:])
|
||||
}
|
||||
|
||||
// Getters and Setters {{{
|
||||
func (self *GraphicsCommand) Action() GRT_a {
|
||||
return self.a
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetAction(a GRT_a) *GraphicsCommand {
|
||||
self.a = a
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Delete() GRT_d {
|
||||
return self.d
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDelete(d GRT_d) *GraphicsCommand {
|
||||
self.d = d
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Quiet() GRT_q {
|
||||
return self.q
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetQuiet(q GRT_q) *GraphicsCommand {
|
||||
self.q = q
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) CursorMovement() GRT_C {
|
||||
return self.C
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCursorMovement(c GRT_C) *GraphicsCommand {
|
||||
self.C = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) UnicodePlaceholder() GRT_U {
|
||||
return self.U
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetUnicodePlaceholder(U GRT_U) *GraphicsCommand {
|
||||
self.U = U
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Format() GRT_f {
|
||||
return self.f
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetFormat(f GRT_f) *GraphicsCommand {
|
||||
self.f = f
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Transmission() GRT_t {
|
||||
return self.t
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTransmission(t GRT_t) *GraphicsCommand {
|
||||
self.t = t
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Compression() GRT_o {
|
||||
return self.o
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCompression(o GRT_o) *GraphicsCommand {
|
||||
self.o = o
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Width() uint64 {
|
||||
return self.w
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetWidth(w uint64) *GraphicsCommand {
|
||||
self.w = w
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Height() uint64 {
|
||||
return self.h
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetHeight(h uint64) *GraphicsCommand {
|
||||
self.h = h
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataWidth() uint64 {
|
||||
return self.s
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataWidth(w uint64) *GraphicsCommand {
|
||||
self.s = w
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataHeight() uint64 {
|
||||
return self.v
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataHeight(h uint64) *GraphicsCommand {
|
||||
self.v = h
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) NumberOfLoops() uint64 {
|
||||
return self.v
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetNumberOfLoops(n uint64) *GraphicsCommand {
|
||||
self.v = n
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataSize() uint64 {
|
||||
return self.S
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataSize(s uint64) *GraphicsCommand {
|
||||
self.S = s
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataOffset() uint64 {
|
||||
return self.O
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataOffset(o uint64) *GraphicsCommand {
|
||||
self.O = o
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) LeftEdge() uint64 {
|
||||
return self.x
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetLeftEdge(x uint64) *GraphicsCommand {
|
||||
self.x = x
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) TopEdge() uint64 {
|
||||
return self.y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTopEdge(y uint64) *GraphicsCommand {
|
||||
self.y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) XOffset() uint64 {
|
||||
return self.X
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetXOffset(x uint64) *GraphicsCommand {
|
||||
self.X = x
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BlendMode() CompositionMode {
|
||||
switch self.X {
|
||||
case 1:
|
||||
return Overwrite
|
||||
default:
|
||||
return AlphaBlend
|
||||
}
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBlendMode(x CompositionMode) *GraphicsCommand {
|
||||
self.X = uint64(x)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) CompositionMode() CompositionMode {
|
||||
switch self.C {
|
||||
case 1:
|
||||
return Overwrite
|
||||
default:
|
||||
return AlphaBlend
|
||||
}
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCompositionMode(x CompositionMode) *GraphicsCommand {
|
||||
switch x {
|
||||
case Overwrite:
|
||||
self.C = 1
|
||||
case AlphaBlend:
|
||||
self.C = 0
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) YOffset() uint64 {
|
||||
return self.Y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetYOffset(y uint64) *GraphicsCommand {
|
||||
self.Y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SourceTopEdge() uint64 {
|
||||
return self.Y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetSourceTopEdge(y uint64) *GraphicsCommand {
|
||||
self.Y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BackgroundColor() uint32 {
|
||||
return uint32(self.Y)
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBackgroundColor(y uint32) *GraphicsCommand {
|
||||
self.Y = uint64(y)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Rows() uint64 {
|
||||
return self.r
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetRows(r uint64) *GraphicsCommand {
|
||||
self.r = r
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Columns() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetColumns(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) TargetFrame() uint64 {
|
||||
return self.r
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTargetFrame(r uint64) *GraphicsCommand {
|
||||
self.r = r
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BaseFrame() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBaseFrame(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) OverlaidFrame() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetOverlaidFrame(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) FrameToMakeCurrent() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetFrameToMakeCurrent(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) UsageHints() uint64 {
|
||||
return self.N
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetUsageHints(hints uint64) *GraphicsCommand {
|
||||
self.N = hints
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ImageId() uint32 {
|
||||
return self.i
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetImageId(i uint32) *GraphicsCommand {
|
||||
self.i = i
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ImageNumber() uint32 {
|
||||
return self.I
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetImageNumber(n uint32) *GraphicsCommand {
|
||||
self.I = n
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) PlacementId() uint32 {
|
||||
return self.p
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetPlacementId(p uint32) *GraphicsCommand {
|
||||
self.p = p
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ZIndex() int32 {
|
||||
return self.z
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetZIndex(z int32) *GraphicsCommand {
|
||||
self.z = z
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Gap() int32 {
|
||||
return self.z
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetGap(z int32) *GraphicsCommand {
|
||||
self.z = z
|
||||
return self
|
||||
}
|
||||
|
||||
type AnimationControl uint
|
||||
|
||||
const (
|
||||
NoAnimationAction AnimationControl = iota
|
||||
StopAnimation
|
||||
RunAnimationButWaitForNewFrames
|
||||
RunAnimation
|
||||
)
|
||||
|
||||
func (self *GraphicsCommand) AnimationControl() AnimationControl {
|
||||
switch AnimationControl(self.s) {
|
||||
default:
|
||||
return NoAnimationAction
|
||||
case StopAnimation:
|
||||
return StopAnimation
|
||||
case RunAnimationButWaitForNewFrames:
|
||||
return RunAnimationButWaitForNewFrames
|
||||
case RunAnimation:
|
||||
return RunAnimation
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetAnimationControl(z uint) *GraphicsCommand {
|
||||
self.s = uint64(z)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ResponseMessage() string {
|
||||
return self.response_message
|
||||
}
|
||||
|
||||
// }}}
|
||||
@@ -0,0 +1,115 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"golang.org/x/exp/rand"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func from_full_apc_escape_code(raw string) *GraphicsCommand {
|
||||
return GraphicsCommandFromAPC([]byte(raw[2 : len(raw)-2]))
|
||||
}
|
||||
|
||||
func TestGraphicsCommandSerialization(t *testing.T) {
|
||||
gc := &GraphicsCommand{}
|
||||
|
||||
test_serialize := func(payload string, vals ...string) {
|
||||
expected := "\033_G" + strings.Join(vals, ",")
|
||||
if payload != "" {
|
||||
expected += ";" + base64.RawStdEncoding.EncodeToString([]byte(payload))
|
||||
}
|
||||
expected += "\033\\"
|
||||
if diff := cmp.Diff(expected, gc.AsAPC([]byte(payload))); diff != "" {
|
||||
t.Fatalf("Failed to write vals: %#v with payload: %#v\n%s", vals, payload, diff)
|
||||
}
|
||||
}
|
||||
|
||||
test_chunked_payload := func(payload []byte) {
|
||||
c := &GraphicsCommand{}
|
||||
data := c.AsAPC([]byte(payload))
|
||||
encoded := strings.Builder{}
|
||||
compressed := false
|
||||
is_first := true
|
||||
for {
|
||||
idx := strings.Index(data, "\033_")
|
||||
if idx < 0 {
|
||||
break
|
||||
}
|
||||
l := strings.Index(data, "\033\\")
|
||||
apc := data[idx+2 : l]
|
||||
data = data[l+2:]
|
||||
g := GraphicsCommandFromAPC([]byte(apc))
|
||||
if is_first {
|
||||
compressed = g.Compression() != 0
|
||||
is_first = false
|
||||
}
|
||||
encoded.WriteString(g.ResponseMessage())
|
||||
if g.m == GRT_more_nomore {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(data) > 0 {
|
||||
t.Fatalf("Unparsed remnant: %#v", string(data))
|
||||
}
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(encoded.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Encoded data not valid base-64 with error: %v", err)
|
||||
}
|
||||
if compressed {
|
||||
b := bytes.Buffer{}
|
||||
b.Write(decoded)
|
||||
r, _ := zlib.NewReader(&b)
|
||||
o := bytes.Buffer{}
|
||||
if _, err = io.Copy(&o, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Close()
|
||||
decoded = o.Bytes()
|
||||
}
|
||||
if diff := cmp.Diff(payload, decoded); diff != "" {
|
||||
t.Fatalf("Decoded payload does not match original\nlen decoded=%d len payload=%d", len(decoded), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
test_serialize("")
|
||||
gc.SetTransmission(GRT_transmission_sharedmem).SetAction(GRT_action_query).SetZIndex(-3).SetWidth(33).SetImageId(11)
|
||||
test_serialize("abcd", "a=q", "t=s", "w=33", "i=11", "z=-3")
|
||||
q := from_full_apc_escape_code(gc.AsAPC([]byte("abcd")))
|
||||
if diff := cmp.Diff(gc.AsAPC(nil), q.AsAPC(nil)); diff != "" {
|
||||
t.Fatalf("Parsing failed:\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(q.response_message, base64.RawStdEncoding.EncodeToString([]byte("abcd"))); diff != "" {
|
||||
t.Fatalf("Failed to parse payload:\n%s", diff)
|
||||
}
|
||||
|
||||
for _, x := range []struct {
|
||||
f GRT_f
|
||||
s string
|
||||
}{{GRT_format_indexed, "f=8"}, {GRT_format_indexed_alpha, "f=16"}} {
|
||||
gc = &GraphicsCommand{}
|
||||
gc.SetFormat(x.f).SetDataWidth(2).SetDataHeight(1)
|
||||
test_serialize("ab", x.s, "s=2", "v=1")
|
||||
if q = from_full_apc_escape_code(gc.AsAPC(nil)); q.Format() != x.f {
|
||||
t.Fatalf("Failed to parse format %s, got: %s", x.s, q.Format())
|
||||
}
|
||||
}
|
||||
|
||||
test_chunked_payload([]byte("abcd"))
|
||||
data := make([]byte, 8111)
|
||||
_, _ = rand.Read(data)
|
||||
test_chunked_payload(data)
|
||||
test_chunked_payload([]byte(strings.Repeat("a", 8007)))
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// Tells kitty that a program it cannot see exit has exited, so that it can drop
|
||||
// the program status (OSC 7501) records that do not outlive the program
|
||||
const PROGRAM_STATUS_PROCESS_EXITED = "\x1b]7501;process-exited\x1b\\"
|
||||
|
||||
func HoldTillEnter(start_with_newline bool) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
if start_with_newline {
|
||||
lp.QueueWriteString("\r\n")
|
||||
}
|
||||
lp.QueueWriteString("\x1b[1;32mPress Enter or Esc to exit\x1b[m")
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
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()
|
||||
}
|
||||
|
||||
func ExecAndHoldTillEnter(cmdline []string) (int, error) {
|
||||
if len(cmdline) == 0 {
|
||||
HoldTillEnter(false)
|
||||
return 0, nil
|
||||
}
|
||||
var cmd *exec.Cmd
|
||||
if len(cmdline) == 1 {
|
||||
cmd = exec.Command(cmdline[0])
|
||||
} else {
|
||||
cmd = exec.Command(cmdline[0], cmdline[1:]...)
|
||||
}
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
var ee *exec.ExitError
|
||||
err := cmd.Run()
|
||||
_, _ = os.Stdout.WriteString(PROGRAM_STATUS_PROCESS_EXITED)
|
||||
is_exit_error := err != nil && errors.As(err, &ee)
|
||||
if err != nil && !is_exit_error {
|
||||
return 1, err
|
||||
}
|
||||
HoldTillEnter(true)
|
||||
if err == nil {
|
||||
return 0, nil
|
||||
}
|
||||
if is_exit_error {
|
||||
return ee.ExitCode(), nil
|
||||
}
|
||||
return 1, err
|
||||
}
|
||||
@@ -0,0 +1,758 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/machine_id"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
type ScreenSize struct {
|
||||
WidthCells, HeightCells, WidthPx, HeightPx, CellWidth, CellHeight uint
|
||||
updated bool
|
||||
}
|
||||
|
||||
type IdType uint64
|
||||
type TimerCallback func(timer_id IdType) error
|
||||
type EscapeCodeType int
|
||||
|
||||
const (
|
||||
CSI EscapeCodeType = iota
|
||||
DCS
|
||||
OSC
|
||||
APC
|
||||
SOS
|
||||
PM
|
||||
)
|
||||
|
||||
type DndCommand struct {
|
||||
Type byte
|
||||
Has_more bool
|
||||
Operation int
|
||||
X, Y, Xp, Yp int
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
type Loop struct {
|
||||
controlling_term *tty.Term
|
||||
terminal_options TerminalStateOptions
|
||||
screen_size ScreenSize
|
||||
seen_inband_resize bool
|
||||
escape_code_parser wcswidth.EscapeCodeParser
|
||||
keep_going bool
|
||||
death_signal unix.Signal
|
||||
exit_code int
|
||||
timers, timers_temp []*timer
|
||||
timer_id_counter, write_msg_id_counter IdType
|
||||
wakeup_channel chan byte
|
||||
panic_channel chan error
|
||||
pending_writes []write_msg
|
||||
tty_write_channel chan write_msg
|
||||
pending_mouse_events *utils.RingBuffer[MouseEvent]
|
||||
on_SIGTSTP func() error
|
||||
style_cache map[string]func(...any) string
|
||||
style_ctx style.Context
|
||||
atomic_update_active bool
|
||||
pointer_shapes []PointerShape
|
||||
dnd_chunking struct {
|
||||
active bool
|
||||
metadata DndCommand
|
||||
}
|
||||
|
||||
// Queried capabilities from terminal
|
||||
TerminalCapabilities TerminalCapabilities
|
||||
|
||||
// Suspend the loop restoring terminal state, and run the provided function. When it returns terminal state is
|
||||
// put back to what it was before suspending unless the function returns an error or an error occurs saving/restoring state.
|
||||
SuspendAndRun func(func() error) error
|
||||
|
||||
// Callbacks
|
||||
|
||||
// Called when the terminal has been fully setup. Any string returned is sent to
|
||||
// the terminal on shutdown
|
||||
OnInitialize func() (string, error)
|
||||
|
||||
// Called just before the loop shuts down. Any returned string is written to the terminal before
|
||||
// shutdown
|
||||
OnFinalize func() string
|
||||
|
||||
// Called when a key event happens
|
||||
OnKeyEvent func(event *KeyEvent) error
|
||||
|
||||
// Called when a mouse event happens
|
||||
OnMouseEvent func(event *MouseEvent) error
|
||||
|
||||
// Called when text is received either from a key event or directly from the terminal
|
||||
// Called with an empty string when bracketed paste ends
|
||||
OnText func(text string, from_key_event bool, in_bracketed_paste bool) error
|
||||
|
||||
// Called when the terminal is resized
|
||||
OnResize func(old_size ScreenSize, new_size ScreenSize) error
|
||||
|
||||
// Called when writing is done
|
||||
OnWriteComplete func(msg_id IdType, has_pending_writes bool) error
|
||||
|
||||
// Called when a response to an rc command is received
|
||||
OnRCResponse func(data []byte) error
|
||||
|
||||
// Called when a response to a query command is received
|
||||
OnQueryResponse func(key, val string, valid bool) error
|
||||
|
||||
// Called when a drag and drop protocol escape code is received
|
||||
OnDnDData func(cmd DndCommand) error
|
||||
|
||||
// Called when any input from tty is received
|
||||
OnReceivedData func(data []byte) error
|
||||
|
||||
// Called when an escape code is received that is not handled by any other handler
|
||||
OnEscapeCode func(EscapeCodeType, []byte) error
|
||||
|
||||
// Called when resuming from a SIGTSTP or Ctrl-z
|
||||
OnResumeFromStop func() error
|
||||
|
||||
// Called when main loop is woken up
|
||||
OnWakeup func() error
|
||||
|
||||
// Called on SIGINT return true if you wish to handle it yourself
|
||||
OnSIGINT func() (bool, error)
|
||||
|
||||
// Called on SIGTERM return true if you wish to handle it yourself
|
||||
OnSIGTERM func() (bool, error)
|
||||
|
||||
// Called when capabilities response is received
|
||||
OnCapabilitiesReceived func(TerminalCapabilities) error
|
||||
|
||||
// Called when the terminal's color scheme changes
|
||||
OnColorSchemeChange func(ColorPreference) error
|
||||
|
||||
// Called on focus in/out events
|
||||
OnFocusChange func(bool) error
|
||||
}
|
||||
|
||||
func New(options ...func(self *Loop)) (*Loop, error) {
|
||||
l := new_loop()
|
||||
for _, f := range options {
|
||||
f(l)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Create a loop that does not change terminal state such as keyboard mode,
|
||||
// resize/focus notifications, mouse tracking, alternate screen etc. Useful
|
||||
// for special purpose kittens such as icat/clipboard/@ etc.
|
||||
func NewForSimpleInteraction() (*Loop, error) {
|
||||
lp, err := New(
|
||||
NoAlternateScreen, NoRestoreColors, NoMouseTracking, NoInBandResizeNotifications,
|
||||
NoFocusTracking, NoKeyboardStateChange, NoRoundtripToTerminalOnExit,
|
||||
)
|
||||
if err == nil {
|
||||
lp.terminal_options.color_scheme_change_notification = false
|
||||
}
|
||||
return lp, err
|
||||
}
|
||||
|
||||
func (self *Loop) AddTimer(interval time.Duration, repeats bool, callback TimerCallback) (IdType, error) {
|
||||
return self.add_timer(interval, repeats, callback)
|
||||
}
|
||||
|
||||
func (self *Loop) CallSoon(callback TimerCallback) (IdType, error) {
|
||||
return self.add_timer(0, false, callback)
|
||||
}
|
||||
|
||||
func (self *Loop) RemoveTimer(id IdType) bool {
|
||||
return self.remove_timer(id)
|
||||
}
|
||||
|
||||
func (self *Loop) NoAlternateScreen() *Loop {
|
||||
self.terminal_options.Alternate_screen = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoAlternateScreen(self *Loop) {
|
||||
self.terminal_options.Alternate_screen = false
|
||||
}
|
||||
|
||||
func (self *Loop) NoRoundtripToTerminalOnExit() *Loop {
|
||||
self.terminal_options.roundtrip_on_exit = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoRoundtripToTerminalOnExit(self *Loop) {
|
||||
self.terminal_options.roundtrip_on_exit = false
|
||||
}
|
||||
|
||||
func (self *Loop) OnlyDisambiguateKeys() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = DISAMBIGUATE_KEYS
|
||||
return self
|
||||
}
|
||||
|
||||
func OnlyDisambiguateKeys(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = DISAMBIGUATE_KEYS
|
||||
}
|
||||
|
||||
func (self *Loop) NoKeyboardStateChange() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = NO_KEYBOARD_STATE_CHANGE
|
||||
return self
|
||||
}
|
||||
|
||||
func NoKeyboardStateChange(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = NO_KEYBOARD_STATE_CHANGE
|
||||
}
|
||||
|
||||
func (self *Loop) FullKeyboardProtocol() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = FULL_KEYBOARD_PROTOCOL
|
||||
return self
|
||||
}
|
||||
|
||||
func FullKeyboardProtocol(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = FULL_KEYBOARD_PROTOCOL
|
||||
}
|
||||
|
||||
func (self *Loop) MouseTrackingMode(mt MouseTracking) *Loop {
|
||||
self.terminal_options.mouse_tracking = mt
|
||||
return self
|
||||
}
|
||||
|
||||
func MouseTrackingMode(self *Loop, mt MouseTracking) {
|
||||
self.terminal_options.mouse_tracking = mt
|
||||
}
|
||||
|
||||
func NoMouseTracking(self *Loop) {
|
||||
self.terminal_options.mouse_tracking = NO_MOUSE_TRACKING
|
||||
}
|
||||
|
||||
func (self *Loop) NoMouseTracking() *Loop {
|
||||
self.terminal_options.mouse_tracking = NO_MOUSE_TRACKING
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Loop) NoRestoreColors() *Loop {
|
||||
self.terminal_options.restore_colors = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoRestoreColors(self *Loop) {
|
||||
self.terminal_options.restore_colors = false
|
||||
}
|
||||
|
||||
func (self *Loop) NoFocusTracking() *Loop {
|
||||
self.terminal_options.focus_tracking = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoFocusTracking(self *Loop) {
|
||||
self.terminal_options.focus_tracking = false
|
||||
}
|
||||
|
||||
func (self *Loop) RequestCurrentColorScheme() {
|
||||
self.QueueWriteString("\x1b[?996n")
|
||||
}
|
||||
|
||||
func (self *Loop) ColorSchemeChangeNotifications() *Loop {
|
||||
self.terminal_options.color_scheme_change_notification = true
|
||||
return self
|
||||
}
|
||||
|
||||
func ColorSchemeChangeNotifications(self *Loop) {
|
||||
self.terminal_options.color_scheme_change_notification = true
|
||||
}
|
||||
|
||||
func NoInBandResizeNotifications(self *Loop) {
|
||||
self.terminal_options.in_band_resize_notification = false
|
||||
}
|
||||
|
||||
func (self *Loop) DeathSignalName() string {
|
||||
if self.death_signal != SIGNULL {
|
||||
return self.death_signal.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *Loop) ScreenSize() (ScreenSize, error) {
|
||||
if self.screen_size.updated {
|
||||
return self.screen_size, nil
|
||||
}
|
||||
err := self.update_screen_size()
|
||||
return self.screen_size, err
|
||||
}
|
||||
|
||||
func (self *Loop) KillIfSignalled() {
|
||||
if self.death_signal != SIGNULL {
|
||||
kill_self(self.death_signal)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) Println(args ...any) {
|
||||
self.QueueWriteString(fmt.Sprintln(args...))
|
||||
self.QueueWriteString("\r")
|
||||
}
|
||||
|
||||
func (self *Loop) style_region(style string, start_x, start_y, end_x, end_y int) string {
|
||||
sgr := self.SprintStyled(style, "|")
|
||||
if len(sgr) > 2 {
|
||||
sgr = sgr[2:strings.IndexByte(sgr, 'm')]
|
||||
return fmt.Sprintf("\x1b[%d;%d;%d;%d;%s$r", start_y+1, start_x+1, end_y+1, end_x+1, sgr)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Apply the specified style to the specified region of the screen (0-based
|
||||
// indexing). The region is all cells from the start cell to the end cell. See
|
||||
// StyleRectangle to apply style to a rectangular area.
|
||||
func (self *Loop) StyleRegion(style string, start_x, start_y, end_x, end_y int) IdType {
|
||||
return self.QueueWriteString(self.style_region(style, start_x, start_y, end_x, end_y))
|
||||
}
|
||||
|
||||
// Apply the specified style to the specified rectangle of the screen (0-based indexing).
|
||||
func (self *Loop) StyleRectangle(style string, start_x, start_y, end_x, end_y int) IdType {
|
||||
return self.QueueWriteString("\x1b[2*x" + self.style_region(style, start_x, start_y, end_x, end_y) + "\x1b[*x")
|
||||
}
|
||||
|
||||
func (self *Loop) SprintStyled(style string, args ...any) string {
|
||||
f := self.style_cache[style]
|
||||
if f == nil {
|
||||
f = self.style_ctx.SprintFunc(style)
|
||||
self.style_cache[style] = f
|
||||
}
|
||||
return f(args...)
|
||||
}
|
||||
|
||||
func (self *Loop) PrintStyled(style string, args ...any) {
|
||||
self.QueueWriteString(self.SprintStyled(style, args...))
|
||||
}
|
||||
|
||||
func (self *Loop) SaveCursorPosition() {
|
||||
self.QueueWriteString("\x1b7")
|
||||
}
|
||||
|
||||
func (self *Loop) RestoreCursorPosition() {
|
||||
self.QueueWriteString("\x1b8")
|
||||
}
|
||||
|
||||
func (self *Loop) Printf(format string, args ...any) {
|
||||
format = strings.ReplaceAll(format, "\n", "\r\n")
|
||||
self.QueueWriteString(fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func (self *Loop) DebugPrintln(args ...any) {
|
||||
if self.controlling_term != nil {
|
||||
const limit = 2048
|
||||
msg := fmt.Sprintln(args...)
|
||||
for i := 0; i < len(msg); i += limit {
|
||||
end := min(i+limit, len(msg))
|
||||
self.QueueWriteString("\x1bP@kitty-print|")
|
||||
self.QueueWriteString(base64.StdEncoding.EncodeToString([]byte(msg[i:end])))
|
||||
self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) Run() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = parallel.Format_stacktrace_on_panic(r, 1)
|
||||
is_terminal := tty.IsTerminal(os.Stderr.Fd())
|
||||
if is_terminal {
|
||||
os.Stderr.WriteString("\x1b]\x1b\\\x1bc\x1b[H\x1b[2J") // reset terminal
|
||||
}
|
||||
os.Stderr.WriteString(err.Error())
|
||||
os.Stderr.WriteString("\n")
|
||||
if is_terminal {
|
||||
if term, err := tty.OpenControllingTerm(tty.SetRaw); err != nil {
|
||||
defer term.RestoreAndClose()
|
||||
term.DebugPrintln(err.Error())
|
||||
fmt.Println("Press any key to exit.\r")
|
||||
buf := make([]byte, 16)
|
||||
_, _ = term.Read(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return self.run()
|
||||
}
|
||||
|
||||
func (self *Loop) WakeupMainThread() bool {
|
||||
select {
|
||||
case self.wakeup_channel <- 1:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) QueueWriteString(data string) IdType {
|
||||
self.write_msg_id_counter++
|
||||
msg := write_msg{str: data, bytes: nil, id: self.write_msg_id_counter}
|
||||
self.add_write_to_pending_queue(msg)
|
||||
return msg.id
|
||||
}
|
||||
|
||||
// This is dangerous as it is upto the calling code
|
||||
// to ensure the data in the underlying array does not change
|
||||
func (self *Loop) UnsafeQueueWriteBytes(data []byte) IdType {
|
||||
self.write_msg_id_counter++
|
||||
msg := write_msg{bytes: data, id: self.write_msg_id_counter}
|
||||
self.add_write_to_pending_queue(msg)
|
||||
return msg.id
|
||||
}
|
||||
|
||||
func (self *Loop) QueueWriteBytesCopy(data []byte) IdType {
|
||||
d := make([]byte, len(data))
|
||||
copy(d, data)
|
||||
return self.UnsafeQueueWriteBytes(d)
|
||||
}
|
||||
|
||||
func (self *Loop) ExitCode() int {
|
||||
return self.exit_code
|
||||
}
|
||||
|
||||
func (self *Loop) Beep() {
|
||||
self.QueueWriteString("\a")
|
||||
}
|
||||
|
||||
func (self *Loop) StartAtomicUpdate() {
|
||||
if self.atomic_update_active {
|
||||
self.EndAtomicUpdate()
|
||||
}
|
||||
self.QueueWriteString(PENDING_UPDATE.EscapeCodeToSet())
|
||||
self.atomic_update_active = true
|
||||
}
|
||||
|
||||
func (self *Loop) IsAtomicUpdateActive() bool { return self.atomic_update_active }
|
||||
|
||||
func (self *Loop) EndAtomicUpdate() {
|
||||
if self.atomic_update_active {
|
||||
self.QueueWriteString(PENDING_UPDATE.EscapeCodeToReset())
|
||||
self.atomic_update_active = false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) SetCursorShape(shape CursorShapes, blink bool) {
|
||||
self.QueueWriteString(CursorShape(shape, blink))
|
||||
}
|
||||
|
||||
func (self *Loop) SetCursorVisible(visible bool) {
|
||||
if visible {
|
||||
self.QueueWriteString(DECTCEM.EscapeCodeToSet())
|
||||
} else {
|
||||
self.QueueWriteString(DECTCEM.EscapeCodeToReset())
|
||||
}
|
||||
}
|
||||
|
||||
const MoveCursorToTemplate = "\x1b[%d;%dH"
|
||||
|
||||
func (self *Loop) MoveCursorTo(x, y int) { // 1, 1 is top left
|
||||
if x > 0 && y > 0 {
|
||||
self.QueueWriteString(fmt.Sprintf(MoveCursorToTemplate, y, x))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) MoveCursorHorizontally(amt int) {
|
||||
if amt != 0 {
|
||||
suffix := "C"
|
||||
if amt < 0 {
|
||||
suffix = "D"
|
||||
amt *= -1
|
||||
}
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b[%d%s", amt, suffix))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) MoveCursorVertically(amt int) {
|
||||
if amt != 0 {
|
||||
suffix := "B"
|
||||
if amt < 0 {
|
||||
suffix = "A"
|
||||
amt *= -1
|
||||
}
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b[%d%s", amt, suffix))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) ClearToEndOfScreen() {
|
||||
self.QueueWriteString("\x1b[J")
|
||||
}
|
||||
|
||||
func (self *Loop) ClearToEndOfLine() {
|
||||
self.QueueWriteString("\x1b[K")
|
||||
}
|
||||
|
||||
func (self *Loop) StartBracketedPaste() {
|
||||
self.QueueWriteString(BRACKETED_PASTE.EscapeCodeToSet())
|
||||
}
|
||||
|
||||
func (self *Loop) EndBracketedPaste() {
|
||||
self.QueueWriteString(BRACKETED_PASTE.EscapeCodeToReset())
|
||||
}
|
||||
|
||||
func (self *Loop) AllowLineWrapping(allow bool) {
|
||||
if allow {
|
||||
self.QueueWriteString(DECAWM.EscapeCodeToSet())
|
||||
} else {
|
||||
self.QueueWriteString(DECAWM.EscapeCodeToReset())
|
||||
}
|
||||
}
|
||||
|
||||
func EscapeCodeToSetWindowTitle(title string) string {
|
||||
title = wcswidth.StripEscapeCodes(title)
|
||||
return "\033]2;" + title + "\033\\"
|
||||
}
|
||||
|
||||
func (self *Loop) SetWindowTitle(title string) {
|
||||
self.QueueWriteString(EscapeCodeToSetWindowTitle(title))
|
||||
}
|
||||
|
||||
func (self *Loop) ClearScreen() {
|
||||
self.QueueWriteString("\x1b[H\x1b[2J")
|
||||
}
|
||||
|
||||
func (self *Loop) ClearScreenButNotGraphics() {
|
||||
self.QueueWriteString("\x1b[H\x1b[J")
|
||||
}
|
||||
|
||||
func (self *Loop) SendOverlayReady() {
|
||||
self.QueueWriteString("\x1bP@kitty-overlay-ready|\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) Quit(exit_code int) {
|
||||
self.exit_code = exit_code
|
||||
self.keep_going = false
|
||||
}
|
||||
|
||||
type DefaultColor int
|
||||
|
||||
const (
|
||||
BACKGROUND DefaultColor = 11
|
||||
FOREGROUND DefaultColor = 10
|
||||
CURSOR DefaultColor = 12
|
||||
SELECTION_BG DefaultColor = 17
|
||||
SELECTION_FG DefaultColor = 19
|
||||
)
|
||||
|
||||
func (self *Loop) SetDefaultColor(which DefaultColor, val style.RGBA) {
|
||||
self.QueueWriteString(fmt.Sprintf("\033]%d;%s\033\\", int(which), val.AsRGBSharp()))
|
||||
}
|
||||
|
||||
func (self *Loop) copy_text_to(text, dest string) {
|
||||
self.QueueWriteString("\x1b]52;" + dest + ";")
|
||||
self.QueueWriteString(base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text)))
|
||||
self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) CopyTextToPrimarySelection(text string) {
|
||||
self.copy_text_to(text, "p")
|
||||
}
|
||||
|
||||
func (self *Loop) CopyTextToClipboard(text string) {
|
||||
self.copy_text_to(text, "c")
|
||||
}
|
||||
|
||||
func (self *Loop) QueryTerminal(fields ...string) IdType {
|
||||
if len(fields) == 0 {
|
||||
return 0
|
||||
}
|
||||
q := make([]string, len(fields))
|
||||
for i, x := range fields {
|
||||
q[i] = hex.EncodeToString(utils.UnsafeStringToBytes("kitty-query-" + x))
|
||||
}
|
||||
return self.QueueWriteString(fmt.Sprintf("\x1bP+q%s\a", strings.Join(q, ";")))
|
||||
}
|
||||
|
||||
func (self *Loop) PushPointerShape(s PointerShape) {
|
||||
self.pointer_shapes = append(self.pointer_shapes, s)
|
||||
self.QueueWriteString("\x1b]22;" + s.String() + "\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) PopPointerShape() {
|
||||
if len(self.pointer_shapes) > 0 {
|
||||
self.pointer_shapes = self.pointer_shapes[:len(self.pointer_shapes)-1]
|
||||
self.QueueWriteString("\x1b]22;<\x1b\\")
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all pointer shapes from the shape stack resetting to default pointer
|
||||
// shape. This is called automatically on loop termination.
|
||||
func (self *Loop) ClearPointerShapes() (ans []PointerShape) {
|
||||
ans = self.pointer_shapes
|
||||
for i := len(self.pointer_shapes) - 1; i >= 0; i-- {
|
||||
self.QueueWriteString("\x1b]22;<\x1b\\")
|
||||
}
|
||||
self.pointer_shapes = nil
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Loop) CurrentPointerShape() (ans PointerShape, has_shape bool) {
|
||||
if len(self.pointer_shapes) > 0 {
|
||||
has_shape = true
|
||||
ans = self.pointer_shapes[len(self.pointer_shapes)-1]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Query the terminal for various capabilities, the OnCapabilitiesReceived
|
||||
// callback will be called once the query response is received. This
|
||||
// function should be called as early as possible ideally in OnInitialize.
|
||||
func (self *Loop) QueryCapabilities() {
|
||||
self.QueueWriteString("\x1b[?u\x1b[?996n\x1b[c")
|
||||
}
|
||||
|
||||
type Alignment int
|
||||
|
||||
const (
|
||||
ALIGN_START Alignment = iota
|
||||
ALIGN_CENTER
|
||||
ALIGN_END
|
||||
)
|
||||
|
||||
type SizedText struct {
|
||||
Scale, Subscale_numerator, Subscale_denominator int
|
||||
Horizontal_alignment, Vertical_alignment Alignment
|
||||
Width int
|
||||
}
|
||||
|
||||
func (self *Loop) RecoverFromPanicInGoRoutine() {
|
||||
if r := recover(); r != nil {
|
||||
err := parallel.Format_stacktrace_on_panic(r, 1)
|
||||
// print to kitty stdout as multiple go routines might panic but only
|
||||
// one panic is reported by the main loop panic_channel
|
||||
if f := tty.KittyStdout(); f != nil {
|
||||
fmt.Fprintln(f, err)
|
||||
}
|
||||
self.panic_channel <- err
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) DrawSizedText(text string, spec SizedText) {
|
||||
b := strings.Builder{}
|
||||
b.Grow(len(text) + 24)
|
||||
b.WriteString("\x1b]66;")
|
||||
sep := ""
|
||||
if spec.Scale > 1 {
|
||||
fmt.Fprintf(&b, "%ss=%d", sep, min(spec.Scale, 7))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Width > 0 {
|
||||
fmt.Fprintf(&b, "%sw=%d", sep, min(spec.Width, 7))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Subscale_numerator > 0 {
|
||||
fmt.Fprintf(&b, "%sn=%d", sep, min(spec.Subscale_numerator, 15))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Subscale_denominator > spec.Subscale_numerator {
|
||||
fmt.Fprintf(&b, "%sd=%d", sep, min(spec.Subscale_denominator, 15))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Horizontal_alignment > ALIGN_START {
|
||||
fmt.Fprintf(&b, "%sh=%d", sep, spec.Horizontal_alignment)
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Vertical_alignment > ALIGN_START {
|
||||
fmt.Fprintf(&b, "%sv=%d", sep, spec.Vertical_alignment)
|
||||
sep = ":"
|
||||
}
|
||||
b.WriteString(";")
|
||||
b.WriteString(text)
|
||||
b.WriteString("\a")
|
||||
self.QueueWriteString(b.String())
|
||||
}
|
||||
|
||||
func (self *Loop) QueueDnDData(cmd DndCommand) IdType {
|
||||
b := strings.Builder{}
|
||||
b.Grow(64)
|
||||
as_base64 := cmd.Type == 'r' || cmd.Type == 'p'
|
||||
fmt.Fprintf(&b, "\x1b]%d;t=%c", kitty.DndCode, cmd.Type)
|
||||
add := func(key byte, val int) {
|
||||
if val != 0 {
|
||||
fmt.Fprintf(&b, ":%c=%d", key, val)
|
||||
}
|
||||
}
|
||||
add('o', cmd.Operation)
|
||||
add('x', cmd.X)
|
||||
add('y', cmd.Y)
|
||||
add('X', cmd.Xp)
|
||||
add('Y', cmd.Yp)
|
||||
payload := utils.UnsafeBytesToString(cmd.Payload)
|
||||
payload_sz := len(payload)
|
||||
if payload_sz == 0 {
|
||||
b.WriteString("\x1b\\")
|
||||
return self.QueueWriteString(b.String())
|
||||
}
|
||||
if as_base64 {
|
||||
payload_sz = base64.RawStdEncoding.EncodedLen(payload_sz)
|
||||
dest := make([]byte, payload_sz)
|
||||
base64.RawStdEncoding.Encode(dest, utils.UnsafeStringToBytes(payload))
|
||||
payload = utils.UnsafeBytesToString(dest)
|
||||
} else {
|
||||
payload = string(cmd.Payload)
|
||||
}
|
||||
const chunk_size = 4096
|
||||
var ans IdType
|
||||
for i := 0; i < len(payload); i += chunk_size {
|
||||
end := i + chunk_size
|
||||
is_last := end >= len(payload)
|
||||
end = min(end, len(payload))
|
||||
if i == 0 {
|
||||
fmt.Fprintf(&b, ":m=%d;", utils.IfElse(is_last, 0, 1))
|
||||
self.QueueWriteString(b.String())
|
||||
} else {
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b]%d;m=%d;", kitty.DndCode, utils.IfElse(is_last, 0, 1)))
|
||||
}
|
||||
self.QueueWriteString(payload[i:end])
|
||||
ans = self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func effective_machine_id(m string) string {
|
||||
if m == "" {
|
||||
if ans, err := machine_id.MachineId(); err == nil {
|
||||
m = ans
|
||||
}
|
||||
}
|
||||
if m != "" {
|
||||
mac := hmac.New(sha256.New, []byte("tty-dnd-protocol-machine-id"))
|
||||
mac.Write(utils.UnsafeStringToBytes(m))
|
||||
m = "1:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (self *Loop) StartAcceptingDrops(machine_id string, mime_types ...string) {
|
||||
self.QueueDnDData(DndCommand{Type: 'a', Payload: []byte(strings.Join(mime_types, " "))})
|
||||
if m := effective_machine_id(machine_id); m != "" {
|
||||
self.QueueDnDData(DndCommand{Type: 'a', X: 1, Payload: []byte(m)})
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) StopAcceptingDrops() {
|
||||
self.QueueDnDData(DndCommand{Type: 'A'})
|
||||
}
|
||||
|
||||
func (self *Loop) StartOfferingDrags(machine_id string) {
|
||||
payload := ""
|
||||
if m := effective_machine_id(machine_id); m != "" {
|
||||
payload = m
|
||||
}
|
||||
self.QueueDnDData(DndCommand{Type: 'o', X: 1, Payload: []byte(payload)})
|
||||
}
|
||||
|
||||
func (self *Loop) StopOfferingDrags() {
|
||||
self.QueueDnDData(DndCommand{Type: 'o', X: 2})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ColorPreference uint8
|
||||
|
||||
const (
|
||||
NO_COLOR_PREFERENCE ColorPreference = iota
|
||||
DARK_COLOR_PREFERENCE
|
||||
LIGHT_COLOR_PREFERENCE
|
||||
)
|
||||
|
||||
func (c ColorPreference) String() string {
|
||||
switch c {
|
||||
case DARK_COLOR_PREFERENCE:
|
||||
return "dark"
|
||||
case LIGHT_COLOR_PREFERENCE:
|
||||
return "light"
|
||||
default:
|
||||
return "no-preference"
|
||||
}
|
||||
}
|
||||
|
||||
type TerminalCapabilities struct {
|
||||
KeyboardProtocol bool
|
||||
KeyboardProtocolResponseReceived bool
|
||||
|
||||
ColorPreference ColorPreference
|
||||
ColorPreferenceResponseReceived bool
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
// key encoding mappings {{{
|
||||
// start csi mapping (auto generated by gen-key-constants.py do not edit)
|
||||
var functional_key_number_to_name_map = map[int]string{57344: "ESCAPE", 57345: "ENTER", 57346: "TAB", 57347: "BACKSPACE", 57348: "INSERT", 57349: "DELETE", 57350: "LEFT", 57351: "RIGHT", 57352: "UP", 57353: "DOWN", 57354: "PAGE_UP", 57355: "PAGE_DOWN", 57356: "HOME", 57357: "END", 57358: "CAPS_LOCK", 57359: "SCROLL_LOCK", 57360: "NUM_LOCK", 57361: "PRINT_SCREEN", 57362: "PAUSE", 57363: "MENU", 57364: "F1", 57365: "F2", 57366: "F3", 57367: "F4", 57368: "F5", 57369: "F6", 57370: "F7", 57371: "F8", 57372: "F9", 57373: "F10", 57374: "F11", 57375: "F12", 57376: "F13", 57377: "F14", 57378: "F15", 57379: "F16", 57380: "F17", 57381: "F18", 57382: "F19", 57383: "F20", 57384: "F21", 57385: "F22", 57386: "F23", 57387: "F24", 57388: "F25", 57389: "F26", 57390: "F27", 57391: "F28", 57392: "F29", 57393: "F30", 57394: "F31", 57395: "F32", 57396: "F33", 57397: "F34", 57398: "F35", 57399: "KP_0", 57400: "KP_1", 57401: "KP_2", 57402: "KP_3", 57403: "KP_4", 57404: "KP_5", 57405: "KP_6", 57406: "KP_7", 57407: "KP_8", 57408: "KP_9", 57409: "KP_DECIMAL", 57410: "KP_DIVIDE", 57411: "KP_MULTIPLY", 57412: "KP_SUBTRACT", 57413: "KP_ADD", 57414: "KP_ENTER", 57415: "KP_EQUAL", 57416: "KP_SEPARATOR", 57417: "KP_LEFT", 57418: "KP_RIGHT", 57419: "KP_UP", 57420: "KP_DOWN", 57421: "KP_PAGE_UP", 57422: "KP_PAGE_DOWN", 57423: "KP_HOME", 57424: "KP_END", 57425: "KP_INSERT", 57426: "KP_DELETE", 57427: "KP_BEGIN", 57428: "MEDIA_PLAY", 57429: "MEDIA_PAUSE", 57430: "MEDIA_PLAY_PAUSE", 57431: "MEDIA_REVERSE", 57432: "MEDIA_STOP", 57433: "MEDIA_FAST_FORWARD", 57434: "MEDIA_REWIND", 57435: "MEDIA_TRACK_NEXT", 57436: "MEDIA_TRACK_PREVIOUS", 57437: "MEDIA_RECORD", 57438: "LOWER_VOLUME", 57439: "RAISE_VOLUME", 57440: "MUTE_VOLUME", 57441: "LEFT_SHIFT", 57442: "LEFT_CONTROL", 57443: "LEFT_ALT", 57444: "LEFT_SUPER", 57445: "LEFT_HYPER", 57446: "LEFT_META", 57447: "RIGHT_SHIFT", 57448: "RIGHT_CONTROL", 57449: "RIGHT_ALT", 57450: "RIGHT_SUPER", 57451: "RIGHT_HYPER", 57452: "RIGHT_META", 57453: "ISO_LEVEL3_SHIFT", 57454: "ISO_LEVEL5_SHIFT"}
|
||||
|
||||
var csi_number_to_functional_number_map = map[int]int{2: 57348, 3: 57349, 5: 57354, 6: 57355, 7: 57356, 8: 57357, 9: 57346, 11: 57364, 12: 57365, 13: 57345, 14: 57367, 15: 57368, 17: 57369, 18: 57370, 19: 57371, 20: 57372, 21: 57373, 23: 57374, 24: 57375, 27: 57344, 127: 57347}
|
||||
|
||||
var letter_trailer_to_csi_number_map = map[string]int{"A": 57352, "B": 57353, "C": 57351, "D": 57350, "E": 57427, "F": 8, "H": 7, "P": 11, "Q": 12, "S": 14}
|
||||
|
||||
var tilde_trailers = map[int]bool{57348: true, 57349: true, 57354: true, 57355: true, 57366: true, 57368: true, 57369: true, 57370: true, 57371: true, 57372: true, 57373: true, 57374: true, 57375: true}
|
||||
|
||||
// end csi mapping
|
||||
// }}}
|
||||
|
||||
var name_to_functional_number_map map[string]int
|
||||
var functional_to_csi_number_map map[int]int
|
||||
var csi_number_to_letter_trailer_map map[int]string
|
||||
|
||||
type KeyEventType uint8
|
||||
type KeyModifiers uint16
|
||||
|
||||
const (
|
||||
PRESS KeyEventType = 1
|
||||
REPEAT KeyEventType = 2
|
||||
RELEASE KeyEventType = 4
|
||||
)
|
||||
|
||||
const (
|
||||
SHIFT KeyModifiers = 1
|
||||
ALT KeyModifiers = 2
|
||||
CTRL KeyModifiers = 4
|
||||
SUPER KeyModifiers = 8
|
||||
HYPER KeyModifiers = 16
|
||||
META KeyModifiers = 32
|
||||
CAPS_LOCK KeyModifiers = 64
|
||||
NUM_LOCK KeyModifiers = 128
|
||||
)
|
||||
|
||||
func (self KeyModifiers) WithoutLocks() KeyModifiers {
|
||||
return self & ^(CAPS_LOCK | NUM_LOCK)
|
||||
}
|
||||
|
||||
func (self KeyEventType) String() string {
|
||||
switch self {
|
||||
case PRESS:
|
||||
return "PRESS"
|
||||
case REPEAT:
|
||||
return "REPEAT"
|
||||
case RELEASE:
|
||||
return "RELEASE"
|
||||
default:
|
||||
return fmt.Sprintf("KeyEventType:%d", int(self))
|
||||
}
|
||||
}
|
||||
|
||||
func (self KeyModifiers) String() string {
|
||||
ans := make([]string, 0)
|
||||
if self&SHIFT != 0 {
|
||||
ans = append(ans, "shift")
|
||||
}
|
||||
if self&ALT != 0 {
|
||||
ans = append(ans, "alt")
|
||||
}
|
||||
if self&CTRL != 0 {
|
||||
ans = append(ans, "ctrl")
|
||||
}
|
||||
if self&SUPER != 0 {
|
||||
ans = append(ans, "super")
|
||||
}
|
||||
if self&HYPER != 0 {
|
||||
ans = append(ans, "hyper")
|
||||
}
|
||||
if self&META != 0 {
|
||||
ans = append(ans, "meta")
|
||||
}
|
||||
if self&CAPS_LOCK != 0 {
|
||||
ans = append(ans, "caps_lock")
|
||||
}
|
||||
if self&NUM_LOCK != 0 {
|
||||
ans = append(ans, "num_lock")
|
||||
}
|
||||
return strings.Join(ans, "+")
|
||||
}
|
||||
|
||||
func (self KeyModifiers) HasCapsLock() bool {
|
||||
return self&CAPS_LOCK != 0
|
||||
}
|
||||
|
||||
type KeyEvent struct {
|
||||
Type KeyEventType
|
||||
Mods KeyModifiers
|
||||
Key string
|
||||
ShiftedKey string
|
||||
AlternateKey string
|
||||
Text string
|
||||
Handled bool
|
||||
|
||||
// The CSI string this key event was decoded from. Empty if not decoded from CSI.
|
||||
CSI string
|
||||
}
|
||||
|
||||
func (self *KeyEvent) String() string {
|
||||
key := self.Key
|
||||
if self.Mods > 0 {
|
||||
key = self.Mods.String() + "+" + key
|
||||
}
|
||||
ans := fmt.Sprint(self.Type, "{ ", key, " ")
|
||||
if self.Text != "" {
|
||||
ans += "Text: " + self.Text + " "
|
||||
}
|
||||
if self.ShiftedKey != "" {
|
||||
ans += "ShiftedKey: " + self.ShiftedKey + " "
|
||||
}
|
||||
if self.AlternateKey != "" {
|
||||
ans += "AlternateKey: " + self.AlternateKey + " "
|
||||
}
|
||||
return ans + "}"
|
||||
}
|
||||
|
||||
func (self *KeyEvent) HasCapsLock() bool {
|
||||
return self.Mods.HasCapsLock()
|
||||
}
|
||||
|
||||
func KeyEventFromCSI(csi string) *KeyEvent {
|
||||
if len(csi) == 0 {
|
||||
return nil
|
||||
}
|
||||
orig_csi := csi
|
||||
last_char := csi[len(csi)-1:]
|
||||
if !strings.Contains("u~ABCDEHFPQS", last_char) || (last_char == "~" && (csi == "200~" || csi == "201~")) {
|
||||
return nil
|
||||
}
|
||||
csi = csi[:len(csi)-1]
|
||||
sections := strings.Split(csi, ";")
|
||||
|
||||
get_sub_sections := func(section string, missing int32) []int32 {
|
||||
p := strings.Split(section, ":")
|
||||
ans := make([]int32, len(p))
|
||||
for i, x := range p {
|
||||
if x == "" {
|
||||
ans[i] = missing
|
||||
} else {
|
||||
q, err := strconv.ParseUint(x, 10, 32)
|
||||
if err != nil || q > math.MaxInt32 {
|
||||
return nil
|
||||
}
|
||||
ans[i] = int32(q)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
first_section := get_sub_sections(sections[0], 0)
|
||||
second_section := []int32{}
|
||||
third_section := []int32{}
|
||||
if len(sections) > 1 {
|
||||
second_section = get_sub_sections(sections[1], 1)
|
||||
}
|
||||
if len(sections) > 2 {
|
||||
third_section = get_sub_sections(sections[2], 0)
|
||||
}
|
||||
var ans = KeyEvent{Type: PRESS, CSI: orig_csi}
|
||||
var keynum int32
|
||||
if val, ok := letter_trailer_to_csi_number_map[last_char]; ok {
|
||||
keynum = int32(val)
|
||||
} else {
|
||||
if len(first_section) == 0 {
|
||||
return nil
|
||||
}
|
||||
keynum = first_section[0]
|
||||
}
|
||||
|
||||
key_name := func(keynum int32) string {
|
||||
switch keynum {
|
||||
case 0:
|
||||
return ""
|
||||
case 13:
|
||||
if last_char == "u" {
|
||||
return "ENTER"
|
||||
}
|
||||
return "F3"
|
||||
default:
|
||||
if val, ok := csi_number_to_functional_number_map[int(keynum)]; ok {
|
||||
keynum = int32(val)
|
||||
}
|
||||
ans := ""
|
||||
if val, ok := functional_key_number_to_name_map[int(keynum)]; ok {
|
||||
ans = val
|
||||
} else {
|
||||
ans = string(rune(keynum))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
}
|
||||
|
||||
ans.Key = key_name(keynum)
|
||||
if len(first_section) > 1 {
|
||||
ans.ShiftedKey = key_name(first_section[1])
|
||||
}
|
||||
if len(first_section) > 2 {
|
||||
ans.AlternateKey = key_name(first_section[2])
|
||||
}
|
||||
if len(second_section) > 0 {
|
||||
ans.Mods = KeyModifiers(second_section[0] - 1)
|
||||
}
|
||||
if len(second_section) > 1 {
|
||||
switch second_section[1] {
|
||||
case 2:
|
||||
ans.Type = REPEAT
|
||||
case 3:
|
||||
ans.Type = RELEASE
|
||||
}
|
||||
}
|
||||
if len(third_section) > 0 {
|
||||
runes := make([]rune, len(third_section))
|
||||
for i, ch := range third_section {
|
||||
runes[i] = rune(ch)
|
||||
}
|
||||
ans.Text = string(runes)
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
type ParsedShortcut struct {
|
||||
Mods KeyModifiers
|
||||
KeyName string
|
||||
}
|
||||
|
||||
func (self *ParsedShortcut) String() string {
|
||||
ans := self.KeyName
|
||||
if self.Mods > 0 {
|
||||
ans = self.Mods.String() + "+" + ans
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
var parsed_shortcut_cache map[string]*ParsedShortcut
|
||||
|
||||
func ParseShortcut(spec string) *ParsedShortcut {
|
||||
if parsed_shortcut_cache == nil {
|
||||
parsed_shortcut_cache = make(map[string]*ParsedShortcut, 128)
|
||||
}
|
||||
if val, ok := parsed_shortcut_cache[spec]; ok {
|
||||
return val
|
||||
}
|
||||
ospec := spec
|
||||
if strings.HasSuffix(spec, "+") {
|
||||
ospec = spec[:len(spec)-1] + "plus"
|
||||
}
|
||||
parts := strings.Split(ospec, "+")
|
||||
key_name := parts[len(parts)-1]
|
||||
if val, ok := kitty.FunctionalKeyNameAliases[strings.ToUpper(key_name)]; ok {
|
||||
key_name = val
|
||||
}
|
||||
if _, is_functional_key := name_to_functional_number_map[strings.ToUpper(key_name)]; is_functional_key {
|
||||
key_name = strings.ToUpper(key_name)
|
||||
} else {
|
||||
if val, ok := kitty.CharacterKeyNameAliases[strings.ToUpper(key_name)]; ok {
|
||||
key_name = val
|
||||
}
|
||||
}
|
||||
ans := ParsedShortcut{KeyName: key_name}
|
||||
if len(parts) > 1 {
|
||||
for _, q := range parts[:len(parts)-1] {
|
||||
val, ok := kitty.ConfigModMap[strings.ToUpper(q)]
|
||||
if ok {
|
||||
ans.Mods |= KeyModifiers(val)
|
||||
} else {
|
||||
ans.Mods |= META << 8
|
||||
}
|
||||
}
|
||||
}
|
||||
parsed_shortcut_cache[spec] = &ans
|
||||
return &ans
|
||||
}
|
||||
|
||||
func isNonASCIIKey(key string) bool {
|
||||
r, size := utf8.DecodeRuneInString(key)
|
||||
return size > 0 && size == len(key) && r > 127 && r < 0xE000 && r != utf8.RuneError
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesParsedShortcutWithFallback(ps *ParsedShortcut, event_type KeyEventType, allowFallback string) bool {
|
||||
return self.MatchesParsedShortcutPriorityWithFallback(ps, event_type, allowFallback) >= 0
|
||||
}
|
||||
|
||||
// MatchesParsedShortcutPriorityWithFallback returns the match priority for the given shortcut:
|
||||
// - returns -1 if the event does not match
|
||||
// - returns 0 for a direct match (no fallback needed)
|
||||
// - returns the 1-based position of the matching fallback type in allowFallback for a fallback match
|
||||
// (e.g., "shifted" at position 0 in "shifted,ascii" returns 1; "ascii" at position 1 returns 2)
|
||||
//
|
||||
// Lower values indicate higher priority, so callers should prefer matches with smaller return values.
|
||||
func (self *KeyEvent) MatchesParsedShortcutPriorityWithFallback(ps *ParsedShortcut, event_type KeyEventType, allowFallback string) int {
|
||||
if self.Type&event_type == 0 {
|
||||
return -1
|
||||
}
|
||||
mods := self.Mods.WithoutLocks()
|
||||
if mods == ps.Mods && self.Key == ps.KeyName {
|
||||
return 0
|
||||
}
|
||||
canShifted := self.ShiftedKey != "" && mods&SHIFT != 0 && (mods & ^SHIFT) == ps.Mods && self.ShiftedKey == ps.KeyName
|
||||
canASCII := self.AlternateKey != "" && isNonASCIIKey(self.Key) && mods == ps.Mods && self.AlternateKey == ps.KeyName
|
||||
for i, part := range strings.Split(allowFallback, ",") {
|
||||
switch strings.TrimSpace(part) {
|
||||
case "shifted":
|
||||
if canShifted {
|
||||
return i + 1
|
||||
}
|
||||
case "ascii":
|
||||
if canASCII {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// MatchesPressOrRepeatPriorityWithFallback returns the match priority (see MatchesParsedShortcutPriorityWithFallback).
|
||||
func (self *KeyEvent) MatchesPressOrRepeatPriorityWithFallback(spec string, allowFallback string) int {
|
||||
return self.MatchesParsedShortcutPriorityWithFallback(ParseShortcut(spec), PRESS|REPEAT, allowFallback)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesParsedShortcut(ps *ParsedShortcut, event_type KeyEventType) bool {
|
||||
return self.MatchesParsedShortcutWithFallback(ps, event_type, "shifted,ascii")
|
||||
}
|
||||
|
||||
func (self *KeyEvent) Matches(spec string, event_type KeyEventType) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), event_type)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesPressOrRepeat(spec string) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesPressOrRepeatWithFallback(spec string, allowFallback string) bool {
|
||||
return self.MatchesParsedShortcutWithFallback(ParseShortcut(spec), PRESS|REPEAT, allowFallback)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesCaseSensitiveTextOrKey(spec string) bool {
|
||||
if self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT) {
|
||||
return true
|
||||
}
|
||||
return self.Text == spec
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesCaseInsensitiveTextOrKey(spec string) bool {
|
||||
if self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT) {
|
||||
return true
|
||||
}
|
||||
return strings.EqualFold(self.Text, spec)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesRelease(spec string) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), RELEASE)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) AsCSI() string {
|
||||
key := csi_number_for_name(self.Key)
|
||||
shifted_key := csi_number_for_name(self.ShiftedKey)
|
||||
alternate_key := csi_number_for_name(self.AlternateKey)
|
||||
trailer, found := csi_number_to_letter_trailer_map[key]
|
||||
if !found {
|
||||
trailer = "u"
|
||||
}
|
||||
if self.Key == "ENTER" {
|
||||
trailer = "u"
|
||||
}
|
||||
if trailer != "u" {
|
||||
key = 1
|
||||
}
|
||||
ans := strings.Builder{}
|
||||
ans.Grow(32)
|
||||
ans.WriteString("\033[")
|
||||
if key != 1 || self.Mods != 0 || shifted_key != 0 || alternate_key != 0 || self.Text != "" {
|
||||
fmt.Fprint(&ans, key)
|
||||
}
|
||||
if shifted_key != 0 || alternate_key != 0 {
|
||||
ans.WriteString(":")
|
||||
if shifted_key != 0 {
|
||||
fmt.Fprint(&ans, shifted_key)
|
||||
}
|
||||
if alternate_key != 0 {
|
||||
fmt.Fprint(&ans, ":", alternate_key)
|
||||
}
|
||||
}
|
||||
action := 1
|
||||
switch self.Type {
|
||||
case REPEAT:
|
||||
action = 2
|
||||
case RELEASE:
|
||||
action = 3
|
||||
}
|
||||
if self.Mods != 0 || action > 1 || self.Text != "" {
|
||||
m := uint(self.Mods)
|
||||
if action > 1 || m != 0 {
|
||||
fmt.Fprintf(&ans, ";%d", m+1)
|
||||
if action > 1 {
|
||||
fmt.Fprintf(&ans, ":%d", action)
|
||||
}
|
||||
} else if self.Text != "" {
|
||||
ans.WriteString(";")
|
||||
}
|
||||
}
|
||||
if self.Text != "" {
|
||||
runes := []rune(self.Text)
|
||||
codes := make([]string, len(runes))
|
||||
for i, r := range runes {
|
||||
codes[i] = strconv.Itoa(int(r))
|
||||
}
|
||||
ans.WriteString(";")
|
||||
ans.WriteString(strings.Join(codes, ":"))
|
||||
}
|
||||
fn, found := name_to_functional_number_map[self.Key]
|
||||
if found && tilde_trailers[fn] {
|
||||
trailer = "~"
|
||||
}
|
||||
ans.WriteString(trailer)
|
||||
return ans.String()
|
||||
}
|
||||
|
||||
func csi_number_for_name(key_name string) int {
|
||||
if key_name == "" {
|
||||
return 0
|
||||
}
|
||||
if key_name == "F3" || key_name == "ENTER" {
|
||||
return 13
|
||||
}
|
||||
fn, ok := name_to_functional_number_map[key_name]
|
||||
if !ok {
|
||||
return int(rune(key_name[0]))
|
||||
}
|
||||
ans, ok := functional_to_csi_number_map[fn]
|
||||
if ok {
|
||||
return ans
|
||||
}
|
||||
return fn
|
||||
}
|
||||
|
||||
func init() {
|
||||
name_to_functional_number_map = make(map[string]int, len(functional_key_number_to_name_map))
|
||||
for k, v := range functional_key_number_to_name_map {
|
||||
name_to_functional_number_map[v] = k
|
||||
}
|
||||
functional_to_csi_number_map = make(map[int]int, len(csi_number_to_functional_number_map))
|
||||
for k, v := range csi_number_to_functional_number_map {
|
||||
functional_to_csi_number_map[v] = k
|
||||
}
|
||||
csi_number_to_letter_trailer_map = make(map[int]string, len(letter_trailer_to_csi_number_map))
|
||||
for k, v := range letter_trailer_to_csi_number_map {
|
||||
csi_number_to_letter_trailer_map[v] = k
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestKeyEventFromCSI(t *testing.T) {
|
||||
|
||||
test_text := func(csi string, expected, alternate string) {
|
||||
ev := KeyEventFromCSI(csi)
|
||||
if ev == nil {
|
||||
t.Fatalf("Failed to get parse %#v", csi)
|
||||
}
|
||||
if diff := cmp.Diff(expected, ev.Text); diff != "" {
|
||||
t.Fatalf("Failed to get text from %#v:\n%s", csi, diff)
|
||||
}
|
||||
if diff := cmp.Diff(alternate, ev.AlternateKey); diff != "" {
|
||||
t.Fatalf("Failed to get alternate from %#v:\n%s", csi, diff)
|
||||
}
|
||||
}
|
||||
test_text("121;;121u", "y", "")
|
||||
test_text("121::122;;121u", "y", "z")
|
||||
}
|
||||
|
||||
func TestIsNonASCIIKey(t *testing.T) {
|
||||
if !isNonASCIIKey("с") { // Cyrillic с (U+0441)
|
||||
t.Fatal("Cyrillic с should be non-ASCII")
|
||||
}
|
||||
if isNonASCIIKey("c") { // Latin c
|
||||
t.Fatal("Latin c should be ASCII")
|
||||
}
|
||||
if isNonASCIIKey("") {
|
||||
t.Fatal("empty string should not be non-ASCII")
|
||||
}
|
||||
// boundary: U+0080 (first non-ASCII) should be true
|
||||
if !isNonASCIIKey("\u0080") {
|
||||
t.Fatal("U+0080 should be non-ASCII")
|
||||
}
|
||||
// boundary: U+007F (DEL, last ASCII) should be false
|
||||
if isNonASCIIKey("\u007f") {
|
||||
t.Fatal("U+007F should be ASCII")
|
||||
}
|
||||
// boundary: U+D7FF (last valid BMP char before surrogates) should be true
|
||||
if !isNonASCIIKey("\uD7FF") {
|
||||
t.Fatal("U+D7FF should be non-ASCII (before PUA)")
|
||||
}
|
||||
// boundary: U+E000 (first PUA, functional key range) should be false
|
||||
if isNonASCIIKey("\uE000") {
|
||||
t.Fatal("U+E000 should be excluded (functional key range)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutWithFallback(t *testing.T) {
|
||||
ps := ParseShortcut("ctrl+c")
|
||||
|
||||
// Per-mapping ascii match: Cyrillic key + AlternateKey=c + allow_fallback contains ascii
|
||||
ev := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if !ev.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted,ascii") {
|
||||
t.Fatal("should match via AlternateKey with allow_fallback=shifted,ascii")
|
||||
}
|
||||
if !ev.MatchesParsedShortcutWithFallback(ps, PRESS, "ascii") {
|
||||
t.Fatal("should match via AlternateKey with allow_fallback=ascii")
|
||||
}
|
||||
|
||||
// Per-mapping no ascii match when allow_fallback=shifted only
|
||||
if ev.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted") {
|
||||
t.Fatal("should NOT match via AlternateKey with allow_fallback=shifted (no ascii)")
|
||||
}
|
||||
|
||||
// No fallback at all
|
||||
if ev.MatchesParsedShortcutWithFallback(ps, PRESS, "") {
|
||||
t.Fatal("should NOT match with empty allow_fallback")
|
||||
}
|
||||
|
||||
// Direct Key match takes priority (always works regardless of allow_fallback)
|
||||
evDirect := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "c"}
|
||||
if !evDirect.MatchesParsedShortcutWithFallback(ps, PRESS, "") {
|
||||
t.Fatal("direct Key match should work even with empty allow_fallback")
|
||||
}
|
||||
if !evDirect.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted") {
|
||||
t.Fatal("direct Key match should work with any allow_fallback")
|
||||
}
|
||||
|
||||
// No AlternateKey match when Key is ASCII (Dvorak safety: non-ASCII guard)
|
||||
evDvorak := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "x", AlternateKey: "c"}
|
||||
if evDvorak.MatchesParsedShortcutWithFallback(ps, PRESS, "ascii") {
|
||||
t.Fatal("should NOT match via AlternateKey when Key is ASCII (Dvorak)")
|
||||
}
|
||||
|
||||
// Shifted fallback respects per-mapping allow_fallback
|
||||
psA := ParseShortcut("a")
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if !evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "shifted") {
|
||||
t.Fatal("shifted fallback should work with allow_fallback=shifted")
|
||||
}
|
||||
if evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "ascii") {
|
||||
t.Fatal("shifted fallback should NOT work with allow_fallback=ascii only")
|
||||
}
|
||||
if evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "") {
|
||||
t.Fatal("shifted fallback should NOT work with empty allow_fallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutPriorityWithFallback(t *testing.T) {
|
||||
psA := ParseShortcut("a")
|
||||
psCtrlC := ParseShortcut("ctrl+c")
|
||||
|
||||
// Direct match: priority 0
|
||||
evDirect := &KeyEvent{Type: PRESS, Key: "a"}
|
||||
if p := evDirect.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, ""); p != 0 {
|
||||
t.Fatalf("direct match should have priority 0, got %d", p)
|
||||
}
|
||||
|
||||
// No match: priority -1
|
||||
evNoMatch := &KeyEvent{Type: PRESS, Key: "b"}
|
||||
if p := evNoMatch.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted,ascii"); p != -1 {
|
||||
t.Fatalf("no match should have priority -1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback at position 0 in "shifted,ascii": priority 1
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted,ascii"); p != 1 {
|
||||
t.Fatalf("shifted fallback first in 'shifted,ascii' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback at position 1 in "ascii,shifted": priority 2
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "ascii,shifted"); p != 2 {
|
||||
t.Fatalf("shifted fallback second in 'ascii,shifted' should have priority 2, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback only in "shifted": priority 1 (same as first position)
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted"); p != 1 {
|
||||
t.Fatalf("shifted fallback only in 'shifted' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback not allowed: priority -1
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "ascii"); p != -1 {
|
||||
t.Fatalf("shifted fallback not in 'ascii' should have priority -1, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII (alternate key) fallback at position 1 in "shifted,ascii": priority 2
|
||||
evASCII := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "shifted,ascii"); p != 2 {
|
||||
t.Fatalf("ascii fallback second in 'shifted,ascii' should have priority 2, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII fallback at position 0 in "ascii,shifted": priority 1
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "ascii,shifted"); p != 1 {
|
||||
t.Fatalf("ascii fallback first in 'ascii,shifted' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII fallback only in "ascii": priority 1
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "ascii"); p != 1 {
|
||||
t.Fatalf("ascii fallback only in 'ascii' should have priority 1, got %d", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutUnconditionalAlternateKey(t *testing.T) {
|
||||
// Unconditional match via MatchesPressOrRepeat (hardcoded shortcuts)
|
||||
ev := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if !ev.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("MatchesPressOrRepeat should match via AlternateKey with non-ASCII guard")
|
||||
}
|
||||
|
||||
// Direct Key match takes priority in unconditional mode too
|
||||
evDirect := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "c"}
|
||||
if !evDirect.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("direct Key match should work in unconditional mode")
|
||||
}
|
||||
|
||||
// No AlternateKey match when Key is ASCII (Dvorak safety)
|
||||
evDvorak := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "x", AlternateKey: "c"}
|
||||
if evDvorak.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("should NOT match via AlternateKey when Key is ASCII in unconditional mode")
|
||||
}
|
||||
|
||||
// ShiftedKey still works unconditionally
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if !evShifted.MatchesPressOrRepeat("a") {
|
||||
t.Fatal("ShiftedKey should match unconditionally in MatchesParsedShortcut")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type MouseEventType uint
|
||||
type MouseButtonFlag uint
|
||||
|
||||
const (
|
||||
MOUSE_PRESS MouseEventType = iota
|
||||
MOUSE_RELEASE
|
||||
MOUSE_MOVE
|
||||
MOUSE_CLICK
|
||||
MOUSE_LEAVE
|
||||
)
|
||||
|
||||
func (e MouseEventType) String() string {
|
||||
switch e {
|
||||
case MOUSE_PRESS:
|
||||
return "press"
|
||||
case MOUSE_RELEASE:
|
||||
return "release"
|
||||
case MOUSE_MOVE:
|
||||
return "move"
|
||||
case MOUSE_CLICK:
|
||||
return "click"
|
||||
}
|
||||
return strconv.Itoa(int(e))
|
||||
}
|
||||
|
||||
type PointerShape uint8
|
||||
|
||||
const (
|
||||
// start pointer shape enum (auto generated by gen-key-constants.py do not edit)
|
||||
DEFAULT_POINTER PointerShape = 0
|
||||
TEXT_POINTER PointerShape = 1
|
||||
POINTER_POINTER PointerShape = 2
|
||||
HELP_POINTER PointerShape = 3
|
||||
WAIT_POINTER PointerShape = 4
|
||||
PROGRESS_POINTER PointerShape = 5
|
||||
CROSSHAIR_POINTER PointerShape = 6
|
||||
CELL_POINTER PointerShape = 7
|
||||
VERTICAL_TEXT_POINTER PointerShape = 8
|
||||
MOVE_POINTER PointerShape = 9
|
||||
E_RESIZE_POINTER PointerShape = 10
|
||||
NE_RESIZE_POINTER PointerShape = 11
|
||||
NW_RESIZE_POINTER PointerShape = 12
|
||||
N_RESIZE_POINTER PointerShape = 13
|
||||
SE_RESIZE_POINTER PointerShape = 14
|
||||
SW_RESIZE_POINTER PointerShape = 15
|
||||
S_RESIZE_POINTER PointerShape = 16
|
||||
W_RESIZE_POINTER PointerShape = 17
|
||||
EW_RESIZE_POINTER PointerShape = 18
|
||||
NS_RESIZE_POINTER PointerShape = 19
|
||||
NESW_RESIZE_POINTER PointerShape = 20
|
||||
NWSE_RESIZE_POINTER PointerShape = 21
|
||||
ZOOM_IN_POINTER PointerShape = 22
|
||||
ZOOM_OUT_POINTER PointerShape = 23
|
||||
ALIAS_POINTER PointerShape = 24
|
||||
COPY_POINTER PointerShape = 25
|
||||
NOT_ALLOWED_POINTER PointerShape = 26
|
||||
NO_DROP_POINTER PointerShape = 27
|
||||
GRAB_POINTER PointerShape = 28
|
||||
GRABBING_POINTER PointerShape = 29
|
||||
|
||||
// end pointer shape enum
|
||||
)
|
||||
|
||||
func (e PointerShape) String() string {
|
||||
switch e {
|
||||
// start pointer shape tostring (auto generated by gen-key-constants.py do not edit)
|
||||
case DEFAULT_POINTER:
|
||||
return "default"
|
||||
case TEXT_POINTER:
|
||||
return "text"
|
||||
case POINTER_POINTER:
|
||||
return "pointer"
|
||||
case HELP_POINTER:
|
||||
return "help"
|
||||
case WAIT_POINTER:
|
||||
return "wait"
|
||||
case PROGRESS_POINTER:
|
||||
return "progress"
|
||||
case CROSSHAIR_POINTER:
|
||||
return "crosshair"
|
||||
case CELL_POINTER:
|
||||
return "cell"
|
||||
case VERTICAL_TEXT_POINTER:
|
||||
return "vertical-text"
|
||||
case MOVE_POINTER:
|
||||
return "move"
|
||||
case E_RESIZE_POINTER:
|
||||
return "e-resize"
|
||||
case NE_RESIZE_POINTER:
|
||||
return "ne-resize"
|
||||
case NW_RESIZE_POINTER:
|
||||
return "nw-resize"
|
||||
case N_RESIZE_POINTER:
|
||||
return "n-resize"
|
||||
case SE_RESIZE_POINTER:
|
||||
return "se-resize"
|
||||
case SW_RESIZE_POINTER:
|
||||
return "sw-resize"
|
||||
case S_RESIZE_POINTER:
|
||||
return "s-resize"
|
||||
case W_RESIZE_POINTER:
|
||||
return "w-resize"
|
||||
case EW_RESIZE_POINTER:
|
||||
return "ew-resize"
|
||||
case NS_RESIZE_POINTER:
|
||||
return "ns-resize"
|
||||
case NESW_RESIZE_POINTER:
|
||||
return "nesw-resize"
|
||||
case NWSE_RESIZE_POINTER:
|
||||
return "nwse-resize"
|
||||
case ZOOM_IN_POINTER:
|
||||
return "zoom-in"
|
||||
case ZOOM_OUT_POINTER:
|
||||
return "zoom-out"
|
||||
case ALIAS_POINTER:
|
||||
return "alias"
|
||||
case COPY_POINTER:
|
||||
return "copy"
|
||||
case NOT_ALLOWED_POINTER:
|
||||
return "not-allowed"
|
||||
case NO_DROP_POINTER:
|
||||
return "no-drop"
|
||||
case GRAB_POINTER:
|
||||
return "grab"
|
||||
case GRABBING_POINTER:
|
||||
return "grabbing"
|
||||
// end pointer shape tostring
|
||||
}
|
||||
return strconv.Itoa(int(e))
|
||||
}
|
||||
|
||||
const (
|
||||
SHIFT_INDICATOR int = 1 << 2
|
||||
ALT_INDICATOR = 1 << 3
|
||||
CTRL_INDICATOR = 1 << 4
|
||||
MOTION_INDICATOR = 1 << 5
|
||||
SCROLL_BUTTON_INDICATOR = 1 << 6
|
||||
EXTRA_BUTTON_INDICATOR = 1 << 7
|
||||
LEAVE_INDICATOR = 1 << 8
|
||||
)
|
||||
|
||||
const (
|
||||
NO_MOUSE_BUTTON MouseButtonFlag = 0
|
||||
LEFT_MOUSE_BUTTON MouseButtonFlag = 1 << iota
|
||||
MIDDLE_MOUSE_BUTTON
|
||||
RIGHT_MOUSE_BUTTON
|
||||
FOURTH_MOUSE_BUTTON
|
||||
FIFTH_MOUSE_BUTTON
|
||||
SIXTH_MOUSE_BUTTON
|
||||
SEVENTH_MOUSE_BUTTON
|
||||
MOUSE_WHEEL_UP
|
||||
MOUSE_WHEEL_DOWN
|
||||
MOUSE_WHEEL_LEFT
|
||||
MOUSE_WHEEL_RIGHT
|
||||
)
|
||||
|
||||
var bmap = [...]MouseButtonFlag{LEFT_MOUSE_BUTTON, MIDDLE_MOUSE_BUTTON, RIGHT_MOUSE_BUTTON}
|
||||
var ebmap = [...]MouseButtonFlag{FOURTH_MOUSE_BUTTON, FIFTH_MOUSE_BUTTON, SIXTH_MOUSE_BUTTON, SEVENTH_MOUSE_BUTTON}
|
||||
var wbmap = [...]MouseButtonFlag{MOUSE_WHEEL_UP, MOUSE_WHEEL_DOWN, MOUSE_WHEEL_LEFT, MOUSE_WHEEL_RIGHT}
|
||||
|
||||
func (b MouseButtonFlag) String() string {
|
||||
ans := ""
|
||||
switch {
|
||||
case b&LEFT_MOUSE_BUTTON != 0:
|
||||
ans += "|LEFT"
|
||||
case b&MIDDLE_MOUSE_BUTTON != 0:
|
||||
ans += "|MIDDLE"
|
||||
case b&RIGHT_MOUSE_BUTTON != 0:
|
||||
ans += "|RIGHT"
|
||||
case b&FOURTH_MOUSE_BUTTON != 0:
|
||||
ans += "|FOURTH"
|
||||
case b&FIFTH_MOUSE_BUTTON != 0:
|
||||
ans += "|FIFTH"
|
||||
case b&SIXTH_MOUSE_BUTTON != 0:
|
||||
ans += "|SIXTH"
|
||||
case b&SEVENTH_MOUSE_BUTTON != 0:
|
||||
ans += "|SEVENTH"
|
||||
case b&MOUSE_WHEEL_UP != 0:
|
||||
ans += "|WHEEL_UP"
|
||||
case b&MOUSE_WHEEL_DOWN != 0:
|
||||
ans += "|WHEEL_DOWN"
|
||||
case b&MOUSE_WHEEL_LEFT != 0:
|
||||
ans += "|WHEEL_LEFT"
|
||||
case b&MOUSE_WHEEL_RIGHT != 0:
|
||||
ans += "|WHEEL_RIGHT"
|
||||
}
|
||||
ans = strings.TrimLeft(ans, "|")
|
||||
if ans == "" {
|
||||
ans = "NONE"
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
type MouseEvent struct {
|
||||
Event_type MouseEventType
|
||||
Buttons MouseButtonFlag
|
||||
Mods KeyModifiers
|
||||
Cell, Pixel struct{ X, Y int }
|
||||
}
|
||||
|
||||
func (e MouseEvent) String() string {
|
||||
return fmt.Sprintf("MouseEvent{%s %s %s Cell:%v Pixel:%v}", e.Event_type, e.Buttons, e.Mods, e.Cell, e.Pixel)
|
||||
}
|
||||
|
||||
func pixel_to_cell(px, length, cell_length int) int {
|
||||
px = max(0, min(px, length-1))
|
||||
if cell_length > 0 {
|
||||
return px / cell_length
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func decode_sgr_mouse(text string, screen_size ScreenSize, last_letter byte) *MouseEvent {
|
||||
text = text[:len(text)-1]
|
||||
parts := strings.Split(text, ";")
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
}
|
||||
cb, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
ans := MouseEvent{}
|
||||
ans.Pixel.X, err = strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if len(parts[2]) < 1 {
|
||||
return nil
|
||||
}
|
||||
if ans.Pixel.Y, err = strconv.Atoi(parts[2]); err != nil {
|
||||
return nil
|
||||
}
|
||||
if last_letter == 'm' {
|
||||
ans.Event_type = MOUSE_RELEASE
|
||||
} else if cb&MOTION_INDICATOR != 0 {
|
||||
ans.Event_type = MOUSE_MOVE
|
||||
}
|
||||
cb3 := cb & 3
|
||||
switch {
|
||||
case cb&LEAVE_INDICATOR != 0:
|
||||
ans.Event_type = MOUSE_LEAVE
|
||||
case cb&EXTRA_BUTTON_INDICATOR != 0:
|
||||
ans.Buttons |= ebmap[cb3]
|
||||
case cb&SCROLL_BUTTON_INDICATOR != 0:
|
||||
ans.Buttons |= wbmap[cb3]
|
||||
case cb3 < 3:
|
||||
ans.Buttons |= bmap[cb3]
|
||||
}
|
||||
if cb&SHIFT_INDICATOR != 0 {
|
||||
ans.Mods |= SHIFT
|
||||
}
|
||||
if cb&ALT_INDICATOR != 0 {
|
||||
ans.Mods |= ALT
|
||||
}
|
||||
if cb&CTRL_INDICATOR != 0 {
|
||||
ans.Mods |= CTRL
|
||||
}
|
||||
ans.Cell.X = pixel_to_cell(ans.Pixel.X, int(screen_size.WidthPx), int(screen_size.CellWidth))
|
||||
ans.Cell.Y = pixel_to_cell(ans.Pixel.Y, int(screen_size.HeightPx), int(screen_size.CellHeight))
|
||||
|
||||
return &ans
|
||||
}
|
||||
|
||||
func MouseEventFromCSI(csi string, screen_size ScreenSize) *MouseEvent {
|
||||
if len(csi) == 0 {
|
||||
return nil
|
||||
}
|
||||
last_char := csi[len(csi)-1]
|
||||
if last_char != 'm' && last_char != 'M' {
|
||||
return nil
|
||||
}
|
||||
switch csi[0] {
|
||||
case '<':
|
||||
return decode_sgr_mouse(csi[1:], screen_size, last_char)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *Loop) dispatch_input_data(data []byte) error {
|
||||
if self.OnReceivedData != nil {
|
||||
err := self.OnReceivedData(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := self.escape_code_parser.Parse(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func read_ignoring_temporary_errors(f *tty.Term, buf []byte) (int, error) {
|
||||
n, err := f.Read(buf)
|
||||
if is_temporary_error(err) {
|
||||
return 0, nil
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func read_from_tty(pipe_r *os.File, term *tty.Term, results_channel chan<- []byte, err_channel chan<- error, quit_channel <-chan byte, leftover_channel chan<- []byte) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err := parallel.Format_stacktrace_on_panic(r, 1)
|
||||
err_channel <- err
|
||||
}
|
||||
}()
|
||||
keep_going := true
|
||||
pipe_fd := int(pipe_r.Fd())
|
||||
tty_fd := term.Fd()
|
||||
selector := utils.CreateSelect(2)
|
||||
selector.RegisterRead(pipe_fd)
|
||||
selector.RegisterRead(tty_fd)
|
||||
|
||||
defer func() {
|
||||
close(results_channel)
|
||||
pipe_r.Close()
|
||||
}()
|
||||
|
||||
const bufsize = 2 * utils.DEFAULT_IO_BUFFER_SIZE
|
||||
|
||||
wait_for_read_available := func() {
|
||||
for {
|
||||
n, err := selector.WaitForever()
|
||||
if err != nil && err != unix.EINTR {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if selector.IsReadyToRead(pipe_fd) {
|
||||
keep_going = false
|
||||
}
|
||||
}
|
||||
|
||||
buf := make([]byte, bufsize)
|
||||
for keep_going {
|
||||
if len(buf) < 64 {
|
||||
buf = make([]byte, bufsize)
|
||||
}
|
||||
if wait_for_read_available(); !keep_going {
|
||||
break
|
||||
}
|
||||
n, err := read_ignoring_temporary_errors(term, buf)
|
||||
if err != nil {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
break
|
||||
}
|
||||
if n == 0 { // temporary error
|
||||
continue
|
||||
}
|
||||
send := buf[:n]
|
||||
buf = buf[n:]
|
||||
select {
|
||||
case results_channel <- send:
|
||||
case <-quit_channel:
|
||||
leftover_channel <- send
|
||||
keep_going = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func has_da1_response(s string) bool {
|
||||
return utils.MustCompile("\x1b\\[\\?[0-9:;]+c").FindString(s) != ""
|
||||
}
|
||||
|
||||
func do_roundtrip_to_terminal(term *tty.Term, timeout time.Duration) {
|
||||
// ask for primary device attributes
|
||||
for {
|
||||
if err := term.WriteAllString("\x1b[c"); err != nil && !is_temporary_error(err) {
|
||||
return
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
s := strings.Builder{}
|
||||
s.Grow(256)
|
||||
received := make(chan error, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
text := parallel.Format_stacktrace_on_panic(r, 1).Error()
|
||||
received <- fmt.Errorf("%s", text)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
n, err := read_ignoring_temporary_errors(term, buf)
|
||||
if n > 0 {
|
||||
s.Write(buf[:n])
|
||||
if has_da1_response(s.String()) {
|
||||
received <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
received <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-received:
|
||||
case <-time.After(timeout):
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user