File: api.go

package info (click to toggle)
kitty 0.45.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 27,476 kB
  • sloc: ansic: 84,285; python: 57,992; objc: 5,432; sh: 1,333; xml: 364; makefile: 144; javascript: 78
file content (56 lines) | stat: -rw-r--r-- 1,235 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>

package shortcuts

import (
	"fmt"
	"github.com/kovidgoyal/kitty/tools/tui/loop"
	"strings"
)

var _ = fmt.Print

type ShortcutMap[T comparable] struct {
	leaves   map[string]T
	children map[string]*ShortcutMap[T]
}

func (self *ShortcutMap[T]) ResolveKeyEvent(k *loop.KeyEvent, pending_keys ...string) (ac T, pending string) {
	q := self
	for _, pk := range pending_keys {
		q = self.children[pk]
		if q == nil {
			return
		}
	}
	for c, ans := range q.leaves {
		if k.MatchesPressOrRepeat(c) {
			ac = ans
			return
		}
	}
	for c := range q.children {
		if k.MatchesPressOrRepeat(c) {
			pending = c
			return
		}
	}
	return
}

func (self *ShortcutMap[T]) Add(ac T, keys ...string) (conflict T) {
	return self.add(ac, keys)
}

func (self *ShortcutMap[T]) AddOrPanic(ac T, keys ...string) {
	var zero T
	c := self.add(ac, keys)
	if c != zero {
		panic(fmt.Sprintf("The shortcut for %#v (%s) conflicted with the shortcut for %#v (%s)",
			ac, strings.Join(keys, " "), c, strings.Join(self.shortcut_for(c), " ")))
	}
}

func New[T comparable]() *ShortcutMap[T] {
	return &ShortcutMap[T]{leaves: make(map[string]T), children: make(map[string]*ShortcutMap[T])}
}