Replace list_fonts with choose-fonts kitten

This commit is contained in:
Kovid Goyal
2024-05-06 12:17:25 +05:30
parent e1b367e1b3
commit 926dfd7ba1
10 changed files with 251 additions and 110 deletions

View File

@@ -1,133 +0,0 @@
package list_fonts
import (
"fmt"
"kitty/tools/tui/subseq"
"kitty/tools/utils"
"kitty/tools/wcswidth"
)
var _ = fmt.Print
type FamilyList struct {
families, all_families []string
current_search string
display_strings []string
widths []int
max_width, current_idx int
}
func (self *FamilyList) Len() int {
return len(self.families)
}
func (self *FamilyList) Next(delta int, allow_wrapping bool) bool {
if len(self.display_strings) == 0 {
return false
}
idx := self.current_idx + delta
if !allow_wrapping && (idx < 0 || idx > self.Len()) {
return false
}
for idx < 0 {
idx += self.Len()
}
self.current_idx = idx % self.Len()
return true
}
func limit_lengths(text string) string {
t, _ := wcswidth.TruncateToVisualLengthWithWidth(text, 31)
if len(t) >= len(text) {
return text
}
return t + "…"
}
func match(expression string, items []string) []*subseq.Match {
matches := subseq.ScoreItems(expression, items, subseq.Options{Level1: " "})
matches = utils.StableSort(matches, func(a, b *subseq.Match) int {
if b.Score < a.Score {
return -1
}
if b.Score > a.Score {
return 1
}
return 0
})
return matches
}
const (
MARK_BEFORE = "\033[33m"
MARK_AFTER = "\033[39m"
)
func apply_search(families []string, expression string, marks ...string) (matched_families []string, display_strings []string) {
mark_before, mark_after := MARK_BEFORE, MARK_AFTER
if len(marks) == 2 {
mark_before, mark_after = marks[0], marks[1]
}
results := utils.Filter(match(expression, families), func(x *subseq.Match) bool { return x.Score > 0 })
matched_families = make([]string, 0, len(results))
display_strings = make([]string, 0, len(results))
for _, m := range results {
text := m.Text
positions := m.Positions
for i := len(positions) - 1; i >= 0; i-- {
p := positions[i]
text = text[:p] + mark_before + text[p:p+1] + mark_after + text[p+1:]
}
display_strings = append(display_strings, text)
matched_families = append(matched_families, m.Text)
}
return
}
func (self *FamilyList) UpdateFamilies(families []string) {
self.families, self.all_families = families, families
if self.current_search != "" {
self.families, self.display_strings = apply_search(self.all_families, self.current_search)
self.display_strings = utils.Map(limit_lengths, self.display_strings)
} else {
self.display_strings = utils.Map(limit_lengths, families)
}
self.widths = utils.Map(wcswidth.Stringwidth, self.display_strings)
self.max_width = utils.Max(0, self.widths...)
self.current_idx = 0
}
func (self *FamilyList) UpdateSearch(query string) bool {
if query == self.current_search || len(self.all_families) == 0 {
return false
}
self.current_search = query
self.UpdateFamilies(self.all_families)
return true
}
type Line struct {
text string
width int
is_current bool
}
func (self *FamilyList) Lines(num_rows int) []Line {
if num_rows < 1 {
return nil
}
ans := make([]Line, 0, len(self.display_strings))
before_num := utils.Min(self.current_idx, num_rows-1)
start := self.current_idx - before_num
for i := start; i < utils.Min(start+num_rows, len(self.display_strings)); i++ {
ans = append(ans, Line{self.display_strings[i], self.widths[i], i == self.current_idx})
}
return ans
}
func (self *FamilyList) CurrentFamily() string {
if self.current_idx >= 0 && self.current_idx < len(self.families) {
return self.families[self.current_idx]
}
return ""
}

View File

