chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
@@ -0,0 +1,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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user