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:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

View File
Whitespace-only changes.
+168
View File
@@ -0,0 +1,168 @@
package choose_fonts
import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type kitty_font_backend_type struct {
from io.ReadCloser
to io.WriteCloser
json_decoder *json.Decoder
cmd *exec.Cmd
stderr strings.Builder
lock sync.Mutex
r io.ReadCloser
w io.WriteCloser
wait_for_exit chan error
started, exited, failed bool
timeout time.Duration
}
func (k *kitty_font_backend_type) start() (err error) {
exe := utils.KittyExe()
if exe == "" {
exe = utils.Which("kitty")
}
if exe == "" {
return fmt.Errorf("Failed to find the kitty executable, this kitten requires the kitty executable to be present. You can use the environment variable KITTY_PATH_TO_KITTY_EXE to specify the path to the kitty executable")
}
k.cmd = exec.Command(exe, "+runpy", "from kittens.choose_fonts.backend import main; main()")
k.cmd.Stderr = &k.stderr
if k.r, k.to, err = os.Pipe(); err != nil {
return err
}
k.cmd.Stdin = k.r
if k.from, k.w, err = os.Pipe(); err != nil {
return err
}
k.cmd.Stdout = k.w
k.json_decoder = json.NewDecoder(k.from)
if err = k.cmd.Start(); err != nil {
return err
}
k.started = true
k.timeout = 60 * time.Second
k.wait_for_exit = make(chan error)
go func() {
k.wait_for_exit <- k.cmd.Wait()
}()
return
}
var kitty_font_backend kitty_font_backend_type
func (k *kitty_font_backend_type) send(v any) error {
if k.to == nil {
return fmt.Errorf("Trying to send data when to pipe is nil")
}
data, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("Could not encode message to kitty with error: %w", err)
}
c := make(chan error)
go func() {
if _, err = k.to.Write(data); err != nil {
c <- fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
return
}
if _, err = k.to.Write([]byte{'\n'}); err != nil {
c <- fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
return
}
c <- nil
}()
select {
case err := <-c:
return err
case <-time.After(k.timeout):
return fmt.Errorf("Timed out waiting to write to kitty font backend after %v", k.timeout)
case err := <-k.wait_for_exit:
k.exited = true
if err == nil {
err = fmt.Errorf("kitty font backend exited with no error while waiting for a response from it")
} else {
k.failed = true
}
return err
}
}
func (k *kitty_font_backend_type) query(action string, cmd map[string]any, result any) error {
k.lock.Lock()
defer k.lock.Unlock()
if cmd == nil {
cmd = make(map[string]any)
}
cmd["action"] = action
if err := k.send(cmd); err != nil {
return err
}
c := make(chan error)
go func() {
if err := k.json_decoder.Decode(result); err != nil {
c <- fmt.Errorf("Failed to decode JSON from kitty with error: %w", err)
}
c <- nil
}()
select {
case err := <-c:
return err
case <-time.After(k.timeout):
return fmt.Errorf("Timed out waiting for response from kitty font backend after %v", k.timeout)
case err := <-k.wait_for_exit:
k.exited = true
if err == nil {
err = fmt.Errorf("kitty font backed exited with no error while waiting for a response from it")
} else {
k.failed = true
}
return err
}
}
func (k *kitty_font_backend_type) release() (err error) {
if k.r != nil {
k.r.Close()
k.r = nil
}
if k.to != nil {
k.to.Close()
k.to = nil
}
if k.w != nil {
k.w.Close()
k.w = nil
}
if k.from != nil {
k.from.Close()
k.from = nil
}
if k.started && !k.exited {
timeout := 2 * time.Second
select {
case err = <-k.wait_for_exit:
k.exited = true
if err != nil {
k.failed = true
}
case <-time.After(timeout):
k.failed = true
err = fmt.Errorf("Timed out waiting for kitty font backend to exit for %v", timeout)
}
}
os.Stderr.WriteString(k.stderr.String())
return
}
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import string
import sys
import tempfile
from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict
from kitty.cli import create_default_opts
from kitty.conf.utils import to_color
from kitty.constants import kitten_exe
from kitty.fonts import Descriptor
from kitty.fonts.common import (
face_from_descriptor,
get_axis_map,
get_font_files,
get_named_style,
get_variable_data_for_descriptor,
get_variable_data_for_face,
is_variable,
spec_for_face,
)
from kitty.fonts.features import Type, known_features
from kitty.fonts.list import create_family_groups
from kitty.fonts.render import display_bitmap
from kitty.options.types import Options
from kitty.options.utils import parse_font_spec
from kitty.typing_compat import NotRequired
from kitty.utils import screen_size_function
if TYPE_CHECKING:
from kitty.fast_data_types import FeatureData
def setup_debug_print() -> bool:
if 'KITTY_STDIO_FORWARDED' in os.environ:
try:
fd = int(os.environ['KITTY_STDIO_FORWARDED'])
except Exception:
return False
try:
sys.stdout = open(fd, 'w', closefd=False)
return True
except OSError:
return False
return False
def send_to_kitten(x: Any) -> None:
f = sys.__stdout__
assert f is not None
try:
f.buffer.write(json.dumps(x).encode())
f.buffer.write(b'\n')
f.buffer.flush()
except BrokenPipeError:
raise SystemExit('Pipe to kitten was broken while sending data to it')
class TextStyle(TypedDict):
font_size: float
dpi_x: float
dpi_y: float
foreground: str
background: str
OptNames = Literal['font_family', 'bold_font', 'italic_font', 'bold_italic_font']
FamilyKey = tuple[OptNames, ...]
def opts_from_cmd(cmd: dict[str, Any]) -> tuple[Options, FamilyKey, float, float]:
opts = Options()
ts: TextStyle = cmd['text_style']
opts.font_size = ts['font_size']
opts.foreground = to_color(ts['foreground'])
opts.background = to_color(ts['background'])
family_key = []
def d(k: OptNames) -> None:
if k in cmd:
setattr(opts, k, parse_font_spec(cmd[k]))
family_key.append(k)
d('font_family')
d('bold_font')
d('italic_font')
d('bold_italic_font')
return opts, tuple(family_key), ts['dpi_x'], ts['dpi_y']
BaseKey = tuple[str, int, int]
FaceKey = tuple[str, BaseKey]
RenderedSample = tuple[bytes, dict[str, Any]]
RenderedSampleTransmit = dict[str, Any]
SAMPLE_TEXT = string.ascii_lowercase + ' ' + string.digits + ' ' + string.ascii_uppercase + ' ' + string.punctuation
class FD(TypedDict):
is_index: bool
name: NotRequired[str]
tooltip: NotRequired[str]
sample: NotRequired[str]
params: NotRequired[tuple[str, ...]]
def get_features(features: dict[str, Optional['FeatureData']]) -> dict[str, FD]:
ans = {}
for tag, data in features.items():
kf = known_features.get(tag)
if kf is None or kf.type is Type.hidden:
continue
fd: FD = {'is_index': kf.type is Type.index}
ans[tag] = fd
if data is not None:
if n := data.get('name'):
fd['name'] = n
if n := data.get('tooltip'):
fd['tooltip'] = n
if n := data.get('sample'):
fd['sample'] = n
if p := data.get('params'):
fd['params'] = p
return ans
def render_face_sample(font: Descriptor, opts: Options, dpi_x: float, dpi_y: float, width: int, height: int, sample_text: str = '') -> RenderedSample:
face = face_from_descriptor(font, opts.font_size, dpi_x, dpi_y)
face.set_size(opts.font_size, dpi_x, dpi_y)
metadata = {
'variable_data': get_variable_data_for_face(face),
'style': font['style'],
'psname': face.postscript_name(),
'features': get_features(face.get_features()),
'applied_features': face.applied_features(),
'spec': spec_for_face(font['family'], face).as_setting,
'cell_width': 0,
'cell_height': 0,
'canvas_height': 0,
'canvas_width': width,
}
if is_variable(font):
ns = get_named_style(face)
if ns:
metadata['variable_named_style'] = ns
metadata['variable_axis_map'] = get_axis_map(face)
bitmap, cell_width, cell_height = face.render_sample_text(sample_text or SAMPLE_TEXT, width, height, opts.foreground.rgb)
metadata['cell_width'] = cell_width
metadata['cell_height'] = cell_height
metadata['canvas_height'] = len(bitmap) // (4 * width)
return bitmap, metadata
def render_family_sample(
opts: Options, family_key: FamilyKey, dpi_x: float, dpi_y: float, width: int, height: int, output_dir: str, cache: dict[FaceKey, RenderedSampleTransmit]
) -> dict[str, RenderedSampleTransmit]:
base_key: BaseKey = opts.font_family.created_from_string, width, height
ans: dict[str, RenderedSampleTransmit] = {}
font_files = get_font_files(opts)
for x in family_key:
key: FaceKey = x + ': ' + str(getattr(opts, x)), base_key
if x == 'font_family':
desc = font_files['medium']
elif x == 'bold_font':
desc = font_files['bold']
elif x == 'italic_font':
desc = font_files['italic']
elif x == 'bold_italic_font':
desc = font_files['bi']
cached = cache.get(key)
if cached is not None:
ans[x] = cached
else:
with tempfile.NamedTemporaryFile(delete=False, suffix='.rgba', dir=output_dir) as tf:
bitmap, metadata = render_face_sample(desc, opts, dpi_x, dpi_y, width, height)
tf.write(bitmap)
metadata['path'] = tf.name
cache[key] = ans[x] = metadata
return ans
ResolvedFace = dict[Literal['family', 'spec', 'setting'], str]
def spec_for_descriptor(d: Descriptor, font_size: float) -> str:
face = face_from_descriptor(d, font_size, 288, 288)
return spec_for_face(d['family'], face).as_setting
def resolved_faces(opts: Options) -> dict[OptNames, ResolvedFace]:
font_files = get_font_files(opts)
ans: dict[OptNames, ResolvedFace] = {}
def d(key: Literal['medium', 'bold', 'italic', 'bi'], opt_name: OptNames) -> None:
descriptor = font_files[key]
ans[opt_name] = {
'family': descriptor['family'],
'spec': spec_for_descriptor(descriptor, opts.font_size),
'setting': getattr(opts, opt_name).created_from_string,
}
d('medium', 'font_family')
d('bold', 'bold_font')
d('italic', 'italic_font')
d('bi', 'bold_italic_font')
return ans
def main() -> None:
setup_debug_print()
cache: dict[FaceKey, RenderedSampleTransmit] = {}
for line in sys.stdin.buffer:
cmd = json.loads(line)
action = cmd.get('action', '')
if action == 'list_monospaced_fonts':
opts = create_default_opts()
send_to_kitten({'fonts': create_family_groups(), 'resolved_faces': resolved_faces(opts)})
elif action == 'read_variable_data':
ans = []
for descriptor in cmd['descriptors']:
ans.append(get_variable_data_for_descriptor(descriptor))
send_to_kitten(ans)
elif action == 'render_family_samples':
opts, family_key, dpi_x, dpi_y = opts_from_cmd(cmd)
send_to_kitten(render_family_sample(opts, family_key, dpi_x, dpi_y, cmd['width'], cmd['height'], cmd['output_dir'], cache))
else:
raise SystemExit(f'Unknown action: {action}')
def query_kitty() -> dict[str, str]:
import subprocess
ans = {}
for line in subprocess.check_output([kitten_exe(), 'query-terminal']).decode().splitlines():
k, sep, v = line.partition(':')
if sep == ':':
ans[k] = v.strip()
return ans
def showcase(family: str = 'family="Fira Code"', sample_text: str = '') -> None:
q = query_kitty()
opts = Options()
opts.foreground = to_color(q['foreground'])
opts.background = to_color(q['background'])
opts.font_size = float(q['font_size'])
opts.font_family = parse_font_spec(family)
font_files = get_font_files(opts)
desc = font_files['medium']
ss = screen_size_function()()
width = ss.cell_width * ss.cols
height = 5 * ss.cell_height
bitmap, m = render_face_sample(desc, opts, float(q['dpi_x']), float(q['dpi_y']), width, height, sample_text=sample_text)
display_bitmap(bitmap, m['canvas_width'], m['canvas_height'])
def test_render(spec: str = 'family="Fira Code"', width: int = 1560, height: int = 116, font_size: float = 12, dpi: float = 288) -> None:
opts = Options()
opts.font_family = parse_font_spec(spec)
opts.font_size = font_size
opts.foreground = to_color('white')
desc = get_font_files(opts)['medium']
bitmap, m = render_face_sample(desc, opts, float(dpi), float(dpi), width, height)
display_bitmap(bitmap, m['canvas_width'], m['canvas_height'])
+489
View File
@@ -0,0 +1,489 @@
package choose_fonts
import (
"fmt"
"maps"
"math"
"slices"
"strconv"
"strings"
"sync"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type face_panel struct {
handler *handler
family, which string
settings faces_settings
current_preview *RenderedSampleTransmit
current_preview_key faces_preview_key
preview_cache map[faces_preview_key]map[string]RenderedSampleTransmit
preview_cache_mutex sync.Mutex
}
// Create a new FontSpec that keeps features and axis values and named styles
// same as the current setting. Names are all reset apart from style name.
func (self *face_panel) new_font_spec() (*FontSpec, error) {
fs, err := NewFontSpec(self.get(), self.current_preview.Features)
if err != nil {
return nil, err
}
if fs.system.val == "auto" {
if fs, err = NewFontSpec(self.current_preview.Spec, self.current_preview.Features); err != nil {
return nil, err
}
}
// reset these selectors as we will be using some style/axis based selector instead
fs.family = settable_string{self.family, true}
fs.postscript_name = settable_string{}
fs.full_name = settable_string{}
if len(self.current_preview.Variable_data.Axes) > 0 {
fs.variable_name = settable_string{self.current_preview.Variable_data.Variations_postscript_name_prefix, true}
} else {
fs.variable_name = settable_string{}
}
return &fs, nil
}
func (self *face_panel) set_variable_spec(named_style string, axis_overrides map[string]float64) error {
fs, err := self.new_font_spec()
if err != nil {
return err
}
if axis_overrides != nil {
axis_values := self.current_preview.current_axis_values()
maps.Copy(axis_values, axis_overrides)
fs.axes = axis_values
fs.style = settable_string{"", false}
} else if named_style != "" {
fs.style = settable_string{named_style, true}
fs.axes = nil
}
self.set(fs.String())
return nil
}
func (self *face_panel) set_style(named_style string) error {
fs, err := self.new_font_spec()
if err != nil {
return err
}
fs.style = settable_string{named_style, true}
self.set(fs.String())
return nil
}
func (self *face_panel) render_lines(start_y int, lines ...string) (y int) {
sz, _ := self.handler.lp.ScreenSize()
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
self.handler.lp.QueueWriteString(str)
return
}
const current_val_style = "fg=cyan bold"
const control_name_style = "fg=yellow bright bold"
func (self *face_panel) draw_axis(sz loop.ScreenSize, y int, ax VariableAxis, axis_value float64) int {
lp := self.handler.lp
buf := strings.Builder{}
buf.WriteString(fmt.Sprintf("%s: ", lp.SprintStyled(control_name_style, utils.IfElse(ax.Strid != "", ax.Strid, ax.Tag))))
num_of_cells := int(sz.WidthCells) - wcswidth.Stringwidth(buf.String())
if num_of_cells < 5 {
return y
}
frac := (min(axis_value, ax.Maximum) - ax.Minimum) / (ax.Maximum - ax.Minimum)
current_cell := int(math.Floor(frac * float64(num_of_cells-1)))
for i := range num_of_cells {
buf.WriteString(utils.IfElse(i == current_cell, lp.SprintStyled(current_val_style, `⬤`),
tui.InternalHyperlink("•", fmt.Sprintf("axis:%d/%d:%s", i, num_of_cells-1, ax.Tag))))
}
return self.render_lines(y, buf.String())
}
func is_current_named_style(style_group_name, style_name string, vd VariableData, ns NamedStyle) bool {
for _, dax := range vd.Design_axes {
if dax.Name == style_group_name {
if val, found := ns.Axis_values[dax.Tag]; found {
for _, v := range dax.Values {
if v.Value == val {
return v.Name == style_name
}
}
}
break
}
}
return false
}
func (self *face_panel) draw_variable_fine_tune(sz loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
s := styles_for_variable_data(preview.Variable_data)
lines := []string{}
lp := self.handler.lp
for _, sg := range s.style_groups {
if len(sg.styles) < 2 {
continue
}
formatted := make([]string, len(sg.styles))
for i, style_name := range sg.styles {
if is_current_named_style(sg.name, style_name, preview.Variable_data, preview.Variable_named_style) {
formatted[i] = self.handler.lp.SprintStyled(current_val_style, style_name)
} else {
formatted[i] = tui.InternalHyperlink(style_name, "variable_style:"+style_name)
}
}
line := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(formatted, ", ")
lines = append(lines, line)
}
y = self.render_lines(start_y, lines...)
sub_title := "Fine tune the appearance by clicking in the variable axes below:"
axis_values := self.current_preview.current_axis_values()
for _, ax := range self.current_preview.Variable_data.Axes {
if ax.Hidden {
continue
}
if sub_title != "" {
y = self.render_lines(y+1, sub_title, "")
sub_title = ``
}
y = self.draw_axis(sz, y, ax, axis_values[ax.Tag])
}
return y, nil
}
func (self *face_panel) draw_family_style_select(_ loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
lp := self.handler.lp
s := styles_in_family(self.family, self.handler.listing.fonts[self.family])
lines := []string{}
for _, sg := range s.style_groups {
formatted := make([]string, len(sg.styles))
for i, style_name := range sg.styles {
if style_name == preview.Style {
formatted[i] = lp.SprintStyled(current_val_style, style_name)
} else {
formatted[i] = tui.InternalHyperlink(style_name, "style:"+style_name)
}
}
line := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(formatted, ", ")
lines = append(lines, line)
}
y = self.render_lines(start_y, lines...)
return y, nil
}
func (self *face_panel) draw_font_features(_ loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
lp := self.handler.lp
y = start_y
if len(preview.Features) == 0 {
return
}
formatted := make([]string, 0, len(preview.Features))
sort_keys := make(map[string]string)
for feat_tag, data := range preview.Features {
var text, sort_key string
if preview.Applied_features[feat_tag] != "" {
text = preview.Applied_features[feat_tag]
sort_key = text
if sort_key[0] == '-' || sort_key[1] == '+' {
sort_key = sort_key[1:]
}
text = strings.Replace(text, "+", lp.SprintStyled("fg=green", "+"), 1)
text = strings.Replace(text, "-", lp.SprintStyled("fg=red", "-"), 1)
text = strings.Replace(text, "=", lp.SprintStyled("fg=cyan", "="), 1)
if data.Name != "" {
text = data.Name + ": " + text
sort_key = data.Name
}
} else {
if data.Name != "" {
text = data.Name
sort_key = data.Name + ": " + text
} else {
text = feat_tag
sort_key = text
}
text = lp.SprintStyled("dim", text)
}
f := tui.InternalHyperlink(text, "feature:"+feat_tag)
sort_keys[f] = strings.ToLower(sort_key)
formatted = append(formatted, f)
}
utils.StableSortWithKey(formatted, func(a string) string { return sort_keys[a] })
line := lp.SprintStyled(control_name_style, `Features`) + ": " + strings.Join(formatted, ", ")
y = self.render_lines(start_y, ``, line)
return
}
func (self *handler) draw_preview_header(x int) {
sz, _ := self.lp.ScreenSize()
width := int(sz.WidthCells) - x
p := center_string(self.lp.SprintStyled("italic", " preview "), width, "─")
self.lp.QueueWriteString(self.lp.SprintStyled("dim", p))
}
func (self *face_panel) render_preview(key faces_preview_key) {
var r map[string]RenderedSampleTransmit
s := key.settings
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
"text_style": self.handler.text_style, "font_family": s.font_family,
"bold_font": s.bold_font, "italic_font": s.italic_font, "bold_italic_font": s.bold_italic_font,
"width": key.width, "height": key.height, "output_dir": self.handler.temp_dir,
}, &r))
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
self.preview_cache[key] = r
}
func (self *face_panel) draw_screen() (err error) {
lp := self.handler.lp
lp.SetCursorVisible(false)
sz, _ := lp.ScreenSize()
styled := lp.SprintStyled
wt := "Regular"
switch self.which {
case "bold_font":
wt = "Bold"
case "italic_font":
wt = "Italic"
case "bold_italic_font":
wt = "Bold-Italic font"
}
lp.QueueWriteString(self.handler.format_title(fmt.Sprintf("%s: %s face", self.family, wt), 0))
lines := []string{
fmt.Sprintf("Press %s to accept any changes or %s to cancel. Click on a style name below to switch to it.", styled("fg=green", "Enter"), styled("fg=red", "Esc")), "",
fmt.Sprintf("Current setting: %s", self.get()), "",
}
y := self.render_lines(2, lines...)
num_lines_per_font := (int(sz.HeightCells) - y - 1) - 2
num_lines := max(1, num_lines_per_font)
key := faces_preview_key{settings: self.settings, width: int(sz.WidthCells * sz.CellWidth), height: int(sz.CellHeight) * num_lines}
self.current_preview_key = key
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
previews, found := self.preview_cache[key]
if !found {
self.preview_cache[key] = make(map[string]RenderedSampleTransmit)
go func() {
self.render_preview(key)
self.handler.lp.WakeupMainThread()
}()
return
}
if len(previews) < 4 {
return
}
preview := previews[self.which]
self.current_preview = &preview
if len(preview.Variable_data.Axes) > 0 {
y, err = self.draw_variable_fine_tune(sz, y, preview)
} else {
y, err = self.draw_family_style_select(sz, y, preview)
}
if err != nil {
return err
}
if y, err = self.draw_font_features(sz, y, preview); err != nil {
return err
}
num_lines = int(math.Ceil(float64(preview.Canvas_height) / float64(sz.CellHeight)))
if int(sz.HeightCells)-y >= num_lines+2 {
y++
lp.MoveCursorTo(1, y+1)
self.handler.draw_preview_header(0)
y++
lp.MoveCursorTo(1, y+1)
self.handler.graphics_manager.display_image(0, preview.Path, preview.Canvas_width, preview.Canvas_height)
}
return
}
func (self *face_panel) initialize(h *handler) (err error) {
self.handler = h
self.preview_cache = make(map[faces_preview_key]map[string]RenderedSampleTransmit)
return
}
func (self *face_panel) on_wakeup() error {
return self.handler.draw_screen()
}
func (self *face_panel) get() string {
switch self.which {
case "font_family":
return self.settings.font_family
case "bold_font":
return self.settings.bold_font
case "italic_font":
return self.settings.italic_font
case "bold_italic_font":
return self.settings.bold_italic_font
}
panic(fmt.Sprintf("Unknown self.which value: %s", self.which))
}
func (self *face_panel) set(setting string) {
switch self.which {
case "font_family":
self.settings.font_family = setting
case "bold_font":
self.settings.bold_font = setting
case "italic_font":
self.settings.italic_font = setting
case "bold_italic_font":
self.settings.bold_italic_font = setting
}
}
func (self *face_panel) update_feature_in_setting(pff ParsedFontFeature) error {
fs, err := self.new_font_spec()
if err != nil {
return err
}
found := false
for _, f := range fs.features {
if f.tag == pff.tag {
f.val = pff.val
found = true
break
}
}
if !found {
fs.features = append(fs.features, &pff)
}
self.set(fs.String())
return nil
}
func (self *face_panel) remove_feature_in_setting(tag string) error {
fs, err := self.new_font_spec()
if err != nil {
return err
}
if len(fs.features) > 0 {
fs.features = slices.DeleteFunc(fs.features, func(x *ParsedFontFeature) bool {
return x.tag == tag
})
}
self.set(fs.String())
return nil
}
func (self *face_panel) change_feature_value(tag string, val uint, remove bool) error {
if remove {
return self.remove_feature_in_setting(tag)
}
pff := ParsedFontFeature{tag: tag, val: val}
return self.update_feature_in_setting(pff)
}
func (self *face_panel) handle_click_on_feature(feat_tag string) error {
d := self.current_preview.Features[feat_tag]
if d.Is_index {
var current_val uint
for q, serialized := range self.current_preview.Applied_features {
if q == feat_tag && serialized != "" {
if _, num, found := strings.Cut(serialized, "="); found {
if v, err := strconv.ParseUint(num, 10, 0); err == nil {
current_val = uint(v)
}
} else {
current_val = utils.IfElse(serialized[0] == '-', uint(0), uint(1))
}
return self.handler.if_pane.on_enter(self.family, self.which, self.settings, feat_tag, d, current_val)
}
}
return self.handler.if_pane.on_enter(self.family, self.which, self.settings, feat_tag, d, current_val)
} else {
for q, serialized := range self.current_preview.Applied_features {
if q == feat_tag && serialized != "" {
if serialized[0] == '-' {
return self.remove_feature_in_setting(feat_tag)
}
return self.update_feature_in_setting(ParsedFontFeature{tag: feat_tag, is_bool: true, val: 0})
}
}
return self.update_feature_in_setting(ParsedFontFeature{tag: feat_tag, is_bool: true, val: 1})
}
}
func (self *face_panel) on_click(id string) (err error) {
scheme, val, _ := strings.Cut(id, ":")
switch scheme {
case "style":
if err = self.set_style(val); err != nil {
return err
}
case "variable_style":
if err = self.set_variable_spec(val, nil); err != nil {
return err
}
case "feature":
if err = self.handle_click_on_feature(val); err != nil {
return err
}
case "axis":
p, tag, _ := strings.Cut(val, ":")
num, den, _ := strings.Cut(p, "/")
n, _ := strconv.Atoi(num)
d, _ := strconv.Atoi(den)
frac := float64(n) / float64(d)
for _, ax := range self.current_preview.Variable_data.Axes {
if ax.Tag == tag {
axval := ax.Minimum + (ax.Maximum-ax.Minimum)*frac
if err = self.set_variable_spec("", map[string]float64{tag: axval}); err != nil {
return err
}
break
}
}
}
// Render preview synchronously to void flashing
key := self.current_preview_key
key.settings = self.settings
self.preview_cache_mutex.Lock()
previews := self.preview_cache[key]
self.preview_cache_mutex.Unlock()
if len(previews) < 4 {
self.render_preview(key)
}
return self.handler.draw_screen()
}
func (self *face_panel) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
self.handler.current_pane = &self.handler.faces
return self.handler.draw_screen()
} else if event.MatchesPressOrRepeat("enter") {
event.Handled = true
self.handler.current_pane = &self.handler.faces
self.handler.faces.settings = self.settings
return self.handler.draw_screen()
}
return
}
func (self *face_panel) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
return
}
func (self *face_panel) on_enter(family, which string, settings faces_settings) error {
self.family = family
self.settings = settings
self.which = which
self.handler.current_pane = self
return self.handler.draw_screen()
}
+164
View File
@@ -0,0 +1,164 @@
package choose_fonts
import (
"fmt"
"math"
"sync"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type faces_settings struct {
font_family, bold_font, italic_font, bold_italic_font string
}
type faces_preview_key struct {
settings faces_settings
width, height int
}
type faces struct {
handler *handler
family string
settings faces_settings
preview_cache map[faces_preview_key]map[string]RenderedSampleTransmit
preview_cache_mutex sync.Mutex
}
const highlight_key_style = "fg=magenta bold"
func (self *faces) draw_screen() (err error) {
lp := self.handler.lp
lp.SetCursorVisible(false)
sz, _ := lp.ScreenSize()
styled := lp.SprintStyled
lp.QueueWriteString(self.handler.format_title(self.family, 0))
lines := []string{
fmt.Sprintf("Press %s to select this font, %s to go back to the font list or any of the %s keys below to fine-tune the appearance of the individual font styles.", styled("fg=green", "Enter"), styled("fg=red", "Esc"), styled(highlight_key_style, "highlighted")), "",
}
_, y, str := self.handler.render_lines.InRectangle(lines, 0, 2, int(sz.WidthCells), int(sz.HeightCells), &self.handler.mouse_state, self.on_click)
lp.QueueWriteString(str)
num_lines_per_font := ((int(sz.HeightCells) - y - 1) / 4) - 2
num_lines := max(1, num_lines_per_font)
key := faces_preview_key{settings: self.settings, width: int(sz.WidthCells * sz.CellWidth), height: int(sz.CellHeight) * num_lines}
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
previews, found := self.preview_cache[key]
if !found {
self.preview_cache[key] = make(map[string]RenderedSampleTransmit)
if self.handler.text_style.Foreground == "" || self.handler.text_style.Background == "" {
return
}
go func() {
var r map[string]RenderedSampleTransmit
s := key.settings
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
"text_style": self.handler.text_style, "font_family": s.font_family,
"bold_font": s.bold_font, "italic_font": s.italic_font, "bold_italic_font": s.bold_italic_font,
"width": key.width, "height": key.height, "output_dir": self.handler.temp_dir,
}, &r))
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
self.preview_cache[key] = r
self.handler.lp.WakeupMainThread()
}()
return
}
if len(previews) < 4 {
return
}
slot := 0
d := func(setting, title string) {
r := previews[setting]
num_lines := int(math.Ceil(float64(r.Canvas_height) / float64(sz.CellHeight)))
if int(sz.HeightCells)-y < num_lines+1 {
return
}
lp.MoveCursorTo(1, y+1)
_, y, str = self.handler.render_lines.InRectangle([]string{title + ": " + previews[setting].Psname}, 0, y, int(sz.WidthCells), int(sz.HeightCells), &self.handler.mouse_state, self.on_click)
lp.QueueWriteString(str)
if y+num_lines < int(sz.HeightCells) {
lp.MoveCursorTo(1, y+1)
self.handler.graphics_manager.display_image(slot, r.Path, r.Canvas_width, r.Canvas_height)
slot++
y += num_lines + 1
}
}
d(`font_family`, styled(highlight_key_style, "R")+`egular`)
d(`bold_font`, styled(highlight_key_style, "B")+`old`)
d(`italic_font`, styled(highlight_key_style, "I")+`talic`)
d(`bold_italic_font`, "B"+styled(highlight_key_style, "o")+`ld-Italic`)
return
}
func (self *faces) initialize(h *handler) (err error) {
self.handler = h
self.preview_cache = make(map[faces_preview_key]map[string]RenderedSampleTransmit)
return
}
func (self *faces) on_wakeup() error {
return self.handler.draw_screen()
}
func (self *faces) on_click(id string) (err error) {
return
}
func (self *faces) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
self.handler.current_pane = &self.handler.listing
return self.handler.draw_screen()
}
if event.MatchesPressOrRepeat("enter") {
event.Handled = true
return self.handler.final_pane.on_enter(self.family, self.settings)
}
return
}
func (self *faces) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if from_key_event {
which := ""
switch text {
case "r", "R":
which = "font_family"
case "b", "B":
which = "bold_font"
case "i", "I":
which = "italic_font"
case "o", "O":
which = "bold_italic_font"
}
if which != "" {
return self.handler.face_pane.on_enter(self.family, which, self.settings)
}
}
return
}
func (self *faces) on_enter(family string) error {
if family != "" {
self.family = family
r := self.handler.listing.resolved_faces_from_kitty_conf
d := func(conf ResolvedFace, setting *string, defval string) {
s := utils.IfElse(conf.Setting == "auto", "auto", conf.Spec)
*setting = utils.IfElse(family == conf.Family, s, defval)
}
d(r.Font_family, &self.settings.font_family, fmt.Sprintf(`family="%s"`, family))
d(r.Bold_font, &self.settings.bold_font, "auto")
d(r.Italic_font, &self.settings.italic_font, "auto")
d(r.Bold_italic_font, &self.settings.bold_italic_font, "auto")
}
self.handler.current_pane = self
return self.handler.draw_screen()
}
+161
View File
@@ -0,0 +1,161 @@
package choose_fonts
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/subseq"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/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) Select(family string) bool {
for idx, q := range self.families {
if q == family {
self.current_idx = idx
return true
}
}
return false
}
func (self *FamilyList) Next(delta int, allow_wrapping bool) bool {
l := func() int { return self.Len() }
if l() == 0 {
return false
}
idx := self.current_idx + delta
if !allow_wrapping && (idx < 0 || idx > l()) {
return false
}
for idx < 0 {
idx += l()
}
self.current_idx = idx % l()
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 make_family_names_clickable(family string) string {
id := wcswidth.StripEscapeCodes(family)
return tui.InternalHyperlink(family, "family-chosen:"+id)
}
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.display_strings = utils.Map(make_family_names_clickable, self.display_strings)
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) SelectFamily(family string) bool {
for i, f := range self.families {
if f == family {
self.current_idx = i
return true
}
}
return false
}
func (self *FamilyList) CurrentFamily() string {
if self.current_idx >= 0 && self.current_idx < len(self.families) {
return self.families[self.current_idx]
}
return ""
}
+123
View File
@@ -0,0 +1,123 @@
package choose_fonts
import (
"fmt"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type final_pane struct {
handler *handler
settings faces_settings
family string
lp *loop.Loop
}
func (self *final_pane) render_lines(start_y int, lines ...string) (y int) {
sz, _ := self.handler.lp.ScreenSize()
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
self.handler.lp.QueueWriteString(str)
return
}
func (self *final_pane) draw_screen() (err error) {
s := self.lp.SprintStyled
h := func(x string) string { return s(highlight_key_style, x) }
self.render_lines(0,
fmt.Sprintf("You have chosen the %s family", s(current_val_style, self.family)),
"",
"What would you like to do?",
"",
fmt.Sprintf("%s to modify %s and use the new fonts", h("Enter"), s("italic", self.handler.opts.Config_file_name)),
"",
fmt.Sprintf("%s to abort and return to font selection", h("Esc")),
"",
fmt.Sprintf("%s to write the new font settings to %s", h("s"), s("italic", `STDOUT`)),
"",
fmt.Sprintf("%s to quit", h("Ctrl+c")),
)
return
}
func (self *final_pane) initialize(h *handler) (err error) {
self.handler = h
self.lp = h.lp
return
}
func (self *final_pane) on_wakeup() error {
return self.handler.draw_screen()
}
func (self *final_pane) on_click(id string) (err error) {
return
}
func (self faces_settings) serialized() string {
return strings.Join([]string{
"font_family " + self.font_family,
"bold_font " + self.bold_font,
"italic_font " + self.italic_font,
"bold_italic_font " + self.bold_italic_font,
}, "\n")
}
func (self *final_pane) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
self.handler.current_pane = &self.handler.faces
return self.handler.draw_screen()
}
if event.MatchesPressOrRepeat("enter") {
event.Handled = true
patcher := config.Patcher{Write_backup: true}
path := ""
if filepath.IsAbs(self.handler.opts.Config_file_name) {
path = self.handler.opts.Config_file_name
} else {
path = filepath.Join(utils.ConfigDir(), self.handler.opts.Config_file_name)
}
updated, err := patcher.Patch(path, "KITTY_FONTS", self.settings.serialized(), "font_family", "bold_font", "italic_font", "bold_italic_font")
if err != nil {
return err
}
if updated {
switch self.handler.opts.Reload_in {
case "parent":
config.ReloadConfigInKitty(true)
case "all":
config.ReloadConfigInKitty(false)
}
}
self.lp.Quit(0)
return nil
}
return
}
func (self *final_pane) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if from_key_event {
switch text {
case "s", "S":
output_on_exit = self.settings.serialized() + "\n"
self.lp.Quit(0)
return
}
}
return
}
func (self *final_pane) on_enter(family string, settings faces_settings) error {
self.settings = settings
self.family = family
self.handler.current_pane = self
return self.handler.draw_screen()
}
+106
View File
@@ -0,0 +1,106 @@
package choose_fonts
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/tui/graphics"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type image struct {
id, image_number uint32
current_file string
}
func (i image) new_graphics_command() *graphics.GraphicsCommand {
gc := &graphics.GraphicsCommand{}
if i.id > 0 {
gc.SetImageId(i.id)
} else {
gc.SetImageNumber(i.image_number)
}
return gc
}
type graphics_manager struct {
main, bold, italic, bi, extra image
lp *loop.Loop
images [5]*image
}
func (g *graphics_manager) initialize(lp *loop.Loop) {
g.images = [5]*image{&g.main, &g.bold, &g.italic, &g.bi, &g.extra}
g.lp = lp
payload := []byte("123")
buf := strings.Builder{}
gc := &graphics.GraphicsCommand{}
gc.SetImageNumber(7891230).SetTransmission(graphics.GRT_transmission_direct).SetDataWidth(1).SetDataHeight(1).SetFormat(
graphics.GRT_format_rgb).SetDataSize(uint64(len(payload)))
d := func() uint32 {
im := gc.ImageNumber()
im++
gc.SetImageNumber(im)
_ = gc.WriteWithPayloadTo(&buf, payload)
return im
}
for _, img := range g.images {
img.image_number = d()
}
lp.QueueWriteString(buf.String())
}
func (g *graphics_manager) clear_placements() {
buf := strings.Builder{}
for _, img := range g.images {
if img.current_file == "" {
continue
}
gc := img.new_graphics_command()
gc.SetAction(graphics.GRT_action_delete)
gc.SetDelete(utils.IfElse(img.id > 0, graphics.GRT_delete_by_id, graphics.GRT_delete_by_number))
gc.WriteWithPayloadTo(&buf, nil)
}
g.lp.QueueWriteString(buf.String())
}
func (g *graphics_manager) display_image(slot int, path string, img_width, img_height int) {
img := g.images[slot]
if img.current_file != path {
gc := img.new_graphics_command()
gc.SetAction(graphics.GRT_action_transmit).SetDataWidth(uint64(img_width)).SetDataHeight(uint64(img_height)).SetTransmission(graphics.GRT_transmission_file)
gc.WriteWithPayloadToLoop(g.lp, []byte(path))
img.current_file = path
}
gc := img.new_graphics_command()
gc.SetAction(graphics.GRT_action_display).SetCursorMovement(graphics.GRT_cursor_static)
gc.WriteWithPayloadToLoop(g.lp, nil)
}
func (g *graphics_manager) on_response(gc *graphics.GraphicsCommand) (err error) {
if gc.ResponseMessage() != "OK" {
return fmt.Errorf("Failed to load image with error: %s\n\nNote that the choose-fonts kitten does not work over SSH as it is meant to select a locally available font to use in kitty.", gc.ResponseMessage())
}
for _, img := range g.images {
if img.image_number == gc.ImageNumber() {
img.id = gc.ImageId()
break
}
}
return
}
func (g *graphics_manager) finalize() {
buf := strings.Builder{}
for _, img := range g.images {
gc := img.new_graphics_command()
gc.SetAction(graphics.GRT_action_delete)
gc.SetDelete(utils.IfElse(img.id > 0, graphics.GRT_free_by_id, graphics.GRT_free_by_number))
gc.WriteWithPayloadTo(&buf, nil)
}
g.lp.QueueWriteString(buf.String())
}
+148
View File
@@ -0,0 +1,148 @@
package choose_fonts
import (
"fmt"
"strconv"
"strings"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/readline"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type if_panel struct {
handler *handler
rl *readline.Readline
family, which, feat_tag string
settings faces_settings
feature_data FeatureData
current_val uint
}
func (self *if_panel) render_lines(start_y int, lines ...string) (y int) {
sz, _ := self.handler.lp.ScreenSize()
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
self.handler.lp.QueueWriteString(str)
return
}
func (self *if_panel) draw_screen() (err error) {
lp := self.handler.lp
feat_name := utils.IfElse(self.feature_data.Name == "", self.feat_tag, self.feature_data.Name)
lp.QueueWriteString(self.handler.format_title("Edit "+feat_name, 0))
lines := []string{
fmt.Sprintf("Enter a value for the '%s' feature of the %s font. Values are non-negative integers. Leaving it blank will cause the feature value to be not set, i.e. take its default value.", feat_name, self.family),
}
if self.feature_data.Tooltip != "" {
lines = append(lines, "")
lines = append(lines, self.feature_data.Tooltip)
}
if len(self.feature_data.Params) > 0 {
lines = append(lines, "")
lines = append(lines, "You can also click on any of the feature names below to choose the corresponding value.")
} else {
lines = append(lines, "")
lines = append(lines, "Consult the documentation for this font to find out what values are valid for this feature.")
}
lines = append(lines, "")
cursor_y := self.render_lines(2, lines...)
if len(self.feature_data.Params) > 0 {
lp.MoveCursorTo(1, cursor_y+3)
num := 1
strings.Join(utils.Map(func(x string) string {
ans := tui.InternalHyperlink(x, fmt.Sprintf("fval:%d", num))
num++
return ans
}, self.feature_data.Params), ", ")
}
lp.MoveCursorTo(1, cursor_y+1)
lp.ClearToEndOfLine()
self.rl.RedrawNonAtomic()
lp.SetCursorVisible(true)
return
}
func (self *if_panel) initialize(h *handler) (err error) {
self.handler = h
self.rl = readline.New(h.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "Value: "})
return
}
func (self *if_panel) on_wakeup() error {
return self.handler.draw_screen()
}
func (self *if_panel) on_click(id string) (err error) {
scheme, val, _ := strings.Cut(id, ":")
if scheme != "fval" {
return
}
v, _ := strconv.ParseUint(val, 10, 0)
if err = self.handler.face_pane.change_feature_value(self.feat_tag, uint(v), false); err != nil {
return err
}
self.handler.current_pane = &self.handler.face_pane
return self.handler.draw_screen()
}
func (self *if_panel) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
self.handler.current_pane = &self.handler.face_pane
return self.handler.draw_screen()
}
if event.MatchesPressOrRepeat("enter") {
event.Handled = true
text := strings.TrimSpace(self.rl.AllText())
remove := false
var val uint64
if text == "" {
remove = true
} else {
val, err = strconv.ParseUint(text, 10, 0)
}
if err != nil {
self.rl.ResetText()
self.handler.lp.Beep()
} else {
if err = self.handler.face_pane.change_feature_value(self.feat_tag, uint(val), remove); err != nil {
return err
}
self.handler.current_pane = &self.handler.face_pane
}
return self.handler.draw_screen()
}
if err = self.rl.OnKeyEvent(event); err != nil {
if err == readline.ErrAcceptInput {
return nil
}
return err
}
return self.draw_screen()
}
func (self *if_panel) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if err = self.rl.OnText(text, from_key_event, in_bracketed_paste); err != nil {
return err
}
return self.draw_screen()
}
func (self *if_panel) on_enter(family, which string, settings faces_settings, feat_tag string, fd FeatureData, current_val uint) error {
self.family = family
self.feat_tag = feat_tag
self.settings = settings
self.which = which
self.handler.current_pane = self
self.feature_data = fd
self.current_val = current_val
self.rl.ResetText()
if self.current_val > 0 {
self.rl.SetText(strconv.FormatUint(uint64(self.current_val), 10))
}
return self.handler.draw_screen()
}
+319
View File
@@ -0,0 +1,319 @@
package choose_fonts
import (
"fmt"
"strings"
"sync"
"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/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type preview_cache_key struct {
family string
width, height int
}
type preview_cache_value struct {
path string
width, height int
}
type FontList struct {
rl *readline.Readline
family_list FamilyList
fonts map[string][]ListedFont
family_list_updated bool
resolved_faces_from_kitty_conf ResolvedFaces
handler *handler
variable_data_requested_for *utils.Set[string]
preview_cache map[preview_cache_key]preview_cache_value
preview_cache_mutex sync.Mutex
}
func (self *FontList) initialize(h *handler) error {
self.handler = h
self.preview_cache = make(map[preview_cache_key]preview_cache_value)
self.rl = readline.New(h.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "Family: "})
self.variable_data_requested_for = utils.NewSet[string](256)
return nil
}
func (self *FontList) draw_search_bar() {
lp := self.handler.lp
lp.SetCursorVisible(true)
lp.SetCursorShape(loop.BAR_CURSOR, true)
sz, err := lp.ScreenSize()
if err != nil {
return
}
lp.MoveCursorTo(1, int(sz.HeightCells))
lp.ClearToEndOfLine()
self.rl.RedrawNonAtomic()
}
const SEPARATOR = "║"
func center_string(x string, width int, filler ...string) string {
space := " "
if len(filler) > 0 {
space = filler[0]
}
l := wcswidth.Stringwidth(x)
spaces := int(float64(width-l) / 2)
space = strings.Repeat(space, utils.Max(0, spaces))
return space + x + space
}
func (self *handler) format_title(title string, start_x int) string {
sz, _ := self.lp.ScreenSize()
return self.lp.SprintStyled("fg=green bold", center_string(title, int(sz.WidthCells)-start_x))
}
func (self *FontList) draw_family_summary(start_x int, sz loop.ScreenSize) (err error) {
lp := self.handler.lp
family := self.family_list.CurrentFamily()
if family == "" || int(sz.WidthCells) < start_x+2 {
return nil
}
lines := []string{self.handler.format_title(family, start_x), ""}
width := int(sz.WidthCells) - start_x - 1
add_line := func(x string) {
lines = append(lines, style.WrapTextAsLines(x, width, style.WrapOptions{})...)
}
fonts := self.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 := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(sg.styles, ", ")
add_line(styles)
add_line("")
}
if s.has_variable_faces {
add_line(fmt.Sprintf("This font is %s allowing for finer style control", lp.SprintStyled("fg=magenta", "variable")))
}
add_line(fmt.Sprintf("Press the %s key to choose this family", lp.SprintStyled("fg=yellow", "Enter")))
} else {
lines = append(lines, "Reading font data, please wait…")
key := fonts[0].cache_key()
if !self.variable_data_requested_for.Has(key) {
self.variable_data_requested_for.Add(key)
go func() {
self.handler.set_worker_error(ensure_variable_data_for_fonts(fonts...))
lp.WakeupMainThread()
}()
}
}
y := 0
for _, line := range lines {
if y >= int(sz.HeightCells)-1 {
break
}
lp.MoveCursorTo(start_x+1, y+1)
lp.QueueWriteString(line)
y++
}
if self.handler.text_style.Foreground != "" && self.handler.text_style.Background != "" {
return self.draw_preview(start_x, y, sz)
}
return
}
func (self *FontList) draw_preview(x, y int, sz loop.ScreenSize) (err error) {
width_cells, height_cells := int(sz.WidthCells)-x, int(sz.HeightCells)-y
if height_cells < 3 {
return
}
y++
self.handler.lp.MoveCursorTo(x+1, y+1)
self.handler.draw_preview_header(x)
y++
height_cells -= 2
self.handler.lp.MoveCursorTo(x+1, y+1)
key := preview_cache_key{
family: self.family_list.CurrentFamily(), width: int(sz.CellWidth) * width_cells, height: int(sz.CellHeight) * height_cells,
}
if key.family == "" {
return
}
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
cc := self.preview_cache[key]
switch cc.path {
case "":
self.preview_cache[key] = preview_cache_value{path: "requested"}
go func() {
var r map[string]RenderedSampleTransmit
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
"text_style": self.handler.text_style, "font_family": key.family, "width": key.width, "height": key.height,
"output_dir": self.handler.temp_dir,
}, &r))
self.preview_cache_mutex.Lock()
defer self.preview_cache_mutex.Unlock()
self.preview_cache[key] = preview_cache_value{path: r["font_family"].Path, width: r["font_family"].Canvas_width, height: r["font_family"].Canvas_height}
self.handler.lp.WakeupMainThread()
}()
return
case "requested":
return
}
self.handler.graphics_manager.display_image(0, cc.path, cc.width, cc.height)
return
}
func (self *FontList) on_wakeup() error {
if !self.family_list_updated {
self.family_list_updated = true
self.family_list.UpdateFamilies(utils.StableSortWithKey(utils.Keys(self.fonts), strings.ToLower))
self.family_list.SelectFamily(self.resolved_faces_from_kitty_conf.Font_family.Family)
}
return self.handler.draw_screen()
}
func (self *FontList) draw_screen() (err error) {
lp := self.handler.lp
sz, err := lp.ScreenSize()
if err != nil {
return err
}
num_rows := max(0, int(sz.HeightCells)-1)
mw := self.family_list.max_width + 1
green_fg, _, _ := strings.Cut(lp.SprintStyled("fg=green", "|"), "|")
lines := make([]string, 0, num_rows)
for _, l := range self.family_list.Lines(num_rows) {
line := l.text
if l.is_current {
line = strings.ReplaceAll(line, MARK_AFTER, green_fg)
line = lp.SprintStyled("fg=green", ">") + lp.SprintStyled("fg=green bold", line)
} else {
line = " " + line
}
lines = append(lines, line)
}
_, _, str := self.handler.render_lines.InRectangle(lines, 0, 0, 0, num_rows, &self.handler.mouse_state, self.on_click)
lp.QueueWriteString(str)
seps := strings.Repeat(SEPARATOR, num_rows)
seps = strings.TrimSpace(seps)
_, _, str = self.handler.render_lines.InRectangle(strings.Split(seps, ""), mw+1, 0, 0, num_rows, &self.handler.mouse_state)
lp.QueueWriteString(str)
if self.family_list.Len() > 0 {
if err = self.draw_family_summary(mw+3, sz); err != nil {
return err
}
}
self.draw_search_bar()
return
}
func (self *FontList) on_click(id string) error {
which, data, found := strings.Cut(id, ":")
if !found {
return fmt.Errorf("Not a valid click id: %s", id)
}
switch which {
case "family-chosen":
if self.handler.state == LISTING_FAMILIES {
if self.family_list.Select(data) {
self.handler.draw_screen()
} else {
self.handler.lp.Beep()
}
}
}
return nil
}
func (self *FontList) update_family_search() {
text := self.rl.AllText()
if self.family_list.UpdateSearch(text) {
self.handler.draw_screen()
} else {
self.draw_search_bar()
}
}
func (self *FontList) next(delta int, allow_wrapping bool) error {
if self.family_list.Next(delta, allow_wrapping) {
return self.handler.draw_screen()
}
self.handler.lp.Beep()
return nil
}
func (self *FontList) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("enter") {
event.Handled = true
if family := self.family_list.CurrentFamily(); family != "" {
return self.handler.faces.on_enter(family)
}
self.handler.lp.Beep()
return
}
if event.MatchesPressOrRepeat("esc") {
event.Handled = true
if self.rl.AllText() != "" {
self.rl.ResetText()
self.update_family_search()
self.handler.draw_screen()
} else {
return fmt.Errorf("canceled by user")
}
return
}
ev := event
if ev.MatchesPressOrRepeat("down") {
ev.Handled = true
return self.next(1, true)
}
if ev.MatchesPressOrRepeat("up") {
ev.Handled = true
return self.next(-1, true)
}
if ev.MatchesPressOrRepeat("page_down") {
ev.Handled = true
sz, err := self.handler.lp.ScreenSize()
if err == nil {
err = self.next(int(sz.HeightCells)-3, false)
}
return err
}
if ev.MatchesPressOrRepeat("page_up") {
ev.Handled = true
sz, err := self.handler.lp.ScreenSize()
if err == nil {
err = self.next(3-int(sz.HeightCells), false)
}
return err
}
if err = self.rl.OnKeyEvent(event); err != nil {
if err == readline.ErrAcceptInput {
return nil
}
return err
}
if event.Handled {
self.update_family_search()
}
self.draw_search_bar()
return
}
func (self *FontList) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if err = self.rl.OnText(text, from_key_event, in_bracketed_paste); err != nil {
return err
}
self.update_family_search()
return
}
+112
View File
@@ -0,0 +1,112 @@
package choose_fonts
import (
"fmt"
"os"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/tui/loop"
)
var _ = fmt.Print
var debugprintln = tty.DebugPrintln
var output_on_exit string
func main(opts *Options) (rc int, err error) {
if err = kitty_font_backend.start(); err != nil {
return 1, err
}
defer func() {
if werr := kitty_font_backend.release(); werr != nil {
if err == nil {
err = werr
}
if rc == 0 {
rc = 1
}
}
}()
lp, err := loop.New()
if err != nil {
return 1, err
}
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
h := &handler{lp: lp, opts: opts}
lp.OnInitialize = func() (string, error) {
lp.AllowLineWrapping(false)
lp.SetWindowTitle(`Choose a font for kitty`)
return "", h.initialize()
}
lp.OnWakeup = h.on_wakeup
lp.OnEscapeCode = h.on_escape_code
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
}
if output_on_exit != "" {
os.Stdout.WriteString(output_on_exit)
}
return lp.ExitCode(), nil
}
type Options struct {
Reload_in string
Config_file_name string
}
func EntryPoint(root *cli.Command) {
ans := root.AddSubCommand(&cli.Command{
Name: "choose-fonts",
ShortDescription: "Choose the fonts used in kitty",
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
opts := Options{}
if err = cmd.GetOptionValues(&opts); err != nil {
return 1, err
}
return main(&opts)
},
})
ans.Add(cli.OptionSpec{
Name: "--reload-in",
Dest: "Reload_in",
Type: "choices",
Choices: "parent, all, none",
Default: "parent",
Help: `By default, this kitten will signal only the parent kitty instance it is
running in to reload its config, after making changes. Use this option to
instead either not reload the config at all or in all running kitty instances.`,
})
ans.Add(cli.OptionSpec{
Name: "--config-file-name",
Dest: "Config_file_name",
Type: "str",
Default: "kitty.conf",
Help: `The name or path to the config file to edit. Relative paths are interpreted
with respect to the kitty config directory. By default the kitty config
file, kitty.conf is edited. This is most useful if you add include
fonts.conf to your kitty.conf and then have the kitten operate only on
fonts.conf, allowing kitty.conf to remain unchanged.`,
})
clone := root.AddClone(ans.Group, ans)
clone.Hidden = true
clone.Name = "choose_fonts"
}
+7
View File
@@ -0,0 +1,7 @@
if __name__ == '__main__':
import os
import sys
from kitty.constants import kitten_exe
os.execlp(kitten_exe(), 'kitten', *sys.argv)
+125
View File
@@ -0,0 +1,125 @@
package choose_fonts
import (
"cmp"
"slices"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
)
type style_group struct {
name string
ordering int
styles []string
style_sort_map map[string]float64
}
type family_style_data struct {
style_groups []style_group
has_variable_faces bool
has_style_attribute_data bool
}
func styles_with_attribute_data(ans *family_style_data, items ...VariableData) {
// Multi axis styles are kept in their own group, separate from any design axis that happens to be named Styles
type group_key struct {
name string
multi_axis_style bool
}
// Store indices, not pointers, as appending to ans.style_groups can reallocate it
groups := make(map[group_key]int)
get := func(key group_key, ordering int) *style_group {
idx, found := groups[key]
if found {
// Use the lowest ordering from any face so that the result does not depend on the order of the faces
ans.style_groups[idx].ordering = min(ans.style_groups[idx].ordering, ordering)
} else {
idx = len(ans.style_groups)
ans.style_groups = append(ans.style_groups, style_group{name: key.name, ordering: ordering, styles: make([]string, 0), style_sort_map: make(map[string]float64)})
groups[key] = idx
}
return &ans.style_groups[idx]
}
has := func(n string, m map[string]float64) bool {
_, found := m[n]
return found
}
for _, vd := range items {
for _, ax := range vd.Design_axes {
if ax.Name == "" {
continue
}
sg := get(group_key{name: ax.Name}, ax.Ordering)
for _, v := range ax.Values {
if v.Name != "" && !has(v.Name, sg.style_sort_map) {
sg.style_sort_map[v.Name] = v.Value
sg.styles = append(sg.styles, v.Name)
}
}
}
for _, ma := range vd.Multi_axis_styles {
sg := get(group_key{name: "Styles", multi_axis_style: true}, 0)
if ma.Name != "" && !has(ma.Name, sg.style_sort_map) {
sg.style_sort_map[ma.Name] = 0
sg.styles = append(sg.styles, ma.Name)
}
}
}
ans.style_groups = utils.StableSortWithKey(ans.style_groups, func(sg style_group) int { return sg.ordering })
for i := range ans.style_groups {
sg := &ans.style_groups[i]
slices.SortStableFunc(sg.styles, func(a, b string) int {
if c := cmp.Compare(sg.style_sort_map[a], sg.style_sort_map[b]); c != 0 {
return c
}
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
}
}
func styles_for_variable_data(vd VariableData) (ans *family_style_data) {
ans = &family_style_data{style_groups: make([]style_group, 0)}
styles_with_attribute_data(ans, vd)
return
}
func styles_in_family(family string, fonts []ListedFont) (ans *family_style_data) {
_ = family
vds := make([]VariableData, len(fonts))
for i, f := range fonts {
vds[i] = variable_data_for(f)
}
return styles_in_family_from_variable_data(fonts, vds)
}
// vds must contain the variable data for each font in fonts, in the same order
func styles_in_family_from_variable_data(fonts []ListedFont, vds []VariableData) (ans *family_style_data) {
ans = &family_style_data{style_groups: make([]style_group, 0)}
for _, vd := range vds {
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 {
styles_with_attribute_data(ans, vds...)
} 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)
}
}
// styles_with_attribute_data has already sorted by axis value, only sort by name here
slices.Sort(sg.styles)
}
return
}
+143
View File
@@ -0,0 +1,143 @@
// License: GPLv3 Copyright: 2026, kitty contributors
package choose_fonts
import (
"testing"
"github.com/google/go-cmp/cmp"
)
type group_result struct {
Name string
Styles []string
}
func group_results(ans *family_style_data) []group_result {
ret := make([]group_result, len(ans.style_groups))
for i, sg := range ans.style_groups {
ret[i] = group_result{sg.name, sg.styles}
}
return ret
}
func TestStylesWithAttributeData(t *testing.T) {
axis := func(name string, ordering int, style string, value float64) DesignAxis {
return DesignAxis{Name: name, Ordering: ordering, Values: []DesignAxisValue{{Name: style, Value: value}}}
}
face := func(axes ...DesignAxis) VariableData { return VariableData{Design_axes: axes} }
check := func(expected []group_result, items ...VariableData) {
t.Helper()
ans := &family_style_data{}
styles_with_attribute_data(ans, items...)
if diff := cmp.Diff(expected, group_results(ans)); diff != "" {
t.Fatalf("Unexpected styles:\n%s", diff)
}
}
// Styles added by later faces to groups created by earlier faces must not be lost
check([]group_result{{"Weight", []string{"Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}},
face(axis("Weight", 0, "Regular", 400), axis("Italic", 1, "Upright", 0)),
face(axis("Weight", 0, "Bold", 700), axis("Italic", 1, "Italic", 1)))
// Group order must not depend on the order of the faces
a := face(axis("Weight", 1, "Regular", 400), axis("Italic", 2, "Upright", 0))
b := face(axis("Weight", 2, "Bold", 700), axis("Italic", 1, "Italic", 1))
expected := []group_result{{"Weight", []string{"Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}}
check(expected, a, b)
check(expected, b, a)
// Multi axis styles are kept separate from a design axis named Styles
ma := face(axis("Styles", 1, "Wide", 2))
ma.Multi_axis_styles = []MultiAxisStyle{{Name: "Light Condensed"}, {Name: "Bold Expanded"}}
mb := face(axis("Styles", 1, "Narrow", 1))
mb.Multi_axis_styles = []MultiAxisStyle{{Name: "Light Condensed"}, {Name: "Black"}}
check([]group_result{{"Styles", []string{"Black", "Bold Expanded", "Light Condensed"}}, {"Styles", []string{"Narrow", "Wide"}}}, ma, mb)
}
func TestStyleAxisValueOrder(t *testing.T) {
for _, tt := range []struct {
name string
values []DesignAxisValue
want []string
}{
{
name: "negative slant values",
values: []DesignAxisValue{
{Name: "Oblique", Value: -5}, {Name: "Upright", Value: 0},
{Name: "Backslant", Value: 5}, {Name: "More oblique", Value: -15},
{Name: "Medium oblique", Value: -10},
},
want: []string{"More oblique", "Medium oblique", "Oblique", "Upright", "Backslant"},
},
{
name: "fractional values",
values: []DesignAxisValue{
{Name: "Zero", Value: 0},
{Name: "A positive", Value: 2.0 / 65536}, {Name: "Z positive", Value: 1.0 / 65536},
{Name: "A negative", Value: -1.0 / 65536}, {Name: "Z negative", Value: -2.0 / 65536},
},
want: []string{"Z negative", "A negative", "Zero", "Z positive", "A positive"},
},
{
name: "large negative values",
values: []DesignAxisValue{
{Name: "Zero", Value: 0}, {Name: "Minimum", Value: -32768},
{Name: "Maximum", Value: 32767 + 65535.0/65536},
{Name: "Minus ten thousand", Value: -10000}, {Name: "Minus one", Value: -1},
},
want: []string{"Minimum", "Minus ten thousand", "Minus one", "Zero", "Maximum"},
},
{
name: "equal values use stable case insensitive name order",
values: []DesignAxisValue{
{Name: "beta", Value: -10}, {Name: "alpha", Value: -10},
{Name: "Alpha", Value: -10},
},
want: []string{"alpha", "Alpha", "beta"},
},
} {
t.Run(tt.name, func(t *testing.T) {
vd := VariableData{Design_axes: []DesignAxis{{Name: "Slant", Values: tt.values}}}
fonts := make([]ListedFont, len(tt.values))
vds := make([]VariableData, len(tt.values))
for i, v := range tt.values {
fonts[i].Style = v.Name
vds[i].Design_axes = []DesignAxis{{Name: "Slant", Values: []DesignAxisValue{v}}}
}
for name, ans := range map[string]*family_style_data{
"single face": styles_for_variable_data(vd),
"family": styles_in_family_from_variable_data(fonts, vds),
} {
t.Run(name, func(t *testing.T) {
if diff := cmp.Diff([]group_result{{"Slant", tt.want}}, group_results(ans)); diff != "" {
t.Fatalf("Unexpected styles (-want +got):\n%s", diff)
}
})
}
})
}
}
func TestStylesInFamily(t *testing.T) {
check := func(expected []group_result, fonts []ListedFont, vds []VariableData) {
t.Helper()
if diff := cmp.Diff(expected, group_results(styles_in_family_from_variable_data(fonts, vds))); diff != "" {
t.Fatalf("Unexpected styles:\n%s", diff)
}
}
// Without style attribute data, the de-duplicated style names of the fonts are used
fonts := []ListedFont{{Style: "Regular"}, {Style: "Bold"}, {Style: ""}, {Style: "Bold"}, {Style: "Italic"}}
check([]group_result{{"Styles", []string{"Bold", "Italic", "Regular"}}}, fonts, make([]VariableData, len(fonts)))
// With style attribute data, styles are sorted by axis value, not by name
vd := func(weight string, weight_value float64, italic string, italic_value float64) VariableData {
return VariableData{Design_axes: []DesignAxis{
{Name: "Weight", Ordering: 0, Values: []DesignAxisValue{{Name: weight, Value: weight_value}}},
{Name: "Italic", Ordering: 1, Values: []DesignAxisValue{{Name: italic, Value: italic_value}}},
}}
}
fonts = []ListedFont{{Style: "Bold"}, {Style: "Regular"}, {Style: "Light"}}
check([]group_result{{"Weight", []string{"Light", "Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}},
fonts, []VariableData{vd("Bold", 700, "Italic", 1), vd("Regular", 400, "Upright", 0), vd("Light", 300, "Upright", 0)})
}
+333
View File
@@ -0,0 +1,333 @@
package choose_fonts
import (
"fmt"
"maps"
"strconv"
"strings"
"sync"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
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"`
}
type ResolvedFace struct {
Family string `json:"family"`
Spec string `json:"spec"`
Setting string `json:"setting"`
}
type ResolvedFaces struct {
Font_family ResolvedFace `json:"font_family"`
Bold_font ResolvedFace `json:"bold_font"`
Italic_font ResolvedFace `json:"italic_font"`
Bold_italic_font ResolvedFace `json:"bold_italic_font"`
}
type ListResult struct {
Fonts map[string][]ListedFont `json:"fonts"`
Resolved_faces ResolvedFaces `json:"resolved_faces"`
}
type FeatureData struct {
Is_index bool `json:"is_index"`
Name string `json:"name"`
Tooltip string `json:"tooltip"`
Sample string `json:"sample"`
Params []string `json:"params"`
}
type RenderedSampleTransmit struct {
Path string `json:"path"`
Variable_data VariableData `json:"variable_data"`
Style string `json:"style"`
Psname string `json:"psname"`
Spec string `json:"spec"`
Features map[string]FeatureData `json:"features"`
Applied_features map[string]string `json:"applied_features"`
Variable_named_style NamedStyle `json:"variable_named_style"`
Variable_axis_map map[string]float64 `json:"variable_axis_map"`
Cell_width int `json:"cell_width"`
Cell_height int `json:"cell_height"`
Canvas_width int `json:"canvas_width"`
Canvas_height int `json:"canvas_height"`
}
func (self RenderedSampleTransmit) default_axis_values() (ans map[string]float64) {
ans = make(map[string]float64)
for _, ax := range self.Variable_data.Axes {
ans[ax.Tag] = ax.Default
}
return
}
func (self RenderedSampleTransmit) current_axis_values() (ans map[string]float64) {
ans = make(map[string]float64, len(self.Variable_data.Axes))
for _, ax := range self.Variable_data.Axes {
ans[ax.Tag] = ax.Default
}
if self.Variable_named_style.Name != "" {
maps.Copy(ans, self.Variable_named_style.Axis_values)
} else {
maps.Copy(ans, self.Variable_axis_map)
}
return
}
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 := kitty_font_backend.query("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
}
type ParsedFontFeature struct {
tag string
val uint
is_bool bool
}
func (self ParsedFontFeature) String() string {
if self.is_bool {
return utils.IfElse(self.val == 0, "-", "+") + self.tag
}
return fmt.Sprintf("%s=%d", self.tag, self.val)
}
type settable_string struct {
val string
is_set bool
}
type FontSpec struct {
family, style, postscript_name, full_name, system, variable_name settable_string
axes map[string]float64
features []*ParsedFontFeature
}
func (self FontSpec) String() string {
if self.system.val != "" {
return self.system.val
}
ans := strings.Builder{}
a := func(k string, v settable_string) {
if v.is_set {
ans.WriteString(fmt.Sprintf(" %s=%s", k, shlex.Quote(v.val)))
}
}
a(`family`, self.family)
a(`style`, self.style)
a(`postscript_name`, self.postscript_name)
a(`full_name`, self.full_name)
a(`variable_name`, self.variable_name)
for name, val := range self.axes {
a(name, settable_string{strconv.FormatFloat(val, 'f', -1, 64), true})
}
if len(self.features) > 0 {
buf := strings.Builder{}
for _, f := range self.features {
buf.WriteString(f.String())
buf.WriteString(" ")
}
a(`features`, settable_string{strings.TrimSpace(buf.String()), true})
}
return strings.TrimSpace(ans.String())
}
func NewParsedFontFeature(x string, features map[string]FeatureData) (ans ParsedFontFeature, err error) {
if x != "" {
if x[0] == '+' || x[0] == '-' {
return ParsedFontFeature{x[1:], utils.IfElse(x[0] == '+', uint(1), uint(0)), true}, nil
} else {
tag, val, found := strings.Cut(x, "=")
fd, defn_found := features[tag]
if defn_found && !fd.Is_index {
return ParsedFontFeature{tag, 1, true}, nil
}
pff := ParsedFontFeature{tag: tag}
if found {
v, err := strconv.ParseUint(val, 10, 0)
if err != nil {
return ans, err
}
pff.val = uint(v)
}
return pff, nil
}
}
return
}
func NewFontSpec(spec string, features map[string]FeatureData) (ans FontSpec, err error) {
if spec == "" || spec == "auto" {
ans.system = settable_string{"auto", true}
return
}
parts, err := shlex.Split(spec)
if err != nil {
return
}
if !strings.Contains(parts[0], "=") {
ans.system = settable_string{spec, true}
return
}
for _, item := range parts {
k, v, found := strings.Cut(item, "=")
if !found {
return ans, fmt.Errorf("The font specification %s is invalid as %s does not contain an =", spec, item)
}
switch k {
case "family":
ans.family = settable_string{v, true}
case "style":
ans.style = settable_string{v, true}
case "full_name":
ans.full_name = settable_string{v, true}
case "postscript_name":
ans.postscript_name = settable_string{v, true}
case "variable_name":
ans.variable_name = settable_string{v, true}
case "features":
for _, x := range utils.NewSeparatorScanner(v, " ").Split(v) {
pff, err := NewParsedFontFeature(x, features)
if err != nil {
return ans, err
}
ans.features = append(ans.features, &pff)
}
default:
if ans.axes == nil {
ans.axes = make(map[string]float64)
}
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return ans, err
}
ans.axes[k] = f
}
}
return
}
+230
View File
@@ -0,0 +1,230 @@
package choose_fonts
import (
"fmt"
"os"
"strconv"
"sync"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/graphics"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type State int
const (
SCANNING_FAMILIES State = iota
LISTING_FAMILIES
CHOOSING_FACES
)
type TextStyle struct {
Font_sz float64 `json:"font_size"`
Dpi_x float64 `json:"dpi_x"`
Dpi_y float64 `json:"dpi_y"`
Foreground string `json:"foreground"`
Background string `json:"background"`
}
type pane interface {
initialize(*handler) error
draw_screen() error
on_wakeup() error
on_key_event(event *loop.KeyEvent) error
on_text(text string, from_key_event bool, in_bracketed_paste bool) error
on_click(id string) error
}
type handler struct {
opts *Options
lp *loop.Loop
state State
err_mutex sync.Mutex
err_in_worker_thread error
mouse_state tui.MouseState
render_count uint
render_lines tui.RenderLines
text_style TextStyle
graphics_manager graphics_manager
temp_dir string
listing FontList
faces faces
face_pane face_panel
if_pane if_panel
final_pane final_pane
panes []pane
current_pane pane
}
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
}
// Events {{{
func (h *handler) initialize() (err error) {
h.lp.SetCursorVisible(false)
h.lp.OnQueryResponse = h.on_query_response
h.lp.QueryTerminal("font_size", "dpi_x", "dpi_y", "foreground", "background")
h.panes = []pane{&h.listing, &h.faces, &h.face_pane, &h.if_pane, &h.final_pane}
for _, pane := range h.panes {
if err = pane.initialize(h); err != nil {
return err
}
}
// dont use /tmp as it may be mounted in RAM, Le Sigh
if h.temp_dir, err = os.MkdirTemp(utils.CacheDir(), "kitten-choose-fonts-*"); err != nil {
return
}
initialize_variable_data_cache()
h.graphics_manager.initialize(h.lp)
go func() {
var r ListResult
h.set_worker_error(kitty_font_backend.query("list_monospaced_fonts", nil, &r))
h.listing.fonts = r.Fonts
h.listing.resolved_faces_from_kitty_conf = r.Resolved_faces
h.lp.WakeupMainThread()
}()
h.draw_screen()
return
}
func (h *handler) finalize() {
if h.temp_dir != "" {
os.RemoveAll(h.temp_dir)
h.temp_dir = ""
}
h.lp.SetCursorVisible(true)
h.lp.SetCursorShape(loop.BLOCK_CURSOR, true)
h.graphics_manager.finalize()
}
func (h *handler) on_query_response(key, val string, valid bool) error {
if !valid {
return fmt.Errorf("Terminal does not support querying the: %s", key)
}
set_float := func(k, v string, dest *float64) error {
if fs, err := strconv.ParseFloat(v, 64); err == nil {
*dest = fs
} else {
return fmt.Errorf("Invalid response from terminal to %s query: %#v", k, v)
}
return nil
}
switch key {
case "font_size":
if err := set_float(key, val, &h.text_style.Font_sz); err != nil {
return err
}
case "dpi_x":
if err := set_float(key, val, &h.text_style.Dpi_x); err != nil {
return err
}
case "dpi_y":
if err := set_float(key, val, &h.text_style.Dpi_y); err != nil {
return err
}
case "foreground":
h.text_style.Foreground = val
if h.text_style.Background != "" {
return h.draw_screen()
}
case "background":
h.text_style.Background = val
if h.text_style.Foreground != "" {
return h.draw_screen()
}
}
return nil
}
func (h *handler) draw_screen() (err error) {
h.render_count++
h.lp.StartAtomicUpdate()
defer func() {
h.mouse_state.UpdateHoveredIds()
h.mouse_state.ApplyHoverStyles(h.lp)
h.lp.EndAtomicUpdate()
}()
h.graphics_manager.clear_placements()
h.lp.ClearScreenButNotGraphics()
h.lp.AllowLineWrapping(false)
h.mouse_state.ClearCellRegions()
if h.current_pane == nil {
h.lp.Println("Scanning system for fonts, please wait...")
} else {
return h.current_pane.draw_screen()
}
return
}
func (h *handler) on_wakeup() (err error) {
if err = h.get_worker_error(); err != nil {
return
}
if h.current_pane == nil {
h.current_pane = &h.listing
}
return h.listing.on_wakeup()
}
func (h *handler) on_mouse_event(event *loop.MouseEvent) (err error) {
rc := h.render_count
redraw_needed := false
if h.mouse_state.UpdateState(event) {
redraw_needed = true
}
if event.Event_type == loop.MOUSE_CLICK && event.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
if err = h.mouse_state.ClickHoveredRegions(); err != nil {
return
}
}
if redraw_needed && rc == h.render_count {
err = h.draw_screen()
}
return
}
func (h *handler) on_key_event(event *loop.KeyEvent) (err error) {
if event.MatchesPressOrRepeat("ctrl+c") {
event.Handled = true
return fmt.Errorf("canceled by user")
}
if h.current_pane != nil {
err = h.current_pane.on_key_event(event)
}
return
}
func (h *handler) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
if h.current_pane != nil {
err = h.current_pane.on_text(text, from_key_event, in_bracketed_paste)
}
return
}
func (h *handler) on_escape_code(etype loop.EscapeCodeType, payload []byte) error {
switch etype {
case loop.APC:
gc := graphics.GraphicsCommandFromAPC(payload)
if gc != nil {
return h.graphics_manager.on_response(gc)
}
}
return nil
}
// }}}