@@ -1,101 +0,0 @@
package list_fonts
import (
"encoding/json"
"fmt"
"os"
"sync"
"kitty/tools/cli"
"kitty/tools/tty"
"kitty/tools/tui/loop"
)
var _ = fmt.Print
var debugprintln = tty.DebugPrintln
var json_decoder *json.Decoder
func json_decode(v any) error {
if err := json_decoder.Decode(v); err != nil {
return fmt.Errorf("Failed to decode JSON from kitty with error: %w", err)
}
return nil
}
func to_kitty(v any) error {
data, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("Could not encode message to kitty with error: %w", err)
}
if _, err = os.Stdout.Write(data); err != nil {
return fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
}
if _, err = os.Stdout.WriteString("\n"); err != nil {
return fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
}
return nil
}
var query_kitty_lock sync.Mutex
func query_kitty(action string, cmd map[string]any, result any) error {
query_kitty_lock.Lock()
defer query_kitty_lock.Unlock()
if action != "" {
cmd["action"] = action
if err := to_kitty(cmd); err != nil {
return err
}
}
return json_decode(result)
}
func main() (rc int, err error) {
json_decoder = json.NewDecoder(os.Stdin)
lp, err := loop.New()
if err != nil {
return 1, err
}
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
h := &handler{lp: lp}
lp.OnInitialize = func() (string, error) {
lp.AllowLineWrapping(false)
lp.SetWindowTitle(`Choose a font for kitty`)
h.initialize()
return "", nil
}
lp.OnWakeup = h.on_wakeup
lp.OnFinalize = func() string {
h.finalize()
lp.SetCursorVisible(true)
return ``
}
lp.OnMouseEvent = h.on_mouse_event
lp.OnResize = func(_, _ loop.ScreenSize) error {
return h.draw_screen()
}
lp.OnKeyEvent = h.on_key_event
lp.OnText = h.on_text
err = lp.Run()
if err != nil {
return 1, err
}
ds := lp.DeathSignalName()
if ds != "" {
fmt.Println("Killed by signal: ", ds)
lp.KillIfSignalled()
return 1, nil
}
return lp.ExitCode(), nil
}
func EntryPoint(root *cli.Command) {
root = root.AddSubCommand(&cli.Command{
Name: "__list_fonts__",
Hidden: true,
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
return main()
},
})
}

View File

@@ -1,84 +0,0 @@
package list_fonts
import (
"fmt"
"kitty/tools/utils"
)
var _ = fmt.Print
type style_group struct {
name string
ordering int
styles []string
}
type family_style_data struct {
style_groups []style_group
has_variable_faces bool
has_style_attribute_data bool
}
func styles_in_family(family string, fonts []ListedFont) (ans *family_style_data) {
_ = family
ans = &family_style_data{style_groups: make([]style_group, 0)}
for _, f := range fonts {
vd := variable_data_for(f)
if len(vd.Design_axes) > 0 {
ans.has_style_attribute_data = true
}
if len(vd.Axes) > 0 {
ans.has_variable_faces = true
}
}
if ans.has_style_attribute_data {
groups := make(map[string]*style_group)
seen_map := make(map[string]*utils.Set[string])
get := func(key string, ordering int) (*style_group, *utils.Set[string]) {
sg := groups[key]
seen := seen_map[key]
if sg == nil {
ans.style_groups = append(ans.style_groups, style_group{name: key, ordering: ordering, styles: make([]string, 0)})
sg = &ans.style_groups[len(ans.style_groups)-1]
groups[key] = sg
seen = utils.NewSet[string]()
seen_map[key] = seen
}
return sg, seen
}
for _, f := range fonts {
vd := variable_data_for(f)
for _, ax := range vd.Design_axes {
if ax.Name == "" {
continue
}
sg, seen := get(ax.Name, ax.Ordering)
for _, v := range ax.Values {
if v.Name != "" && !seen.Has(v.Name) {
seen.Add(v.Name)
sg.styles = append(sg.styles, v.Name)
}
}
}
for _, ma := range vd.Multi_axis_styles {
sg, seen := get("Styles", 0)
if ma.Name != "" && !seen.Has(ma.Name) {
seen.Add(ma.Name)
sg.styles = append(sg.styles, ma.Name)
}
}
}
utils.StableSortWithKey(ans.style_groups, func(sg style_group) int { return sg.ordering })
} else {
ans.style_groups = append(ans.style_groups, style_group{name: "Styles", styles: make([]string, 0)})
sg := &ans.style_groups[0]
seen := utils.NewSet[string]()
for _, f := range fonts {
if f.Style != "" && !seen.Has(f.Style) {
seen.Add(f.Style)
sg.styles = append(sg.styles, f.Style)
}
}
}
return
}

View File

@@ -1,136 +0,0 @@
package list_fonts
import (
"fmt"
"sync"
)
var _ = fmt.Print
type VariableAxis struct {
Minimum float64 `json:"minimum"`
Maximum float64 `json:"maximum"`
Default float64 `json:"default"`
Hidden bool `json:"hidden"`
Tag string `json:"tag"`
Strid string `json:"strid"`
}
type NamedStyle struct {
Axis_values map[string]float64 `json:"axis_values"`
Name string `json:"name"`
Postscript_name string `json:"psname"`
}
type DesignAxisValue struct {
Format int `json:"format"`
Flags int `json:"flags"`
Name string `json:"name"`
Value float64 `json:"value"`
Minimum float64 `json:"minimum"`
Maximum float64 `json:"maximum"`
Linked_value float64 `json:"linked_value"`
}
type DesignAxis struct {
Tag string `json:"tag"`
Name string `json:"name"`
Ordering int `json:"ordering"`
Values []DesignAxisValue `json:"values"`
}
type AxisValue struct {
Design_index int `json:"design_index"`
Value float64 `json:"value"`
}
type MultiAxisStyle struct {
Flags int `json:"flags"`
Name string `json:"name"`
Values []AxisValue `json:"values"`
}
type ListedFont struct {
Family string `json:"family"`
Style string `json:"style"`
Fullname string `json:"full_name"`
Postscript_name string `json:"postscript_name"`
Is_monospace bool `json:"is_monospace"`
Is_variable bool `json:"is_variable"`
Descriptor map[string]any `json:"descriptor"`
}
type VariableData struct {
Axes []VariableAxis `json:"axes"`
Named_styles []NamedStyle `json:"named_styles"`
Variations_postscript_name_prefix string `json:"variations_postscript_name_prefix"`
Elided_fallback_name string `json:"elided_fallback_name"`
Design_axes []DesignAxis `json:"design_axes"`
Multi_axis_styles []MultiAxisStyle `json:"multi_axis_styles"`
}
var variable_data_cache map[string]VariableData
var variable_data_cache_mutex sync.Mutex
func (f ListedFont) cache_key() string {
key := f.Postscript_name
if key == "" {
key = "path:" + f.Descriptor["path"].(string)
} else {
key = "psname:" + key
}
return key
}
func ensure_variable_data_for_fonts(fonts ...ListedFont) error {
descriptors := make([]map[string]any, 0, len(fonts))
keys := make([]string, 0, len(fonts))
variable_data_cache_mutex.Lock()
for _, f := range fonts {
key := f.cache_key()
if _, found := variable_data_cache[key]; !found {
descriptors = append(descriptors, f.Descriptor)
keys = append(keys, key)
}
}
variable_data_cache_mutex.Unlock()
var data []VariableData
if err := query_kitty("read_variable_data", map[string]any{"descriptors": descriptors}, &data); err != nil {
return err
}
variable_data_cache_mutex.Lock()
for i, key := range keys {
variable_data_cache[key] = data[i]
}
variable_data_cache_mutex.Unlock()
return nil
}
func initialize_variable_data_cache() {
variable_data_cache = make(map[string]VariableData)
}
func _cached_vd(key string) (ans VariableData, found bool) {
variable_data_cache_mutex.Lock()
defer variable_data_cache_mutex.Unlock()
ans, found = variable_data_cache[key]
return
}
func variable_data_for(f ListedFont) VariableData {
key := f.cache_key()
ans, found := _cached_vd(key)
if found {
return ans
}
if err := ensure_variable_data_for_fonts(f); err != nil {
panic(err)
}
ans, found = _cached_vd(key)
return ans
}
func has_variable_data_for_font(font ListedFont) bool {
_, found := _cached_vd(font.cache_key())
return found
}

View File

@@ -1,311 +0,0 @@
package list_fonts
import (
"fmt"
"strings"
"sync"
"kitty/tools/tui"
"kitty/tools/tui/loop"
"kitty/tools/tui/readline"
"kitty/tools/utils"
"kitty/tools/utils/style"
"kitty/tools/wcswidth"
)
var _ = fmt.Print
type State int
const (
SCANNING_FAMILIES State = iota
LISTING_FAMILIES
CHOOSING_FACES
)
type handler struct {
lp *loop.Loop
fonts map[string][]ListedFont
state State
err_mutex sync.Mutex
err_in_worker_thread error
mouse_state tui.MouseState
render_lines tui.RenderLines
// Listing
rl *readline.Readline
family_list FamilyList
variable_data_requested_for *utils.Set[string]
}
func (h *handler) set_worker_error(err error) {
h.err_mutex.Lock()
defer h.err_mutex.Unlock()
h.err_in_worker_thread = err
}
func (h *handler) get_worker_error() error {
h.err_mutex.Lock()
defer h.err_mutex.Unlock()
return h.err_in_worker_thread
}
// Listing families {{{
func (h *handler) draw_search_bar() {
h.lp.SetCursorVisible(true)
h.lp.SetCursorShape(loop.BAR_CURSOR, true)
sz, err := h.lp.ScreenSize()
if err != nil {
return
}
h.lp.MoveCursorTo(1, int(sz.HeightCells))
h.lp.ClearToEndOfLine()
h.rl.RedrawNonAtomic()
}
const SEPARATOR = "║"
func center_string(x string, width int) string {
l := wcswidth.Stringwidth(x)
spaces := int(float64(width-l) / 2)
return strings.Repeat(" ", utils.Max(0, spaces)) + x
}
func (h *handler) draw_family_summary(start_x int, sz loop.ScreenSize) (err error) {
family := h.family_list.CurrentFamily()
if family == "" || int(sz.WidthCells) < start_x+2 {
return nil
}
lines := []string{
h.lp.SprintStyled("fg=green bold", center_string(family, int(sz.WidthCells)-start_x)),
"",
}
width := int(sz.WidthCells) - start_x - 1
add_line := func(x string) {
lines = append(lines, style.WrapTextAsLines(x, width, style.WrapOptions{})...)
}
fonts := h.fonts[family]
if len(fonts) == 0 {
return fmt.Errorf("The family: %s has no fonts", family)
}
if has_variable_data_for_font(fonts[0]) {
s := styles_in_family(family, fonts)
for _, sg := range s.style_groups {
styles := sg.name + ": " + strings.Join(sg.styles, ", ")
add_line(styles)
add_line("")
}
add_line(fmt.Sprintf("Press the %s key to choose this family", h.lp.SprintStyled("fg=yellow", "Enter")))
} else {
lines = append(lines, "Reading font data, please wait…")
key := fonts[0].cache_key()
if !h.variable_data_requested_for.Has(key) {
h.variable_data_requested_for.Add(key)
go func() {
h.set_worker_error(ensure_variable_data_for_fonts(fonts...))
h.lp.WakeupMainThread()
}()
}
}
for i, line := range lines {
if i >= int(sz.HeightCells)-1 {
break
}
h.lp.MoveCursorTo(start_x+1, i+1)
h.lp.QueueWriteString(line)
}
return
}
func (h *handler) draw_listing_screen() (err error) {
sz, err := h.lp.ScreenSize()
if err != nil {
return err
}
num_rows := max(0, int(sz.HeightCells)-1)
mw := h.family_list.max_width + 1
green_fg, _, _ := strings.Cut(h.lp.SprintStyled("fg=green", "|"), "|")
lines := make([]string, 0, num_rows)
for _, l := range h.family_list.Lines(num_rows) {
line := l.text
if l.is_current {
line = strings.ReplaceAll(line, MARK_AFTER, green_fg)
line = h.lp.SprintStyled("fg=green", ">") + h.lp.SprintStyled("fg=green bold", line)
} else {
line = " " + line
}
lines = append(lines, line)
}
_, _, str := h.render_lines.InRectangle(lines, 0, 0, 0, num_rows, &h.mouse_state)
h.lp.QueueWriteString(str)
seps := strings.Repeat(SEPARATOR, num_rows)
seps = strings.TrimSpace(seps)
_, _, str = h.render_lines.InRectangle(strings.Split(seps, ""), mw+1, 0, 0, num_rows, &h.mouse_state)
h.lp.QueueWriteString(str)
if h.family_list.Len() > 0 {
if err = h.draw_family_summary(mw+3, sz); err != nil {
return err
}
}
h.draw_search_bar()
return
}
func (h *handler) update_family_search() {
text := h.rl.AllText()
if h.family_list.UpdateSearch(text) {
h.draw_screen()
} else {
h.draw_search_bar()
}
}
func (h *handler) next(delta int, allow_wrapping bool) {
if h.family_list.Next(delta, allow_wrapping) {
h.draw_screen()
} else {
h.lp.Beep()
}
}
func (h *handler) handle_listing_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
if h.rl.AllText() != "" {
h.rl.ResetText()
h.update_family_search()
h.draw_screen()
} else {
h.lp.Quit(1)
}
return
}
ev := event
if ev.MatchesPressOrRepeat("down") {
h.next(1, true)
ev.Handled = true
return nil
}
if ev.MatchesPressOrRepeat("up") {
h.next(-1, true)
ev.Handled = true
return nil
}
if ev.MatchesPressOrRepeat("page_down") {
ev.Handled = true
sz, err := h.lp.ScreenSize()
if err == nil {
h.next(int(sz.HeightCells)-3, false)
}
return nil
}
if ev.MatchesPressOrRepeat("page_up") {
ev.Handled = true
sz, err := h.lp.ScreenSize()
if err == nil {
h.next(3-int(sz.HeightCells), false)
}
return nil
}
if err = h.rl.OnKeyEvent(event); err != nil {
if err == readline.ErrAcceptInput {
return nil
}
return err
}
if event.Handled {
h.update_family_search()
}
h.draw_search_bar()
return
}
func (h *handler) handle_listing_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if err = h.rl.OnText(text, from_key_event, in_bracketed_paste); err != nil {
return err
}
h.update_family_search()
return
}
// }}}
// Events {{{
func (h *handler) initialize() {
h.lp.SetCursorVisible(false)
h.rl = readline.New(h.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "Family: "})
h.variable_data_requested_for = utils.NewSet[string](256)
h.draw_screen()
initialize_variable_data_cache()
go func() {
h.set_worker_error(query_kitty("", nil, &h.fonts))
h.lp.WakeupMainThread()
}()
}
func (h *handler) finalize() {
h.lp.SetCursorVisible(true)
h.lp.SetCursorShape(loop.BLOCK_CURSOR, true)
}
func (h *handler) draw_screen() (err error) {
h.lp.StartAtomicUpdate()
defer h.mouse_state.UpdateHoveredIds()
defer h.mouse_state.ApplyHoverStyles(h.lp)
defer h.lp.EndAtomicUpdate()
h.lp.ClearScreen()
h.lp.AllowLineWrapping(false)
h.mouse_state.ClearCellRegions()
switch h.state {
case SCANNING_FAMILIES:
h.lp.Println("Scanning system for fonts, please wait...")
case LISTING_FAMILIES:
return h.draw_listing_screen()
}
return
}
func (h *handler) on_wakeup() (err error) {
if err = h.get_worker_error(); err != nil {
return
}
switch h.state {
case SCANNING_FAMILIES:
h.state = LISTING_FAMILIES
h.family_list.UpdateFamilies(utils.StableSortWithKey(utils.Keys(h.fonts), strings.ToLower))
case LISTING_FAMILIES:
}
return h.draw_screen()
}
func (h *handler) on_mouse_event(event *loop.MouseEvent) (err error) {
err = h.mouse_state.UpdateState(event)
h.mouse_state.ApplyHoverStyles(h.lp)
return
}
func (h *handler) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("ctrl+c") {
event.Handled = true
h.lp.Quit(1)
return nil
}
switch h.state {
case LISTING_FAMILIES:
return h.handle_listing_key_event(event)
}
return
}
func (h *handler) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
switch h.state {
case LISTING_FAMILIES:
return h.handle_listing_text(text, from_key_event, in_bracketed_paste)
}
return
}
// }}}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"kitty/kittens/ask"
"kitty/kittens/choose_fonts"
"kitty/kittens/clipboard"
"kitty/kittens/diff"
"kitty/kittens/hints"
@@ -20,7 +21,6 @@ import (
"kitty/tools/cmd/at"
"kitty/tools/cmd/benchmark"
"kitty/tools/cmd/edit_in_kitty"
"kitty/tools/cmd/list_fonts"
"kitty/tools/cmd/mouse_demo"
"kitty/tools/cmd/pytest"
"kitty/tools/cmd/run_shell"
@@ -77,10 +77,10 @@ func KittyToolEntryPoints(root *cli.Command) {
run_shell.EntryPoint(root)
// show_error
show_error.EntryPoint(root)
// choose-fonts
choose_fonts.EntryPoint(root)
// __pytest__
pytest.EntryPoint(root)
// __list_fonts__
list_fonts.EntryPoint(root)
// __hold_till_enter__
root.AddSubCommand(&cli.Command{
Name: "__hold_till_enter__",