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.
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import inspect
from typing import Any, NamedTuple
from .boss import Boss
from .tabs import Tab
from .types import ActionGroup, ActionSpec, run_once
from .window import Window
class Action(NamedTuple):
name: str
group: ActionGroup
short_help: str
long_help: str
groups: dict[ActionGroup, str] = {
'cp': 'Copy/paste',
'sc': 'Scrolling',
'win': 'Window management',
'tab': 'Tab management',
'fs': 'Font sizes',
'mouse': 'Mouse actions',
'mk': 'Marks',
'lay': 'Layouts',
'misc': 'Miscellaneous',
'debug': 'Debugging',
'session': 'Sessions',
}
group_title = groups.__getitem__
@run_once
def get_all_actions() -> dict[ActionGroup, list[Action]]:
"test docstring"
ans: dict[ActionGroup, list[Action]] = {}
def is_action(x: Any) -> bool:
return isinstance(getattr(x, 'action_spec', None), ActionSpec)
def as_action(x: Any) -> Action:
spec: ActionSpec = getattr(x, 'action_spec')
doc = inspect.cleandoc(spec.doc)
lines = doc.splitlines()
first = lines.pop(0)
short_help = first
long_help = '\n'.join(lines).strip()
if spec.group not in groups:
raise KeyError(f'Unknown action type: {spec.group}')
return Action(getattr(x, '__name__'), spec.group, short_help, long_help)
seen = set()
for cls in (Window, Tab, Boss):
for name, func in inspect.getmembers(cls, is_action):
ac = as_action(func)
if ac.name not in seen:
ans.setdefault(ac.group, []).append(ac)
seen.add(ac.name)
ans['misc'].append(
Action(
'no_op',
'misc',
'Unbind a shortcut',
'Mapping a shortcut to no_op causes kitty to not intercept the key stroke anymore, instead passing it to the program running inside it.',
)
)
return ans
def dump() -> None:
from pprint import pprint
pprint(get_all_actions())
def as_rst() -> str:
from .conf.types import Mapping
from .options.definition import definition
allg = get_all_actions()
lines: list[str] = []
a = lines.append
maps: dict[str, list[Mapping]] = {}
for m in definition.iter_all_maps():
if m.documented:
func = m.action_def.split()[0]
maps.setdefault(func, []).append(m)
def key(x: ActionGroup) -> str:
return group_title(x).lower()
def kitten_link(text: str) -> str:
# skip any --flag tokens at the start, then key, then 'kitten', then kitten name
parts = text.split()
# find 'kitten' token and take the next one as the kitten name
for i, p in enumerate(parts):
if p == 'kitten' and i + 1 < len(parts):
return f':doc:`kittens/{parts[i + 1]}`'
return ''
for group in sorted(allg, key=key):
title = group_title(group)
a('')
a(f'.. _action-group-{group}:')
a('')
a(title)
a('-' * len(title))
a('')
for action in allg[group]:
a('')
a(f'.. action:: {action.name}')
a('')
a(action.short_help)
a('')
if action.long_help:
a(action.long_help)
if action.name in maps:
a('')
a('Default shortcuts using this action:')
if action.name == 'kitten':
a('')
scs = {(kitten_link(m.parseable_text), m.short_text, f':sc:`kitty.{m.name}`') for m in maps[action.name]}
for s in sorted(scs):
a(f'- {s[0]} - {s[2]} {s[1]}')
else:
sscs = {f':sc:`kitty.{m.name}`' for m in maps[action.name]}
a(', '.join(sorted(sscs)))
return '\n'.join(lines)
+51
View File
@@ -0,0 +1,51 @@
/*
* animation-parse.h
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include "animation.h"
// Populate an Animation from a Python EasingFunction NamedTuple
// (kitty.options.utils.EasingFunction). y_at_start/y_at_end are the output
// values at t=0 and t=1 respectively.
static void
add_easing_function(Animation *a, PyObject *e, double y_at_start, double y_at_end) {
#define G(name) RAII_PyObject(name, PyObject_GetAttrString(e, #name))
#define D(container, idx) PyFloat_AsDouble(PyTuple_GET_ITEM(container, idx))
#define EQ(x, val) (PyUnicode_CompareWithASCIIString((x), val) == 0)
G(type);
if (EQ(type, "cubic-bezier")) {
G(cubic_bezier_points);
add_cubic_bezier_animation(
a, y_at_start, y_at_end, D(cubic_bezier_points, 0), D(cubic_bezier_points, 1), D(cubic_bezier_points, 2), D(cubic_bezier_points, 3));
} else if (EQ(type, "linear")) {
G(linear_x);
G(linear_y);
size_t count = PyTuple_GET_SIZE(linear_x);
RAII_ALLOC(double, x, malloc(2 * sizeof(double) * count));
if (x) {
double *y = x + count;
for (size_t i = 0; i < count; i++) {
x[i] = D(linear_x, i);
y[i] = D(linear_y, i);
}
add_linear_animation(a, y_at_start, y_at_end, count, x, y);
}
} else if (EQ(type, "steps")) {
G(num_steps);
G(jump_type);
EasingStep jt = EASING_STEP_END;
if (EQ(jump_type, "start")) jt = EASING_STEP_START;
else if (EQ(jump_type, "none")) jt = EASING_STEP_NONE;
else if (EQ(jump_type, "both")) jt = EASING_STEP_BOTH;
add_steps_animation(a, y_at_start, y_at_end, PyLong_AsSize_t(num_steps), jt);
}
#undef EQ
#undef D
#undef G
}
+337
View File
@@ -0,0 +1,337 @@
/*
* animation.c
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#define ANIMATION_INTERNAL_API
typedef struct LinearParameters {
size_t count;
double buf[];
} LinearParameters;
typedef struct StepsParameters {
size_t num_of_buckets;
double jump_size, start_value;
} StepsParameters;
static const double bezier_epsilon = 1e-7;
static const unsigned max_newton_iterations = 4;
static const unsigned max_bisection_iterations = 16;
typedef struct BezierParameters {
double ax, bx, cx, ay, by, cy, start_gradient, end_gradient, spline_samples[11];
} BezierParameters;
typedef double (*easing_curve)(void *, double, monotonic_t);
typedef struct animation_function {
void *params;
easing_curve curve;
double y_at_start, y_size;
} animation_function;
typedef struct Animation {
animation_function *functions;
size_t count, capacity;
} Animation;
#include "animation.h"
#include "state.h"
Animation *
alloc_animation(void) {
return calloc(1, sizeof(Animation));
}
bool
animation_is_valid(const Animation *a) {
return a != NULL && a->count > 0;
}
Animation *
free_animation(Animation *a) {
if (a) {
for (size_t i = 0; i < a->count; i++) free(a->functions[i].params);
free(a->functions);
free(a);
}
return NULL;
}
static double
unit_value(double x) {
return MAX(0., MIN(x, 1.));
}
static double
linear_easing_curve(void *p_, double val, monotonic_t duration UNUSED) {
LinearParameters *p = p_;
double start_pos = 0, stop_pos = 1, start_val = 0, stop_val = 1;
double *x = p->buf, *y = p->buf + p->count;
for (size_t i = 0; i < p->count; i++) {
if (x[i] >= val) {
stop_pos = x[i];
stop_val = y[i];
if (i > 0) {
start_val = y[i - 1];
start_pos = x[i - 1];
}
break;
}
}
if (stop_pos > start_pos) {
double frac = (val - start_pos) / (stop_pos - start_pos);
return start_val + frac * (stop_val - start_val);
}
return stop_val;
}
// Cubic Bezier {{{
static double
sample_curve_x(const BezierParameters *p, double t) {
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
return ((p->ax * t + p->bx) * t + p->cx) * t;
}
static double
sample_curve_y(const BezierParameters *p, double t) {
return ((p->ay * t + p->by) * t + p->cy) * t;
}
static double
sample_derivative_x(const BezierParameters *p, double t) {
return (3.0 * p->ax * t + 2.0 * p->bx) * t + p->cx;
}
static double
solve_curve_x(const BezierParameters *p, double x, double epsilon) {
// Given an x value, find a parametric value it came from.
double t0 = 0.0, t1 = 0.0, t2 = x, x2 = 0.0, d2 = 0.0;
// Linear interpolation of spline curve for initial guess.
static const size_t num_samples = arraysz(p->spline_samples);
double delta = 1.0 / (num_samples - 1);
for (size_t i = 1; i < num_samples; i++) {
if (x <= p->spline_samples[i]) {
t1 = delta * i;
t0 = t1 - delta;
t2 = t0 + (t1 - t0) * (x - p->spline_samples[i - 1]) / (p->spline_samples[i] - p->spline_samples[i - 1]);
break;
}
}
// Perform a few iterations of Newton's method -- normally very fast.
// See https://en.wikipedia.org/wiki/Newton%27s_method.
double newton_epsilon = MIN(bezier_epsilon, epsilon);
for (unsigned i = 0; i < max_newton_iterations; i++) {
x2 = sample_curve_x(p, t2) - x;
if (fabs(x2) < newton_epsilon) return t2;
d2 = sample_derivative_x(p, t2);
if (fabs(d2) < bezier_epsilon) break;
t2 = t2 - x2 / d2;
}
if (fabs(x2) < epsilon) return t2;
t0 = 0.0, t1 = 0.0, t2 = x, x2 = 0.0;
// Fall back to the bisection method for reliability.
unsigned iteration = 0;
while (t0 < t1 && iteration++ < max_bisection_iterations) {
x2 = sample_curve_x(p, t2);
if (fabs(x2 - x) < epsilon) return t2;
if (x > x2) t0 = t2;
else t1 = t2;
t2 = (t1 + t0) * .5;
}
// Failure.
return t2;
}
static double
solve_unit_bezier(const BezierParameters *p, double x, double epsilon) {
if (x < 0.0) return 0.0 + p->start_gradient * x;
if (x > 1.0) return 1.0 + p->end_gradient * (x - 1.0);
return sample_curve_y(p, solve_curve_x(p, x, epsilon));
}
static double
cubic_bezier_easing_curve(void *p_, double t, monotonic_t duration) {
BezierParameters *p = p_;
// The longer the animation, the more precision we need
double epsilon = 1.0 / monotonic_t_to_ms(duration);
return fabs(solve_unit_bezier(p, t, epsilon));
}
// }}}
static double
step_easing_curve(void *p_, double t, monotonic_t duration UNUSED) {
StepsParameters *p = p_;
size_t val_bucket = (size_t)(t * p->num_of_buckets);
return p->start_value + val_bucket * p->jump_size;
}
static double
identity_easing_curve(void *p_ UNUSED, double t, monotonic_t duration UNUSED) {
return t;
}
bool
animations_equal(const Animation *a, const Animation *b) {
if (a == b) return true;
if (!a || !b) return false;
if (a->count != b->count) return false;
for (size_t i = 0; i < a->count; i++) {
const animation_function *fa = &a->functions[i];
const animation_function *fb = &b->functions[i];
if (fa->curve != fb->curve || fa->y_at_start != fb->y_at_start || fa->y_size != fb->y_size) return false;
if (fa->curve == cubic_bezier_easing_curve) {
if (memcmp(fa->params, fb->params, sizeof(BezierParameters)) != 0) return false;
} else if (fa->curve == linear_easing_curve) {
const LinearParameters *pa = fa->params, *pb = fb->params;
if (pa->count != pb->count) return false;
if (memcmp(pa->buf, pb->buf, 2 * pa->count * sizeof(double)) != 0) return false;
} else if (fa->curve == step_easing_curve) {
if (memcmp(fa->params, fb->params, sizeof(StepsParameters)) != 0) return false;
}
// identity_easing_curve has no params; function-pointer equality above is sufficient
}
return true;
}
double
apply_easing_curve(const Animation *a, double val, monotonic_t duration) {
val = unit_value(val);
if (!a->count) return val;
size_t idx = MIN((size_t)(val * a->count), a->count - 1);
animation_function *f = a->functions + idx;
double interval_size = 1. / a->count, interval_start = idx * interval_size;
double scaled_val = (val - interval_start) / interval_size;
double ans = f->curve(f->params, scaled_val, duration);
return f->y_at_start + unit_value(ans) * f->y_size;
}
static animation_function *
init_function(Animation *a, double y_at_start, double y_at_end, easing_curve curve) {
ensure_space_for(a, functions, animation_function, a->count + 1, capacity, 4, false);
animation_function *f = a->functions + a->count++;
zero_at_ptr(f);
f->y_at_start = y_at_start;
f->y_size = y_at_end - y_at_start;
f->curve = curve;
return f;
}
static bool
is_bezier_linear(double p1x, double p1y, double p2x, double p2y) {
// Is linear if all four points are on the same line. P0 and P4 are fixed at (0, 0) and (1, 1) for us.
return p1x == p1y && p2x == p2y;
}
void
add_cubic_bezier_animation(Animation *a, double y_at_start, double y_at_end, double p1x, double p1y, double p2x, double p2y) {
p1x = unit_value(p1x);
p2x = unit_value(p2x);
if (is_bezier_linear(p1x, p1y, p2x, p2y)) {
init_function(a, y_at_start, y_at_end, identity_easing_curve);
return;
}
BezierParameters *p = calloc(1, sizeof(BezierParameters));
if (!p) fatal("Out of memory");
// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
p->cx = 3.0 * p1x;
p->bx = 3.0 * (p2x - p1x) - p->cx;
p->ax = 1.0 - p->cx - p->bx;
p->cy = 3.0 * p1y;
p->by = 3.0 * (p2y - p1y) - p->cy;
p->ay = 1.0 - p->cy - p->by;
// Calculate gradients used for values outside the unit interval
if (p1x > 0) p->start_gradient = p1y / p1x;
else if (p1y == 0 && p2x > 0) p->start_gradient = p2y / p2x;
else if (p1y == 0 && p2y == 0) p->start_gradient = 1;
else p->start_gradient = 0;
if (p2x < 1) p->end_gradient = (p2y - 1) / (p2x - 1);
else if (p2y == 1 && p1x < 1) p->end_gradient = (p1y - 1) / (p1x - 1);
else if (p2y == 1 && p1y == 1) p->end_gradient = 1;
else p->end_gradient = 0;
size_t num_samples = arraysz(p->spline_samples);
double delta = 1. / num_samples;
for (size_t i = 0; i < num_samples; i++) p->spline_samples[i] = sample_curve_x(p, i * delta);
animation_function *f = init_function(a, y_at_start, y_at_end, cubic_bezier_easing_curve);
f->params = p;
}
void
add_linear_animation(Animation *a, double y_at_start, double y_at_end, size_t count, const double *x, const double *y) {
const size_t sz = count * sizeof(double);
LinearParameters *p = calloc(1, sizeof(LinearParameters) + 2 * sz);
if (!p) fatal("Out of memory");
p->count = count;
double *px = p->buf, *py = px + count;
memcpy(px, x, sz);
memcpy(py, y, sz);
animation_function *f = init_function(a, y_at_start, y_at_end, linear_easing_curve);
f->params = p;
}
void
add_steps_animation(Animation *a, double y_at_start, double y_at_end, size_t count, EasingStep step) {
double jump_size = 1. / count, start_value = 0.;
size_t num_of_buckets = count;
switch (step) {
case EASING_STEP_START: start_value = jump_size; break;
case EASING_STEP_END: break;
case EASING_STEP_NONE: jump_size = 1. / (num_of_buckets - 1); break;
case EASING_STEP_BOTH:
num_of_buckets++;
jump_size = 1. / num_of_buckets;
start_value = jump_size;
break;
}
StepsParameters *p = malloc(sizeof(StepsParameters));
if (!p) fatal("Out of memory");
p->num_of_buckets = num_of_buckets;
p->jump_size = jump_size;
p->start_value = start_value;
animation_function *f = init_function(a, y_at_start, y_at_end, step_easing_curve);
f->params = p;
}
static PyObject *
test_cursor_blink_easing_function(PyObject *self UNUSED, PyObject *args) {
Animation *a = OPT(animation.cursor);
if (!animation_is_valid(a)) {
PyErr_SetString(PyExc_RuntimeError, "must set a cursor blink animation on the global options object first");
return NULL;
}
double t, duration_s = 0.5;
int only_single = 1;
if (!PyArg_ParseTuple(args, "d|pd", &t, &only_single, &duration_s)) return NULL;
monotonic_t duration = s_double_to_monotonic_t(duration_s);
if (only_single) {
animation_function f = a->functions[0];
return PyFloat_FromDouble(f.curve(f.params, t, duration));
}
return PyFloat_FromDouble(apply_easing_curve(a, t, duration));
}
static PyMethodDef module_methods[] = {
METHODB(test_cursor_blink_easing_function, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_animations(PyObject *module) {
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
return true;
}
+29
View File
@@ -0,0 +1,29 @@
/*
* animation.h
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stddef.h>
#include <stdbool.h>
#include "monotonic.h"
typedef enum { EASING_STEP_START, EASING_STEP_END, EASING_STEP_NONE, EASING_STEP_BOTH } EasingStep;
#ifndef ANIMATION_INTERNAL_API
typedef struct {
int x;
} *Animation;
#endif
#define EASE_IN_OUT 0.42, 0, 0.58, 1
#define ANIMATION_SAMPLE_WAIT (50 * MONOTONIC_T_1e6)
Animation *alloc_animation(void);
double apply_easing_curve(const Animation *a, double t /* must be between 0 and 1*/, monotonic_t duration);
bool animation_is_valid(const Animation *a);
void add_cubic_bezier_animation(Animation *a, double y_at_start, double y_at_end, double p1_x, double p1_y, double p2_x, double p2_y);
void add_linear_animation(Animation *a, double y_at_start, double y_at_end, size_t count, const double *x, const double *y);
void add_steps_animation(Animation *a, double y_at_start, double y_at_end, size_t count, EasingStep step);
Animation *free_animation(Animation *a);
bool animations_equal(const Animation *a, const Animation *b);
+29
View File
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#ifdef __aarch64__
#define KITTY_TARGET_CPU_IS_ARM64
#define KITTY_128BIT_ALLOWED
#define KITTY_256BIT_ALLOWED
#elif defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__)
#define KITTY_TARGET_CPU_IS_X86
#define KITTY_128BIT_ALLOWED
#elif defined(__amd64__)
#define KITTY_TARGET_CPU_IS_AMD64
#define KITTY_128BIT_ALLOWED
#define KITTY_256BIT_ALLOWED
#endif
#if defined(__clang__) && defined(KITTY_128BIT_ALLOWED)
#define KITTY_START_128BIT_CODE
#elif defined(KITTY_128BIT_ALLOWED)
#define KITTY_START_128BIT_CODE
#else
#define KITTY_START_128BIT_CODE
#endif
+89
View File
@@ -0,0 +1,89 @@
/*
* arena.h
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#ifndef MA_NAME
#error "Must define MA_NAME"
#endif
#ifndef MA_BLOCK_SIZE
#define MA_BLOCK_SIZE 1u
#endif
#define MA_CAT_(a, b) a##b
#define MA_CAT(a, b) MA_CAT_(a, b)
#ifndef MA_ARENA_NUM_BLOCKS
#define MA_ARENA_NUM_BLOCKS 4096u
#endif
#define MA_TYPE_NAME MA_CAT(MA_NAME, MonotonicArena)
#define MA_BLOCK_TYPE_NAME MA_CAT(MA_NAME, MonotonicArenaBlock)
typedef struct MA_BLOCK_TYPE_NAME {
void *buf;
size_t used, capacity;
} MA_BLOCK_TYPE_NAME;
typedef struct MA_TYPE_NAME {
MA_BLOCK_TYPE_NAME *blocks;
size_t count, capacity;
// total number of bytes malloced by this arena, for callers that need to
// bound their memory use. Note that this is larger than the sum of the
// sizes passed to _get() since blocks are allocated in fixed size chunks
// and the tail of a block is wasted when the next allocation does not fit.
size_t allocated;
} MA_TYPE_NAME;
static inline void
MA_CAT(MA_NAME, _free_all)(MA_TYPE_NAME *self) {
for (size_t i = 0; i < self->count; i++) free(self->blocks[i].buf);
free(self->blocks);
zero_at_ptr(self);
}
static inline void *
MA_CAT(MA_NAME, _get)(MA_TYPE_NAME *self, size_t sz) {
size_t required_size = (sz / MA_BLOCK_SIZE) * MA_BLOCK_SIZE;
if (required_size < sz) required_size += MA_BLOCK_SIZE;
if (!self->count || (self->blocks[self->count - 1].capacity - self->blocks[self->count - 1].used) < required_size) {
size_t count = self->count + 1;
size_t block_sz = MAX(required_size, MA_ARENA_NUM_BLOCKS * MA_BLOCK_SIZE);
void *chunk = NULL;
if (MA_BLOCK_SIZE >= sizeof(void *) && MA_BLOCK_SIZE % sizeof(void *) == 0) {
if (posix_memalign(&chunk, MA_BLOCK_SIZE, block_sz) != 0) chunk = NULL;
else memset(chunk, 0, block_sz);
} else chunk = calloc(1, block_sz);
if (!chunk) { return NULL; }
if (count > self->capacity) {
size_t capacity = MAX(8u, 2 * self->capacity);
MA_BLOCK_TYPE_NAME *blocks = realloc(self->blocks, capacity * sizeof(MA_BLOCK_TYPE_NAME));
if (!blocks) {
free(chunk);
return NULL;
}
self->allocated += (capacity - self->capacity) * sizeof(MA_BLOCK_TYPE_NAME);
self->capacity = capacity;
self->blocks = blocks;
}
self->blocks[count - 1] = (MA_BLOCK_TYPE_NAME){.capacity = block_sz, .buf = chunk};
self->count = count;
self->allocated += block_sz;
}
char *ans = (char *)self->blocks[self->count - 1].buf + self->blocks[self->count - 1].used;
self->blocks[self->count - 1].used += required_size;
return ans;
}
#undef MA_NAME
#undef MA_BLOCK_SIZE
#undef MA_ARENA_NUM_BLOCKS
#undef MA_TYPE_NAME
#undef MA_BLOCK_TYPE_NAME
#undef MA_CAT
#undef MA_CAT_
+33
View File
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#if __has_include(<execinfo.h>)
#include <execinfo.h>
static inline void
print_stack_trace(void) {
void *array[256];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 256);
// print out all the frames to stderr
backtrace_symbols_fd(array, size, STDERR_FILENO);
}
#else
static inline void
print_stack_trace(void) {
fprintf(stderr, "Stack trace functionality not available.\n");
}
#endif
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#define BANNED(func) sorry_##func##_is_a_banned_function
#undef strcpy
#define strcpy(x, y) BANNED(strcpy)
#undef strcat
#define strcat(x, y) BANNED(strcat)
#undef strncpy
#define strncpy(x, y, n) BANNED(strncpy)
#undef strncat
#define strncat(x, y, n) BANNED(strncat)
#undef sprintf
#undef vsprintf
#ifdef HAVE_VARIADIC_MACROS
#define sprintf(...) BANNED(sprintf)
#define vsprintf(...) BANNED(vsprintf)
#else
#define sprintf(buf, fmt, arg) BANNED(sprintf)
#define vsprintf(buf, fmt, arg) BANNED(vsprintf)
#endif
#undef gmtime
#define gmtime(t) BANNED(gmtime)
#undef localtime
#define localtime(t) BANNED(localtime)
#undef ctime
#define ctime(t) BANNED(ctime)
#undef ctime_r
#define ctime_r(t, buf) BANNED(ctime_r)
#undef asctime
#define asctime(t) BANNED(asctime)
#undef asctime_r
#define asctime_r(t, buf) BANNED(asctime_r)
+70
View File
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2023 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "../3rdparty/base64/include/libbase64.h"
typedef struct base64_state base64_state;
static inline size_t
required_buffer_size_for_base64_decode(size_t src_sz) {
return (src_sz / 4 * 3 + 2);
}
static inline size_t
required_buffer_size_for_base64_encode(size_t src_sz) {
return ((src_sz + 2) / 3 * 4);
}
static inline void
base64_init_stream_decoder(base64_state *state) {
base64_stream_decode_init(state, 0);
}
static inline bool
base64_decode_stream(base64_state *state, const uint8_t *src, size_t src_sz, uint8_t *dest, size_t *dest_sz) {
// Decoding nothing always succeeds. libbase64 fails any call made after
// it has seen padding, even an empty one, which breaks protocols that
// terminate streams with an empty chunk.
if (!src_sz) {
*dest_sz = 0;
return true;
}
if (*dest_sz < required_buffer_size_for_base64_decode(src_sz)) return false;
return base64_stream_decode(state, (const char *)src, src_sz, (char *)dest, dest_sz) == 1;
}
static inline bool
base64_decode8(const uint8_t *src, size_t src_sz, uint8_t *dest, size_t *dest_sz) {
if (*dest_sz < required_buffer_size_for_base64_decode(src_sz)) return false;
// we ignore the return value of base64_decode as it returns non-zero when it is
// waiting for padding bytes
base64_decode((const char *)src, src_sz, (char *)dest, dest_sz, 0);
return true;
}
// Same as base64_decode8() but rejects, rather than ignoring, data that is not
// valid RFC-4648 base64, that is, data containing characters outside the
// base64 alphabet or data that is not correctly padded.
static inline bool
base64_decode8_strict(const uint8_t *src, size_t src_sz, uint8_t *dest, size_t *dest_sz) {
if (*dest_sz < required_buffer_size_for_base64_decode(src_sz)) return false;
// base64_decode() returns zero both for invalid characters and for input
// that ends in the middle of a four byte group, i.e. missing padding bytes
return base64_decode((const char *)src, src_sz, (char *)dest, dest_sz, 0) != 0;
}
static inline bool
base64_encode8(const unsigned char *src, size_t src_len, unsigned char *out, size_t *out_len, bool add_padding) {
if (*out_len < required_buffer_size_for_base64_encode(src_len)) return false;
base64_encode((const char *)src, src_len, (char *)out, out_len, 0);
if (!add_padding) {
while (*out_len && out[*out_len - 1] == '=') *out_len -= 1;
}
return true;
}
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
from .utils import shlex_split
def decode_ansi_c_quoted_string(text: str) -> str:
return next(shlex_split(text, True))
def decode_double_quoted_string(text: str, pos: int) -> tuple[str, int]:
escapes = r'"\$`'
buf: list[str] = []
a = buf.append
while pos < len(text):
ch = text[pos]
pos += 1
if ch == '\\':
if text[pos] in escapes:
a(text[pos])
pos += 1
continue
a(ch)
elif ch == '"':
break
else:
a(ch)
return ''.join(buf), pos
def parse_modern_bash_env(text: str) -> dict[str, str]:
ans = {}
for line in text.splitlines():
idx = line.find('=')
if idx < 0:
break
key = line[:idx].rpartition(' ')[2]
val = line[idx + 1 :]
if val.startswith('"'):
val = decode_double_quoted_string(val, 1)[0]
else:
val = decode_ansi_c_quoted_string(val)
ans[key] = val
return ans
def parse_bash_env(text: str, bash_version: str) -> dict[str, str]:
# See https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
parts = bash_version.split('.')
bv = tuple(map(int, parts[:2]))
if bv >= (5, 2):
return parse_modern_bash_env(text)
ans = {}
pos = 0
while pos < len(text):
idx = text.find('="', pos)
if idx < 0:
break
i = text.rfind(' ', 0, idx)
if i < 0:
break
key = text[i + 1 : idx]
pos = idx + 2
ans[key], pos = decode_double_quoted_string(text, pos)
return ans
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2023 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdint.h>
static inline uint16_t
be16dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((unsigned)p[0] << 8) | p[1]);
}
static inline uint32_t
be32dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3]);
}
static inline uint64_t
be64dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((uint64_t)be32dec(p) << 32) | be32dec(p + 4));
}
static inline uint16_t
le16dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((unsigned)p[1] << 8) | p[0]);
}
static inline uint32_t
le32dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((uint32_t)p[3] << 24) | ((uint32_t)p[2] << 16) | ((uint32_t)p[1] << 8) | p[0]);
}
static inline uint64_t
le64dec(const void *pp) {
uint8_t const *p = (uint8_t const *)pp;
return (((uint64_t)le32dec(p + 4) << 32) | le32dec(p));
}
static inline void
be16enc(void *pp, uint16_t u) {
uint8_t *p = (uint8_t *)pp;
p[0] = (u >> 8) & 0xff;
p[1] = u & 0xff;
}
static inline void
be32enc(void *pp, uint32_t u) {
uint8_t *p = (uint8_t *)pp;
p[0] = (u >> 24) & 0xff;
p[1] = (u >> 16) & 0xff;
p[2] = (u >> 8) & 0xff;
p[3] = u & 0xff;
}
static inline void
be64enc(void *pp, uint64_t u) {
uint8_t *p = (uint8_t *)pp;
be32enc(p, (uint32_t)(u >> 32));
be32enc(p + 4, (uint32_t)(u & 0xffffffffU));
}
static inline void
le16enc(void *pp, uint16_t u) {
uint8_t *p = (uint8_t *)pp;
p[0] = u & 0xff;
p[1] = (u >> 8) & 0xff;
}
static inline void
le32enc(void *pp, uint32_t u) {
uint8_t *p = (uint8_t *)pp;
p[0] = u & 0xff;
p[1] = (u >> 8) & 0xff;
p[2] = (u >> 16) & 0xff;
p[3] = (u >> 24) & 0xff;
}
static inline void
le64enc(void *pp, uint64_t u) {
uint8_t *p = (uint8_t *)pp;
le32enc(p, (uint32_t)(u & 0xffffffffU));
le32enc(p + 4, (uint32_t)(u >> 32));
}
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from collections.abc import Iterable
from enum import IntFlag
from functools import partial
from typing import NamedTuple
from .fast_data_types import current_focused_os_window_id, get_options, pt_to_px, set_borders_rects
from .typing_compat import LayoutType
from .utils import color_as_int
from .window_list import WindowGroup, WindowList
class BorderColor(IntFlag):
# These are indices into the array of colors in the border vertex shader
default_bg, active, inactive, window_bg, bell, tab_bar_bg, tab_bar_margin_color, tab_bar_left_edge_color, tab_bar_right_edge_color = range(9)
class Border(NamedTuple):
left: int
top: int
right: int
bottom: int
color: BorderColor
border_type: int = 0
horizontal: bool = False
render: bool = True
radius: int = 0
thickness: int = 0
def vertical_edge(rects: list[Border], color: BorderColor, width: int, top: int, bottom: int, left: int, border_type: int, render: bool = True) -> None:
if width > 0:
rects.append(Border(left, top, left + width, bottom, color, border_type, False, render))
def horizontal_edge(rects: list[Border], color: BorderColor, height: int, left: int, right: int, top: int, border_type: int, render: bool = True) -> None:
if height > 0:
rects.append(Border(left, top, right, top + height, color, border_type, True, render))
def add_borders(rects: list[Border], color: BorderColor, wg: WindowGroup, radius: int = 0) -> None:
geometry = wg.geometry
if geometry is None:
return
# The compensatory padding (pixels left over after fitting whole cells) is
# inside the border so that the frames of neighboring windows line up
c = geometry.compensatory
pl, pt = wg.effective_padding('left') + c.left, wg.effective_padding('top') + c.top
pr, pb = wg.effective_padding('right') + c.right, wg.effective_padding('bottom') + c.bottom
left = geometry.left - pl
top = geometry.top - pt
lr = geometry.right
right = lr + pr
bt = geometry.bottom
bottom = bt + pb
h = partial(horizontal_edge, rects, color)
v = partial(vertical_edge, rects, color)
width = wg.effective_border()
bt = bottom
lr = right
left -= width
top -= width
right += width
bottom += width
pl = pr = pb = pt = width
wid = wg.active_window_id
render_edges = radius < 1
h(pt, left, right, top, -wid, render_edges)
h(pb, left, right, bt, wid, render_edges)
v(pl, top, bottom, left, -wid, render_edges)
v(pr, top, bottom, lr, wid, render_edges)
if radius > 0:
rects.append(Border(left, top, right, bottom, color, render=False, radius=radius, thickness=width))
class Borders:
def __init__(self, os_window_id: int, tab_id: int):
self.os_window_id = os_window_id
self.tab_id = tab_id
def __call__(
self,
all_windows: WindowList,
current_layout: LayoutType,
tab_bar_rects: Iterable[Border],
draw_window_borders: bool = True,
) -> None:
opts = get_options()
draw_active_borders = opts.active_border_color is not None
rects: list[Border] = []
for br in current_layout.blank_rects:
rects.append(Border(*br, BorderColor.default_bg))
rects.extend(tab_bar_rects)
bw = 0
groups = tuple(all_windows.iter_visible_groups())
if groups:
bw = groups[0].effective_border()
draw_borders = bw > 0 and draw_window_borders
active_group = all_windows.active_group
# Count visible windows
num_visible_groups = len(groups)
# When draw_window_borders_for_single_window is set and there's only 1 window,
# behave like draw_minimal_borders is False (draw full borders around the window)
if opts.draw_window_borders_for_single_window and num_visible_groups == 1:
draw_minimal_borders = False
else:
draw_minimal_borders = opts.draw_minimal_borders and max(opts.window_margin_width) < 1
# For single window with the option enabled, check OS window focus state
# When unfocused, the border should appear inactive
os_window_focused = True
if opts.draw_window_borders_for_single_window and num_visible_groups == 1:
os_window_focused = current_focused_os_window_id() == self.os_window_id
radius_val, radius_unit = opts.window_border_radius
radius = pt_to_px(radius_val, self.os_window_id) if radius_unit == 'pt' else round(radius_val)
if draw_borders and not draw_minimal_borders:
for i, wg in enumerate(groups):
window_bg = color_as_int(wg.default_bg)
window_bg = (window_bg << 8) | BorderColor.window_bg
# Draw the border rectangles
if wg is active_group and draw_active_borders and os_window_focused:
color = BorderColor.active
else:
color = BorderColor.bell if wg.needs_attention else BorderColor.inactive
add_borders(rects, color, wg, radius)
if draw_minimal_borders:
for border_line in current_layout.get_minimal_borders(all_windows):
rects.append(Border(*border_line.edges, border_line.color, border_line.window_id, border_line.horizontal))
set_borders_rects(self.os_window_id, self.tab_id, rects)
+4298
View File
File diff suppressed because it is too large. Load diff
+3046
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
/*
* char-props.c
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "char-props.h"
#include "char-props-data.h"
static char_type
ensure_char_in_range(const char_type value) {
// Branchless: if (value > MAX_UNICODE) value = 0
const int64_t diff = ((int64_t)value) - ((int64_t)(MAX_UNICODE + 1u));
// The right shift gives all ones for negative diff and all zeros for positive diff
const char_type mask = diff >> 63;
return value & mask;
}
CharProps
char_props_for(char_type ch) {
ch = ensure_char_in_range(ch);
return CharProps_t3[CharProps_t2[(CharProps_t1[ch >> CharProps_shift] << CharProps_shift) + (ch & CharProps_mask)]];
}
void
grapheme_segmentation_reset(GraphemeSegmentationResult *s) {
s->val = 0;
}
GraphemeSegmentationResult
grapheme_segmentation_step(GraphemeSegmentationResult r, CharProps ch) {
unsigned key = GraphemeSegmentationKey(r, ch);
unsigned t1 = ((unsigned)GraphemeSegmentationResult_t1[key >> GraphemeSegmentationResult_shift]) << GraphemeSegmentationResult_shift;
GraphemeSegmentationResult ans = GraphemeSegmentationResult_t2[t1 + (key & GraphemeSegmentationResult_mask)];
// printf("state: %u gsp: %u -> key: %u t1: %u -> add_to_cell: %u\n", r.state, ch.grapheme_segmentation_property, key, t1, ans.add_to_current_cell);
return ans;
}
+212
View File
@@ -0,0 +1,212 @@
/*
* char-props.h
* Copyright (C) 2025 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
// CharPropsDeclaration: uses 23 bits {{{
typedef union CharProps {
struct __attribute__((packed)) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t is_extended_pictographic : 1;
uint8_t indic_conjunct_break : 2;
uint8_t grapheme_break : 4;
uint8_t is_punctuation : 1;
uint8_t is_word_char : 1;
uint8_t is_combining_char : 1;
uint8_t is_symbol : 1;
uint8_t is_non_rendered : 1;
uint8_t is_invalid : 1;
uint8_t is_emoji_presentation_base : 1;
uint8_t category : 5;
uint8_t is_emoji : 1;
uint8_t shifted_width : 3;
uint16_t : 9;
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint16_t : 9;
uint8_t shifted_width : 3;
uint8_t is_emoji : 1;
uint8_t category : 5;
uint8_t is_emoji_presentation_base : 1;
uint8_t is_invalid : 1;
uint8_t is_non_rendered : 1;
uint8_t is_symbol : 1;
uint8_t is_combining_char : 1;
uint8_t is_word_char : 1;
uint8_t is_punctuation : 1;
uint8_t grapheme_break : 4;
uint8_t indic_conjunct_break : 2;
uint8_t is_extended_pictographic : 1;
#else
#error "Unsupported endianness"
#endif
};
struct __attribute__((packed)) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t grapheme_segmentation_property : 7;
uint32_t : 25;
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint32_t : 25;
uint8_t grapheme_segmentation_property : 7;
#else
#error "Unsupported endianness"
#endif
};
uint32_t val;
} CharProps;
static_assert(sizeof(CharProps) == sizeof(uint32_t), "Fix the ordering of CharProps");
// EndCharPropsDeclaration }}}
// GraphemeSegmentationResultDeclaration: uses 10 bits {{{
typedef union GraphemeSegmentationResult {
struct __attribute__((packed)) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t emoji_modifier_sequence_before_last_char : 1;
uint8_t emoji_modifier_sequence : 1;
uint8_t incb_consonant_extended_linker_extended : 1;
uint8_t incb_consonant_extended_linker : 1;
uint8_t incb_consonant_extended : 1;
uint8_t grapheme_break : 4;
uint8_t add_to_current_cell : 1;
uint8_t : 6;
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t : 6;
uint8_t add_to_current_cell : 1;
uint8_t grapheme_break : 4;
uint8_t incb_consonant_extended : 1;
uint8_t incb_consonant_extended_linker : 1;
uint8_t incb_consonant_extended_linker_extended : 1;
uint8_t emoji_modifier_sequence : 1;
uint8_t emoji_modifier_sequence_before_last_char : 1;
#else
#error "Unsupported endianness"
#endif
};
struct __attribute__((packed)) {
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint16_t state : 9;
uint8_t : 7;
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t : 7;
uint16_t state : 9;
#else
#error "Unsupported endianness"
#endif
};
uint16_t val;
} GraphemeSegmentationResult;
static_assert(sizeof(GraphemeSegmentationResult) == sizeof(uint16_t), "Fix the ordering of GraphemeSegmentationResult");
// EndGraphemeSegmentationResultDeclaration }}}
// UCBDeclaration {{{
#define MAX_UNICODE (1114111u)
typedef enum GraphemeBreakProperty {
GBP_AtStart,
GBP_None,
GBP_Prepend,
GBP_CR,
GBP_LF,
GBP_Control,
GBP_Extend,
GBP_Regional_Indicator,
GBP_SpacingMark,
GBP_L,
GBP_V,
GBP_T,
GBP_LV,
GBP_LVT,
GBP_ZWJ,
GBP_Private_Expecting_RI,
} GraphemeBreakProperty;
typedef enum UnicodeCategory {
UC_Cn,
UC_Cc,
UC_Zs,
UC_Po,
UC_Sc,
UC_Ps,
UC_Pe,
UC_Sm,
UC_Pd,
UC_Nd,
UC_Lu,
UC_Sk,
UC_Pc,
UC_Ll,
UC_So,
UC_Lo,
UC_Pi,
UC_Cf,
UC_No,
UC_Pf,
UC_Lt,
UC_Lm,
UC_Mn,
UC_Me,
UC_Mc,
UC_Nl,
UC_Zl,
UC_Zp,
UC_Cs,
UC_Co,
} UnicodeCategory;
// EndUCBDeclaration }}}
CharProps char_props_for(char_type ch);
void grapheme_segmentation_reset(GraphemeSegmentationResult *s);
GraphemeSegmentationResult grapheme_segmentation_step(GraphemeSegmentationResult r, CharProps ch);
static inline int
wcwidth_std(CharProps ch) {
return (int)ch.shifted_width - 4 /*=width_shift*/;
}
static inline bool
is_private_use(CharProps ch) {
return ch.category == UC_Co;
}
static inline const char *
char_category(CharProps cp) {
#define a(x) \
case UC_##x: return #x
switch ((UnicodeCategory)cp.category) {
a(Cn);
a(Cc);
a(Zs);
a(Po);
a(Sc);
a(Ps);
a(Pe);
a(Sm);
a(Pd);
a(Nd);
a(Lu);
a(Sk);
a(Pc);
a(Ll);
a(So);
a(Lo);
a(Pi);
a(Cf);
a(No);
a(Pf);
a(Lt);
a(Lm);
a(Mn);
a(Me);
a(Mc);
a(Nl);
a(Zl);
a(Zp);
a(Cs);
a(Co);
}
return "Cn";
#undef a
}
+254
View File
@@ -0,0 +1,254 @@
/*
* consolemap.c
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
// Taken from consolemap.c in the linux vt driver sourcecode
#include "data-types.h"
#ifndef NO_SINGLE_BYTE_CHARSETS
static uint32_t charset_translations[4][256] = {
/* VT100 graphics mapped to Unicode */
{
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x2192, 0x2190, 0x2191, 0x2193, 0x002f,
0x2588, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x00a0,
0x25c6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1,
0x2591, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba,
0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c,
0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af,
0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7,
0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf,
0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7,
0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf,
0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7,
0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df,
0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7,
0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef,
0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7,
0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff
},
/* IBM Codepage 437 mapped to Unicode */
{
0x0000, 0x263a, 0x263b, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022,
0x25d8, 0x25cb, 0x25d9, 0x2642, 0x2640, 0x266a, 0x266b, 0x263c,
0x25b6, 0x25c0, 0x2195, 0x203c, 0x00b6, 0x00a7, 0x25ac, 0x21a8,
0x2191, 0x2193, 0x2192, 0x2190, 0x221f, 0x2194, 0x25b2, 0x25bc,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x2302,
0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7,
0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5,
0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9,
0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, 0x20a7, 0x0192,
0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba,
0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb,
0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510,
0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567,
0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580,
0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4,
0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229,
0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248,
0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0
},
// VAX 42 map
{
0x0000, 0x263a, 0x263b, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022,
0x25d8, 0x25cb, 0x25d9, 0x2642, 0x2640, 0x266a, 0x266b, 0x263c,
0x25b6, 0x25c0, 0x2195, 0x203c, 0x00b6, 0x00a7, 0x25ac, 0x21a8,
0x2191, 0x2193, 0x2192, 0x2190, 0x221f, 0x2194, 0x25b2, 0x25bc,
0x0020, 0x043b, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x0435,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0441, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0435, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x043a,
0x0070, 0x0071, 0x0442, 0x0073, 0x043b, 0x0435, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x2302,
0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7,
0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5,
0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9,
0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, 0x20a7, 0x0192,
0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba,
0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb,
0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510,
0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f,
0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567,
0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b,
0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580,
0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4,
0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229,
0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248,
0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0
},
/* UK mapping, same as 8-bit Latin1 except the pound sign replaces # */
{
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x00a3, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af,
0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7,
0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf,
0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7,
0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf,
0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7,
0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df,
0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7,
0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef,
0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7,
0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff
},
};
uint32_t*
translation_table(uint32_t which) {
switch(which){
default:
return NULL;
case '0':
return charset_translations[0];
case 'U':
return charset_translations[1];
case 'V':
return charset_translations[2];
case 'A':
return charset_translations[3];
}
}
#endif
// UTF-8 decode taken from: https://bjoern.hoehrmann.de/utf-8/decoder/dfa/
static const uint8_t utf8_data[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
};
#ifndef CHARSETS_STORAGE
#define CHARSETS_STORAGE
#endif
CHARSETS_STORAGE uint32_t
decode_utf8(UTF8State* state, uint32_t* codep, uint8_t byte) {
uint32_t type = utf8_data[byte];
*codep = (*state != UTF8_ACCEPT) ?
(byte & 0x3fu) | (*codep << 6) :
(0xff >> type) & (byte);
*state = utf8_data[256 + *state*16 + type];
return *state;
}
CHARSETS_STORAGE size_t
decode_utf8_string(const char *src, size_t sz, uint32_t *dest) {
// dest must be a zeroed array of size at least sz
uint32_t codep = 0;
UTF8State state = 0, prev = UTF8_ACCEPT;
size_t i, d;
for (i = 0, d = 0; i < sz; i++) {
switch(decode_utf8(&state, &codep, src[i])) {
case UTF8_ACCEPT:
dest[d++] = codep;
break;
case UTF8_REJECT:
state = UTF8_ACCEPT;
if (prev != UTF8_ACCEPT && i > 0) i--;
break;
}
prev = state;
}
return d;
}
CHARSETS_STORAGE unsigned int
encode_utf8(uint32_t ch, char* dest) {
if (ch < 0x80) { // only lower 7 bits can be 1
dest[0] = (char)ch; // 0xxxxxxx
return 1;
}
if (ch < 0x800) { // only lower 11 bits can be 1
dest[0] = (ch>>6) | 0xC0; // 110xxxxx
dest[1] = (ch & 0x3F) | 0x80; // 10xxxxxx
return 2;
}
if (ch < 0x10000) { // only lower 16 bits can be 1
dest[0] = (ch>>12) | 0xE0; // 1110xxxx
dest[1] = ((ch>>6) & 0x3F) | 0x80; // 10xxxxxx
dest[2] = (ch & 0x3F) | 0x80; // 10xxxxxx
return 3;
}
if (ch < 0x110000) { // only lower 21 bits can be 1
dest[0] = (ch>>18) | 0xF0; // 11110xxx
dest[1] = ((ch>>12) & 0x3F) | 0x80; // 10xxxxxx
dest[2] = ((ch>>6) & 0x3F) | 0x80; // 10xxxxxx
dest[3] = (ch & 0x3F) | 0x80; // 10xxxxxx
return 4;
}
return 0;
}
+15
View File
@@ -0,0 +1,15 @@
/*
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
uint32_t decode_utf8(uint32_t *, uint32_t *, uint8_t byte);
size_t decode_utf8_string(const char *src, size_t sz, uint32_t *dest);
unsigned int encode_utf8(uint32_t ch, char *dest);
uint32_t *translation_table(uint32_t which);
File diff suppressed because it is too large. Load diff
+293
View File
@@ -0,0 +1,293 @@
/*
* child.c
* Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#include "safe-wrappers.h"
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>
#define EXTRA_ENV_BUFFER_SIZE 64
static char **
serialize_string_tuple(PyObject *src, Py_ssize_t extra) {
const Py_ssize_t sz = PyTuple_GET_SIZE(src);
size_t required_size = sizeof(char *) * (1 + sz + extra);
required_size += extra * EXTRA_ENV_BUFFER_SIZE;
void *block = calloc(required_size, 1);
if (!block) {
PyErr_NoMemory();
return NULL;
}
char **ans = block;
for (Py_ssize_t i = 0; i < sz; i++) {
PyObject *x = PyTuple_GET_ITEM(src, i);
if (!PyUnicode_Check(x)) {
free(block);
PyErr_SetString(PyExc_TypeError, "string tuple must have only strings");
return NULL;
}
ans[i] = (char *)PyUnicode_AsUTF8(x);
if (!ans[i]) {
free(block);
return NULL;
}
}
return ans;
}
static void
write_to_stderr(const char *text) {
size_t sz = strlen(text);
size_t written = 0;
while (written < sz) {
ssize_t amt = write(2, text + written, sz - written);
if (amt == 0) break;
if (amt < 0) {
if (errno == EAGAIN || errno == EINTR) continue;
break;
}
written += amt;
}
}
#define exit_on_err(m) \
{ \
write_to_stderr(m); \
write_to_stderr(": "); \
write_to_stderr(strerror(errno)); \
exit(EXIT_FAILURE); \
}
static void
wait_for_terminal_ready(int fd) {
char data;
while (1) {
int ret = read(fd, &data, 1);
if (ret == -1 && (errno == EINTR || errno == EAGAIN)) continue;
break;
}
}
static PyObject *
spawn(PyObject *self UNUSED, PyObject *args) {
PyObject *argv_p, *env_p, *handled_signals_p, *pass_fds;
int master, slave, stdin_read_fd, stdin_write_fd, ready_read_fd, ready_write_fd, forward_stdio;
const char *kitten_exe;
char *cwd, *exe;
if (!PyArg_ParseTuple(
args,
"ssO!O!iiiiiiO!spO!",
&exe,
&cwd,
&PyTuple_Type,
&argv_p,
&PyTuple_Type,
&env_p,
&master,
&slave,
&stdin_read_fd,
&stdin_write_fd,
&ready_read_fd,
&ready_write_fd,
&PyTuple_Type,
&handled_signals_p,
&kitten_exe,
&forward_stdio,
&PyTuple_Type,
&pass_fds))
return NULL;
char name[2048] = {0};
#ifdef __APPLE__
// ttyname_r() on macOS calls lstat() on every entry in /dev until it finds
// the pty, so a single stuck entry can hang it. ptsname_r() gets the name
// from the master with an ioctl() instead.
// See https://github.com/kovidgoyal/kitty/issues/10741
int ret = ptsname_r(master, name, sizeof(name) - 1);
#else
int ret = ttyname_r(slave, name, sizeof(name) - 1);
#endif
if (ret != 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
#ifdef __APPLE__
// The name came from master, ensure it refers to the same pty as slave
struct stat slave_st, name_st;
if (fstat(slave, &slave_st) != 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (stat(name, &name_st) != 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
return NULL;
}
if (slave_st.st_rdev != name_st.st_rdev) {
PyErr_Format(PyExc_ValueError, "The slave fd %d is not the pty of the master fd %d (%s)", slave, master, name);
return NULL;
}
#endif
char **argv = serialize_string_tuple(argv_p, 0);
if (!argv) return NULL;
char **env = serialize_string_tuple(env_p, 1);
if (!env) {
free(argv);
return NULL;
}
int handled_signals[16] = {0}, num_handled_signals = MIN((int)arraysz(handled_signals), PyTuple_GET_SIZE(handled_signals_p));
for (Py_ssize_t i = 0; i < num_handled_signals; i++) handled_signals[i] = PyLong_AsLong(PyTuple_GET_ITEM(handled_signals_p, i));
#if PY_VERSION_HEX >= 0x03070000
PyOS_BeforeFork();
#endif
pid_t pid = fork();
switch (pid) {
case 0: {
// child
#if PY_VERSION_HEX >= 0x03070000
PyOS_AfterFork_Child();
#endif
const struct sigaction act = {.sa_handler = SIG_DFL};
#define SA(which) \
if (sigaction(which, &act, NULL) != 0) exit_on_err("sigaction() in child process failed");
for (int si = 0; si < num_handled_signals; si++) { SA(handled_signals[si]); }
// See _Py_RestoreSignals in signalmodule.c for a list of signals python nukes
#ifdef SIGPIPE
SA(SIGPIPE)
#endif
#ifdef SIGXFSZ
SA(SIGXFSZ);
#endif
#ifdef SIGXFZ
SA(SIGXFZ);
#endif
#undef SA
sigset_t signals;
sigemptyset(&signals);
if (sigprocmask(SIG_SETMASK, &signals, NULL) != 0) exit_on_err("sigprocmask() in child process failed");
// Use only signal-safe functions (man 7 signal-safety)
if (chdir(cwd) != 0) {
if (access(".", X_OK) != 0) { // existing cwd does not exist or dont have permissions for it
if (chdir("/") != 0) {} // ignore failure to chdir to /
}
};
if (setsid() == -1) exit_on_err("setsid() in child process failed");
// Establish the controlling terminal (see man 7 credentials)
int tfd = safe_open(name, O_RDWR | O_CLOEXEC, 0);
if (tfd == -1) exit_on_err("Failed to open controlling terminal");
// On BSD open() does not establish the controlling terminal
if (ioctl(tfd, TIOCSCTTY, 0) == -1) exit_on_err("Failed to set controlling terminal with TIOCSCTTY");
safe_close(tfd, __FILE__, __LINE__);
fd_set passed_fds;
FD_ZERO(&passed_fds);
bool has_preserved_fds = false;
if (forward_stdio) {
int fd = safe_dup(STDOUT_FILENO);
if (fd < 0) exit_on_err("dup() failed for forwarded STDOUT");
FD_SET(fd, &passed_fds);
size_t s = PyTuple_GET_SIZE(env_p);
env[s] = (char *)(env + (s + 2));
snprintf(env[s], EXTRA_ENV_BUFFER_SIZE, "KITTY_STDIO_FORWARDED=%d", fd);
fd = safe_dup(STDERR_FILENO);
if (fd < 0) exit_on_err("dup() failed for forwarded STDERR");
FD_SET(fd, &passed_fds);
has_preserved_fds = true;
}
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(pass_fds); i++) {
PyObject *pfd = PyTuple_GET_ITEM(pass_fds, i);
if (!PyLong_Check(pfd)) exit_on_err("pass_fds must contain only integers");
int fd = PyLong_AsLong(pfd);
if (fd > -1 && fd < FD_SETSIZE) {
FD_SET(fd, &passed_fds);
has_preserved_fds = true;
}
}
// Redirect stdin/stdout/stderr to the pty
if (safe_dup2(slave, STDOUT_FILENO) == -1) exit_on_err("dup2() failed for fd number 1");
if (safe_dup2(slave, STDERR_FILENO) == -1) exit_on_err("dup2() failed for fd number 2");
if (stdin_read_fd > -1) {
if (safe_dup2(stdin_read_fd, STDIN_FILENO) == -1) exit_on_err("dup2() failed for fd number 0");
safe_close(stdin_read_fd, __FILE__, __LINE__);
safe_close(stdin_write_fd, __FILE__, __LINE__);
} else {
if (safe_dup2(slave, STDIN_FILENO) == -1) exit_on_err("dup2() failed for fd number 0");
}
safe_close(slave, __FILE__, __LINE__);
safe_close(master, __FILE__, __LINE__);
// Wait for READY_SIGNAL which indicates kitty has setup the screen object
safe_close(ready_write_fd, __FILE__, __LINE__);
wait_for_terminal_ready(ready_read_fd);
safe_close(ready_read_fd, __FILE__, __LINE__);
// Close any extra fds inherited from parent
if (has_preserved_fds) {
for (int c = 3; c < 256; c++) {
if (!FD_ISSET(c, &passed_fds)) safe_close(c, __FILE__, __LINE__);
}
} else
for (int c = 3; c < 256; c++) { safe_close(c, __FILE__, __LINE__); }
extern char **environ;
environ = env;
execvp(exe, argv);
// Report the failure and exec kitten instead, so that we are not left
// with a forked but not exec'ed process
write_to_stderr("Failed to launch child: ");
write_to_stderr(exe);
write_to_stderr("\nWith error: ");
write_to_stderr(strerror(errno));
write_to_stderr("\n");
execlp(kitten_exe, "kitten", "__hold_till_enter__", NULL);
exit(EXIT_FAILURE);
break;
}
case -1: {
#if PY_VERSION_HEX >= 0x03070000
int saved_errno = errno;
PyOS_AfterFork_Parent();
errno = saved_errno;
#endif
PyErr_SetFromErrno(PyExc_OSError);
break;
}
default:
#if PY_VERSION_HEX >= 0x03070000
PyOS_AfterFork_Parent();
#endif
break;
}
#undef exit_on_err
free(argv);
free(env);
if (PyErr_Occurred()) return NULL;
return PyLong_FromLong(pid);
}
static PyMethodDef module_methods[] = {
METHODB(spawn, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_child(PyObject *module) {
PyModule_AddIntMacro(module, CLD_KILLED);
PyModule_AddIntMacro(module, CLD_STOPPED);
PyModule_AddIntMacro(module, CLD_EXITED);
PyModule_AddIntMacro(module, CLD_CONTINUED);
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
return true;
}
+829
View File
@@ -0,0 +1,829 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
import termios
from collections import defaultdict
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
from contextlib import contextmanager, suppress
from itertools import count
from time import monotonic
from typing import TYPE_CHECKING, Any, DefaultDict, NamedTuple, Optional, TypedDict
import kitty.fast_data_types as fast_data_types
from .constants import handled_signals, is_freebsd, is_macos, kitten_exe, kitty_base_dir, shell_path, terminfo_dir
from .types import run_once
from .utils import cmdline_for_hold, log_error, resolved_shell, which
if TYPE_CHECKING:
from .window import CwdRequest
if is_macos:
from kitty.fast_data_types import abspath_of_process as _abspath_of_process
from kitty.fast_data_types import cmdline_of_process as cmdline_
from kitty.fast_data_types import cwd_of_process as _cwd
from kitty.fast_data_types import environ_of_process as _environ_of_process
from kitty.fast_data_types import memory_of_process as _memory_of_process
from kitty.fast_data_types import ppid_of_process as _ppid_of_process
from kitty.fast_data_types import process_group_map as _process_group_map
def cwd_of_process(pid: int) -> str:
# The underlying code on macos returns a path with symlinks resolved
# anyway but we use realpath for extra safety.
return os.path.realpath(_cwd(pid), strict=True)
def abspath_of_exe(pid: int) -> str:
return os.path.realpath(_abspath_of_process(pid), strict=True)
def process_group_map() -> DefaultDict[int, list[int]]:
ans: DefaultDict[int, list[int]] = defaultdict(list)
for pid, pgid in _process_group_map():
ans[pgid].append(pid)
return ans
def cmdline_of_pid(pid: int) -> list[str]:
return cmdline_(pid)
def _get_descendants_of_macos(pid: int) -> set[int]:
children_map: DefaultDict[int, list[int]] = defaultdict(list)
for p in fast_data_types.get_all_processes():
with suppress(Exception):
children_map[_ppid_of_process(p)].append(p)
result: set[int] = set()
stack = list(children_map.get(pid, []))
while stack:
child = stack.pop()
if child not in result:
result.add(child)
stack.extend(children_map.get(child, []))
return result
def children_of_process(pid: int) -> list[int]:
ans = []
for p in fast_data_types.get_all_processes():
with suppress(Exception):
if _ppid_of_process(p) == pid:
ans.append(p)
return ans
def memory_used_by_process_tree_rooted_at(pid: int, check_if_cgroup_root: bool = False) -> int:
with suppress(Exception):
pids = _get_descendants_of_macos(pid)
total = _memory_of_process(pid) # raises if pid doesn't exist
for p in pids:
with suppress(Exception):
total += _memory_of_process(p)
return total
return -1
else:
def cmdline_of_pid(pid: int) -> list[str]:
with open(f'/proc/{pid}/cmdline', 'rb') as f:
return list(filter(None, f.read().decode('utf-8').split('\0')))
if is_freebsd:
def cwd_of_process(pid: int) -> str:
import subprocess
cp = subprocess.run(['pwdx', str(pid)], capture_output=True)
if cp.returncode != 0:
raise ValueError(f'Failed to find cwd of process with pid: {pid}')
ans = cp.stdout.decode('utf-8', 'replace').split()[1]
return os.path.realpath(ans, strict=True)
else:
def cwd_of_process(pid: int) -> str:
# We use realpath instead of readlink to match macOS behavior where
# the underlying OS API returns real paths.
ans = f'/proc/{pid}/cwd'
return os.path.realpath(ans, strict=True)
def _environ_of_process(pid: int) -> str:
with open(f'/proc/{pid}/environ', 'rb') as f:
return f.read().decode('utf-8')
def process_group_map() -> DefaultDict[int, list[int]]:
ans: DefaultDict[int, list[int]] = defaultdict(list)
for x in os.listdir('/proc'):
try:
pid = int(x)
except Exception:
continue
try:
with open(f'/proc/{x}/stat', 'rb') as f:
raw = f.read().decode('utf-8')
except OSError:
continue
try:
q = int(raw.split(' ', 5)[4])
except Exception:
continue
ans[q].append(pid)
return ans
def abspath_of_exe(pid: int) -> str:
return os.path.realpath(f'/proc/{pid}/exe', strict=True)
@run_once
def proc_children_supported() -> bool:
# Needs a kernel built with CONFIG_PROC_CHILDREN
pid = os.getpid()
return os.path.exists(f'/proc/{pid}/task/{pid}/children')
def _children_from_task_files(pid: int) -> list[int]:
# Each thread has its own list of children, and multi-threaded programs
# such as kitten can create children from any thread
ans: list[int] = []
for tid in os.listdir(f'/proc/{pid}/task'):
with suppress(FileNotFoundError): # thread exited
with open(f'/proc/{pid}/task/{tid}/children', 'rb') as f:
ans.extend(map(int, f.read().split()))
return ans
def _children_map() -> DefaultDict[int, list[int]]:
ans: DefaultDict[int, list[int]] = defaultdict(list)
try:
entries = os.listdir('/proc')
except OSError: # no procfs, for example on FreeBSD
return ans
for x in entries:
if not x.isdigit():
continue
with suppress(OSError, ValueError, IndexError):
with open(f'/proc/{x}/stat', 'rb') as f:
raw = f.read()
# The process name can contain spaces and parentheses
ans[int(raw[raw.rindex(b')') + 2 :].split()[1])].append(int(x))
return ans
def children_of_process(pid: int) -> list[int]:
if proc_children_supported():
try:
return _children_from_task_files(pid)
except FileNotFoundError: # process exited
return []
return _children_map().get(pid, [])
def _get_descendants_of(pid: int) -> set[int]:
result: set[int] = set()
# Without per thread children files, build the full map only once
get_children: Callable[[int], list[int]] = children_of_process if proc_children_supported() else _children_map().__getitem__
stack = [pid]
while stack:
for child in get_children(stack.pop()):
if child not in result:
result.add(child)
stack.append(child)
return result
def _memory_from_smaps_rollup(pid: int) -> int:
with open(f'/proc/{pid}/smaps_rollup') as f:
for line in f:
if line.startswith('Pss:'):
return int(line.split()[1]) * 1024
return 0
def memory_used_by_process_tree_rooted_at(pid: int, check_if_cgroup_root: bool = False) -> int:
with suppress(Exception):
with open(f'/proc/{pid}/cgroup') as f:
cgroup_line = f.readline().strip()
cgroup_path = cgroup_line.split(':')[2].lstrip('/')
cgroup_dir = os.path.join('/sys/fs/cgroup', cgroup_path)
use_cgroup = True
descendants: set[int] | None = None
if check_if_cgroup_root:
with suppress(OSError):
with open(os.path.join(cgroup_dir, 'cgroup.procs')) as f:
cgroup_pids = {int(x) for x in f.read().split() if x}
descendants = _get_descendants_of(pid)
descendants.add(pid)
use_cgroup = cgroup_pids <= descendants
if use_cgroup:
target_keys = {'anon', 'shmem', 'kernel', 'sock', 'zswap'}
mem_bytes = 0
with open(os.path.join(cgroup_dir, 'memory.stat')) as f:
for line in f:
parts = line.split()
if parts[0] in target_keys:
mem_bytes += int(parts[1])
return mem_bytes
# cgroup contains processes outside our tree; sum PSS per process
if descendants is None:
descendants = _get_descendants_of(pid)
descendants.add(pid)
mem_bytes = 0
for p in descendants:
with suppress(OSError):
mem_bytes += _memory_from_smaps_rollup(p)
return mem_bytes
return -1
@run_once
def checked_terminfo_dir() -> str | None:
return terminfo_dir if os.path.isdir(terminfo_dir) else None
class CachedProcessData:
cached_result: DefaultDict[int, list[int]] | None = None
cache_active: bool = False
cache_at: float = 0
ttl: float = 1
def process_group_map(self) -> DefaultDict[int, list[int]]:
if self.cached_result is None or not self.cache_active:
try:
self.cached_result = process_group_map()
except Exception:
self.cached_result = defaultdict(list)
self.cache_at = monotonic()
return self.cached_result
def processes_in_group(self, grp: int) -> list[int]:
return self.process_group_map()[grp]
def clear_cache(self) -> None:
self.cached_result = None
self.cache_at = 0
def start_caching(self, refresh: bool = False) -> bool:
prev, self.cache_active = self.cache_active, True
if refresh or monotonic() - self.cache_at > self.ttl:
self.clear_cache()
return prev
def stop_caching(self, prev: bool) -> None:
self.cache_active = prev
process_data_cache = CachedProcessData()
processes_in_group = process_data_cache.processes_in_group
@contextmanager
def cached_process_data() -> Generator[None, None, None]:
orig = process_data_cache.start_caching(refresh=True)
try:
yield
finally:
process_data_cache.stop_caching(orig)
def session_id(pids: Iterable[int]) -> int:
for pid in pids:
with suppress(OSError):
if (sid := os.getsid(pid)) > -1:
return sid
return -1
def parse_environ_block(data: str) -> dict[str, str]:
"""Parse a C environ block of environment variables into a dictionary."""
# The block is usually raw data from the target process. It might contain
# trailing garbage and lines that do not look like assignments.
ret: dict[str, str] = {}
pos = 0
while True:
next_pos = data.find('\0', pos)
# nul byte at the beginning or double nul byte means finish
if next_pos <= pos:
break
# there might not be an equals sign
equal_pos = data.find('=', pos, next_pos)
if equal_pos > pos:
key = data[pos:equal_pos]
value = data[equal_pos + 1 : next_pos]
ret[key] = value
pos = next_pos + 1
return ret
def environ_of_process(pid: int) -> dict[str, str]:
return parse_environ_block(_environ_of_process(pid))
def process_env(env: Mapping[str, str] | None = None) -> dict[str, str]:
ans = dict(os.environ if env is None else env)
ssl_env_var = getattr(sys, 'kitty_ssl_env_var', None)
if ssl_env_var is not None:
ans.pop(ssl_env_var, None)
ans.pop('XDG_ACTIVATION_TOKEN', None)
ans.pop('VTE_VERSION', None) # Used by the stupid VTE shell integration script that is installed system wide, sigh
ans.pop('KITTY_SI_RUN_COMMAND_AT_STARTUP', None)
return ans
def default_env() -> dict[str, str]:
ans: dict[str, str] | None = getattr(default_env, 'env', None)
if ans is None:
return process_env()
return ans
def set_default_env(val: dict[str, str] | None = None) -> None:
env = process_env().copy()
has_lctype = False
if val:
has_lctype = 'LC_CTYPE' in val
env.update(val)
setattr(default_env, 'env', env)
setattr(default_env, 'lc_ctype_set_by_user', has_lctype)
def set_LANG_in_default_env(val: str) -> None:
default_env().setdefault('LANG', val)
def openpty() -> tuple[int, int]:
master, slave = os.openpty() # Note that master and slave are in blocking mode
os.set_inheritable(slave, True)
os.set_inheritable(master, False)
fast_data_types.set_iutf8_fd(master, True)
return master, slave
@run_once
def getpid() -> str:
return str(os.getpid())
@run_once
def base64_terminfo_data() -> str:
return (b'b64:' + fast_data_types.base64_encode(fast_data_types.terminfo_data(), True)).decode('ascii')
class ProcessDesc(TypedDict):
cwd: str | None
pid: int
cmdline: Sequence[str] | None
class KittyWrapper(NamedTuple):
# The argv the wrapper process was started with
argv: tuple[str, ...]
# True if the wrapper eventually replaces itself (via exec) with
# something else, at which point it is no longer a wrapper
replaces_itself: bool
child_counter = count()
class Child:
child_fd: int | None = None
pid: int | None = None
initial_termios_state: list[Any] | None = None
forked = False
# Wrapper processes kitty itself inserted around the command, outermost first
kitty_wrappers: tuple[KittyWrapper, ...] = ()
resolved_root_pid: int | None = None
def __init__(
self,
argv: Sequence[str],
cwd: str,
stdin: bytes | None = None,
env: dict[str, str] | None = None,
cwd_from: Optional['CwdRequest'] = None,
is_clone_launch: str = '',
add_listen_on_env_var: bool = True,
hold: bool = False,
pass_fds: tuple[int, ...] = (),
remote_control_fd: int = -1,
hold_after_ssh: bool = False,
startup_command_via_shell_integration: Sequence[str] | str = (),
):
self.is_clone_launch = is_clone_launch
self.id = next(child_counter)
# Used to cache the root pid, see root_pid
self.wrapper_children: dict[int, int] = {}
self.wrappers_seen: set[int] = set()
self.add_listen_on_env_var = add_listen_on_env_var
self.argv = list(argv)
self.pass_fds = pass_fds
self.remote_control_fd = remote_control_fd
if cwd_from:
try:
cwd = cwd_from.modify_argv_for_launch_with_cwd(self.argv, env, hold_after_ssh=hold_after_ssh) or cwd
except Exception as err:
log_error(f'Failed to read cwd of {cwd_from} with error: {err}')
else:
cwd = os.path.expandvars(os.path.expanduser(cwd or os.getcwd()))
self.cwd = os.path.abspath(cwd)
self.stdin = stdin
self.env = env or {}
self.startup_command_via_shell_integration = startup_command_via_shell_integration
self.final_env: dict[str, str] = {}
self.is_default_shell = bool(self.argv and self.argv[0] == shell_path)
self.should_run_via_run_shell_kitten = is_macos and self.is_default_shell
self.hold = hold
def get_final_env(self) -> tuple[dict[str, str], bool]:
from kitty.options.utils import DELETE_ENV_VAR
env = default_env().copy()
opts = fast_data_types.get_options()
boss = fast_data_types.get_boss()
if (
is_macos
and env.get('LC_CTYPE') == 'UTF-8'
and not getattr(sys, 'kitty_run_data').get('lc_ctype_before_python')
and not getattr(default_env, 'lc_ctype_set_by_user', False)
):
del env['LC_CTYPE']
env.update(self.env)
env['TERM'] = opts.term
env['COLORTERM'] = 'truecolor'
env['KITTY_PID'] = getpid()
env['KITTY_PUBLIC_KEY'] = boss.encryption_public_key
if self.remote_control_fd > -1:
env['KITTY_LISTEN_ON'] = f'fd:{self.remote_control_fd}'
elif self.add_listen_on_env_var and boss.listening_on:
env['KITTY_LISTEN_ON'] = boss.listening_on
else:
env.pop('KITTY_LISTEN_ON', None)
env.pop('KITTY_STDIO_FORWARDED', None)
if self.cwd:
# needed in case cwd is a symlink, in which case shells
# can use it to display the current directory name rather
# than the resolved path
env['PWD'] = self.cwd
if opts.terminfo_type == 'path':
tdir = checked_terminfo_dir()
if tdir:
env['TERMINFO'] = tdir
elif opts.terminfo_type == 'direct':
env['TERMINFO'] = base64_terminfo_data()
env['KITTY_INSTALLATION_DIR'] = kitty_base_dir
self.unmodified_argv = list(self.argv)
if not self.should_run_via_run_shell_kitten and 'disabled' not in opts.shell_integration:
from .shell_integration import modify_shell_environ
modify_shell_environ(opts, env, self.argv)
env = {k: v for k, v in env.items() if v is not DELETE_ENV_VAR}
if self.is_clone_launch:
env['KITTY_IS_CLONE_LAUNCH'] = self.is_clone_launch
self.is_clone_launch = '1' # free memory
else:
env.pop('KITTY_IS_CLONE_LAUNCH', None)
must_run_startup_command_via_kitten = False
if self.startup_command_via_shell_integration:
if isinstance(self.startup_command_via_shell_integration, str):
env['KITTY_SI_RUN_COMMAND_AT_STARTUP'] = self.startup_command_via_shell_integration
else:
from .shell_integration import join
scmd = self.argv or resolved_shell(fast_data_types.get_options())
try:
env['KITTY_SI_RUN_COMMAND_AT_STARTUP'] = join(scmd[0], self.startup_command_via_shell_integration)
except Exception:
must_run_startup_command_via_kitten = True # unknown shell
return env, must_run_startup_command_via_kitten
def fork(self) -> int | None:
if self.forked:
return None
opts = fast_data_types.get_options()
self.forked = True
master, slave = openpty()
stdin, self.stdin = self.stdin, None
ready_read_fd, ready_write_fd = os.pipe()
os.set_inheritable(ready_write_fd, False)
os.set_inheritable(ready_read_fd, True)
if stdin is not None:
stdin_read_fd, stdin_write_fd = os.pipe()
os.set_inheritable(stdin_write_fd, False)
os.set_inheritable(stdin_read_fd, True)
else:
stdin_read_fd = stdin_write_fd = -1
self.final_env, must_run_startup_command_via_kitten = self.get_final_env()
self.initial_termios_state = termios.tcgetattr(master)
argv = list(self.argv)
kitty_wrappers: list[KittyWrapper] = []
cwd = self.cwd
pass_fds = self.pass_fds
if self.remote_control_fd > -1:
pass_fds += (self.remote_control_fd,)
if self.should_run_via_run_shell_kitten or must_run_startup_command_via_kitten:
# bash will only source ~/.bash_profile if it detects it is a login
# shell (see the invocation section of the bash man page), which it
# does if argv[0] is prefixed by a hyphen see
# https://github.com/kovidgoyal/kitty/issues/247
# it is apparently common to use ~/.bash_profile instead of the
# more correct ~/.bashrc on macOS to setup env vars, so if
# the default shell is used prefix argv[0] by '-'
#
# it is arguable whether graphical terminals should start shells
# in login mode in general, there are at least a few Linux users
# that also make this incorrect assumption, see for example
# https://github.com/kovidgoyal/kitty/issues/1870
# xterm, urxvt, konsole and gnome-terminal do not do it in my
# testing.
import shlex
ksi = ' '.join(opts.shell_integration)
if ksi == 'invalid':
ksi = 'enabled'
argv = [kitten_exe(), 'run-shell', '--shell', shlex.join(argv), '--shell-integration', ksi]
if must_run_startup_command_via_kitten:
argv.extend(self.startup_command_via_shell_integration)
if is_macos and not pass_fds and not opts.forward_stdio:
# In addition for getlogin() to work we need to run the shell
# via the /usr/bin/login wrapper, sigh.
# And login on macOS looks for .hushlogin in CWD instead of
# HOME, bloody idiotic so we cant cwd when running it.
# https://github.com/kovidgoyal/kitty/issues/6511
# login closes inherited file descriptors so dont use it when
# forward_stdio or pass_fds are used.
import pwd
user = pwd.getpwuid(os.geteuid()).pw_name
if cwd:
argv.append('--cwd=' + cwd)
cwd = os.path.expanduser('~')
login_argv = ['/usr/bin/login', '-f', '-l', '-p', user]
argv = login_argv + argv
kitty_wrappers.insert(0, KittyWrapper(tuple(login_argv), False))
self.final_exe = final_exe = which(argv[0]) or argv[0]
self.final_argv0 = argv[0]
if self.hold:
hold_argv = cmdline_for_hold()
argv = hold_argv + argv
final_exe = argv[0]
# run-shell runs the command as a child and then execs the shell
kitty_wrappers.insert(0, KittyWrapper(tuple(hold_argv), True))
self.kitty_wrappers = tuple(kitty_wrappers)
env = tuple(f'{k}={v}' for k, v in self.final_env.items())
pid = fast_data_types.spawn(
final_exe,
cwd,
tuple(argv),
env,
master,
slave,
stdin_read_fd,
stdin_write_fd,
ready_read_fd,
ready_write_fd,
tuple(handled_signals),
kitten_exe(),
opts.forward_stdio,
pass_fds,
)
os.close(slave)
self.pid = pid
self.child_fd = master
if stdin is not None:
os.close(stdin_read_fd)
fast_data_types.thread_write(stdin_write_fd, stdin)
os.close(ready_read_fd)
self.terminal_ready_fd = ready_write_fd
if self.child_fd is not None:
os.set_blocking(self.child_fd, False)
if not is_macos:
ppid = getpid()
try:
fast_data_types.systemd_move_pid_into_new_scope(pid, f'kitty-{ppid}-{self.id}.scope', f'kitty child process: {pid} launched by: {ppid}')
except NotImplementedError:
pass
except OSError as err:
log_error('Could not move child process into a systemd scope: ' + str(err))
return pid
def __del__(self) -> None:
fd = getattr(self, 'terminal_ready_fd', -1)
if fd > -1:
os.close(fd)
self.terminal_ready_fd = -1
def mark_terminal_ready(self) -> None:
os.close(self.terminal_ready_fd)
self.terminal_ready_fd = -1
def cmdline_of_pid(self, pid: int) -> list[str]:
try:
ans = cmdline_of_pid(pid)
except Exception:
ans = []
if not ans and pid in (self.pid, self.root_pid):
ans = list(self.argv)
return ans
def process_desc(self, pid: int) -> ProcessDesc:
ans: ProcessDesc = {'pid': pid, 'cmdline': None, 'cwd': None}
with suppress(Exception):
ans['cmdline'] = self.cmdline_of_pid(pid)
with suppress(Exception):
ans['cwd'] = cwd_of_process(pid) or None
return ans
@property
def foreground_processes(self) -> list[ProcessDesc]:
if self.child_fd is None:
return []
try:
pgrp = os.tcgetpgrp(self.child_fd)
foreground_processes = processes_in_group(pgrp) if pgrp >= 0 else []
return [self.process_desc(x) for x in foreground_processes]
except Exception:
return []
@property
def background_processes(self) -> list[ProcessDesc]:
if self.child_fd is None:
return []
try:
foreground_process_group_id = os.tcgetpgrp(self.child_fd)
if foreground_process_group_id < 0:
return []
gmap = process_group_map()
sid = session_id(gmap.get(foreground_process_group_id, ()))
if sid < 0:
return []
ans: list[ProcessDesc] = []
for grp_id, pids in gmap.items():
if grp_id != foreground_process_group_id and session_id(pids) == sid:
ans.extend(map(self.process_desc, pids))
return ans
except Exception:
return []
@property
def cmdline(self) -> list[str]:
try:
pid = self.root_pid
assert pid is not None
return self.cmdline_of_pid(pid) or list(self.argv)
except Exception:
return list(self.argv)
@property
def foreground_cmdline(self) -> list[str]:
try:
assert self.pid_for_cwd is not None
return self.cmdline_of_pid(self.pid_for_cwd) or self.cmdline
except Exception:
return self.cmdline
@property
def environ(self) -> dict[str, str]:
try:
pid = self.root_pid
assert pid is not None
return environ_of_process(pid) or self.final_env.copy()
except Exception:
return self.final_env.copy()
@property
def current_cwd(self) -> str | None:
with suppress(Exception):
pid = self.root_pid
assert pid is not None
return cwd_of_process(pid)
return None
@property
def root_pid(self) -> int | None:
"""
The pid of the process originally started when the window was created,
skipping over any wrapper processes kitty itself inserted, such as
/usr/bin/login on macOS. A wrapper is replaced by its first child.
"""
if self.resolved_root_pid is not None:
return self.resolved_root_pid
pid = self.pid
if pid is None or not self.kitty_wrappers:
return pid
# Whether the result can never change and so can be cached
final = True
for i, w in enumerate(self.kitty_wrappers):
if w.replaces_itself:
try:
cmdline = tuple(cmdline_of_pid(pid))
except Exception:
final = False
break
if cmdline[: len(w.argv)] != w.argv:
# Either the wrapper has replaced itself, which is
# permanent, or it has not been exec-ed yet and the forked
# process is still running kitty code
final = final and i in self.wrappers_seen
break
self.wrappers_seen.add(i)
final = False # it will replace itself later
# A wrapper only ever runs a single child, so cache it
child = self.wrapper_children.get(pid)
if child is None:
try:
children = children_of_process(pid)
except Exception as err:
log_error(f'Failed to get children of process {pid} with error: {err}')
final = False
break
if not children:
final = False # the wrapper has not started its child yet
break
child = self.wrapper_children[pid] = min(children)
pid = child
if final:
self.resolved_root_pid = pid
self.wrapper_children.clear()
return pid
def get_pid_for_cwd(self, oldest: bool = False) -> int | None:
with suppress(Exception):
assert self.child_fd is not None
pgrp = os.tcgetpgrp(self.child_fd)
foreground_processes = processes_in_group(pgrp) if pgrp >= 0 else []
if foreground_processes:
# there is no easy way that I know of to know which process is the
# foreground process in this group from the users perspective,
# so we assume the one with the highest PID is as that is most
# likely to be the newest process. This situation can happen
# for example with a shell script such as:
# #!/bin/bash
# cd /tmp
# vim
# With this script , the foreground process group will contain
# both the bash instance running the script and vim.
return min(foreground_processes) if oldest else max(foreground_processes)
return self.root_pid
@property
def pid_for_cwd(self) -> int | None:
return self.get_pid_for_cwd()
def get_foreground_cwd(self, oldest: bool = False) -> str | None:
with suppress(Exception):
pid = self.get_pid_for_cwd(oldest)
if pid is not None:
return cwd_of_process(pid) or None
return None
def get_foreground_exe(self, oldest: bool = False) -> str | None:
with suppress(Exception):
pid = self.get_pid_for_cwd(oldest)
if pid is not None:
c = cmdline_of_pid(pid)
if c:
return c[0]
return None
@property
def foreground_cwd(self) -> str | None:
return self.get_foreground_cwd()
@property
def foreground_environ(self) -> dict[str, str]:
pid = self.pid_for_cwd
if pid is not None:
with suppress(Exception):
return environ_of_process(pid)
pid = self.root_pid
if pid is not None:
with suppress(Exception):
return environ_of_process(pid)
return {}
def send_signal_for_key(self, key_num: bytes) -> bool:
import signal
if self.child_fd is None:
return False
t = termios.tcgetattr(self.child_fd)
if not t[3] & termios.ISIG:
return False
cc = t[-1]
if key_num == cc[termios.VINTR]:
s: signal.Signals = signal.SIGINT
elif key_num == cc[termios.VSUSP]:
s = signal.SIGTSTP
elif key_num == cc[termios.VQUIT]:
s = signal.SIGQUIT
else:
return False
pgrp = os.tcgetpgrp(self.child_fd)
os.killpg(pgrp, s)
return True
def reset_termios_state(self, when: int = termios.TCSANOW) -> None:
if self.initial_termios_state is not None and self.child_fd is not None:
try:
termios.tcsetattr(self.child_fd, when, self.initial_termios_state)
except OSError:
pass
def get_memory_used_by_child(self) -> int:
if self.pid is None:
return -1
return memory_used_by_process_tree_rooted_at(self.pid, check_if_cgroup_root=False)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import re
from collections.abc import Generator
from typing import Any
from .cli_stub import HintsCLIOptions
from .typing_compat import MarkType
def mark(text: str, args: HintsCLIOptions, Mark: type[MarkType], extra_cli_args: list[str], *a: Any) -> Generator[MarkType, None, None]:
idx = 0
found_start_line = False
for m in re.finditer(r'(?m)^.+$', text):
start, end = m.span()
line = text[start:end].replace('\0', '').replace('\n', '')
if line == ' ':
found_start_line = True
continue
if line.startswith(': '):
yield Mark(idx, start, end, line, {'index': idx})
idx += 1
elif found_start_line:
# skip this line incrementing the index
idx += 1
+25
View File
@@ -0,0 +1,25 @@
/*
* cleanup.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "cleanup.h"
#include <unistd.h>
kitty_cleanup_at_exit_func exit_funcs[NUM_CLEANUP_FUNCS] = {0};
void
register_at_exit_cleanup_func(AtExitCleanupFunc which, kitty_cleanup_at_exit_func func) {
if (which < NUM_CLEANUP_FUNCS) exit_funcs[which] = func;
}
void
run_at_exit_cleanup_functions(void) {
for (unsigned i = 0; i < NUM_CLEANUP_FUNCS; i++) {
if (exit_funcs[i]) exit_funcs[i]();
exit_funcs[i] = NULL;
}
}
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
typedef void (*kitty_cleanup_at_exit_func)(void);
typedef enum {
STATE_CLEANUP_FUNC,
GLFW_CLEANUP_FUNC,
DESKTOP_CLEANUP_FUNC,
CORE_TEXT_CLEANUP_FUNC,
COCOA_CLEANUP_FUNC,
PNG_READER_CLEANUP_FUNC,
FONTCONFIG_CLEANUP_FUNC,
FREETYPE_CLEANUP_FUNC,
SYSTEMD_CLEANUP_FUNC,
SHADERS_CLEANUP_FUNC,
NUM_CLEANUP_FUNCS
} AtExitCleanupFunc;
void register_at_exit_cleanup_func(AtExitCleanupFunc which, kitty_cleanup_at_exit_func func);
void run_at_exit_cleanup_functions(void);
+749
View File
@@ -0,0 +1,749 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import sys
import types
from collections.abc import Callable, Iterator, Sequence
from re import Match
from typing import Any, NoReturn, TypeVar, cast
from .cli_stub import CLIOptions
from .conf.utils import resolve_config
from .constants import appname, clear_handled_signals, config_dir, default_pager_for_help, defconf, is_macos, str_version, website_url
from .fast_data_types import parse_cli_from_spec, wcswidth
from .options.types import Options as KittyOpts
from .simple_cli_definitions import (
CompletionType,
OptionDefinition,
OptionSpecSeq,
defval_for_opt,
get_option_maps,
kitty_options_spec,
parse_option_spec,
serialize_as_go_string,
)
from .types import run_once
from .typing_compat import BadLineType
is_macos
go_type_map = {
'bool-set': 'bool',
'bool-reset': 'bool',
'bool-unset': 'bool',
'int': 'int',
'float': 'float64',
'': 'string',
'list': '[]string',
'choices': 'string',
'str': 'string',
}
class GoOption:
def __init__(self, x: OptionDefinition) -> None:
flags = sorted(x.aliases, key=len)
short = ''
self.aliases = []
if len(flags) > 1 and not flags[0].startswith('--'):
short = flags[0][1:]
self.short, self.long = short, x.name.replace('_', '-')
for f in flags:
q = f[2:] if f.startswith('--') else f[1:]
self.aliases.append(q)
self.type = x.type
if x.choices:
self.type = 'choices'
self.default = x.default
self.obj_defn = x
self.go_type = go_type_map[self.type]
if x.dest:
self.go_var_name = ''.join(x.capitalize() for x in x.dest.replace('-', '_').split('_'))
else:
self.go_var_name = ''.join(x.capitalize() for x in self.long.replace('-', '_').split('_'))
self.help_text = serialize_as_go_string(self.obj_defn.help.strip())
def struct_declaration(self) -> str:
return f'{self.go_var_name} {self.go_type}'
@property
def flags(self) -> list[str]:
return sorted(self.obj_defn.aliases)
def as_option(self, cmd_name: str = 'cmd', depth: int = 0, group: str = '') -> str:
add = f'AddToGroup("{serialize_as_go_string(group)}", ' if group else 'Add('
aliases = ' '.join(self.flags)
ans = f'''{cmd_name}.{add}cli.OptionSpec{{
Name: "{serialize_as_go_string(aliases)}",
Type: "{self.type}",
Dest: "{serialize_as_go_string(self.go_var_name)}",
Help: "{self.help_text}",
'''
if self.type in ('choice', 'choices'):
c = ', '.join(self.sorted_choices)
cx = ', '.join(f'"{serialize_as_go_string(x)}"' for x in self.sorted_choices)
ans += f'\nChoices: "{serialize_as_go_string(c)}",\n'
ans += f'\nCompleter: cli.NamesCompleter("Choices for {self.long}", {cx}),'
elif self.obj_defn.completion.type is not CompletionType.none:
ans += ''.join(self.obj_defn.completion.as_go_code('Completer', ': ')) + ','
if depth > 0:
ans += f'\n\tDepth: {depth},\n'
if self.default:
ans += f'\n\tDefault: "{serialize_as_go_string(self.default)}",\n'
return ans + '})'
def as_string_for_commandline(self) -> Iterator[str]:
# }}}}}}}}}}}]]]]]]]]]]]]]]]]]
flag = self.flags[0]
val = f'opts.{self.go_var_name}'
if self.go_type == '[]string':
yield f'\tfor _, x := range {val} {{ ans = append(ans, `{flag}=` + x) }}'
return
match self.go_type:
case 'bool':
yield f'sval = fmt.Sprintf(`%#v`, {val})'
godef = '`true`' if self.type != 'bool-set' else '`false`'
case 'int':
yield f'sval = fmt.Sprintf(`%d`, {val})'
godef = f'`{self.default or "0"}`'
case 'string':
yield f'sval = {val}'
godef = f'''"{serialize_as_go_string(self.default or '')}"'''
case 'float64':
yield f'sval = fmt.Sprintf(`%f`, {val})'
godef = f'`{self.default or "0"}`'
case _:
raise ValueError(f'Unknown type: {self.go_type}')
yield f'\tif (sval != {godef}) {{ ans = append(ans, `{flag}=` + sval)}}'
@property
def sorted_choices(self) -> list[str]:
choices = sorted(self.obj_defn.choices)
choices.remove(self.default or '')
choices.insert(0, self.default or '')
return choices
def go_options_for_seq(seq: 'OptionSpecSeq') -> Iterator[GoOption]:
for x in seq:
if not isinstance(x, str):
yield GoOption(x)
def surround(x: str, start: int, end: int) -> str:
if sys.stdout.isatty():
x = f'\033[{start}m{x}\033[{end}m'
return x
role_map: dict[str, Callable[[str], str]] = {}
def role(func: Callable[[str], str]) -> Callable[[str], str]:
assert isinstance(func, types.FunctionType)
role_map[func.__name__] = func
return func
@role
def emph(x: str) -> str:
return surround(x, 91, 39)
@role
def cyan(x: str) -> str:
return surround(x, 96, 39)
@role
def green(x: str) -> str:
return surround(x, 32, 39)
@role
def blue(x: str) -> str:
return surround(x, 34, 39)
@role
def yellow(x: str) -> str:
return surround(x, 93, 39)
@role
def italic(x: str) -> str:
return surround(x, 3, 23)
@role
def bold(x: str) -> str:
return surround(x, 1, 22)
@role
def title(x: str) -> str:
return blue(bold(x))
@role
def opt(text: str) -> str:
return bold(text)
@role
def option(x: str) -> str:
idx = x.rfind('--')
if idx < 0:
idx = x.find('-')
if idx > -1:
x = x[idx:]
return bold(x.rstrip('>'))
@role
def code(x: str) -> str:
return cyan(x)
def text_and_target(x: str) -> tuple[str, str]:
parts = x.split('<', 1)
return parts[0].strip(), parts[-1].rstrip('>')
@role
def term(x: str) -> str:
return ref_hyperlink(x, 'term-')
@role
def kbd(x: str) -> str:
return x
@role
def env(x: str) -> str:
return ref_hyperlink(x, 'envvar-')
role_map['envvar'] = role_map['env']
@run_once
def hostname() -> str:
from .utils import get_hostname
return get_hostname(fallback='localhost')
def hyperlink_for_url(url: str, text: str) -> str:
if sys.stdout.isatty():
return f'\x1b]8;;{url}\x1b\\\x1b[4:3;58:5:4m{text}\x1b[4:0;59m\x1b]8;;\x1b\\'
return text
def hyperlink_for_path(path: str, text: str) -> str:
path = os.path.abspath(path).replace(os.sep, '/')
if os.path.isdir(path):
path += path.rstrip('/') + '/'
return hyperlink_for_url(f'file://{hostname()}{path}', text)
@role
def file(x: str) -> str:
if x == 'kitty.conf':
x = hyperlink_for_path(os.path.join(config_dir, x), x)
return italic(x)
@role
def doc(x: str) -> str:
t, q = text_and_target(x)
if t == q:
from .conf.types import ref_map
m = ref_map()['doc']
q = q.strip('/')
if q in m:
x = f'{m[q]} <{t}>'
return ref_hyperlink(x, 'doc-')
def ref_hyperlink(x: str, prefix: str = '') -> str:
t, q = text_and_target(x)
url = f'kitty+doc://{hostname()}/#ref={prefix}{q}'
t = re.sub(r':([a-z]+):`([^`]+)`', r'\2', t)
return hyperlink_for_url(url, t)
@role
def ref(x: str) -> str:
return ref_hyperlink(x)
@role
def ac(x: str) -> str:
return ref_hyperlink(x, 'action-')
@role
def iss(x: str) -> str:
return ref_hyperlink(x, 'issues-')
@role
def pull(x: str) -> str:
return ref_hyperlink(x, 'pull-')
@role
def disc(x: str) -> str:
return ref_hyperlink(x, 'discussions-')
def prettify(text: str) -> str:
def identity(x: str) -> str:
return x
def sub(m: 'Match[str]') -> str:
role, text = m.group(1, 2)
return role_map.get(role, identity)(text)
text = re.sub(r':([a-z]+):`([^`]+)`', sub, text)
return text
def prettify_rst(text: str) -> str:
return re.sub(r':([a-z]+):`([^`]+)`(=[^\s.]+)', r':\1:`\2`:code:`\3`', text)
def version(add_rev: bool = False) -> str:
rev = ''
from . import fast_data_types
suffix = fast_data_types.KITTY_VERSION_SUFFIX
# nightly builds already include the revision in the version suffix
if add_rev and not suffix:
if getattr(fast_data_types, 'KITTY_VCS_REV', ''):
rev = f' ({fast_data_types.KITTY_VCS_REV[:10]})'
return '{} {}{} created by {}'.format(italic(appname), green(str_version + suffix), rev, title('Kovid Goyal'))
def wrap(text: str, limit: int = 80) -> Iterator[str]:
if not text.strip():
yield ''
return
in_escape = 0
current_line: list[str] = []
escapes: list[str] = []
current_word: list[str] = []
current_line_length = 0
def print_word(ch: str = '') -> Iterator[str]:
nonlocal current_word, current_line, escapes, current_line_length
cw = ''.join(current_word)
w = wcswidth(cw)
if current_line_length + w > limit:
yield ''.join(current_line)
current_line = []
current_line_length = 0
cw = cw.strip()
current_word = [cw]
if escapes:
current_line.append(''.join(escapes))
escapes = []
if current_word:
current_line.append(cw)
current_line_length += w
current_word = []
if ch:
current_word.append(ch)
for i, ch in enumerate(text):
if in_escape > 0:
if in_escape == 1 and ch in '[]':
in_escape = 2 if ch == '[' else 3
if (in_escape == 2 and ch == 'm') or (in_escape == 3 and ch == '\\' and text[i - 1] == '\x1b'):
in_escape = 0
escapes.append(ch)
continue
if ch == '\x1b':
in_escape = 1
if current_word:
yield from print_word()
escapes.append(ch)
continue
if current_word and ch.isspace() and ch != '\xa0':
yield from print_word(ch)
else:
current_word.append(ch)
yield from print_word()
if current_line:
yield ''.join(current_line)
def get_defaults_from_seq(seq: OptionSpecSeq) -> dict[str, Any]:
ans: dict[str, Any] = {}
for opt in seq:
if not isinstance(opt, str):
ans[opt.dest] = defval_for_opt(opt)
return ans
default_msg = (
"""\
Run the :italic:`{appname}` terminal emulator. You can also specify the
:italic:`program` to run inside :italic:`{appname}` as normal arguments
following the :italic:`options`.
For example: {appname} --hold sh -c "echo hello, world"
For comprehensive documentation for kitty, please see: {url}"""
).format(appname=appname, url=website_url())
def help_defval_for_bool(otype: str) -> str:
if otype == 'bool-set':
return 'no'
return 'yes'
class PrintHelpForSeq:
allow_pager = True
def __call__(self, seq: OptionSpecSeq, usage: str | None, message: str | None, appname: str) -> None:
from kitty.utils import screen_size_function
screen_size = screen_size_function()
try:
linesz = min(screen_size().cols, 76)
except OSError:
linesz = 76
blocks: list[str] = []
a = blocks.append
def wa(text: str, indent: int = 0, leading_indent: int | None = None) -> None:
if leading_indent is None:
leading_indent = indent
j = '\n' + (' ' * indent)
lines: list[str] = []
for ln in text.splitlines():
lines.extend(wrap(ln, limit=linesz - indent))
a((' ' * leading_indent) + j.join(lines))
usage = '[program-to-run ...]' if usage is None else usage
optstring = '[options] ' if seq else ''
a('{}: {} {}{}'.format(title('Usage'), bold(yellow(appname)), optstring, usage))
a('')
message = message or default_msg
# replace rst literal code block syntax
message = message.replace('::\n\n', ':\n\n')
wa(prettify(message))
a('')
if seq:
a('{}:'.format(title('Options')))
for opt in seq:
if isinstance(opt, str):
a(f'{title(opt)}:')
continue
help_text = opt.help
if help_text == '!':
continue # hidden option
a(' ' + ', '.join(map(green, sorted(opt.aliases, reverse=True))))
defval = opt.default
if (otype := opt.type).startswith('bool-'):
blocks[-1] += italic(f'[={help_defval_for_bool(otype)}]')
else:
dt = f"""=[{italic(defval or '""')}]"""
blocks[-1] += dt
if opt.help:
t = help_text.replace('%default', str(defval)).strip()
# replace rst literal code block syntax
t = t.replace('::\n\n', ':\n\n')
t = t.replace('#placeholder_for_formatting#', '')
wa(prettify(t), indent=4)
if opt.choices:
wa('Choices: {}'.format(', '.join(opt.choices)), indent=4)
a('')
text = '\n'.join(blocks) + '\n\n' + version()
if print_help_for_seq.allow_pager and sys.stdout.isatty():
import subprocess
try:
p = subprocess.Popen(default_pager_for_help, stdin=subprocess.PIPE, preexec_fn=clear_handled_signals)
except FileNotFoundError:
print(text)
else:
try:
p.communicate(text.encode('utf-8'))
except KeyboardInterrupt:
raise SystemExit(1)
raise SystemExit(p.wait())
else:
print(text)
print_help_for_seq = PrintHelpForSeq()
def escape_rst(text: str) -> str:
text = text.replace('\\', '\\\\')
text = text.replace('*', '\\*')
text = text.replace('`', '\\`')
text = text.replace('_', '\\_')
text = text.replace('|', '\\|')
return text
def seq_as_rst(seq: OptionSpecSeq, usage: str | None, message: str | None, appname: str | None, heading_char: str = '-') -> str:
import textwrap
blocks: list[str] = []
a = blocks.append
usage = '[program-to-run ...]' if usage is None else usage
optstring = '[options] ' if seq else ''
a('.. highlight:: sh')
a('.. code-block:: sh')
a('')
a(f' {appname} {optstring}{usage}')
a('')
message = message or default_msg
a(prettify_rst(message))
a('')
if seq:
a('Options')
a(heading_char * 30)
for opt in seq:
if isinstance(opt, str):
a(opt)
a('~' * (len(opt) + 10))
continue
help_text = opt.help
if help_text == '!':
continue # hidden option
defn = '.. option:: '
if (otype := opt.type).startswith('bool-'):
val_name = f' [={help_defval_for_bool(otype)}]'
else:
val_name = f' <{opt.dest.upper()}>'
a(defn + ', '.join(o + val_name for o in sorted(opt.aliases)))
if opt.help:
defval = opt.default
t = help_text.replace('%default', ':code:`' + escape_rst(str(defval)) + '`').strip()
t = t.replace('#placeholder_for_formatting#', '')
a('')
a(textwrap.indent(prettify_rst(t), ' ' * 4))
if defval is not None:
a(textwrap.indent(f'Default: :code:`{escape_rst(str(defval))}`', ' ' * 4))
if opt.choices:
a(textwrap.indent('Choices: {}'.format(', '.join(f':code:`{escape_rst(c)}`' for c in sorted(opt.choices))), ' ' * 4))
a('')
text = '\n'.join(blocks)
return text
def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, extra_fields: Sequence[str] = ()) -> str:
from itertools import chain
ans: list[str] = [f'class {class_name}:']
for opt in chain(seq, disabled):
if isinstance(opt, str):
continue
name = opt.dest
otype = opt.type or 'str'
if otype in ('str', 'int', 'float'):
t = otype
if t == 'str' and defval_for_opt(opt) is None:
t = 'typing.Optional[str]'
elif otype == 'list':
t = 'typing.Sequence[str]'
elif otype in ('choice', 'choices'):
if opt.choices:
t = 'typing.Literal[{}]'.format(','.join(f'{x!r}' for x in opt.choices))
else:
t = 'str'
elif otype.startswith('bool-'):
t = 'bool'
else:
raise ValueError(f'Unknown CLI option type: {otype}')
ans.append(f' {name}: {t}')
for x in extra_fields:
ans.append(f' {x}')
return '\n'.join(ans) + '\n\n\n'
bool_map = {'y': True, 'yes': True, 'true': True, 'n': False, 'no': False, 'false': False}
def to_bool(alias: str, x: str) -> bool:
try:
return bool_map[x]
except KeyError:
raise SystemExit(f'{x} is not a valid value for {alias}. Valid values are y, yes, true, n, no, false only')
class Options:
do_print = True
def __init__(self, seq: OptionSpecSeq, usage: str | None, message: str | None, appname: str | None):
self.seq = seq
self.usage, self.message, self.appname = usage, message, appname
self.names_map, self.alias_map, self.values_map = get_option_maps(seq)
self.help_called = self.version_called = False
def handle_help(self) -> NoReturn:
if self.do_print:
print_help_for_seq(self.seq, self.usage, self.message, self.appname or appname)
self.help_called = True
raise SystemExit(0)
def handle_version(self) -> NoReturn:
self.version_called = True
if self.do_print:
print(version())
raise SystemExit(0)
PreparsedCLIFlags = tuple[dict[str, tuple[Any, bool]], list[str]]
def apply_preparsed_cli_flags(
preparsed_from_c: PreparsedCLIFlags, ans: Any, create_oc: Callable[[], Options], track_seen_options: dict[str, Any] | None = None
) -> list[str]:
for key, (val, is_seen) in preparsed_from_c[0].items():
if key == 'help' and is_seen and val:
create_oc().handle_help()
elif key == 'version' and is_seen and val:
create_oc().handle_version()
if is_seen and track_seen_options is not None:
track_seen_options[key] = val
setattr(ans, key, val)
return preparsed_from_c[1]
def parse_cmdline_inner(
args: list[str],
oc: Options,
disabled: OptionSpecSeq,
names_map: dict[str, OptionDefinition],
values_map: dict[str, OptionDefinition],
ans: Any,
track_seen_options: dict[str, Any] | None = None,
) -> list[str]:
preparsed = parse_cli_from_spec(args, names_map, values_map)
leftover_args = apply_preparsed_cli_flags(preparsed, ans, lambda: oc, track_seen_options)
for opt in disabled:
if not isinstance(opt, str):
setattr(ans, opt.dest, defval_for_opt(opt))
return leftover_args
def parse_cmdline(oc: Options, disabled: OptionSpecSeq, ans: Any, args: list[str] | None = None, track_seen_options: dict[str, Any] | None = None) -> list[str]:
names_map = oc.names_map.copy()
values_map = oc.values_map.copy()
if 'help' not in names_map:
names_map['help'] = OptionDefinition(type='bool-set', aliases=('--help', '-h'))
values_map['help'] = False
if 'version' not in names_map:
names_map['version'] = OptionDefinition(type='bool-set', aliases=('--version', '-v'))
values_map['version'] = False
try:
return parse_cmdline_inner(sys.argv[1:] if args is None else args, oc, disabled, names_map, values_map, ans, track_seen_options)
except Exception as e:
raise SystemExit(str(e))
spec_cache: dict[str, tuple[Options, OptionSpecSeq]] = {}
def cached_parse_cmdline(spec: str, args: list[str], ans: Any) -> list[str]:
if (x := spec_cache.get(spec)) is None:
seq, disabled = parse_option_spec(spec)
oc = Options(seq, '', '', '')
x = spec_cache[spec] = oc, disabled
oc, disabled = x
leftover_args = parse_cmdline_inner(args, oc, disabled, oc.names_map, oc.values_map, ans)
return leftover_args
def options_for_completion() -> OptionSpecSeq:
raw = '--help -h\ntype=bool-set\nShow help for {appname} command line options\n\n{raw}'.format(appname=appname, raw=kitty_options_spec())
return parse_option_spec(raw)[0]
def option_spec_as_rst(
ospec: Callable[[], str] = kitty_options_spec, usage: str | None = None, message: str | None = None, appname: str | None = None, heading_char: str = '-'
) -> str:
options = parse_option_spec(ospec())
seq, disabled = options
oc = Options(seq, usage, message, appname)
return seq_as_rst(oc.seq, oc.usage, oc.message, oc.appname, heading_char=heading_char)
T = TypeVar('T')
def parse_args(
args: list[str] | None = None,
ospec: Callable[[], str] = kitty_options_spec,
usage: str | None = None,
message: str | None = None,
appname: str | None = None,
result_class: type[T] | None = None,
preparsed_from_c: PreparsedCLIFlags | None = None,
track_seen_options: dict[str, Any] | None = None,
) -> tuple[T, list[str]]:
if result_class is not None:
ans = result_class()
else:
ans = cast(T, CLIOptions())
def create_oc() -> Options:
options = parse_option_spec(ospec())
seq, disabled = options
return Options(seq, usage, message, appname)
if preparsed_from_c:
return ans, apply_preparsed_cli_flags(preparsed_from_c, ans, create_oc)
options = parse_option_spec(ospec())
seq, disabled = options
oc = Options(seq, usage, message, appname)
return ans, parse_cmdline(oc, disabled, ans, args=args, track_seen_options=track_seen_options)
SYSTEM_CONF = f'/etc/xdg/{appname}/{appname}.conf'
def default_config_paths(conf_paths: Sequence[str]) -> tuple[str, ...]:
return tuple(resolve_config(SYSTEM_CONF, defconf, conf_paths))
@run_once
def override_pat() -> 're.Pattern[str]':
return re.compile(r'^([a-zA-Z0-9_]+)[ \t]*=')
def parse_override(x: str) -> str:
# Does not cover the case where `name =` when `=` is the value.
return override_pat().sub(r'\1 ', x.lstrip())
def create_opts(args: CLIOptions, accumulate_bad_lines: list[BadLineType] | None = None) -> KittyOpts:
from .config import load_config
config = default_config_paths(args.config)
overrides = map(parse_override, args.override or ())
opts = load_config(*config, overrides=overrides, accumulate_bad_lines=accumulate_bad_lines)
return opts
def create_default_opts() -> KittyOpts:
from .config import load_config
config = default_config_paths(())
opts = load_config(*config)
return opts
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from collections.abc import Sequence
class CLIOptions:
def __repr__(self) -> str:
return repr(vars(self))
LaunchCLIOptions = AskCLIOptions = ClipboardCLIOptions = DiffCLIOptions = CLIOptions
HintsCLIOptions = IcatCLIOptions = PanelCLIOptions = ResizeCLIOptions = CLIOptions
ErrorCLIOptions = UnicodeCLIOptions = RCOptions = RemoteFileCLIOptions = CLIOptions
BroadcastCLIOptions = ShowKeyCLIOptions = SaveAsSessionOptions = GotoSessionOptions = CLIOptions
ThemesCLIOptions = TransferCLIOptions = LoadConfigRCOptions = ActionRCOptions = CLIOptions
def generate_stub() -> None:
from .cli import as_type_stub
from .conf.utils import save_type_stub
from .simple_cli_definitions import parse_option_spec
text = 'import typing\n\n\n'
def do(otext: str | None = None, cls: str = 'CLIOptions', extra_fields: Sequence[str] = ()) -> None:
nonlocal text
text += as_type_stub(*parse_option_spec(otext), class_name=cls, extra_fields=extra_fields)
do(extra_fields=('args: typing.List[str]',))
from .launch import options_spec
do(options_spec(), 'LaunchCLIOptions')
from .remote_control import global_options_spec
do(global_options_spec(), 'RCOptions')
from kittens.ask.main import option_text
do(option_text(), 'AskCLIOptions')
from kittens.remote_file.main import option_text
do(option_text(), 'RemoteFileCLIOptions')
from kittens.clipboard.main import OPTIONS
do(OPTIONS(), 'ClipboardCLIOptions')
from kittens.show_key.main import OPTIONS
do(OPTIONS(), 'ShowKeyCLIOptions')
from kittens.diff.main import OPTIONS
do(OPTIONS(), 'DiffCLIOptions')
from kittens.hints.main import OPTIONS
do(OPTIONS(), 'HintsCLIOptions')
from kittens.broadcast.main import OPTIONS
do(OPTIONS(), 'BroadcastCLIOptions')
from kittens.icat.main import OPTIONS as OS
do(OS, 'IcatCLIOptions')
from kittens.panel.main import panel_kitten_options_spec
do(panel_kitten_options_spec(), 'PanelCLIOptions')
from kittens.resize_window.main import OPTIONS
do(OPTIONS(), 'ResizeCLIOptions')
from kittens.unicode_input.main import OPTIONS
do(OPTIONS(), 'UnicodeCLIOptions')
from kittens.themes.main import OPTIONS
do(OPTIONS(), 'ThemesCLIOptions')
from kittens.transfer.main import option_text
do(option_text(), 'TransferCLIOptions')
from kitty.session import goto_session_options, save_as_session_options
do(save_as_session_options(), 'SaveAsSessionOptions')
do(goto_session_options(), 'GotoSessionOptions')
from kitty.rc.base import all_command_names, command_for_name
for cmd_name in all_command_names():
cmd = command_for_name(cmd_name)
if cmd.options_spec:
do(cmd.options_spec, f'{cmd.__class__.__name__}RCOptions')
save_type_stub(text, __file__)
if __name__ == '__main__':
import subprocess
subprocess.Popen(['kitty', '+runpy', 'from kitty.cli_stub import generate_stub; generate_stub()'])
+362
View File
@@ -0,0 +1,362 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
# Replay the log from --dump-commands. To use first run
# kitty --dump-commands > file.txt
# then run
# kitty --replay-commands file.txt
# will replay the commands and pause at the end waiting for user to press enter
import json
import sys
from contextlib import suppress
from typing import Any
from .fast_data_types import DND_CODE, TEXT_SIZE_CODE
CSI = '\x1b['
OSC = '\x1b]'
def write(x: str) -> None:
sys.stdout.write(x)
sys.stdout.flush()
def set_title(*args: Any) -> None:
pass
def set_icon(*args: Any) -> None:
pass
def screen_bell() -> None:
pass
def screen_normal_keypad_mode() -> None:
write('\x1b>')
def screen_alternate_keypad_mode() -> None:
write('\x1b=')
def screen_cursor_position(y: int, x: int) -> None:
write(f'{CSI}{y};{x}H')
def screen_cursor_forward(amt: int) -> None:
write(f'{CSI}{amt}C')
def screen_save_cursor() -> None:
write('\x1b7')
def screen_restore_cursor() -> None:
write('\x1b8')
def screen_cursor_back1(amt: int) -> None:
write(f'{CSI}{amt}D')
def screen_save_modes() -> None:
write(f'{CSI}?s')
def screen_restore_modes() -> None:
write(f'{CSI}?r')
def screen_designate_charset(which: int, to: int) -> None:
w = '()'[int(which)]
t = chr(int(to))
write(f'\x1b{w}{t}')
def select_graphic_rendition(payload: str) -> None:
write(f'{CSI}{payload}m')
def deccara(*a: int) -> None:
write(f'{CSI}{";".join(map(str, a))}$r')
def screen_cursor_to_column(c: int) -> None:
write(f'{CSI}{c}G')
def screen_cursor_to_line(ln: int) -> None:
write(f'{CSI}{ln}d')
def screen_set_mode(x: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{x}h')
def screen_save_mode(x: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{x}s')
def screen_reset_mode(x: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{x}l')
def screen_restore_mode(x: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{x}r')
def screen_set_margins(t: int, b: int) -> None:
write(f'{CSI}{t};{b}r')
def screen_indexn(n: int) -> None:
write(f'{CSI}{n}S')
def screen_delete_characters(count: int) -> None:
write(f'{CSI}{count}P')
def screen_push_colors(which: int) -> None:
write(f'{CSI}{which}#P')
def screen_pop_colors(which: int) -> None:
write(f'{CSI}{which}#Q')
def screen_report_colors() -> None:
write(f'{CSI}#R')
def screen_repeat_character(num: int) -> None:
write(f'{CSI}{num}b')
def screen_insert_characters(count: int) -> None:
write(f'{CSI}{count}@')
def screen_scroll(count: int) -> None:
write(f'{CSI}{count}S')
def screen_erase_in_display(how: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{how}J')
def screen_erase_in_line(how: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{how}K')
def screen_erase_characters(num: int) -> None:
write(f'{CSI}{num}X')
def screen_delete_lines(num: int) -> None:
write(f'{CSI}{num}M')
def screen_cursor_up2(count: int) -> None:
write(f'{CSI}{count}A')
def screen_cursor_down(count: int) -> None:
write(f'{CSI}{count}B')
def screen_cursor_down1(count: int) -> None:
write(f'{CSI}{count}E')
def screen_report_key_encoding_flags() -> None:
write(f'{CSI}?u')
def screen_set_key_encoding_flags(flags: int, how: int) -> None:
write(f'{CSI}={flags};{how}u')
def screen_push_key_encoding_flags(flags: int) -> None:
write(f'{CSI}>{flags}u')
def screen_pop_key_encoding_flags(flags: int) -> None:
write(f'{CSI}<{flags}u')
def screen_carriage_return() -> None:
write('\r')
def screen_linefeed() -> None:
write('\n')
def screen_tab() -> None:
write('\t')
def screen_backspace() -> None:
write('\x08')
def screen_set_cursor(mode: int, secondary: int) -> None:
write(f'{CSI}{secondary} q')
def screen_insert_lines(num: int) -> None:
write(f'{CSI}{num}L')
def draw(*a: str) -> None:
write(' '.join(a))
def screen_manipulate_title_stack(op: int, which: int) -> None:
write(f'{CSI}{op};{which}t')
def report_device_attributes(mode: int, char: int) -> None:
x = CSI
if char:
x += chr(char)
if mode:
x += str(mode)
write(f'{x}c')
def report_device_status(x: int, private: bool) -> None:
write(f'{CSI}{"?" if private else ""}{x}n')
def screen_decsace(mode: int) -> None:
write(f'{CSI}{mode}*x')
def screen_set_8bit_controls(mode: int) -> None:
write(f'\x1b {"G" if mode else "F"}')
def write_osc(code: int, string: str = '') -> None:
if string:
write(f'{OSC}{code};{string}\x07')
else:
write(f'{OSC}{code}\x07')
set_color_table_color = process_cwd_notification = write_osc
clipboard_control_pending: str = ''
def set_dynamic_color(payload: str) -> None:
code, data = payload.partition(' ')[::2]
write_osc(int(code), data)
def shell_prompt_marking(payload: str) -> None:
write_osc(133, payload)
def clipboard_control(payload: str) -> None:
global clipboard_control_pending
code, data = payload.split(';', 1)
if code == '-52':
if clipboard_control_pending:
clipboard_control_pending += data.lstrip(';')
else:
clipboard_control_pending = payload
return
if clipboard_control_pending:
clipboard_control_pending += data.lstrip(';')
payload = clipboard_control_pending
clipboard_control_pending = ''
write(f'{OSC}{payload}\x07')
def dnd_command(payload: str) -> None:
c = json.loads(payload)
text = c.pop('', '')
t = c.pop('type', 'a')
if isinstance(t, (bytes, memoryview)):
t = str(t, 'utf-8', 'replace')
m = f't={t}'
if more := c.pop('more', None):
m += f':m={more}'
if client_id := c.pop('client_id', None):
m += f':i={client_id}'
if operation := c.pop('operation', None):
m += f':o={operation}'
if cell_x := c.pop('cell_x', None):
m += f':x={cell_x}'
if cell_y := c.pop('cell_y', None):
m += f':y={cell_y}'
if pixel_x := c.pop('pixel_x', None):
m += f':X={pixel_x}'
if pixel_y := c.pop('pixel_y', None):
m += f':Y={pixel_y}'
write(f'{OSC}{DND_CODE};{m};{text}\x1b\\')
def multicell_command(payload: str) -> None:
c = json.loads(payload)
text = c.pop('', '')
m = ''
if (w := c.pop('width', None)) is not None and w > 0:
m += f'w={w}:'
if (s := c.pop('scale', None)) is not None and s > 1:
m += f's={s}:'
if (n := c.pop('subscale_n', None)) is not None and n > 0:
m += f'n={n}:'
if (d := c.pop('subscale_d', None)) is not None and d > 0:
m += f'd={d}:'
if (v := c.pop('vertical_align', None)) is not None and v > 0:
m += f'v={v}:'
if (h := c.pop('horizontal_align', None)) is not None and h > 0:
m += f'h={h}:'
if c:
raise Exception('Unknown keys in multicell_command: ' + ', '.join(c))
write(f'{OSC}{TEXT_SIZE_CODE};{m.rstrip(":")};{text}\a')
def screen_multi_cursor(rest: str) -> None:
write(f'{CSI}>{rest.strip()} q')
def replay(raw: str) -> None:
specials = frozenset(
{
'draw',
'set_title',
'set_icon',
'set_dynamic_color',
'set_color_table_color',
'select_graphic_rendition',
'process_cwd_notification',
'clipboard_control',
'shell_prompt_marking',
'multicell_command',
'screen_multi_cursor',
'dnd_command',
}
)
for line in raw.splitlines():
if line.strip() and not line.startswith('#'):
cmd, rest = line.partition(' ')[::2]
if cmd in specials:
globals()[cmd](rest)
else:
r = map(int, rest.split()) if rest else ()
globals()[cmd](*r)
def main(path: str) -> None:
with open(path) as f:
raw = f.read()
replay(raw)
with suppress(EOFError, KeyboardInterrupt):
input()
+735
View File
@@ -0,0 +1,735 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import io
import os
from collections.abc import Callable, Mapping
from enum import Enum, IntEnum
from gettext import gettext as _
from tempfile import TemporaryFile
from typing import IO, NamedTuple, Union
from .conf.utils import uniq
from .constants import supports_primary_selection
from .fast_data_types import (
ESC_OSC,
GLFW_CLIPBOARD,
GLFW_PRIMARY_SELECTION,
StreamingBase64Decoder,
base64_decode,
find_in_memoryview,
get_boss,
get_clipboard_mime,
get_options,
set_clipboard_data_types,
)
from .typing_compat import WindowType
from .utils import log_error
READ_RESPONSE_CHUNK_SIZE = 4096
class Tempfile:
def __init__(self, max_size: int) -> None:
self.file: io.BytesIO | IO[bytes] = io.BytesIO()
self.max_size = max_size
def rollover_if_needed(self, sz: int) -> None:
if isinstance(self.file, io.BytesIO) and self.file.tell() + sz > self.max_size:
before = self.file.getvalue()
self.file = TemporaryFile()
self.file.write(before)
def write(self, data: bytes) -> None:
self.rollover_if_needed(len(data))
self.file.write(data)
def tell(self) -> int:
return self.file.tell()
def seek(self, pos: int) -> None:
self.file.seek(pos, os.SEEK_SET)
def read(self, offset: int, size: int) -> bytes:
self.file.seek(offset)
return self.file.read(size)
def create_chunker(self, offset: int, size: int) -> Callable[[], Callable[[], bytes]]:
def chunk_creator() -> Callable[[], bytes]:
pos = offset
limit = offset + size
def chunker() -> bytes:
nonlocal pos, limit
if pos >= limit:
return b''
ans = self.read(pos, min(io.DEFAULT_BUFFER_SIZE, limit - pos))
pos = self.file.tell()
return ans
return chunker
return chunk_creator
DataType = Union[bytes, Callable[[], Callable[[], bytes]]]
TARGETS_MIME = '.'
class ClipboardType(IntEnum):
clipboard = GLFW_CLIPBOARD
primary_selection = GLFW_PRIMARY_SELECTION
unknown = -311
@staticmethod
def from_osc52_where_field(where: str) -> 'ClipboardType':
if where in ('c', 's'):
return ClipboardType.clipboard
if where == 'p':
return ClipboardType.primary_selection
return ClipboardType.unknown
class Clipboard:
def __init__(self, clipboard_type: ClipboardType = ClipboardType.clipboard) -> None:
self.data: dict[str, DataType] = {}
self.clipboard_type = clipboard_type
self.enabled = self.clipboard_type is ClipboardType.clipboard or supports_primary_selection
def set_text(self, x: str | bytes) -> None:
if isinstance(x, str):
x = x.encode('utf-8')
self.set_mime({'text/plain': x})
def set_mime(self, data: Mapping[str, DataType]) -> None:
if self.enabled and isinstance(data, dict):
self.data = dict(data)
set_clipboard_data_types(self.clipboard_type, tuple(self.data))
def get_text(self) -> str:
parts: list[bytes] = []
self.get_mime('text/plain', parts.append)
return b''.join(parts).decode('utf-8', 'replace')
def get_mime(self, mime: str, output: Callable[[bytes], None]) -> None:
if self.enabled:
try:
get_clipboard_mime(self.clipboard_type, mime, output)
except RuntimeError as err:
if str(err) != 'is_self_offer':
raise
data = self.data.get(mime, b'')
if isinstance(data, bytes):
output(data)
else:
chunker = data()
q = b' '
while q:
q = chunker()
output(q)
def get_mime_data(self, mime: str) -> bytes:
ans: list[bytes] = []
self.get_mime(mime, ans.append)
return b''.join(ans)
def get_available_mime_types_for_paste(self) -> tuple[str, ...]:
if self.enabled:
parts: list[bytes] = []
try:
get_clipboard_mime(self.clipboard_type, None, parts.append)
except RuntimeError as err:
if str(err) != 'is_self_offer':
raise
return tuple(self.data)
return tuple(x.decode('utf-8', 'replace') for x in uniq(parts))
return ()
def __call__(self, mime: str) -> Callable[[], bytes]:
data = self.data.get(mime, b'')
if isinstance(data, str):
data = data.encode('utf-8')
if isinstance(data, bytes):
def chunker() -> bytes:
nonlocal data
assert isinstance(data, bytes)
ans = data
data = b''
return ans
return chunker
return data()
def set_clipboard_string(x: str | bytes) -> None:
get_boss().clipboard.set_text(x)
def get_clipboard_string() -> str:
return get_boss().clipboard.get_text()
def set_primary_selection(x: str | bytes) -> None:
get_boss().primary_selection.set_text(x)
def get_primary_selection() -> str:
return get_boss().primary_selection.get_text()
def develop() -> tuple[Clipboard, Clipboard]:
from .constants import detect_if_wayland_ok, is_macos
from .fast_data_types import set_boss
from .main import init_glfw_module
glfw_module = 'cocoa' if is_macos else ('wayland' if detect_if_wayland_ok() else 'x11')
class Boss:
clipboard = Clipboard()
primary_selection = Clipboard(ClipboardType.primary_selection)
init_glfw_module(glfw_module)
set_boss(Boss()) # type: ignore
return Boss.clipboard, Boss.primary_selection
class ProtocolType(Enum):
osc_52 = 52
osc_5522 = 5522
def encode_mime(x: str) -> str:
import base64
return base64.standard_b64encode(x.encode('utf-8')).decode('ascii')
def strict_base64_decode(x: str | bytes | memoryview) -> bytes:
# Unlike the base64 module from the stdlib this rejects characters outside
# the base64 alphabet as required by RFC 4648 and is faster as it uses SIMD
return base64_decode(x, True)
def decode_metadata_value(k: str, x: str) -> str:
if k in ('mime', 'name', 'pw'):
x = strict_base64_decode(x).decode('utf-8')
return x
class ReadRequest(NamedTuple):
is_primary_selection: bool = False
mime_types: tuple[str, ...] = ('text/plain',)
id: str = ''
protocol_type: ProtocolType = ProtocolType.osc_52
human_name: str = ''
password: str = ''
otp_for_response: str = ''
def encode_response(self, status: str = 'DATA', mime: str = '', payload: bytes | memoryview = b'') -> bytes:
from base64 import standard_b64encode
def encode_b64(s: str) -> str:
return standard_b64encode(s.encode()).decode()
ans = f'{self.protocol_type.value};type=read:status={status}'
if status == 'OK' and self.is_primary_selection:
ans += ':loc=primary'
if self.id:
ans += f':id={self.id}'
if mime:
ans += f':mime={encode_mime(mime)}'
if self.otp_for_response:
ans += f':pw={encode_b64(self.otp_for_response)}'
a = ans.encode('ascii')
if payload:
a += b';' + standard_b64encode(payload)
return a
def encode_osc52(loc: str, response: str) -> str:
from base64 import standard_b64encode
return '52;{};{}'.format(loc, standard_b64encode(response.encode('utf-8')).decode('ascii'))
class MimePos(NamedTuple):
start: int
size: int
class WriteRequest:
def __init__(
self,
is_primary_selection: bool = False,
protocol_type: ProtocolType = ProtocolType.osc_52,
id: str = '',
rollover_size: int = 16 * 1024 * 1024,
max_size: int = -1,
human_name: str = '',
password: str = '',
) -> None:
self.decoder = StreamingBase64Decoder()
self.human_name = human_name
self.password = password
self.id = id
self.is_primary_selection = is_primary_selection
self.protocol_type = protocol_type
self.max_size_exceeded = False
self.tempfile = Tempfile(max_size=rollover_size)
self.mime_map: dict[str, MimePos] = {}
self.currently_writing_mime = ''
self.max_size = int(get_options().clipboard_max_size * 1024 * 1024) if max_size < 0 else max_size
self.aliases: dict[str, str] = {}
self.committed = False
self.permission_pending = True
self.commit_pending = False
self.aborted = False
def encode_response(self, status: str = 'OK') -> bytes:
ans = f'{self.protocol_type.value};type=write:status={status}'
if self.id:
ans += f':id={self.id}'
a = ans.encode('ascii')
return a
def commit(self) -> None:
if self.committed:
return
if self.permission_pending:
self.commit_pending = True
return
self.committed = True
self.commit_pending = False
cp = get_boss().primary_selection if self.is_primary_selection else get_boss().clipboard
if cp.enabled:
for alias, src in self.aliases.items():
pos = self.mime_map.get(src)
if pos is not None:
self.mime_map[alias] = pos
x = {mime: self.tempfile.create_chunker(pos.start, pos.size) for mime, pos in self.mime_map.items()}
cp.set_mime(x)
def abort(self, msg: str) -> ValueError:
# returns the error to raise, so that callers read as: raise self.abort(...)
self.aborted = True
self.decoder.reset()
return ValueError(msg)
def add_base64_data(self, data: str | bytes | memoryview, mime: str = 'text/plain') -> None:
if self.aborted:
return
if isinstance(data, str):
data = data.encode('ascii')
if self.currently_writing_mime and self.currently_writing_mime != mime:
self.flush_base64_data()
if not self.currently_writing_mime:
self.mime_map[mime] = MimePos(self.tempfile.tell(), -1)
self.currently_writing_mime = mime
self.write_base64_data(data)
def flush_base64_data(self) -> None:
if self.currently_writing_mime:
incomplete = self.decoder.needs_more_data()
self.decoder.reset()
start = self.mime_map[self.currently_writing_mime][0]
self.mime_map[self.currently_writing_mime] = MimePos(start, self.tempfile.tell() - start)
self.currently_writing_mime = ''
if incomplete:
# the data is not padded to a multiple of four bytes. This is
# tolerated for the legacy OSC 52 protocol as it has no way to
# report errors to the client.
if self.protocol_type is ProtocolType.osc_5522:
raise self.abort('Incomplete base64 data, missing padding bytes')
log_error('Received incomplete data for clipboard')
def write_base64_data(self, b: bytes | memoryview) -> None:
if not self.max_size_exceeded:
try:
decoded = self.decoder.decode(b)
except ValueError as e:
raise self.abort(f'Invalid base64 data: {e}') from e
if decoded:
self.tempfile.write(decoded)
if self.max_size > 0 and self.tempfile.tell() > self.max_size:
log_error(f'Clipboard write request has more data than allowed by clipboard_max_size ({self.max_size} bytes), ignoring further data')
self.max_size_exceeded = True
def data_for(self, mime: str = 'text/plain', offset: int = 0, size: int = -1) -> bytes:
start, full_size = self.mime_map[mime]
if size == -1:
size = full_size
return self.tempfile.read(start + offset, size)
class GrantedPermission:
one_time: bool = False
write_ban: bool = False
read_ban: bool = False
def __init__(self, read: bool = False, write: bool = False, one_time: bool = False):
self.read, self.write = read, write
self.one_time = one_time
class ClipboardRequestManager:
def __init__(self, window_id: int) -> None:
self.window_id = window_id
self.currently_asking_permission_for: ReadRequest | None = None
self.in_flight_write_request: WriteRequest | None = None
self.osc52_in_flight_write_requests: dict[ClipboardType, WriteRequest] = {}
self.granted_passwords: dict[str, GrantedPermission] = {}
def parse_osc_5522(self, data: memoryview) -> None:
from .notifications import sanitize_id
idx = find_in_memoryview(data, ord(b';'))
if idx > -1:
metadata = str(data[:idx], 'utf-8', 'replace')
epayload = data[idx + 1 :]
else:
metadata = str(data, 'utf-8', 'replace')
epayload = data[len(data) :]
m: dict[str, str] = {}
for record in metadata.split(':'):
try:
k, v = record.split('=', 1)
except Exception:
log_error('Malformed OSC 5522: metadata is not key=value pairs')
return
m[k] = v
typ = m.get('type', '')
try:
m = {k: decode_metadata_value(k, v) for k, v in m.items()}
except Exception as e:
log_error(f'Malformed OSC 5522: could not decode a metadata value. Error: {e}')
if typ in ('wdata', 'walias') and self.in_flight_write_request is not None:
self.abort_write_request(self.in_flight_write_request, 'EINVAL')
return
if typ == 'read':
try:
mime_types = tuple(strict_base64_decode(epayload).decode('utf-8').split())
except Exception as e:
log_error(f'Malformed OSC 5522: read request payload is not valid base64 encoded UTF-8. Error: {e}')
return
rr = ReadRequest(
is_primary_selection=m.get('loc', '') == 'primary',
mime_types=mime_types,
protocol_type=ProtocolType.osc_5522,
id=sanitize_id(m.get('id', '')),
human_name=m.get('name', ''),
password=m.get('pw', ''),
)
self.handle_read_request(rr)
elif typ == 'write':
self.in_flight_write_request = WriteRequest(
is_primary_selection=m.get('loc', '') == 'primary',
protocol_type=ProtocolType.osc_5522,
id=sanitize_id(m.get('id', '')),
human_name=m.get('name', ''),
password=m.get('pw', ''),
)
self.handle_write_request(self.in_flight_write_request)
elif typ == 'walias':
wr = self.in_flight_write_request
if wr is None:
return
mime = m.get('mime', '')
if not mime:
log_error('Clipboard alias request has no MIME type, aborting the write request')
self.abort_write_request(wr, 'EINVAL')
return
try:
aliases = strict_base64_decode(epayload).decode('utf-8').split()
except Exception as e:
log_error(f'Clipboard alias request payload is not valid base64 encoded UTF-8, aborting the write request. Error: {e}')
self.abort_write_request(wr, 'EINVAL')
return
for alias in aliases:
wr.aliases[alias] = mime
elif typ == 'wdata':
wr = self.in_flight_write_request
if wr is None:
return
mime = m.get('mime', '')
try:
if not mime:
self.commit_write_request(wr)
return
wr.add_base64_data(epayload, mime)
except OSError:
self.abort_write_request(wr, 'EIO')
raise
except ValueError as e:
log_error(f'Clipboard write request payload is not valid base64, aborting the write request. Error: {e}')
self.abort_write_request(wr, 'EINVAL')
return
except Exception:
self.abort_write_request(wr, 'EINVAL')
raise
if wr.max_size_exceeded:
self.abort_write_request(wr, 'EFBIG')
def abort_write_request(self, wr: WriteRequest, status: str) -> None:
self.in_flight_write_request = None
w = get_boss().window_id_map.get(self.window_id)
if w is not None:
w.screen.send_escape_code_to_child(ESC_OSC, wr.encode_response(status=status))
def commit_write_request(self, wr: WriteRequest, needs_flush: bool = True) -> None:
if needs_flush:
wr.flush_base64_data()
wr.commit()
if wr.committed:
self.in_flight_write_request = None
w = get_boss().window_id_map.get(self.window_id)
if w is not None:
w.screen.send_escape_code_to_child(ESC_OSC, wr.encode_response(status='DONE'))
def parse_osc_52(self, data: memoryview, is_partial: bool = False) -> None:
idx = find_in_memoryview(data, ord(b';'))
if idx > -1:
where = str(data[:idx], 'utf-8', 'replace')
data = data[idx + 1 :]
else:
where = str(data, 'utf-8', 'replace')
data = data[len(data) :]
destinations = {ClipboardType.from_osc52_where_field(where) for where in where or 's0'}
destinations.discard(ClipboardType.unknown)
if len(data) == 1 and data.tobytes() == b'?':
for d in destinations:
rr = ReadRequest(is_primary_selection=d is ClipboardType.primary_selection)
self.handle_read_request(rr)
else:
for d in destinations:
wr = self.osc52_in_flight_write_requests.get(d)
if wr is None:
wr = self.osc52_in_flight_write_requests[d] = WriteRequest(d is ClipboardType.primary_selection)
try:
wr.add_base64_data(data)
except ValueError as e:
# OSC 52 has no way to report errors to the client so just
# discard the entire request
log_error(f'Ignoring OSC 52 clipboard write request as it is not valid base64. Error: {e}')
if is_partial:
return
self.osc52_in_flight_write_requests.pop(d, None)
if not wr.aborted:
self.handle_write_request(wr)
def handle_write_request(self, wr: WriteRequest) -> None:
wr.flush_base64_data()
q = 'write-primary' if wr.is_primary_selection else 'write-clipboard'
allowed = q in get_options().clipboard_control
self.fulfill_write_request(wr, allowed)
def fulfill_write_request(self, wr: WriteRequest, allowed: bool = True) -> None:
wr.permission_pending = not allowed
if wr.protocol_type is ProtocolType.osc_52:
self.fulfill_legacy_write_request(wr, allowed)
return
cp = get_boss().primary_selection if wr.is_primary_selection else get_boss().clipboard
w = get_boss().window_id_map.get(self.window_id)
if w is None:
self.in_flight_write_request = None
return
if not cp.enabled:
self.in_flight_write_request = None
w.screen.send_escape_code_to_child(ESC_OSC, wr.encode_response(status='ENOSYS'))
return
if not allowed:
if wr.password and wr.human_name:
if self.password_is_allowed_already(wr.password, for_write=True):
wr.permission_pending = False
else:
wid = w.id
def callback(granted: bool) -> None:
if wr is not self.in_flight_write_request:
return
if granted:
wr.permission_pending = False
if wr.commit_pending:
self.commit_write_request(wr, needs_flush=False)
else:
w = get_boss().window_id_map.get(wid)
if w is not None:
w.screen.send_escape_code_to_child(ESC_OSC, wr.encode_response(status='EPERM'))
self.in_flight_write_request = None
self.request_permission(w, wr.human_name, wr.password, callback, for_write=True)
else:
self.in_flight_write_request = None
w.screen.send_escape_code_to_child(ESC_OSC, wr.encode_response(status='EPERM'))
def request_permission(self, window: WindowType, human_name: str, password: str, callback: Callable[[bool], None], for_write: bool = False) -> None:
if (gp := self.granted_passwords.get(password)) and (gp.write_ban if for_write else gp.read_ban):
callback(False)
return
def cb(q: str) -> None:
p = self.granted_passwords.get(password)
if p is None:
p = self.granted_passwords[password] = GrantedPermission()
callback(q in ('a', 'w'))
match q:
case 'w':
if for_write:
p.write = True
else:
p.read = True
case 'b':
if for_write:
p.write = False
p.write_ban = True
else:
p.read = False
p.read_ban = True
if for_write:
msg = _('The program {0} running in this window wants to write to the system clipboard.')
else:
msg = _('The program {0} running in this window wants to read from the system clipboard.')
msg += '\n\n' + ('If you choose "Always" similar requests from this program will be automatically allowed for the rest of this session.')
msg += '\n\n' + ('If you choose "Ban" similar requests from this program will be automatically dis-allowed for the rest of this session.')
from kittens.tui.operations import styled
get_boss().choose(
msg.format(styled(human_name, fg='yellow')),
cb,
'a;green:Allow',
'w;yellow:Always',
'd;red:Deny',
'b;red:Ban',
default='d',
window=window,
title=_('A program wants to access the clipboard'),
)
def password_is_allowed_already(self, password: str, for_write: bool = False) -> bool:
q = self.granted_passwords.get(password)
if q is not None:
if q.one_time:
self.granted_passwords.pop(password, None)
return q.write if for_write else q.read
return False
def fulfill_legacy_write_request(self, wr: WriteRequest, allowed: bool = True) -> None:
cp = get_boss().primary_selection if wr.is_primary_selection else get_boss().clipboard
w = get_boss().window_id_map.get(self.window_id)
if w is not None and cp.enabled and allowed:
wr.commit()
def handle_read_request(self, rr: ReadRequest) -> None:
cc = get_options().clipboard_control
if rr.is_primary_selection:
ask_for_permission = 'read-primary-ask' in cc
allowed = 'read-primary' in cc
else:
ask_for_permission = 'read-clipboard-ask' in cc
allowed = 'read-clipboard' in cc
if ask_for_permission:
self.ask_to_read_clipboard(rr)
else:
self.fulfill_read_request(rr, allowed=allowed)
def send_paste_event(self, is_primary_selection: bool) -> None:
from kitty.short_uuid import uuid4
pw = uuid4()
self.granted_passwords[pw] = GrantedPermission(read=True, one_time=True)
rr = ReadRequest(is_primary_selection=is_primary_selection, mime_types=(TARGETS_MIME,), protocol_type=ProtocolType.osc_5522)
rr = rr._replace(otp_for_response=pw)
self.fulfill_read_request(rr)
def fulfill_read_request(self, rr: ReadRequest, allowed: bool = True) -> None:
if rr.protocol_type is ProtocolType.osc_52:
return self.fulfill_legacy_read_request(rr, allowed)
w = get_boss().window_id_map.get(self.window_id)
if w is None:
return
cp = get_boss().primary_selection if rr.is_primary_selection else get_boss().clipboard
if not cp.enabled:
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(status='ENOSYS'))
return
if not allowed:
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(status='EPERM'))
return
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(status='OK'))
current_mime = ''
def write_chunks(data: bytes) -> None:
assert w is not None
mv = memoryview(data)
while mv:
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(payload=mv[:READ_RESPONSE_CHUNK_SIZE], mime=current_mime))
mv = mv[READ_RESPONSE_CHUNK_SIZE:]
for mime in rr.mime_types:
current_mime = mime
if mime == TARGETS_MIME:
payload = ' '.join(cp.get_available_mime_types_for_paste()).encode('utf-8')
if payload:
payload += b'\n'
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(payload=payload, mime=current_mime))
continue
try:
cp.get_mime(mime, write_chunks)
except Exception as e:
log_error(f'Failed to read requested mime type {mime} with error: {e}')
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(status='DONE'))
def reject_read_request(self, rr: ReadRequest) -> None:
if rr.protocol_type is ProtocolType.osc_52:
return self.fulfill_legacy_read_request(rr, False)
w = get_boss().window_id_map.get(self.window_id)
if w is not None:
w.screen.send_escape_code_to_child(ESC_OSC, rr.encode_response(status='EPERM'))
def fulfill_legacy_read_request(self, rr: ReadRequest, allowed: bool = True) -> None:
cp = get_boss().primary_selection if rr.is_primary_selection else get_boss().clipboard
w = get_boss().window_id_map.get(self.window_id)
if w is not None:
text = ''
if cp.enabled and allowed:
text = cp.get_text()
loc = 'p' if rr.is_primary_selection else 'c'
w.screen.send_escape_code_to_child(ESC_OSC, encode_osc52(loc, text))
def ask_to_read_clipboard(self, rr: ReadRequest) -> None:
if rr.mime_types == (TARGETS_MIME,):
self.fulfill_read_request(rr, True)
return
if self.currently_asking_permission_for is not None:
self.reject_read_request(rr)
return
w = get_boss().window_id_map.get(self.window_id)
if w is not None:
self.currently_asking_permission_for = rr
if rr.password and rr.human_name:
if self.password_is_allowed_already(rr.password):
self.handle_clipboard_confirmation(True)
return
if (p := self.granted_passwords.get(rr.password)) and p.read_ban:
self.handle_clipboard_confirmation(False)
return
self.request_permission(w, rr.human_name, rr.password, self.handle_clipboard_confirmation)
else:
if rr.human_name:
msg = _('The program {} running in this window wants to read from the system clipboard. Allow it to do so, once?').format(rr.human_name)
else:
msg = _('A program running in this window wants to read from the system clipboard. Allow it to do so, once?')
get_boss().confirm(msg, self.handle_clipboard_confirmation, window=w)
def handle_clipboard_confirmation(self, confirmed: bool) -> None:
rr = self.currently_asking_permission_for
self.currently_asking_permission_for = None
if rr is not None:
self.fulfill_read_request(rr, confirmed)
def close(self) -> None:
if self.in_flight_write_request is not None:
self.in_flight_write_request = None
self.osc52_in_flight_write_requests.clear()
+73
View File
@@ -0,0 +1,73 @@
/*
* cocoa_window.h
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
typedef enum {
PREFERENCES_WINDOW,
NEW_OS_WINDOW,
NEW_OS_WINDOW_WITH_WD,
NEW_TAB_WITH_WD,
CLOSE_OS_WINDOW,
CLOSE_TAB,
NEW_TAB,
NEXT_TAB,
PREVIOUS_TAB,
DETACH_TAB,
LAUNCH_URLS,
NEW_WINDOW,
CLOSE_WINDOW,
RESET_TERMINAL,
CLEAR_TERMINAL_AND_SCROLLBACK,
CLEAR_SCROLLBACK,
CLEAR_SCREEN,
CLEAR_LAST_COMMAND,
RELOAD_CONFIG,
TOGGLE_MACOS_SECURE_KEYBOARD_ENTRY,
MACOS_CYCLE_THROUGH_OS_WINDOWS,
MACOS_CYCLE_THROUGH_OS_WINDOWS_BACKWARDS,
SEARCH_SCROLLBACK,
TOGGLE_FULLSCREEN,
OPEN_KITTY_WEBSITE,
HIDE,
HIDE_OTHERS,
MINIMIZE,
QUIT,
PASTE_FROM_CLIPBOARD,
COPY_OR_NOOP,
USER_MENU_ACTION,
COCOA_NOTIFICATION_UNTRACKED,
NUM_COCOA_PENDING_ACTIONS
} CocoaPendingAction;
void cocoa_focus_window(void *w);
long cocoa_window_number(void *w);
void cocoa_application_lifecycle_event(bool);
void cocoa_recreate_global_menu(void);
void cocoa_system_beep(const char *);
void cocoa_set_activation_policy(bool);
bool cocoa_alt_option_key_pressed(unsigned long);
void cocoa_toggle_secure_keyboard_entry(void);
void cocoa_hide(void);
void cocoa_clear_global_shortcuts(void);
void cocoa_hide_others(void);
void cocoa_minimize(void *w);
void cocoa_set_uncaught_exception_handler(void);
void cocoa_update_menu_bar_title(PyObject *);
size_t cocoa_get_workspace_ids(void *w, size_t *workspace_ids, size_t array_sz);
monotonic_t cocoa_cursor_blink_interval(void);
bool cocoa_render_line_of_text(const char *text, const color_type fg, const color_type bg, uint8_t *rgba_output, const size_t width, const size_t height);
size_t cocoa_text_width_for_single_line(const char *text, const size_t height);
extern uint8_t *render_single_ascii_char_as_mask(const char ch, size_t *result_width, size_t *result_height);
void get_cocoa_key_equivalent(uint32_t, int, char *key, size_t key_sz, int *);
void set_cocoa_pending_action(CocoaPendingAction action, const char *);
void cocoa_report_live_notifications(const char *ident);
void cocoa_set_dock_badge(const char *label);
void cocoa_clear_dock_badge_if_set(void);
+1804
View File
File diff suppressed because it is too large. Load diff
+3845
View File
File diff suppressed because it is too large. Load diff
+1902
View File
File diff suppressed because it is too large. Load diff
+76
View File
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
typedef union ARGB32 {
color_type val;
struct {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t b : 8;
uint8_t g : 8;
uint8_t r : 8;
uint8_t a : 8;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t a : 8;
uint8_t r : 8;
uint8_t g : 8;
uint8_t b : 8;
#else
#error "Unsupported endianness"
#endif
};
struct {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t blue : 8;
uint8_t green : 8;
uint8_t red : 8;
uint8_t alpha : 8;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t alpha : 8;
uint8_t red : 8;
uint8_t green : 8;
uint8_t blue : 8;
#else
#error "Unsupported endianness"
#endif
};
struct {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
color_type rgb : 24;
uint8_t _ignore_me : 8;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
uint8_t _ignore_me : 8;
color_type rgb : 24;
#else
#error "Unsupported endianness"
#endif
};
} ARGB32;
typedef struct {
PyObject_HEAD
ARGB32 color;
} Color;
extern PyTypeObject ColorProfile_Type;
extern PyTypeObject Color_Type;
static inline double
rgb_luminance(ARGB32 c) {
// From ITU BT 601 https://www.itu.int/rec/R-REC-BT.601
return 0.299 * c.red + 0.587 * c.green + 0.114 * c.blue;
}
static inline double
rgb_contrast(ARGB32 a, ARGB32 b) {
double al = rgb_luminance(a), bl = rgb_luminance(b);
if (al < bl) SWAP(al, bl);
return (al + 0.05) / (bl + 0.05);
}
+401
View File
@@ -0,0 +1,401 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import os
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Literal, Optional, TypedDict, cast
from .config import parse_config
from .constants import config_dir, config_dir_files_ignored
from .fast_data_types import (
COLOR_LAYER_GLOBAL,
COLOR_LAYER_OVERRIDE,
COLOR_LAYER_SESSION,
Color,
ColorProfile,
get_boss,
get_options,
glfw_get_system_color_theme,
patch_color_profiles,
patch_global_colors,
set_os_window_chrome,
)
from .options.types import Options, all_colors, nullable_colors, special_colors
from .rgb import color_from_int
from .types import run_once
from .typing_compat import WindowType
ColorsSpec = dict[str, Optional[int]]
TransparentBackgroundColors = tuple[tuple[Color, float], ...]
ColorSchemes = Literal['light', 'dark', 'no_preference']
Colors = tuple[ColorsSpec, TransparentBackgroundColors]
# None for the transparent background colors means they were not specified and
# should be left unchanged, as opposed to () which means clear them.
ParsedColors = tuple[ColorsSpec, TransparentBackgroundColors | None]
class BackgroundImageOptions(TypedDict, total=False):
background_image: Sequence[str] | None
background_image_layout: str | None
background_image_linear: bool | None
background_tint: float | None
background_tint_gaps: float | None
class ThemeFile(Enum):
dark = 'dark-theme.auto.conf'
light = 'light-theme.auto.conf'
no_preference = 'no-preference-theme.auto.conf'
theme_file_schemes: dict[str, ColorSchemes] = {ThemeFile.dark.value: 'dark', ThemeFile.light.value: 'light', ThemeFile.no_preference.value: 'no_preference'}
@dataclass
class AutoTheme:
# mtime is -1 when there is no theme file for this color scheme
mtime: int = -1
spec: ColorsSpec = field(default_factory=dict)
tbc: TransparentBackgroundColors = ()
background_image_options: BackgroundImageOptions = field(default_factory=lambda: BackgroundImageOptions())
class ThemeColors:
applied_theme: Literal['light', 'dark', 'no_preference', ''] = ''
default_colors: ColorsSpec | None = None
default_background_image_options: BackgroundImageOptions | None = None
def __init__(self) -> None:
self.themes: dict[ColorSchemes, AutoTheme] = {'dark': AutoTheme(), 'light': AutoTheme(), 'no_preference': AutoTheme()}
def get_default_colors(self) -> ColorsSpec:
if self.default_colors is None:
from kitty.options.types import defaults, option_names
ans: ColorsSpec = dict.fromkeys(nullable_colors)
for name in option_names:
defval = getattr(defaults, name)
if isinstance(defval, Color):
ans[name] = int(defval)
for name in special_colors:
ans[name] = getattr(defaults, name)
self.default_colors = ans
self.default_background_image_options: BackgroundImageOptions = {k: getattr(defaults, k) for k in BackgroundImageOptions.__optional_keys__} # type: ignore
return self.default_colors
def parse_colors(self, f: Iterable[str], background_image_options: BackgroundImageOptions | None = None) -> Colors:
# When parsing the theme file we first apply the default theme so that
# all colors are reset to default values first. This is needed for themes
# that don't specify all colors.
dc_spec = self.get_default_colors()
if background_image_options is not None and self.default_background_image_options:
background_image_options.update(self.default_background_image_options)
spec, tbc = parse_colors((f,), background_image_options)
ans = dc_spec.copy()
ans.update(spec)
return ans, (() if tbc is None else tbc)
def refresh(self) -> bool:
"Load new or modified theme files and forget deleted ones. Returns True if any theme changed."
changed = False
if config_dir_files_ignored():
return changed
present: set[ColorSchemes] = set()
try:
entries = list(os.scandir(config_dir))
except FileNotFoundError:
entries = []
for x in entries:
if (scheme := theme_file_schemes.get(x.name)) is None:
continue
theme = self.themes[scheme]
try:
mtime = x.stat().st_mtime_ns
if mtime > theme.mtime:
bgo: BackgroundImageOptions = {}
with open(x.path) as f:
spec, tbc = self.parse_colors(f, bgo)
self.themes[scheme] = AutoTheme(mtime, spec, tbc, bgo)
changed = True
except FileNotFoundError:
continue # deleted after the directory was scanned
present.add(scheme)
for scheme, theme in tuple(self.themes.items()):
if theme.mtime > -1 and scheme not in present:
self.themes[scheme] = AutoTheme()
if self.applied_theme == scheme:
self.applied_theme = ''
changed = True
return changed
@property
def has_applied_theme(self) -> bool:
return self.applied_theme != '' and self.themes[self.applied_theme].mtime > -1
@property
def has_dark_theme(self) -> bool:
return self.themes['dark'].mtime > -1
@property
def has_light_theme(self) -> bool:
return self.themes['light'].mtime > -1
@property
def has_no_preference_theme(self) -> bool:
return self.themes['no_preference'].mtime > -1
def patch_opts(self, opts: Options, debug_rendering: bool = False) -> None:
from .utils import log_error
if debug_rendering:
log_error('Querying system for current color scheme')
which = glfw_get_system_color_theme()
if debug_rendering:
log_error('Current system color scheme:', which)
theme = self.themes[which]
if theme.mtime > -1:
patch_options_with_color_spec(opts, theme.spec, theme.tbc, background_image_options=theme.background_image_options)
patch_global_colors(theme.spec, True)
self.applied_theme = which
if debug_rendering:
log_error(f'Applied {self.applied_theme} color theme')
def on_system_color_scheme_change(self, new_value: ColorSchemes, is_initial_value: bool = False) -> bool:
if is_initial_value:
return False
self.refresh()
return self.apply_theme(new_value)
def on_config_reload(self) -> None:
# Reloading the config resets colors to those from kitty.conf, so apply the
# theme for the current system color scheme, if any. Theme files are
# always re-read so that ones created or deleted since the last refresh
# are picked up.
self.refresh()
if not self.apply_theme(glfw_get_system_color_theme(), notify_on_bg_change=False):
self.applied_theme = ''
def apply_theme(self, new_value: ColorSchemes, notify_on_bg_change: bool = True) -> bool:
from .utils import log_error
theme = self.themes[new_value]
if theme.mtime < 0:
return False
patch_colors(theme.spec, theme.tbc, True, notify_on_bg_change=notify_on_bg_change, background_image_options=theme.background_image_options)
self.applied_theme = new_value
if get_boss().args.debug_rendering:
log_error(f'Applied color theme {new_value}')
return True
theme_colors = ThemeColors()
# The colors that can be set by a session color scheme, these are the colors
# the ssh kitten sets via escape codes for a color_scheme
session_color_scheme_keys = frozenset(('foreground', 'background', 'cursor', 'selection_foreground', 'selection_background')) | frozenset(
f'color{i}' for i in range(256)
)
color_schemes: dict[str, ColorSchemes] = {'dark': 'dark', 'light': 'light', 'no_preference': 'no_preference'}
ColorSchemeVariants = dict[ColorSchemes, ColorsSpec]
def parse_color_scheme_variants(data: object) -> ColorSchemeVariants:
"""
Parse untrusted color scheme variants of the form: {scheme: {color_name: 0xRRGGBB or None}}
where scheme is one of dark, light or no_preference. Raises ValueError if data is invalid.
"""
if not isinstance(data, dict):
raise ValueError('Color scheme variants must be a JSON object')
ans: ColorSchemeVariants = {}
for scheme, spec in data.items():
if (cs := color_schemes.get(scheme)) is None:
raise ValueError(f'Unknown color scheme: {scheme!r}')
if not isinstance(spec, dict):
raise ValueError(f'The colors for the {cs} color scheme must be a JSON object')
colors: ColorsSpec = {}
for name, val in spec.items():
if name not in session_color_scheme_keys:
raise ValueError(f'Unknown color in the {cs} color scheme: {name!r}')
if val is None:
if name not in nullable_colors:
raise ValueError(f'The color {name} in the {cs} color scheme cannot be null')
elif isinstance(val, bool) or not isinstance(val, int) or not 0 <= val <= 0xFFFFFF:
raise ValueError(f'The color {name} in the {cs} color scheme must be an integer from 0 to 0xffffff')
colors[name] = val
ans[cs] = colors
return ans
class SessionColorSchemes:
"""
The color schemes of sessions running in a window, such as from the ssh
kitten. Each session has variants for the dark, light and no preference
system color schemes and is associated with the depth of the color stack
when it was set, it is removed when the color stack is popped below that
depth. The variant matching the system color scheme of the innermost
session is applied to the session color layer of the window.
"""
def __init__(self) -> None:
self.sessions: list[tuple[int, ColorSchemeVariants]] = []
def __bool__(self) -> bool:
return bool(self.sessions)
def add(self, color_stack_depth: int, variants: ColorSchemeVariants) -> None:
self.sessions = [x for x in self.sessions if x[0] < color_stack_depth]
self.sessions.append((color_stack_depth, variants))
def color_stack_popped(self, color_stack_depth: int) -> bool:
before = len(self.sessions)
self.sessions = [x for x in self.sessions if x[0] <= color_stack_depth]
return len(self.sessions) != before
def clear(self) -> bool:
had_sessions = bool(self.sessions)
self.sessions = []
return had_sessions
def copy_from(self, other: 'SessionColorSchemes') -> None:
# The copy is not associated with any color stack entry in this window
self.sessions = [(0, other.sessions[-1][1])] if other.sessions else []
def apply(self, cp: ColorProfile, scheme: ColorSchemes) -> None:
cp.reset_layer(COLOR_LAYER_SESSION)
if self.sessions and (spec := self.sessions[-1][1].get(scheme)):
patch_color_profiles(spec, None, (cp,), COLOR_LAYER_SESSION)
@run_once
def all_color_related_conf_keys() -> frozenset[str]:
return all_colors | frozenset(BackgroundImageOptions.__optional_keys__) | frozenset({'transparent_background_colors'})
def parse_colors(
args: Iterable[str | Iterable[str]],
background_image_options: BackgroundImageOptions | None = None,
allow_reading_conf_files: bool = True,
) -> ParsedColors:
from kitty.options.parse import parse_conf_item
colors: dict[str, Color | None | int] = {}
nullable_color_map: dict[str, int | None] = {}
special_color_map: dict[str, int] = {}
transparent_background_colors: TransparentBackgroundColors | None = None
allowed = all_color_related_conf_keys()
for spec in args:
conf: dict[str, Any] = {}
if isinstance(spec, str):
k, sep, v = spec.partition('=')
if sep == '=':
k, v = k.strip(), v.strip()
if k in allowed:
parse_conf_item(k, v, conf)
elif allow_reading_conf_files:
with open(os.path.expanduser(spec), encoding='utf-8', errors='replace') as f:
conf = parse_config(f)
elif allow_reading_conf_files:
conf = parse_config(spec)
transparent_background_colors = conf.pop('transparent_background_colors', transparent_background_colors)
if background_image_options is not None:
bio: dict[str, Any] = cast(dict[str, Any], background_image_options)
for key in BackgroundImageOptions.__optional_keys__:
if key in conf:
bio[key] = conf[key]
colors.update(conf)
for k in nullable_colors:
q = colors.pop(k, False)
if q is not False:
val = int(q) if isinstance(q, Color) else None
nullable_color_map[k] = val
for k in special_colors:
sq = colors.pop(k, None)
if isinstance(sq, int):
special_color_map[k] = sq
ans: dict[str, int | None] = {k: int(v) for k, v in colors.items() if isinstance(v, Color)}
ans.update(nullable_color_map)
ans.update(special_color_map)
return ans, transparent_background_colors
def patch_options_with_color_spec(
opts: Options,
spec: ColorsSpec,
transparent_background_colors: TransparentBackgroundColors | None,
background_image_options: BackgroundImageOptions | None = None,
) -> None:
for k, v in spec.items():
if hasattr(opts, k):
if v is None:
if k in nullable_colors:
setattr(opts, k, None)
else:
if k in special_colors:
setattr(opts, k, v)
else:
setattr(opts, k, color_from_int(v))
if transparent_background_colors is not None:
opts.transparent_background_colors = transparent_background_colors
if background_image_options is not None:
for k, bv in background_image_options.items():
if hasattr(opts, k):
setattr(opts, k, bv)
def patch_colors(
spec: ColorsSpec,
transparent_background_colors: TransparentBackgroundColors | None = None,
configured: bool = False,
windows: Sequence[WindowType] | None = None,
notify_on_bg_change: bool = True,
background_image_options: BackgroundImageOptions | None = None,
replace_window_colors: bool = False,
) -> None:
# When configured is True the global configured colors are changed, colors
# set in individual windows, by launch --color or by programs running in
# them, are kept unless replace_window_colors is True. When configured is
# False, the colors are set as if by the programs running in the windows.
boss = get_boss()
opts = get_options()
if windows is None:
windows = tuple(boss.all_windows)
bg_colors_before = {w.id: w.screen.color_profile.default_bg for w in windows}
profiles = tuple(w.screen.color_profile for w in windows if w)
patch_color_profiles(spec, transparent_background_colors, profiles, COLOR_LAYER_GLOBAL if configured else COLOR_LAYER_OVERRIDE, replace_window_colors)
if configured:
patch_options_with_color_spec(opts, spec, transparent_background_colors, background_image_options)
os_window_ids = set()
for tm in get_boss().all_tab_managers:
tm.tab_bar.patch_colors(spec)
tm.tab_bar.layout()
tm.mark_tab_bar_dirty()
t = tm.active_tab
if t is not None:
t.relayout_borders()
os_window_ids.add(tm.os_window_id)
patch_global_colors(spec, configured) # changes macos_titlebar_color
for oswid in os_window_ids:
set_os_window_chrome(oswid)
default_bg_changed = 'background' in spec
notify_bg = notify_on_bg_change and default_bg_changed
boss = get_boss()
if background_image_options is not None:
bg = background_image_options.get('background_image')
boss.set_background_image(
bg[0] if bg else None,
tuple(os_window_ids),
configured,
layout=background_image_options.get('background_image_layout'),
linear_interpolation=background_image_options.get('background_image_linear'),
tint=background_image_options.get('background_tint'),
tint_gaps=background_image_options.get('background_tint_gaps'),
)
for w in windows:
if w:
if notify_bg and w.screen.color_profile.default_bg != bg_colors_before.get(w.id):
boss.default_bg_changed_for(w.id)
w.refresh()
View File
Whitespace-only changes.
+748
View File
@@ -0,0 +1,748 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import inspect
import os
import re
import textwrap
import types
from collections.abc import Callable, Iterator
from typing import Any, get_type_hints
from kitty.conf.types import Definition, MultiOption, Option, ParserFuncType, unset
from kitty.fast_data_types import NULL_COLOR_VALUE
from kitty.options.utils import parse_options_for_map
from kitty.simple_cli_definitions import serialize_as_go_string
def chunks[_T](lst: list[_T], n: int) -> Iterator[list[_T]]:
for i in range(0, len(lst), n):
yield lst[i : i + n]
def atoi(text: str) -> str:
return f'{int(text):08d}' if text.isdigit() else text
def natural_keys(text: str) -> tuple[str, ...]:
return tuple(atoi(c) for c in re.split(r'(\d+)', text))
def generate_class(defn: Definition, loc: str) -> tuple[str, str]:
class_lines: list[str] = []
tc_lines: list[str] = []
a = class_lines.append
t = tc_lines.append
a('class Options:')
t('class Parser:')
choices = {}
imports: set[tuple[str, str]] = set()
tc_imports: set[tuple[str, str]] = set()
ki_imports: 're.Pattern[str]' = re.compile(r'\b((?:kittens|kitty).+?)[,\]]')
def option_type_as_str(x: Any) -> str:
needs_import = False
if type(x) is type:
ans = x.__name__
needs_import = True
else:
ans = repr(x)
ans = ans.replace('NoneType', 'None')
if needs_import and getattr(x, '__module__', None) and x.__module__ not in ('builtins', 'typing'):
imports.add((x.__module__, x.__name__))
return ans
def option_type_data(option: Option | MultiOption) -> tuple[Callable[[Any], Any], str]:
func = option.parser_func
if func.__module__ == 'builtins':
return func, getattr(func, '__name__')
th = get_type_hints(func)
rettype = th['return']
typ = option_type_as_str(rettype)
if isinstance(option, MultiOption):
typ = typ[typ.index('[') + 1 : -1]
typ = typ.replace('tuple', 'dict', 1)
kq = ki_imports.search(typ)
if kq is not None:
kqi = kq.group(1)
kqim, kqii = kqi.rsplit('.', 1)
imports.add((kqim, ''))
return func, typ
is_mutiple_vars = {}
option_names = set()
color_table = list(map(str, range(256)))
choice_dedup: dict[str, str] = {}
choice_parser_dedup: dict[str, str] = {}
def parser_function_declaration(option_name: str) -> None:
t('')
t(f' def {option_name}(self, val: str, ans: dict[str, typing.Any]) -> None:')
for option in sorted(defn.iter_all_options(), key=lambda a: natural_keys(a.name)):
option_names.add(option.name)
parser_function_declaration(option.name)
if isinstance(option, MultiOption):
mval: dict[str, dict[str, Any]] = {'macos': {}, 'linux': {}, '': {}}
func, typ = option_type_data(option)
assert isinstance(func, types.FunctionType)
for val in option:
if val.add_to_default:
gr = mval[val.only]
for k, v in func(val.defval_as_str):
gr[k] = v
is_mutiple_vars[option.name] = typ, mval
sig = inspect.signature(func)
tc_imports.add((func.__module__, func.__name__))
if len(sig.parameters) == 1:
t(f' for k, v in {func.__name__}(val):')
t(f' ans["{option.name}"][k] = v')
else:
t(f' for k, v in {func.__name__}(val, ans["{option.name}"]):')
t(f' ans["{option.name}"][k] = v')
continue
if option.choices:
typ = 'typing.Literal[{}]'.format(', '.join(repr(x) for x in option.choices))
ename = f'choices_for_{option.name}'
if typ in choice_dedup:
typ = choice_dedup[typ]
else:
choice_dedup[typ] = ename
choices[ename] = typ
typ = ename
func = str
elif defn.has_color_table and option.is_color_table_color:
func, typ = option_type_data(option)
assert isinstance(func, types.FunctionType)
t(f' ans[{option.name!r}] = {func.__name__}(val)')
tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:])
if option.defval_as_string == 'none':
color_table[cnum] = f'0x{NULL_COLOR_VALUE:x}'
else:
color_table[cnum] = f'0x{func(option.defval_as_string).__int__():06x}'
continue
else:
func, typ = option_type_data(option)
try:
params = dict(inspect.signature(func).parameters)
except Exception:
params = {}
assert isinstance(func, types.FunctionType)
if 'dict_with_parse_results' in params:
t(f' {func.__name__}(val, ans)')
else:
t(f' ans[{option.name!r}] = {func.__name__}(val)')
if func.__module__ != 'builtins':
tc_imports.add((func.__module__, func.__name__))
defval_as_obj = func(option.defval_as_string)
if isinstance(defval_as_obj, frozenset):
defval = 'frozenset({' + ', '.join(repr(x) for x in sorted(defval_as_obj)) + '})'
else:
defval = repr(defval_as_obj)
if option.macos_defval is not unset:
md = repr(func(option.macos_defval))
defval = f'{md} if is_macos else {defval}'
imports.add(('kitty.constants', 'is_macos'))
a(f' {option.name}: {typ} = {defval}')
if option.choices:
ecname = f'choices_for_{option.name}'
crepr = f'frozenset({option.choices!r})'
if crepr in choice_parser_dedup:
crepr = choice_parser_dedup[crepr]
else:
choice_parser_dedup[crepr] = ecname
t(' val = val.lower()')
t(f' if val not in self.choices_for_{option.name}:')
t(f' raise ValueError(f"The value {{val}} is not a valid choice for {option.name}")')
t(f' ans["{option.name}"] = val')
t('')
t(f' {ecname} = {crepr}')
for option_name, (typ, mval) in is_mutiple_vars.items():
a(f' {option_name}: {typ} = {{}}')
for parser, aliases in defn.deprecations.items():
assert isinstance(parser, types.FunctionType)
for alias in aliases:
parser_function_declaration(alias)
tc_imports.add((parser.__module__, parser.__name__))
t(f' {parser.__name__}({alias!r}, val, ans)')
action_parsers = {}
def resolve_import(ftype: str) -> str:
if '.' in ftype:
fmod, ftype = ftype.rpartition('.')[::2]
else:
fmod = f'{loc}.options.utils'
imports.add((fmod, ftype))
return ftype
if loc == 'kitty':
imports.add(('kitty.options.utils', 'KeyFallbackType'))
for aname, action in defn.actions.items():
option_names.add(aname)
action_parsers[aname] = func = action.parser_func
assert isinstance(func, types.FunctionType)
th = get_type_hints(func)
rettype = th['return']
typ = option_type_as_str(rettype)
typ = typ[typ.index('[') + 1 : -1]
a(f' {aname}: list[{typ}] = []')
for imp in action.imports:
resolve_import(imp)
for fname, ftype in action.fields.items():
ftype = resolve_import(ftype)
fval = f'{ftype}()' if ftype == 'AliasMap' else '{}'
a(f' {fname}: {ftype} = {fval}')
parser_function_declaration(aname)
t(f' for k in {func.__name__}(val):')
t(f' ans[{aname!r}].append(k)')
tc_imports.add((func.__module__, func.__name__))
if defn.has_color_table:
imports.add(('array', 'array'))
a(' color_table: "array[int]" = array("L", (')
for grp in chunks(color_table, 8):
a(' ' + ', '.join(grp) + ',')
a(' ))')
a(' config_paths: tuple[str, ...] = ()')
a(' all_config_paths: tuple[str, ...] = ()')
a(' config_overrides: tuple[str, ...] = ()')
a('')
a(' def __init__(self, options_dict: dict[str, typing.Any] | None = None) -> None:')
if defn.has_color_table:
a(' self.color_table = array(self.color_table.typecode, self.color_table)')
a(' if options_dict is not None:')
a(' null = object()')
a(' for key in option_names:')
a(' val = options_dict.get(key, null)')
a(' if val is not null:')
a(' setattr(self, key, val)')
a('')
a(' @property')
a(' def _fields(self) -> tuple[str, ...]:')
a(' return option_names')
a('')
a(' def __iter__(self) -> typing.Iterator[str]:')
a(' return iter(self._fields)')
a('')
a(' def __len__(self) -> int:')
a(' return len(self._fields)')
a('')
a(' def _copy_of_val(self, name: str) -> typing.Any:')
a(' ans = getattr(self, name)')
a(' if isinstance(ans, dict):\n ans = ans.copy()')
a(' elif isinstance(ans, list):\n ans = ans[:]')
a(' return ans')
a('')
a(' def _asdict(self) -> dict[str, typing.Any]:')
a(' return {k: self._copy_of_val(k) for k in self}')
a('')
a(' def _replace(self, **kw: typing.Any) -> "Options":')
a(' ans = Options()')
a(' for name in self:')
a(' setattr(ans, name, self._copy_of_val(name))')
a(' for name, val in kw.items():')
a(' setattr(ans, name, val)')
a(' return ans')
a('')
a(' def __getitem__(self, key: int | str) -> typing.Any:')
a(' k = option_names[key] if isinstance(key, int) else key')
a(' try:')
a(' return getattr(self, k)')
a(' except AttributeError:')
a(' pass')
a(' raise KeyError(f"No option named: {k}")')
if defn.has_color_table:
a('')
a(' def __getattr__(self, key: str) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' x = self.color_table[k]')
a(f' if x == 0x{NULL_COLOR_VALUE:x}:')
a(' return None')
a(' return Color((x >> 16) & 255, (x >> 8) & 255, x & 255)')
a(' raise AttributeError(key)')
a('')
a(' def __setattr__(self, key: str, val: typing.Any) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' if val is None:')
a(f' self.color_table[k] = 0x{NULL_COLOR_VALUE:x}')
a(' else:')
a(' self.color_table[k] = int(val)')
a(' return')
a(' object.__setattr__(self, key, val)')
a('')
a('')
a('defaults = Options()')
a('')
for option_name, (typ, mval) in is_mutiple_vars.items():
a(f'defaults.{option_name} = {mval[""]!r}')
if mval['macos']:
imports.add(('kitty.constants', 'is_macos'))
a('if is_macos:')
a(f' defaults.{option_name}.update({mval["macos"]!r}')
if mval['macos']:
imports.add(('kitty.constants', 'is_macos'))
a('if not is_macos:')
a(f' defaults.{option_name}.update({mval["linux"]!r}')
a('')
for aname, func in action_parsers.items():
a(f'defaults.{aname} = [')
only: dict[str, list[tuple[str, Callable[..., Any]]]] = {}
for sc in defn.iter_all_maps(aname):
if not sc.add_to_default:
continue
text = sc.parseable_text
if sc.only:
only.setdefault(sc.only, []).append((text, func))
else:
for val in func(text):
a(f' # {sc.name}')
a(f' {val!r},')
a(']')
a('')
if only:
imports.add(('kitty.constants', 'is_macos'))
for cond, items in only.items():
cond = 'is_macos' if cond == 'macos' else 'not is_macos'
a(f'if {cond}:')
for text, parser_func in items:
for val in parser_func(text):
a(f' defaults.{aname}.append({val!r})')
a('')
t('')
t('')
t('def create_result_dict() -> dict[str, typing.Any]:')
t(' return {')
for oname in is_mutiple_vars:
t(f' {oname!r}: {{}},')
for aname in defn.actions:
t(f' {aname!r}: [],')
t(' }')
t('')
t('')
t(f'actions: frozenset[str] = frozenset({tuple(defn.actions)!r})')
t('')
t('')
t('def merge_result_dicts(defaults: dict[str, typing.Any], vals: dict[str, typing.Any]) -> dict[str, typing.Any]:')
t(' ans = {}')
t(' for k, v in defaults.items():')
t(' if isinstance(v, dict):')
t(' ans[k] = merge_dicts(v, vals.get(k, {}))')
t(' elif k in actions:')
t(' ans[k] = v + vals.get(k, [])')
t(' else:')
t(' ans[k] = vals.get(k, v)')
t(' return ans')
tc_imports.add(('kitty.conf.utils', 'merge_dicts'))
t('')
t('')
t('parser = Parser()')
t('')
t('')
t('def parse_conf_item(key: str, val: str, ans: dict[str, typing.Any]) -> bool:')
t(' func = getattr(parser, key, None)')
t(' if func is not None:')
t(' func(val, ans)')
t(' return True')
t(' return False')
preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append
def output_imports(imports: set[tuple[str, str]], add_module_imports: bool = True) -> None:
a('# isort: skip_file')
a('import typing')
a('import collections.abc # noqa: F401, RUF100')
seen_mods = {'typing'}
mmap: dict[str, list[str]] = {}
for mod, name in imports:
mmap.setdefault(mod, []).append(name)
for mod in sorted(mmap):
names = list(filter(None, sorted(mmap[mod])))
if names:
lines = textwrap.wrap(', '.join(names), 100)
if len(lines) == 1:
s = lines[0]
else:
s = '\n '.join(lines)
s = f'(\n {s}\n)'
a(f'from {mod} import {s}')
else:
s = ''
if add_module_imports and mod not in seen_mods and mod != s:
a(f'import {mod}')
seen_mods.add(mod)
output_imports(imports)
a('')
if choices:
for name, cdefn in choices.items():
a(f'{name} = {cdefn}')
a('')
a('option_names = (')
for option_name in sorted(option_names, key=natural_keys):
a(f' {option_name!r},')
a(')')
class_def = '\n'.join(preamble + ['', ''] + class_lines)
preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append
output_imports(tc_imports, False)
return class_def, '\n'.join(preamble + ['', ''] + tc_lines)
def generate_c_conversion(loc: str, ctypes: list[Option | MultiOption]) -> str:
lines: list[str] = []
basic_converters = {
'int': 'PyLong_AsLong',
'uint': 'PyLong_AsUnsignedLong',
'bool': 'PyObject_IsTrue',
'float': 'PyFloat_AsFloat',
'double': 'PyFloat_AsDouble',
'percent': 'percent',
'time': 'parse_s_double_to_monotonic_t',
'time-ms': 'parse_ms_long_to_monotonic_t',
}
for opt in ctypes:
lines.append('')
lines.append(f'static void\nconvert_from_python_{opt.name}(PyObject *val, Options *opts) {{')
is_special = opt.ctype.startswith('!')
if is_special:
func = opt.ctype[1:]
lines.append(f' {func}(val, opts);')
else:
func = basic_converters.get(opt.ctype, opt.ctype)
lines.append(f' opts->{opt.name} = {func}(val);')
lines.append('}')
lines.append('')
lines.append(f'static void\nconvert_from_opts_{opt.name}(PyObject *py_opts, Options *opts) {{')
lines.append(f' PyObject *ret = PyObject_GetAttrString(py_opts, "{opt.name}");')
lines.append(' if (ret == NULL) return;')
lines.append(f' convert_from_python_{opt.name}(ret, opts);')
lines.append(' Py_DECREF(ret);')
lines.append('}')
lines.append('')
lines.append('static bool\nconvert_opts_from_python_opts(PyObject *py_opts, Options *opts) {')
for opt in ctypes:
lines.append(f' convert_from_opts_{opt.name}(py_opts, opts);')
lines.append(' if (PyErr_Occurred()) return false;')
lines.append(' return true;')
lines.append('}')
preamble = ['// generated by gen-config.py DO NOT edit', '// vim:fileencoding=utf-8', '#pragma once', '#include "to-c.h"']
return '\n'.join(preamble + ['', ''] + lines)
def write_output(loc: str, defn: Definition, extra_after_type_defn: str = '') -> None:
cls, tc = generate_class(defn, loc)
ctypes = []
has_secret = []
for opt in defn.root_group.iter_all_non_groups():
if isinstance(opt, (Option, MultiOption)) and opt.ctype:
ctypes.append(opt)
if getattr(opt, 'has_secret', False):
has_secret.append(opt.name)
with open(os.path.join(*loc.split('.'), 'options', 'types.py'), 'w') as f:
f.write(f'{cls}\n')
f.write(extra_after_type_defn)
if has_secret:
f.write('\n\nsecret_options = ' + repr(tuple(has_secret)))
with open(os.path.join(*loc.split('.'), 'options', 'parse.py'), 'w') as f:
f.write(f'{tc}\n')
if ctypes:
c = generate_c_conversion(loc, ctypes)
with open(os.path.join(*loc.split('.'), 'options', 'to-c-generated.h'), 'w') as f:
f.write(f'{c}\n')
def go_type_data(parser_func: ParserFuncType, ctype: str, is_multiple: bool = False) -> tuple[str, str]:
if ctype or is_multiple:
if ctype in ('string', ''):
if is_multiple:
return 'string', '[]string{val}, nil'
return 'string', 'val, nil'
if ctype.startswith('strdict_'):
_, rsep, fsep = ctype.split('_', 2)
return 'map[string]string', f'config.ParseStrDict(val, `{rsep}`, `{fsep}`)'
return f'*{ctype}', f'Parse{ctype}(val)'
assert isinstance(parser_func, types.FunctionType)
p = parser_func.__name__
if p == 'int':
return 'int64', 'strconv.ParseInt(val, 10, 64)'
if p == 'str':
return 'string', 'val, nil'
if p == 'float':
return 'float64', 'strconv.ParseFloat(val, 10, 64)'
if p == 'to_bool':
return 'bool', 'config.StringToBool(val), nil'
if p == 'to_color':
return 'style.RGBA', 'style.ParseColor(val)'
if p == 'to_color_or_none':
return 'style.NullableColor', 'style.ParseColorOrNone(val)'
if p == 'positive_int':
return 'uint64', 'strconv.ParseUint(val, 10, 64)'
if p == 'positive_float':
return 'float64', 'config.PositiveFloat(val)'
if p == 'unit_float':
return 'float64', 'config.UnitFloat(val)'
if p == 'python_string':
return 'string', 'config.StringLiteral(val)'
th = get_type_hints(parser_func)
rettype = th['return']
return {int: 'int64', str: 'string', float: 'float64'}[rettype], f'{p}(val)'
mod_map = {
'shift': 'shift',
'⇧': 'shift',
'alt': 'alt',
'option': 'alt',
'opt': 'alt',
'⌥': 'alt',
'super': 'super',
'command': 'super',
'cmd': 'super',
'⌘': 'super',
'control': 'ctrl',
'ctrl': 'ctrl',
'⌃': 'ctrl',
'hyper': 'hyper',
'meta': 'meta',
'num_lock': 'num_lock',
'caps_lock': 'caps_lock',
}
def normalize_shortcut(spec: str) -> str:
if spec.endswith('+'):
spec = spec[:-1] + 'plus'
parts = spec.lower().split('+')
key = parts[-1]
if len(parts) == 1:
return key
mods = parts[:-1]
return '+'.join(mod_map.get(x, x) for x in mods) + '+' + key
def normalize_shortcuts(spec: str) -> Iterator[str]:
spec = spec.replace('++', '+plus')
spec = re.sub(r'([^+])>', '\\1\0', spec)
for x in spec.split('\0'):
yield normalize_shortcut(x)
def gen_go_code(defn: Definition) -> str:
lines = [
'import "fmt"',
'import "strconv"',
'import "github.com/kovidgoyal/kitty/tools/config"',
'import "github.com/kovidgoyal/kitty/tools/utils/style"',
'var _ = fmt.Println',
'var _ = config.StringToBool',
'var _ = strconv.Atoi',
'var _ = style.ParseColor',
]
a = lines.append
keyboard_shortcuts = tuple(defn.iter_all_maps())
choices = {}
go_types = {}
go_parsers = {}
defaults = {}
multiopts = {''}
for option in sorted(defn.iter_all_options(), key=lambda a: natural_keys(a.name)):
name = option.name.capitalize()
if isinstance(option, MultiOption):
go_types[name], go_parsers[name] = go_type_data(option.parser_func, option.ctype, True)
multiopts.add(name)
defval = []
for x in option.items:
if x.add_to_default:
defval.append(option.parser_func(x.defval_as_str))
defaults[name] = defval
else:
defaults[name] = option.parser_func(option.defval_as_string)
if option.choices:
choices[name] = option.choices
go_types[name] = f'{name}_Choice_Type'
go_parsers[name] = f'Parse_{name}(val)'
continue
go_types[name], go_parsers[name] = go_type_data(option.parser_func, option.ctype)
for oname in choices:
a(f'type {go_types[oname]} int')
a('type Config struct {')
for name, gotype in go_types.items():
if name in multiopts:
a(f'{name} []{gotype}')
else:
a(f'{name} {gotype}')
if keyboard_shortcuts:
a('KeyboardShortcuts []*config.KeyAction')
a('}')
def cval(x: str) -> str:
return x.replace('-', '_')
a('func NewConfig() *Config {')
a('return &Config{')
from kitty.fast_data_types import Color
def basic_defval(d: Any) -> str:
if isinstance(d, str):
dval = f'{name}_{cval(d)}' if name in choices else f'`{d}`'
elif isinstance(d, bool):
dval = repr(d).lower()
elif isinstance(d, dict):
dval = 'map[string]string{'
for k, v in d.items():
dval += f'"{serialize_as_go_string(k)}": "{serialize_as_go_string(v)}",'
dval += '}'
elif isinstance(d, list):
dval = '[]string{'
for k in d:
dval += f'"{serialize_as_go_string(k)}",'
dval += '}'
elif isinstance(d, Color):
dval = f'style.RGBA{{Red:{d.red}, Green: {d.green}, Blue: {d.blue}}}'
if 'NullableColor' in go_types[name]:
dval = f'style.NullableColor{{IsSet: true, Color:{dval}}}'
else:
dval = repr(d)
return dval
for name, pname in go_parsers.items():
d = defaults[name]
if d:
a(f'{name}: {basic_defval(d)},')
if keyboard_shortcuts:
a('KeyboardShortcuts: []*config.KeyAction{')
for sc in keyboard_shortcuts:
options, leftover = parse_options_for_map(sc.parseable_text)
allow_fallback = ','.join(x.value for x in options.allow_fallback)
key_spec, action = leftover.split(None, 1)
aname, _, aargs = action.partition(' ')
aname = serialize_as_go_string(aname)
aargs = serialize_as_go_string(aargs)
fb = f', AllowFallback: "{serialize_as_go_string(allow_fallback)}"'
a(f'{{Name: "{aname}", Args: "{aargs}"{fb}, Normalized_keys: []string{{')
ns = normalize_shortcuts(key_spec)
a(', '.join(f'"{serialize_as_go_string(x)}"' for x in ns) + ',')
a('}},')
a('},')
a('}}')
for oname, choice_vals in choices.items():
a('const (')
for i, c in enumerate(choice_vals):
c = cval(c)
if i == 0:
a(f'{oname}_{c} {oname}_Choice_Type = iota')
else:
a(f'{oname}_{c}')
a(')')
a(f'func (x {oname}_Choice_Type) String() string {{')
a('switch x {')
a('default: return ""')
for c in choice_vals:
a(f'case {oname}_{cval(c)}: return "{c}"')
a('}}')
a(f'func {go_parsers[oname].split("(")[0]}(val string) (ans {go_types[oname]}, err error) {{')
a('switch val {')
for c in choice_vals:
a(f'case "{c}": return {oname}_{cval(c)}, nil')
vals = ', '.join(choice_vals)
a(f'default: return ans, fmt.Errorf("%#v is not a valid value for %s. Valid values are: %s", val, "{c}", "{vals}")')
a('}}')
has_parsers = bool(go_parsers or keyboard_shortcuts)
a('func (c *Config) Parse(key, val string) (err error) {')
if has_parsers:
a('switch key {')
a('default: return fmt.Errorf("Unknown configuration key: %#v", key)')
for oname, pname in go_parsers.items():
ol = oname.lower()
is_multiple = oname in multiopts
a(f'case "{ol}":')
if is_multiple:
a(f'var temp_val []{go_types[oname]}')
else:
a(f'var temp_val {go_types[oname]}')
a(f'temp_val, err = {pname}')
a(f'if err != nil {{ return fmt.Errorf("Failed to parse {ol} = %#v with error: %w", val, err) }}')
if is_multiple:
a(f'c.{oname} = append(c.{oname}, temp_val...)')
else:
a(f'c.{oname} = temp_val')
if keyboard_shortcuts:
a('case "map":')
a('tempsc, err := config.ParseMap(val)')
a('if err != nil { return fmt.Errorf("Failed to parse map = %#v with error: %w", val, err) }')
a('c.KeyboardShortcuts = append(c.KeyboardShortcuts, tempsc)')
a('}')
a('return}')
else:
a('return fmt.Errorf("Unknown configuration key: %#v", key)')
a('}')
return '\n'.join(lines)
def main() -> None:
# To use run it as:
# kitty +runpy 'from kitty.conf.generate import main; main()' /path/to/kitten/file.py
import importlib
import sys
from kittens.runner import path_to_custom_kitten, resolved_kitten
from kitty.constants import config_dir
kitten = sys.argv[-1]
if not kitten.endswith('.py'):
kitten += '.py'
kitten = resolved_kitten(kitten)
path = os.path.realpath(path_to_custom_kitten(config_dir, kitten))
if not os.path.dirname(path):
raise SystemExit(f'No custom kitten named {kitten} found')
sys.path.insert(0, os.path.dirname(path))
package_name = os.path.basename(os.path.dirname(path))
m = importlib.import_module('kitten_options_definition')
defn = getattr(m, 'definition')
loc = package_name
cls, tc = generate_class(defn, loc)
with open(os.path.join(os.path.dirname(path), 'kitten_options_types.py'), 'w') as f:
f.write(f'{cls}\n')
with open(os.path.join(os.path.dirname(path), 'kitten_options_parse.py'), 'w') as f:
f.write(f'{tc}\n')
+781
View File
@@ -0,0 +1,781 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import builtins
import re
import textwrap
import typing
from collections.abc import Callable, Iterable, Iterator, Sequence
from functools import lru_cache
from importlib import import_module
from re import Match
from typing import Any, Optional, Union, cast
import kitty.conf.utils as generic_parsers
from kitty.constants import website_url
from kitty.types import run_once
if typing.TYPE_CHECKING:
Only = typing.Literal['macos', 'linux', '']
else:
Only = str
class Unset:
def __bool__(self) -> bool:
return False
unset = Unset()
ParserFuncType = Callable[[str], Any]
def expand_opt_references(conf_name: str, text: str) -> str:
conf_name += '.'
def expand(m: 'Match[str]') -> str:
ref = m.group(1)
if '<' not in ref and '.' not in ref:
# full ref
return f':opt:`{ref} <{conf_name}{ref}>`'
return str(m.group())
return re.sub(r':opt:`(.+?)`', expand, text)
@run_once
def ref_map() -> dict[str, dict[str, str]]:
import json
from ..fast_data_types import get_docs_ref_map
ans: dict[str, dict[str, str]] = json.loads(get_docs_ref_map())
return ans
def resolve_ref(ref: str, website_url: Callable[[str], str] = website_url) -> str:
m = ref_map()
href = m['ref'].get(ref, '')
prefix, rest = ref.partition('-')[::2]
if href:
pass
elif ref.startswith('conf-kitty-'):
href = f'conf#{ref}'
elif ref.startswith('conf-kitten-'):
parts = ref.split('-')
href = 'kittens/' + parts[2] + f'/#{ref}'
elif ref.startswith('at_'):
base = ref.split('_', 1)[1]
href = 'remote-control/#at-' + base.replace('_', '-')
elif ref.startswith('at-'):
base = ref.split('-', 1)[1]
href = 'remote-control/#at-' + base.replace('_', '-')
elif ref.startswith('action-group-'):
href = f'actions/#{ref}'
elif prefix == 'action':
href = f'actions/#{rest.replace("_", "-")}'
elif prefix in ('term', 'envvar'):
href = 'glossary/#' + ref
elif prefix == 'doc':
href = rest.lstrip('/')
elif prefix in ('issues', 'pull', 'discussions'):
t, num = ref.partition(':')[::2]
href = f'https://github.com/kovidgoyal/kitty/{prefix}/{rest}'
if not (href.startswith('https://') or href.startswith('http://')):
href = website_url(href)
return href
def remove_markup(text: str) -> str:
imap = {'iss': 'issues-', 'pull': 'pull-', 'disc': 'discussions-'}
def extract(m: 'Match[str]') -> tuple[str, str]:
parts = m.group(2).split('<')
t = parts[0].strip()
q = parts[-1].rstrip('>')
return t, q
def sub(m: 'Match[str]') -> str:
key = m.group(1)
if key in ('ref', 'iss', 'pull', 'disc'):
t, q = extract(m)
q = imap.get(key, '') + q
url = resolve_ref(q)
if not url:
raise KeyError(f'Failed to resolve :{m.group(1)}: {q}')
return f'{t} <{url}>'
if key == 'doc':
t, q = extract(m)
return f'{t} <{website_url(q)}>'
if key in ('term', 'option'):
t, _ = extract(m)
return t
if key in ('ac', 'opt'):
t, q = extract(m)
return f'{t} {q}' if q and q != t else t
if key == 'code':
return m.group(2).replace('\\\\', '\\')
return str(m.group(2))
return re.sub(r':([a-zA-Z0-9]+):`(.+?)`', sub, text, flags=re.DOTALL)
def strip_inline_literal(text: str) -> str:
return re.sub(r'``([^`]+)``', r'`\1`', text, flags=re.DOTALL)
def iter_blocks(lines: Iterable[str]) -> Iterator[tuple[list[str], int]]:
current_block: list[str] = []
prev_indent = 0
for line in lines:
indent_size = len(line) - len(line.lstrip())
if indent_size != prev_indent or not line:
if current_block:
yield current_block, prev_indent
current_block = []
prev_indent = indent_size
if not line:
yield [''], 100
else:
current_block.append(line)
if current_block:
yield current_block, indent_size
@lru_cache(maxsize=8)
def block_wrapper(comment_symbol: str) -> textwrap.TextWrapper:
return textwrap.TextWrapper(initial_indent=comment_symbol, subsequent_indent=comment_symbol, width=70, break_long_words=False)
def wrapped_block(lines: Iterable[str], comment_symbol: str = '#: ') -> Iterator[str]:
wrapper = block_wrapper(comment_symbol)
for block, indent_size in iter_blocks(lines):
if indent_size > 0:
for line in block:
if not line:
yield line
else:
yield comment_symbol + line
else:
for line in wrapper.wrap('\n'.join(block)):
yield line
def render_block(text: str, comment_symbol: str = '#: ') -> str:
text = remove_markup(text)
text = strip_inline_literal(text)
lines = text.splitlines()
return '\n'.join(wrapped_block(lines, comment_symbol))
class CoalescedIteratorData:
option_groups: dict[int, list['Option']] = {}
action_groups: dict[str, list['Mapping']] = {}
coalesced: set[int] = set()
initialized: bool = False
kitty_mod: str = 'kitty_mod'
def initialize(self, root: 'Group') -> None:
if self.initialized:
return
self.root = root
option_groups = self.option_groups = {}
current_group: list[Option] = []
action_groups: dict[str, list[Mapping]] = {}
self.action_groups = action_groups
coalesced = self.coalesced = set()
self.kitty_mod = 'kitty_mod'
for item in root.iter_all_non_groups():
if isinstance(item, Option):
if item.name == 'kitty_mod':
self.kitty_mod = item.defval_as_string
if current_group:
if item.needs_coalescing:
current_group.append(item)
coalesced.add(id(item))
continue
option_groups[id(current_group[0])] = current_group[1:]
current_group = [item]
else:
current_group.append(item)
elif isinstance(item, Mapping):
if item.name in action_groups:
coalesced.add(id(item))
action_groups[item.name].append(item)
else:
action_groups[item.name] = []
if current_group:
option_groups[id(current_group[0])] = current_group[1:]
def option_group_for_option(self, opt: 'Option') -> list['Option']:
return self.option_groups.get(id(opt), [])
def action_group_for_action(self, ac: 'Mapping') -> list['Mapping']:
return self.action_groups.get(ac.name, [])
class Option:
def __init__(
self,
name: str,
defval: str,
macos_default: Unset | str,
parser_func: ParserFuncType,
long_text: str,
documented: bool,
group: 'Group',
choices: tuple[str, ...],
ctype: str,
has_secret: bool = False,
):
self.name = name
self.ctype = ctype
self.defval_as_string = defval
self.macos_defval = macos_default
self.long_text = long_text
self.documented = documented
self.group = group
self.parser_func = parser_func
self.choices = choices
self.has_secret = has_secret
@property
def needs_coalescing(self) -> bool:
return self.documented and not self.long_text
@property
def is_color_table_color(self) -> bool:
return self.name.startswith('color') and self.name[5:].isdigit()
def as_conf(self, commented: bool = False, level: int = 0, option_group: Sequence['Option'] = ()) -> list[str]:
ans: list[str] = []
a = ans.append
if not self.documented:
return ans
if option_group:
sz = max(len(self.name), max(len(o.name) for o in option_group))
a(f'{self.name.ljust(sz)} {self.defval_as_string}'.rstrip())
for o in option_group:
a(f'{o.name.ljust(sz)} {o.defval_as_string}'.rstrip())
else:
a(f'{self.name} {self.defval_as_string}'.rstrip())
if self.long_text:
a('')
a(render_block(self.long_text))
a('')
return ans
def as_rst(
self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0, option_group: Sequence['Option'] = ()
) -> list[str]:
ans: list[str] = []
a = ans.append
if not self.documented:
return ans
mopts = [self] + list(option_group)
a('.. opt:: ' + ', '.join(f'{conf_name}.{mo.name}' for mo in mopts))
if any(mo.defval_as_string for mo in mopts):
a('.. code-block:: conf')
a('')
sz = max(len(x.name) for x in mopts)
for mo in mopts:
a((' {:%ds} {}' % sz).format(mo.name, mo.defval_as_string))
a('')
if self.long_text:
a(expand_opt_references(conf_name, self.long_text))
a('')
return ans
class MultiVal:
def __init__(self, val_as_str: str, add_to_default: bool, documented: bool, only: Only) -> None:
self.defval_as_str = val_as_str
self.documented = documented
self.only = only
self.add_to_default = add_to_default
class MultiOption:
def __init__(self, name: str, parser_func: ParserFuncType, long_text: str, group: 'Group', ctype: str, has_secret: bool = False):
self.name = name
self.ctype = ctype
self.parser_func = parser_func
self.long_text = long_text
self.group = group
self.has_secret = has_secret
self.items: list[MultiVal] = []
def add_value(self, val_as_str: str, add_to_default: bool, documented: bool, only: Only) -> None:
self.items.append(MultiVal(val_as_str, add_to_default, documented, only))
def __iter__(self) -> Iterator[MultiVal]:
yield from self.items
def as_conf(self, commented: bool = False, level: int = 0) -> list[str]:
ans: list[str] = []
a = ans.append
documented = False
for k in self.items:
if k.documented:
documented = True
if k.add_to_default:
a(f'{self.name} {k.defval_as_str}'.rstrip())
else:
# Comment out multi-options that have no default values
a(f'# {self.name}'.rstrip())
if not k.add_to_default and k.defval_as_str:
a('')
a(f'#: E.g. {self.name} {k.defval_as_str}'.rstrip())
if self.long_text and documented:
a('')
a(render_block(self.long_text))
a('')
return ans
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0) -> list[str]:
ans: list[str] = []
a = ans.append
a(f'.. opt:: {conf_name}.{self.name}')
documented = tuple(x for x in self.items if x.documented)
if any(k.defval_as_str for k in documented):
defaults = tuple(x for x in documented if x.add_to_default)
if defaults:
a('.. code-block:: conf')
a('')
for k in defaults:
a(f' {self.name:s} {k.defval_as_str}'.rstrip())
else:
a('')
a('Has no default values. Example values are shown below:')
a('')
a('.. code-block:: conf')
a('')
for k in self.items:
a(f' {self.name:s} {k.defval_as_str}'.rstrip())
a('')
if self.long_text:
a(expand_opt_references(conf_name, self.long_text))
a('')
return ans
class Mapping:
add_to_default: bool
short_text: str
long_text: str
documented: bool
setting_name: str
name: str
only: Only
@property
def parseable_text(self) -> str:
return ''
@property
def key_text(self) -> str:
return ''
def as_conf(self, commented: bool = False, level: int = 0, action_group: list['Mapping'] = []) -> list[str]:
ans: list[str] = []
if not self.documented:
return ans
a = ans.append
if self.short_text:
a(render_block(self.short_text.strip())), a('')
for sc in [self] + action_group:
if sc.documented:
prefix = '' if sc.add_to_default else '#:: E.g. '
a(f'{prefix}{sc.setting_name} {sc.parseable_text}')
if self.long_text:
a(''), a(render_block(self.long_text.strip(), '#:: '))
a('')
return ans
def as_rst(
self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str, level: int = 0, action_group: list['Mapping'] = []
) -> list[str]:
ans: list[str] = []
a = ans.append
if not self.documented:
return ans
if not self.short_text:
raise ValueError(f'The shortcut for {self.name} has no short_text')
sc_text = f'{conf_name}.{self.short_text}'
shortcut_slugs[f'{conf_name}.{self.name}'] = (sc_text, self.key_text.replace('kitty_mod', kitty_mod))
a(f'.. shortcut:: {sc_text}')
block_started = False
for sc in [self] + action_group:
if sc.add_to_default and sc.documented:
if not block_started:
a('.. code-block:: conf')
a('')
block_started = True
suffix = ''
if sc.only == 'macos':
suffix = ' 🍎'
elif sc.only == 'linux':
suffix = ' 🐧'
a(f' {sc.setting_name} {sc.parseable_text.replace("kitty_mod", kitty_mod)}{suffix}')
a('')
if self.long_text:
a('')
a(expand_opt_references(conf_name, self.long_text))
a('')
return ans
class ShortcutMapping(Mapping):
setting_name: str = 'map'
def __init__(
self,
name: str,
raw_definition: str,
short_text: str,
long_text: str,
add_to_default: bool,
documented: bool,
group: 'Group',
only: Only,
):
self.name = name
self.only = only
self._raw_definition = raw_definition
self.short_text = short_text
self.long_text = long_text
self.documented = documented
self.add_to_default = add_to_default
self.group = group
from kitty.options.utils import parse_options_for_map
_, remainder = parse_options_for_map(raw_definition)
parts = remainder.split(maxsplit=1)
self.key = parts[0]
self.action_def = parts[1] if len(parts) > 1 else ''
@property
def parseable_text(self) -> str:
return self._raw_definition
@property
def key_text(self) -> str:
return self.key
class MouseMapping(Mapping):
setting_name: str = 'mouse_map'
def __init__(
self,
name: str,
button: str,
event: str,
modes: str,
action_def: str,
short_text: str,
long_text: str,
add_to_default: bool,
documented: bool,
group: 'Group',
only: Only,
):
self.name = name
self.only = only
self.button = button
self.event = event
self.modes = modes
self.action_def = action_def
self.short_text = short_text
self.long_text = long_text
self.documented = documented
self.add_to_default = add_to_default
self.group = group
@property
def parseable_text(self) -> str:
return f'{self.button} {self.event} {self.modes} {self.action_def}'
@property
def key_text(self) -> str:
return self.button
NonGroups = Union[Option, MultiOption, ShortcutMapping, MouseMapping]
GroupItem = Union[NonGroups, 'Group']
class Group:
def __init__(self, name: str, title: str, coalesced_iterator_data: CoalescedIteratorData, start_text: str = '', parent: Optional['Group'] = None):
self.name = name
self.coalesced_iterator_data = coalesced_iterator_data
self.title = title
self.start_text = start_text
self.end_text = ''
self.items: list[GroupItem] = []
self.parent = parent
def append(self, item: GroupItem) -> None:
self.items.append(item)
def __iter__(self) -> Iterator[GroupItem]:
return iter(self.items)
def __len__(self) -> int:
return len(self.items)
def iter_with_coalesced_options(self) -> Iterator[GroupItem]:
for item in self:
if id(item) not in self.coalesced_iterator_data.coalesced:
yield item
def iter_all(self) -> Iterator[GroupItem]:
for x in self:
yield x
if isinstance(x, Group):
yield from x.iter_all()
def iter_all_non_groups(self) -> Iterator[NonGroups]:
for x in self:
if isinstance(x, Group):
yield from x.iter_all_non_groups()
else:
yield x
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]], kitty_mod: str = 'kitty_mod', level: int = 0) -> list[str]:
ans: list[str] = []
a = ans.append
if level:
a('')
a(f'.. _conf-{conf_name}-{self.name}:')
a('')
a(self.title)
heading_level = '+' if level > 1 else '-'
a(heading_level * (len(self.title) + 20))
a('')
if self.start_text:
a(self.start_text)
a('')
else:
ans.extend(('.. default-domain:: conf', ''))
kitty_mod = self.coalesced_iterator_data.kitty_mod
for item in self.iter_with_coalesced_options():
if isinstance(item, Option):
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, option_group=self.coalesced_iterator_data.option_group_for_option(item))
elif isinstance(item, Mapping):
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, level + 1, action_group=self.coalesced_iterator_data.action_group_for_action(item))
else:
lines = item.as_rst(conf_name, shortcut_slugs, kitty_mod, level + 1)
ans.extend(lines)
if level:
if self.end_text:
a('')
a(self.end_text)
return ans
def as_conf(self, commented: bool = False, level: int = 0) -> list[str]:
ans: list[str] = []
a = ans.append
if level:
a('#: ' + self.title + ' {{{')
a('')
if self.start_text:
a(render_block(self.start_text))
a('')
else:
ans.extend(('# vim:fileencoding=utf-8:foldmethod=marker', ''))
for item in self.iter_with_coalesced_options():
if isinstance(item, Option):
lines = item.as_conf(option_group=self.coalesced_iterator_data.option_group_for_option(item))
elif isinstance(item, Mapping):
lines = item.as_conf(commented, level + 1, action_group=self.coalesced_iterator_data.action_group_for_action(item))
else:
lines = item.as_conf(commented, level + 1)
ans.extend(lines)
if level:
if self.end_text:
a('')
a(render_block(self.end_text))
a('#: }}}')
a('')
else:
map_groups = []
start: int | None = None
count: int | None = None
for i, line in enumerate(ans):
if line.startswith('map ') or line.startswith('mouse_map '):
if start is None:
start = i
count = 1
else:
if count is not None:
count += 1
else:
if start is not None and count is not None:
map_groups.append((start, count))
start = count = None
for start, count in map_groups:
r = range(start, start + count)
sz = max(len(ans[i].split(' ', 3)[1]) for i in r)
for i in r:
line = ans[i]
parts = line.split(' ', 3)
parts[1] = parts[1].ljust(sz)
ans[i] = ' '.join(parts)
if commented:
ans = [x if x.startswith('#') or not x.strip() else (f'# {x}') for x in ans]
else:
# Comment out any invalid options that have no value
ans = [f'# {x}' if not x.startswith('#') and len(x.strip().split()) == 1 else x for x in ans]
return ans
def resolve_import(name: str, module: Any = None) -> ParserFuncType:
ans = None
if name.count('.') > 1:
m = import_module(name.rpartition('.')[0])
ans = getattr(m, name.rpartition('.')[2])
else:
ans = getattr(builtins, name, None)
if not callable(ans):
ans = getattr(generic_parsers, name, None)
if not callable(ans):
ans = getattr(module, name)
if not callable(ans):
raise TypeError(f'{name} is not a function')
return cast(ParserFuncType, ans)
class Action:
def __init__(self, name: str, option_type: str, fields: dict[str, str], imports: Iterable[str]):
self.name = name
self._parser_func = option_type
self.fields = fields
self.imports = frozenset(imports)
def resolve_imports(self, module: Any) -> 'Action':
self.parser_func = resolve_import(self._parser_func, module)
return self
class Definition:
def __init__(self, package: str, *actions: Action, has_color_table: bool = False) -> None:
if package.startswith('!'):
self.module_for_parsers = import_module(package[1:])
else:
self.module_for_parsers = import_module(f'{package}.options.utils')
self.has_color_table = has_color_table
self.coalesced_iterator_data = CoalescedIteratorData()
self.root_group = Group('', '', self.coalesced_iterator_data)
self.current_group = self.root_group
self.option_map: dict[str, Option] = {}
self.multi_option_map: dict[str, MultiOption] = {}
self.shortcut_map: dict[str, list[ShortcutMapping]] = {}
self.mouse_map: dict[str, list[MouseMapping]] = {}
self.actions = {a.name: a.resolve_imports(self.module_for_parsers) for a in actions}
self.deprecations: dict[ParserFuncType, tuple[str, ...]] = {}
def iter_all_non_groups(self) -> Iterator[NonGroups]:
yield from self.root_group.iter_all_non_groups()
def iter_all_options(self) -> Iterator[Option | MultiOption]:
for x in self.iter_all_non_groups():
if isinstance(x, (Option, MultiOption)):
yield x
def iter_all_maps(self, which: str = 'map') -> Iterator[ShortcutMapping | MouseMapping]:
for x in self.iter_all_non_groups():
if isinstance(x, ShortcutMapping) and which in ('map', '*'):
yield x
elif isinstance(x, MouseMapping) and which in ('mouse_map', '*'):
yield x
def parser_func(self, name: str) -> ParserFuncType:
ans = getattr(builtins, name, None)
if callable(ans):
return cast(ParserFuncType, ans)
ans = getattr(generic_parsers, name, None)
if callable(ans):
return cast(ParserFuncType, ans)
ans = getattr(self.module_for_parsers, name)
if not callable(ans):
raise TypeError(f'{name} is not a function')
return cast(ParserFuncType, ans)
def add_group(self, name: str, title: str = '', start_text: str = '') -> None:
self.current_group = Group(name, title or name, self.coalesced_iterator_data, start_text.strip(), self.current_group)
if self.current_group.parent is not None:
self.current_group.parent.append(self.current_group)
def end_group(self, end_text: str = '') -> None:
self.current_group.end_text = end_text.strip()
if self.current_group.parent is not None:
self.current_group = self.current_group.parent
def add_option(
self,
name: str,
defval: str | float | int | bool,
option_type: str = 'str',
long_text: str = '',
documented: bool = True,
add_to_default: bool = False,
only: Only = '',
macos_default: Unset | str = unset,
choices: tuple[str, ...] = (),
ctype: str = '',
has_secret: bool = False,
) -> None:
if isinstance(defval, bool):
defval = 'yes' if defval else 'no'
else:
defval = str(defval)
is_multiple = name.startswith('+')
long_text = long_text.strip()
if is_multiple:
name = name[1:]
if macos_default is not unset:
raise TypeError(f'Cannot specify macos_default for is_multiple option: {name} use only instead')
is_new = name not in self.multi_option_map
if is_new:
self.multi_option_map[name] = MultiOption(name, self.parser_func(option_type), long_text, self.current_group, ctype, has_secret)
mopt = self.multi_option_map[name]
if is_new:
self.current_group.append(mopt)
mopt.add_value(defval, add_to_default, documented, only)
return
opt = Option(name, defval, macos_default, self.parser_func(option_type), long_text, documented, self.current_group, choices, ctype, has_secret)
self.current_group.append(opt)
self.option_map[name] = opt
def add_map(self, short_text: str, defn: str, long_text: str = '', add_to_default: bool = True, documented: bool = True, only: Only = '') -> None:
name, rest = defn.split(maxsplit=1)
sc = ShortcutMapping(name, rest, short_text, long_text.strip(), add_to_default, documented, self.current_group, only)
self.current_group.append(sc)
self.shortcut_map.setdefault(name, []).append(sc)
def add_mouse_map(self, short_text: str, defn: str, long_text: str = '', add_to_default: bool = True, documented: bool = True, only: Only = '') -> None:
name, button, event, modes, action_def = defn.split(maxsplit=4)
mm = MouseMapping(name, button, event, modes, action_def, short_text, long_text.strip(), add_to_default, documented, self.current_group, only)
self.current_group.append(mm)
self.mouse_map.setdefault(name, []).append(mm)
def add_deprecation(self, parser_name: str, *aliases: str) -> None:
self.deprecations[self.parser_func(parser_name)] = aliases
def as_conf(self, commented: bool = False) -> list[str]:
self.coalesced_iterator_data.initialize(self.root_group)
return self.root_group.as_conf(commented)
def as_rst(self, conf_name: str, shortcut_slugs: dict[str, tuple[str, str]]) -> list[str]:
self.coalesced_iterator_data.initialize(self.root_group)
return self.root_group.as_rst(conf_name, shortcut_slugs)
+574
View File
@@ -0,0 +1,574 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import sys
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
from contextlib import contextmanager
from typing import (
Any,
Generic,
Literal,
NamedTuple,
TypeVar,
)
from ..constants import _plat, is_macos
from ..fast_data_types import Color
from ..rgb import to_color as as_color
from ..types import ConvertibleToNumbers, ParsedShortcut, run_once
from ..typing_compat import Protocol
from ..utils import expandvars, log_error, shlex_split
key_pat = re.compile(r'([a-zA-Z][a-zA-Z0-9_-]*)\s+(.+)$')
number_unit_pat = re.compile(r'\s*([-+]?\d+\.?\d*)\s*([^\d\s]*)?')
ItemParser = Callable[[str, str, dict[str, Any]], bool]
T = TypeVar('T')
class OptionsProtocol(Protocol):
def _asdict(self) -> dict[str, Any]:
pass
class BadLine(NamedTuple):
number: int
line: str
exception: Exception
file: str
def positive_int(x: ConvertibleToNumbers) -> int:
return max(0, int(x))
def positive_float(x: ConvertibleToNumbers) -> float:
return max(0, float(x))
def percent(x: str) -> float:
return float(x.rstrip('%')) / 100.0
def to_color(x: str) -> Color:
ans = as_color(x, validate=True)
if ans is None: # this is only for type-checking
ans = Color(0, 0, 0)
return ans
def to_color_or_none(x: str) -> Color | None:
return None if x.lower() == 'none' else to_color(x)
def unit_float(x: ConvertibleToNumbers) -> float:
return max(0, min(float(x), 1))
def signed_unit_float(x: ConvertibleToNumbers) -> float:
return max(-1, min(float(x), 1))
def number_with_unit(x: str, default_unit: str, *extra_units: str) -> tuple[float, str]:
if (mat := number_unit_pat.match(x)) is not None:
try:
value = float(mat.group(1))
except Exception as e:
raise ValueError(f'Not a number: {x} with error: {e}')
unit = mat.group(2) or default_unit
if unit != default_unit and unit not in extra_units:
raise ValueError(f'Not a valid unit: {x}. Allowed units are: {default_unit}, {", ".join(extra_units)}')
return value, unit
raise ValueError(f'Invalid number with unit: {x}')
def to_bool(x: str) -> bool:
return x.lower() in ('y', 'yes', 'true')
class ToCmdline:
def __init__(self) -> None:
self.override_env: dict[str, str] | None = None
def __enter__(self) -> 'ToCmdline':
return self
def __exit__(self, *a: Any) -> None:
self.override_env = None
def filter_env_vars(self, *a: str, **override: str) -> 'ToCmdline':
remove = frozenset(a)
self.override_env = {k: v for k, v in os.environ.items() if k not in remove}
self.override_env.update(override)
return self
def __call__(self, x: str, expand: bool = True) -> list[str]:
if expand:
ans = list(
map(
lambda y: expandvars(os.path.expanduser(y), os.environ if self.override_env is None else self.override_env, fallback_to_os_env=False),
shlex_split(x),
)
)
else:
ans = list(shlex_split(x))
return ans
to_cmdline_implementation = ToCmdline()
def to_cmdline(x: str, expand: bool = True) -> list[str]:
return to_cmdline_implementation(x, expand)
def python_string(text: str) -> str:
from ast import literal_eval
text = (text[:-1] + "\\'") if text.endswith("'") else text
ans: str = literal_eval("'''" + text.replace("'''", "'\\''") + "'''")
return ans
class Choice:
def __init__(self, choices: Sequence[str]):
self.defval = choices[0]
self.all_choices = frozenset(choices)
def __call__(self, x: str) -> str:
x = x.lower()
if x not in self.all_choices:
raise ValueError(f'The value {x} is not a known choice')
return x
def choices(*choices: str) -> Choice:
return Choice(choices)
class CurrentlyParsing:
__slots__ = 'line', 'number', 'file'
def __init__(self, line: str = '', number: int = -1, file: str = ''):
self.line = line
self.number = number
self.file = file
def __copy__(self) -> 'CurrentlyParsing':
return CurrentlyParsing(self.line, self.number, self.file)
@contextmanager
def set_line(self, line: str, number: int) -> Generator['CurrentlyParsing', None, None]:
orig = self.line, self.number
self.line = line
self.number = number
try:
yield self
finally:
self.line, self.number = orig
@contextmanager
def set_file(self, file: str) -> Generator['CurrentlyParsing', None, None]:
orig = self.file
self.file = file
try:
yield self
finally:
self.file = orig
currently_parsing = CurrentlyParsing()
OSNames = Literal['macos', 'bsd', 'linux', 'unknown']
@run_once
def os_name() -> OSNames:
if is_macos:
return 'macos'
if 'bsd' in _plat:
return 'bsd'
if 'linux' in _plat:
return 'linux'
return 'unknown'
class NamedLineIterator:
def __init__(self, name: str, lines: Iterator[str]):
self.lines = lines
self.name = name
def __iter__(self) -> Iterator[str]:
return self.lines
class GenincludeError(Exception): ...
def pygeninclude(path: str) -> list[str]:
import io
import runpy
before = sys.stdout
buf = sys.stdout = io.StringIO()
try:
runpy.run_path(path, run_name='__main__')
except FileNotFoundError:
raise
except Exception:
import traceback
tb = traceback.format_exc()
raise GenincludeError(f'Running the geninclude program: {path} failed with the error:\n{tb}')
finally:
sys.stdout = before
return buf.getvalue().splitlines()
def geninclude(path: str) -> list[str]:
old = os.environ.get('KITTY_OS')
os.environ['KITTY_OS'] = os_name()
try:
if path.endswith('.py'):
return pygeninclude(path)
import subprocess
cp = subprocess.run([path], capture_output=True, text=True)
if cp.returncode != 0:
raise GenincludeError(f'Running the geninclude program: {path} failed with exit code: {cp.returncode} and STDERR:\n{cp.stderr}')
return cp.stdout.splitlines()
finally:
if old is None:
os.environ.pop('KITTY_OS', None)
else:
os.environ['KITTY_OS'] = old
include_keys = 'include', 'globinclude', 'envinclude', 'geninclude'
class RecursiveInclude(Exception):
pass
class Memory:
def __init__(self, accumulate_bad_lines: list[BadLine] | None) -> None:
self.s: set[str] = set()
if accumulate_bad_lines is None:
accumulate_bad_lines = []
self.accumulate_bad_lines = accumulate_bad_lines
def seen(self, path: str) -> bool:
key = os.path.normpath(path)
if key in self.s:
self.accumulate_bad_lines.append(
BadLine(
currently_parsing.number,
currently_parsing.line.rstrip(),
RecursiveInclude(f'The file {path} has already been included, ignoring'),
currently_parsing.file,
)
)
return True
self.s.add(key)
return False
def parse_line(
line: str,
parse_conf_item: ItemParser,
ans: dict[str, Any],
base_path_for_includes: str,
effective_config_lines: Callable[[str, str], None],
memory: Memory,
accumulate_bad_lines: list[BadLine] | None = None,
allow_geninclude: bool = True,
) -> None:
line = line.strip()
if not line or line.startswith('#'):
return
m = key_pat.match(line)
if m is None:
log_error(f'Ignoring invalid config line: {line!r}')
return
key, val = m.groups()
if key.endswith('include') and key in include_keys:
val = expandvars(os.path.expanduser(val.strip()), {'KITTY_OS': os_name()})
if key == 'globinclude':
from pathlib import Path
vals = tuple(map(lambda x: str(os.fspath(x)), sorted(Path(base_path_for_includes).glob(val))))
elif key == 'envinclude':
from fnmatch import fnmatchcase
for x in os.environ:
if fnmatchcase(x, val):
with currently_parsing.set_file(f'<env var: {x}>'):
_parse(
NamedLineIterator(os.path.join(base_path_for_includes, ''), iter(os.environ[x].splitlines())),
parse_conf_item,
ans,
memory,
accumulate_bad_lines,
effective_config_lines,
allow_geninclude=allow_geninclude,
)
return
elif key == 'geninclude':
if not allow_geninclude:
log_error('Ignoring geninclude directive for security')
return
if not os.path.isabs(val):
val = os.path.join(base_path_for_includes, val)
if not memory.seen(val):
try:
lines = geninclude(val)
except FileNotFoundError as e:
if e.filename == val:
log_error(f'Could not find the geninclude file: {val}, ignoring')
else:
raise
else:
with currently_parsing.set_file(f'<get: {val}>'):
_parse(
NamedLineIterator(os.path.join(base_path_for_includes, ''), iter(lines)),
parse_conf_item,
ans,
memory,
accumulate_bad_lines,
effective_config_lines,
allow_geninclude=allow_geninclude,
)
return
else:
if not os.path.isabs(val):
val = os.path.join(base_path_for_includes, val)
vals = (val,)
for val in vals:
if memory.seen(val):
continue
try:
with open(val, encoding='utf-8', errors='replace') as include:
with currently_parsing.set_file(val):
_parse(include, parse_conf_item, ans, memory, accumulate_bad_lines, effective_config_lines, allow_geninclude=allow_geninclude)
except FileNotFoundError:
log_error(f'Could not find included config file: {val}, ignoring')
except OSError:
log_error('Could not read from included config file: {}, ignoring'.format(val))
return
if parse_conf_item(key, val, ans):
effective_config_lines(key, line)
else:
log_error(f'Ignoring unknown config key: {key}')
def _parse(
lines: Iterable[str],
parse_conf_item: ItemParser,
ans: dict[str, Any],
memory: Memory,
accumulate_bad_lines: list[BadLine] | None = None,
effective_config_lines: Callable[[str, str], None] | None = None,
allow_geninclude: bool = True,
) -> None:
name = getattr(lines, 'name', None)
effective_config_lines = effective_config_lines or (lambda a, b: None)
if name:
base_path_for_includes = os.path.abspath(name) if name.endswith(os.path.sep) else os.path.dirname(os.path.abspath(name))
else:
from ..constants import config_dir
base_path_for_includes = config_dir
it = iter(lines)
line = ''
next_line: str = ''
next_line_num = 0
while True:
try:
if next_line:
line = next_line
else:
line = next(it).lstrip()
next_line_num += 1
line_num = next_line_num
try:
next_line = next(it).lstrip()
next_line_num += 1
while next_line.startswith('\\'):
line = line.rstrip('\n') + next_line[1:]
try:
next_line = next(it).lstrip()
next_line_num += 1
except StopIteration:
next_line = ''
break
except StopIteration:
next_line = ''
try:
with currently_parsing.set_line(line, line_num):
parse_line(line, parse_conf_item, ans, base_path_for_includes, effective_config_lines, memory, accumulate_bad_lines, allow_geninclude)
except Exception as e:
if accumulate_bad_lines is None:
raise
accumulate_bad_lines.append(BadLine(line_num, line.rstrip(), e, currently_parsing.file))
except StopIteration:
break
def parse_config_base(
lines: Iterable[str],
parse_conf_item: ItemParser,
ans: dict[str, Any],
accumulate_bad_lines: list[BadLine] | None = None,
effective_config_lines: Callable[[str, str], None] | None = None,
allow_geninclude: bool = True,
) -> None:
_parse(lines, parse_conf_item, ans, Memory(accumulate_bad_lines), accumulate_bad_lines, effective_config_lines, allow_geninclude)
def merge_dicts(defaults: dict[str, Any], newvals: dict[str, Any]) -> dict[str, Any]:
ans = defaults.copy()
ans.update(newvals)
return ans
def resolve_config(SYSTEM_CONF: str, defconf: str, config_files_on_cmd_line: Sequence[str] = ()) -> Generator[str, None, None]:
if config_files_on_cmd_line:
if 'NONE' not in config_files_on_cmd_line:
yield SYSTEM_CONF
yield from config_files_on_cmd_line
else:
yield SYSTEM_CONF
yield defconf
def load_config(
defaults: OptionsProtocol,
parse_config: Callable[[Iterable[str]], dict[str, Any]],
merge_configs: Callable[[dict[str, Any], dict[str, Any]], dict[str, Any]],
*paths: str,
overrides: Iterable[str] | None = None,
initialize_defaults: Callable[[dict[str, Any]], dict[str, Any]] = lambda x: x,
) -> tuple[dict[str, Any], tuple[str, ...]]:
ans = initialize_defaults(defaults._asdict())
found_paths = []
for path in paths:
if not path:
continue
if path == '-':
path = '/dev/stdin'
with currently_parsing.set_file(path):
vals = parse_config(sys.stdin)
else:
try:
with open(path, encoding='utf-8', errors='replace') as f:
with currently_parsing.set_file(path):
vals = parse_config(f)
except (FileNotFoundError, PermissionError):
continue
found_paths.append(path)
ans = merge_configs(ans, vals)
if overrides is not None:
with currently_parsing.set_file('<override>'):
vals = parse_config(overrides)
ans = merge_configs(ans, vals)
return ans, tuple(found_paths)
ReturnType = TypeVar('ReturnType')
KeyFunc = Callable[[str, str], ReturnType]
class KeyFuncWrapper(Generic[ReturnType]):
def __init__(self) -> None:
self.args_funcs: dict[str, KeyFunc[ReturnType]] = {}
def __call__(self, *names: str) -> Callable[[KeyFunc[ReturnType]], KeyFunc[ReturnType]]:
def w(f: KeyFunc[ReturnType]) -> KeyFunc[ReturnType]:
for name in names:
if self.args_funcs.setdefault(name, f) is not f:
raise ValueError(f'the args_func {name} is being redefined')
return f
return w
def get(self, name: str) -> KeyFunc[ReturnType] | None:
return self.args_funcs.get(name)
class KeyAction(NamedTuple):
func: str
args: tuple[str | float | bool | int | None, ...] = ()
def __repr__(self) -> str:
if self.args:
return f'KeyAction({self.func!r}, {self.args!r})'
return f'KeyAction({self.func!r})'
def pretty(self) -> str:
ans = self.func
for x in self.args:
ans += f' {x}'
return ans
def parse_kittens_func_args(action: str, args_funcs: dict[str, KeyFunc[tuple[str, Any]]]) -> KeyAction:
parts = action.strip().split(' ', 1)
func = parts[0]
if len(parts) == 1:
return KeyAction(func, ())
rest = parts[1]
try:
parser = args_funcs[func]
except KeyError as e:
raise KeyError(f'Unknown action: {func}. Check if map action: {action} is valid') from e
try:
func, args = parser(func, rest)
except Exception:
raise ValueError(f'Unknown key action: {action}')
if not isinstance(args, (list, tuple)):
args = (args,)
return KeyAction(func, tuple(args))
KittensKeyDefinition = tuple[ParsedShortcut, KeyAction]
KittensKeyMap = dict[ParsedShortcut, KeyAction]
def parse_kittens_key(val: str, funcs_with_args: dict[str, KeyFunc[tuple[str, Any]]]) -> KittensKeyDefinition | None:
from ..key_encoding import parse_shortcut
sc, action = val.partition(' ')[::2]
if not sc or not action:
return None
ans = parse_kittens_func_args(action, funcs_with_args)
return parse_shortcut(sc), ans
def uniq(vals: Iterable[T]) -> list[T]:
seen: set[T] = set()
seen_add = seen.add
return [x for x in vals if x not in seen and not seen_add(x)] # ty: ignore[redundant-condition]
def save_type_stub(text: str, fpath: str) -> None:
fpath += 'i'
preamble = '# Update this file by running: ./test.py type-check\n\n'
try:
with open(fpath) as fs:
existing = fs.read()
except FileNotFoundError:
existing = ''
current = preamble + text
if existing != current:
with open(fpath, 'w') as f:
f.write(current)
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
from collections.abc import Callable, Generator, Iterable
from contextlib import contextmanager, suppress
from functools import partial
from typing import Any
from .conf.utils import BadLine, parse_config_base
from .conf.utils import load_config as _load_config
from .constants import cache_dir, defconf
from .options.types import Options, defaults, option_names
from .options.utils import KeyboardMode, KeyboardModeMap, KeyDefinition, MapType, MouseMap, MouseMapping, build_action_aliases
from .typing_compat import TypedDict
from .utils import log_error
def option_names_for_completion() -> tuple[str, ...]:
return option_names
def atomic_save(data: bytes, path: str) -> None:
import shutil
import tempfile
path = os.path.realpath(path)
fd, p = tempfile.mkstemp(dir=os.path.dirname(path), suffix='.tmp')
try:
with os.fdopen(fd, 'wb') as f:
f.write(data)
with suppress(FileNotFoundError):
shutil.copystat(path, p)
os.utime(p)
os.replace(p, path)
finally:
try:
os.remove(p)
except FileNotFoundError:
pass
except Exception as err:
log_error(f'Failed to delete temp file {p} for atomic save with error: {err}')
@contextmanager
def cached_values_for(name: str) -> Generator[dict[str, Any], None, None]:
cached_path = os.path.join(cache_dir(), f'{name}.json')
cached_values: dict[str, Any] = {}
try:
with open(cached_path, 'rb') as f:
cached_values.update(json.loads(f.read().decode('utf-8')))
except FileNotFoundError:
pass
except Exception as err:
log_error(f'Failed to load cached in {name} values with error: {err}')
yield cached_values
try:
data = json.dumps(cached_values).encode('utf-8')
atomic_save(data, cached_path)
except Exception as err:
log_error(f'Failed to save cached values with error: {err}')
def commented_out_default_config() -> str:
from .options.definition import definition
return '\n'.join(definition.as_conf(commented=True))
def prepare_config_file_for_editing() -> str:
if not os.path.exists(defconf):
d = os.path.dirname(defconf)
with suppress(FileExistsError):
os.makedirs(d)
with open(defconf, 'w', encoding='utf-8') as f:
f.write(commented_out_default_config())
return defconf
def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
defns: list[KeyDefinition] = []
for d in opts.map:
if d is None: # clear_all_shortcuts
defns = []
else:
try:
defns.append(d.resolve_and_copy(opts.kitty_mod))
except Exception as err:
if accumulate_bad_lines is None:
log_error(f'Ignoring map with invalid action: {d.definition}. Error: {err}')
else:
accumulate_bad_lines.append(BadLine(d.definition_location.number, d.definition_location.line, err, d.definition_location.file))
modes: KeyboardModeMap = {'': KeyboardMode()}
for defn in defns:
if defn.options.new_mode:
modes[defn.options.new_mode] = nm = KeyboardMode(defn.options.new_mode)
nm.on_unknown = defn.options.on_unknown
nm.on_action = defn.options.on_action
nm.timeout = defn.options.timeout if defn.options.timeout is not None else opts.map_timeout
defn.definition = f'push_keyboard_mode {defn.options.new_mode}'
try:
m = modes[defn.options.mode]
except KeyError:
kerr = f'The keyboard mode {defn.options.mode} is unknown, ignoring the mapping'
if accumulate_bad_lines is None:
log_error(kerr)
else:
dl = defn.definition_location
accumulate_bad_lines.append(BadLine(dl.number, dl.line, KeyError(kerr), dl.file))
continue
items = m.keymap[defn.trigger]
if defn.is_sequence:
items = m.keymap[defn.trigger] = [kd for kd in items if defn.rest != kd.rest or defn.options.when_focus_on != kd.options.when_focus_on]
items.append(defn)
opts.keyboard_modes = modes
def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None:
from .fast_data_types import GLFW_MOUSE_BUTTON_LAST
from .keys import mod_mask
defns: list[MouseMapping] = []
for d in opts.mouse_map:
if d is None: # clear_all_mouse_actions
defns = []
else:
try:
defns.append(d.resolve_and_copy(opts.kitty_mod))
except Exception as err:
if accumulate_bad_lines is None:
log_error(f'Ignoring mouse_map with invalid action: {d.definition}. Error: {err}')
else:
accumulate_bad_lines.append(BadLine(d.definition_location.number, d.definition_location.line, err, d.definition_location.file))
mousemap: MouseMap = {}
for defn in defns:
if defn.definition:
mousemap[defn.trigger] = defn.definition
else:
mousemap.pop(defn.trigger, None)
opts.mousemap = mousemap
opts.url_mappings = {False: 0, True: 0}
for event, definition in mousemap.items():
if not 0 <= event.button <= GLFW_MOUSE_BUTTON_LAST or event.mods & ~mod_mask or event.repeat_count not in (-2, -1, 1):
continue
try:
actions = opts.alias_map.resolve_aliases(definition, MapType.MOUSE_MAP)
except Exception as err:
log_error(f'Ignoring mouse_map with invalid action: {definition}. Error: {err}')
continue
if any(a.func in ('mouse_click_url', 'mouse_click_url_or_select') or (a.func == 'mouse_handle_click' and 'link' in a.args) for a in actions):
opts.url_mappings[event.grabbed] |= 1 << event.mods
def parse_config(
lines: Iterable[str],
accumulate_bad_lines: list[BadLine] | None = None,
effective_config_lines: Callable[[str, str], None] | None = None,
allow_geninclude: bool = True,
) -> dict[str, Any]:
from .options.parse import create_result_dict, parse_conf_item
ans: dict[str, Any] = create_result_dict()
parse_config_base(
lines,
parse_conf_item,
ans,
accumulate_bad_lines=accumulate_bad_lines,
effective_config_lines=effective_config_lines,
allow_geninclude=allow_geninclude,
)
return ans
effective_config_lines: list[str] = []
def load_config(*paths: str, overrides: Iterable[str] | None = None, accumulate_bad_lines: list[BadLine] | None = None) -> Options:
from .options.parse import merge_result_dicts
from .options.types import secret_options
del effective_config_lines[:]
def add_effective_config_line(key: str, line: str) -> None:
if key not in secret_options:
effective_config_lines.append(line)
overrides = tuple(overrides) if overrides is not None else ()
opts_dict, found_paths = _load_config(
defaults,
partial(parse_config, accumulate_bad_lines=accumulate_bad_lines, effective_config_lines=add_effective_config_line),
merge_result_dicts,
*paths,
overrides=overrides,
)
opts = Options(opts_dict)
opts.alias_map = build_action_aliases(opts.kitten_alias, 'kitten')
opts.alias_map.update(build_action_aliases(opts.action_alias))
finalize_keys(opts, accumulate_bad_lines)
finalize_mouse_mappings(opts, accumulate_bad_lines)
# delete no longer needed definitions, replacing with empty placeholders
opts.kitten_alias = {}
opts.action_alias = {}
opts.mouse_map = []
opts.map = []
opts.config_paths = found_paths
opts.all_config_paths = paths
opts.config_overrides = overrides
return opts
def store_effective_config() -> tuple[str, str]:
import os
import stat
import tempfile
path = ''
try:
dest = os.path.join(cache_dir(), 'effective-config')
os.makedirs(dest, exist_ok=True)
raw = '\n'.join(effective_config_lines)
with suppress(FileNotFoundError), tempfile.NamedTemporaryFile('w', dir=dest) as tf:
os.chmod(tf.name, stat.S_IRUSR | stat.S_IWUSR)
print(raw, file=tf)
path = os.path.join(dest, f'{os.getpid()}')
os.replace(tf.name, path)
except OSError as err:
# effective config is used by some kittens to read the config of the
# current kitty instance. If missing they fallback to parsing
# kitty.conf so ignore the error which would prevent kitty from
# starting.
msg = f'Failed to store effective config with error: {err}'
log_error(msg)
return '', msg
return path, ''
class KittyCommonOpts(TypedDict):
select_by_word_characters: str
open_url_with: list[str]
url_prefixes: tuple[str, ...]
def common_opts_as_dict(opts: Options | None = None) -> KittyCommonOpts:
if opts is None:
opts = defaults
return {
'select_by_word_characters': opts.select_by_word_characters,
'open_url_with': opts.open_url_with,
'url_prefixes': opts.url_prefixes,
}
+349
View File
@@ -0,0 +1,349 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import os
import pwd
import sys
from collections.abc import Iterator
from contextlib import suppress
from typing import TYPE_CHECKING, Any, NamedTuple, Optional
from .types import run_once
if TYPE_CHECKING:
from .options.types import Options
class Version(NamedTuple):
major: int
minor: int
patch: int
appname: str = 'kitty'
kitty_face = '🐱'
version: Version = Version(0, 50, 0)
str_version: str = '.'.join(map(str, version))
_plat = sys.platform.lower()
is_macos: bool = 'darwin' in _plat
is_freebsd: bool = 'freebsd' in _plat
is_running_from_develop: bool = False
RC_ENCRYPTION_PROTOCOL_VERSION = '1'
website_base_url = 'https://sw.kovidgoyal.net/kitty/'
default_pager_for_help = ('less', '-iRXF')
kitty_run_data: dict[str, Any] = getattr(sys, 'kitty_run_data', {})
launched_by_launch_services = kitty_run_data.get('launched_by_launch_services', False)
is_quick_access_terminal_app = kitty_run_data.get('is_quick_access_terminal_app', False)
unserialize_launch_flag = 'kitty-unserialize-data='
_slangc: tuple[str, ...] = ()
def slangc() -> tuple[str, ...]:
global _slangc
if not _slangc:
from kitty.fast_data_types import DEVELOP_ROOT, Shlex
if DEVELOP_ROOT:
_slangc = (os.path.join(DEVELOP_ROOT, 'bin', 'slangc'),)
else:
_slangc = tuple(Shlex(os.environ.get('SLANGC', 'slangc'), False))
return _slangc
if getattr(sys, 'frozen', False):
extensions_dir: str = kitty_run_data['extensions_dir']
def get_frozen_base() -> str:
global is_running_from_develop
try:
from bypy_importer import running_in_develop_mode # type: ignore
except ImportError:
pass
else:
is_running_from_develop = running_in_develop_mode()
if is_running_from_develop:
q = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
try:
if os.path.isdir(q):
return q
except OSError:
pass
ans = os.path.dirname(extensions_dir)
if is_macos:
ans = os.path.dirname(os.path.dirname(ans))
ans = os.path.join(ans, 'kitty')
return ans
kitty_base_dir = get_frozen_base()
if rpath := kitty_run_data.get('bundle_exe_dir'):
_slangc = (os.path.join(rpath, 'slangc'),)
del get_frozen_base, rpath
else:
kitty_base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
extensions_dir = os.path.join(kitty_base_dir, 'kitty')
@run_once
def kitty_exe() -> str:
rpath = kitty_run_data.get('bundle_exe_dir')
if not rpath:
items = os.environ.get('PATH', '').split(os.pathsep) + [os.path.join(kitty_base_dir, 'kitty', 'launcher')]
seen: set[str] = set()
for candidate in filter(None, items):
if candidate not in seen:
seen.add(candidate)
if os.access(os.path.join(candidate, 'kitty'), os.X_OK):
rpath = candidate
break
else:
raise RuntimeError('kitty binary not found')
return os.path.join(rpath, 'kitty')
@run_once
def kitten_exe() -> str:
return os.path.join(os.path.dirname(kitty_exe()), 'kitten')
def _get_config_dir() -> str:
cdir = kitty_run_data.get('config_dir', '')
if cdir:
return str(cdir)
import atexit
import tempfile
ans = tempfile.mkdtemp(prefix='kitty-conf-')
def cleanup() -> None:
import shutil
with suppress(Exception):
shutil.rmtree(ans)
atexit.register(cleanup)
return ans
config_dir = _get_config_dir()
del _get_config_dir
defconf = os.path.join(config_dir, 'kitty.conf')
# When True, auxiliary files in config_dir that kitty loads implicitly, such as
# the automatic color theme files, open-actions.conf, etc. are ignored. Set when
# kitty is run with --config=NONE.
_ignore_config_dir_files = False
def set_ignore_config_dir_files(val: bool) -> None:
global _ignore_config_dir_files
_ignore_config_dir_files = val
def config_dir_files_ignored() -> bool:
return _ignore_config_dir_files
@run_once
def cache_dir() -> str:
if 'KITTY_CACHE_DIRECTORY' in os.environ:
candidate = os.path.abspath(os.environ['KITTY_CACHE_DIRECTORY'])
elif is_macos:
candidate = os.path.join(os.path.expanduser('~/Library/Caches'), appname)
else:
candidate = os.environ.get('XDG_CACHE_HOME', '~/.cache')
candidate = os.path.join(os.path.expanduser(candidate), appname)
os.makedirs(candidate, exist_ok=True)
return candidate
@run_once
def runtime_dir() -> str:
if 'KITTY_RUNTIME_DIRECTORY' in os.environ:
candidate = os.path.abspath(os.environ['KITTY_RUNTIME_DIRECTORY'])
elif is_macos:
from .fast_data_types import user_cache_dir
candidate = user_cache_dir()
elif 'XDG_RUNTIME_DIR' in os.environ:
candidate = os.path.abspath(os.environ['XDG_RUNTIME_DIR'])
else:
candidate = f'/run/user/{os.geteuid()}'
if not os.path.isdir(candidate) or not os.access(candidate, os.X_OK | os.W_OK | os.R_OK):
candidate = os.path.join(cache_dir(), 'run')
os.makedirs(candidate, exist_ok=True)
import stat
if stat.S_IMODE(os.stat(candidate).st_mode) != 0o700:
os.chmod(candidate, 0o700)
return candidate
def wakeup_io_loop() -> None:
from .fast_data_types import get_boss
b = get_boss()
if b is not None:
b.child_monitor.wakeup()
terminfo_dir = os.path.join(kitty_base_dir, 'terminfo')
logo_png_file = os.path.join(kitty_base_dir, 'logo', 'kitty.png')
beam_cursor_data_file = os.path.join(kitty_base_dir, 'logo', 'beam-cursor.png')
shell_integration_dir = os.path.join(kitty_base_dir, 'shell-integration')
fonts_dir = os.path.join(kitty_base_dir, 'fonts')
shaders_dir = os.path.join(kitty_base_dir, 'shaders')
try:
shell_path = os.environ.get('SHELL') or pwd.getpwuid(os.geteuid()).pw_shell or '/bin/sh'
except KeyError:
with suppress(Exception):
print('Failed to read login shell via getpwuid() for current user, falling back to /bin/sh', file=sys.stderr)
shell_path = '/bin/sh'
# Keep this short as it is limited to 103 bytes on macOS
# https://github.com/ansible/ansible/issues/11536#issuecomment-153030743
ssh_control_master_template = 'kssh-{kitty_pid}-{ssh_placeholder}'
# See https://specifications.freedesktop.org/icon-naming-spec/latest/ar01s04.html
# Update the spec in docs/desktop-notifications.rst if you change this.
standard_icon_names = {
'error': ('dialog-error', '☠'),
'warning': ('dialog-warning', '⚠'),
'warn': ('dialog-warning', '⚠'),
'info': ('dialog-information', 'ℹ'),
'question': ('dialog-question', '❔'),
'help': ('system-help', '📖'),
'file-manager': ('system-file-manager', '🗄'),
'system-monitor': ('utilities-system-monitor', '🎛'),
'text-editor': ('utilities-text-editor', '📄'),
}
# See https://github.com/TUNER88/iOSSystemSoundsLibrary for Apple's system
# sound ids not all of which are available on macOS.
standard_sound_names = {
'error': ('dialog-error', 1),
'info': ('dialog-information', 2),
'warning': ('dialog-warning', 3),
'warn': ('dialog-warning', 3),
'question': ('dialog-question', 4),
}
def glfw_path(module: str) -> str:
prefix = 'kitty.' if getattr(sys, 'frozen', False) else ''
return os.path.join(extensions_dir, f'{prefix}glfw-{module}.so')
def detect_if_wayland_ok() -> bool:
if not os.environ.get('WAYLAND_DISPLAY') and not os.environ.get('WAYLAND_SOCKET'):
return False
if os.environ.get('KITTY_DISABLE_WAYLAND'):
return False
wayland = glfw_path('wayland')
if not os.path.exists(wayland):
return False
import ctypes
with suppress(Exception):
setattr(detect_if_wayland_ok, 'keep_module_loaded', ctypes.CDLL(wayland))
return True
return False
def is_wayland(opts: Optional['Options'] = None) -> bool:
if is_macos:
return False
if opts is None:
return bool(getattr(is_wayland, 'ans'))
if opts.linux_display_server == 'auto':
ans = detect_if_wayland_ok()
else:
ans = opts.linux_display_server == 'wayland'
setattr(is_wayland, 'ans', ans)
return ans
supports_primary_selection = not is_macos
def running_in_kitty(set_val: bool | None = None) -> bool:
if set_val is not None:
setattr(running_in_kitty, 'ans', set_val)
return bool(getattr(running_in_kitty, 'ans', False))
def list_kitty_resources(package: str = 'kitty') -> Iterator[str]:
from importlib.resources import files
return (path.name for path in files(package).iterdir())
def read_kitty_resource(name: str, package_name: str = 'kitty') -> bytes:
from importlib.resources import files
return (files(package_name) / name).read_bytes()
def website_url(doc_name: str = '', website: str = website_base_url) -> str:
if doc_name:
base, _, frag = doc_name.partition('#')
base = base.rstrip('/')
if base:
base += '/'
doc_name = base + (f'#{frag}' if frag else '')
return website + doc_name.lstrip('/')
handled_signals: set[int] = set()
def clear_handled_signals(*a: Any) -> None:
if not handled_signals:
return
import signal
if hasattr(signal, 'pthread_sigmask'):
signal.pthread_sigmask(signal.SIG_UNBLOCK, handled_signals)
for s in handled_signals:
signal.signal(s, signal.SIG_DFL)
@run_once
def local_docs() -> str:
d = os.path.dirname
base = d(d(kitty_exe()))
from_source = kitty_run_data.get('from_source')
if is_macos and from_source and '/kitty.app/Contents/' in kitty_exe():
base = d(d(d(base)))
subdir = os.path.join('doc', 'kitty', 'html')
linux_ans = os.path.join(base, 'share', subdir)
if getattr(sys, 'frozen', False):
if is_macos:
return os.path.join(d(d(d(extensions_dir))), subdir)
return linux_ans
if os.path.isdir(linux_ans):
return linux_ans
if from_source:
sq = os.path.join(d(base), 'docs', '_build', 'html')
if os.path.isdir(sq):
return sq
for candidate in ('/usr', '/usr/local', '/opt/homebrew'):
q = os.path.join(candidate, 'share', subdir)
if os.path.isdir(q):
return q
return ''
@run_once
def wrapped_kitten_names() -> frozenset[str]:
import kitty.fast_data_types as f
return frozenset(f.wrapped_kitten_names())
_supports_window_occlusion = False
def supports_window_occlusion(set: bool | None = None) -> bool:
global _supports_window_occlusion
if set is not None:
_supports_window_occlusion = set
return _supports_window_occlusion
+239
View File
@@ -0,0 +1,239 @@
/*
* control_codes.h
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
// Space
#define SP ' '
// *Null*: Does nothing.
#define NUL 0
// *Bell*: Beeps.
#define BEL 0x07
// *Backspace*: Backspace one column, but not past the beginning of the
// line.
#define BS 0x08
// *Horizontal tab*: Move cursor to the next tab stop, or to the end
// of the line if there is no earlier tab stop.
#define HT 0x09
// *Linefeed*: Give a line feed, and, if LNM (new
// line mode) is set also a carriage return.
#define LF 10
// *Vertical tab*: Same as :data:`LF`.
#define VT 0x0b
// *Form feed*: Same as :data:`LF`.
#define FF 0x0c
// *Carriage return*: Move cursor to left margin on current line.
#define CR 13
// *Shift out*: Activate G1 character set.
#define SO 0x0e
// *Shift in*: Activate G0 character set.
#define SI 0x0f
// *Cancel*: Interrupt escape sequence. If received during an escape or
// control sequence, cancels the sequence and displays substitution
// character.
#define CAN 0x18
// *Substitute*: Same as :data:`CAN`.
#define SUB 0x1a
// *Escape*: Starts an escape sequence.
#define ESC 0x1b
// *Delete*: Is ignored.
#define DEL 0x7f
// Sharp control codes
// -------------------
// Align display
#define DECALN '8'
// Esc control codes
// ------------------
#define ESC_DCS 'P'
#define ESC_OSC ']'
#define ESC_CSI '['
#define ESC_ST '\\'
#define ESC_PM '^'
#define ESC_APC '_'
#define ESC_SOS 'X'
// *Reset*.
#define ESC_RIS 'c'
// *Index*: Move cursor down one line in same column. If the cursor is
// at the bottom margin, the screen performs a scroll-up.
#define ESC_IND 'D'
// *Next line*: Same as LF.
#define ESC_NEL 'E'
// Tabulation set: Set a horizontal tab stop at cursor position.
#define ESC_HTS 'H'
// *Reverse index*: Move cursor up one line in same column. If the
// cursor is at the top margin, the screen performs a scroll-down.
#define ESC_RI 'M'
// Save cursor: Save cursor position, character attribute (graphic
// rendition), character set, and origin mode selection (see
// :data:`DECRC`).
#define ESC_DECSC '7'
// *Restore cursor*: Restore previously saved cursor position, character
// attribute (graphic rendition), character set, and origin mode
// selection. If none were saved, move cursor to home position.
#define ESC_DECRC '8'
// Set normal keypad mode
#define ESC_DECKPNM '>'
// Set alternate keypad mode
#define ESC_DECKPAM '='
// ECMA-48 CSI sequences.
// ---------------------
// *Insert character*: Insert the indicated # of blank characters.
#define ICH '@'
// *Cursor up*: Move cursor up the indicated # of lines in same column.
// Cursor stops at top margin.
#define CUU 'A'
// *Cursor down*: Move cursor down the indicated # of lines in same
// column. Cursor stops at bottom margin.
#define CUD 'B'
// *Cursor forward*: Move cursor right the indicated # of columns.
// Cursor stops at right margin.
#define CUF 'C'
// *Cursor back*: Move cursor left the indicated # of columns. Cursor
// stops at left margin.
#define CUB 'D'
// *Cursor next line*: Move cursor down the indicated # of lines to
// column 1.
#define CNL 'E'
// *Cursor previous line*: Move cursor up the indicated # of lines to
// column 1.
#define CPL 'F'
// *Cursor horizontal align*: Move cursor to the indicated column in
// current line.
#define CHA 'G'
// *Cursor position*: Move cursor to the indicated line, column (origin
// at ``1, 1``).
#define CUP 'H'
// *Erase data* (default: from cursor to end of line).
#define ED 'J'
// *Erase in line* (default: from cursor to end of line).
#define EL 'K'
// *Insert line*: Insert the indicated # of blank lines, starting from
// the current line. Lines displayed below cursor move down. Lines moved
// past the bottom margin are lost.
#define IL 'L'
// *Delete line*: Delete the indicated # of lines, starting from the
// current line. As lines are deleted, lines displayed below cursor
// move up. Lines added to bottom of screen have spaces with same
// character attributes as last line move up.
#define DL 'M'
// *Delete character*: Delete the indicated # of characters on the
// current line. When character is deleted, all characters to the right
// of cursor move left.
#define DCH 'P'
// Scroll up by the specified number of lines
#define SU 'S'
// Scroll down by the specified number of lines
#define SD 'T'
// *Erase character*: Erase the indicated # of characters on the
// current line.
#define ECH 'X'
// *Horizontal position relative*: Same as :data:`CUF`.
#define HPR 'a'
// Repeat the preceding graphic character Ps times.
#define REP 'b'
// *Device Attributes*.
#define DA 'c'
// *Vertical position adjust*: Move cursor to the indicated line,
// current column.
#define VPA 'd'
// *Vertical position relative*: Same as :data:`CUD`.
#define VPR 'e'
// *Horizontal / Vertical position*: Same as :data:`CUP`.
#define HVP 'f'
// *Tabulation clear*: Clears a horizontal tab stop at cursor position.
#define TBC 'g'
// *Set mode*.
#define SM 'h'
// *Reset mode*.
#define RM 'l'
// *Select graphics rendition*: The terminal can display the following
// character attributes that change the character display without
// changing the character
#define SGR 'm'
// *Device status report*.
#define DSR 'n'
// Soft reset
#define DECSTR 'p'
// *Horizontal position adjust*: Same as :data:`CHA`.
#define HPA '`'
// Back tab
#define CBT 'Z'
// Forward tab
#define CHT 'I'
// Misc sequences
// ----------------
// Change cursor shape/blink
#define DECSCUSR 'q'
// File transfer OSC number
#define FILE_TRANSFER_CODE 5113
// Pending mode CSI code
#define PENDING_MODE 2026
// Text size OSC number
#define TEXT_SIZE_CODE 66
// Drag and drop protocol
#define DND_CODE 72
+1506
View File
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2020 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include <stdlib.h>
#include <stdbool.h>
#if __linux__
#include <errno.h>
#if __has_include(<sys/random.h>)
#include <sys/random.h>
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
unsigned char *p = buf;
ssize_t left = nbytes;
while (1) {
ssize_t n = getrandom(p, left, 0);
if (n >= left) return true;
if (n < 0) {
if (errno != EINTR) return false; // should never happen but if it does, we fail without any feedback
continue;
}
left -= n;
p += n;
}
}
#else
#include "safe-wrappers.h"
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
int fd = safe_open("/dev/urandom", O_RDONLY, 0);
if (fd < 0) return false;
size_t bytes_read = 0;
while (bytes_read < nbytes) {
ssize_t n = read(fd, (uint8_t *)buf + bytes_read, nbytes - bytes_read);
if (n < 0) {
if (errno == EINTR) continue;
break;
}
bytes_read += n;
}
safe_close(fd, __FILE__, __LINE__);
return bytes_read == nbytes;
}
#endif
#else
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
arc4random_buf(buf, nbytes);
return true;
}
#endif
+647
View File
@@ -0,0 +1,647 @@
/*
* crypto.c
* Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#include "crypto.h"
#include "cross-platform-random.h"
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include <sys/mman.h>
#include <structmember.h>
#ifdef LIBRESSL_VERSION_NUMBER
/* from: https://github.com/libressl/portable/blob/master/include/compat/string.h#L63 */
#define explicit_bzero libressl_explicit_bzero
void explicit_bzero(void *, size_t);
/* from: https://github.com/libressl/portable/blob/master/crypto/compat/freezero.c */
void
freezero(void *ptr, size_t sz) {
if (ptr == NULL) return;
explicit_bzero(ptr, sz);
free(ptr);
}
#define OPENSSL_clear_free freezero
#endif
#define SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
typedef enum HASH_ALGORITHM { SHA1_HASH, SHA224_HASH, SHA256_HASH, SHA384_HASH, SHA512_HASH } HASH_ALGORITHM;
static PyObject *Crypto_Exception = NULL;
static PyObject *
set_error_from_openssl(const char *prefix) {
BIO *bio = BIO_new(BIO_s_mem());
ERR_print_errors(bio);
char *buf = NULL;
size_t len = BIO_get_mem_data(bio, &buf);
PyObject *msg = PyUnicode_FromStringAndSize(buf, len);
if (msg) PyErr_Format(Crypto_Exception, "%s: %U", prefix, msg);
BIO_free(bio);
Py_CLEAR(msg);
return NULL;
}
// Secret {{{
typedef struct {
PyObject_HEAD
void *secret;
size_t secret_len;
} Secret;
static PyObject *
new_secret(PyTypeObject *type UNUSED, PyObject *args UNUSED, PyObject *kwds UNUSED) {
PyErr_SetString(PyExc_TypeError, "Cannot create Secret objects directly");
return NULL;
}
static Secret *alloc_secret(size_t len);
static void
dealloc_secret(Secret *self) {
if (self->secret) OPENSSL_clear_free(self->secret, self->secret_len);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
__eq__(Secret *a, Secret *b) {
if (a->secret_len != b->secret_len) return 0;
return CRYPTO_memcmp(a->secret, b->secret, a->secret_len) == 0;
}
static Py_ssize_t
__len__(PyObject *self) {
return (Py_ssize_t)(((Secret *)self)->secret_len);
}
static PySequenceMethods sequence_methods = {
.sq_length = __len__,
};
static PyObject *richcmp(PyObject *obj1, PyObject *obj2, int op);
static PyTypeObject Secret_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.Secret",
.tp_basicsize = sizeof(Secret),
.tp_dealloc = (destructor)dealloc_secret,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Secure storage for secrets",
.tp_new = new_secret,
.tp_richcompare = richcmp,
.tp_as_sequence = &sequence_methods,
};
RICHCMP(Secret)
static Secret *
alloc_secret(size_t len) {
Secret *self = (Secret *)Secret_Type.tp_alloc(&Secret_Type, 0);
if (self) {
self->secret_len = len;
if (NULL == (self->secret = OPENSSL_malloc(len))) {
Py_CLEAR(self);
return (Secret *)set_error_from_openssl("Failed to malloc");
}
if (0 != mlock(self->secret, self->secret_len)) {
Py_CLEAR(self);
return (Secret *)PyErr_SetFromErrno(PyExc_OSError);
}
}
return self;
}
PyObject *
secret_from_data(const void *data, size_t len) {
Secret *ans = alloc_secret(len);
if (ans) memcpy(ans->secret, data, len);
return (PyObject *)ans;
}
bool
secret_data(PyObject *obj, const void **data, size_t *len) {
if (!PyObject_TypeCheck(obj, &Secret_Type)) {
PyErr_SetString(PyExc_TypeError, "Not a Secret object");
return false;
}
*data = ((Secret *)obj)->secret;
*len = ((Secret *)obj)->secret_len;
return true;
}
static PyObject *
random_secret(PyObject *self UNUSED, PyObject *args) {
unsigned int len = 32;
if (!PyArg_ParseTuple(args, "|I", &len)) return NULL;
if (!len) {
PyErr_SetString(PyExc_ValueError, "The length of a secret must be positive");
return NULL;
}
Secret *ans = alloc_secret(len);
if (ans && !secure_random_bytes(ans->secret, len)) {
Py_CLEAR(ans);
PyErr_SetString(PyExc_OSError, "Failed to generate random bytes for a secret");
}
return (PyObject *)ans;
}
// }}}
// EllipticCurveKey {{{
typedef struct {
PyObject_HEAD
EVP_PKEY *key;
int algorithm, nid;
} EllipticCurveKey;
static PyObject *
new_ec_key(PyTypeObject *type, PyObject *args, PyObject *kwds) {
EllipticCurveKey *self;
static const char *kwlist[] = {"algorithm", NULL};
int algorithm = EVP_PKEY_X25519, nid = NID_X25519;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", (char **)kwlist, &algorithm)) return NULL;
switch (algorithm) {
case EVP_PKEY_X25519: break;
default: PyErr_SetString(PyExc_KeyError, "Unknown algorithm"); return NULL;
}
EVP_PKEY *key = NULL;
EVP_PKEY_CTX *pctx = NULL;
#define cleanup() \
{ \
if (key) EVP_PKEY_free(key); \
key = NULL; \
if (pctx) EVP_PKEY_CTX_free(pctx); \
pctx = NULL; \
}
#define ssl_error(text) \
{ \
cleanup(); \
return set_error_from_openssl(text); \
}
if (NULL == (pctx = EVP_PKEY_CTX_new_id(nid, NULL))) ssl_error("Failed to create context for key generation");
if (1 != EVP_PKEY_keygen_init(pctx)) ssl_error("Failed to initialize keygen context");
if (1 != EVP_PKEY_keygen(pctx, &key)) ssl_error("Failed to generate key");
self = (EllipticCurveKey *)type->tp_alloc(type, 0);
if (self) {
self->key = key;
key = NULL;
self->nid = nid;
self->algorithm = algorithm;
}
cleanup();
return (PyObject *)self;
#undef cleanup
#undef ssl_error
}
static void
dealloc_ec_key(EllipticCurveKey *self) {
if (self->key) EVP_PKEY_free(self->key);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
hash_data_to_secret(const unsigned char *data, size_t len, int hash_algorithm) {
size_t hash_size;
#define H(which) \
case which##_HASH: hash_size = which##_DIGEST_LENGTH; break;
switch (hash_algorithm) {
H(SHA1) H(SHA224) H(SHA256) H(SHA384) H(SHA512) default : PyErr_Format(PyExc_KeyError, "Unknown hash algorithm: %d", hash_algorithm);
return NULL;
}
#undef H
Secret *ans = alloc_secret(hash_size);
if (!ans) return NULL;
#define H(which) \
case which##_HASH: \
if (which(data, len, ans->secret) == NULL) { \
Py_CLEAR(ans); \
return set_error_from_openssl("Failed to " #which); \
} \
break;
switch ((HASH_ALGORITHM)hash_algorithm) { H(SHA1) H(SHA224) H(SHA256) H(SHA384) H(SHA512) }
#undef H
return (PyObject *)ans;
}
static PyObject *
derive_secret(EllipticCurveKey *self, PyObject *args) {
const char *pubkey_raw;
int hash_algorithm = SHA256_HASH;
Py_ssize_t pubkey_len;
if (!PyArg_ParseTuple(args, "y#|i", &pubkey_raw, &pubkey_len, &hash_algorithm)) return NULL;
EVP_PKEY_CTX *ctx = NULL;
unsigned char *secret = NULL;
size_t secret_len = 0;
EVP_PKEY *public_key = EVP_PKEY_new_raw_public_key(self->algorithm, NULL, (const unsigned char *)pubkey_raw, pubkey_len);
#define cleanup() \
{ \
if (public_key) EVP_PKEY_free(public_key); \
public_key = NULL; \
if (ctx) EVP_PKEY_CTX_free(ctx); \
ctx = NULL; \
if (secret) OPENSSL_clear_free(secret, secret_len); \
secret = NULL; \
}
#define ssl_error(text) \
{ \
cleanup(); \
return set_error_from_openssl(text); \
}
if (!public_key) ssl_error("Failed to create public key");
if (NULL == (ctx = EVP_PKEY_CTX_new(self->key, NULL))) ssl_error("Failed to create context for shared secret derivation");
if (1 != EVP_PKEY_derive_init(ctx)) ssl_error("Failed to initialize derivation");
if (1 != EVP_PKEY_derive_set_peer(ctx, public_key)) ssl_error("Failed to add public key");
if (1 != EVP_PKEY_derive(ctx, NULL, &secret_len)) ssl_error("Failed to get length for secret");
if (NULL == (secret = OPENSSL_malloc(secret_len))) ssl_error("Failed to allocate secret key");
if (mlock(secret, secret_len) != 0) {
cleanup();
return PyErr_SetFromErrno(PyExc_OSError);
}
if (1 != (EVP_PKEY_derive(ctx, secret, &secret_len))) ssl_error("Failed to derive the secret");
PyObject *ans = hash_data_to_secret(secret, secret_len, hash_algorithm);
cleanup();
return ans;
#undef cleanup
#undef ssl_error
}
static PyObject *
elliptic_curve_key_get_public(EllipticCurveKey *self, void UNUSED *closure) {
/* PEM_write_PUBKEY(stdout, pkey); */
size_t len = 0;
if (1 != EVP_PKEY_get_raw_public_key(self->key, NULL, &len)) return set_error_from_openssl("Could not get public key from EVP_PKEY");
PyObject *ans = PyBytes_FromStringAndSize(NULL, len);
if (!ans) return NULL;
if (1 != EVP_PKEY_get_raw_public_key(self->key, (unsigned char *)PyBytes_AS_STRING(ans), &len)) {
Py_CLEAR(ans);
return set_error_from_openssl("Could not get public key from EVP_PKEY");
}
return ans;
}
static PyObject *
elliptic_curve_key_get_private(EllipticCurveKey *self, void UNUSED *closure) {
size_t len = 0;
if (1 != EVP_PKEY_get_raw_private_key(self->key, NULL, &len)) return set_error_from_openssl("Could not get public key from EVP_PKEY");
Secret *ans = alloc_secret(len);
if (!ans) return NULL;
if (mlock(PyBytes_AS_STRING(ans), len) != 0) {
Py_CLEAR(ans);
return PyErr_SetFromErrno(PyExc_OSError);
}
if (1 != EVP_PKEY_get_raw_private_key(self->key, (unsigned char *)ans->secret, &len)) {
Py_CLEAR(ans);
return set_error_from_openssl("Could not get public key from EVP_PKEY");
}
return (PyObject *)ans;
}
static PyGetSetDef getsetters[] = {
{"public", (getter)elliptic_curve_key_get_public, NULL, "Get the public key as raw bytes", NULL},
{"private", (getter)elliptic_curve_key_get_private, NULL, "Get the private key as raw bytes", NULL},
{NULL} /* Sentinel */
};
static PyMethodDef methods[] = {
METHODB(derive_secret, METH_VARARGS), {NULL} /* Sentinel */
};
static PyTypeObject EllipticCurveKey_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.EllipticCurveKey",
.tp_basicsize = sizeof(EllipticCurveKey),
.tp_dealloc = (destructor)dealloc_ec_key,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Keys for use with Elliptic Curve crypto",
.tp_new = new_ec_key,
.tp_methods = methods,
.tp_getset = getsetters,
};
// }}}
// AES256GCMEncrypt {{{
typedef struct {
PyObject_HEAD
EVP_CIPHER_CTX *ctx;
PyObject *iv, *tag;
int state;
} AES256GCMEncrypt;
static PyObject *
new_aes256gcmencrypt(PyTypeObject *type, PyObject *args, PyObject *kwds UNUSED) {
Secret *key;
if (!PyArg_ParseTuple(args, "O!", &Secret_Type, &key)) return NULL;
const EVP_CIPHER *cipher = EVP_get_cipherbynid(NID_aes_256_gcm);
if (key->secret_len != (size_t)EVP_CIPHER_key_length(cipher)) {
PyErr_Format(PyExc_ValueError, "The key for AES 256 GCM must be %d bytes long", EVP_CIPHER_key_length(cipher));
return NULL;
}
AES256GCMEncrypt *self = (AES256GCMEncrypt *)type->tp_alloc(type, 0);
if (!self) return NULL;
if (!(self->ctx = EVP_CIPHER_CTX_new())) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to allocate encryption context");
}
if (!(self->iv = PyBytes_FromStringAndSize(NULL, EVP_CIPHER_iv_length(cipher)))) {
Py_CLEAR(self);
return NULL;
}
if (!secure_random_bytes((unsigned char *)PyBytes_AS_STRING(self->iv), PyBytes_GET_SIZE(self->iv))) {
Py_CLEAR(self);
return NULL;
}
if (!(self->tag = PyBytes_FromStringAndSize(NULL, 0))) {
Py_CLEAR(self);
return NULL;
}
if (1 != EVP_EncryptInit_ex(self->ctx, cipher, NULL, key->secret, (const unsigned char *)PyBytes_AS_STRING(self->iv))) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to initialize encryption context");
}
return (PyObject *)self;
}
static void
dealloc_aes256gcmencrypt(AES256GCMEncrypt *self) {
Py_CLEAR(self->iv);
Py_CLEAR(self->tag);
if (self->ctx) EVP_CIPHER_CTX_free(self->ctx);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
add_authenticated_but_unencrypted_data(AES256GCMEncrypt *self, PyObject *args) {
if (self->state > 0) {
PyErr_SetString(Crypto_Exception, "Cannot add data once encryption has started");
return NULL;
}
const char *aad;
Py_ssize_t aad_len;
if (!PyArg_ParseTuple(args, "y#", &aad, &aad_len)) return NULL;
int len;
if (aad_len > 0 && 1 != EVP_EncryptUpdate(self->ctx, NULL, &len, (const unsigned char *)aad, aad_len))
return set_error_from_openssl("Failed to add AAD data");
Py_RETURN_NONE;
}
static int
cipher_ctx_tag_length(const EVP_CIPHER_CTX *ctx) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
return EVP_CIPHER_CTX_tag_length(ctx);
#else
(void)ctx;
return 16;
#endif
}
static PyObject *
add_data_to_be_encrypted(AES256GCMEncrypt *self, PyObject *args) {
if (self->state > 1) {
PyErr_SetString(Crypto_Exception, "Encryption has been finished");
return NULL;
}
const char *plaintext;
Py_ssize_t plaintext_len;
int finish_encryption = 0;
if (!PyArg_ParseTuple(args, "y#|p", &plaintext, &plaintext_len, &finish_encryption)) return NULL;
PyObject *ciphertext = PyBytes_FromStringAndSize(NULL, plaintext_len + 2 * EVP_CIPHER_CTX_block_size(self->ctx));
if (!ciphertext) return NULL;
self->state = 1;
int offset = 0;
if (plaintext_len) {
int len = PyBytes_GET_SIZE(ciphertext);
if (1 != EVP_EncryptUpdate(self->ctx, (unsigned char *)PyBytes_AS_STRING(ciphertext), &len, (const unsigned char *)plaintext, plaintext_len)) {
Py_CLEAR(ciphertext);
return set_error_from_openssl("Failed to encrypt");
}
offset = len;
}
if (finish_encryption) {
int len = PyBytes_GET_SIZE(ciphertext) - offset;
if (1 != EVP_EncryptFinal_ex(self->ctx, (unsigned char *)PyBytes_AS_STRING(ciphertext) + offset, &len)) {
Py_CLEAR(ciphertext);
return set_error_from_openssl("Failed to finish encryption");
}
offset += len;
self->state = 2;
PyObject *tag = PyBytes_FromStringAndSize(NULL, cipher_ctx_tag_length(self->ctx));
if (!tag) {
Py_CLEAR(ciphertext);
return NULL;
}
if (1 != EVP_CIPHER_CTX_ctrl(self->ctx, EVP_CTRL_AEAD_GET_TAG, PyBytes_GET_SIZE(tag), PyBytes_AS_STRING(tag))) {
Py_CLEAR(tag);
Py_CLEAR(ciphertext);
return set_error_from_openssl("Failed to get the tag");
}
Py_CLEAR(self->tag);
self->tag = tag;
}
if (offset != PyBytes_GET_SIZE(ciphertext)) {
_PyBytes_Resize(&ciphertext, offset);
if (!ciphertext) return NULL;
}
return ciphertext;
}
static PyMethodDef aes256gcmencrypt_methods[] = {
METHODB(add_authenticated_but_unencrypted_data, METH_VARARGS), METHODB(add_data_to_be_encrypted, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */
};
static PyMemberDef aes256gcmencrypt_members[] = {
{"iv", T_OBJECT_EX, offsetof(AES256GCMEncrypt, iv), READONLY, "IV"},
{"tag", T_OBJECT_EX, offsetof(AES256GCMEncrypt, tag), READONLY, "The tag for authentication"},
{NULL}};
static PyTypeObject AES256GCMEncrypt_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.AES256GCMEncrypt",
.tp_basicsize = sizeof(AES256GCMEncrypt),
.tp_dealloc = (destructor)dealloc_aes256gcmencrypt,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Encrypt using AES 256 GCM with authentication",
.tp_new = new_aes256gcmencrypt,
.tp_methods = aes256gcmencrypt_methods,
.tp_members = aes256gcmencrypt_members,
};
// }}}
// AES256GCMDecrypt {{{
typedef struct {
PyObject_HEAD
EVP_CIPHER_CTX *ctx;
int state;
} AES256GCMDecrypt;
static PyObject *
new_aes256gcmdecrypt(PyTypeObject *type, PyObject *args, PyObject *kwds UNUSED) {
Secret *key;
unsigned char *iv, *tag;
Py_ssize_t iv_len, tag_len;
if (!PyArg_ParseTuple(args, "O!y#y#", &Secret_Type, &key, &iv, &iv_len, &tag, &tag_len)) return NULL;
const EVP_CIPHER *cipher = EVP_get_cipherbynid(NID_aes_256_gcm);
if (key->secret_len != (size_t)EVP_CIPHER_key_length(cipher)) {
PyErr_Format(PyExc_ValueError, "The key for AES 256 GCM must be %d bytes long", EVP_CIPHER_key_length(cipher));
return NULL;
}
if (iv_len < EVP_CIPHER_iv_length(cipher)) {
PyErr_Format(PyExc_ValueError, "The iv for AES 256 GCM must be at least %d bytes long", EVP_CIPHER_iv_length(cipher));
return NULL;
}
AES256GCMDecrypt *self = (AES256GCMDecrypt *)type->tp_alloc(type, 0);
if (!self) return NULL;
if (!(self->ctx = EVP_CIPHER_CTX_new())) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to allocate decryption context");
}
if (iv_len > EVP_CIPHER_iv_length(cipher)) {
if (!EVP_CIPHER_CTX_ctrl(self->ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL)) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to set the IV length");
}
}
if (1 != EVP_DecryptInit_ex(self->ctx, cipher, NULL, key->secret, iv)) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to initialize encryption context");
}
// Ensure tag length is 16 because the OpenSSL verification routines will happily pass even if you set a truncated tag.
if (tag_len < cipher_ctx_tag_length(self->ctx)) {
PyErr_Format(PyExc_ValueError, "Tag length for AES 256 GCM must be at least %d", cipher_ctx_tag_length(self->ctx));
Py_CLEAR(self);
return NULL;
}
if (!EVP_CIPHER_CTX_ctrl(self->ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag)) {
Py_CLEAR(self);
return set_error_from_openssl("Failed to set the tag");
}
return (PyObject *)self;
}
static void
dealloc_aes256gcmdecrypt(AES256GCMDecrypt *self) {
if (self->ctx) EVP_CIPHER_CTX_free(self->ctx);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
add_data_to_be_authenticated_but_not_decrypted(AES256GCMDecrypt *self, PyObject *args) {
if (self->state > 0) {
PyErr_SetString(Crypto_Exception, "Cannot add data once decryption has started");
return NULL;
}
const char *aad;
Py_ssize_t aad_len;
if (!PyArg_ParseTuple(args, "y#", &aad, &aad_len)) return NULL;
int len;
if (aad_len > 0 && 1 != EVP_DecryptUpdate(self->ctx, NULL, &len, (const unsigned char *)aad, aad_len))
return set_error_from_openssl("Failed to add AAD data");
Py_RETURN_NONE;
}
static PyObject *
add_data_to_be_decrypted(AES256GCMDecrypt *self, PyObject *args) {
if (self->state > 1) {
PyErr_SetString(Crypto_Exception, "Decryption has been finished");
return NULL;
}
const char *ciphertext;
Py_ssize_t ciphertext_len;
int finish_decryption = 0;
if (!PyArg_ParseTuple(args, "y#|p", &ciphertext, &ciphertext_len, &finish_decryption)) return NULL;
PyObject *plaintext = PyBytes_FromStringAndSize(NULL, ciphertext_len + 2 * EVP_CIPHER_CTX_block_size(self->ctx));
if (!plaintext) return NULL;
self->state = 1;
int offset = 0;
if (ciphertext_len) {
int len = PyBytes_GET_SIZE(plaintext);
if (1 != EVP_DecryptUpdate(self->ctx, (unsigned char *)PyBytes_AS_STRING(plaintext), &len, (const unsigned char *)ciphertext, ciphertext_len)) {
Py_CLEAR(plaintext);
return set_error_from_openssl("Failed to decrypt");
}
offset = len;
}
if (finish_decryption) {
int len = PyBytes_GET_SIZE(plaintext) - offset;
int ret = EVP_DecryptFinal_ex(self->ctx, (unsigned char *)PyBytes_AS_STRING(plaintext) + offset, &len);
self->state = 2;
if (ret <= 0) {
Py_CLEAR(plaintext);
PyErr_SetString(Crypto_Exception, "Failed to finish decrypt");
return NULL;
}
offset += len;
}
if (offset != PyBytes_GET_SIZE(plaintext)) {
_PyBytes_Resize(&plaintext, offset);
if (!plaintext) return NULL;
}
return plaintext;
}
static PyMethodDef aes256gcmdecrypt_methods[] = {
METHODB(add_data_to_be_authenticated_but_not_decrypted, METH_VARARGS), METHODB(add_data_to_be_decrypted, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */
};
static PyTypeObject AES256GCMDecrypt_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.AES256GCMDecrypt",
.tp_basicsize = sizeof(AES256GCMDecrypt),
.tp_dealloc = (destructor)dealloc_aes256gcmdecrypt,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Decrypt using AES 256 GCM with authentication",
.tp_new = new_aes256gcmdecrypt,
.tp_methods = aes256gcmdecrypt_methods,
};
// }}}
static PyMethodDef module_methods[] = {
METHODB(random_secret, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_crypto_library(PyObject *module) {
Crypto_Exception = PyErr_NewException("fast_data_types.CryptoError", NULL, NULL);
if (Crypto_Exception == NULL) return false;
if (PyModule_AddObject(module, "CryptoError", Crypto_Exception) != 0) return false;
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
ADD_TYPE(Secret);
ADD_TYPE(EllipticCurveKey);
ADD_TYPE(AES256GCMEncrypt);
ADD_TYPE(AES256GCMDecrypt);
if (PyModule_AddIntConstant(module, "X25519", EVP_PKEY_X25519) != 0) return false;
#define AI(which) \
if (PyModule_AddIntMacro(module, which) != 0) return false;
AI(SHA1_HASH);
AI(SHA224_HASH);
AI(SHA256_HASH);
AI(SHA384_HASH);
AI(SHA512_HASH);
#undef AI
return true;
}
+14
View File
@@ -0,0 +1,14 @@
/*
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
// Create a Secret object containing a copy of data
PyObject *secret_from_data(const void *data, size_t len);
// Get the data of a Secret object, without copying it. Sets a Python exception and returns false if obj is not a Secret.
bool secret_data(PyObject *obj, const void **data, size_t *len);
+407
View File
@@ -0,0 +1,407 @@
/*
* cursor.c
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "line.h"
#include <structmember.h>
static PyObject *
new_cursor_object(PyTypeObject *type, PyObject UNUSED *args, PyObject UNUSED *kwds) {
Cursor *self;
self = (Cursor *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static void
dealloc(Cursor *self) {
Py_TYPE(self)->tp_free((PyObject *)self);
}
#define EQ(x) (a->x == b->x)
static int
__eq__(Cursor *a, Cursor *b) {
return memcmp(&a->sgr, &b->sgr, sizeof(a->sgr)) == 0 && EQ(x) && EQ(y) && EQ(shape) && EQ(non_blinking);
}
#undef EQ
static const char *cursor_names[NUM_OF_CURSOR_SHAPES] = {"NO_SHAPE", "BLOCK", "BEAM", "UNDERLINE", "HOLLOW"};
#define BOOL(x) ((x) ? Py_True : Py_False)
static PyObject *
repr(Cursor *self) {
return PyUnicode_FromFormat(
"Cursor(x=%u, y=%u, shape=%s, blink=%R, fg=#%08x, bg=#%08x, bold=%R, italic=%R, reverse=%R, strikethrough=%R, dim=%R, decoration=%d, "
"decoration_fg=#%08x, text_blink=%R)",
self->x,
self->y,
(self->shape < NUM_OF_CURSOR_SHAPES ? cursor_names[self->shape] : "INVALID"),
BOOL(!self->non_blinking),
self->sgr.fg,
self->sgr.bg,
BOOL(self->sgr.bold),
BOOL(self->sgr.italic),
BOOL(self->sgr.reverse),
BOOL(self->sgr.strikethrough),
BOOL(self->sgr.dim),
self->sgr.decoration,
self->sgr.decoration_fg,
BOOL(self->sgr.blink));
}
void
cursor_reset_display_attrs(Cursor *self) {
zero_at_ptr(&self->sgr);
}
static void
parse_color(int *params, unsigned int *i, unsigned int count, uint32_t *result) {
unsigned int attr;
uint8_t r, g, b;
if (*i < count) {
attr = params[(*i)++];
switch (attr) {
case 5:
if (*i < count) *result = (params[(*i)++] & 0xFF) << 8 | 1;
break;
case 2:
if (*i + 2 < count) {
/* Ignore the first parameter in a four parameter RGB */
/* sequence (unused color space id), see https://github.com/kovidgoyal/kitty/issues/227 */
if (*i + 3 < count) (*i)++;
r = params[(*i)++] & 0xFF;
g = params[(*i)++] & 0xFF;
b = params[(*i)++] & 0xFF;
*result = r << 24 | g << 16 | b << 8 | 2;
}
break;
}
}
}
void
cursor_from_sgr(Cursor *self, int *params, unsigned int count, bool is_group) {
#define SET_COLOR(which) \
{ parse_color(params, &i, count, &self->which); } \
break;
START_ALLOW_CASE_RANGE
unsigned int i = 0, attr;
if (!count) {
params[0] = 0;
count = 1;
}
while (i < count) {
attr = params[i++];
switch (attr) {
case 0: cursor_reset_display_attrs(self); break;
case 1: self->sgr.bold = true; break;
case 2: self->sgr.dim = true; break;
case 3: self->sgr.italic = true; break;
case 4:
if (is_group && i < count) {
self->sgr.decoration = MIN(5, params[i]);
i++;
} else self->sgr.decoration = 1;
break;
case 5: self->sgr.blink = true; break;
case 7: self->sgr.reverse = true; break;
case 9: self->sgr.strikethrough = true; break;
case 21: self->sgr.decoration = 2; break;
case 221: self->sgr.bold = false; break;
case 222: self->sgr.dim = false; break;
case 22:
self->sgr.bold = false;
self->sgr.dim = false;
break;
case 23: self->sgr.italic = false; break;
case 24: self->sgr.decoration = 0; break;
case 25: self->sgr.blink = false; break;
case 27: self->sgr.reverse = false; break;
case 29: self->sgr.strikethrough = false; break;
case 30 ... 37: self->sgr.fg = ((attr - 30) << 8) | 1; break;
case 38: SET_COLOR(sgr.fg);
case 39: self->sgr.fg = 0; break;
case 40 ... 47: self->sgr.bg = ((attr - 40) << 8) | 1; break;
case 48: SET_COLOR(sgr.bg);
case 49: self->sgr.bg = 0; break;
case 90 ... 97: self->sgr.fg = ((attr - 90 + 8) << 8) | 1; break;
case 100 ... 107: self->sgr.bg = ((attr - 100 + 8) << 8) | 1; break;
case DECORATION_FG_CODE: SET_COLOR(sgr.decoration_fg);
case DECORATION_FG_CODE + 1: self->sgr.decoration_fg = 0; break;
}
if (is_group) break;
}
#undef SET_COLOR
END_ALLOW_CASE_RANGE
}
void
apply_sgr_to_cells(GPUCell *first_cell, unsigned int cell_count, int *params, unsigned int count, bool is_group) {
#define RANGE for (unsigned c = 0; c < cell_count; c++, cell++)
#define SET_COLOR(which) \
{ \
color_type color = 0; \
parse_color(params, &i, count, &color); \
if (color) { \
RANGE { cell->which = color; } \
} \
} \
break;
#define SIMPLE(which, val) \
RANGE { cell->which = (val); } \
break;
#define S(which, val) \
RANGE { cell->attrs.which = (val); } \
break;
unsigned int i = 0, attr;
if (!count) {
params[0] = 0;
count = 1;
}
while (i < count) {
GPUCell *cell = first_cell;
attr = params[i++];
switch (attr) {
case 0: {
const CellAttrs remove_sgr_mask = {.val = ~SGR_MASK};
RANGE {
cell->attrs.val &= remove_sgr_mask.val;
cell->fg = 0;
cell->bg = 0;
cell->decoration_fg = 0;
}
} break;
case 1: S(bold, true);
case 2: S(dim, true);
case 3: S(italic, true);
case 4: {
uint8_t val = 1;
if (is_group && i < count) {
val = MIN(5, params[i]);
i++;
}
S(decoration, val);
}
case 5: S(blink, true);
case 7: S(reverse, true);
case 9: S(strike, true);
case 21: S(decoration, 2);
case 221: S(bold, false);
case 222: S(dim, false);
case 22:
RANGE {
cell->attrs.bold = false;
cell->attrs.dim = false;
}
break;
case 23: S(italic, false);
case 24: S(decoration, 0);
case 25: S(blink, false);
case 27: S(reverse, false);
case 29: S(strike, false); START_ALLOW_CASE_RANGE
case 30 ... 37: SIMPLE(fg, ((attr - 30) << 8) | 1);
case 38: SET_COLOR(fg);
case 39: SIMPLE(fg, 0);
case 40 ... 47: SIMPLE(bg, ((attr - 40) << 8) | 1);
case 48: SET_COLOR(bg);
case 49: SIMPLE(bg, 0);
case 90 ... 97: SIMPLE(fg, ((attr - 90 + 8) << 8) | 1);
case 100 ... 107: SIMPLE(bg, ((attr - 100 + 8) << 8) | 1); END_ALLOW_CASE_RANGE
case DECORATION_FG_CODE: SET_COLOR(decoration_fg);
case DECORATION_FG_CODE + 1: SIMPLE(decoration_fg, 0);
}
if (is_group) break;
}
#undef SET_COLOR
#undef RANGE
#undef SIMPLE
#undef S
}
const char *
cursor_as_sgr(const Cursor *self) {
GPUCell blank_cell = {0}, cursor_cell = {
.attrs = cursor_to_attrs(self),
.fg = self->sgr.fg & COL_MASK,
.bg = self->sgr.bg & COL_MASK,
.decoration_fg = self->sgr.decoration_fg & COL_MASK,
};
return cell_as_sgr(&cursor_cell, &blank_cell);
}
static PyObject *
reset_display_attrs(Cursor *self, PyObject *a UNUSED) {
#define reset_display_attrs_doc "Reset all display attributes to unset"
cursor_reset_display_attrs(self);
Py_RETURN_NONE;
}
void
cursor_reset(Cursor *self) {
cursor_reset_display_attrs(self);
self->x = 0;
self->y = 0;
self->shape = NO_CURSOR_SHAPE;
self->non_blinking = false;
}
void
cursor_copy_to(Cursor *src, Cursor *dest) {
#define CCY(x) dest->x = src->x;
CCY(x);
CCY(y);
CCY(shape);
CCY(non_blinking);
#undef CCY
memcpy(&dest->sgr, &src->sgr, sizeof(dest->sgr));
}
static PyObject *copy(Cursor *self, PyObject *);
#define copy_doc "Create a clone of this cursor"
// Boilerplate {{{
#define SGR_BOOL_GETSET(x) \
static PyObject *x##_get(Cursor *self, void UNUSED *closure) { \
PyObject *ans = self->sgr.x ? Py_True : Py_False; \
Py_INCREF(ans); \
return ans; \
} \
static int x##_set(Cursor *self, PyObject *value, void UNUSED *closure) { \
if (value == NULL) { \
PyErr_SetString(PyExc_TypeError, "Cannot delete attribute"); \
return -1; \
} \
self->sgr.x = PyObject_IsTrue(value) ? true : false; \
return 0; \
}
SGR_BOOL_GETSET(bold)
SGR_BOOL_GETSET(italic)
SGR_BOOL_GETSET(reverse)
SGR_BOOL_GETSET(strikethrough)
SGR_BOOL_GETSET(dim)
#undef SGR_BOOL_GETSET
static PyObject *
blink_get(Cursor *self, void UNUSED *closure) {
PyObject *ans = !self->non_blinking ? Py_True : Py_False;
Py_INCREF(ans);
return ans;
}
static int
blink_set(Cursor *self, PyObject *value, void UNUSED *closure) {
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete attribute");
return -1;
}
self->non_blinking = PyObject_IsTrue(value) ? false : true;
return 0;
}
static PyObject *
text_blink_get(Cursor *self, void UNUSED *closure) {
return Py_NewRef(self->sgr.blink ? Py_True : Py_False);
}
static int
text_blink_set(Cursor *self, PyObject *value, void UNUSED *closure) {
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete attribute");
return -1;
}
int blink = PyObject_IsTrue(value);
if (blink < 0) return -1;
self->sgr.blink = blink;
return 0;
}
#define SGR_UINT_GETSET(x) \
static PyObject *x##_get(Cursor *self, void UNUSED *closure) { return PyLong_FromUnsignedLong((unsigned long)self->sgr.x); } \
static int x##_set(Cursor *self, PyObject *value, void UNUSED *closure) { \
if (value == NULL) { \
PyErr_SetString(PyExc_TypeError, "Cannot delete attribute"); \
return -1; \
} \
if (!PyLong_Check(value)) { \
PyErr_SetString(PyExc_TypeError, "value must be an int"); \
return -1; \
} \
self->sgr.x = PyLong_AsUnsignedLong(value); \
return 0; \
}
SGR_UINT_GETSET(decoration)
SGR_UINT_GETSET(fg)
SGR_UINT_GETSET(bg)
SGR_UINT_GETSET(decoration_fg)
static PyMemberDef members[] = {
{"x", T_UINT, offsetof(Cursor, x), 0, "x"},
{"y", T_UINT, offsetof(Cursor, y), 0, "y"},
{"shape", T_INT, offsetof(Cursor, shape), 0, "shape"},
{NULL} /* Sentinel */
};
static PyGetSetDef getseters[] = {
GETSET(bold) GETSET(italic) GETSET(reverse) GETSET(strikethrough) GETSET(dim) GETSET(blink) GETSET(text_blink) GETSET(decoration) GETSET(fg) GETSET(bg)
GETSET(decoration_fg){NULL} /* Sentinel */
};
static PyMethodDef methods[] = {
METHOD(copy, METH_NOARGS) METHOD(reset_display_attrs, METH_NOARGS){NULL} /* Sentinel */
};
static PyObject *richcmp(PyObject *obj1, PyObject *obj2, int op);
PyTypeObject Cursor_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.Cursor",
.tp_basicsize = sizeof(Cursor),
.tp_dealloc = (destructor)dealloc,
.tp_repr = (reprfunc)repr,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Cursors",
.tp_richcompare = richcmp,
.tp_methods = methods,
.tp_members = members,
.tp_getset = getseters,
.tp_new = new_cursor_object,
};
RICHCMP(Cursor)
// }}}
Cursor *
cursor_copy(Cursor *self) {
Cursor *ans;
ans = alloc_cursor();
if (ans == NULL) {
PyErr_NoMemory();
return NULL;
}
cursor_copy_to(self, ans);
return ans;
}
static PyObject *
copy(Cursor *self, PyObject *a UNUSED) {
return (PyObject *)cursor_copy(self);
}
Cursor *
alloc_cursor(void) {
return (Cursor *)new_cursor_object(&Cursor_Type, NULL, NULL);
}
INIT_TYPE(Cursor)
+209
View File
@@ -0,0 +1,209 @@
#include <float.h>
#include "state.h"
#define WD w->render_data
#define EDGE(axis, index) ct->cursor_edge_##axis[index]
inline static float
norm(float x, float y) {
return sqrtf(x * x + y * y);
}
typedef struct ndc_coords {
float xstart, ystart, dx, dy;
} ndc_coords;
static void
update_cursor_trail_target(CursorTrail *ct, Window *w, ndc_coords g) {
float left = FLT_MAX, right = FLT_MAX, top = FLT_MAX, bottom = FLT_MAX;
switch (WD.screen->cursor_render_info.shape) {
case CURSOR_BLOCK:
case CURSOR_HOLLOW:
case CURSOR_BEAM:
case CURSOR_UNDERLINE: left = g.xstart + WD.screen->cursor_render_info.x * g.dx; bottom = g.ystart - (WD.screen->cursor_render_info.y + 1) * g.dy;
default: break;
}
switch (WD.screen->cursor_render_info.shape) {
case CURSOR_BLOCK:
case CURSOR_HOLLOW:
right = left + g.dx;
top = bottom + g.dy;
break;
case CURSOR_BEAM:
right = left + g.dx / WD.screen->cell_size.width * OPT(cursor_beam_thickness);
top = bottom + g.dy;
break;
case CURSOR_UNDERLINE:
right = left + g.dx;
top = bottom + g.dy / WD.screen->cell_size.height * OPT(cursor_underline_thickness);
break;
default: break;
}
if (left != FLT_MAX) {
if (EDGE(x, 0) != left || EDGE(x, 1) != right || EDGE(y, 0) != top || EDGE(y, 1) != bottom) {
ct->target_updated = true;
ct->window_changed = ct->window_id && ct->window_id != w->id;
ct->window_id = w->id;
if (ct->prev_edge_valid) {
ct->prev_cursor_edge_x[0] = EDGE(x, 0);
ct->prev_cursor_edge_x[1] = EDGE(x, 1);
ct->prev_cursor_edge_y[0] = EDGE(y, 0);
ct->prev_cursor_edge_y[1] = EDGE(y, 1);
}
}
ct->prev_edge_valid = true;
EDGE(x, 0) = left;
EDGE(x, 1) = right;
EDGE(y, 0) = top;
EDGE(y, 1) = bottom;
}
}
static void
record_cursor_move(CursorTrail *ct, monotonic_t now) {
memmove(ct->history + 1, ct->history, sizeof(ct->history) - sizeof(ct->history[0]));
CursorMove *m = ct->history;
memcpy(m->from_x, ct->prev_cursor_edge_x, sizeof(m->from_x));
memcpy(m->from_y, ct->prev_cursor_edge_y, sizeof(m->from_y));
memcpy(m->to_x, ct->cursor_edge_x, sizeof(m->to_x));
memcpy(m->to_y, ct->cursor_edge_y, sizeof(m->to_y));
m->at = now;
}
static bool
should_skip_cursor_trail_update(CursorTrail *ct, ndc_coords g, OSWindow *os_window, Window *w) {
if (os_window->live_resize.in_progress) { return true; }
if (!WD.screen->modes.mDECTCEM && ct->opacity <= 0.0f) { return true; }
// moving to a different window is a change of context, so always show the trail for it
if ((OPT(cursor_trail_start_threshold_x) > 0 || OPT(cursor_trail_start_threshold_y) > 0) && !ct->needs_render && !ct->window_changed) {
int dx = (int)round((ct->corner_x[0] - EDGE(x, 1)) / g.dx);
int dy = (int)round((ct->corner_y[0] - EDGE(y, 0)) / g.dy);
if (abs(dx) <= OPT(cursor_trail_start_threshold_x) && abs(dy) <= OPT(cursor_trail_start_threshold_y)) { return true; }
}
return false;
}
static void
update_cursor_trail_corners(CursorTrail *ct, ndc_coords g, monotonic_t now, OSWindow *os_window, Window *w) {
// the trail corners move towards the cursor corner at a speed proportional to their distance from the cursor corner.
// equivalent to exponential ease out animation.
static const int corner_index[2][4] = {{1, 1, 0, 0}, {0, 1, 1, 0}};
// the decay time for the trail to reach 1/1024 of its distance from the cursor corner
float decay_fast = OPT(cursor_trail_decay_fast);
float decay_slow = OPT(cursor_trail_decay_slow);
if (should_skip_cursor_trail_update(ct, g, os_window, w)) {
ct->target_updated = false;
for (int i = 0; i < 4; ++i) {
ct->corner_x[i] = EDGE(x, corner_index[0][i]);
ct->corner_y[i] = EDGE(y, corner_index[1][i]);
}
} else if (ct->updated_at < now) {
float cursor_center_x = (EDGE(x, 0) + EDGE(x, 1)) * 0.5f;
float cursor_center_y = (EDGE(y, 0) + EDGE(y, 1)) * 0.5f;
float cursor_diag_2 = norm(EDGE(x, 1) - EDGE(x, 0), EDGE(y, 1) - EDGE(y, 0)) * 0.5f;
float dt = (float)monotonic_t_to_s_double(now - ct->updated_at);
// dot product here is used to dynamically adjust the decay speed of
// each corner. The closer the corner is to the cursor, the faster it
// moves.
float dx[4], dy[4];
float dot[4]; // dot product of "direction vector" and "cursor center to corner vector"
for (int i = 0; i < 4; ++i) {
dx[i] = EDGE(x, corner_index[0][i]) - ct->corner_x[i];
dy[i] = EDGE(y, corner_index[1][i]) - ct->corner_y[i];
if (fabsf(dx[i]) < 1e-6 && fabsf(dy[i]) < 1e-6) {
dx[i] = dy[i] = 0.0f;
dot[i] = 0.0f;
continue;
}
dot[i] = (dx[i] * (EDGE(x, corner_index[0][i]) - cursor_center_x) + dy[i] * (EDGE(y, corner_index[1][i]) - cursor_center_y)) / cursor_diag_2 /
norm(dx[i], dy[i]);
}
float min_dot = FLT_MAX, max_dot = -FLT_MAX;
for (int i = 0; i < 4; ++i) {
min_dot = fminf(min_dot, dot[i]);
max_dot = fmaxf(max_dot, dot[i]);
}
for (int i = 0; i < 4; ++i) {
if ((dx[i] == 0 && dy[i] == 0) || min_dot == FLT_MAX) { continue; }
float decay = (min_dot == max_dot) ? decay_slow : decay_slow + (decay_fast - decay_slow) * (dot[i] - min_dot) / (max_dot - min_dot);
float step = 1.0f - exp2f(-10.0f * dt / decay);
ct->corner_x[i] += dx[i] * step;
ct->corner_y[i] += dy[i] * step;
}
}
ct->window_changed = false;
}
static void
update_cursor_trail_opacity(CursorTrail *ct, Window *w, monotonic_t now) {
const bool cursor_trail_always_visible = false;
if (cursor_trail_always_visible) {
ct->opacity = 1.0f;
} else if (WD.screen->modes.mDECTCEM) {
ct->opacity += (float)monotonic_t_to_s_double(now - ct->updated_at) / OPT(cursor_trail_decay_slow);
ct->opacity = fminf(ct->opacity, 1.0f);
} else {
ct->opacity -= (float)monotonic_t_to_s_double(now - ct->updated_at) / OPT(cursor_trail_decay_slow);
ct->opacity = fmaxf(ct->opacity, 0.0f);
}
}
static void
update_cursor_trail_needs_render(CursorTrail *ct, Window *w, ndc_coords g) {
static const int corner_index[2][4] = {{1, 1, 0, 0}, {0, 1, 1, 0}};
ct->needs_render = false;
// check if any corner is still far from the cursor corner, so it should be rendered
const float dx_threshold = g.dx / WD.screen->cell_size.width * 0.5f;
const float dy_threshold = g.dy / WD.screen->cell_size.height * 0.5f;
for (int i = 0; i < 4; ++i) {
float dx = fabsf(EDGE(x, corner_index[0][i]) - ct->corner_x[i]);
float dy = fabsf(EDGE(y, corner_index[1][i]) - ct->corner_y[i]);
if (dx_threshold <= dx || dy_threshold <= dy) {
ct->needs_render = true;
break;
}
}
}
bool
update_cursor_trail(CursorTrail *ct, Window *w, monotonic_t now, OSWindow *os_window) {
// remember where the trail was drawn in the previous frame, for shaders that do motion blur
memcpy(ct->previous_corner_x, ct->corner_x, sizeof(ct->previous_corner_x));
memcpy(ct->previous_corner_y, ct->corner_y, sizeof(ct->previous_corner_y));
ct->target_updated = false;
ndc_coords g = {
.xstart = gl_pos_x(w->render_data.geometry.left, os_window->viewport_width),
.ystart = gl_pos_y(w->render_data.geometry.top, os_window->viewport_height),
.dx = gl_size(w->render_data.screen->cell_size.width, os_window->viewport_width),
.dy = gl_size(w->render_data.screen->cell_size.height, os_window->viewport_height),
};
bool had_prev_edge = ct->prev_edge_valid;
if (!WD.screen->paused_rendering.expires_at && OPT(cursor_trail) <= now - WD.screen->cursor->position_changed_by_client_at) {
update_cursor_trail_target(ct, w, g);
}
if (ct->target_updated && had_prev_edge) ct->cursor_changed_at = now;
update_cursor_trail_corners(ct, g, now, os_window, w);
// update_cursor_trail_corners() clears target_updated for moves too small to start a trail
if (ct->target_updated && had_prev_edge) record_cursor_move(ct, now);
update_cursor_trail_opacity(ct, w, now);
bool needs_render_prev = ct->needs_render;
update_cursor_trail_needs_render(ct, w, g);
ct->updated_at = now;
// returning true here will cause the cells to be drawn
return ct->needs_render || needs_render_prev;
}
#undef WD
#undef EDGE
+1060
View File
File diff suppressed because it is too large. Load diff
+451
View File
@@ -0,0 +1,451 @@
/*
* data-types.h
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#ifdef _POSIX_C_SOURCE
#error "Must include \"data-types.h\" before any system headers"
#endif
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <assert.h>
#include <stdint.h>
#include <stdbool.h>
#include <poll.h>
#include <pthread.h>
#include <locale.h>
#include "glfw-wrapper.h"
#include "banned.h"
// Required minimum OpenGL version
#define OPENGL_REQUIRED_VERSION_MAJOR 3
#ifdef __APPLE__
#include <xlocale.h>
#define OPENGL_REQUIRED_VERSION_MINOR 3
#else
#define OPENGL_REQUIRED_VERSION_MINOR 1
#endif
#define GLSL_VERSION 140
#define GLFW_MOD_KITTY (GLFW_MOD_LAST * 2)
#define UNUSED __attribute__((unused))
#define PYNOARG PyObject *__a1 UNUSED, PyObject *__a2 UNUSED
#define EXPORTED __attribute__((visibility("default")))
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#define MAX(x, y) \
__extension__({ \
const __typeof__(x) __a__ = (x); \
const __typeof__(y) __b__ = (y); \
__a__ > __b__ ? __a__ : __b__; \
})
#define MIN(x, y) \
__extension__({ \
const __typeof__(x) __a__ = (x); \
const __typeof__(y) __b__ = (y); \
__a__ < __b__ ? __a__ : __b__; \
})
#define SWAP(x, y) \
do { \
__typeof__(x) _sw_ = y; \
y = x; \
x = _sw_; \
} while (0)
#define xstr(s) str(s)
#define str(s) #s
#define arraysz(x) (sizeof(x) / sizeof(x[0]))
#define zero_at_i(array, idx) memset((array) + (idx), 0, sizeof((array)[0]))
#define zero_at_ptr(p) memset((p), 0, sizeof((p)[0]))
#define literal_strlen(x) (sizeof(x) - 1)
#define zero_at_ptr_count(p, count) memset((p), 0, (count) * sizeof((p)[0]))
#define C0_EXCEPT_NL_SPACE_TAB_DEL 0x0 ... 0x8 : case 0xb ... 0x1f
#define C0_EXCEPT_NL_SPACE_TAB \
0x0 ... 0x8 : case 0xb ... 0x1f: \
case 0x7f
void log_error(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
#define fatal(...) \
{ \
log_error(__VA_ARGS__); \
exit(EXIT_FAILURE); \
}
static inline void
cleanup_free(void *p) {
free(*(void **)p);
}
#define RAII_ALLOC(type, name, initializer) __attribute__((cleanup(cleanup_free))) type *name = initializer
static inline void
cleanup_decref(PyObject **p) {
Py_CLEAR(*p);
}
#define RAII_PyObject(name, initializer) __attribute__((cleanup(cleanup_decref))) PyObject *name = initializer
#define RAII_PY_BUFFER(name) __attribute__((cleanup(PyBuffer_Release))) Py_buffer name = {0}
typedef unsigned long long id_type;
typedef uint32_t char_type;
static_assert(sizeof(Py_UCS4) == sizeof(char_type), "PyUCS4 and char_type dont match");
#define MAX_CHAR_TYPE_VALUE UINT32_MAX
typedef uint32_t color_type;
typedef uint16_t hyperlink_id_type;
typedef int key_type;
#define HYPERLINK_MAX_NUMBER UINT16_MAX
typedef uint16_t combining_type;
typedef uint16_t glyph_index;
typedef uint32_t pixel;
typedef unsigned int index_type;
typedef uint32_t sprite_index;
typedef enum CursorShapes { NO_CURSOR_SHAPE, CURSOR_BLOCK, CURSOR_BEAM, CURSOR_UNDERLINE, CURSOR_HOLLOW, NUM_OF_CURSOR_SHAPES } CursorShape;
typedef enum { DISABLE_LIGATURES_NEVER, DISABLE_LIGATURES_CURSOR, DISABLE_LIGATURES_ALWAYS } DisableLigature;
#define ERROR_PREFIX "[PARSE ERROR]"
typedef enum MouseTrackingModes { NO_TRACKING, BUTTON_MODE, MOTION_MODE, ANY_MODE } MouseTrackingMode;
typedef enum MouseTrackingProtocols { NORMAL_PROTOCOL, UTF8_PROTOCOL, SGR_PROTOCOL, URXVT_PROTOCOL, SGR_PIXEL_PROTOCOL } MouseTrackingProtocol;
typedef enum MouseShapes {
INVALID_POINTER,
/* start mouse shapes (auto generated by gen-key-constants.py do not edit) */
DEFAULT_POINTER,
TEXT_POINTER,
POINTER_POINTER,
HELP_POINTER,
WAIT_POINTER,
PROGRESS_POINTER,
CROSSHAIR_POINTER,
CELL_POINTER,
VERTICAL_TEXT_POINTER,
MOVE_POINTER,
E_RESIZE_POINTER,
NE_RESIZE_POINTER,
NW_RESIZE_POINTER,
N_RESIZE_POINTER,
SE_RESIZE_POINTER,
SW_RESIZE_POINTER,
S_RESIZE_POINTER,
W_RESIZE_POINTER,
EW_RESIZE_POINTER,
NS_RESIZE_POINTER,
NESW_RESIZE_POINTER,
NWSE_RESIZE_POINTER,
ZOOM_IN_POINTER,
ZOOM_OUT_POINTER,
ALIAS_POINTER,
COPY_POINTER,
NOT_ALLOWED_POINTER,
NO_DROP_POINTER,
GRAB_POINTER,
GRABBING_POINTER,
/* end mouse shapes */
} MouseShape;
typedef enum { NONE, MENUBAR, WINDOW, ALL } WindowTitleIn;
typedef enum {
SCROLLBAR_NEVER,
SCROLLBAR_ON_SCROLLED,
SCROLLBAR_ON_HOVERED,
SCROLLBAR_ON_SCROLL_AND_HOVER,
SCROLLBAR_ON_SCROLL_OR_HOVER,
SCROLLBAR_ALWAYS
} ScrollbarVisibilityPolicy;
typedef enum { PROGRESS_BAR_HIDDEN, PROGRESS_BAR_LEFT, PROGRESS_BAR_RIGHT, PROGRESS_BAR_TOP, PROGRESS_BAR_BOTTOM } ProgressBarPosition;
typedef enum { PROGRESS_STATE_UNSET, PROGRESS_STATE_SET, PROGRESS_STATE_ERROR, PROGRESS_STATE_INDETERMINATE, PROGRESS_STATE_PAUSED } ProgressBarState;
typedef enum { TILING, SCALED, MIRRORED, CLAMPED, CENTER_CLAMPED, CENTER_SCALED } BackgroundImageLayout;
typedef enum { PADDING_FILL_BACKGROUND, PADDING_FILL_NEIGHBORING_CELL } PaddingFillStrategy;
typedef struct ImageAnchorPosition {
float canvas_x, canvas_y, image_x, image_y;
} ImageAnchorPosition;
#define MAX_CHILDREN 512
#define BLANK_CHAR 0
#define COL_MASK 0xFFFFFFFF
#define DECORATION_FG_CODE 58
// PUA character used as an image placeholder.
#define IMAGE_PLACEHOLDER_CHAR 0x10EEEE
#define FG 1
#define BG 2
#define COPY_CELL(src, s, dest, d) \
(dest)->cpu_cells[d] = (src)->cpu_cells[s]; \
(dest)->gpu_cells[d] = (src)->gpu_cells[s];
#define COPY_SELF_CELL(s, d) COPY_CELL(self, s, self, d)
#define METHOD(name, arg_type) {#name, (PyCFunction)name, arg_type, name##_doc},
#define METHODB(name, arg_type) {#name, (PyCFunction)name, arg_type, ""}
#define BOOL_GETSET(type, x) \
static PyObject *x##_get(type *self, void UNUSED *closure) { \
PyObject *ans = self->x ? Py_True : Py_False; \
Py_INCREF(ans); \
return ans; \
} \
static int x##_set(type *self, PyObject *value, void UNUSED *closure) { \
if (value == NULL) { \
PyErr_SetString(PyExc_TypeError, "Cannot delete attribute"); \
return -1; \
} \
self->x = PyObject_IsTrue(value) ? true : false; \
return 0; \
}
#define GETSET(x) {#x, (getter)x##_get, (setter)x##_set, #x, NULL},
#ifndef EXTRA_INIT
#define EXTRA_INIT
#endif
#define INIT_TYPE(type) \
int init_##type(PyObject *module) { \
if (PyType_Ready(&type##_Type) < 0) return 0; \
if (PyModule_AddObject(module, #type, (PyObject *)&type##_Type) != 0) return 0; \
Py_INCREF(&type##_Type); \
EXTRA_INIT; \
return 1; \
}
#define RICHCMP(type) \
static PyObject *richcmp(PyObject *obj1, PyObject *obj2, int op) { \
PyObject *result = NULL; \
int eq; \
if (op != Py_EQ && op != Py_NE) { Py_RETURN_NOTIMPLEMENTED; } \
if (!PyObject_TypeCheck(obj1, &type##_Type)) { Py_RETURN_FALSE; } \
if (!PyObject_TypeCheck(obj2, &type##_Type)) { Py_RETURN_FALSE; } \
eq = __eq__((type *)obj1, (type *)obj2); \
if (op == Py_NE) result = eq ? Py_False : Py_True; \
else result = eq ? Py_True : Py_False; \
Py_INCREF(result); \
return result; \
}
#ifdef __clang__
#define START_IGNORE_DIAGNOSTIC(diag) _Pragma(xstr(clang diagnostic push)) _Pragma(xstr(clang diagnostic ignored diag))
#define END_IGNORE_DIAGNOSTIC _Pragma("clang diagnostic pop")
#else
#define START_IGNORE_DIAGNOSTIC(diag) _Pragma(xstr(GCC diagnostic push)) _Pragma(xstr(GCC diagnostic ignored diag))
#define END_IGNORE_DIAGNOSTIC _Pragma("GCC diagnostic pop")
#endif
#define IGNORE_PEDANTIC_WARNINGS START_IGNORE_DIAGNOSTIC("-Wpedantic")
#define END_IGNORE_PEDANTIC_WARNINGS END_IGNORE_DIAGNOSTIC
#define ALLOW_UNUSED_RESULT START_IGNORE_DIAGNOSTIC("-Wunused-result")
#define END_ALLOW_UNUSED_RESULT END_IGNORE_DIAGNOSTIC
#define START_ALLOW_CASE_RANGE IGNORE_PEDANTIC_WARNINGS
#define END_ALLOW_CASE_RANGE END_IGNORE_PEDANTIC_WARNINGS
#define BIT_MASK(__TYPE__, __ONE_COUNT__) (((__TYPE__)(-((__ONE_COUNT__) != 0))) & (((__TYPE__) - 1) >> ((sizeof(__TYPE__) * CHAR_BIT) - (__ONE_COUNT__))))
#define ADD_TYPE(which) \
if (PyType_Ready(&which##_Type) < 0) return false; \
if (PyModule_AddObject(module, #which, (PyObject *)&which##_Type) != 0) return false; \
Py_INCREF(&which##_Type);
typedef enum UTF8State { UTF8_ACCEPT = 0, UTF8_REJECT = 1 } UTF8State;
typedef struct {
// right = left + width, bottom = top + height
uint32_t left, top, right, bottom;
} Region;
typedef enum { UNKNOWN_PROMPT_KIND = 0, PROMPT_START = 1, SECONDARY_PROMPT = 2, OUTPUT_START = 3 } PromptKind;
typedef struct {
int x;
} *HYPERLINK_POOL_HANDLE;
typedef struct {
Py_UCS4 *buf;
size_t len, capacity;
HYPERLINK_POOL_HANDLE hyperlink_pool;
hyperlink_id_type active_hyperlink_id;
} ANSIBuf;
typedef struct {
PyObject_HEAD monotonic_t position_changed_by_client_at;
unsigned int x, y;
bool non_blinking;
CursorShape shape;
struct {
bool bold, italic, reverse, strikethrough, dim, blink;
uint8_t decoration;
color_type fg, bg, decoration_fg;
} sgr;
} Cursor;
typedef struct {
bool is_focused, render_even_when_unfocused, is_visible;
CursorShape shape;
unsigned x, y, multicursor_count;
float cursor_opacity, text_blink_opacity;
} CursorRenderInfo;
typedef enum DynamicColorType { COLOR_NOT_SET, COLOR_IS_SPECIAL, COLOR_IS_INDEX, COLOR_IS_RGB } DynamicColorType;
typedef union DynamicColor {
struct {
color_type rgb : 24;
DynamicColorType type : 8;
};
color_type val;
} DynamicColor;
typedef struct {
DynamicColor default_fg, default_bg, cursor_color, cursor_text_color, highlight_fg, highlight_bg, visual_bell_color;
} DynamicColors;
typedef struct TransparentDynamicColor {
color_type color;
float opacity;
bool is_set;
} TransparentDynamicColor;
#define MARK_MASK (3u)
// Number of special colors such as the default foreground and background
// that indexed color images can use, they are the last colors in the
// 256 color palette available to such images, see graphics-protocol.rst
#define NUM_INDEXED_IMAGE_SPECIAL_COLORS (8u)
// One bit per entry of the 256 color palette
typedef uint64_t ColorTableMask[4];
// The background and foreground colors of the marks, entry i is for mark i + 1
typedef struct MarkColors {
DynamicColor bg[MARK_MASK], fg[MARK_MASK];
} MarkColors;
// A layer of colors. The configured colors of a window are the global layer
// (kitty.conf and the automatic color theme) with the window layer (launch
// --color, --copy-colors) on top and the session layer (color schemes from
// the ssh kitten) on top of that. Colors set by the program running in the
// window (escape codes or set-colors without --configured) are on top of all.
typedef struct ColorLayer {
// Entries of type COLOR_NOT_SET mean use the value from the layer below
DynamicColors dynamic_colors;
color_type color_table[256];
// Which entries in color_table are set, unused for the global layer, where all entries are set
ColorTableMask color_table_mask;
TransparentDynamicColor transparent_colors[8];
// Whether transparent_colors is set, unused for the global layer
bool transparent_colors_set;
MarkColors mark_colors;
} ColorLayer;
typedef struct {
PyObject_HEAD
bool dirty;
// color_table is the current palette and orig_color_table the configured
// palette. Entries in color_table that are set by the program are marked
// in overridden_color_table_mask, all other entries are the same as in
// orig_color_table.
color_type color_table[256], orig_color_table[256];
ColorTableMask overridden_color_table_mask;
TransparentDynamicColor configured_transparent_colors[8], overriden_transparent_colors[8];
struct {
DynamicColors dynamic_colors;
uint32_t color_table[256];
ColorTableMask color_table_mask;
TransparentDynamicColor transparent_colors[8];
MarkColors mark_colors;
} *color_stack;
unsigned int color_stack_idx, color_stack_sz;
// configured is the global, window and session layers combined. overridden
// has entries of type COLOR_NOT_SET for colors not set by the program.
DynamicColors configured, overridden;
ColorLayer global_layer, window_layer, session_layer;
// The mark colors set by the program, entries of type COLOR_NOT_SET for colors not set by the program
MarkColors overridden_mark_colors;
// The current mark colors resolved from the layers and overridden_mark_colors, in
// the layout used by the shaders, entry i is for mark i + 1 and the last entry is unused
color_type mark_foregrounds[MARK_MASK + 1], mark_backgrounds[MARK_MASK + 1];
} ColorProfile;
typedef struct {
unsigned width, height;
} CellPixelSize;
typedef struct {
int x;
} *SPRITE_MAP_HANDLE;
typedef struct FontCellMetrics {
unsigned int cell_width, cell_height, baseline, underline_position, underline_thickness, strikethrough_position, strikethrough_thickness;
} FontCellMetrics;
#define FONTS_DATA_HEAD \
SPRITE_MAP_HANDLE sprite_map; \
double logical_dpi_x, logical_dpi_y, font_sz_in_pts; \
FontCellMetrics fcm;
typedef struct {
FONTS_DATA_HEAD
} *FONTS_DATA_HANDLE;
#define clear_sprite_position(cell) (cell).sprite_idx = 0;
#define ensure_space_for(base, array, type, num, capacity, initial_cap, zero_mem) \
if ((base)->capacity < num) { \
size_t _newcap = MAX((size_t)initial_cap, MAX(2 * (base)->capacity, (size_t)num)); \
(base)->array = realloc((base)->array, sizeof(type) * _newcap); \
if ((base)->array == NULL) fatal("Out of memory while ensuring space for %zu elements in array of %s", (size_t)num, #type); \
if (zero_mem) memset((base)->array + (base)->capacity, 0, sizeof(type) * (_newcap - (base)->capacity)); \
(base)->capacity = _newcap; \
}
#define remove_i_from_array(array, i, count) \
{ \
(count)--; \
if ((i) < (count)) { memmove((array) + (i), (array) + (i) + 1, sizeof((array)[0]) * ((count) - (i))); } \
}
// Global functions
Cursor *alloc_cursor(void);
ColorProfile *alloc_color_profile(void);
void copy_color_profile(ColorProfile *, ColorProfile *);
PyObject *parse_bytes_dump(PyObject UNUSED *, PyObject *);
PyObject *parse_bytes(PyObject UNUSED *, PyObject *);
void cursor_reset(Cursor *);
Cursor *cursor_copy(Cursor *);
void cursor_copy_to(Cursor *src, Cursor *dest);
void cursor_reset_display_attrs(Cursor *);
void cursor_from_sgr(Cursor *self, int *params, unsigned int count, bool is_group);
const char *cursor_as_sgr(const Cursor *);
PyObject *cm_thread_write(PyObject *self, PyObject *args);
bool schedule_write_to_child(id_type id, unsigned int num, ...);
bool schedule_write_to_child_python(id_type id, const char *prefix, PyObject *tuple_of_str_or_bytes, const char *suffix);
void schedule_write_to_child_if_possible(id_type id, const char *data, size_t sz, bool *found, bool *too_much_data, size_t keep_space);
bool set_iutf8(int, bool);
DynamicColor colorprofile_to_color(const ColorProfile *self, DynamicColor entry, DynamicColor defval);
void colorprofile_reset(ColorProfile *self);
bool colorprofile_to_transparent_color(const ColorProfile *self, unsigned index, color_type *color, float *opacity);
color_type colorprofile_to_color_with_fallback(ColorProfile *self, DynamicColor entry, DynamicColor defval, DynamicColor fallback, DynamicColor falback_defval);
void copy_color_table_to_buffer(ColorProfile *self, color_type *address, int offset, size_t stride);
bool colorprofile_push_colors(ColorProfile *, unsigned int);
bool colorprofile_pop_colors(ColorProfile *, unsigned int);
void colorprofile_report_stack(ColorProfile *, unsigned int *, unsigned int *);
void set_mouse_cursor(MouseShape);
void enter_event(int modifiers, bool cursor_moved);
void leave_event(int modifiers);
void mouse_event(const int, int, int);
void focus_in_event(void);
void scroll_event(const GLFWScrollEvent *ev);
void on_key_input(const GLFWkeyevent *ev);
void request_window_attention(id_type, bool);
void free_drag_source(void);
locale_t get_c_locale(void);
#ifndef __APPLE__
void play_canberra_sound(const char *which_sound, const char *event_id, bool is_path, const char *role, const char *theme_name);
#endif
SPRITE_MAP_HANDLE alloc_sprite_map(void);
void free_sprite_data(FONTS_DATA_HANDLE);
const char *get_hyperlink_for_id(const HYPERLINK_POOL_HANDLE, hyperlink_id_type id, bool only_url);
#define memset_array(array, val, count) \
if ((count) > 0) { \
(array)[0] = (val); \
size_t __copied__ = 1; \
while (__copied__ < (count)) { \
const size_t __num__ = MIN(__copied__, (count) - __copied__); \
memcpy((array) + __copied__, (array), __num__ * sizeof((val))); \
__copied__ += __num__; \
} \
}
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import socket
import sys
import termios
import time
from collections.abc import Callable, Iterator, Sequence
from contextlib import suppress
from functools import partial
from pprint import pformat
from typing import IO, TYPE_CHECKING, Protocol, cast
from kittens.tui.operations import colored, styled
from .child import cmdline_of_pid
from .cli import version
from .colors import theme_colors
from .constants import extensions_dir, is_macos, is_wayland, kitty_base_dir, kitty_exe, shell_path
from .fast_data_types import Color, SingleKey, current_fonts, glfw_get_system_color_theme, gpu_driver_version_string, num_users, wayland_compositor_data
from .options.types import Options as KittyOpts
from .options.types import defaults, secret_options
from .options.utils import KeyboardMode, KeyDefinition
from .rgb import color_as_sharp, color_from_int
from .types import Shortcut, mod_to_names
from .utils import shlex_split
Print = Callable[..., None]
ShortcutMap = dict[Shortcut, str]
if TYPE_CHECKING:
from .fast_data_types import FontFace
else:
FontFace = object
def green(x: str) -> str:
return colored(x, 'green')
def yellow(x: str) -> str:
return colored(x, 'yellow')
def title(x: str) -> str:
return colored(x, 'blue', intense=True)
def print_event(ev: str, defn: str, print: Print) -> None:
print(f'\t{ev} → {defn}')
def print_mapping_changes(defns: dict[str, str], changes: set[str], text: str, print: Print) -> None:
if changes:
print(title(text))
for k in sorted(changes):
print_event(k, defns[k], print)
class AnyEvent(Protocol):
def human_repr(self, kitty_mod: int = 0) -> str: ...
def compare_maps[T: AnyEvent](
final: dict[T, str], final_kitty_mod: int, initial: dict[T, str], initial_kitty_mod: int, print: Print, mode_name: str = ''
) -> None:
ei = {k.human_repr(initial_kitty_mod): v for k, v in initial.items()}
ef = {k.human_repr(final_kitty_mod): v for k, v in final.items()}
added = set(ef) - set(ei)
removed = set(ei) - set(ef)
changed = {k for k in set(ef) & set(ei) if ef[k] != ei[k]}
which = 'shortcuts' if isinstance(next(iter(initial or final)), Shortcut) else 'mouse actions'
if mode_name and (added or removed or changed):
print(f'{title("Changes in keyboard mode: " + mode_name)}')
print_mapping_changes(ef, added, f'Added {which}:', print)
print_mapping_changes(ei, removed, f'Removed {which}:', print)
print_mapping_changes(ef, changed, f'Changed {which}:', print)
def compare_opts(opts: KittyOpts, global_shortcuts: dict[str, SingleKey] | None, print: Print) -> None:
from .config import load_config
print()
print('Config options different from defaults:')
default_opts = load_config()
ignored = ('keymap', 'sequence_map', 'mousemap', 'url_mappings', 'map', 'mouse_map')
changed_opts = [f for f in sorted(defaults._fields) if f not in ignored and getattr(opts, f) != getattr(defaults, f)]
field_len = max(map(len, changed_opts)) if changed_opts else 20
fmt = f'{{:{field_len:d}s}}'
colors = []
for f in changed_opts:
if f in secret_options:
print(title(f'{f}:'), 'REDACTED FOR SECURITY')
continue
val = getattr(opts, f)
if isinstance(val, dict):
print(f'{f}:')
if f == 'symbol_map':
for k in sorted(val):
print(f'\tU+{k[0]:04x} - U+{k[1]:04x} → {val[k]}')
elif f == 'modify_font':
for k in sorted(val):
print(' ', val[k])
elif f == 'exe_search_path':
for k in val:
print(' ', k)
else:
print(pformat(val))
else:
val = getattr(opts, f)
if isinstance(val, Color):
colors.append(fmt.format(f) + ' ' + color_as_sharp(val) + ' ' + styled(' ', bg=val))
else:
if f == 'kitty_mod':
print(fmt.format(f), '+'.join(mod_to_names(getattr(opts, f))))
elif f in ('wayland_titlebar_color', 'macos_titlebar_color'):
if val == 0:
cval = 'system'
elif val == 1:
cval = 'background'
else:
col = color_from_int(val >> 8)
cval = color_as_sharp(col) + ' ' + styled(' ', bg=col)
colors.append(fmt.format(f) + ' ' + cval)
else:
print(fmt.format(f), str(getattr(opts, f)))
compare_maps(opts.mousemap, opts.kitty_mod, default_opts.mousemap, default_opts.kitty_mod, print)
def as_str(defns: Sequence[KeyDefinition]) -> str:
seen = set()
uniq = []
for d in reversed(defns):
key = d.unique_identity_within_keymap
if key not in seen:
seen.add(key)
uniq.append(d)
return ', '.join(d.human_repr() for d in uniq)
def build_shortcut_map(km: KeyboardMode) -> ShortcutMap:
result: ShortcutMap = {}
for defns in km.keymap.values():
by_seq: dict[tuple[SingleKey, ...], list[KeyDefinition]] = {}
for d in defns:
by_seq.setdefault(d.full_key_sequence_to_trigger, []).append(d)
for seq, seq_defns in by_seq.items():
result[Shortcut(seq)] = as_str(seq_defns)
return result
for kmn, initial_ in default_opts.keyboard_modes.items():
initial = build_shortcut_map(initial_)
final_ = opts.keyboard_modes.get(kmn, KeyboardMode(kmn))
final = build_shortcut_map(final_)
if not kmn and global_shortcuts:
for action, sk in global_shortcuts.items():
sc = Shortcut((sk,))
if sc not in final:
final[sc] = action
compare_maps(final, opts.kitty_mod, initial, default_opts.kitty_mod, print, mode_name=kmn)
new_keyboard_modes = set(opts.keyboard_modes) - set(default_opts.keyboard_modes)
for kmn in new_keyboard_modes:
initial_ = KeyboardMode(kmn)
initial = build_shortcut_map(initial_)
final_ = opts.keyboard_modes[kmn]
final = build_shortcut_map(final_)
compare_maps(final, opts.kitty_mod, initial, default_opts.kitty_mod, print, mode_name=kmn)
if colors:
print(f'{title("Colors")}:', end='\n\t')
print('\n\t'.join(sorted(colors)))
class IssueData:
def __init__(self) -> None:
self.uname = os.uname()
self.s, self.n, self.r, self.v, self.m = self.uname
try:
self.hostname = self.o = socket.gethostname()
except Exception:
self.hostname = self.o = 'localhost'
_time = time.localtime()
self.formatted_time = self.d = time.strftime('%a %b %d %Y', _time)
self.formatted_date = self.t = time.strftime('%H:%M:%S', _time)
try:
self.tty_name = format_tty_name(os.ctermid())
except OSError:
self.tty_name = '(none)'
self.l = self.tty_name
self.baud_rate = 0
if sys.stdin.isatty():
with suppress(OSError):
self.baud_rate = termios.tcgetattr(sys.stdin.fileno())[5]
self.b = str(self.baud_rate)
try:
self.num_users = num_users()
except RuntimeError:
self.num_users = -1
self.u = str(self.num_users)
self.U = self.u + ' user' + ('' if self.num_users == 1 else 's')
self.vars = {}
with suppress(Exception), open('/etc/os-release') as osf:
for line in osf:
k, _, v = line.strip().partition('=')
self.vars[k] = ' '.join(shlex_split(v))
if not self.vars:
with suppress(Exception), open('/usr/lib/os-release') as osf:
for line in osf:
k, _, v = line.strip().partition('=')
self.vars[k] = ' '.join(shlex_split(v))
def translate_issue_char(self, char: str) -> str:
try:
return str(getattr(self, char)) if len(char) == 1 else char
except AttributeError:
return char
def parse_issue_file(self, issue_file: IO[str]) -> Iterator[str]:
state = 'normal'
varname = ''
for ch in issue_file.read():
match state:
case 'normal':
if ch == '\\':
state = 'escape'
else:
yield ch
case 'escape':
match ch:
case 'S':
state = 'sub_start'
case '\\':
yield '\\'
state = 'normal'
case _:
yield self.translate_issue_char(ch)
state = 'normal'
case 'sub_start':
if ch == '{': # }
state = 'sub'
varname = ''
else:
yield ch
state = 'normal'
case 'sub':
if ch == '}':
if val := self.vars.get(varname):
yield val
state = 'normal'
else:
varname += ch
def format_tty_name(raw: str) -> str:
return re.sub(r'^/dev/([^/]+)/([^/]+)$', r'\1\2', raw)
def compositor_name() -> str:
ans = 'X11'
if is_wayland():
ans = 'Wayland'
with suppress(Exception):
pid, missing_capabilities = wayland_compositor_data()
if pid > -1:
cmdline = cmdline_of_pid(pid)
exe = cmdline[0]
with suppress(Exception):
import subprocess
if exe.lower() == 'hyprland':
raw = subprocess.check_output(['hyprctl', 'version']).decode().strip()
m = re.search(r'^Tag:\s*(\S+)', raw, flags=re.M)
if m is not None:
exe = f'{exe} {m.group(1)}'
else:
exe = raw.splitlines()[0]
exe = subprocess.check_output([exe, '--version']).decode().strip().splitlines()[0]
ans += f' ({exe})'
if missing_capabilities:
ans += f' missing: {missing_capabilities}'
return ans
def issue_data() -> str:
with suppress(Exception):
idata = IssueData()
with open('/etc/issue', encoding='utf-8', errors='replace') as f:
return ''.join(idata.parse_issue_file(f)).strip()
return ''
def debug_config(opts: KittyOpts | None = None, global_shortcuts: dict[str, SingleKey] | None = None) -> str:
if opts is None:
from kitty.cli import create_default_opts
opts = create_default_opts()
from io import StringIO
out = StringIO()
p = partial(print, file=out)
p(version(add_rev=True))
p(' '.join(os.uname()))
if is_macos:
import subprocess
with suppress(Exception):
p(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip())
if idata := issue_data():
p(idata)
with suppress(Exception), open('/etc/lsb-release', encoding='utf-8', errors='replace') as f:
p(f.read().strip())
if not is_macos:
p('Running under:', green(compositor_name()))
p(green('OpenGL:'), gpu_driver_version_string())
p(green('Frozen:'), 'True' if getattr(sys, 'frozen', False) else 'False')
p(green('Fonts:'))
for k, font in current_fonts().items():
if hasattr(font, 'identify_for_debug'):
face: FontFace = cast(FontFace, font)
flines = face.identify_for_debug().splitlines()
p(yellow(f'{k.rjust(8)}:'), flines[0])
for fl in flines[1:]:
p(' ' * 9, fl)
p(green('Paths:'))
p(yellow(' kitty:'), os.path.realpath(kitty_exe()))
p(yellow(' base dir:'), kitty_base_dir)
p(yellow(' extensions dir:'), extensions_dir)
p(yellow(' system shell:'), shell_path)
p(f'System color scheme: {green(glfw_get_system_color_theme())}. Applied color theme type: {yellow(theme_colors.applied_theme or "none")}')
if opts.config_paths:
p(green('Loaded config files:'))
p(' ', '\n '.join(opts.config_paths))
if opts.config_overrides:
p(green('Loaded config overrides:'))
p(' ', '\n '.join(opts.config_overrides))
compare_opts(opts, global_shortcuts, p)
p()
p(green('Important environment variables seen by the kitty process:'))
def penv(k: str) -> None:
v = os.environ.get(k)
if v is not None:
p('\t' + k.ljust(35), styled(v, dim=True))
for k in (
'PATH LANG KITTY_CONFIG_DIRECTORY KITTY_CACHE_DIRECTORY VISUAL EDITOR SHELL'
' GLFW_IM_MODULE KITTY_WAYLAND_DETECT_MODIFIERS DISPLAY WAYLAND_DISPLAY USER XCURSOR_SIZE'
).split():
penv(k)
for k in os.environ:
if k.startswith('LC_') or k.startswith('XDG_'):
penv(k)
return out.getvalue()
+2903
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
/*
* decorations.h
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
typedef struct DecorationGeometry {
uint32_t top, height;
} DecorationGeometry;
DecorationGeometry add_straight_underline(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_double_underline(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_dotted_underline(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_dashed_underline(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_curl_underline(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_strikethrough(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_missing_glyph(uint8_t *buf, FontCellMetrics fcm);
DecorationGeometry add_beam_cursor(uint8_t *buf, FontCellMetrics fcm, double dpi_x, double scale);
DecorationGeometry add_underline_cursor(uint8_t *buf, FontCellMetrics fcm, double dpi_y, double scale);
DecorationGeometry add_hollow_cursor(uint8_t *buf, FontCellMetrics fcm, double dpi_x, double dpi_y, double scale);
void render_box_char(char_type ch, uint8_t *buf, unsigned width, unsigned height, double dpi_x, double dpi_y, double scale);
#define SUPERSAMPLE_FACTOR 4u
+315
View File
@@ -0,0 +1,315 @@
/*
* desktop.c
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "state.h"
#include "safe-wrappers.h"
#include "cleanup.h"
#include "loop-utils.h"
#include "threading.h"
#include <dlfcn.h>
#define FUNC(name, restype, ...) \
typedef restype (*name##_func)(__VA_ARGS__); \
static name##_func name = NULL
#define LOAD_FUNC(handle, name) \
{ \
*(void **)(&name) = dlsym(handle, #name); \
if (!name) { \
const char *error = dlerror(); \
if (error != NULL) { \
PyErr_Format(PyExc_OSError, "Failed to load the function %s with error: %s", #name, error); \
dlclose(handle); \
handle = NULL; \
return NULL; \
} \
} \
}
FUNC(sn_display_new, void *, void *, void *, void *);
FUNC(sn_launchee_context_new_from_environment, void *, void *, int);
FUNC(sn_launchee_context_new, void *, void *, int, const char *);
FUNC(sn_display_unref, void, void *);
FUNC(sn_launchee_context_setup_window, void, void *, int32_t);
FUNC(sn_launchee_context_complete, void, void *);
FUNC(sn_launchee_context_unref, void, void *);
static void *libsn_handle = NULL;
static PyObject *
init_x11_startup_notification(PyObject UNUSED *self, PyObject *args) {
static bool done = false;
if (!done) {
done = true;
const char *libnames[] = {
#if defined(_KITTY_STARTUP_NOTIFICATION_LIBRARY)
_KITTY_STARTUP_NOTIFICATION_LIBRARY,
#else
"libstartup-notification-1.so",
// some installs are missing the .so symlink, so try the full name
"libstartup-notification-1.so.0",
"libstartup-notification-1.so.0.0.0",
#endif
NULL};
for (int i = 0; libnames[i]; i++) {
libsn_handle = dlopen(libnames[i], RTLD_LAZY);
if (libsn_handle) break;
}
if (libsn_handle == NULL) {
PyErr_Format(PyExc_OSError, "Failed to load %s with error: %s", libnames[0], dlerror());
return NULL;
}
dlerror(); /* Clear any existing error */
#define F(name) LOAD_FUNC(libsn_handle, name)
F(sn_display_new);
F(sn_launchee_context_new_from_environment);
F(sn_launchee_context_new);
F(sn_display_unref);
F(sn_launchee_context_setup_window);
F(sn_launchee_context_complete);
F(sn_launchee_context_unref);
#undef F
}
int window_id;
PyObject *dp;
char *startup_id = NULL;
if (!PyArg_ParseTuple(args, "O!i|z", &PyLong_Type, &dp, &window_id, &startup_id)) return NULL;
void *display = PyLong_AsVoidPtr(dp);
void *sn_display = sn_display_new(display, NULL, NULL);
if (!sn_display) {
PyErr_SetString(PyExc_OSError, "Failed to create SnDisplay");
return NULL;
}
void *ctx = startup_id ? sn_launchee_context_new(sn_display, 0, startup_id) : sn_launchee_context_new_from_environment(sn_display, 0);
sn_display_unref(sn_display);
if (!ctx) {
PyErr_SetString(PyExc_OSError, "Failed to create startup-notification context");
return NULL;
}
sn_launchee_context_setup_window(ctx, window_id);
return PyLong_FromVoidPtr(ctx);
}
static PyObject *
end_x11_startup_notification(PyObject UNUSED *self, PyObject *args) {
if (!libsn_handle) Py_RETURN_NONE;
PyObject *dp;
if (!PyArg_ParseTuple(args, "O!", &PyLong_Type, &dp)) return NULL;
void *ctx = PyLong_AsVoidPtr(dp);
sn_launchee_context_complete(ctx);
sn_launchee_context_unref(ctx);
Py_RETURN_NONE;
}
static void *libcanberra_handle = NULL;
static void *canberra_ctx = NULL;
FUNC(ca_context_create, int, void **);
FUNC(ca_context_destroy, int, void *);
FUNC(ca_context_play_full, int, void *, uint32_t, void *, void (*)(void), void *);
typedef int (*ca_context_play_func)(void *, uint32_t, ...);
static ca_context_play_func ca_context_play = NULL;
typedef int (*ca_context_change_props_func)(void *, ...);
static ca_context_change_props_func ca_context_change_props = NULL;
static PyObject *
load_libcanberra_functions(void) {
LOAD_FUNC(libcanberra_handle, ca_context_create);
LOAD_FUNC(libcanberra_handle, ca_context_play);
LOAD_FUNC(libcanberra_handle, ca_context_play_full);
LOAD_FUNC(libcanberra_handle, ca_context_destroy);
LOAD_FUNC(libcanberra_handle, ca_context_change_props);
return NULL;
}
static void
load_libcanberra(void) {
static bool done = false;
if (done) return;
done = true;
const char *libnames[] = {
#if defined(_KITTY_CANBERRA_LIBRARY)
_KITTY_CANBERRA_LIBRARY,
#else
"libcanberra.so",
// some installs are missing the .so symlink, so try the full name
"libcanberra.so.0",
"libcanberra.so.0.2.5",
#endif
NULL};
for (int i = 0; libnames[i]; i++) {
libcanberra_handle = dlopen(libnames[i], RTLD_LAZY);
if (libcanberra_handle) break;
}
if (libcanberra_handle == NULL) {
fprintf(stderr, "Failed to load %s, cannot play beep sound, with error: %s\n", libnames[0], dlerror());
return;
}
load_libcanberra_functions();
if (PyErr_Occurred()) {
PyErr_Print();
dlclose(libcanberra_handle);
libcanberra_handle = NULL;
return;
}
if (ca_context_create(&canberra_ctx) != 0) {
fprintf(stderr, "Failed to create libcanberra context, cannot play beep sound\n");
canberra_ctx = NULL;
dlclose(libcanberra_handle);
libcanberra_handle = NULL;
} else {
if (ca_context_change_props(canberra_ctx, "application.name", "kitty Terminal", "application.id", "kitty", NULL) != 0) {
fprintf(stderr, "Failed to set basic properties on libcanberra context, cannot play beep sound\n");
}
}
}
typedef struct {
char *which_sound, *event_id, *media_role, *theme_name;
bool is_path;
} CanberraEvent;
static pthread_t canberra_thread;
static int canberra_pipe_r = -1, canberra_pipe_w = -1;
static pthread_mutex_t canberra_lock;
static CanberraEvent current_sound = {0};
static void
free_canberra_event_fields(CanberraEvent *e) {
free(e->which_sound);
e->which_sound = NULL;
free(e->event_id);
e->event_id = NULL;
free(e->media_role);
e->media_role = NULL;
free(e->theme_name);
e->theme_name = NULL;
}
static void
play_current_sound(void) {
CanberraEvent e;
pthread_mutex_lock(&canberra_lock);
e = current_sound;
current_sound = (const CanberraEvent){0};
pthread_mutex_unlock(&canberra_lock);
if (e.which_sound && e.event_id && e.media_role) {
const char *which_type = e.is_path ? "media.filename" : "event.id";
ca_context_play(
canberra_ctx,
0,
which_type,
e.which_sound,
"event.description",
e.event_id,
"media.role",
e.media_role,
"canberra.xdg-theme.name",
e.theme_name,
NULL);
free_canberra_event_fields(&e);
}
}
static void
queue_canberra_sound(const char *which_sound, const char *event_id, bool is_path, const char *media_role, const char *theme_name) {
pthread_mutex_lock(&canberra_lock);
current_sound.which_sound = strdup(which_sound);
current_sound.event_id = strdup(event_id);
current_sound.media_role = strdup(media_role);
current_sound.is_path = is_path;
current_sound.theme_name = theme_name ? strdup(theme_name) : NULL;
pthread_mutex_unlock(&canberra_lock);
while (true) {
ssize_t ret = write(canberra_pipe_w, "w", 1);
if (ret < 0) {
if (errno == EINTR) continue;
log_error("Failed to write to canberra wakeup fd with error: %s", strerror(errno));
}
break;
}
}
static void *
canberra_play_loop(void *x UNUSED) {
// canberra hangs on misconfigured systems. We dont want kitty to hang so use a thread.
// For example: https://github.com/kovidgoyal/kitty/issues/5646
static char buf[16];
set_thread_name("LinuxAudioSucks");
while (true) {
int ret = read(canberra_pipe_r, buf, sizeof(buf));
if (ret < 0) {
if (errno == EINTR || errno == EAGAIN) continue;
break;
}
play_current_sound();
}
safe_close(canberra_pipe_r, __FILE__, __LINE__);
return NULL;
}
void
play_canberra_sound(const char *which_sound, const char *event_id, bool is_path, const char *media_role, const char *theme_name) {
load_libcanberra();
if (libcanberra_handle == NULL || canberra_ctx == NULL) return;
int ret;
if (canberra_pipe_r == -1) {
int fds[2];
if ((ret = pthread_mutex_init(&canberra_lock, NULL)) != 0) return;
if (!self_pipe(fds, false)) return;
canberra_pipe_r = fds[0];
canberra_pipe_w = fds[1];
int flags = fcntl(canberra_pipe_w, F_GETFL);
fcntl(canberra_pipe_w, F_SETFL, flags | O_NONBLOCK);
if ((ret = pthread_create(&canberra_thread, NULL, canberra_play_loop, NULL)) != 0) return;
}
queue_canberra_sound(which_sound, event_id, is_path, media_role, theme_name);
}
static PyObject *
play_desktop_sound_async(PyObject *self UNUSED, PyObject *args, PyObject *kw) {
const char *which, *event_id = "test sound";
const char *theme_name = OPT(bell_theme);
if (!theme_name || !theme_name[0]) theme_name = "__custom";
int is_path = 0;
static const char *kwlist[] = {"sound_name", "event_id", "is_path", "theme_name", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|sps", (char **)kwlist, &which, &event_id, &is_path, &theme_name)) return NULL;
play_canberra_sound(which, event_id, is_path, "event", theme_name);
Py_RETURN_NONE;
}
static void
finalize(void) {
if (libsn_handle) dlclose(libsn_handle);
libsn_handle = NULL;
if (canberra_pipe_w > -1) {
pthread_mutex_lock(&canberra_lock);
free_canberra_event_fields(&current_sound);
pthread_mutex_unlock(&canberra_lock);
safe_close(canberra_pipe_w, __FILE__, __LINE__);
}
if (canberra_ctx) ca_context_destroy(canberra_ctx);
canberra_ctx = NULL;
if (libcanberra_handle) dlclose(libcanberra_handle);
}
static PyMethodDef module_methods[] = {
METHODB(init_x11_startup_notification, METH_VARARGS),
METHODB(end_x11_startup_notification, METH_VARARGS),
{"play_desktop_sound_async", (PyCFunction)(void (*)(void))play_desktop_sound_async, METH_VARARGS | METH_KEYWORDS, ""},
{NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_desktop(PyObject *m) {
if (PyModule_AddFunctions(m, module_methods) != 0) return false;
register_at_exit_cleanup_func(DESKTOP_CLEANUP_FUNC, finalize);
return true;
}
+1235
View File
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2020 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
PyObject *create_disk_cache(void);
bool add_to_disk_cache(PyObject *self, const void *key, size_t key_sz, const void *data, size_t data_sz, bool memory_only);
// As above, but takes ownership of *data (which must be a malloc() allocated
// pointer), setting it to NULL. Ownership is transferred only on success, on
// failure the caller remains responsible for freeing it. Note that once
// ownership has been transferred the data must not be read or written by the
// caller, the cache write thread can modify it at any time.
bool add_to_disk_cache_move(PyObject *self, const void *key, size_t key_sz, void **data, size_t data_sz, bool memory_only);
bool remove_from_disk_cache(PyObject *self_, const void *key, size_t key_sz);
void *read_from_disk_cache(PyObject *self_, const void *key, size_t key_sz, void *(allocator)(void *, size_t), void *, bool);
PyObject *read_from_disk_cache_python(PyObject *self_, const void *key, size_t key_sz, bool);
bool disk_cache_wait_for_write(PyObject *self, monotonic_t timeout);
size_t disk_cache_total_size(PyObject *self);
size_t disk_cache_size_on_disk(PyObject *self);
size_t disk_cache_num_cached_in_ram(PyObject *self_);
static inline void *
disk_cache_malloc_allocator(void *x, size_t sz) {
*((size_t *)x) = sz;
return malloc(sz);
}
static inline bool
read_from_disk_cache_simple(PyObject *self_, const void *key, size_t key_sz, void **data, size_t *data_sz, bool store_in_ram) {
*data = read_from_disk_cache(self_, key, key_sz, disk_cache_malloc_allocator, data_sz, store_in_ram);
if (PyErr_Occurred()) {
PyErr_Clear();
return false;
}
return *data != NULL;
}
+3129
View File
File diff suppressed because it is too large. Load diff
+40
View File
@@ -0,0 +1,40 @@
/*
* dnd.h
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "state.h"
void dnd_query(Window *w, uint32_t client_id);
void drop_register_window(Window *w, const uint8_t *payload, size_t payload_sz, bool on, uint32_t client_id, bool more);
void drop_register_machine_id(Window *w, const uint8_t *machine_id, size_t sz);
void drop_move_on_child(Window *w, const char **mimes, size_t num_mimes, bool is_drop);
void drop_left_child(Window *w);
void drop_free_data(Window *w);
void drop_send_einval(Window *w, const char *desc);
void drop_handle_dir_request(Window *w, uint32_t handle_id, int32_t entry_num);
void drop_enqueue_request(Window *w, int32_t cell_x, int32_t cell_y, int32_t pixel_y, uint32_t operation);
void drop_set_status(Window *w, int operation, const char *payload, size_t payload_sz, bool more);
size_t drop_update_mimes(Window *w, const char **allowed_mimes, size_t allowed_mimes_count);
void drop_dispatch_data(Window *w, const char *mime_type, const char *data, ssize_t sz);
void drop_finish(Window *w);
typedef enum { DRAG_NOTIFY_ACCEPTED, DRAG_NOTIFY_ACTION_CHANGED, DRAG_NOTIFY_DROPPED, DRAG_NOTIFY_FINISHED } DragNotifyType;
void drag_free_offer(Window *w, bool remove_remote_items);
void drag_add_mimes(Window *w, int allowed_operations, uint32_t client_id, const char *data, size_t sz, bool has_more);
void drag_add_pre_sent_data(Window *w, unsigned idx, const uint8_t *payload, size_t sz);
void drag_add_image(Window *w, unsigned idx_, int fmt, int width, int height, int opacity, const uint8_t *payload, size_t sz);
void drag_change_image(Window *w, unsigned idx);
void drag_start(Window *w);
void drag_notify(Window *w, DragNotifyType type);
int drag_free_data(Window *w, const char *mime_type, const char *data, size_t sz);
const char *drag_get_data(Window *w, const char *mime_type, size_t *sz, int *err_code);
void drag_process_item_data(Window *w, size_t idx, int has_more, const uint8_t *payload, size_t payload_sz);
void drag_remote_file_data(Window *w, int32_t x, int32_t y, int32_t X, int32_t Y, bool has_more, const uint8_t *payload, size_t payload_sz);
void drag_start_offerring(Window *w, const char *client_machine_id, size_t sz);
void drag_stop_offerring(Window *w);
void drag_offer_start_to_child(Window *w, int32_t cell_x, int32_t cell_y, int32_t pixel_x, int32_t pixel_y);
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
def icat(args: list[str]) -> None:
from kitty.constants import kitten_exe
os.execl(kitten_exe(), 'kitten', *args)
def list_fonts(args: list[str]) -> None:
from kitty.fonts.list import main as list_main
list_main(args)
def runpy(args: list[str]) -> None:
if len(args) < 2:
raise SystemExit('Usage: kitty +runpy "some python code"')
sys.argv = ['kitty'] + args[2:]
exec(args[1])
def hold(args: list[str]) -> None:
from kitty.constants import kitten_exe
args = ['kitten', '__hold_till_enter__'] + args[1:]
os.execvp(kitten_exe(), args)
def complete(args: list[str]) -> None:
# Delegate to kitten to maintain backward compatibility
if len(args) < 2 or args[1] not in ('setup', 'zsh', 'fish2', 'bash'):
raise SystemExit(1)
if args[1] == 'fish2':
args[1:1] = ['fish', '_legacy_completion=fish2']
elif len(args) >= 3 and args[1:3] == ['setup', 'fish2']:
args[2] = 'fish'
from kitty.constants import kitten_exe
args = ['kitten', '__complete__'] + args[1:]
os.execvp(kitten_exe(), args)
def open_urls(args: list[str]) -> None:
setattr(sys, 'cmdline_args_for_open', True)
sys.argv = ['kitty'] + args[1:]
from kitty.main import main as kitty_main
kitty_main()
def launch(args: list[str]) -> None:
import runpy
sys.argv = args[1:]
try:
exe = args[1]
except IndexError:
raise SystemExit(
'usage: kitty +launch script.py [arguments to be passed to script.py ...]\n\n'
'script.py will be run with full access to kitty code. If script.py is '
'prefixed with a : it will be searched for in PATH. If script.py is a directory '
'the __main__.py file inside it is run just as with the normal Python interpreter.'
)
if exe.startswith(':'):
import shutil
q = shutil.which(exe[1:])
if not q:
raise SystemExit(f'{exe[1:]} not found in PATH')
exe = q
if not os.path.exists(exe):
raise SystemExit(f'{exe} does not exist')
runpy.run_path(exe, run_name='__main__')
def shebang(args: list[str]) -> None:
from kitty.constants import kitten_exe
os.execvp(kitten_exe(), ['kitten', '__shebang__', 'confirm-if-needed'] + args[1:])
def run_kitten(args: list[str]) -> None:
try:
kitten = args[1]
except IndexError:
from kittens.runner import list_kittens
list_kittens()
raise SystemExit(1)
sys.argv = args[1:]
from kittens.runner import run_kitten as rk
rk(kitten)
def namespaced(args: list[str]) -> None:
try:
func = namespaced_entry_points[args[1]]
except IndexError:
raise SystemExit('The kitty command line is incomplete')
except KeyError:
pass
else:
func(args[1:])
return
raise SystemExit(f'{args[1]} is not a known entry point. Choices are: ' + ', '.join(namespaced_entry_points))
entry_points = {
# These two are here for backwards compat
'icat': icat,
'list-fonts': list_fonts,
'+': namespaced,
}
namespaced_entry_points = {k: v for k, v in entry_points.items() if k[0] not in '+@'}
namespaced_entry_points['hold'] = hold
namespaced_entry_points['complete'] = complete
namespaced_entry_points['runpy'] = runpy
namespaced_entry_points['launch'] = launch
namespaced_entry_points['open'] = open_urls
namespaced_entry_points['kitten'] = run_kitten
namespaced_entry_points['shebang'] = shebang
def setup_openssl_environment(ext_dir: str) -> None:
# Use our bundled CA certificates instead of the system ones, since
# many systems come with no certificates in a usable form or have various
# locations for the certificates.
d = os.path.dirname
if 'darwin' in sys.platform.lower():
cert_file = os.path.join(d(d(d(ext_dir))), 'cacert.pem')
else:
cert_file = os.path.join(d(ext_dir), 'cacert.pem')
os.environ['SSL_CERT_FILE'] = cert_file
setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_FILE')
def main() -> None:
if getattr(sys, 'frozen', False) and (ext_dir := getattr(sys, 'kitty_run_data', {}).get('extensions_dir')):
setup_openssl_environment(ext_dir)
first_arg = '' if len(sys.argv) < 2 else sys.argv[1]
func = entry_points.get(first_arg)
if func is None:
if first_arg.startswith('+'):
namespaced(['+', first_arg[1:]] + sys.argv[2:])
else:
from kitty.main import main as kitty_main
kitty_main()
else:
func(sys.argv[1:])
+125
View File
@@ -0,0 +1,125 @@
/*
* fast-file-copy.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#if __linux__
#define _GNU_SOURCE 1
#endif
#include "fast-file-copy.h"
#if __linux__
#define HAS_SENDFILE
#include <sys/sendfile.h>
#include <unistd.h>
#endif
static bool
copy_with_buffer(int infd, int outfd, off_t in_pos, size_t len, FastFileCopyBuffer *fcb) {
if (!fcb->buf) {
fcb->sz = 32 * 1024;
fcb->buf = malloc(fcb->sz);
if (!fcb->buf) return false;
}
while (len) {
ssize_t amt_read = pread(infd, fcb->buf, MIN(len, fcb->sz), in_pos);
if (amt_read < 0) {
if (errno == EINTR || errno == EAGAIN) continue;
return false;
}
if (amt_read == 0) {
errno = EIO;
return false;
}
len -= amt_read;
in_pos += amt_read;
uint8_t *p = fcb->buf;
while (amt_read) {
ssize_t amt_written = write(outfd, p, amt_read);
if (amt_written < 0) {
if (errno == EINTR || errno == EAGAIN) continue;
return false;
}
if (amt_written == 0) {
errno = EIO;
return false;
}
amt_read -= amt_written;
p += amt_written;
}
}
return true;
}
#ifdef HAS_SENDFILE
static bool
copy_with_sendfile(int infd, int outfd, off_t in_pos, size_t len, FastFileCopyBuffer *fcb) {
unsigned num_of_consecutive_zero_returns = 128;
while (len) {
off_t r = in_pos;
ssize_t n = sendfile(outfd, infd, &r, len);
if (n < 0) {
if (errno == EAGAIN) continue;
if (errno == ENOSYS || // No kernel support
errno == EPERM || errno == EINVAL) // ZFS for some reason
return copy_with_buffer(infd, outfd, in_pos, len, fcb);
return false;
}
if (n == 0) {
// happens if input file is truncated
if (!--num_of_consecutive_zero_returns) return false;
continue;
};
num_of_consecutive_zero_returns = 128;
in_pos += n;
len -= n;
}
return true;
}
static bool
copy_with_file_range(int infd, int outfd, off_t in_pos, size_t len, FastFileCopyBuffer *fcb) {
#ifdef HAS_COPY_FILE_RANGE
unsigned num_of_consecutive_zero_returns = 128;
while (len) {
int64_t r = in_pos;
ssize_t n = copy_file_range(infd, &r, outfd, NULL, len, 0);
if (n < 0) {
if (errno == EAGAIN) continue;
if (errno == ENOSYS || // Linux < 4.5
errno == EPERM || // Possibly Docker
errno == EINVAL || // ZFS for some reason
errno == EIO || // CIFS
errno == EOPNOTSUPP || // NFS
errno == EXDEV) // Prior to Linux 5.3, it was not possible to copy_file_range across file systems
return copy_with_sendfile(infd, outfd, in_pos, len, fcb);
return false;
}
if (n == 0) {
// happens if input file is truncated
if (!--num_of_consecutive_zero_returns) return false;
continue;
};
num_of_consecutive_zero_returns = 128;
in_pos += n;
len -= n;
}
return true;
#else
return copy_with_sendfile(infd, outfd, in_pos, len, fcb);
#endif
}
#endif
bool
copy_between_files(int infd, int outfd, off_t in_pos, size_t len, FastFileCopyBuffer *fcb) {
#ifdef HAS_SENDFILE
return copy_with_file_range(infd, outfd, in_pos, len, fcb);
#else
return copy_with_buffer(infd, outfd, in_pos, len, fcb);
#endif
return true;
}
+24
View File
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
typedef struct FastFileCopyBuffer {
uint8_t *buf;
size_t sz;
} FastFileCopyBuffer;
static inline void
free_fast_file_copy_buffer(FastFileCopyBuffer *fcb) {
free(fcb->buf);
fcb->buf = NULL;
}
#define RAII_FreeFastFileCopyBuffer(name) __attribute__((__cleanup__(free_fast_file_copy_buffer))) FastFileCopyBuffer name = {0}
bool copy_between_files(int infd, int outfd, off_t in_pos, size_t len, FastFileCopyBuffer *fcb);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
/*
* fixed_size_deque.h
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*
* A fixed size deque that does not allocate. To use define DEQUE_NAME, DEQUE_CAPACITY and
* DEQUE_DATA_TYPE and include header. Use deque_push_back() to append. To
* iterate in append order use deque_at(i) for 0 <= i < deque_size().
*/
#include <stdbool.h>
#include <string.h>
#ifndef DEQUE_NAME
#define DEQUE_NAME CircularDeque
#endif
#ifndef DEQUE_CAPACITY
#define DEQUE_CAPACITY 50
#endif
#ifndef DEQUE_DATA_TYPE
#define DEQUE_DATA_TYPE int
#endif
typedef struct {
DEQUE_DATA_TYPE items[DEQUE_CAPACITY];
unsigned head; // Index of first element
unsigned tail; // Index one past last element
unsigned count; // Number of elements
} DEQUE_NAME;
// Check if empty
static inline bool
deque_is_empty(const DEQUE_NAME *dq) {
return dq->count == 0;
}
// Check if full
static inline bool
deque_is_full(const DEQUE_NAME *dq) {
return dq->count == DEQUE_CAPACITY;
}
// Get current size
static inline unsigned
deque_size(const DEQUE_NAME *dq) {
return dq->count;
}
// Push to back auto-evicts from front if full.
// Returns true if an item was evicted, which will be copied to *evicted_item is not NULL.
static inline bool
deque_push_back(DEQUE_NAME *dq, DEQUE_DATA_TYPE item, DEQUE_DATA_TYPE *evicted_item) {
bool evicted = false;
if (deque_is_full(dq)) {
// Evict front item
if (evicted_item) *evicted_item = dq->items[dq->head];
evicted = true;
dq->head = (dq->head + 1) % DEQUE_CAPACITY;
dq->count--;
}
dq->items[dq->tail] = item;
dq->tail = (dq->tail + 1) % DEQUE_CAPACITY;
dq->count++;
return evicted;
}
// Push to front, auto-evicts from back if full.
// Returns true if an item was evicted, which will be copied to *evicted_item is not NULL.
static inline bool
deque_push_front(DEQUE_NAME *dq, DEQUE_DATA_TYPE item, DEQUE_DATA_TYPE *evicted_item) {
bool evicted = false;
if (deque_is_full(dq)) {
// Evict oldest (back) item
dq->tail = (dq->tail - 1 + DEQUE_CAPACITY) % DEQUE_CAPACITY;
if (evicted_item) *evicted_item = dq->items[dq->tail];
evicted = true;
dq->count--;
}
dq->head = (dq->head - 1 + DEQUE_CAPACITY) % DEQUE_CAPACITY;
dq->items[dq->head] = item;
dq->count++;
return evicted;
}
// Pop from front
static inline bool
deque_pop_front(DEQUE_NAME *dq, DEQUE_DATA_TYPE *ans) {
if (deque_is_empty(dq)) return false;
if (ans) *ans = dq->items[dq->head];
dq->head = (dq->head + 1) % DEQUE_CAPACITY;
dq->count--;
return true;
}
// Pop from back
static inline bool
deque_pop_back(DEQUE_NAME *dq, DEQUE_DATA_TYPE *ans) {
if (deque_is_empty(dq)) return false;
dq->tail = (dq->tail - 1 + DEQUE_CAPACITY) % DEQUE_CAPACITY;
if (ans) *ans = dq->items[dq->tail];
dq->count--;
return true;
}
// Peek at front without removing
static inline const DEQUE_DATA_TYPE *
deque_peek_front(const DEQUE_NAME *dq) {
if (deque_is_empty(dq)) return NULL;
return &dq->items[dq->head];
}
// Peek at back without removing
static inline const DEQUE_DATA_TYPE *
deque_peek_back(const DEQUE_NAME *dq) {
if (deque_is_empty(dq)) return NULL;
int idx = (dq->tail - 1 + DEQUE_CAPACITY) % DEQUE_CAPACITY;
return &dq->items[idx];
}
// Access by index (0 = oldest, count-1 = newest)
static inline const DEQUE_DATA_TYPE *
deque_at(const DEQUE_NAME *dq, unsigned index) {
if (index >= dq->count) return NULL;
return &dq->items[(dq->head + index) % DEQUE_CAPACITY];
}
// Clear all items (doesn't free items)
static inline void
deque_clear(DEQUE_NAME *dq) {
dq->head = 0;
dq->tail = 0;
dq->count = 0;
}
#undef DEQUE_CAPACITY
#undef DEQUE_DATA_TYPE
#undef DEQUE_NAME
+446
View File
@@ -0,0 +1,446 @@
/*
* font-names.c
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "fonts.h"
static PyObject *
decode_name_record(PyObject *namerec) {
#define d(x) PyLong_AsUnsignedLong(PyTuple_GET_ITEM(namerec, x))
unsigned long platform_id = d(0), encoding_id = d(1), language_id = d(2);
#undef d
const char *encoding = "unicode_escape";
if ((platform_id == 3 && encoding_id == 1) || platform_id == 0) encoding = "utf-16-be";
else if (platform_id == 1 && encoding_id == 0 && language_id == 0) encoding = "mac-roman";
PyObject *b = PyTuple_GET_ITEM(namerec, 3);
return PyUnicode_Decode(PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b), encoding, "replace");
}
static bool
namerec_matches(PyObject *namerec, unsigned platform_id, unsigned encoding_id, unsigned language_id) {
#define d(x) PyLong_AsUnsignedLong(PyTuple_GET_ITEM(namerec, x))
return d(0) == platform_id && d(1) == encoding_id && d(2) == language_id;
#undef d
}
static PyObject *
find_matching_namerec(PyObject *namerecs, unsigned platform_id, unsigned encoding_id, unsigned language_id) {
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(namerecs); i++) {
PyObject *namerec = PyList_GET_ITEM(namerecs, i);
if (namerec_matches(namerec, platform_id, encoding_id, language_id)) return decode_name_record(namerec);
}
return NULL;
}
bool
add_font_name_record(
PyObject *table, uint16_t platform_id, uint16_t encoding_id, uint16_t language_id, uint16_t name_id, const char *string, uint16_t string_len) {
RAII_PyObject(key, PyLong_FromUnsignedLong((unsigned long)name_id));
if (!key) return false;
RAII_PyObject(list, PyDict_GetItem(table, key));
if (list == NULL) {
list = PyList_New(0);
if (!list) return false;
if (PyDict_SetItem(table, key, list) != 0) return false;
} else Py_INCREF(list);
RAII_PyObject(value, Py_BuildValue("(H H H y#)", platform_id, encoding_id, language_id, string, (Py_ssize_t)string_len));
if (!value) return false;
if (PyList_Append(list, value) != 0) return false;
return true;
}
PyObject *
get_best_name_from_name_table(PyObject *table, PyObject *name_id) {
PyObject *namerecs = PyDict_GetItem(table, name_id);
if (namerecs == NULL) return PyUnicode_FromString("");
if (PyList_GET_SIZE(namerecs) == 1) return decode_name_record(PyList_GET_ITEM(namerecs, 0));
#define d(...) \
{ \
PyObject *ans = find_matching_namerec(namerecs, __VA_ARGS__); \
if (ans != NULL || PyErr_Occurred()) return ans; \
}
d(3, 1, 1033); // Microsoft/Windows/US English
d(1, 0, 0); // Mac/Roman/English
d(0, 6, 0); // Unicode/SMP/*
d(0, 4, 0); // Unicode/SMP/*
d(0, 3, 0); // Unicode/BMP/*
d(0, 2, 0); // Unicode/10646-BMP/*
d(0, 1, 0); // Unicode/1.1/*
#undef d
return PyUnicode_FromString("");
}
static PyObject *
get_best_name(PyObject *table, unsigned long name_id) {
RAII_PyObject(id, PyLong_FromUnsignedLong(name_id));
return get_best_name_from_name_table(table, id);
}
// OpenType tables are big-endian for god knows what reason so need to byteswap
static uint16_t
byteswap(const uint16_t *p) {
const uint8_t *b = (const uint8_t *)p;
return (((uint16_t)b[0]) << 8) | b[1];
}
static uint32_t
byteswap32(const uint32_t *val) {
const uint8_t *p = (const uint8_t *)val;
return (((uint32_t)p[0]) << 24) | (((uint32_t)p[1]) << 16) | (((uint32_t)p[2]) << 8) | p[3];
}
static double
load_fixed(const uint32_t *p_) {
uint32_t p = byteswap32(p_);
static const double denom = 1 << 16;
return ((int32_t)p) / denom;
}
#define next byteswap(p++)
#define next32 load_fixed(p32++)
PyObject *
read_name_font_table(const uint8_t *table, size_t table_len) {
if (!table || table_len < 9 * sizeof(uint16_t)) return PyDict_New();
uint16_t *p = (uint16_t *)table;
p++;
uint16_t num_of_name_records = next, storage_offset = next;
const uint8_t *storage = table + storage_offset, *slimit = table + table_len;
if (storage >= slimit) return PyDict_New();
RAII_PyObject(ans, PyDict_New());
for (; num_of_name_records > 0 && p + 6 <= (uint16_t *)slimit; num_of_name_records--) {
uint16_t platform_id = next, encoding_id = next, language_id = next, name_id = next, length = next, offset = next;
const uint8_t *s = storage + offset;
if (s + length <= slimit && !add_font_name_record(ans, platform_id, encoding_id, language_id, name_id, (const char *)(s), length)) return NULL;
}
Py_INCREF(ans);
return ans;
}
static bool
is_digit(char x) {
return '0' <= x && x <= '9';
}
static PyObject *
read_cv_feature_table(const uint8_t *table, const uint8_t *limit, PyObject *name_lookup_table) {
RAII_PyObject(ans, PyDict_New());
if (!ans) return NULL;
if (limit - table >= 12) {
uint16_t *p = (uint16_t *)(table + 2);
uint16_t name_id = next, tooltip_id = next, sample_id = next, num_params = next, first_value_id = next;
if (name_id) {
RAII_PyObject(name, get_best_name(name_lookup_table, name_id));
if (!name) return NULL;
if (PyDict_SetItemString(ans, "name", name) != 0) return NULL;
}
if (tooltip_id) {
RAII_PyObject(tooltip, get_best_name(name_lookup_table, tooltip_id));
if (!tooltip) return NULL;
if (PyDict_SetItemString(ans, "tooltip", tooltip) != 0) return NULL;
}
if (sample_id) {
RAII_PyObject(sample, get_best_name(name_lookup_table, sample_id));
if (!sample) return NULL;
if (PyDict_SetItemString(ans, "sample", sample) != 0) return NULL;
}
if (num_params && first_value_id) {
RAII_PyObject(params, PyTuple_New(num_params));
if (!params) return NULL;
for (uint16_t i = 0; i < num_params; i++) {
PyObject *pval = get_best_name(name_lookup_table, first_value_id + i);
if (!pval) return NULL;
PyTuple_SET_ITEM(params, i, pval);
}
if (PyDict_SetItemString(ans, "params", params) != 0) return NULL;
}
}
Py_INCREF(ans);
return ans;
}
static PyObject *
read_ss_feature_table(const uint8_t *table, const uint8_t *limit, PyObject *name_lookup_table) {
RAII_PyObject(ans, PyDict_New());
if (!ans) return NULL;
if (limit - table < 4) {
Py_INCREF(ans);
return ans;
}
uint16_t *p = (uint16_t *)(table + 2);
uint16_t name_id = next;
if (name_id) {
RAII_PyObject(name, get_best_name(name_lookup_table, name_id));
if (!name) return NULL;
if (PyDict_SetItemString(ans, "name", name) != 0) return NULL;
}
Py_INCREF(ans);
return ans;
}
bool
read_features_from_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output) {
if (table_len < 20) return true;
const uint16_t *p = (uint16_t *)table;
const uint8_t *limit = table + table_len;
uint16_t major_version = next, minor_version = next, script_list_offset = next, feature_list_offset = next;
(void)major_version;
(void)minor_version;
(void)script_list_offset;
const uint8_t *feature_list_table = table + feature_list_offset;
char tag_buf[5] = {0};
if (feature_list_table + 2 >= limit) return true;
p = (uint16_t *)feature_list_table;
uint16_t feature_count = next;
const uint8_t *pos = (uint8_t *)p;
for (uint16_t i = 0; i < feature_count && pos + 6 <= limit; pos += 6, i++) {
memcpy(tag_buf, pos, 4);
RAII_PyObject(tag, PyUnicode_FromString(tag_buf));
if (!tag) return false;
if (PyDict_Contains(output, tag) == 1) continue;
if (PyDict_SetItem(output, tag, Py_None) != 0) return false;
p = (uint16_t *)(pos + 4);
uint16_t offset_to_feature_table = next;
const uint8_t *feature_table = feature_list_table + offset_to_feature_table;
if (feature_table + 2 > limit) continue;
p = (uint16_t *)(feature_table);
uint16_t offset_to_feature_params_table = next;
if (tag_buf[0] == 'c' && tag_buf[1] == 'v' && is_digit(tag_buf[2]) && is_digit(tag_buf[3])) {
if (offset_to_feature_params_table) {
RAII_PyObject(cv, read_cv_feature_table(feature_table + offset_to_feature_params_table, limit, name_lookup_table));
if (!cv) return false;
if (PyDict_SetItem(output, tag, cv) != 0) return false;
}
} else if (tag_buf[0] == 's' && tag_buf[1] == 's' && '0' <= tag_buf[2] && tag_buf[2] <= '2' && is_digit(tag_buf[3])) {
if (offset_to_feature_params_table) {
RAII_PyObject(ss, read_ss_feature_table(feature_table + offset_to_feature_params_table, limit, name_lookup_table));
if (!ss) return false;
if (PyDict_SetItem(output, tag, ss) != 0) return false;
}
}
}
return true;
}
bool
read_STAT_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output) {
uint16_t elided_fallback_name_id = 0;
RAII_PyObject(design_axes, PyTuple_New(0));
RAII_PyObject(multi_axis_styles, PyTuple_New(0));
RAII_PyObject(efn, NULL);
if (!design_axes || !multi_axis_styles) return false;
if (table_len < 20) goto ok;
const uint16_t *p = (uint16_t *)table;
uint16_t major_version = next, minor_version = next, size_of_design_axis_entry = next, count_of_design_axis_entries = next;
const uint32_t *p32 = (uint32_t *)p;
uint32_t offset_to_start_of_design_axes_entries = byteswap32(p32++);
p = (uint16_t *)p32;
uint16_t count_of_axis_value_entries = next;
p32 = (uint32_t *)p;
uint32_t offset_to_start_of_axis_value_entries = byteswap32(p32++);
p = (uint16_t *)p32;
elided_fallback_name_id = next;
if (major_version == 1 && minor_version < 1) elided_fallback_name_id = 0;
const uint8_t *table_limit = table + table_len;
size_t count = 0;
if (_PyTuple_Resize(&design_axes, count_of_design_axis_entries) == -1) return false;
// Bound the loop by the actual size of the tuple being filled rather than
// by count_of_design_axis_entries, so that the index passed to
// PyTuple_SET_ITEM() below cannot run past the end of the tuple.
const size_t num_design_axes = (size_t)PyTuple_GET_SIZE(design_axes);
for (const uint8_t *pos = table + offset_to_start_of_design_axes_entries; pos + size_of_design_axis_entry <= table_limit && count < num_design_axes;
pos += size_of_design_axis_entry, count++) {
p = (uint16_t *)(pos + 4);
uint16_t name_id = next, ordering = next;
PyObject *rec = Py_BuildValue(
"{ss# sN sH sN}",
"tag",
(char *)pos,
(Py_ssize_t)4,
"name",
get_best_name(name_lookup_table, name_id),
"ordering",
ordering,
"values",
PyList_New(0));
if (!rec) return false;
PyTuple_SET_ITEM(design_axes, count, rec);
}
if (_PyTuple_Resize(&design_axes, count) == -1) return false;
count = 0;
const uint8_t *start_of_axis_values_offsets_array = table + offset_to_start_of_axis_value_entries;
Py_ssize_t num_of_multi_axis_styles = 0;
if (_PyTuple_Resize(&multi_axis_styles, count_of_axis_value_entries) == -1) return false;
for (const uint8_t *pos = start_of_axis_values_offsets_array; pos + 2 <= table_limit && count < count_of_axis_value_entries; pos += 2, count++) {
p = (uint16_t *)pos;
uint16_t offset = next;
const uint8_t *start_of_axis_values_table = start_of_axis_values_offsets_array + offset;
if (start_of_axis_values_table + 12 > table_limit) continue;
p = (uint16_t *)(start_of_axis_values_table);
uint16_t format = next, axis_index = next, flags = next, value_name_id = next;
p32 = (uint32_t *)p;
#define app(fmt, ...) \
{ \
RAII_PyObject( \
v, Py_BuildValue("{sH sH sN " fmt "}", "format", format, "flags", flags, "name", get_best_name(name_lookup_table, value_name_id), __VA_ARGS__)); \
if (!v) return false; \
PyObject *l = PyDict_GetItemString(PyTuple_GET_ITEM(design_axes, axis_index), "values"); \
if (l && PyList_Append(l, v) != 0) return false; \
}
switch (format) {
case 1:
if (p32 + 1 <= (uint32_t *)table_limit && axis_index < PyTuple_GET_SIZE(design_axes)) {
const double value = next32;
app("sd", "value", value);
}
break;
case 2:
if (p32 + 3 <= (uint32_t *)table_limit && axis_index < PyTuple_GET_SIZE(design_axes)) {
const double value = next32, minimum = next32, maximum = next32;
app("sd sd sd", "value", value, "minimum", minimum, "maximum", maximum);
}
break;
case 3:
if (p32 + 2 <= (uint32_t *)table_limit && axis_index < PyTuple_GET_SIZE(design_axes)) {
const double value = next32, linked_value = next32;
app("sd sd", "value", value, "linked_value", linked_value);
}
break;
case 4:
if ((uint8_t *)(p) + 6 * axis_index <= table_limit) {
if (num_of_multi_axis_styles >= PyTuple_GET_SIZE(multi_axis_styles)) {
PyErr_Format(
PyExc_IndexError,
"corrupted STAT table in font too many multi_axis_styles (%d >= %d)",
(int)num_of_multi_axis_styles,
(int)PyTuple_GET_SIZE(multi_axis_styles));
return false;
}
RAII_PyObject(values, PyTuple_New(axis_index));
if (!values) return false;
for (Py_ssize_t n = 0; n < PyTuple_GET_SIZE(values); n++) {
uint16_t actual_axis_index = next;
double value = load_fixed((uint32_t *)p);
p += 2;
PyObject *e = Py_BuildValue("{sH sd}", "design_index", actual_axis_index, "value", value);
if (!e) return false;
PyTuple_SET_ITEM(values, n, e);
}
PyObject *e = Py_BuildValue("{sH sN sO}", "flags", flags, "name", get_best_name(name_lookup_table, value_name_id), "values", values);
if (!e) return false;
PyTuple_SET_ITEM(multi_axis_styles, num_of_multi_axis_styles, e);
num_of_multi_axis_styles++;
}
break;
}
}
if (_PyTuple_Resize(&multi_axis_styles, num_of_multi_axis_styles) == -1) return false;
ok:
if (PyDict_SetItemString(output, "design_axes", design_axes) != 0) return false;
if (PyDict_SetItemString(output, "multi_axis_styles", multi_axis_styles) != 0) return false;
efn = elided_fallback_name_id ? get_best_name(name_lookup_table, elided_fallback_name_id) : PyUnicode_FromString("");
if (!efn) return false;
if (PyDict_SetItemString(output, "elided_fallback_name", efn) != 0) return false;
return true;
}
bool
read_fvar_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output) {
RAII_PyObject(named_styles, PyTuple_New(0));
if (!named_styles) return false;
RAII_PyObject(axes, PyTuple_New(0));
if (!axes) return false;
RAII_PyObject(vpp, NULL);
if (!table || table_len < 14 * sizeof(uint16_t)) goto ok;
const uint16_t *p = (uint16_t *)table;
p += 2;
const uint16_t offset_to_start_of_axis_array = next;
next;
const uint16_t num_of_axis_records = next, size_of_axis_record = next, num_of_name_records = next, size_of_name_record = next;
const uint16_t size_of_coordinates = num_of_axis_records * sizeof(int32_t);
if (size_of_name_record < size_of_coordinates + 4) {
PyErr_Format(PyExc_ValueError, "size of name record: %u too small", size_of_name_record);
return NULL;
}
const bool has_postscript_name = size_of_name_record >= 3 * sizeof(uint16_t) + size_of_coordinates;
uint16_t i = 0;
if (size_of_axis_record < 20) {
PyErr_Format(PyExc_ValueError, "size of axis record: %u too small", size_of_axis_record);
return NULL;
}
if (_PyTuple_Resize(&axes, num_of_axis_records) == -1) return NULL;
for (const uint8_t *pos = table + offset_to_start_of_axis_array; pos + size_of_axis_record <= table + table_len && i < num_of_axis_records;
i++, pos += size_of_axis_record) {
uint32_t *p32 = (uint32_t *)(pos + 4);
const double minimum = next32, def = next32, maximum = next32;
p = (uint16_t *)(pos + 16);
int32_t flags = next, strid = next;
PyObject *axis = Py_BuildValue(
"{sd sd sd sN sO sN}",
"minimum",
minimum,
"maximum",
maximum,
"default",
def,
"tag",
PyUnicode_FromStringAndSize((const char *)pos, 4),
"hidden",
(flags & 1) ? Py_True : Py_False,
"strid",
get_best_name(name_lookup_table, strid));
if (!axis) return NULL;
PyTuple_SET_ITEM(axes, i, axis);
}
if (_PyTuple_Resize(&axes, i) == -1) return NULL;
char tag_buf[5] = {0};
i = 0;
if (_PyTuple_Resize(&named_styles, num_of_name_records) == -1) return NULL;
for (const uint8_t *pos = table + offset_to_start_of_axis_array + num_of_axis_records * size_of_axis_record;
pos + size_of_name_record <= table + table_len && i < num_of_name_records;
i++, pos += size_of_name_record) {
p = (uint16_t *)pos;
uint16_t name_id = next, psname_id = 0xffff;
next;
const uint32_t *p32 = (uint32_t *)p;
RAII_PyObject(axis_values, PyDict_New());
if (!axis_values) return NULL;
for (uint16_t i = 0; i < num_of_axis_records; i++) {
const uint8_t *t = table + offset_to_start_of_axis_array + i * size_of_axis_record;
memcpy(tag_buf, t, 4);
RAII_PyObject(pval, PyFloat_FromDouble(next32));
if (!pval || PyDict_SetItemString(axis_values, tag_buf, pval) != 0) return NULL;
}
if (has_postscript_name) {
p = (uint16_t *)p32;
psname_id = next;
}
PyObject *ns = Py_BuildValue(
"{sO sN sN}",
"axis_values",
axis_values,
"name",
get_best_name(name_lookup_table, name_id),
"psname",
(psname_id != 0xffff && psname_id ? get_best_name(name_lookup_table, psname_id) : PyUnicode_FromString("")));
if (!ns) return NULL;
PyTuple_SET_ITEM(named_styles, i, ns);
}
if (_PyTuple_Resize(&named_styles, i) == -1) return NULL;
ok:
vpp = get_best_name(name_lookup_table, 25);
if (!vpp) return false;
if (PyDict_SetItemString(output, "variations_postscript_name_prefix", vpp) != 0) return false;
if (PyDict_SetItemString(output, "axes", axes) != 0) return false;
if (PyDict_SetItemString(output, "named_styles", named_styles) != 0) return false;
return true;
}
#undef next32
#undef next
+967
View File
@@ -0,0 +1,967 @@
/*
* fontconfig.c
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "cleanup.h"
#include "lineops.h"
#include "fonts.h"
#include <fontconfig/fontconfig.h>
#include <dlfcn.h>
#include "freetype_render_ui_text.h"
#ifndef FC_COLOR
#define FC_COLOR "color"
#endif
static bool initialized = false;
static void *libfontconfig_handle = NULL;
static struct {
PyObject *face, *descriptor;
} builtin_nerd_font = {0};
#define FcInit dynamically_loaded_fc_symbol.Init
#define FcFini dynamically_loaded_fc_symbol.Fini
#define FcCharSetAddChar dynamically_loaded_fc_symbol.CharSetAddChar
#define FcPatternDestroy dynamically_loaded_fc_symbol.PatternDestroy
#define FcObjectSetDestroy dynamically_loaded_fc_symbol.ObjectSetDestroy
#define FcPatternAddDouble dynamically_loaded_fc_symbol.PatternAddDouble
#define FcPatternAddString dynamically_loaded_fc_symbol.PatternAddString
#define FcFontMatch dynamically_loaded_fc_symbol.FontMatch
#define FcCharSetCreate dynamically_loaded_fc_symbol.CharSetCreate
#define FcPatternGetString dynamically_loaded_fc_symbol.PatternGetString
#define FcFontSetDestroy dynamically_loaded_fc_symbol.FontSetDestroy
#define FcPatternGetInteger dynamically_loaded_fc_symbol.PatternGetInteger
#define FcPatternAddBool dynamically_loaded_fc_symbol.PatternAddBool
#define FcFontList dynamically_loaded_fc_symbol.FontList
#define FcObjectSetBuild dynamically_loaded_fc_symbol.ObjectSetBuild
#define FcCharSetDestroy dynamically_loaded_fc_symbol.CharSetDestroy
#define FcConfigSubstitute dynamically_loaded_fc_symbol.ConfigSubstitute
#define FcDefaultSubstitute dynamically_loaded_fc_symbol.DefaultSubstitute
#define FcPatternAddInteger dynamically_loaded_fc_symbol.PatternAddInteger
#define FcPatternCreate dynamically_loaded_fc_symbol.PatternCreate
#define FcPatternGetBool dynamically_loaded_fc_symbol.PatternGetBool
#define FcPatternGetMatrix dynamically_loaded_fc_symbol.PatternGetMatrix
#define FcPatternAddCharSet dynamically_loaded_fc_symbol.PatternAddCharSet
#define FcConfigAppFontAddFile dynamically_loaded_fc_symbol.ConfigAppFontAddFile
#define FcFontSort dynamically_loaded_fc_symbol.FontSort
#define FcFontSetMatch dynamically_loaded_fc_symbol.FontSetMatch
#define FcPatternGetCharSet dynamically_loaded_fc_symbol.PatternGetCharSet
#define FcCharSetHasChar dynamically_loaded_fc_symbol.CharSetHasChar
#define FcConfigGetCurrent dynamically_loaded_fc_symbol.ConfigGetCurrent
static struct {
FcBool (*Init)(void);
void (*Fini)(void);
FcBool (*CharSetAddChar)(FcCharSet *fcs, FcChar32 ucs4);
void (*PatternDestroy)(FcPattern *p);
void (*ObjectSetDestroy)(FcObjectSet *os);
FcBool (*PatternAddDouble)(FcPattern *p, const char *object, double d);
FcBool (*PatternAddString)(FcPattern *p, const char *object, const FcChar8 *s);
FcPattern *(*FontMatch)(FcConfig *config, FcPattern *p, FcResult *result);
FcCharSet *(*CharSetCreate)(void);
FcResult (*PatternGetString)(const FcPattern *p, const char *object, int n, FcChar8 **s);
void (*FontSetDestroy)(FcFontSet *s);
FcResult (*PatternGetInteger)(const FcPattern *p, const char *object, int n, int *i);
FcBool (*PatternAddBool)(FcPattern *p, const char *object, FcBool b);
FcFontSet *(*FontList)(FcConfig *config, FcPattern *p, FcObjectSet *os);
FcObjectSet *(*ObjectSetBuild)(const char *first, ...);
void (*CharSetDestroy)(FcCharSet *fcs);
FcBool (*ConfigSubstitute)(FcConfig *config, FcPattern *p, FcMatchKind kind);
void (*DefaultSubstitute)(FcPattern *pattern);
FcBool (*PatternAddInteger)(FcPattern *p, const char *object, int i);
FcPattern *(*PatternCreate)(void);
FcResult (*PatternGetBool)(const FcPattern *p, const char *object, int n, FcBool *b);
FcResult (*PatternGetMatrix)(const FcPattern *p, const char *object, int n, FcMatrix **m);
FcBool (*PatternAddCharSet)(FcPattern *p, const char *object, const FcCharSet *c);
FcBool (*ConfigAppFontAddFile)(FcConfig *config, const FcChar8 *file);
FcFontSet *(*FontSort)(FcConfig *config, FcPattern *p, FcBool trim, FcCharSet **csp, FcResult *result);
FcPattern *(*FontSetMatch)(FcConfig *config, FcFontSet **sets, int nsets, FcPattern *p, FcResult *result);
FcResult (*PatternGetCharSet)(const FcPattern *p, const char *object, int n, FcCharSet **c);
FcBool (*CharSetHasChar)(const FcCharSet *fcs, FcChar32 ucs4);
FcConfig *(*ConfigGetCurrent)(void);
} dynamically_loaded_fc_symbol = {0};
#define LOAD_FUNC(name) \
{ \
*(void **)(&dynamically_loaded_fc_symbol.name) = dlsym(libfontconfig_handle, "Fc" #name); \
if (!dynamically_loaded_fc_symbol.name) { \
const char *error = dlerror(); \
fatal("Failed to load the function Fc" #name " with error: %s", error ? error : ""); \
} \
}
static void
load_fontconfig_lib(void) {
const char *libnames[] = {
#if defined(_KITTY_FONTCONFIG_LIBRARY)
_KITTY_FONTCONFIG_LIBRARY,
#else
"libfontconfig.so",
// some installs are missing the .so symlink, so try the full name
"libfontconfig.so.1",
#endif
NULL};
for (int i = 0; libnames[i]; i++) {
libfontconfig_handle = dlopen(libnames[i], RTLD_LAZY);
if (libfontconfig_handle) break;
}
if (libfontconfig_handle == NULL) { fatal("Failed to find and load fontconfig"); }
dlerror(); /* Clear any existing error */
LOAD_FUNC(Init);
LOAD_FUNC(Fini);
LOAD_FUNC(CharSetAddChar);
LOAD_FUNC(PatternDestroy);
LOAD_FUNC(ObjectSetDestroy);
LOAD_FUNC(PatternAddDouble);
LOAD_FUNC(PatternAddString);
LOAD_FUNC(FontMatch);
LOAD_FUNC(CharSetCreate);
LOAD_FUNC(PatternGetString);
LOAD_FUNC(FontSetDestroy);
LOAD_FUNC(PatternGetInteger);
LOAD_FUNC(PatternAddBool);
LOAD_FUNC(FontList);
LOAD_FUNC(ObjectSetBuild);
LOAD_FUNC(CharSetDestroy);
LOAD_FUNC(ConfigSubstitute);
LOAD_FUNC(DefaultSubstitute);
LOAD_FUNC(PatternAddInteger);
LOAD_FUNC(PatternCreate);
LOAD_FUNC(PatternGetBool);
LOAD_FUNC(PatternGetMatrix);
LOAD_FUNC(PatternAddCharSet);
LOAD_FUNC(ConfigAppFontAddFile);
LOAD_FUNC(FontSort);
LOAD_FUNC(FontSetMatch);
LOAD_FUNC(PatternGetCharSet);
LOAD_FUNC(CharSetHasChar);
LOAD_FUNC(ConfigGetCurrent);
}
#undef LOAD_FUNC
static void
ensure_initialized(void) {
if (!initialized) {
load_fontconfig_lib();
if (!FcInit()) fatal("Failed to initialize fontconfig library");
initialized = true;
}
}
static void clear_fallback_candidates(void);
static void
finalize(void) {
if (initialized) {
Py_CLEAR(builtin_nerd_font.face);
Py_CLEAR(builtin_nerd_font.descriptor);
clear_fallback_candidates();
FcFini();
dlclose(libfontconfig_handle);
libfontconfig_handle = NULL;
initialized = false;
}
}
static PyObject *
pybool(FcBool x) {
PyObject *ans = x ? Py_True : Py_False;
Py_INCREF(ans);
return ans;
}
static PyObject *
pyspacing(int val) {
#define S(x) \
case FC_##x: return PyUnicode_FromString(#x)
switch (val) {
S(PROPORTIONAL);
S(DUAL);
S(MONO);
S(CHARCELL);
default: return PyUnicode_FromString("UNKNOWN");
}
#undef S
}
static PyObject *
increment_and_return(PyObject *x) {
if (x) Py_INCREF(x);
return x;
}
static PyObject *
pattern_as_dict(FcPattern *pat) {
RAII_PyObject(ans, Py_BuildValue("{ss}", "descriptor_type", "fontconfig"));
if (ans == NULL) return NULL;
#define PS(x) PyUnicode_Decode((const char *)x, strlen((const char *)x), "UTF-8", "replace")
#define G(type, get, which, conv, name, default) \
{ \
type out; \
if (get(pat, which, 0, &out) == FcResultMatch) { \
RAII_PyObject(p, conv(out)); \
if (!p || PyDict_SetItemString(ans, #name, p) != 0) return NULL; \
} else { \
RAII_PyObject(d, default); \
if (!d || PyDict_SetItemString(ans, #name, d) != 0) return NULL; \
} \
}
#define L(type, get, which, conv, name) \
{ \
type out; \
int n = 0; \
RAII_PyObject(list, PyList_New(0)); \
if (!list) return NULL; \
while (get(pat, which, n++, &out) == FcResultMatch) { \
RAII_PyObject(p, conv(out)); \
if (!p || PyList_Append(list, p) != 0) return NULL; \
} \
if (PyDict_SetItemString(ans, #name, list) != 0) return NULL; \
}
#define S(which, key) G(FcChar8 *, FcPatternGetString, which, PS, key, PyUnicode_FromString(""))
#define LS(which, key) L(FcChar8 *, FcPatternGetString, which, PS, key)
#define I(which, key) G(int, FcPatternGetInteger, which, PyLong_FromLong, key, PyLong_FromUnsignedLong(0))
#define B(which, key) G(FcBool, FcPatternGetBool, which, pybool, key, increment_and_return(Py_False))
#define E(which, key, conv) G(int, FcPatternGetInteger, which, conv, key, PyLong_FromUnsignedLong(0))
S(FC_FILE, path);
S(FC_FAMILY, family);
S(FC_STYLE, style);
S(FC_FULLNAME, full_name);
S(FC_POSTSCRIPT_NAME, postscript_name);
LS(FC_FONT_FEATURES, fontfeatures);
B(FC_VARIABLE, variable);
#ifdef FC_NAMED_INSTANCE
B(FC_NAMED_INSTANCE, named_instance);
#else
PyDict_SetItemString(ans, "named_instance", Py_False);
#endif
I(FC_WEIGHT, weight);
I(FC_WIDTH, width)
I(FC_SLANT, slant);
I(FC_HINT_STYLE, hint_style);
I(FC_INDEX, index);
I(FC_RGBA, subpixel);
I(FC_LCD_FILTER, lcdfilter);
B(FC_HINTING, hinting);
B(FC_SCALABLE, scalable);
B(FC_OUTLINE, outline);
B(FC_COLOR, color);
E(FC_SPACING, spacing, pyspacing);
{
FcMatrix *mtx = NULL;
if (FcPatternGetMatrix(pat, FC_MATRIX, 0, &mtx) == FcResultMatch && mtx) {
RAII_PyObject(t, Py_BuildValue("(dddd)", mtx->xx, mtx->xy, mtx->yx, mtx->yy));
if (!t || PyDict_SetItemString(ans, "matrix", t) != 0) return NULL;
}
}
Py_INCREF(ans);
return ans;
#undef PS
#undef S
#undef I
#undef B
#undef E
#undef G
#undef L
#undef LS
}
static PyObject *
font_set(FcFontSet *fs) {
PyObject *ans = PyTuple_New(fs->nfont);
if (ans == NULL) return NULL;
for (int i = 0; i < fs->nfont; i++) {
PyObject *d = pattern_as_dict(fs->fonts[i]);
if (d == NULL) {
Py_CLEAR(ans);
break;
}
PyTuple_SET_ITEM(ans, i, d);
}
return ans;
}
#define AP(func, which, in, desc) \
if (!func(pat, which, in)) { \
PyErr_Format(PyExc_ValueError, "Failed to add %s to fontconfig pattern", desc, NULL); \
goto end; \
}
static PyObject *
fc_list(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
ensure_initialized();
int allow_bitmapped_fonts = 0, spacing = -1, only_variable = 0;
PyObject *ans = NULL;
FcObjectSet *os = NULL;
FcPattern *pat = NULL;
FcFontSet *fs = NULL;
static char *kwds[] = {"spacing", "allow_bitmapped_fonts", "only_variable", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "|ipp", kwds, &spacing, &allow_bitmapped_fonts, &only_variable)) return NULL;
pat = FcPatternCreate();
if (pat == NULL) return PyErr_NoMemory();
if (!allow_bitmapped_fonts) {
AP(FcPatternAddBool, FC_OUTLINE, FcTrue, "outline");
AP(FcPatternAddBool, FC_SCALABLE, FcTrue, "scalable");
}
if (spacing > -1) AP(FcPatternAddInteger, FC_SPACING, spacing, "spacing");
if (only_variable) AP(FcPatternAddBool, FC_VARIABLE, FcTrue, "variable");
os = FcObjectSetBuild(
FC_FILE,
FC_POSTSCRIPT_NAME,
FC_FAMILY,
FC_STYLE,
FC_FULLNAME,
FC_WEIGHT,
FC_WIDTH,
FC_SLANT,
FC_HINT_STYLE,
FC_INDEX,
FC_HINTING,
FC_SCALABLE,
FC_OUTLINE,
FC_COLOR,
FC_SPACING,
FC_VARIABLE,
#ifdef FC_NAMED_INSTANCE
FC_NAMED_INSTANCE,
#endif
NULL);
if (!os) {
PyErr_SetString(PyExc_ValueError, "Failed to create fontconfig object set");
goto end;
}
fs = FcFontList(NULL, pat, os);
if (!fs) {
PyErr_SetString(PyExc_ValueError, "Failed to create fontconfig font set");
goto end;
}
ans = font_set(fs);
end:
if (pat != NULL) FcPatternDestroy(pat);
if (os != NULL) FcObjectSetDestroy(os);
if (fs != NULL) FcFontSetDestroy(fs);
return ans;
}
static PyObject *
_fc_match(FcPattern *pat) {
FcPattern *match = NULL;
PyObject *ans = NULL;
FcResult result;
FcConfigSubstitute(NULL, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
/* printf("fc_match = %s\n", FcNameUnparse(pat)); */
match = FcFontMatch(NULL, pat, &result);
if (match == NULL) {
PyErr_SetString(PyExc_KeyError, "FcFontMatch() failed");
goto end;
}
ans = pattern_as_dict(match);
end:
if (match) FcPatternDestroy(match);
return ans;
}
static char_type char_buf[1024];
static bool
add_charset(FcPattern *pat, const char_type *chars, size_t num) {
bool ok = false;
FcCharSet *charset = NULL;
if (!num) return true;
charset = FcCharSetCreate();
if (charset == NULL) {
PyErr_NoMemory();
goto end;
}
for (size_t i = 0; i < num; i++) {
if (!FcCharSetAddChar(charset, chars[i])) {
PyErr_SetString(PyExc_RuntimeError, "Failed to add character to fontconfig charset");
goto end;
}
}
AP(FcPatternAddCharSet, FC_CHARSET, charset, "charset");
ok = true;
end:
if (charset != NULL) FcCharSetDestroy(charset);
return ok;
}
// Fallback font matching {{{
// Asking fontconfig for the font to use for a codepoint the main font does not
// cover means calling FcFontMatch(), which scores the entire system font
// database. Cells that need a fallback font are memoized by fallback_font() in
// fonts.c, but a screen containing many *distinct* uncovered codepoints (for
// instance Nerd Font Private Use Area icons with no Nerd Font installed) still
// needs one full database scan per distinct cell, which stalls the main thread
// for tens to hundreds of milliseconds. See
// https://github.com/kovidgoyal/kitty/issues/10496
//
// Instead, cache the list of candidate fonts, sorted by closeness to the
// requested family and style, once per (family, style, color) combination. A
// lookup then walks that in-memory list using the candidates' charsets, narrows
// the field down to a handful of fonts and has fontconfig score only those.
typedef struct FallbackCandidates {
char *family; // NULL means no family was requested
bool bold, italic, prefer_color;
FcFontSet *fonts; // all candidate fonts, closest match first
FcCharSet *coverage; // union of the charsets of all candidates
} FallbackCandidates;
static struct {
FallbackCandidates *entries;
size_t count, capacity;
FcPattern **scratch; // scratch space used to build the narrowed down font set
size_t scratch_capacity;
FcConfig *config; // the fontconfig configuration entries were built against
} fallback_candidates = {0};
static void
clear_fallback_candidates(void) {
for (size_t i = 0; i < fallback_candidates.count; i++) {
FallbackCandidates *q = fallback_candidates.entries + i;
free(q->family);
if (q->fonts) FcFontSetDestroy(q->fonts);
if (q->coverage) FcCharSetDestroy(q->coverage);
}
free(fallback_candidates.entries);
free(fallback_candidates.scratch);
memset(&fallback_candidates, 0, sizeof(fallback_candidates));
}
static FcPattern *
create_fallback_pattern(const char *family, bool bold, bool italic, bool prefer_color) {
FcPattern *pat = FcPatternCreate();
if (pat == NULL) {
PyErr_NoMemory();
return NULL;
}
if (family) AP(FcPatternAddString, FC_FAMILY, (const FcChar8 *)family, "family");
if (bold) { AP(FcPatternAddInteger, FC_WEIGHT, FC_WEIGHT_BOLD, "weight"); }
if (italic) { AP(FcPatternAddInteger, FC_SLANT, FC_SLANT_ITALIC, "slant"); }
if (prefer_color) { AP(FcPatternAddBool, FC_COLOR, true, "color"); }
return pat;
end:
FcPatternDestroy(pat);
return NULL;
}
static FallbackCandidates *
candidates_for(const char *family, bool bold, bool italic, bool prefer_color) {
FcConfig *config = FcConfigGetCurrent();
if (config != fallback_candidates.config) clear_fallback_candidates();
for (size_t i = 0; i < fallback_candidates.count; i++) {
FallbackCandidates *q = fallback_candidates.entries + i;
if (q->bold == bold && q->italic == italic && q->prefer_color == prefer_color &&
(q->family == NULL ? family == NULL : (family != NULL && strcmp(q->family, family) == 0)))
return q;
}
FcPattern *pat = create_fallback_pattern(family, bold, italic, prefer_color);
if (!pat) {
PyErr_Clear(); // fall back to FcFontMatch()
return NULL;
}
FcConfigSubstitute(NULL, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
// trim must be false so that the candidate list contains every font
// FcFontMatch() would consider, in the order in which it prefers them
FcCharSet *coverage = NULL;
FcResult result;
FcFontSet *fonts = FcFontSort(NULL, pat, FcFalse, &coverage, &result);
FcPatternDestroy(pat);
if (fonts && fonts->nfont < 1) {
FcFontSetDestroy(fonts);
fonts = NULL;
}
if (!fonts && coverage) {
FcCharSetDestroy(coverage);
coverage = NULL;
}
ensure_space_for(&fallback_candidates, entries, FallbackCandidates, fallback_candidates.count + 1, capacity, 8, true);
if (fonts) ensure_space_for(&fallback_candidates, scratch, FcPattern *, (size_t)fonts->nfont, scratch_capacity, 64, false);
FallbackCandidates *ans = fallback_candidates.entries + fallback_candidates.count++;
*ans = (FallbackCandidates){.bold = bold, .italic = italic, .prefer_color = prefer_color, .fonts = fonts, .coverage = coverage};
if (family) {
ans->family = strdup(family);
if (!ans->family) fatal("Out of memory allocating fallback font candidate key");
}
fallback_candidates.config = config;
// fonts is NULL if FcFontSort() failed, cached so that it is not retried
// for every lookup, match_fallback_font() then uses FcFontMatch()
return ans;
}
static FcPattern *
match_in_candidates(const FallbackCandidates *q, FcPattern *pat, const char_type *chars, size_t num_chars, FcResult *result) {
// Chars that no font at all covers cannot change which font fontconfig
// prefers, since every candidate is missing them equally.
char_type relevant[arraysz(char_buf)];
size_t num_relevant = 0;
for (size_t i = 0; i < num_chars; i++) {
if (!q->coverage || FcCharSetHasChar(q->coverage, chars[i])) relevant[num_relevant++] = chars[i];
}
FcPattern **narrow = fallback_candidates.scratch;
int num_narrow = 1;
// The closest candidate ignoring coverage altogether always has to be
// considered: it is the answer when no font covers any of the chars and it
// can also win on higher priority criteria such as FC_COLOR, which
// fontconfig ranks above coverage.
narrow[0] = q->fonts->fonts[0];
for (int i = 0; i < q->fonts->nfont && num_relevant; i++) {
FcPattern *f = q->fonts->fonts[i];
FcCharSet *cs = NULL;
if (FcPatternGetCharSet(f, FC_CHARSET, 0, &cs) != FcResultMatch || !cs) continue;
size_t covered = 0;
for (size_t c = 0; c < num_relevant; c++) {
if (FcCharSetHasChar(cs, relevant[c])) covered++;
}
if (!covered) continue;
if (f != narrow[0]) narrow[num_narrow++] = f;
// Once a font covering every char has been found, no font later in the
// candidate list can score better, since fontconfig prefers closer
// candidates and full coverage is the best possible coverage score.
// Earlier candidates with only partial coverage are kept, as they can
// still win on criteria fontconfig ranks above coverage, such as
// FC_COLOR.
if (covered == num_relevant) break;
}
FcFontSet set = {.nfont = num_narrow, .sfont = num_narrow, .fonts = narrow};
FcFontSet *sets[1] = {&set};
return FcFontSetMatch(NULL, sets, 1, pat, result);
}
// Returns the (render prepared) fontconfig pattern for the best font for the
// specified chars, which the caller must destroy, or NULL with a Python
// exception set. Set use_candidate_cache to false to use FcFontMatch() directly,
// this is used by the tests to check the two give equivalent results.
static FcPattern *
match_fallback_font(const char *family, bool bold, bool italic, bool prefer_color, const char_type *chars, size_t num_chars, bool use_candidate_cache) {
if (family && !family[0]) family = NULL;
if (num_chars > arraysz(char_buf)) num_chars = arraysz(char_buf);
FcResult result;
const FallbackCandidates *q = NULL;
FcPattern *ans = NULL, *pat = create_fallback_pattern(family, bold, italic, prefer_color);
if (!pat) return NULL;
if (!add_charset(pat, chars, num_chars)) goto end;
FcConfigSubstitute(NULL, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
if (use_candidate_cache) q = candidates_for(family, bold, italic, prefer_color);
ans = (q && q->fonts) ? match_in_candidates(q, pat, chars, num_chars, &result) : FcFontMatch(NULL, pat, &result);
if (ans == NULL) PyErr_SetString(PyExc_KeyError, "Failed to find any font matching the specified pattern");
end:
FcPatternDestroy(pat);
return ans;
}
// }}}
static bool
extract_face_from_pattern(FcPattern *match, FontConfigFace *ans) {
FcChar8 *out;
#define g(func, prop, output) \
if (func(match, prop, 0, &output) != FcResultMatch) { \
PyErr_SetString(PyExc_ValueError, "No " #prop " found in fontconfig match result"); \
return false; \
}
g(FcPatternGetString, FC_FILE, out);
if (FcPatternGetInteger(match, FC_INDEX, 0, &ans->index) != FcResultMatch) ans->index = 0; // ignore missing index assume it is zero
g(FcPatternGetInteger, FC_HINT_STYLE, ans->hintstyle);
g(FcPatternGetBool, FC_HINTING, ans->hinting);
#undef g
ans->path = strdup((char *)out);
if (!ans->path) {
PyErr_NoMemory();
return false;
}
return true;
}
static bool
_native_fc_match(FcPattern *pat, FontConfigFace *ans) {
FcResult result;
FcConfigSubstitute(NULL, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
/* printf("fc_match = %s\n", FcNameUnparse(pat)); */
FcPattern *match = FcFontMatch(NULL, pat, &result);
if (match == NULL) {
PyErr_SetString(PyExc_KeyError, "FcFontMatch() failed");
return false;
}
bool ok = extract_face_from_pattern(match, ans);
FcPatternDestroy(match);
return ok;
}
bool
information_for_font_family(const char *family, bool bold, bool italic, FontConfigFace *ans) {
ensure_initialized();
memset(ans, 0, sizeof(FontConfigFace));
FcPattern *pat = FcPatternCreate();
bool ok = false;
if (pat == NULL) {
PyErr_NoMemory();
return ok;
}
if (family && strlen(family) > 0) AP(FcPatternAddString, FC_FAMILY, (const FcChar8 *)family, "family");
if (bold) { AP(FcPatternAddInteger, FC_WEIGHT, FC_WEIGHT_BOLD, "weight"); }
if (italic) { AP(FcPatternAddInteger, FC_SLANT, FC_SLANT_ITALIC, "slant"); }
ok = _native_fc_match(pat, ans);
end:
if (pat != NULL) FcPatternDestroy(pat);
return ok;
}
static PyObject *
fc_match(PyObject UNUSED *self, PyObject *args) {
ensure_initialized();
char *family = NULL;
int bold = 0, italic = 0, allow_bitmapped_fonts = 0, spacing = FC_MONO;
double size_in_pts = 0, dpi = 0;
FcPattern *pat = NULL;
PyObject *ans = NULL;
if (!PyArg_ParseTuple(args, "|zppipdd", &family, &bold, &italic, &spacing, &allow_bitmapped_fonts, &size_in_pts, &dpi)) return NULL;
pat = FcPatternCreate();
if (pat == NULL) return PyErr_NoMemory();
if (family && strlen(family) > 0) AP(FcPatternAddString, FC_FAMILY, (const FcChar8 *)family, "family");
if (spacing >= FC_DUAL) {
// pass the family,monospace as the family parameter to fc-match,
// which will fallback to using monospace if the family does not match.
AP(FcPatternAddString, FC_FAMILY, (const FcChar8 *)"monospace", "family");
AP(FcPatternAddInteger, FC_SPACING, spacing, "spacing");
}
if (!allow_bitmapped_fonts) {
AP(FcPatternAddBool, FC_OUTLINE, true, "outline");
AP(FcPatternAddBool, FC_SCALABLE, true, "scalable");
}
if (size_in_pts > 0) { AP(FcPatternAddDouble, FC_SIZE, size_in_pts, "size"); }
if (dpi > 0) { AP(FcPatternAddDouble, FC_DPI, dpi, "dpi"); }
if (bold) { AP(FcPatternAddInteger, FC_WEIGHT, FC_WEIGHT_BOLD, "weight"); }
if (italic) { AP(FcPatternAddInteger, FC_SLANT, FC_SLANT_ITALIC, "slant"); }
ans = _fc_match(pat);
end:
if (pat != NULL) FcPatternDestroy(pat);
return ans;
}
static PyObject *
fc_match_postscript_name(PyObject UNUSED *self, PyObject *args) {
ensure_initialized();
const char *postscript_name = NULL;
FcPattern *pat = NULL;
PyObject *ans = NULL;
if (!PyArg_ParseTuple(args, "s", &postscript_name)) return NULL;
if (!postscript_name || !postscript_name[0]) {
PyErr_SetString(PyExc_KeyError, "postscript_name must not be empty");
return NULL;
}
pat = FcPatternCreate();
if (pat == NULL) return PyErr_NoMemory();
AP(FcPatternAddString, FC_POSTSCRIPT_NAME, (const FcChar8 *)postscript_name, "postscript_name");
ans = _fc_match(pat);
end:
if (pat != NULL) FcPatternDestroy(pat);
return ans;
}
PyObject *
specialize_font_descriptor(PyObject *base_descriptor, double font_sz_in_pts, double dpi_x, double dpi_y) {
ensure_initialized();
PyObject *p = PyDict_GetItemString(base_descriptor, "path");
PyObject *idx = PyDict_GetItemString(base_descriptor, "index");
if (p == NULL) {
PyErr_SetString(PyExc_ValueError, "Base descriptor has no path");
return NULL;
}
if (idx == NULL) {
PyErr_SetString(PyExc_ValueError, "Base descriptor has no index");
return NULL;
}
unsigned long face_idx = PyLong_AsUnsignedLong(idx);
if (PyErr_Occurred()) return NULL;
FcPattern *pat = FcPatternCreate();
if (pat == NULL) return PyErr_NoMemory();
RAII_PyObject(features, PyList_New(0));
if (!features) return NULL;
RAII_PyObject(final_features, NULL);
RAII_PyObject(ans, NULL);
AP(FcPatternAddString, FC_FILE, (const FcChar8 *)PyUnicode_AsUTF8(p), "path");
AP(FcPatternAddInteger, FC_INDEX, face_idx, "index");
AP(FcPatternAddDouble, FC_SIZE, font_sz_in_pts, "size");
AP(FcPatternAddDouble, FC_DPI, (dpi_x + dpi_y) / 2.0, "dpi");
ans = _fc_match(pat);
FcPatternDestroy(pat);
pat = NULL;
if (!ans) return NULL;
// fontconfig returns a completely random font if the base descriptor
// points to a font that fontconfig hasnt indexed, for example the built-in
// NERD font
PyObject *new_path = PyDict_GetItemString(ans, "path");
if (!new_path || PyObject_RichCompareBool(p, new_path, Py_EQ) != 1) {
Py_CLEAR(ans);
ans = PyDict_Copy(base_descriptor);
if (!ans) return NULL;
}
if (face_idx > 0) {
// For some reason FcFontMatch sets the index to zero, so manually restore it.
if (PyDict_SetItemString(ans, "index", idx) != 0) return NULL;
}
PyObject *named_style = PyDict_GetItemString(base_descriptor, "named_style");
if (named_style) {
if (PyDict_SetItemString(ans, "named_style", named_style) != 0) return NULL;
}
PyObject *axes = PyDict_GetItemString(base_descriptor, "axes");
if (axes) {
if (PyDict_SetItemString(ans, "axes", axes) != 0) return NULL;
}
PyObject *matrix = PyDict_GetItemString(base_descriptor, "matrix");
if (matrix) {
if (PyDict_SetItemString(ans, "matrix", matrix) != 0) return NULL;
}
PyObject *ff = PyDict_GetItemString(ans, "fontfeatures");
if (ff && PyList_GET_SIZE(ff)) {
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(ff); i++) {
RAII_PyObject(pff, (PyObject *)parse_font_feature(PyUnicode_AsUTF8(PyList_GET_ITEM(ff, i))));
if (pff == NULL) {
PyErr_Print();
fprintf(stderr, "\n");
} else if (PyList_Append(features, pff) != 0) return NULL;
}
}
PyObject *base_features = PyDict_GetItemString(base_descriptor, "features");
final_features = PyTuple_New(PyList_GET_SIZE(features) + (base_features ? PyTuple_GET_SIZE(base_features) : 0));
if (!final_features) return NULL;
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(features); i++) { PyTuple_SET_ITEM(final_features, i, Py_NewRef(PyList_GET_ITEM(features, i))); }
if (base_features) {
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(base_features); i++) {
PyTuple_SET_ITEM(final_features, i + PyList_GET_SIZE(features), Py_NewRef(PyTuple_GET_ITEM(base_features, i)));
}
}
if (PyDict_SetItemString(ans, "features", final_features) != 0) return NULL;
Py_INCREF(ans);
return ans;
end:
if (pat) FcPatternDestroy(pat);
return NULL;
}
bool
fallback_font(char_type ch, const char *family, bool bold, bool italic, bool prefer_color, FontConfigFace *ans) {
ensure_initialized();
memset(ans, 0, sizeof(FontConfigFace));
bool ok = false;
FcPattern *match = match_fallback_font(family, bold, italic, prefer_color, &ch, 1, true);
if (match) {
ok = extract_face_from_pattern(match, ans);
FcPatternDestroy(match);
}
if (!ok && builtin_nerd_font.face && builtin_nerd_font.descriptor && glyph_id_for_codepoint(builtin_nerd_font.face, ch) > 0) {
PyObject *pypath = PyDict_GetItemString(builtin_nerd_font.descriptor, "path");
PyObject *pyindex = PyDict_GetItemString(builtin_nerd_font.descriptor, "index");
PyObject *pyhinting = PyDict_GetItemString(builtin_nerd_font.descriptor, "hinting");
PyObject *pyhintstyle = PyDict_GetItemString(builtin_nerd_font.descriptor, "hint_style");
if (pypath && PyUnicode_Check(pypath)) {
const char *path = PyUnicode_AsUTF8(pypath);
if (path) {
ans->path = strdup(path);
if (ans->path) {
ans->index = (pyindex && PyLong_Check(pyindex)) ? (int)PyLong_AsLong(pyindex) : 0;
ans->hinting = (pyhinting && PyLong_Check(pyhinting)) ? (int)PyLong_AsLong(pyhinting) : 0;
ans->hintstyle = (pyhintstyle && PyLong_Check(pyhintstyle)) ? (int)PyLong_AsLong(pyhintstyle) : 0;
ok = true;
}
}
}
if (PyErr_Occurred()) PyErr_Clear();
}
return ok;
}
static bool
face_has_codepoint(const void *face, char_type cp) {
return glyph_id_for_codepoint(face, cp) > 0;
}
PyObject *
create_fallback_face(PyObject UNUSED *base_face, const ListOfChars *lc, bool bold, bool italic, bool emoji_presentation, FONTS_DATA_HANDLE fg) {
ensure_initialized();
PyObject *ans = NULL;
RAII_PyObject(d, NULL);
bool glyph_found = false;
size_t num = cell_as_unicode_for_fallback(lc, char_buf, arraysz(char_buf));
FcPattern *match = match_fallback_font(
emoji_presentation ? "emoji" : "monospace", !emoji_presentation && bold, !emoji_presentation && italic, emoji_presentation, char_buf, num, true);
if (match) {
d = pattern_as_dict(match);
FcPatternDestroy(match);
}
face_from_descriptor:
if (d) {
ssize_t idx = -1;
PyObject *q;
while ((q = iter_fallback_faces(fg, &idx))) {
if (face_equals_descriptor(q, d)) {
ans = PyLong_FromSsize_t(idx);
if (!glyph_found) glyph_found = has_cell_text(face_has_codepoint, q, false, lc);
goto end;
}
}
ans = face_from_descriptor(d, fg);
if (!glyph_found && ans) glyph_found = has_cell_text(face_has_codepoint, ans, false, lc);
}
end:
Py_CLEAR(d);
if (!glyph_found && !PyErr_Occurred()) {
if (builtin_nerd_font.face && has_cell_text(face_has_codepoint, builtin_nerd_font.face, false, lc)) {
Py_CLEAR(ans);
d = builtin_nerd_font.descriptor;
Py_INCREF(d);
glyph_found = true;
goto face_from_descriptor;
} else {
if (global_state.debug_font_fallback && ans) has_cell_text(face_has_codepoint, ans, true, lc);
Py_CLEAR(ans);
ans = Py_None;
Py_INCREF(ans);
}
}
return ans;
}
static PyObject *
set_builtin_nerd_font(PyObject UNUSED *self, PyObject *pypath) {
if (!PyUnicode_Check(pypath)) {
PyErr_SetString(PyExc_TypeError, "path must be a string");
return NULL;
}
ensure_initialized();
const char *path = PyUnicode_AsUTF8(pypath);
FcPattern *pat = FcPatternCreate();
if (pat == NULL) return PyErr_NoMemory();
Py_CLEAR(builtin_nerd_font.face);
Py_CLEAR(builtin_nerd_font.descriptor);
builtin_nerd_font.face = face_from_path(path, 0, NULL);
if (builtin_nerd_font.face) {
// Copy whatever hinting settings fontconfig returns for the nerd font postscript name
AP(FcPatternAddString, FC_POSTSCRIPT_NAME, (const unsigned char *)postscript_name_for_face(builtin_nerd_font.face), "postscript_name");
RAII_PyObject(d, _fc_match(pat));
if (!d) goto end;
builtin_nerd_font.descriptor = PyDict_New();
if (!builtin_nerd_font.descriptor) goto end;
#define copy(key) \
{ \
PyObject *t = PyDict_GetItemString(d, #key); \
if (t) { \
if (PyDict_SetItemString(builtin_nerd_font.descriptor, #key, t) != 0) goto end; \
} \
}
copy(hinting);
copy(hint_style);
#undef copy
if (PyDict_SetItemString(builtin_nerd_font.descriptor, "path", pypath) != 0) goto end;
if (PyDict_SetItemString(builtin_nerd_font.descriptor, "index", PyLong_FromLong(0)) != 0) goto end;
}
end:
if (pat) FcPatternDestroy(pat);
if (PyErr_Occurred()) {
Py_CLEAR(builtin_nerd_font.face);
Py_CLEAR(builtin_nerd_font.descriptor);
return NULL;
}
Py_INCREF(builtin_nerd_font.descriptor);
return builtin_nerd_font.descriptor;
}
static PyObject *
add_font_file(PyObject UNUSED *self, PyObject *args) {
ensure_initialized();
const char *path = NULL;
if (!PyArg_ParseTuple(args, "s", &path)) return NULL;
if (FcConfigAppFontAddFile(NULL, (const unsigned char *)path)) {
clear_fallback_candidates(); // the newly added font must be considered for fallback
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject *
clear_fallback_font_cache(PyObject UNUSED *self, PyObject UNUSED *args) {
clear_fallback_candidates();
Py_RETURN_NONE;
}
// Used by the tests to verify that the cached candidate list based matching is
// equivalent to asking fontconfig to score the entire font database.
static PyObject *
fc_match_fallback(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
ensure_initialized();
PyObject *text;
int bold = 0, italic = 0, prefer_color = 0, use_candidate_cache = 1;
static char *kwds[] = {"text", "bold", "italic", "prefer_color", "use_candidate_cache", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "U|pppp", kwds, &text, &bold, &italic, &prefer_color, &use_candidate_cache)) return NULL;
const Py_ssize_t count = PyUnicode_GET_LENGTH(text);
if (count < 1 || count > (Py_ssize_t)arraysz(char_buf)) {
PyErr_Format(PyExc_ValueError, "text must have between 1 and %zu characters", arraysz(char_buf));
return NULL;
}
for (Py_ssize_t i = 0; i < count; i++) char_buf[i] = PyUnicode_READ_CHAR(text, i);
FcPattern *match = match_fallback_font(prefer_color ? "emoji" : "monospace", bold, italic, prefer_color, char_buf, count, use_candidate_cache);
if (!match) return NULL;
PyObject *ans = pattern_as_dict(match);
FcPatternDestroy(match);
return ans;
}
#undef AP
static PyMethodDef module_methods[] = {
{"fc_list", (PyCFunction)(void (*)(void))(fc_list), METH_VARARGS | METH_KEYWORDS, NULL},
METHODB(fc_match, METH_VARARGS),
METHODB(fc_match_postscript_name, METH_VARARGS),
METHODB(add_font_file, METH_VARARGS),
METHODB(clear_fallback_font_cache, METH_NOARGS),
{"fc_match_fallback", (PyCFunction)(void (*)(void))(fc_match_fallback), METH_VARARGS | METH_KEYWORDS, NULL},
METHODB(set_builtin_nerd_font, METH_O),
{NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_fontconfig_library(PyObject *module) {
register_at_exit_cleanup_func(FONTCONFIG_CLEANUP_FUNC, finalize);
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
PyModule_AddIntMacro(module, FC_WEIGHT_REGULAR);
PyModule_AddIntMacro(module, FC_WEIGHT_MEDIUM);
PyModule_AddIntMacro(module, FC_WEIGHT_SEMIBOLD);
PyModule_AddIntMacro(module, FC_WEIGHT_BOLD);
PyModule_AddIntMacro(module, FC_SLANT_ITALIC);
PyModule_AddIntMacro(module, FC_SLANT_ROMAN);
PyModule_AddIntMacro(module, FC_PROPORTIONAL);
PyModule_AddIntMacro(module, FC_DUAL);
PyModule_AddIntMacro(module, FC_MONO);
PyModule_AddIntMacro(module, FC_CHARCELL);
PyModule_AddIntMacro(module, FC_WIDTH_NORMAL);
return true;
}
+2957
View File
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "lineops.h"
#include "state.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#include <hb.h>
#pragma GCC diagnostic pop
typedef struct {
uint8_t *canvas;
size_t width, height;
} StringCanvas;
typedef struct FontFeatures {
size_t count;
hb_feature_t *features;
} FontFeatures;
typedef struct ParsedFontFeature {
PyObject_HEAD
hb_feature_t feature;
Py_hash_t hashval;
bool hash_computed;
} ParsedFontFeature;
typedef struct GlyphRenderInfo {
unsigned canvas_width, rendered_width;
int x;
} GlyphRenderInfo;
ParsedFontFeature *parse_font_feature(const char *spec);
// API that font backends need to implement
unsigned int glyph_id_for_codepoint(const PyObject *, char_type);
int get_glyph_width(PyObject *, glyph_index);
bool is_glyph_empty(PyObject *, glyph_index);
hb_font_t *harfbuzz_font_for_face(PyObject *);
bool set_size_for_face(PyObject *, unsigned int, bool, FONTS_DATA_HANDLE);
FontCellMetrics cell_metrics(PyObject *);
bool render_glyphs_in_cells(
PyObject *f,
bool bold,
bool italic,
hb_glyph_info_t *info,
hb_glyph_position_t *positions,
unsigned int num_glyphs,
pixel *canvas,
unsigned int cell_width,
unsigned int cell_height,
unsigned int num_cells,
unsigned int baseline,
bool *was_colored,
FONTS_DATA_HANDLE,
GlyphRenderInfo *);
PyObject *create_fallback_face(PyObject *base_face, const ListOfChars *lc, bool bold, bool italic, bool emoji_presentation, FONTS_DATA_HANDLE fg);
PyObject *specialize_font_descriptor(PyObject *base_descriptor, double, double, double);
PyObject *face_from_path(const char *path, int index, FONTS_DATA_HANDLE);
PyObject *face_from_descriptor(PyObject *, FONTS_DATA_HANDLE);
PyObject *iter_fallback_faces(FONTS_DATA_HANDLE fgh, ssize_t *idx);
bool face_equals_descriptor(PyObject *face_, PyObject *descriptor);
const char *postscript_name_for_face(const PyObject *);
void sprite_tracker_current_layout(FONTS_DATA_HANDLE data, unsigned int *x, unsigned int *y, unsigned int *z);
void render_alpha_mask(
const uint8_t *alpha_mask, pixel *dest, const Region *src_rect, const Region *dest_rect, size_t src_stride, size_t dest_stride, pixel color_rgb);
void render_line(FONTS_DATA_HANDLE, Line *line, index_type lnum, Cursor *cursor, DisableLigature, ListOfChars *);
void sprite_tracker_set_limits(size_t max_texture_size, size_t max_array_len);
typedef void (*free_extra_data_func)(void *);
StringCanvas render_simple_text_impl(PyObject *s, const char *text, unsigned int baseline);
StringCanvas render_simple_text(FONTS_DATA_HANDLE fg_, const char *text);
bool face_apply_scaling(PyObject *face, const FONTS_DATA_HANDLE fg);
// Lines whose thickness is specified in pts (box drawing, cursors, etc.) are
// scaled by this factor so that they scale along with the text when the font
// size is changed from the configured font size.
static inline double
line_thickness_scale_for_font_size(const FONTS_DATA_HANDLE fg) {
return OPT(font_size) > 0 && fg->font_sz_in_pts > 0 ? fg->font_sz_in_pts / OPT(font_size) : 1.0;
}
bool add_font_name_record(
PyObject *table, uint16_t platform_id, uint16_t encoding_id, uint16_t language_id, uint16_t name_id, const char *string, uint16_t string_len);
PyObject *get_best_name_from_name_table(PyObject *table, PyObject *name_id);
PyObject *read_name_font_table(const uint8_t *table, size_t table_len);
bool read_fvar_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output);
bool read_STAT_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output);
bool read_features_from_font_table(const uint8_t *table, size_t table_len, PyObject *name_lookup_table, PyObject *output);
FontFeatures *features_for_face(PyObject *);
bool create_features_for_face(const char *psname, PyObject *features, FontFeatures *output);
PyObject *font_features_as_dict(const FontFeatures *font_features);
bool has_cell_text(bool (*has_codepoint)(const void *, char_type ch), const void *face, bool do_debug, const ListOfChars *lc);
static inline void
right_shift_canvas(pixel *canvas, size_t width, size_t height, size_t amt) {
pixel *src;
size_t r;
for (r = 0, src = canvas; r < height; r++, src += width) {
memmove(src + amt, src, sizeof(pixel) * (width - amt));
zero_at_ptr_count(src, amt);
}
}
+242
View File
@@ -0,0 +1,242 @@
from collections.abc import Sequence
from enum import Enum, IntEnum, auto
from typing import TYPE_CHECKING, Literal, NamedTuple, TypedDict, Union
from kitty.fast_data_types import ParsedFontFeature
from kitty.types import run_once
from kitty.typing_compat import CoreTextFont, FontConfigPattern
from kitty.utils import shlex_split
if TYPE_CHECKING:
import re
class ListedFont(TypedDict):
family: str
style: str
full_name: str
postscript_name: str
is_monospace: bool
is_variable: bool
descriptor: FontConfigPattern | CoreTextFont
class VariableAxis(TypedDict):
minimum: float
maximum: float
default: float
hidden: bool
tag: str
strid: str # Can be empty string when not present
class NamedStyle(TypedDict):
axis_values: dict[str, float]
name: str
psname: str # can be empty string when not present
class DesignValue1(TypedDict):
format: Literal[1]
flags: int
name: str
value: float
class DesignValue2(TypedDict):
format: Literal[2]
flags: int
name: str
value: float
minimum: float
maximum: float
class DesignValue3(TypedDict):
format: Literal[3]
flags: int
name: str
value: float
linked_value: float
DesignValue = Union[DesignValue1, DesignValue2, DesignValue3]
class DesignAxis(TypedDict):
name: str
ordering: int
tag: str
values: list[DesignValue]
class AxisValue(TypedDict):
design_index: int
value: float
class MultiAxisStyle(TypedDict):
flags: int
name: str
values: tuple[AxisValue, ...]
class VariableData(TypedDict):
axes: tuple[VariableAxis, ...]
named_styles: tuple[NamedStyle, ...]
variations_postscript_name_prefix: str
elided_fallback_name: str
design_axes: tuple[DesignAxis, ...]
multi_axis_styles: tuple[MultiAxisStyle, ...]
class ModificationType(Enum):
underline_position = auto()
underline_thickness = auto()
strikethrough_position = auto()
strikethrough_thickness = auto()
cell_width = auto()
cell_height = auto()
baseline = auto()
size = auto()
class ModificationUnit(IntEnum):
pt = 0
percent = 1
pixel = 2
class ModificationValue(NamedTuple):
val: float
unit: ModificationUnit
def __repr__(self) -> str:
u = '%' if self.unit is ModificationUnit.percent else ''
return f'{self.val:g}{u}'
class FontModification(NamedTuple):
mod_type: ModificationType
mod_value: ModificationValue
font_name: str = ''
def __repr__(self) -> str:
fn = f' {self.font_name}' if self.font_name else ''
return f'{self.mod_type.name}{fn} {self.mod_value}'
class FontSpec(NamedTuple):
family: str | None = None
style: str | None = None
postscript_name: str | None = None
full_name: str | None = None
system: str | None = None
axes: tuple[tuple[str, float], ...] = ()
variable_name: str | None = None
features: tuple[ParsedFontFeature, ...] = ()
created_from_string: str = ''
@classmethod
def from_setting(cls, spec: str) -> 'FontSpec':
if spec == 'auto':
return FontSpec(system='auto', created_from_string=spec)
items = tuple(shlex_split(spec))
if '=' not in items[0]:
return FontSpec(system=spec, created_from_string=spec)
axes = {}
defined = {}
features: tuple[ParsedFontFeature, ...] = ()
for item in items:
k, sep, v = item.partition('=')
if sep != '=':
raise ValueError(f'The font specification: {spec} is not valid as {item} does not contain an =')
if k in ('family', 'style', 'full_name', 'postscript_name', 'variable_name'):
defined[k] = v
elif k == 'features':
features += tuple(ParsedFontFeature(x) for x in v.split())
else:
try:
axes[k] = float(v)
except Exception:
raise ValueError(f'The font specification: {spec} is not valid as {v} is not a number')
return FontSpec(axes=tuple(axes.items()), created_from_string=spec, features=features, **defined)
@property
def is_system(self) -> bool:
return bool(self.system)
@property
def is_auto(self) -> bool:
return self.system == 'auto'
@property
def as_setting(self) -> str:
if self.created_from_string:
return self.created_from_string
if self.system:
return self.system
ans = []
from shlex import quote
def a(key: str, val: str) -> None:
ans.append(f'{key}={quote(val)}')
if self.family is not None:
a('family', self.family)
if self.postscript_name is not None:
a('postscript_name', self.postscript_name)
if self.full_name is not None:
a('full_name', self.full_name)
if self.variable_name is not None:
a('variable_name', self.variable_name)
if self.style is not None:
a('style', self.style)
if self.features:
a('features', ' '.join(str(f) for f in self.features))
if self.axes:
for key, val in self.axes:
a(key, f'{val:g}')
return ' '.join(ans)
def __str__(self) -> str:
return self.as_setting
# Cannot change __repr__ as it will break config generation
Descriptor = Union[FontConfigPattern, CoreTextFont]
class Score(NamedTuple):
variable_score: int
style_score: float
monospace_score: int
width_score: int
class Scorer[T]:
def __init__(self, bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> None:
self.bold = bold
self.italic = italic
self.monospaced = monospaced
self.prefer_variable = prefer_variable
def sorted_candidates(self, candidates: Sequence[T], dump: bool = False) -> list[T]:
raise NotImplementedError()
def __repr__(self) -> str:
return f'{self.__class__.__name__}(bold={self.bold}, italic={self.italic}, monospaced={self.monospaced}, prefer_variable={self.prefer_variable})'
__str__ = __repr__
@run_once
def fnname_pat() -> 're.Pattern[str]':
import re
return re.compile(r'\s+')
def family_name_to_key(family: str) -> str:
return fnname_pat().sub(' ', family).strip().lower()
+579
View File
@@ -0,0 +1,579 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import copy
from typing import TYPE_CHECKING, Any, Literal, TypedDict, Union, cast
from kitty.constants import is_macos
from kitty.fast_data_types import ParsedFontFeature
from kitty.fonts import Descriptor, DesignAxis, FontSpec, NamedStyle, Scorer, VariableAxis, VariableData, family_name_to_key
from kitty.options.types import Options
if TYPE_CHECKING:
from kitty.fast_data_types import CoreTextFont, CTFace, FontConfigPattern
from kitty.fast_data_types import Face as FT_Face
FontCollectionMapType = Literal['family_map', 'ps_map', 'full_map', 'variable_map']
FontMap = dict[FontCollectionMapType, dict[str, list[Descriptor]]]
Face = Union[FT_Face, CTFace]
def all_fonts_map(monospaced: bool) -> FontMap: ...
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer: ...
def find_best_match(
family: str,
bold: bool = False,
italic: bool = False,
monospaced: bool = True,
ignore_face: Descriptor | None = None,
prefer_variable: bool = False,
) -> Descriptor: ...
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> Descriptor: ...
def face_from_descriptor(descriptor: Descriptor, font_sz_in_pts: float | None = None, dpi_x: float | None = None, dpi_y: float | None = None) -> Face: ...
def is_monospace(descriptor: Descriptor) -> bool: ...
def is_variable(descriptor: Descriptor) -> bool: ...
def set_named_style(name: str, font: Descriptor, vd: VariableData) -> bool: ...
def set_axis_values(tag_map: dict[str, float], font: Descriptor, vd: VariableData) -> bool: ...
def get_axis_values(font: Descriptor, vd: VariableData) -> dict[str, float]: ...
else:
FontCollectionMapType = FontMap = None
from kitty.fast_data_types import specialize_font_descriptor
if is_macos:
from kitty.fast_data_types import CTFace as Face
from kitty.fonts.core_text import (
all_fonts_map,
create_scorer,
find_best_match,
find_last_resort_text_font,
get_axis_values,
is_monospace,
is_variable,
set_axis_values,
set_named_style,
)
else:
from kitty.fast_data_types import Face
from kitty.fonts.fontconfig import (
all_fonts_map,
create_scorer,
find_best_match,
find_last_resort_text_font,
get_axis_values,
is_monospace,
is_variable,
set_axis_values,
set_named_style,
)
def face_from_descriptor(descriptor: Descriptor, font_sz_in_pts: float | None = None, dpi_x: float | None = None, dpi_y: float | None = None) -> Face:
if font_sz_in_pts is not None:
descriptor = specialize_font_descriptor(descriptor, font_sz_in_pts, dpi_x, dpi_y)
return Face(descriptor=descriptor)
cache_for_variable_data_by_path: dict[str, VariableData] = {}
def clear_caches() -> None:
cache_for_variable_data_by_path.clear()
actually_variable_cache.clear()
attr_map = {(False, False): 'font_family', (True, False): 'bold_font', (False, True): 'italic_font', (True, True): 'bold_italic_font'}
class Event:
is_set: bool = False
class FamilyAxisValues:
regular_weight: float | None = None
regular_slant: float | None = None
regular_ital: float | None = None
regular_width: float | None = None
bold_weight: float | None = None
italic_slant: float | None = None
italic_ital: float | None = None
def get_wght(self, bold: bool, italic: bool) -> float | None:
return self.bold_weight if bold else self.regular_weight
def get_ital(self, bold: bool, italic: bool) -> float | None:
return self.italic_ital if italic else self.regular_ital
def get_slnt(self, bold: bool, italic: bool) -> float | None:
return self.italic_slant if italic else self.regular_slant
def get_wdth(self, bold: bool, italic: bool) -> float | None:
return self.regular_width
def get(self, tag: str, bold: bool, italic: bool) -> float | None:
f = getattr(self, f'get_{tag}', None)
return None if f is None else f(bold, italic)
def set_regular_values(self, axis_values: dict[str, float]) -> None:
self.regular_weight = axis_values.get('wght')
self.regular_width = axis_values.get('wdth')
self.regular_ital = axis_values.get('ital')
self.regular_slant = axis_values.get('slnt')
def set_bold_values(self, axis_values: dict[str, float]) -> None:
self.bold_weight = axis_values.get('wght')
def set_italic_values(self, axis_values: dict[str, float]) -> None:
self.italic_ital = axis_values.get('ital')
self.italic_slant = axis_values.get('slnt')
def get_variable_data_for_descriptor(d: Descriptor) -> VariableData:
if not d['path']:
return face_from_descriptor(d).get_variable_data()
ans = cache_for_variable_data_by_path.get(d['path'])
if ans is None:
ans = cache_for_variable_data_by_path[d['path']] = face_from_descriptor(d).get_variable_data()
return ans
def get_variable_data_for_face(d: Face) -> VariableData:
path = d.path
if not path:
return d.get_variable_data()
ans = cache_for_variable_data_by_path.get(path)
if ans is None:
ans = cache_for_variable_data_by_path[path] = d.get_variable_data()
return ans
def find_best_match_in_candidates[T](candidates: list[T], scorer: Scorer[T], is_medium_face: bool, ignore_face: T | None = None) -> T | None:
if candidates:
for x in scorer.sorted_candidates(candidates):
if ignore_face is None or x != ignore_face:
return x
return None
def pprint(*a: Any, **kw: Any) -> None:
from pprint import pprint
pprint(*a, **kw)
def find_medium_variant[T: (CoreTextFont | FontConfigPattern)](font: T) -> T:
font = copy.copy(font)
vd = get_variable_data_for_descriptor(font)
for i, ns in enumerate(vd['named_styles']):
if ns['name'] == 'Regular':
set_named_style(ns['psname'] or ns['name'], font, vd)
return font
axis_values = {}
for i, ax in enumerate(vd['axes']):
tag = ax['tag']
for dax in vd['design_axes']:
if dax['tag'] == tag:
for x in dax['values']:
if x['format'] in (1, 2):
if x['name'] == 'Regular':
axis_values[tag] = x['value']
break
if axis_values:
set_axis_values(axis_values, font, vd)
return font
def get_bold_design_weight(dax: DesignAxis, ax: VariableAxis, regular_weight: float) -> float:
ans = regular_weight
candidates = []
for x in dax['values']:
if x['format'] in (1, 2):
if x['value'] > regular_weight:
candidates.append(x['value'])
if candidates:
ans = min(candidates)
return ans
def get_design_value_for(dax: DesignAxis, ax: VariableAxis, bold: bool, italic: bool, family_axis_values: FamilyAxisValues) -> float:
family_val = family_axis_values.get(ax['tag'], bold, italic)
if family_val is not None and ax['minimum'] <= family_val <= ax['maximum']:
return family_val
default = ax['default']
if dax['tag'] == 'wght':
keys = ('semibold', 'bold', 'heavy', 'black') if bold else ('regular', 'medium')
elif dax['tag'] in ('ital', 'slnt'):
keys = ('italic', 'oblique', 'slanted', 'slant') if italic else ('regular', 'normal', 'medium', 'upright')
else:
return default
priorities = {}
for x in dax['values']:
if x['format'] in (1, 2):
q = x['name'].lower()
try:
idx = keys.index(q)
except ValueError:
continue
priorities[x['value']] = idx
ans = default
if priorities:
ans = sorted(priorities, key=priorities.__getitem__)[0]
if bold and ax['tag'] == 'wght' and family_axis_values.regular_weight is not None and ans <= family_axis_values.regular_weight:
ans = get_bold_design_weight(dax, ax, family_axis_values.regular_weight)
return ans
def find_bold_italic_variant(medium: Descriptor, bold: bool, italic: bool, family_axis_values: FamilyAxisValues) -> Descriptor:
# we first pick the best font file for bold/italic if there are more than
# one. For example SourceCodeVF has Italic and Upright faces with variable
# weights in each, so we rely on the OS font matcher to give us the best
# font file.
monospaced = is_monospace(medium)
unsorted = all_fonts_map(monospaced)['variable_map'][family_name_to_key(medium['family'])]
fonts = create_scorer(bold, italic, monospaced).sorted_candidates(unsorted)
vd = get_variable_data_for_descriptor(fonts[0])
ans = fonts[0].copy()
# now we need to specialise all axes in ans
axis_values = {}
dax_map = {dax['tag']: dax for dax in vd['design_axes']}
for ax in vd['axes']:
tag = ax['tag']
dax = dax_map.get(tag)
if dax is not None:
axis_values[tag] = get_design_value_for(dax, ax, bold, italic, family_axis_values)
if axis_values:
set_axis_values(axis_values, ans, vd)
return ans
def find_best_variable_face(spec: FontSpec, bold: bool, italic: bool, monospaced: bool, candidates: list[Descriptor]) -> Descriptor:
if spec.variable_name is not None:
q = spec.variable_name.lower()
for font in candidates:
vd = get_variable_data_for_descriptor(font)
if vd['variations_postscript_name_prefix'].lower() == q:
return font
if spec.style:
q = spec.style.lower()
for font in candidates:
vd = get_variable_data_for_descriptor(font)
for x in vd['named_styles']:
if x['psname'].lower() == q:
return font
for x in vd['named_styles']:
if x['name'].lower() == q:
return font
return create_scorer(bold, italic, monospaced).sorted_candidates(candidates)[0]
def get_fine_grained_font(
spec: FontSpec,
bold: bool = False,
italic: bool = False,
family_axis_values: FamilyAxisValues = FamilyAxisValues(),
resolved_medium_font: Descriptor | None = None,
monospaced: bool = True,
match_is_more_specific_than_family: Event = Event(),
) -> Descriptor:
font_map = all_fonts_map(monospaced)
is_medium_face = resolved_medium_font is None
scorer = create_scorer(bold, italic, monospaced)
if spec.postscript_name:
q = find_best_match_in_candidates(font_map['ps_map'].get(family_name_to_key(spec.postscript_name), []), scorer, is_medium_face)
if q:
match_is_more_specific_than_family.is_set = True
return q
if spec.full_name:
q = find_best_match_in_candidates(font_map['full_map'].get(family_name_to_key(spec.full_name), []), scorer, is_medium_face)
if q:
match_is_more_specific_than_family.is_set = True
return q
if spec.family:
key = family_name_to_key(spec.family)
# First look for a variable font
candidates = font_map['variable_map'].get(key, [])
if candidates:
q = candidates[0] if len(candidates) == 1 else find_best_variable_face(spec, bold, italic, monospaced, candidates)
q, applied = apply_variation_to_pattern(q, spec)
if applied:
match_is_more_specific_than_family.is_set = True
return q
return find_medium_variant(q) if resolved_medium_font is None else find_bold_italic_variant(resolved_medium_font, bold, italic, family_axis_values)
# Now look for any font
candidates = font_map['family_map'].get(key, [])
if candidates:
if spec.style:
qs = spec.style.lower()
candidates = [x for x in candidates if x['style'].lower() == qs]
q = find_best_match_in_candidates(candidates, scorer, is_medium_face)
if q:
return q
return find_last_resort_text_font(bold, italic, monospaced)
def apply_variation_to_pattern(pat: Descriptor, spec: FontSpec) -> tuple[Descriptor, bool]:
vd = face_from_descriptor(pat).get_variable_data()
pat = pat.copy()
if spec.style:
if set_named_style(spec.style, pat, vd):
return pat, True
tag_map, name_map = {}, {}
for i, ax in enumerate(vd['axes']):
tag_map[ax['tag']] = i
if ax['strid']:
name_map[ax['strid'].lower()] = ax['tag']
axis_values = {}
for axspec in spec.axes:
qname = axspec[0]
if qname in tag_map:
axis_values[qname] = axspec[1]
continue
tag = name_map.get(qname.lower())
if tag:
axis_values[tag] = axspec[1]
return pat, set_axis_values(axis_values, pat, vd)
def get_font_from_spec(
spec: FontSpec,
bold: bool = False,
italic: bool = False,
family_axis_values: FamilyAxisValues = FamilyAxisValues(),
resolved_medium_font: Descriptor | None = None,
match_is_more_specific_than_family: Event = Event(),
) -> Descriptor:
if not spec.is_system:
ans = get_fine_grained_font(
spec,
bold,
italic,
resolved_medium_font=resolved_medium_font,
family_axis_values=family_axis_values,
match_is_more_specific_than_family=match_is_more_specific_than_family,
)
if spec.features:
ans = ans.copy()
ans['features'] = spec.features
return ans
family = spec.system or ''
if family == 'auto':
if bold or italic:
assert resolved_medium_font is not None
family = resolved_medium_font['family']
if is_variable(resolved_medium_font) or is_actually_variable_despite_fontconfigs_lies(resolved_medium_font):
v = find_bold_italic_variant(resolved_medium_font, bold, italic, family_axis_values=family_axis_values)
if v is not None:
return v
else:
family = 'monospace'
return find_best_match(family, bold, italic, ignore_face=resolved_medium_font)
class FontFiles(TypedDict):
medium: Descriptor
bold: Descriptor
italic: Descriptor
bi: Descriptor
actually_variable_cache: dict[str, bool] = {}
def is_actually_variable_despite_fontconfigs_lies(d: Descriptor) -> bool:
if d['descriptor_type'] != 'fontconfig':
return False
path = d['path']
ans = actually_variable_cache.get(path)
if ans is not None:
return ans
m = all_fonts_map(is_monospace(d))['variable_map']
for x in m.get(family_name_to_key(d['family']), ()):
if x['path'] == path:
actually_variable_cache[path] = True
return True
actually_variable_cache[path] = False
return False
def get_font_files(opts: Options) -> FontFiles:
ans: dict[str, Descriptor] = {}
match_is_more_specific_than_family = Event()
medium_font = get_font_from_spec(opts.font_family, match_is_more_specific_than_family=match_is_more_specific_than_family)
medium_font_is_variable = is_variable(medium_font) or is_actually_variable_despite_fontconfigs_lies(medium_font)
if not match_is_more_specific_than_family.is_set and medium_font_is_variable:
medium_font = find_medium_variant(medium_font)
family_axis_values = FamilyAxisValues()
if medium_font_is_variable:
family_axis_values.set_regular_values(get_axis_values(medium_font, get_variable_data_for_descriptor(medium_font)))
kd = {(False, False): 'medium', (True, False): 'bold', (False, True): 'italic', (True, True): 'bi'}
for (bold, italic), attr in attr_map.items():
if bold or italic:
spec: FontSpec = getattr(opts, attr)
font = get_font_from_spec(spec, bold, italic, resolved_medium_font=medium_font, family_axis_values=family_axis_values)
# Set family axis values based on the values in font
if not (bold and italic) and (is_variable(medium_font) or is_actually_variable_despite_fontconfigs_lies(medium_font)):
av = get_axis_values(font, get_variable_data_for_descriptor(font))
(family_axis_values.set_italic_values if italic else family_axis_values.set_bold_values)(av)
if spec.is_auto and not font.get('features') and medium_font.get('features'):
# Set font features based on medium face features
font = font.copy()
font['features'] = medium_font['features']
else:
font = medium_font
key = kd[(bold, italic)]
ans[key] = font
def apply_synthetic_matrix(font: Descriptor, bold: bool, italic: bool) -> Descriptor:
# fontconfig's FcFontList (used by find_best_match) omits FC_MATRIX from
# its object set, so a roman font found there carries no synthetic-italic
# shear and its "italic" renders upright. Fira Code is the case (it ships
# no italic), in both its static and variable builds. The italic intent
# exists only here at selection finalize, not at face construction, so
# recover the matrix now: for an italic slot whose chosen face is upright
# (no slant) and has no matrix yet, ask fc_match what fontconfig would do.
# fc_match returns a synthetic matrix only when there is no real italic to
# use (no italic face and no slanted named instance or variable slant
# axis); when a real italic exists it returns no matrix, so a font that is
# already italic, static or variable, is never double-slanted. Face construction applies the matrix
# via FT_Set_Transform; specialize_font_descriptor preserves it when the
# descriptor is sized for rendering. Only the matrix is taken, so
# selection is unchanged. Covers the four configured faces; fc_match
# re-matches by family name (see commit message).
if italic and font['descriptor_type'] == 'fontconfig' and not font.get('matrix') and not font.get('slant'):
from kitty.fast_data_types import FC_MONO
from kitty.fonts.fontconfig import fc_match
mtx = fc_match(font['family'], bold, italic, FC_MONO if is_monospace(font) else -1).get('matrix')
if mtx:
new_font = font.copy()
new_font['matrix'] = mtx
return new_font
return font
return {
'medium': ans['medium'],
'bold': ans['bold'],
'italic': apply_synthetic_matrix(ans['italic'], False, True),
'bi': apply_synthetic_matrix(ans['bi'], True, True),
}
def axis_values_are_equal(defaults: dict[str, float], a: dict[str, float], b: dict[str, float]) -> bool:
ad, bd = defaults.copy(), defaults.copy()
ad.update(a)
bd.update(b)
return ad == bd
def _get_named_style(axis_map: dict[str, float], vd: VariableData) -> NamedStyle | None:
defaults = {ax['tag']: ax['default'] for ax in vd['axes']}
for ns in vd['named_styles']:
if axis_values_are_equal(defaults, ns['axis_values'], axis_map):
return ns
return None
def get_named_style(face_or_descriptor: Face | Descriptor) -> NamedStyle | None:
if isinstance(face_or_descriptor, dict):
d = cast(Descriptor, face_or_descriptor)
vd = get_variable_data_for_descriptor(d)
if d['descriptor_type'] == 'fontconfig':
ns = d.get('named_style', -1)
if ns > -1 and ns < len(vd['named_styles']):
return vd['named_styles'][ns]
axis_map = {}
axes = vd['axes']
for i, val in enumerate(d.get('axes', ())):
if i < len(axes):
axis_map[axes[i]['tag']] = val
else:
axis_map = d.get('axis_map', {}).copy()
else:
face = cast(Face, face_or_descriptor)
vd = get_variable_data_for_face(face)
q = face.get_variation()
if q is None:
return None
axis_map = q
return _get_named_style(axis_map, vd)
def get_axis_map(face_or_descriptor: Face | Descriptor) -> dict[str, float]:
base_axis_map = {}
axis_map: dict[str, float] = {}
if isinstance(face_or_descriptor, dict):
d = cast(Descriptor, face_or_descriptor)
vd = get_variable_data_for_descriptor(d)
if d['descriptor_type'] == 'fontconfig':
ns = d.get('named_style', -1)
if ns > -1 and ns < len(vd['named_styles']):
base_axis_map = vd['named_styles'][ns]['axis_values'].copy()
axis_map = {}
axes = vd['axes']
for i, val in enumerate(d.get('axes', ())):
if i < len(axes):
axis_map[axes[i]['tag']] = val
else:
axis_map = d.get('axis_map', {}).copy()
else:
face = cast(Face, face_or_descriptor)
q = face.get_variation()
if q is not None:
axis_map = q
base_axis_map.update(axis_map)
return base_axis_map
def spec_for_face(family: str, face: Face) -> FontSpec:
v = face.get_variation()
features = tuple(map(ParsedFontFeature, face.applied_features().values()))
if v is None:
return FontSpec(family=family, postscript_name=face.postscript_name(), features=features)
vd = face.get_variable_data()
varname = vd['variations_postscript_name_prefix']
ns = get_named_style(face)
if ns is None:
axes = []
for key, val in get_axis_map(face).items():
axes.append((key, val))
return FontSpec(family=family, variable_name=varname, axes=tuple(axes), features=features)
return FontSpec(family=family, variable_name=varname, style=ns['psname'] or ns['name'], features=features)
def develop(family: str = '') -> None:
import sys
family = family or sys.argv[-1]
from kitty.options.utils import parse_font_spec
opts = Options()
opts.font_family = parse_font_spec(family)
ff = get_font_files(opts)
def s(name: str, d: Descriptor) -> None:
f = face_from_descriptor(d)
print(name, str(f))
features = f.get_features()
print(' Features :', features)
s('Medium :', ff['medium'])
print()
s('Bold :', ff['bold'])
print()
s('Italic :', ff['italic'])
print()
s('Bold-Italic:', ff['bi'])
def list_fonts(monospaced: bool = True) -> dict[str, list[dict[str, str]]]:
ans: dict[str, list[dict[str, str]]] = {}
for key, descriptors in all_fonts_map(monospaced)['family_map'].items():
entries = ans.setdefault(key, [])
for d in descriptors:
entries.append({'family': d['family'], 'psname': d['postscript_name'], 'path': d['path'], 'style': d['style']})
return ans
if __name__ == '__main__':
develop()
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import itertools
import operator
from collections import defaultdict
from collections.abc import Generator, Iterable, Sequence
from functools import lru_cache
from typing import NamedTuple
from kitty.fast_data_types import CTFace, coretext_all_fonts
from kitty.typing_compat import CoreTextFont
from kitty.utils import log_error
from . import Descriptor, ListedFont, Score, Scorer, VariableData, family_name_to_key
attr_map = {(False, False): 'font_family', (True, False): 'bold_font', (False, True): 'italic_font', (True, True): 'bold_italic_font'}
FontMap = dict[str, dict[str, list[CoreTextFont]]]
def create_font_map(all_fonts: Iterable[CoreTextFont]) -> FontMap:
ans: FontMap = {'family_map': {}, 'ps_map': {}, 'full_map': {}, 'variable_map': {}}
vmap: dict[str, list[CoreTextFont]] = defaultdict(list)
for x in all_fonts:
f = family_name_to_key(x['family'])
s = family_name_to_key(x['style'])
ps = family_name_to_key(x['postscript_name'])
ans['family_map'].setdefault(f, []).append(x)
ans['ps_map'].setdefault(ps, []).append(x)
ans['full_map'].setdefault(f'{f} {s}', []).append(x)
if x['variation'] is not None:
vmap[f].append(x)
# CoreText makes a separate descriptor for each named style in each
# variable font file. Keep only the default style descriptor, which has an
# empty variation dictionary. If no default exists, pick the one with the
# smallest variation dictionary size.
keyfunc = operator.itemgetter('path')
for k, v in vmap.items():
v.sort(key=keyfunc)
uniq_per_path = []
for _, g in itertools.groupby(v, keyfunc):
uniq_per_path.append(sorted(g, key=lambda x: len(x['variation'] or ()))[0])
ans['variable_map'][k] = uniq_per_path
return ans
def clear_caches() -> None:
all_fonts_map.cache_clear()
weight_range_for_family.cache_clear()
@lru_cache(maxsize=2)
def all_fonts_map(monospaced: bool = True) -> FontMap:
return create_font_map(coretext_all_fonts(monospaced))
def is_monospace(descriptor: CoreTextFont) -> bool:
return descriptor['monospace']
def is_variable(descriptor: CoreTextFont) -> bool:
return descriptor['variation'] is not None
def list_fonts() -> Generator[ListedFont, None, None]:
for fd in coretext_all_fonts(False):
f = fd['family']
if f:
fn = fd['display_name']
if not fn:
fn = f'{f} {fd["style"]}'.strip()
yield {
'family': f,
'full_name': fn,
'postscript_name': fd['postscript_name'] or '',
'is_monospace': fd['monospace'],
'is_variable': is_variable(fd),
'descriptor': fd,
'style': fd['style'],
}
class WeightRange(NamedTuple):
minimum: float = 99999
maximum: float = -99999
medium: float = -99999
bold: float = -99999
@property
def is_valid(self) -> bool:
return self.minimum != wr.minimum and self.maximum != wr.maximum and self.medium != wr.medium and self.bold != wr.bold
wr = WeightRange()
@lru_cache
def weight_range_for_family(family: str) -> WeightRange:
faces = all_fonts_map(True)['family_map'].get(family_name_to_key(family), ())
mini, maxi, medium, bold = wr.minimum, wr.maximum, wr.medium, wr.bold
for face in faces:
w = face['weight']
mini, maxi = min(w, mini), max(w, maxi)
s = face['style'].lower()
if not s:
continue
s = s.split()[0]
if s == 'semibold':
bold = w
elif s == 'bold' and bold == wr.bold:
bold = w
elif s == 'regular':
medium = w
elif s == 'medium' and medium == wr.medium:
medium = w
return WeightRange(mini, maxi, medium, bold)
class CTScorer(Scorer[CoreTextFont]):
weight_range: WeightRange | None = None
def score(self, candidate: Descriptor) -> Score:
assert candidate['descriptor_type'] == 'core_text'
variable_score = 0 if self.prefer_variable and candidate['variation'] is not None else 1
bold_score = candidate['weight'] # -1 to 1 with 0 being normal
if self.weight_range is None:
if bold_score < 0: # thinner than normal, reject
bold_score = 2.0
else:
if self.bold:
# prefer semibold=0.3 to full bold = 0.4
bold_score = abs(bold_score - 0.3)
else:
anchor = self.weight_range.bold if self.bold else self.weight_range.medium
bold_score = abs(bold_score - anchor)
italic_score = candidate['slant'] # -1 to 1 with 0 being upright < 0 being backward slant, abs(slant) == 1 implies 30 deg rotation
if self.italic:
if italic_score < 0:
italic_score = 2.0
else:
italic_score = abs(1 - italic_score)
monospace_match = 0 if candidate['monospace'] else 1
is_regular_width = not candidate['expanded'] and not candidate['condensed']
return Score(variable_score, bold_score + italic_score, monospace_match, 0 if is_regular_width else 1)
def sorted_candidates(self, candidates: Sequence[CoreTextFont], dump: bool = False) -> list[CoreTextFont]:
self.weight_range = None
families = {x['family'] for x in candidates}
if len(families) == 1:
wr = weight_range_for_family(next(iter(families)))
if wr.is_valid and wr.medium < 0: # Operator Mono is an example of this craziness
self.weight_range = wr
candidates = sorted(candidates, key=self.score)
if dump:
print(self)
if self.weight_range:
print(self.weight_range)
for x in candidates:
assert x['descriptor_type'] == 'core_text'
print(
CTFace(descriptor=x).postscript_name(), f'bold={x["bold"]}', f'italic={x["italic"]}', f'weight={x["weight"]:.2f}', f'slant={x["slant"]:.2f}'
)
print(' ', self.score(x))
print()
return candidates
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer:
return CTScorer(bold, italic, monospaced, prefer_variable)
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> CoreTextFont:
font_map = all_fonts_map(monospaced)
candidates = font_map['family_map']['menlo']
return create_scorer(bold, italic, monospaced).sorted_candidates(candidates)[0]
def find_best_match(
family: str, bold: bool = False, italic: bool = False, monospaced: bool = True, ignore_face: CoreTextFont | None = None, prefer_variable: bool = False
) -> CoreTextFont:
q = family_name_to_key(family)
font_map = all_fonts_map(monospaced)
scorer = create_scorer(bold, italic, monospaced, prefer_variable=prefer_variable)
# First look for an exact match
for selector in ('ps_map', 'full_map'):
candidates = font_map[selector].get(q)
if candidates:
candidates = scorer.sorted_candidates(candidates)
possible = candidates[0]
if possible != ignore_face:
return possible
# See if we have a variable font
if not bold and not italic and font_map['variable_map'].get(q):
candidates = font_map['variable_map'][q]
candidates = scorer.sorted_candidates(candidates)
possible = candidates[0]
if possible != ignore_face:
from .common import find_medium_variant
return find_medium_variant(possible)
# Let CoreText choose the font if the family exists, otherwise
# fallback to Menlo
if q not in font_map['family_map']:
if family.lower() not in ('monospace', 'symbols nerd font mono'):
log_error(f'The font {family} was not found, falling back to Menlo')
q = 'menlo'
candidates = scorer.sorted_candidates(font_map['family_map'][q])
return candidates[0]
def font_for_family(family: str) -> tuple[CoreTextFont, bool, bool]:
ans = find_best_match(family, monospaced=False)
return ans, ans['bold'], ans['italic']
def descriptor(f: ListedFont) -> CoreTextFont:
d = f['descriptor']
assert d['descriptor_type'] == 'core_text'
return d
def prune_family_group(g: list[ListedFont]) -> list[ListedFont]:
# CoreText returns a separate font for every style in the variable font, so
# merge them.
variable_paths = {descriptor(f)['path']: False for f in g if f['is_variable']}
if not variable_paths:
return g
def is_ok(d: CoreTextFont) -> bool:
if d['path'] not in variable_paths:
return True
if not variable_paths[d['path']]:
variable_paths[d['path']] = True
return True
return False
return [x for x in g if is_ok(descriptor(x))]
def set_axis_values(tag_map: dict[str, float], font: CoreTextFont, vd: VariableData) -> bool:
known_axes = {ax['tag'] for ax in vd['axes']}
previous = font.get('axis_map', {})
new = previous.copy()
for tag in known_axes:
val = tag_map.get(tag)
if val is not None:
new[tag] = val
font['axis_map'] = new
return new != previous
def set_named_style(name: str, font: CoreTextFont, vd: VariableData) -> bool:
q = name.lower()
for i, ns in enumerate(vd['named_styles']):
if ns['psname'].lower() == q:
return set_axis_values(ns['axis_values'], font, vd)
for i, ns in enumerate(vd['named_styles']):
if ns['name'].lower() == q:
return set_axis_values(ns['axis_values'], font, vd)
if vd['elided_fallback_name']:
for i, ns in enumerate(vd['named_styles']):
eq = ' '.join(ns['name'].replace(vd['elided_fallback_name'], '').strip().split()).lower()
if q == eq:
return set_axis_values(ns['axis_values'], font, vd)
return False
def get_axis_values(font: CoreTextFont, vd: VariableData) -> dict[str, float]:
return font.get('axis_map', {})
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntEnum
from typing import NamedTuple
class Type(IntEnum):
boolean = 1
index = 2
hidden = 3
class FeatureDefinition(NamedTuple):
name: str
type: Type
# From: https://learn.microsoft.com/en-ca/typography/opentype/spec/featurelist
known_features: dict[str, FeatureDefinition] = { # {{{
'aalt': FeatureDefinition('Access All Alternates', Type.index),
'abvf': FeatureDefinition('Above-base Forms', Type.hidden),
'abvm': FeatureDefinition('Above-base Mark Positioning', Type.hidden),
'abvs': FeatureDefinition('Above-base Substitutions', Type.hidden),
'afrc': FeatureDefinition('Alternative Fractions', Type.boolean),
'akhn': FeatureDefinition('Akhand', Type.hidden),
'blwf': FeatureDefinition('Below-base Forms', Type.hidden),
'blwm': FeatureDefinition('Below-base Mark Positioning', Type.hidden),
'blws': FeatureDefinition('Below-base Substitutions', Type.hidden),
'calt': FeatureDefinition('Contextual Alternates', Type.boolean),
'case': FeatureDefinition('Case-Sensitive Forms', Type.hidden),
'ccmp': FeatureDefinition('Glyph Composition / Decomposition', Type.hidden),
'cfar': FeatureDefinition('Conjunct Form After Ro', Type.hidden),
'chws': FeatureDefinition('Contextual Half-width Spacing', Type.boolean),
'cjct': FeatureDefinition('Conjunct Forms', Type.hidden),
'clig': FeatureDefinition('Contextual Ligatures', Type.boolean),
'cpct': FeatureDefinition('Centered CJK Punctuation', Type.boolean),
'cpsp': FeatureDefinition('Capital Spacing', Type.boolean),
'cswh': FeatureDefinition('Contextual Swash', Type.boolean),
'curs': FeatureDefinition('Cursive Positioning', Type.hidden),
'c2pc': FeatureDefinition('Petite Capitals From Capitals', Type.boolean),
'c2sc': FeatureDefinition('Small Capitals From Capitals', Type.boolean),
'dist': FeatureDefinition('Distances', Type.hidden),
'dlig': FeatureDefinition('Discretionary Ligatures', Type.boolean),
'dnom': FeatureDefinition('Denominators', Type.hidden),
'dtls': FeatureDefinition('Dotless Forms', Type.hidden),
'expt': FeatureDefinition('Expert Forms', Type.boolean),
'falt': FeatureDefinition('Final Glyph on Line Alternates', Type.boolean),
'fin2': FeatureDefinition('Terminal Forms #2', Type.hidden),
'fin3': FeatureDefinition('Terminal Forms #3', Type.hidden),
'fina': FeatureDefinition('Terminal Forms', Type.hidden),
'flac': FeatureDefinition('Flattened accent forms', Type.hidden),
'frac': FeatureDefinition('Fractions', Type.boolean),
'fwid': FeatureDefinition('Full Widths', Type.boolean),
'half': FeatureDefinition('Half Forms', Type.hidden),
'haln': FeatureDefinition('Halant Forms', Type.hidden),
'halt': FeatureDefinition('Alternate Half Widths', Type.boolean),
'hist': FeatureDefinition('Historical Forms', Type.boolean),
'hkna': FeatureDefinition('Horizontal Kana Alternates', Type.boolean),
'hlig': FeatureDefinition('Historical Ligatures', Type.boolean),
'hngl': FeatureDefinition('Hangul', Type.boolean),
'hojo': FeatureDefinition('Hojo Kanji Forms (JIS X 0212-1990 Kanji Forms)', Type.boolean),
'hwid': FeatureDefinition('Half Widths', Type.boolean),
'init': FeatureDefinition('Initial Forms', Type.hidden),
'isol': FeatureDefinition('Isolated Forms', Type.hidden),
'ital': FeatureDefinition('Italics', Type.boolean),
'jalt': FeatureDefinition('Justification Alternates', Type.boolean),
'jp78': FeatureDefinition('JIS78 Forms', Type.boolean),
'jp83': FeatureDefinition('JIS83 Forms', Type.boolean),
'jp90': FeatureDefinition('JIS90 Forms', Type.boolean),
'jp04': FeatureDefinition('JIS2004 Forms', Type.boolean),
'kern': FeatureDefinition('Kerning', Type.boolean),
'lfbd': FeatureDefinition('Left Bounds', Type.boolean),
'liga': FeatureDefinition('Standard Ligatures', Type.boolean),
'ljmo': FeatureDefinition('Leading Jamo Forms', Type.hidden),
'lnum': FeatureDefinition('Lining Figures', Type.boolean),
'locl': FeatureDefinition('Localized Forms', Type.hidden),
'ltra': FeatureDefinition('Left-to-right alternates', Type.hidden),
'ltrm': FeatureDefinition('Left-to-right mirrored forms', Type.hidden),
'mark': FeatureDefinition('Mark Positioning', Type.hidden),
'med2': FeatureDefinition('Medial Forms #2', Type.hidden),
'medi': FeatureDefinition('Medial Forms', Type.hidden),
'mgrk': FeatureDefinition('Mathematical Greek', Type.boolean),
'mkmk': FeatureDefinition('Mark to Mark Positioning', Type.hidden),
'mset': FeatureDefinition('Mark Positioning via Substitution', Type.hidden),
'nalt': FeatureDefinition('Alternate Annotation Forms', Type.index),
'nlck': FeatureDefinition('NLC Kanji Forms', Type.boolean),
'nukt': FeatureDefinition('Nukta Forms', Type.hidden),
'numr': FeatureDefinition('Numerators', Type.hidden),
'onum': FeatureDefinition('Oldstyle Figures', Type.boolean),
'opbd': FeatureDefinition('Optical Bounds', Type.boolean),
'ordn': FeatureDefinition('Ordinals', Type.boolean),
'ornm': FeatureDefinition('Ornaments', Type.index),
'palt': FeatureDefinition('Proportional Alternate Widths', Type.boolean),
'pcap': FeatureDefinition('Petite Capitals', Type.boolean),
'pkna': FeatureDefinition('Proportional Kana', Type.boolean),
'pnum': FeatureDefinition('Proportional Figures', Type.boolean),
'pref': FeatureDefinition('Pre-Base Forms', Type.hidden),
'pres': FeatureDefinition('Pre-base Substitutions', Type.hidden),
'pstf': FeatureDefinition('Post-base Forms', Type.hidden),
'psts': FeatureDefinition('Post-base Substitutions', Type.hidden),
'pwid': FeatureDefinition('Proportional Widths', Type.boolean),
'qwid': FeatureDefinition('Quarter Widths', Type.boolean),
'rand': FeatureDefinition('Randomize', Type.boolean),
'rclt': FeatureDefinition('Required Contextual Alternates', Type.hidden),
'rkrf': FeatureDefinition('Rakar Forms', Type.hidden),
'rlig': FeatureDefinition('Required Ligatures', Type.hidden),
'rphf': FeatureDefinition('Reph Forms', Type.hidden),
'rtbd': FeatureDefinition('Right Bounds', Type.boolean),
'rtla': FeatureDefinition('Right-to-left alternates', Type.hidden),
'rtlm': FeatureDefinition('Right-to-left mirrored forms', Type.hidden),
'ruby': FeatureDefinition('Ruby Notation Forms', Type.boolean),
'rvrn': FeatureDefinition('Required Variation Alternates', Type.hidden),
'salt': FeatureDefinition('Stylistic Alternates', Type.index),
'sinf': FeatureDefinition('Scientific Inferiors', Type.boolean),
'size': FeatureDefinition('Optical size', Type.hidden),
'smcp': FeatureDefinition('Small Capitals', Type.boolean),
'smpl': FeatureDefinition('Simplified Forms', Type.boolean),
'ssty': FeatureDefinition('Math script style alternates', Type.hidden),
'stch': FeatureDefinition('Stretching Glyph Decomposition', Type.hidden),
'subs': FeatureDefinition('Subscript', Type.boolean),
'sups': FeatureDefinition('Superscript', Type.boolean),
'swsh': FeatureDefinition('Swash', Type.index),
'titl': FeatureDefinition('Titling', Type.boolean),
'tjmo': FeatureDefinition('Trailing Jamo Forms', Type.hidden),
'tnam': FeatureDefinition('Traditional Name Forms', Type.boolean),
'tnum': FeatureDefinition('Tabular Figures', Type.boolean),
'trad': FeatureDefinition('Traditional Forms', Type.index),
'twid': FeatureDefinition('Third Widths', Type.boolean),
'unic': FeatureDefinition('Unicase', Type.boolean),
'valt': FeatureDefinition('Alternate Vertical Metrics', Type.boolean),
'vatu': FeatureDefinition('Vattu Variants', Type.hidden),
'vchw': FeatureDefinition('Vertical Contextual Half-width Spacing', Type.hidden),
'vert': FeatureDefinition('Vertical Writing', Type.boolean),
'vhal': FeatureDefinition('Alternate Vertical Half Metrics', Type.boolean),
'vjmo': FeatureDefinition('Vowel Jamo Forms', Type.hidden),
'vkna': FeatureDefinition('Vertical Kana Alternates', Type.boolean),
'vkrn': FeatureDefinition('Vertical Kerning', Type.boolean),
'vpal': FeatureDefinition('Proportional Alternate Vertical Metrics', Type.boolean),
'vrt2': FeatureDefinition('Vertical Alternates and Rotation', Type.boolean),
'vrtr': FeatureDefinition('Vertical Alternates for Rotation', Type.boolean),
'zero': FeatureDefinition('Slashed Zero', Type.boolean),
}
for i in range(1, 100):
known_features[f'cv{i:02d}'] = FeatureDefinition(f'Character Variant {i}', Type.index)
for i in range(1, 20):
known_features[f'ss{i:02d}'] = FeatureDefinition(f'Stylistic Set {i}', Type.boolean)
# }}}
+319
View File
@@ -0,0 +1,319 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import sys
from collections.abc import Generator, Sequence
from functools import lru_cache
from typing import Literal, NamedTuple, Optional, cast
from kitty.fast_data_types import (
FC_DUAL,
FC_MONO,
FC_SLANT_ITALIC,
FC_SLANT_ROMAN,
FC_WEIGHT_REGULAR,
FC_WIDTH_NORMAL,
Face,
clear_fallback_font_cache,
fc_list,
)
from kitty.fast_data_types import (
FC_WEIGHT_SEMIBOLD as FC_WEIGHT_BOLD,
)
from kitty.fast_data_types import fc_match as fc_match_impl
from kitty.typing_compat import FontConfigPattern
from . import Descriptor, ListedFont, Score, Scorer, VariableData, family_name_to_key
FontCollectionMapType = Literal['family_map', 'ps_map', 'full_map', 'variable_map']
FontMap = dict[FontCollectionMapType, dict[str, list[FontConfigPattern]]]
def create_font_map(all_fonts: tuple[FontConfigPattern, ...]) -> FontMap:
ans: FontMap = {'family_map': {}, 'ps_map': {}, 'full_map': {}, 'variable_map': {}}
for x in all_fonts:
if not x.get('path'):
continue
f = family_name_to_key(x['family'])
full = family_name_to_key(x['full_name'])
ps = family_name_to_key(x['postscript_name'])
ans['family_map'].setdefault(f, []).append(x)
ans['ps_map'].setdefault(ps, []).append(x)
ans['full_map'].setdefault(full, []).append(x)
if x['variable']:
ans['variable_map'].setdefault(f, []).append(x)
return ans
def clear_caches() -> None:
all_fonts_map.cache_clear()
fc_match.cache_clear()
weight_range_for_family.cache_clear()
clear_fallback_font_cache()
@lru_cache(maxsize=2)
def all_fonts_map(monospaced: bool = True) -> FontMap:
if monospaced:
ans = fc_list(spacing=FC_DUAL) + fc_list(spacing=FC_MONO)
else:
# allow non-monospaced and bitmapped fonts as these are used for
# symbol_map
ans = fc_list(allow_bitmapped_fonts=True)
return create_font_map(ans)
def is_monospace(descriptor: FontConfigPattern) -> bool:
return descriptor['spacing'] in ('MONO', 'DUAL')
def is_variable(descriptor: FontConfigPattern) -> bool:
return descriptor['variable']
def list_fonts(only_variable: bool = False) -> Generator[ListedFont, None, None]:
for fd in fc_list(only_variable=only_variable):
f = fd.get('family')
if f and isinstance(f, str):
fn_ = fd.get('full_name')
if fn_:
fn = str(fn_)
else:
fn = f'{f} {fd.get("style", "")}'.strip()
yield {
'family': f,
'full_name': fn,
'postscript_name': str(fd.get('postscript_name', '')),
'is_monospace': is_monospace(fd),
'descriptor': fd,
'is_variable': is_variable(fd),
'style': fd['style'],
}
@lru_cache
def fc_match(family: str, bold: bool, italic: bool, spacing: int = FC_MONO) -> FontConfigPattern:
return fc_match_impl(family, bold, italic, spacing)
class WeightRange(NamedTuple):
minimum: int = sys.maxsize
maximum: int = -1
medium: int = -1
bold: int = -1
@property
def is_valid(self) -> bool:
return self.minimum != wr.minimum and self.maximum != wr.maximum and self.medium != wr.medium and self.bold != wr.bold
wr = WeightRange()
@lru_cache
def weight_range_for_family(family: str) -> WeightRange:
faces = all_fonts_map(True)['family_map'].get(family_name_to_key(family), ())
mini, maxi, medium, bold = wr.minimum, wr.maximum, wr.medium, wr.bold
seen_weights = set()
for face in faces:
w = face['weight']
mini, maxi = min(w, mini), max(w, maxi)
seen_weights.add(w)
s = face['style'].lower()
if not s:
continue
s = s.split()[0]
if s == 'semibold':
bold = w
elif s == 'bold' and bold == wr.bold:
bold = w
elif s == 'regular':
medium = w
elif s == 'medium' and medium == wr.medium:
medium = w
if len(seen_weights) < 2:
return wr
return WeightRange(mini, maxi, medium, bold)
class FCScorer(Scorer[FontConfigPattern]):
weight_range: WeightRange | None = None
def score(self, candidate: Descriptor) -> Score:
assert candidate['descriptor_type'] == 'fontconfig'
variable_score = 0 if self.prefer_variable and candidate['variable'] else 1
if self.weight_range is None:
bold_score = abs((FC_WEIGHT_BOLD if self.bold else FC_WEIGHT_REGULAR) - candidate['weight'])
else:
bold_score = abs((self.weight_range.bold if self.bold else self.weight_range.medium) - candidate['weight'])
italic_score = abs((FC_SLANT_ITALIC if self.italic else FC_SLANT_ROMAN) - candidate['slant'])
monospace_match = 0
if self.monospaced:
monospace_match = 0 if candidate.get('spacing') == 'MONO' else 1
width_score = abs(candidate['width'] - FC_WIDTH_NORMAL)
return Score(variable_score, bold_score / 1000 + italic_score / 110, monospace_match, width_score)
def sorted_candidates(self, candidates: Sequence[FontConfigPattern], dump: bool = False) -> list[FontConfigPattern]:
self.weight_range = None
families = {x['family'] for x in candidates}
if len(families) == 1:
wr = weight_range_for_family(next(iter(families)))
if wr.is_valid and wr.medium < 100: # Operator Mono and Cascadia Code are examples
self.weight_range = wr
candidates = sorted(candidates, key=self.score)
if dump:
print(self)
if self.weight_range:
print(self.weight_range)
for x in candidates:
assert x['descriptor_type'] == 'fontconfig'
print(Face(descriptor=x).postscript_name(), f'weight={x["weight"]}', f'slant={x["slant"]}')
print(' ', self.score(x))
print()
return candidates
def create_scorer(bold: bool = False, italic: bool = False, monospaced: bool = True, prefer_variable: bool = False) -> Scorer:
return FCScorer(bold, italic, monospaced, prefer_variable)
def find_last_resort_text_font(bold: bool = False, italic: bool = False, monospaced: bool = True) -> FontConfigPattern:
# Use fc-match with a generic family
family = 'monospace' if monospaced else 'sans-serif'
return fc_match(family, bold, italic)
def find_best_match(
family: str,
bold: bool = False,
italic: bool = False,
monospaced: bool = True,
ignore_face: FontConfigPattern | None = None,
prefer_variable: bool = False,
) -> FontConfigPattern:
from .common import find_best_match_in_candidates
q = family_name_to_key(family)
font_map = all_fonts_map(monospaced)
scorer = create_scorer(bold, italic, monospaced, prefer_variable=prefer_variable)
is_medium_face = not bold and not italic
# First look for an exact match
groups: tuple[FontCollectionMapType, ...] = ('ps_map', 'full_map', 'family_map')
for which in groups:
m = font_map[which]
cq = m.get(q, [])
if cq:
if which == 'full_map' and cq[0]['family'] == cq[0]['full_name']:
continue # IBM Plex Mono has fullname of regular face == family_name under fontconfig
exact_match = find_best_match_in_candidates(cq, scorer, is_medium_face, ignore_face=ignore_face)
if exact_match:
return exact_match
# Use fc-match to see if we can find a monospaced font that matches family
# When aliases are defined, spacing can cause the incorrect font to be
# returned, so check with and without spacing and use the one that matches.
mono_possibility = fc_match(family, False, False, FC_MONO)
dual_possibility = fc_match(family, False, False, FC_DUAL)
any_possibility = fc_match(family, False, False, 0)
tries = (dual_possibility, mono_possibility) if any_possibility == dual_possibility else (mono_possibility, dual_possibility)
for possibility in tries:
for key, map_key in (('postscript_name', 'ps_map'), ('full_name', 'full_map'), ('family', 'family_map')):
map_key = cast(FontCollectionMapType, map_key)
val: str | None = cast(Optional[str], possibility.get(key))
if val:
candidates = font_map[map_key].get(family_name_to_key(val))
if candidates:
if len(candidates) == 1:
# happens if the family name is an alias, so we search with
# the actual family name to see if we can find all the
# fonts in the family.
family_name_candidates = font_map['family_map'].get(family_name_to_key(candidates[0]['family']))
if family_name_candidates and len(family_name_candidates) > 1:
candidates = family_name_candidates
return scorer.sorted_candidates(candidates)[0]
return find_last_resort_text_font(bold, italic, monospaced)
def font_for_family(family: str) -> tuple[FontConfigPattern, bool, bool]:
ans = find_best_match(family, monospaced=False)
return ans, ans.get('weight', 0) >= FC_WEIGHT_BOLD, ans.get('slant', FC_SLANT_ROMAN) != FC_SLANT_ROMAN
def descriptor(f: ListedFont) -> FontConfigPattern:
d = f['descriptor']
assert d['descriptor_type'] == 'fontconfig'
return d
def prune_family_group(g: list[ListedFont]) -> list[ListedFont]:
# fontconfig creates dummy entries for named styles in variable fonts, prune them
variable_paths = {descriptor(f)['path'] for f in g if f['is_variable']}
if not variable_paths:
return g
def is_ok(d: FontConfigPattern) -> bool:
return d['variable'] or d['path'] not in variable_paths
return [x for x in g if is_ok(descriptor(x))]
def set_named_style(name: str, font: FontConfigPattern, vd: VariableData) -> bool:
q = name.lower()
for i, ns in enumerate(vd['named_styles']):
if ns['psname'].lower() == q:
font['named_style'] = i
return True
for i, ns in enumerate(vd['named_styles']):
if ns['name'].lower() == q:
font['named_style'] = i
return True
if vd['elided_fallback_name']:
for i, ns in enumerate(vd['named_styles']):
eq = ' '.join(ns['name'].replace(vd['elided_fallback_name'], '').strip().split()).lower()
if q == eq:
font['named_style'] = i
return True
return False
def lift_axes_to_named_style_if_possible(font: FontConfigPattern, vd: VariableData) -> bool:
axes = font.get('axes', tuple(ax['default'] for ax in vd['axes']))
q = {vd['axes'][i]['tag']: val for i, val in enumerate(axes)}
for i, ns in enumerate(vd['named_styles']):
if ns['axis_values'] == q:
font.pop('axes', None)
font['named_style'] = i
return True
return False
def set_axis_values(tag_map: dict[str, float], font: FontConfigPattern, vd: VariableData) -> bool:
axes = list(font.get('axes', ())) or [ax['default'] for ax in vd['axes']]
changed = False
for i, ax in enumerate(vd['axes']):
val = tag_map.get(ax['tag'])
if val is not None:
changed = True
axes[i] = val
if changed:
font['axes'] = tuple(axes)
lift_axes_to_named_style_if_possible(font, vd)
return changed
def get_axis_values(font: FontConfigPattern, vd: VariableData) -> dict[str, float]:
ans: dict[str, float] = {}
ns = font.get('named_style')
if ns is not None:
if ns > -1 and ns < len(vd['named_styles']):
ans = vd['named_styles'][ns]['axis_values']
axis_values = font.get('axes', ())
for i, ax in enumerate(vd['axes']):
tag = ax['tag']
if i < len(axis_values):
ans[tag] = axis_values[i]
else:
if tag not in ans:
ans[tag] = ax['default']
return ans
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from collections.abc import Sequence
from kitty.constants import is_macos
from . import ListedFont
from .common import get_variable_data_for_descriptor
if is_macos:
from .core_text import list_fonts, prune_family_group
else:
from .fontconfig import list_fonts, prune_family_group
def create_family_groups(monospaced: bool = True) -> dict[str, list[ListedFont]]:
g: dict[str, list[ListedFont]] = {}
for f in list_fonts():
if not monospaced or f['is_monospace']:
g.setdefault(f['family'], []).append(f)
return {k: prune_family_group(v) for k, v in g.items()}
def as_json(indent: int | None = None) -> str:
import json
groups = create_family_groups()
for v in groups.values():
for f in v:
f['variable_data'] = get_variable_data_for_descriptor(f['descriptor']) # type: ignore
return json.dumps(groups, indent=indent)
def main(argv: Sequence[str]) -> None:
import os
from kitty.constants import kitten_exe, kitty_exe
argv = list(argv)
if '--psnames' in argv:
argv.remove('--psnames')
os.environ['KITTY_PATH_TO_KITTY_EXE'] = kitty_exe()
os.execlp(kitten_exe(), 'kitten', 'choose-fonts')
+388
View File
@@ -0,0 +1,388 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
from collections.abc import Callable, Generator
from typing import TYPE_CHECKING, Any, Literal, Union
from kitty.constants import fonts_dir, is_macos
from kitty.fast_data_types import (
Screen,
concat_cells,
create_test_font_group,
current_fonts,
get_fallback_font,
render_decoration,
set_builtin_nerd_font,
set_font_data,
set_options,
set_send_sprite_to_gpu,
sprite_idx_to_pos,
sprite_map_set_limits,
test_render_line,
test_shape,
)
from kitty.options.types import Options, defaults
from kitty.options.utils import parse_font_spec
from kitty.typing_compat import CoreTextFont, FontConfigPattern
from kitty.utils import log_error
from . import family_name_to_key
from .common import get_font_files
if is_macos:
from .core_text import font_for_family as font_for_family_macos
else:
from .fontconfig import font_for_family as font_for_family_fontconfig
if TYPE_CHECKING:
from kitty.fast_data_types import CTFace, DecorationTypes, Face
else:
DecorationTypes = str
FontObject = Union[CoreTextFont, FontConfigPattern]
current_faces: list[tuple[FontObject, bool, bool]] = []
builtin_nerd_font_descriptor: FontObject | None = None
def font_for_family(family: str) -> tuple[FontObject, bool, bool]:
if is_macos:
return font_for_family_macos(family)
return font_for_family_fontconfig(family)
def merge_ranges[_T](
a: tuple[tuple[int, int], _T], b: tuple[tuple[int, int], _T], priority_map: dict[tuple[int, int], int]
) -> Generator[tuple[tuple[int, int], _T], None, None]:
a_start, a_end = a[0]
b_start, b_end = b[0]
a_val, b_val = a[1], b[1]
a_prio, b_prio = priority_map[a[0]], priority_map[b[0]]
if b_start > a_end:
if b_start == a_end + 1 and a_val == b_val:
# ranges can be coalesced
r = ((a_start, b_end), a_val)
priority_map[r[0]] = max(a_prio, b_prio)
yield r
return
# disjoint ranges
yield a
yield b
return
if a_val == b_val:
# mergeable ranges
r = ((a_start, max(a_end, b_end)), a_val)
priority_map[r[0]] = max(a_prio, b_prio)
yield r
return
before_range = mid_range = after_range = None
before_range_prio = mid_range_prio = after_range_prio = 0
if b_start > a_start:
before_range = ((a_start, b_start - 1), a_val)
before_range_prio = a_prio
mid_end = min(a_end, b_end)
if mid_end >= b_start:
# overlap range
mid_range = ((b_start, mid_end), a_val if priority_map[a[0]] >= priority_map[b[0]] else b_val)
mid_range_prio = max(a_prio, b_prio)
# after range
if mid_end is a_end:
if b_end > a_end:
after_range = ((a_end + 1, b_end), b_val)
after_range_prio = b_prio
else:
if a_end > b_end:
after_range = ((b_end + 1, a_end), a_val)
after_range_prio = a_prio
# check if the before, mid and after ranges can be coalesced
ranges: list[tuple[tuple[int, int], _T]] = []
priorities: list[int] = []
for rq, prio in ((before_range, before_range_prio), (mid_range, mid_range_prio), (after_range, after_range_prio)):
if rq is None:
continue
r = rq
if ranges:
x = ranges[-1]
if x[0][1] + 1 == r[0][0] and x[1] == r[1]:
ranges[-1] = ((x[0][0], r[0][1]), x[1])
priorities[-1] = max(priorities[-1], prio)
else:
ranges.append(r)
priorities.append(prio)
else:
ranges.append(r)
priorities.append(prio)
for r, p in zip(ranges, priorities):
priority_map[r[0]] = p
yield from ranges
def coalesce_symbol_maps[_T](maps: dict[tuple[int, int], _T]) -> dict[tuple[int, int], _T]:
if not maps:
return maps
priority_map = {r: i for i, r in enumerate(maps.keys())}
ranges = tuple((r, maps[r]) for r in sorted(maps))
ans = [ranges[0]]
for i in range(1, len(ranges)):
r = ranges[i]
new_ranges = merge_ranges(ans[-1], r, priority_map)
if ans:
del ans[-1]
if not ans:
ans = list(new_ranges)
else:
for r in new_ranges:
prev = ans[-1]
if prev[0][1] + 1 == r[0][0] and prev[1] == r[1]:
ans[-1] = (prev[0][0], r[0][1]), prev[1]
else:
ans.append(r)
return dict(ans)
def create_symbol_map(opts: Options) -> tuple[tuple[int, int, int], ...]:
val = coalesce_symbol_maps(opts.symbol_map)
family_map: dict[str, int] = {}
count = 0
for family in val.values():
if family not in family_map:
font, bold, italic = font_for_family(family)
fkey = family_name_to_key(family)
if fkey in ('symbolsnfm', 'symbols nerd font mono') and font['postscript_name'] != 'SymbolsNFM' and builtin_nerd_font_descriptor:
font = builtin_nerd_font_descriptor
bold = italic = False
family_map[family] = count
count += 1
current_faces.append((font, bold, italic))
sm = tuple((a, b, family_map[f]) for (a, b), f in val.items())
return sm
def create_narrow_symbols(opts: Options) -> tuple[tuple[int, int, int], ...]:
return tuple((a, b, v) for (a, b), v in coalesce_symbol_maps(opts.narrow_symbols).items())
descriptor_overrides: dict[int, tuple[str, bool, bool]] = {}
def descriptor_for_idx(idx: int) -> tuple[FontObject | str, bool, bool]:
ans = descriptor_overrides.get(idx)
if ans is None:
return current_faces[idx]
return ans
def dump_font_debug() -> None:
cf = current_fonts()
log_error('Text fonts:')
for key, text in {'medium': 'Normal', 'bold': 'Bold', 'italic': 'Italic', 'bi': 'Bold-Italic'}.items():
log_error(f' {text}:', cf[key].identify_for_debug())
ss = cf['symbol']
if ss:
log_error('Symbol map fonts:')
for s in ss:
log_error(' ' + s.identify_for_debug())
def clear_font_caches() -> None:
from .common import clear_caches as clear_common_caches
clear_common_caches()
if is_macos:
from .core_text import clear_caches as clear_platform_caches
else:
from .fontconfig import clear_caches as clear_platform_caches
clear_platform_caches()
def set_font_family(opts: Options | None = None, override_font_size: float | None = None, add_builtin_nerd_font: bool = False) -> None:
global current_faces, builtin_nerd_font_descriptor
opts = opts or defaults
sz = override_font_size or opts.font_size
font_map = get_font_files(opts)
current_faces = [(font_map['medium'], False, False)]
ftypes: list[Literal['bold', 'italic', 'bi']] = ['bold', 'italic', 'bi']
indices = {k: 0 for k in ftypes}
for k in ftypes:
if k in font_map:
indices[k] = len(current_faces)
current_faces.append((font_map[k], 'b' in k, 'i' in k))
before = len(current_faces)
if add_builtin_nerd_font:
builtin_nerd_font_path = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf')
if os.path.exists(builtin_nerd_font_path):
builtin_nerd_font_descriptor = set_builtin_nerd_font(builtin_nerd_font_path)
else:
log_error(f'No builtin NERD font found in {fonts_dir}')
sm = create_symbol_map(opts)
ns = create_narrow_symbols(opts)
num_symbol_fonts = len(current_faces) - before
set_font_data(descriptor_for_idx, indices['bold'], indices['italic'], indices['bi'], num_symbol_fonts, sm, sz, ns)
if TYPE_CHECKING:
import ctypes
CBufType = ctypes.Array[ctypes.c_ubyte]
else:
CBufType = None
UnderlineCallback = Callable[[CBufType, int, int, int, int], None]
class setup_for_testing:
xnum = 100000
ynum = 100
baseline = 0
def __init__(self, family: str = 'monospace', size: float = 11.0, dpi: float = 96.0, main_face_path: str = ''):
self.family, self.size, self.dpi = family, size, dpi
self.main_face_path = main_face_path
def __enter__(self) -> tuple[dict[tuple[int, int, int], bytes], int, int]:
global descriptor_overrides
opts = defaults._replace(font_family=parse_font_spec(self.family), font_size=self.size)
set_options(opts)
sprites = {}
def send_to_gpu(x: int, y: int, z: int, data: bytes) -> None:
sprites[(x, y, z)] = data
sprite_map_set_limits(self.xnum, self.ynum)
set_send_sprite_to_gpu(send_to_gpu)
self.orig_desc_overrides = descriptor_overrides
descriptor_overrides = {}
if self.main_face_path:
descriptor_overrides[0] = self.main_face_path, False, False
try:
set_font_family(opts)
cell_width, cell_height, self.baseline = create_test_font_group(self.size, self.dpi, self.dpi)
return sprites, cell_width, cell_height
except Exception:
set_send_sprite_to_gpu(None)
raise
def __exit__(self, *args: Any) -> None:
global descriptor_overrides
descriptor_overrides = self.orig_desc_overrides
set_send_sprite_to_gpu(None)
def render_string(text: str, family: str = 'monospace', size: float = 11.0, dpi: float = 96.0) -> tuple[int, int, list[bytes]]:
with setup_for_testing(family, size, dpi) as (sprites, cell_width, cell_height):
s = Screen(None, 1, len(text) * 2)
line = s.line(0)
s.draw(text)
test_render_line(line)
cells = []
found_content = False
for i in reversed(range(s.columns)):
sp = line.sprite_at(i)
sp &= 0x7FFFFFFF
if not sp and not found_content:
continue
found_content = True
cells.append(sprites[sprite_idx_to_pos(sp, setup_for_testing.xnum, setup_for_testing.ynum)])
return cell_width, cell_height, list(reversed(cells))
def shape_string(
text: str = 'abcd', family: str = 'monospace', size: float = 11.0, dpi: float = 96.0, path: str | None = None
) -> list[tuple[int, int, int, tuple[int, ...]]]:
with setup_for_testing(family, size, dpi) as (sprites, cell_width, cell_height):
s = Screen(None, 1, len(text) * 2)
line = s.line(0)
s.draw(text)
return test_shape(line, path)
def show(rgba_data: bytes | memoryview, width: int, height: int, fmt: int = 32) -> None:
from base64 import standard_b64encode
from kittens.tui.images import GraphicsCommand
data = memoryview(standard_b64encode(rgba_data))
cmd = GraphicsCommand()
cmd.a = 'T'
cmd.f = fmt
cmd.s = width
cmd.v = height
sys.stdout.flush()
while data:
chunk, data = data[:4096], data[4096:]
cmd.m = 1 if data else 0
sys.stdout.buffer.write(cmd.serialize(chunk))
cmd.clear()
sys.stdout.buffer.flush()
def display_bitmap(rgb_data: bytes, width: int, height: int) -> None:
assert len(rgb_data) == 4 * width * height
show(rgb_data, width, height)
def test_render_string(text: str = 'Hello, world!', family: str = 'monospace', size: float = 64.0, dpi: float = 96.0) -> None:
cell_width, cell_height, cells = render_string(text, family, size, dpi)
rgb_data = concat_cells(cell_width, cell_height, True, tuple(cells))
cf = current_fonts()
fonts = [cf['medium'].postscript_name()]
fonts.extend(f.postscript_name() for f in cf['fallback'])
msg = 'Rendered string {} below, with fonts: {}\n'.format(text, ', '.join(fonts))
try:
print(msg)
except UnicodeEncodeError:
sys.stdout.buffer.write(msg.encode('utf-8') + b'\n')
display_bitmap(rgb_data, cell_width * len(cells), cell_height)
print('\n')
def test_fallback_font(qtext: str | None = None, bold: bool = False, italic: bool = False) -> None:
with setup_for_testing():
if qtext:
trials = [qtext]
else:
trials = ['你', 'He\u0347\u0305', '\U0001f929']
for text in trials:
f = get_fallback_font(text, bold, italic)
try:
print(text, f)
except UnicodeEncodeError:
sys.stdout.buffer.write(f'{text} {f}\n'.encode())
def showcase() -> None:
f = 'monospace' if is_macos else 'Liberation Mono'
test_render_string('He\u0347\u0305llo\u0337, w\u0302or\u0306l\u0354d!', family=f)
test_render_string('你好,世界', family=f)
test_render_string('│😁│🙏│😺│', family=f)
test_render_string('A=>>B!=C', family='Fira Code')
def create_face(path: str) -> 'Union[CTFace, Face]':
if is_macos:
from kitty.fast_data_types import CTFace
return CTFace(path=path)
from kitty.fast_data_types import Face
return Face(path=path)
def test_render_codepoint(chars: str = '😺', path: str = '/t/Noto-COLRv1.ttf', font_size: float = 160.0) -> None:
f = create_face(path=path)
f.set_size(font_size, 96, 96)
for char in chars:
bitmap, w, h = f.render_codepoint(ord(char))
print('Rendered:', char)
display_bitmap(bitmap, w, h)
print('\n')
def test_render_decoration(which: DecorationTypes, cell_width: int, cell_height: int, underline_position: int, underline_thickness: int) -> None:
buf = render_decoration(which, cell_width, cell_height, underline_position, underline_thickness)
cells = buf, buf, buf, buf, buf
rgb_data = concat_cells(cell_width, cell_height, False, cells)
display_bitmap(rgb_data, cell_width * len(cells), cell_height)
+1713
View File
File diff suppressed because it is too large. Load diff
+799
View File
@@ -0,0 +1,799 @@
/*
* freetype_render_ui_text.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "freetype_render_ui_text.h"
#include <hb.h>
#include <hb-ft.h>
#include "charsets.h"
#include "char-props.h"
#include "wcswidth.h"
#include FT_BITMAP_H
#define ELLIPSIS 0x2026
typedef struct FamilyInformation {
char *name;
bool bold, italic;
} FamilyInformation;
typedef struct Face {
FT_Face freetype;
hb_font_t *hb;
FT_UInt pixel_size;
int hinting, hintstyle;
struct Face **fallbacks;
size_t count, capacity;
} Face;
typedef struct {
unsigned char *buf;
size_t start_x, width, stride;
size_t rows;
FT_Pixel_Mode pixel_mode;
unsigned int left_edge, top_edge, bottom_edge, right_edge;
float factor;
int bitmap_left, bitmap_top;
} ProcessedBitmap;
typedef struct RenderCtx {
bool created;
Face main_face;
FontConfigFace main_face_information;
FamilyInformation main_face_family;
hb_buffer_t *hb_buffer;
} RenderCtx;
#define main_face ctx->main_face
#define main_face_information ctx->main_face_information
#define main_face_family ctx->main_face_family
#define hb_buffer ctx->hb_buffer
static FT_UInt
glyph_id_for_codepoint(Face *face, char_type cp) {
return FT_Get_Char_Index(face->freetype, cp);
}
static void
free_face(Face *face) {
if (face->freetype) FT_Done_Face(face->freetype);
if (face->hb) hb_font_destroy(face->hb);
for (size_t i = 0; i < face->count; i++) {
free_face(face->fallbacks[i]);
free(face->fallbacks[i]);
}
free(face->fallbacks);
memset(face, 0, sizeof(Face));
}
static void
cleanup(RenderCtx *ctx) {
free_face(&main_face);
free(main_face_information.path);
main_face_information.path = NULL;
free(main_face_family.name);
memset(&main_face_family, 0, sizeof(FamilyInformation));
if (hb_buffer) hb_buffer_destroy(hb_buffer);
hb_buffer = NULL;
}
void
set_main_face_family(FreeTypeRenderCtx ctx_, const char *family, bool bold, bool italic) {
RenderCtx *ctx = (RenderCtx *)ctx_;
if ((family == main_face_family.name || (main_face_family.name && strcmp(family, main_face_family.name) == 0)) && main_face_family.bold == bold &&
main_face_family.italic == italic)
return;
cleanup(ctx);
main_face_family.name = family ? strdup(family) : NULL;
main_face_family.bold = bold;
main_face_family.italic = italic;
}
static int
get_load_flags(int hinting, int hintstyle, int base) {
int flags = base;
if (hinting) {
if (hintstyle >= 3) flags |= FT_LOAD_TARGET_NORMAL;
else if (0 < hintstyle) flags |= FT_LOAD_TARGET_LIGHT;
} else flags |= FT_LOAD_NO_HINTING;
return flags;
}
static bool
load_font(FontConfigFace *info, Face *ans) {
ans->freetype = native_face_from_path(info->path, info->index);
if (!ans->freetype || PyErr_Occurred()) return false;
ans->hb = hb_ft_font_create(ans->freetype, NULL);
if (!ans->hb) {
PyErr_NoMemory();
return false;
}
ans->hinting = info->hinting;
ans->hintstyle = info->hintstyle;
hb_ft_font_set_load_flags(ans->hb, get_load_flags(ans->hinting, ans->hintstyle, FT_LOAD_DEFAULT));
return true;
}
static int
font_units_to_pixels_y(FT_Face face, int x) {
return (int)ceil((double)FT_MulFix(x, face->size->metrics.y_scale) / 64.0);
}
static FT_UInt
choose_bitmap_size(FT_Face face, FT_UInt desired_height) {
unsigned short best = 0, diff = USHRT_MAX;
const short limit = face->num_fixed_sizes;
for (short i = 0; i < limit; i++) {
unsigned short h = face->available_sizes[i].height;
unsigned short d = h > (unsigned short)desired_height ? h - (unsigned short)desired_height : (unsigned short)desired_height - h;
if (d < diff) {
diff = d;
best = i;
}
}
FT_Select_Size(face, best);
return best;
}
static void
set_pixel_size(RenderCtx *ctx, Face *face, FT_UInt sz, bool get_metrics UNUSED) {
if (sz != face->pixel_size) {
if (face->freetype->num_fixed_sizes > 0 && FT_HAS_COLOR(face->freetype))
choose_bitmap_size(face->freetype, font_units_to_pixels_y(main_face.freetype, main_face.freetype->height));
else FT_Set_Pixel_Sizes(face->freetype, sz, sz);
hb_ft_font_changed(face->hb);
hb_ft_font_set_load_flags(face->hb, get_load_flags(face->hinting, face->hintstyle, FT_LOAD_DEFAULT));
face->pixel_size = sz;
}
}
typedef struct RenderState {
uint32_t pending_in_buffer, fg, bg;
pixel *output;
size_t output_width, output_height, stride;
Face *current_face;
float x, y, start_pos_for_current_run;
int y_offset;
Region src, dest;
unsigned sz_px;
bool truncated;
bool horizontally_center;
} RenderState;
static void
setup_regions(ProcessedBitmap *bm, RenderState *rs, int baseline) {
rs->src = (Region){.left = bm->start_x, .bottom = bm->rows, .right = bm->width + bm->start_x};
rs->dest = (Region){.bottom = rs->output_height, .right = rs->output_width};
int xoff = (int)(rs->x + bm->bitmap_left);
if (xoff < 0) rs->src.left += -xoff;
else rs->dest.left = xoff;
if (rs->horizontally_center) {
int run_width = (int)(rs->output_width - rs->start_pos_for_current_run);
rs->dest.left = (int)rs->start_pos_for_current_run + (run_width > (int)bm->width ? (run_width - bm->width) / 2 : 0);
}
int yoff = (int)(rs->y + bm->bitmap_top);
if ((yoff > 0 && yoff > baseline)) {
rs->dest.top = 0;
} else {
rs->dest.top = baseline - yoff;
}
rs->dest.top += rs->y_offset;
}
#define ARGB(a, r, g, b) ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)
static pixel
premult_pixel(pixel p, uint16_t alpha) {
#define s(x) (x * alpha / 255)
uint16_t r = (p >> 16) & 0xff, g = (p >> 8) & 0xff, b = p & 0xff;
return ARGB(alpha, s(r), s(g), s(b));
#undef s
}
static pixel
alpha_blend_premult(pixel over, pixel under) {
const uint16_t over_r = (over >> 16) & 0xff, over_g = (over >> 8) & 0xff, over_b = over & 0xff;
const uint16_t under_r = (under >> 16) & 0xff, under_g = (under >> 8) & 0xff, under_b = under & 0xff;
const uint16_t over_alpha = (over >> 24) & 0xff;
const uint16_t factor = 255 - over_alpha;
const uint16_t result_alpha = over_alpha + (uint16_t)(factor * ((under >> 24) & 0xff) / 255);
#define ans(x) (over_##x + (factor * under_##x) / 255)
return ARGB(result_alpha, ans(r), ans(g), ans(b));
#undef ans
}
static void
render_color_bitmap(ProcessedBitmap *src, RenderState *rs) {
for (size_t sr = rs->src.top, dr = rs->dest.top; sr < rs->src.bottom && dr < rs->dest.bottom; sr++, dr++) {
pixel *dest_row = rs->output + rs->stride * dr;
uint8_t *src_px = src->buf + src->stride * sr + 4 * rs->src.left;
for (size_t sc = rs->src.left, dc = rs->dest.left; sc < rs->src.right && dc < rs->dest.right; sc++, dc++, src_px += 4) {
pixel fg = premult_pixel(ARGB(src_px[3], src_px[2], src_px[1], src_px[0]), src_px[3]);
dest_row[dc] = alpha_blend_premult(fg, dest_row[dc]);
}
}
}
static void
render_gray_bitmap(ProcessedBitmap *src, RenderState *rs) {
for (size_t sr = rs->src.top, dr = rs->dest.top; sr < rs->src.bottom && dr < rs->dest.bottom; sr++, dr++) {
pixel *dest_row = rs->output + rs->stride * dr;
uint8_t *src_row = src->buf + src->stride * sr;
for (size_t sc = rs->src.left, dc = rs->dest.left; sc < rs->src.right && dc < rs->dest.right; sc++, dc++) {
pixel fg = premult_pixel(rs->fg, src_row[sc]);
dest_row[dc] = alpha_blend_premult(fg, dest_row[dc]);
}
}
}
static void
populate_processed_bitmap(FT_GlyphSlotRec *slot, FT_Bitmap *bitmap, ProcessedBitmap *ans) {
ans->stride = bitmap->pitch < 0 ? -bitmap->pitch : bitmap->pitch;
ans->rows = bitmap->rows;
ans->start_x = 0;
ans->width = bitmap->width;
ans->pixel_mode = bitmap->pixel_mode;
ans->bitmap_top = slot->bitmap_top;
ans->bitmap_left = slot->bitmap_left;
ans->buf = bitmap->buffer;
}
static void
detect_edges(ProcessedBitmap *ans) {
#define check \
const uint8_t *p = ans->buf + x * 4 + y * ans->stride; \
if (p[3] > 20)
ans->right_edge = 0;
ans->bottom_edge = 0;
for (ssize_t x = ans->width - 1; !ans->right_edge && x > -1; x--) {
for (size_t y = 0; y < ans->rows && !ans->right_edge; y++) { check ans->right_edge = x; }
}
for (ssize_t y = ans->rows - 1; !ans->bottom_edge && y > -1; y--) {
for (size_t x = 0; x < ans->width && !ans->bottom_edge; x++) { check ans->bottom_edge = y; }
}
ans->left_edge = ans->width;
for (size_t x = 0; ans->left_edge == ans->width && x < ans->width; x++) {
for (size_t y = 0; y < ans->rows && ans->left_edge == ans->width; y++) { check ans->left_edge = x; }
}
ans->top_edge = ans->rows;
for (size_t y = 0; ans->top_edge == ans->rows && y < ans->rows; y++) {
for (size_t x = 0; x < ans->width && ans->top_edge == ans->rows; x++) { check ans->top_edge = y; }
}
#undef check
}
static Face *
find_fallback_font_for(RenderCtx *ctx, char_type codep, char_type next_codep) {
if (glyph_id_for_codepoint(&main_face, codep) > 0) return &main_face;
for (size_t i = 0; i < main_face.count; i++) {
if (glyph_id_for_codepoint(main_face.fallbacks[i], codep) > 0) return main_face.fallbacks[i];
}
FontConfigFace q;
bool prefer_color = false;
char_type string[3] = {codep, next_codep, 0};
if (wcswidth_string(string) >= 2 && char_props_for(codep).is_emoji_presentation_base) prefer_color = true;
if (!fallback_font(codep, main_face_family.name, main_face_family.bold, main_face_family.italic, prefer_color, &q)) return NULL;
ensure_space_for(&main_face, fallbacks, Face, main_face.count + 1, capacity, 8, true);
Face *ans = calloc(1, sizeof(Face));
if (!ans) fatal("Out of memory");
bool ok = load_font(&q, ans);
if (PyErr_Occurred()) PyErr_Print();
free(q.path);
if (!ok) {
free(ans);
return NULL;
}
main_face.fallbacks[main_face.count] = ans;
main_face.count++;
return ans;
}
static unsigned
calculate_ellipsis_width(RenderCtx *ctx) {
Face *face = find_fallback_font_for(ctx, ELLIPSIS, 0);
if (!face) return 0;
set_pixel_size(ctx, face, main_face.pixel_size, false);
int glyph_index = FT_Get_Char_Index(face->freetype, ELLIPSIS);
if (!glyph_index) return 0;
int error = FT_Load_Glyph(face->freetype, glyph_index, get_load_flags(face->hinting, face->hintstyle, FT_LOAD_DEFAULT));
if (error) return 0;
return (unsigned)ceilf((float)face->freetype->glyph->metrics.horiAdvance / 64.f);
}
static bool
render_run(RenderCtx *ctx, RenderState *rs) {
hb_buffer_guess_segment_properties(hb_buffer);
if (!HB_DIRECTION_IS_HORIZONTAL(hb_buffer_get_direction(hb_buffer))) {
PyErr_SetString(PyExc_ValueError, "Vertical text is not supported");
return false;
}
FT_Face face = rs->current_face->freetype;
bool has_color = FT_HAS_COLOR(face);
FT_UInt pixel_size = rs->sz_px;
set_pixel_size(ctx, rs->current_face, pixel_size, false);
hb_shape(rs->current_face->hb, hb_buffer, NULL, 0);
unsigned int len = hb_buffer_get_length(hb_buffer);
hb_glyph_info_t *info = hb_buffer_get_glyph_infos(hb_buffer, NULL);
hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(hb_buffer, NULL);
int baseline = font_units_to_pixels_y(face, face->ascender);
int load_flags = get_load_flags(rs->current_face->hinting, rs->current_face->hintstyle, FT_LOAD_RENDER | (has_color ? FT_LOAD_COLOR : 0));
float pos = rs->x;
unsigned int limit = len;
for (unsigned int i = 0; i < len; i++) {
float delta = (float)positions[i].x_offset / 64.0f + (float)positions[i].x_advance / 64.0f;
if (pos + delta > rs->output_width) {
limit = i;
break;
}
pos += delta;
}
if (limit < len) {
unsigned ellipsis_width = calculate_ellipsis_width(ctx);
while (pos + ellipsis_width >= rs->output_width && limit) {
limit--;
pos -= (float)positions[limit].x_offset / 64.0f + (float)positions[limit].x_advance / 64.0f;
}
rs->truncated = true;
}
rs->start_pos_for_current_run = rs->x;
for (unsigned int i = 0; i < limit; i++) {
rs->x += (float)positions[i].x_offset / 64.0f;
rs->y += (float)positions[i].y_offset / 64.0f;
if (rs->x > rs->output_width) break;
int error = FT_Load_Glyph(face, info[i].codepoint, load_flags);
if (error) {
set_freetype_error("Failed loading glyph", error);
PyErr_Print();
continue;
};
ProcessedBitmap pbm = {0};
switch (face->glyph->bitmap.pixel_mode) {
case FT_PIXEL_MODE_BGRA: {
uint8_t *buf = NULL;
unsigned text_height = font_units_to_pixels_y(main_face.freetype, main_face.freetype->height);
populate_processed_bitmap(face->glyph, &face->glyph->bitmap, &pbm);
unsigned bm_width = 0, bm_height = text_height;
if (pbm.rows > bm_height) {
double ratio = pbm.width / (double)pbm.rows;
bm_width = (unsigned)(ratio * bm_height);
buf = calloc((size_t)bm_height * bm_width, sizeof(pixel));
if (!buf) break;
downsample_32bit_image(pbm.buf, pbm.width, pbm.rows, pbm.stride, buf, bm_width, bm_height);
pbm.buf = buf;
pbm.stride = 4 * bm_width;
pbm.width = bm_width;
pbm.rows = bm_height;
detect_edges(&pbm);
}
setup_regions(&pbm, rs, baseline);
if (bm_width) {
/* printf("bottom_edge: %u top_edge: %u left_edge: %u right_edge: %u\n", */
/* pbm.bottom_edge, pbm.top_edge, pbm.left_edge, pbm.right_edge); */
rs->src.top = pbm.top_edge;
rs->src.bottom = pbm.bottom_edge + 1;
rs->src.left = pbm.left_edge;
rs->src.right = pbm.right_edge + 1;
rs->dest.left = (int)(rs->x + 2);
positions[i].x_advance = (pbm.right_edge - pbm.left_edge + 2) * 64;
unsigned main_baseline = font_units_to_pixels_y(main_face.freetype, main_face.freetype->ascender);
unsigned symbol_height = pbm.bottom_edge - pbm.top_edge;
unsigned baseline_y = main_baseline + rs->y_offset, text_bottom_y = text_height + rs->y_offset;
if (symbol_height <= baseline_y) {
rs->dest.top = baseline_y - symbol_height + 2;
} else {
if (symbol_height <= text_bottom_y) rs->dest.top = text_bottom_y - symbol_height;
else rs->dest.top = 0;
}
rs->dest.top += main_baseline > pbm.bottom_edge ? main_baseline - pbm.bottom_edge : 0;
/* printf("symbol_height: %u baseline_y: %u\n", symbol_height, baseline_y); */
}
render_color_bitmap(&pbm, rs);
free(buf);
} break;
case FT_PIXEL_MODE_MONO: {
FT_Bitmap bitmap;
freetype_convert_mono_bitmap(&face->glyph->bitmap, &bitmap);
populate_processed_bitmap(face->glyph, &bitmap, &pbm);
setup_regions(&pbm, rs, baseline);
render_gray_bitmap(&pbm, rs);
FT_Bitmap_Done(freetype_library(), &bitmap);
} break;
case FT_PIXEL_MODE_GRAY:
populate_processed_bitmap(face->glyph, &face->glyph->bitmap, &pbm);
setup_regions(&pbm, rs, baseline);
render_gray_bitmap(&pbm, rs);
break;
default:
PyErr_Format(PyExc_TypeError, "Unknown FreeType bitmap type: 0x%x", face->glyph->bitmap.pixel_mode);
return false;
break;
}
rs->x += (float)positions[i].x_advance / 64.0f;
}
return true;
}
static bool
process_codepoint(RenderCtx *ctx, RenderState *rs, char_type codep, char_type next_codep) {
bool add_to_current_buffer = false;
Face *fallback_font = NULL;
if (char_props_for(codep).is_combining_char) {
add_to_current_buffer = true;
} else if (glyph_id_for_codepoint(&main_face, codep) > 0) {
add_to_current_buffer = rs->current_face == &main_face;
if (!add_to_current_buffer) fallback_font = &main_face;
} else {
if (glyph_id_for_codepoint(rs->current_face, codep) > 0) fallback_font = rs->current_face;
else fallback_font = find_fallback_font_for(ctx, codep, next_codep);
add_to_current_buffer = !fallback_font || rs->current_face == fallback_font;
}
if (!add_to_current_buffer) {
if (rs->pending_in_buffer) {
if (!render_run(ctx, rs)) return false;
rs->pending_in_buffer = 0;
hb_buffer_clear_contents(hb_buffer);
}
if (fallback_font) rs->current_face = fallback_font;
}
hb_buffer_add_utf32(hb_buffer, &codep, 1, 0, 1);
rs->pending_in_buffer += 1;
return true;
}
bool
render_single_line(
FreeTypeRenderCtx ctx_,
const char *text,
unsigned sz_px,
pixel fg,
pixel bg,
uint8_t *output_buf,
size_t width,
size_t height,
float x_offset,
float y_offset,
size_t right_margin,
bool horizontally_center_runs) {
RenderCtx *ctx = (RenderCtx *)ctx_;
if (!ctx->created) return false;
size_t output_width = right_margin <= width ? width - right_margin : 0;
bool has_text = text && text[0];
pixel pbg = premult_pixel(bg, ((bg >> 24) & 0xff));
for (size_t y = 0; y < height; y++) {
pixel *px = (pixel *)(output_buf + 4 * y * width);
for (size_t x = (size_t)x_offset; x < output_width; x++) px[x] = pbg;
}
if (!has_text) return true;
hb_buffer_clear_contents(hb_buffer);
if (!hb_buffer_pre_allocate(hb_buffer, 512)) {
PyErr_NoMemory();
return false;
}
size_t text_len = strlen(text);
char_type *unicode = calloc(text_len + 1, sizeof(char_type));
if (!unicode) {
PyErr_NoMemory();
return false;
}
bool ok = false;
text_len = decode_utf8_string(text, text_len, unicode);
set_pixel_size(ctx, &main_face, sz_px, true);
unsigned text_height = font_units_to_pixels_y(main_face.freetype, main_face.freetype->height);
RenderState rs = {
.current_face = &main_face,
.fg = fg,
.bg = bg,
.horizontally_center = horizontally_center_runs,
.output_width = output_width,
.output_height = height,
.stride = width,
.output = (pixel *)output_buf,
.x = x_offset,
.y = y_offset,
.sz_px = sz_px};
if (text_height < height) rs.y_offset = (height - text_height) / 2;
for (size_t i = 0; i < text_len && rs.x < rs.output_width && !rs.truncated; i++) {
if (!process_codepoint(ctx, &rs, unicode[i], unicode[i + 1])) goto end;
}
if (rs.pending_in_buffer && rs.x < rs.output_width && !rs.truncated) {
if (!render_run(ctx, &rs)) goto end;
rs.pending_in_buffer = 0;
hb_buffer_clear_contents(hb_buffer);
}
if (rs.truncated) {
hb_buffer_clear_contents(hb_buffer);
rs.pending_in_buffer = 0;
rs.current_face = &main_face;
if (!process_codepoint(ctx, &rs, ELLIPSIS, 0)) goto end;
if (!render_run(ctx, &rs)) goto end;
}
ok = true;
end:
free(unicode);
return ok;
}
size_t
freetype_text_width_for_single_line(FreeTypeRenderCtx ctx_, const char *text, unsigned sz_px) {
RenderCtx *ctx = (RenderCtx *)ctx_;
if (!ctx->created) return 0;
bool has_text = text && text[0];
if (!has_text) return 0;
hb_buffer_clear_contents(hb_buffer);
if (!hb_buffer_pre_allocate(hb_buffer, 512)) {
PyErr_NoMemory();
return 0;
}
size_t text_len = strlen(text);
char_type *unicode = calloc(text_len + 1, sizeof(char_type));
if (!unicode) {
PyErr_NoMemory();
return 0;
}
text_len = decode_utf8_string(text, text_len, unicode);
set_pixel_size(ctx, &main_face, sz_px, true);
// Use a very large output_width so nothing is truncated
RenderState rs = {
.current_face = &main_face,
.fg = 0,
.bg = 0,
.horizontally_center = false,
.output_width = SIZE_MAX,
.output_height = 0,
.stride = 0,
.output = NULL,
.x = 0,
.y = 0,
.sz_px = sz_px};
for (size_t i = 0; i < text_len; i++) {
bool add_to_current_buffer = false;
char_type codep = unicode[i];
char_type next_codep = unicode[i + 1];
Face *fallback_font = NULL;
if (char_props_for(codep).is_combining_char) {
add_to_current_buffer = true;
} else if (glyph_id_for_codepoint(&main_face, codep) > 0) {
add_to_current_buffer = rs.current_face == &main_face;
if (!add_to_current_buffer) fallback_font = &main_face;
} else {
if (glyph_id_for_codepoint(rs.current_face, codep) > 0) fallback_font = rs.current_face;
else fallback_font = find_fallback_font_for(ctx, codep, next_codep);
add_to_current_buffer = !fallback_font || rs.current_face == fallback_font;
}
if (!add_to_current_buffer) {
if (rs.pending_in_buffer) {
// Shape the current run and accumulate width
hb_buffer_guess_segment_properties(hb_buffer);
set_pixel_size(ctx, rs.current_face, sz_px, false);
hb_shape(rs.current_face->hb, hb_buffer, NULL, 0);
unsigned int len = hb_buffer_get_length(hb_buffer);
hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(hb_buffer, NULL);
for (unsigned int j = 0; j < len; j++) { rs.x += (float)positions[j].x_offset / 64.0f + (float)positions[j].x_advance / 64.0f; }
rs.pending_in_buffer = 0;
hb_buffer_clear_contents(hb_buffer);
}
if (fallback_font) rs.current_face = fallback_font;
}
hb_buffer_add_utf32(hb_buffer, &codep, 1, 0, 1);
rs.pending_in_buffer += 1;
}
if (rs.pending_in_buffer) {
hb_buffer_guess_segment_properties(hb_buffer);
set_pixel_size(ctx, rs.current_face, sz_px, false);
hb_shape(rs.current_face->hb, hb_buffer, NULL, 0);
unsigned int len = hb_buffer_get_length(hb_buffer);
hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(hb_buffer, NULL);
for (unsigned int j = 0; j < len; j++) { rs.x += (float)positions[j].x_offset / 64.0f + (float)positions[j].x_advance / 64.0f; }
hb_buffer_clear_contents(hb_buffer);
}
free(unicode);
return (size_t)ceilf(rs.x);
}
static uint8_t *
render_single_char_bitmap(const FT_Bitmap *bm, size_t *result_width, size_t *result_height) {
*result_width = bm->width;
*result_height = bm->rows;
uint8_t *rendered = malloc(*result_width * *result_height);
if (!rendered) {
PyErr_NoMemory();
return NULL;
}
for (size_t r = 0; r < bm->rows; r++) {
uint8_t *src_row = bm->buffer + bm->pitch * r;
uint8_t *dest_row = rendered + *result_width * r;
memcpy(dest_row, src_row, *result_width);
}
return rendered;
}
typedef struct TempFontData {
Face *face;
FT_UInt orig_sz;
} TempFontData;
static void
cleanup_resize(TempFontData *f) {
if (f->face && f->face->freetype) {
f->face->pixel_size = f->orig_sz;
FT_Set_Pixel_Sizes(f->face->freetype, f->orig_sz, f->orig_sz);
}
}
#define RAII_TempFontData(name) __attribute__((cleanup(cleanup_resize))) TempFontData name = {0}
static void *
report_freetype_error_for_char(int error, char ch, const char *operation) {
char buf[128];
snprintf(buf, sizeof(buf), "Failed to %s glyph for character: %c, with error: ", operation, ch);
set_freetype_error(buf, error);
return NULL;
}
uint8_t *
render_single_ascii_char_as_mask(FreeTypeRenderCtx ctx_, const char ch, size_t *result_width, size_t *result_height) {
RenderCtx *ctx = (RenderCtx *)ctx_;
if (!ctx->created) {
PyErr_SetString(PyExc_RuntimeError, "freetype render ctx not created");
return NULL;
}
size_t avail_height = *result_height;
if (avail_height < 4) {
PyErr_Format(PyExc_ValueError, "Invalid available height: %zu", avail_height);
return NULL;
}
Face *face = &main_face;
RAII_TempFontData(temp);
temp.face = face;
temp.orig_sz = face->pixel_size;
set_pixel_size(ctx, face, avail_height, false);
int glyph_index = FT_Get_Char_Index(face->freetype, ch);
if (!glyph_index) {
PyErr_Format(PyExc_KeyError, "character %c not found in font", ch);
return NULL;
}
unsigned int height = font_units_to_pixels_y(face->freetype, face->freetype->height);
float ratio = ((float)height) / avail_height;
face->pixel_size = (FT_UInt)(face->pixel_size / ratio);
if (face->pixel_size != temp.orig_sz) FT_Set_Pixel_Sizes(face->freetype, avail_height, avail_height);
int error = FT_Load_Glyph(face->freetype, glyph_index, get_load_flags(face->hinting, face->hintstyle, FT_LOAD_DEFAULT));
if (error) return report_freetype_error_for_char(error, ch, "load");
if (face->freetype->glyph->format != FT_GLYPH_FORMAT_BITMAP) {
error = FT_Render_Glyph(face->freetype->glyph, FT_RENDER_MODE_NORMAL);
if (error) return report_freetype_error_for_char(error, ch, "render");
}
uint8_t *rendered = NULL;
switch (face->freetype->glyph->bitmap.pixel_mode) {
case FT_PIXEL_MODE_MONO: {
FT_Bitmap bitmap;
if (!freetype_convert_mono_bitmap(&face->freetype->glyph->bitmap, &bitmap)) return NULL;
rendered = render_single_char_bitmap(&bitmap, result_width, result_height);
FT_Bitmap_Done(freetype_library(), &bitmap);
} break;
case FT_PIXEL_MODE_GRAY: rendered = render_single_char_bitmap(&face->freetype->glyph->bitmap, result_width, result_height); break;
default: PyErr_Format(PyExc_TypeError, "Unknown FreeType bitmap type: 0x%x", face->freetype->glyph->bitmap.pixel_mode); break;
}
return rendered;
}
FreeTypeRenderCtx
create_freetype_render_context(const char *family, bool bold, bool italic) {
RenderCtx *ctx = calloc(1, sizeof(RenderCtx));
if (!ctx) {
PyErr_NoMemory();
return NULL;
}
main_face_family.name = family ? strdup(family) : NULL;
main_face_family.bold = bold;
main_face_family.italic = italic;
if (!information_for_font_family(main_face_family.name, main_face_family.bold, main_face_family.italic, &main_face_information) ||
!load_font(&main_face_information, &main_face)) {
release_freetype_render_context((FreeTypeRenderCtx)ctx);
return NULL;
}
hb_buffer = hb_buffer_create();
if (!hb_buffer) {
PyErr_NoMemory();
release_freetype_render_context((FreeTypeRenderCtx)ctx);
return NULL;
}
ctx->created = true;
return (FreeTypeRenderCtx)ctx;
}
void
release_freetype_render_context(FreeTypeRenderCtx ctx) {
if (ctx) {
cleanup((RenderCtx *)ctx);
free(ctx);
}
}
static PyObject *
render_line(PyObject *self UNUSED, PyObject *args, PyObject *kw) {
// use for testing as below
// kitty +runpy "from kitty.fast_data_types import *; open('/tmp/test.rgba', 'wb').write(freetype_render_line())" && magick -size 800x60 -depth 8
// /tmp/test.rgba /tmp/test.png && icat /tmp/test.png
const char *text = "Test 猫 H🐱🚀b r\U000f0320endering with ellipsis for cut off text", *family = NULL;
unsigned int width = 800, height = 60, right_margin = 0;
int bold = 0, italic = 0;
unsigned long fg = 0, bg = 0xfffefefe;
float x_offset = 0, y_offset = 0;
static const char *kwlist[] = {"text", "width", "height", "font_family", "bold", "italic", "fg", "bg", "x_offset", "y_offset", "right_margin", NULL};
if (!PyArg_ParseTupleAndKeywords(
args, kw, "|sIIzppkkffI", (char **)kwlist, &text, &width, &height, &family, &bold, &italic, &fg, &bg, &x_offset, &y_offset, &right_margin))
return NULL;
PyObject *ans = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)width * height * 4);
if (!ans) return NULL;
uint8_t *buffer = (uint8_t *)PyBytes_AS_STRING(ans);
RenderCtx *ctx = (RenderCtx *)create_freetype_render_context(family, bold, italic);
if (!ctx) return NULL;
if (!render_single_line((FreeTypeRenderCtx)ctx, text, 3 * height / 4, 0, 0xffffffff, buffer, width, height, x_offset, y_offset, right_margin, false)) {
Py_CLEAR(ans);
if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "Unknown error while rendering text");
ans = NULL;
} else {
// remove pre-multiplication and convert to ABGR which is what the ImageMagick .rgba filetype wants
for (pixel *p = (pixel *)buffer, *end = (pixel *)(buffer + PyBytes_GET_SIZE(ans)); p < end; p++) {
const uint16_t a = (*p >> 24) & 0xff;
if (!a) continue;
uint16_t r = (*p >> 16) & 0xff, g = (*p >> 8) & 0xff, b = *p & 0xff;
#define c(x) (((x * 255) / a))
*p = ARGB(a, c(b), c(g), c(r));
#undef c
}
}
release_freetype_render_context((FreeTypeRenderCtx)ctx);
return ans;
}
static PyObject *
path_for_font(PyObject *self UNUSED, PyObject *args) {
const char *family = NULL;
int bold = 0, italic = 0;
if (!PyArg_ParseTuple(args, "|zpp", &family, &bold, &italic)) return NULL;
FontConfigFace f;
if (!information_for_font_family(family, bold, italic, &f)) return NULL;
PyObject *ret = Py_BuildValue("{ss si si si}", "path", f.path, "index", f.index, "hinting", f.hinting, "hintstyle", f.hintstyle);
free(f.path);
return ret;
}
static PyObject *
fallback_for_char(PyObject *self UNUSED, PyObject *args) {
const char *family = NULL;
int bold = 0, italic = 0;
unsigned int ch;
if (!PyArg_ParseTuple(args, "I|zpp", &ch, &family, &bold, &italic)) return NULL;
FontConfigFace f;
if (!fallback_font(ch, family, bold, italic, false, &f)) return NULL;
PyObject *ret = Py_BuildValue("{ss si si si}", "path", f.path, "index", f.index, "hinting", f.hinting, "hintstyle", f.hintstyle);
free(f.path);
return ret;
}
static PyMethodDef module_methods[] = {
{"fontconfig_path_for_font", (PyCFunction)(void (*)(void))(path_for_font), METH_VARARGS, NULL},
{"fontconfig_fallback_for_char", (PyCFunction)(void (*)(void))(fallback_for_char), METH_VARARGS, NULL},
{"freetype_render_line", (PyCFunction)(void (*)(void))(render_line), METH_VARARGS | METH_KEYWORDS, NULL},
{NULL, NULL, 0, NULL} /* Sentinel */
};
bool
init_freetype_render_ui_text(PyObject *module) {
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
return true;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include <hb-ft.h>
typedef struct {
bool created;
} *FreeTypeRenderCtx;
FreeTypeRenderCtx create_freetype_render_context(const char *family, bool bold, bool italic);
void set_main_face_family(FreeTypeRenderCtx ctx, const char *family, bool bold, bool italic);
bool render_single_line(
FreeTypeRenderCtx ctx,
const char *text,
unsigned sz_px,
uint32_t fg,
uint32_t bg,
uint8_t *output_buf,
size_t width,
size_t height,
float x_offset,
float y_offset,
size_t right_margin,
bool horizontally_center_runs);
size_t freetype_text_width_for_single_line(FreeTypeRenderCtx ctx, const char *text, unsigned sz_px);
uint8_t *render_single_ascii_char_as_mask(FreeTypeRenderCtx ctx_, const char ch, size_t *result_width, size_t *result_height);
void release_freetype_render_context(FreeTypeRenderCtx ctx);
typedef struct FontConfigFace {
char *path;
int index;
int hinting;
int hintstyle;
} FontConfigFace;
bool information_for_font_family(const char *family, bool bold, bool italic, FontConfigFace *ans);
FT_Face native_face_from_path(const char *path, int index);
bool fallback_font(char_type ch, const char *family, bool bold, bool italic, bool prefer_color, FontConfigFace *ans);
bool freetype_convert_mono_bitmap(FT_Bitmap *src, FT_Bitmap *dest);
FT_Library freetype_library(void);
void set_freetype_error(const char *prefix, int err_code);
int
downsample_32bit_image(uint8_t *src, unsigned src_width, unsigned src_height, unsigned src_stride, uint8_t *dest, unsigned dest_width, unsigned dest_height);
+2
View File
@@ -0,0 +1,2 @@
#define GLAD_GL_IMPLEMENTATION
#include "gl-wrapper.h"
+11508
View File
File diff suppressed because it is too large. Load diff
+740
View File
@@ -0,0 +1,740 @@
/*
* gl.c
* Copyright (C) 2019 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "gl.h"
#include <string.h>
#include <stddef.h>
#include "glfw-wrapper.h"
#include "state.h"
#include "png-reader.h"
// GL setup and error handling {{{
static void
check_for_gl_error(void UNUSED *ret, const char *name, GLADapiproc UNUSED funcptr, int UNUSED len_args, ...) {
#define f(msg) \
fatal("OpenGL error: %s (calling function: %s)", msg, name); \
break;
GLenum code = glad_glGetError();
switch (code) {
case GL_NO_ERROR: break;
case GL_INVALID_ENUM: f("An enum value is invalid (GL_INVALID_ENUM)");
case GL_INVALID_VALUE: f("An numeric value is invalid (GL_INVALID_VALUE)");
case GL_INVALID_OPERATION: f("This operation is invalid (GL_INVALID_OPERATION)");
case GL_INVALID_FRAMEBUFFER_OPERATION: f("The framebuffer object is not complete (GL_INVALID_FRAMEBUFFER_OPERATION)");
case GL_OUT_OF_MEMORY: f("There is not enough memory left to execute the command. (GL_OUT_OF_MEMORY)");
case GL_STACK_UNDERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to underflow. (GL_STACK_UNDERFLOW)");
case GL_STACK_OVERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to overflow. (GL_STACK_OVERFLOW)");
default: fatal("An unknown OpenGL error occurred with code: %d (calling function: %s)", code, name); break;
}
}
const char *
gl_version_string(void) {
static char buf[256];
int gl_major = GLAD_VERSION_MAJOR(global_state.gl_version);
int gl_minor = GLAD_VERSION_MINOR(global_state.gl_version);
const char *gvs = (const char *)glGetString(GL_VERSION);
snprintf(buf, sizeof(buf), "'%s' Detected version: %d.%d", gvs, gl_major, gl_minor);
return buf;
}
void
gl_init(void) {
static bool glad_loaded = false;
if (!glad_loaded) {
global_state.gl_version = gladLoadGL(glfwGetProcAddress);
if (!global_state.gl_version) { fatal("Loading the OpenGL library failed"); }
if (!global_state.debug_rendering) { gladUninstallGLDebug(); }
gladSetGLPostCallback(check_for_gl_error);
#define ARB_TEST(name) \
if (!GLAD_GL_ARB_##name) { fatal("The OpenGL driver on this system is missing the required extension: ARB_%s", #name); }
ARB_TEST(texture_storage);
#undef ARB_TEST
#ifdef __APPLE__
// See nsgl_context.m srgb is always supported on macOS but its OpenGL
// drivers dont report the extensions, so hardcode to true.
global_state.supports_framebuffer_srgb = true;
#else
global_state.supports_framebuffer_srgb = (GLAD_GL_ARB_framebuffer_sRGB + GLAD_GL_EXT_framebuffer_sRGB) != 0;
#endif
glad_loaded = true;
int gl_major = GLAD_VERSION_MAJOR(global_state.gl_version);
int gl_minor = GLAD_VERSION_MINOR(global_state.gl_version);
if (global_state.debug_rendering) printf("[%.3f] GL version string: %s\n", monotonic_t_to_s_double(monotonic()), gl_version_string());
if (gl_major < OPENGL_REQUIRED_VERSION_MAJOR || (gl_major == OPENGL_REQUIRED_VERSION_MAJOR && gl_minor < OPENGL_REQUIRED_VERSION_MINOR)) {
fatal(
"OpenGL version is %d.%d, version >= %d.%d required for kitty",
gl_major,
gl_minor,
OPENGL_REQUIRED_VERSION_MAJOR,
OPENGL_REQUIRED_VERSION_MINOR);
}
}
}
const char *
check_framebuffer_status(void) {
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
switch (status) {
case GL_FRAMEBUFFER_COMPLETE: return NULL;
case GL_FRAMEBUFFER_UNDEFINED: return ("GL_FRAMEBUFFER_UNDEFINED");
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return ("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return ("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return ("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER");
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return ("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER");
case GL_FRAMEBUFFER_UNSUPPORTED: return ("GL_FRAMEBUFFER_UNSUPPORTED");
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return ("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE");
default: return ("Unknown error");
}
}
void
free_texture(GLuint *tex_id) {
glDeleteTextures(1, tex_id);
*tex_id = 0;
}
void
free_framebuffer(GLuint *fb_id) {
glDeleteFramebuffers(1, fb_id);
*fb_id = 0;
}
static GLuint output_framebuffer = 0;
void
bind_framebuffer_for_output(unsigned fbid) {
glBindFramebuffer(GL_FRAMEBUFFER, fbid ? fbid : output_framebuffer);
}
void
set_framebuffer_to_use_for_output(unsigned fbid) {
output_framebuffer = fbid;
}
static void
set_blending(bool allowed) {
if (allowed) {
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} // blending of pre-multiplied colors
else {
glDisable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ZERO);
} // no blending
}
void
draw_quad(bool blend, unsigned instance_count) {
set_blending(blend);
if (instance_count) glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, instance_count);
else glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
static struct {
GLsizei items[16][4];
size_t used;
} saved_viewports;
void
set_gpu_viewport(unsigned w, unsigned h) {
glViewport(0, 0, w, h);
}
Viewport
get_gpu_viewport(void) {
GLsizei v[4];
glGetIntegerv(GL_VIEWPORT, v);
return (Viewport){.left = v[0], .top = v[1], .width = v[2], .height = v[3]};
}
void
save_viewport_using_bottom_left_origin(GLsizei newx, GLsizei newy, GLsizei width, GLsizei height) {
if (saved_viewports.used >= arraysz(saved_viewports.items)) fatal("Too many nested saved viewports");
GLsizei *saved_viewport = saved_viewports.items[saved_viewports.used++];
glGetIntegerv(GL_VIEWPORT, saved_viewport);
glViewport(newx, newy, width, height);
}
void
save_viewport_using_top_left_origin(GLsizei newx, GLsizei newy, GLsizei width, GLsizei height, GLsizei full_framebuffer_height) {
// Converts the viewport defined by the specified arguments which are
// assumed to be in the usual co-ord system with origin at top left to the
// OpenGL viewport co-ord system with origin at bottom left.
// Use restore_viewport() to restore the viewport to what it was before.
if (saved_viewports.used >= arraysz(saved_viewports.items)) fatal("Too many nested saved viewports");
GLsizei *saved_viewport = saved_viewports.items[saved_viewports.used++];
glGetIntegerv(GL_VIEWPORT, saved_viewport);
newy = full_framebuffer_height - (newy + height);
glViewport(newx, newy, width, height);
}
void
restore_viewport(void) {
if (!saved_viewports.used) fatal("Trying to restore a viewport when none is saved");
GLsizei *saved_viewport = saved_viewports.items[--saved_viewports.used];
glViewport(saved_viewport[0], saved_viewport[1], saved_viewport[2], saved_viewport[3]);
}
void
enable_scissor_using_top_left_origin(Viewport vp, unsigned full_framebuffer_height) {
glEnable(GL_SCISSOR_TEST);
GLsizei newy = full_framebuffer_height - (vp.top + vp.height);
glScissor(vp.left, newy, vp.width, vp.height);
}
void
disable_scissor(void) {
glDisable(GL_SCISSOR_TEST);
}
static float
linear_to_srgb(float c) {
return (c <= 0.0031308f) ? 12.92f * c : 1.055f * powf(c, 1.0f / 2.4f) - 0.055f;
}
void
save_texture_as_png(uint32_t texture_id, const char *filename) {
GLint prev_tex = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &prev_tex);
glBindTexture(GL_TEXTURE_2D, texture_id);
int width = 0, height = 0;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
size_t sz = sizeof(uint32_t) * width * height;
uint32_t *data = malloc(sz);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
// assume data is linear and pre-multiplied
for (int i = 0; i < width * height; i++) {
uint32_t px = data[i];
uint8_t r = (px >> 0) & 0xFF;
uint8_t g = (px >> 8) & 0xFF;
uint8_t b = (px >> 16) & 0xFF;
uint8_t a = (px >> 24) & 0xFF;
float alpha = a / 255.0f;
float rf = 0, gf = 0, bf = 0;
if (alpha > 0.0f) {
rf = (r / 255.0f) / alpha;
gf = (g / 255.0f) / alpha;
bf = (b / 255.0f) / alpha;
}
rf = linear_to_srgb(rf);
gf = linear_to_srgb(gf);
bf = linear_to_srgb(bf);
r = (uint8_t)(rf * 255);
g = (uint8_t)(gf * 255);
b = (uint8_t)(bf * 255);
data[i] = (r << 0) | (g << 8) | (b << 16) | (a << 24);
}
const char *png = png_from_32bit_rgba((char *)data, width, height, &sz, true);
if (!sz) fatal("Failed to save PNG to %s with error: %s", filename, png);
free(data);
FILE *file = fopen(filename, "wb");
fwrite(png, 1, sz, file);
fclose(file);
glBindTexture(GL_TEXTURE_2D, prev_tex);
}
// }}}
// Programs {{{
static Program programs[64] = {{0}};
GLuint
compile_shaders(GLenum shader_type, GLsizei count, const GLchar *const *source) {
GLuint shader_id = glCreateShader(shader_type);
glShaderSource(shader_id, count, source, NULL);
glCompileShader(shader_id);
GLint ret = GL_FALSE;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &ret);
if (ret != GL_TRUE) {
GLsizei len;
static char glbuf[4096];
glGetShaderInfoLog(shader_id, sizeof(glbuf), &len, glbuf);
glDeleteShader(shader_id);
const char *shader_type_name = "unknown_type";
switch (shader_type) {
case GL_VERTEX_SHADER: shader_type_name = "vertex"; break;
case GL_FRAGMENT_SHADER: shader_type_name = "fragment"; break;
}
PyErr_Format(PyExc_ValueError, "Failed to compile GLSL %s shader:\n%s", shader_type_name, glbuf);
return 0;
}
return shader_id;
}
Program *
program_ptr(int program) {
return programs + (size_t)program;
}
GLuint
program_id(int program) {
return programs[program].id;
}
void
init_uniforms(int program) {
Program *p = programs + program;
glGetProgramiv(p->id, GL_ACTIVE_UNIFORMS, &(p->num_of_uniforms));
for (GLint i = 0; i < p->num_of_uniforms; i++) {
Uniform *u = p->uniforms + i;
glGetActiveUniform(p->id, (GLuint)i, sizeof(u->name) / sizeof(u->name[0]), NULL, &(u->size), &(u->type), u->name);
char *l = strchr(u->name, '[');
if (l) *l = 0;
u->location = glGetUniformLocation(p->id, u->name);
u->idx = i;
}
}
GLint
get_uniform_location(int program, const char *name) {
Program *p = programs + program;
const size_t n = strlen(name) + 1;
for (GLint i = 0; i < p->num_of_uniforms; i++) {
Uniform *u = p->uniforms + i;
if (strncmp(u->name, name, n) == 0) return u->location;
}
return -1;
}
GLint
get_uniform_information(int program, const char *name, GLenum information_type) {
GLint q;
GLuint t;
const char *names[] = {""};
names[0] = name;
GLuint pid = program_id(program);
glGetUniformIndices(pid, 1, (void *)names, &t);
glGetActiveUniformsiv(pid, 1, &t, information_type, &q);
return q;
}
ArrayInformation
get_uniform_array_information(int program, const char *name) {
ArrayInformation ans;
const char *names[] = {""};
names[0] = name;
GLuint pid = program_id(program);
GLuint t;
glGetUniformIndices(pid, 1, (void *)names, &t);
if (t == GL_INVALID_INDEX) { fatal("Could not find the index for uniform array: %s", name); }
glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_ARRAY_STRIDE, &ans.stride);
glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_OFFSET, &ans.offset);
glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_SIZE, &ans.size);
return ans;
}
GLint
attrib_location(int program, const char *name) {
GLint ans = glGetAttribLocation(programs[program].id, name);
return ans;
}
GLuint
block_index(int program, const char *name) {
GLuint ans = glGetUniformBlockIndex(programs[program].id, name);
if (ans == GL_INVALID_INDEX) { fatal("Could not find block index for %s", name); }
return ans;
}
GLint
block_size(int program, GLuint block_index) {
GLint ans;
glGetActiveUniformBlockiv(programs[program].id, block_index, GL_UNIFORM_BLOCK_DATA_SIZE, &ans);
return ans;
}
// Program metadata (uniform/attribute locations and UBO/array info, looked up by name) {{{
#define NAME program_metadata_map
#define KEY_TY const char *
#define VAL_TY ProgramMetadataEntry
#include "kitty-verstable.h"
static program_metadata_map program_layouts[arraysz(programs)];
static bool program_layouts_initialized[arraysz(programs)] = {0};
static void
clear_program_layout(int program) {
if (!program_layouts_initialized[program]) return;
program_metadata_map *m = program_layouts + program;
vt_create_for_loop(program_metadata_map_itr, itr, m) free((void *)itr.data->key);
vt_cleanup(m);
program_layouts_initialized[program] = false;
}
void
free_program_layouts(void) {
for (size_t i = 0; i < arraysz(program_layouts); i++) clear_program_layout((int)i);
}
static void
insert_program_metadata(int program, const char *name, ProgramMetadataEntry entry) {
program_metadata_map_itr itr = vt_insert(program_layouts + program, strdup(name), entry);
if (vt_is_end(itr)) fatal("Out of memory adding program metadata entry: %s", name);
}
static ProgramMetadataEntry *
program_metadata_entry(int program, const char *name, ProgramMetadataKind expected) {
program_metadata_map_itr itr = vt_get(program_layouts + program, name);
if (vt_is_end(itr)) fatal("No metadata entry named: %s for program: %d", name, program);
if (itr.data->val.kind != expected) fatal("The metadata entry named: %s for program: %d is not of the expected kind", name, program);
return &itr.data->val;
}
void
set_program_layout(int program, PyObject *metadata) {
clear_program_layout(program);
vt_init(program_layouts + program);
program_layouts_initialized[program] = true;
PyObject *key, *val;
Py_ssize_t pos;
PyObject *loose_uniforms = PyDict_GetItemString(metadata, "loose_uniforms");
pos = 0;
while (PyDict_Next(loose_uniforms, &pos, &key, &val)) {
const char *actual_name = PyUnicode_AsUTF8(val);
// The metadata records array uniforms with a [0] subscript to mark them
// as arrays, but init_uniforms() stores them under their bare name.
char without_subscript[256];
const char *bracket = strchr(actual_name, '[');
if (bracket) {
size_t n = MIN(sizeof(without_subscript) - 1, (size_t)(bracket - actual_name));
memcpy(without_subscript, actual_name, n);
without_subscript[n] = 0;
actual_name = without_subscript;
}
ProgramMetadataEntry e = {.kind = PROGRAM_UNIFORM, .location = get_uniform_location(program, actual_name)};
insert_program_metadata(program, PyUnicode_AsUTF8(key), e);
}
PyObject *input_locations = PyDict_GetItemString(metadata, "input_locations");
pos = 0;
while (PyDict_Next(input_locations, &pos, &key, &val)) {
ProgramMetadataEntry e = {.kind = PROGRAM_ATTRIBUTE, .location = (GLint)PyLong_AsLong(val)};
insert_program_metadata(program, PyUnicode_AsUTF8(key), e);
}
PyObject *uniform_structs = PyDict_GetItemString(metadata, "uniform_structs");
PyObject *uniform_struct_names = PyDict_GetItemString(metadata, "uniform_struct_names");
pos = 0;
while (PyDict_Next(uniform_structs, &pos, &key, &val)) {
const char *glsl_block_name = PyUnicode_AsUTF8(PyDict_GetItem(uniform_struct_names, key));
GLuint index = block_index(program, glsl_block_name);
ProgramMetadataEntry be = {.kind = PROGRAM_BLOCK, .block = {.size = block_size(program, index), .index = (GLint)index}};
insert_program_metadata(program, PyUnicode_AsUTF8(key), be);
PyObject *mkey, *mval;
Py_ssize_t mpos = 0;
while (PyDict_Next(val, &mpos, &mkey, &mval)) {
const char *decl = PyUnicode_AsUTF8(mval);
const char *bracket = strchr(decl, '[');
if (!bracket) continue; // scalar block members are hand-mirrored in C structs, not queried here
char actual_name[256];
size_t n = MIN(sizeof(actual_name) - 1, (size_t)(bracket - decl));
memcpy(actual_name, decl, n);
actual_name[n] = 0;
ProgramMetadataEntry ae = {.kind = PROGRAM_ARRAY, .array = get_uniform_array_information(program, actual_name)};
insert_program_metadata(program, PyUnicode_AsUTF8(mkey), ae);
}
}
}
GLint
program_uniform_location(int program, const char *name) {
ProgramMetadataEntry *e = program_metadata_entry(program, name, PROGRAM_UNIFORM);
// glUniform*() on location -1 is a silent no-op, so a uniform the driver
// does not report as active leaves whatever value it was last set to,
// rendering incorrectly with no other indication that anything is wrong.
if (e->location < 0 && !e->missing_location_logged) {
e->missing_location_logged = true;
log_error("The uniform: %s is not active in the linked GPU program: %d. Setting it will have no effect and rendering may be incorrect.", name, program);
}
return e->location;
}
GLint
try_program_uniform_location(int program, const char *name) {
program_metadata_map_itr itr = vt_get(program_layouts + program, name);
if (vt_is_end(itr) || itr.data->val.kind != PROGRAM_UNIFORM) return -1;
return itr.data->val.location;
}
GLint
program_attribute_location(int program, const char *name) {
return program_metadata_entry(program, name, PROGRAM_ATTRIBUTE)->location;
}
UniformBlock
program_uniform_block(int program, const char *name) {
return program_metadata_entry(program, name, PROGRAM_BLOCK)->block;
}
ArrayInformation
program_uniform_array(int program, const char *name) {
return program_metadata_entry(program, name, PROGRAM_ARRAY)->array;
}
// }}}
void
bind_program(int program) {
glUseProgram(programs[program].id);
}
void
unbind_program(void) {
glUseProgram(0);
}
// }}}
// Buffers {{{
typedef struct {
GLuint id;
GLsizeiptr size;
GLenum usage;
} Buffer;
static Buffer buffers[MAX_CHILDREN * 6 + 4] = {{0}};
static ssize_t
create_buffer(GLenum usage) {
GLuint buffer_id;
glGenBuffers(1, &buffer_id);
for (size_t i = 0; i < sizeof(buffers) / sizeof(buffers[0]); i++) {
if (buffers[i].id == 0) {
buffers[i].id = buffer_id;
buffers[i].size = 0;
buffers[i].usage = usage;
return i;
}
}
glDeleteBuffers(1, &buffer_id);
fatal("Too many buffers");
return -1;
}
static void
delete_buffer(ssize_t buf_idx) {
glDeleteBuffers(1, &(buffers[buf_idx].id));
buffers[buf_idx].id = 0;
buffers[buf_idx].size = 0;
}
static GLuint
bind_buffer(ssize_t buf_idx) {
glBindBuffer(buffers[buf_idx].usage, buffers[buf_idx].id);
return buffers[buf_idx].id;
}
static void
unbind_buffer(ssize_t buf_idx) {
glBindBuffer(buffers[buf_idx].usage, 0);
}
static void
alloc_buffer(ssize_t idx, GLsizeiptr size, GLenum usage) {
Buffer *b = buffers + idx;
if (b->size == size) return;
b->size = size;
glBufferData(b->usage, size, NULL, usage);
}
static void *
map_buffer(ssize_t idx, GLenum access) {
void *ans = glMapBuffer(buffers[idx].usage, access);
return ans;
}
static void *
map_buffer_range(ssize_t idx, GLbitfield access, int offset, unsigned size) {
return glMapBufferRange(buffers[idx].usage, offset, size, access);
}
static void
unmap_buffer(ssize_t idx) {
glUnmapBuffer(buffers[idx].usage);
}
// }}}
// Vertex Array Objects (VAO) {{{
typedef struct {
GLuint id;
size_t num_buffers;
ssize_t buffers[10];
} VAO;
static VAO vaos[4 * MAX_CHILDREN + 10] = {{0}};
ssize_t
create_vao(void) {
GLuint vao_id;
glGenVertexArrays(1, &vao_id);
for (size_t i = 0; i < sizeof(vaos) / sizeof(vaos[0]); i++) {
if (!vaos[i].id) {
vaos[i].id = vao_id;
vaos[i].num_buffers = 0;
glBindVertexArray(vao_id);
return i;
}
}
glDeleteVertexArrays(1, &vao_id);
fatal("Too many VAOs");
return -1;
}
size_t
add_buffer_to_vao(ssize_t vao_idx, GLenum usage) {
VAO *vao = vaos + vao_idx;
if (vao->num_buffers >= sizeof(vao->buffers) / sizeof(vao->buffers[0])) { fatal("Too many buffers in a single VAO"); }
ssize_t buf = create_buffer(usage);
vao->buffers[vao->num_buffers++] = buf;
return vao->num_buffers - 1;
}
static void
add_located_attribute_to_vao(ssize_t vao_idx, GLint aloc, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) {
VAO *vao = vaos + vao_idx;
if (!vao->num_buffers) fatal("You must create a buffer for this attribute first");
ssize_t buf = vao->buffers[vao->num_buffers - 1];
bind_buffer(buf);
glEnableVertexAttribArray(aloc);
switch (data_type) {
case GL_BYTE:
case GL_UNSIGNED_BYTE:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_INT:
case GL_UNSIGNED_INT: glVertexAttribIPointer(aloc, size, data_type, stride, offset); break;
default: glVertexAttribPointer(aloc, size, data_type, GL_FALSE, stride, offset); break;
}
if (divisor) { glVertexAttribDivisorARB(aloc, divisor); }
unbind_buffer(buf);
}
void
add_attribute_to_vao(ssize_t vao_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) {
add_located_attribute_to_vao(vao_idx, location, size, data_type, stride, offset, divisor);
}
void
set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) {
// (Re)configure an attribute pointer that reads from a specific buffer of
// the VAO (unlike add_attribute_to_vao which always uses the last added
// buffer). The VAO must be bound before calling this.
VAO *vao = vaos + vao_idx;
ssize_t buf = vao->buffers[buffer_idx];
bind_buffer(buf);
glEnableVertexAttribArray(location);
switch (data_type) {
case GL_BYTE:
case GL_UNSIGNED_BYTE:
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_INT:
case GL_UNSIGNED_INT: glVertexAttribIPointer(location, size, data_type, stride, offset); break;
default: glVertexAttribPointer(location, size, data_type, GL_FALSE, stride, offset); break;
}
glVertexAttribDivisorARB(location, divisor);
unbind_buffer(buf);
}
void
remove_vao(ssize_t vao_idx) {
VAO *vao = vaos + vao_idx;
while (vao->num_buffers) {
vao->num_buffers--;
delete_buffer(vao->buffers[vao->num_buffers]);
}
glDeleteVertexArrays(1, &(vao->id));
vaos[vao_idx].id = 0;
}
void
bind_vertex_array(ssize_t vao_idx) {
glBindVertexArray(vaos[vao_idx].id);
}
void
unbind_vertex_array(void) {
glBindVertexArray(0);
}
ssize_t
alloc_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum, GLenum usage) {
ssize_t buf_idx = vaos[vao_idx].buffers[bufnum];
bind_buffer(buf_idx);
alloc_buffer(buf_idx, size, usage);
return buf_idx;
}
void *
map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, int offset, unsigned size) {
ssize_t buf_idx = vaos[vao_idx].buffers[bufnum];
bind_buffer(buf_idx);
return map_buffer_range(buf_idx, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT, offset, size);
}
void *
alloc_and_map_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum) {
ssize_t buf_idx = alloc_vao_buffer(vao_idx, size, bufnum, GL_STATIC_DRAW);
return map_buffer(buf_idx, GL_WRITE_ONLY);
}
void *
alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, GLsizeiptr size, size_t bufnum) {
// The previous contents are discarded so the driver can hand out fresh
// storage instead of waiting for the GPU to finish reading the old data.
// The caller MUST write every byte of the mapped range, any byte not
// written is undefined.
ssize_t buf_idx = alloc_vao_buffer(vao_idx, size, bufnum, GL_STREAM_DRAW);
return map_buffer_range(buf_idx, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT, 0, (unsigned)size);
}
void
bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, GLuint block_index) {
ssize_t buf_idx = vaos[vao_idx].buffers[bufnum];
glBindBufferBase(GL_UNIFORM_BUFFER, block_index, buffers[buf_idx].id);
}
void
unmap_vao_buffer(ssize_t vao_idx, size_t bufnum) {
ssize_t buf_idx = vaos[vao_idx].buffers[bufnum];
unmap_buffer(buf_idx);
unbind_buffer(buf_idx);
}
void
copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, GLintptr src_off, size_t dst_bufnum, GLintptr dst_off, GLsizeiptr size) {
ssize_t src_buf = vaos[vao_idx].buffers[src_bufnum];
ssize_t dst_buf = vaos[vao_idx].buffers[dst_bufnum];
glBindBuffer(GL_COPY_READ_BUFFER, buffers[src_buf].id);
glBindBuffer(GL_COPY_WRITE_BUFFER, buffers[dst_buf].id);
glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, src_off, dst_off, size);
glBindBuffer(GL_COPY_READ_BUFFER, 0);
glBindBuffer(GL_COPY_WRITE_BUFFER, 0);
}
const void *
map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum) {
ssize_t buf_idx = vaos[vao_idx].buffers[bufnum];
bind_buffer(buf_idx);
return map_buffer(buf_idx, GL_READ_ONLY);
}
// }}}
+100
View File
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include "gl-wrapper.h"
typedef struct {
GLint size, index;
} UniformBlock;
typedef struct {
GLint offset; // byte offset from start of UBO
GLint stride; // element stride in bytes
GLint size; // umber of elements
} ArrayInformation;
typedef struct {
char name[256];
GLint size, location, idx;
GLenum type;
} Uniform;
typedef struct {
GLuint id;
Uniform uniforms[256];
GLint num_of_uniforms;
} Program;
typedef struct Viewport {
unsigned left, top, width, height;
} Viewport;
typedef enum { PROGRAM_UNIFORM, PROGRAM_ATTRIBUTE, PROGRAM_BLOCK, PROGRAM_ARRAY } ProgramMetadataKind;
typedef struct ProgramMetadataEntry {
ProgramMetadataKind kind;
bool missing_location_logged;
union {
GLint location;
UniformBlock block;
ArrayInformation array;
};
} ProgramMetadataEntry;
void gl_init(void);
const char *gl_version_string(void);
void set_gpu_viewport(unsigned w, unsigned h);
Viewport get_gpu_viewport(void);
void draw_quad(bool blend, unsigned instance_count);
void save_texture_as_png(uint32_t texture_id, const char *filename);
void free_texture(GLuint *tex_id);
void free_framebuffer(GLuint *fb_id);
void remove_vao(ssize_t vao_idx);
void init_uniforms(int program);
GLuint program_id(int program);
Program *program_ptr(int program);
GLuint block_index(int program, const char *name);
GLint block_size(int program, GLuint block_index);
GLint get_uniform_location(int program, const char *name);
GLint get_uniform_information(int program, const char *name, GLenum information_type);
ArrayInformation get_uniform_array_information(int program, const char *name);
GLint attrib_location(int program, const char *name);
void set_program_layout(int program, PyObject *metadata);
void free_program_layouts(void);
GLint program_uniform_location(int program, const char *name);
GLint try_program_uniform_location(int program, const char *name);
GLint program_attribute_location(int program, const char *name);
UniformBlock program_uniform_block(int program, const char *name);
ArrayInformation program_uniform_array(int program, const char *name);
ssize_t create_vao(void);
size_t add_buffer_to_vao(ssize_t vao_idx, GLenum usage);
void add_attribute_to_vao(ssize_t vao_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor);
void set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor);
ssize_t alloc_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum, GLenum usage);
void *alloc_and_map_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum);
// Discards the old contents, the caller must write every byte of the buffer
void *alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, GLsizeiptr size, size_t bufnum);
void unmap_vao_buffer(ssize_t vao_idx, size_t bufnum);
void *map_vao_buffer(ssize_t vao_idx, size_t bufnum, GLenum access);
void *map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, int offset, unsigned size);
void bind_program(int program);
void bind_vertex_array(ssize_t vao_idx);
void bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, GLuint block_index);
void copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, GLintptr src_off, size_t dst_bufnum, GLintptr dst_off, GLsizeiptr size);
const void *map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum);
void unbind_vertex_array(void);
void unbind_program(void);
GLuint compile_shaders(GLenum shader_type, GLsizei count, const GLchar *const *string);
void save_viewport_using_top_left_origin(GLsizei x, GLsizei y, GLsizei width, GLsizei height, GLsizei full_framebuffer_height);
void save_viewport_using_bottom_left_origin(GLsizei x, GLsizei y, GLsizei width, GLsizei height);
const char *check_framebuffer_status(void);
void restore_viewport(void);
void bind_framebuffer_for_output(unsigned fbid);
void set_framebuffer_to_use_for_output(unsigned fbid);
void enable_scissor_using_top_left_origin(Viewport, unsigned);
void disable_scissor(void);
+605
View File
@@ -0,0 +1,605 @@
// generated by glfw.py DO NOT edit
#define GFW_EXTERN
#include "data-types.h"
#include "glfw-wrapper.h"
#include <dlfcn.h>
static void* handle = NULL;
#define fail(msg, ...) { snprintf(buf, sizeof(buf), msg, __VA_ARGS__); return buf; }
const char*
load_glfw(const char* path) {
static char buf[2048];
handle = dlopen(path, RTLD_LAZY);
if (handle == NULL) fail("Failed to dlopen %s with error: %s", path, dlerror());
dlerror();
*(void **) (&glfwInit_impl) = dlsym(handle, "glfwInit");
if (glfwInit_impl == NULL) fail("Failed to load glfw function glfwInit with error: %s", dlerror());
*(void **) (&glfwRunMainLoop_impl) = dlsym(handle, "glfwRunMainLoop");
if (glfwRunMainLoop_impl == NULL) fail("Failed to load glfw function glfwRunMainLoop with error: %s", dlerror());
*(void **) (&glfwStopMainLoop_impl) = dlsym(handle, "glfwStopMainLoop");
if (glfwStopMainLoop_impl == NULL) fail("Failed to load glfw function glfwStopMainLoop with error: %s", dlerror());
*(void **) (&glfwAddTimer_impl) = dlsym(handle, "glfwAddTimer");
if (glfwAddTimer_impl == NULL) fail("Failed to load glfw function glfwAddTimer with error: %s", dlerror());
*(void **) (&glfwUpdateTimer_impl) = dlsym(handle, "glfwUpdateTimer");
if (glfwUpdateTimer_impl == NULL) fail("Failed to load glfw function glfwUpdateTimer with error: %s", dlerror());
*(void **) (&glfwRemoveTimer_impl) = dlsym(handle, "glfwRemoveTimer");
if (glfwRemoveTimer_impl == NULL) fail("Failed to load glfw function glfwRemoveTimer with error: %s", dlerror());
*(void **) (&glfwSetDrawTextFunction_impl) = dlsym(handle, "glfwSetDrawTextFunction");
if (glfwSetDrawTextFunction_impl == NULL) fail("Failed to load glfw function glfwSetDrawTextFunction with error: %s", dlerror());
*(void **) (&glfwSetCurrentSelectionCallback_impl) = dlsym(handle, "glfwSetCurrentSelectionCallback");
if (glfwSetCurrentSelectionCallback_impl == NULL) fail("Failed to load glfw function glfwSetCurrentSelectionCallback with error: %s", dlerror());
*(void **) (&glfwSetHasCurrentSelectionCallback_impl) = dlsym(handle, "glfwSetHasCurrentSelectionCallback");
if (glfwSetHasCurrentSelectionCallback_impl == NULL) fail("Failed to load glfw function glfwSetHasCurrentSelectionCallback with error: %s", dlerror());
*(void **) (&glfwSetIMECursorPositionCallback_impl) = dlsym(handle, "glfwSetIMECursorPositionCallback");
if (glfwSetIMECursorPositionCallback_impl == NULL) fail("Failed to load glfw function glfwSetIMECursorPositionCallback with error: %s", dlerror());
*(void **) (&glfwSetIMETextAroundCursorCallback_impl) = dlsym(handle, "glfwSetIMETextAroundCursorCallback");
if (glfwSetIMETextAroundCursorCallback_impl == NULL) fail("Failed to load glfw function glfwSetIMETextAroundCursorCallback with error: %s", dlerror());
*(void **) (&glfwIsLayerShellSupported_impl) = dlsym(handle, "glfwIsLayerShellSupported");
if (glfwIsLayerShellSupported_impl == NULL) fail("Failed to load glfw function glfwIsLayerShellSupported with error: %s", dlerror());
*(void **) (&glfwTerminate_impl) = dlsym(handle, "glfwTerminate");
if (glfwTerminate_impl == NULL) fail("Failed to load glfw function glfwTerminate with error: %s", dlerror());
*(void **) (&glfwInitHint_impl) = dlsym(handle, "glfwInitHint");
if (glfwInitHint_impl == NULL) fail("Failed to load glfw function glfwInitHint with error: %s", dlerror());
*(void **) (&glfwGetVersion_impl) = dlsym(handle, "glfwGetVersion");
if (glfwGetVersion_impl == NULL) fail("Failed to load glfw function glfwGetVersion with error: %s", dlerror());
*(void **) (&glfwGetVersionString_impl) = dlsym(handle, "glfwGetVersionString");
if (glfwGetVersionString_impl == NULL) fail("Failed to load glfw function glfwGetVersionString with error: %s", dlerror());
*(void **) (&glfwGetError_impl) = dlsym(handle, "glfwGetError");
if (glfwGetError_impl == NULL) fail("Failed to load glfw function glfwGetError with error: %s", dlerror());
*(void **) (&glfwSetErrorCallback_impl) = dlsym(handle, "glfwSetErrorCallback");
if (glfwSetErrorCallback_impl == NULL) fail("Failed to load glfw function glfwSetErrorCallback with error: %s", dlerror());
*(void **) (&glfwGetMonitors_impl) = dlsym(handle, "glfwGetMonitors");
if (glfwGetMonitors_impl == NULL) fail("Failed to load glfw function glfwGetMonitors with error: %s", dlerror());
*(void **) (&glfwGetPrimaryMonitor_impl) = dlsym(handle, "glfwGetPrimaryMonitor");
if (glfwGetPrimaryMonitor_impl == NULL) fail("Failed to load glfw function glfwGetPrimaryMonitor with error: %s", dlerror());
*(void **) (&glfwGetMonitorPos_impl) = dlsym(handle, "glfwGetMonitorPos");
if (glfwGetMonitorPos_impl == NULL) fail("Failed to load glfw function glfwGetMonitorPos with error: %s", dlerror());
*(void **) (&glfwGetMonitorWorkarea_impl) = dlsym(handle, "glfwGetMonitorWorkarea");
if (glfwGetMonitorWorkarea_impl == NULL) fail("Failed to load glfw function glfwGetMonitorWorkarea with error: %s", dlerror());
*(void **) (&glfwGetMonitorPhysicalSize_impl) = dlsym(handle, "glfwGetMonitorPhysicalSize");
if (glfwGetMonitorPhysicalSize_impl == NULL) fail("Failed to load glfw function glfwGetMonitorPhysicalSize with error: %s", dlerror());
*(void **) (&glfwGetMonitorContentScale_impl) = dlsym(handle, "glfwGetMonitorContentScale");
if (glfwGetMonitorContentScale_impl == NULL) fail("Failed to load glfw function glfwGetMonitorContentScale with error: %s", dlerror());
*(void **) (&glfwGetMonitorName_impl) = dlsym(handle, "glfwGetMonitorName");
if (glfwGetMonitorName_impl == NULL) fail("Failed to load glfw function glfwGetMonitorName with error: %s", dlerror());
*(void **) (&glfwGetMonitorDescription_impl) = dlsym(handle, "glfwGetMonitorDescription");
if (glfwGetMonitorDescription_impl == NULL) fail("Failed to load glfw function glfwGetMonitorDescription with error: %s", dlerror());
*(void **) (&glfwSetMonitorUserPointer_impl) = dlsym(handle, "glfwSetMonitorUserPointer");
if (glfwSetMonitorUserPointer_impl == NULL) fail("Failed to load glfw function glfwSetMonitorUserPointer with error: %s", dlerror());
*(void **) (&glfwGetMonitorUserPointer_impl) = dlsym(handle, "glfwGetMonitorUserPointer");
if (glfwGetMonitorUserPointer_impl == NULL) fail("Failed to load glfw function glfwGetMonitorUserPointer with error: %s", dlerror());
*(void **) (&glfwSetMonitorCallback_impl) = dlsym(handle, "glfwSetMonitorCallback");
if (glfwSetMonitorCallback_impl == NULL) fail("Failed to load glfw function glfwSetMonitorCallback with error: %s", dlerror());
*(void **) (&glfwGetVideoModes_impl) = dlsym(handle, "glfwGetVideoModes");
if (glfwGetVideoModes_impl == NULL) fail("Failed to load glfw function glfwGetVideoModes with error: %s", dlerror());
*(void **) (&glfwGetVideoMode_impl) = dlsym(handle, "glfwGetVideoMode");
if (glfwGetVideoMode_impl == NULL) fail("Failed to load glfw function glfwGetVideoMode with error: %s", dlerror());
*(void **) (&glfwSetGamma_impl) = dlsym(handle, "glfwSetGamma");
if (glfwSetGamma_impl == NULL) fail("Failed to load glfw function glfwSetGamma with error: %s", dlerror());
*(void **) (&glfwGetGammaRamp_impl) = dlsym(handle, "glfwGetGammaRamp");
if (glfwGetGammaRamp_impl == NULL) fail("Failed to load glfw function glfwGetGammaRamp with error: %s", dlerror());
*(void **) (&glfwSetGammaRamp_impl) = dlsym(handle, "glfwSetGammaRamp");
if (glfwSetGammaRamp_impl == NULL) fail("Failed to load glfw function glfwSetGammaRamp with error: %s", dlerror());
*(void **) (&glfwDefaultWindowHints_impl) = dlsym(handle, "glfwDefaultWindowHints");
if (glfwDefaultWindowHints_impl == NULL) fail("Failed to load glfw function glfwDefaultWindowHints with error: %s", dlerror());
*(void **) (&glfwWindowHint_impl) = dlsym(handle, "glfwWindowHint");
if (glfwWindowHint_impl == NULL) fail("Failed to load glfw function glfwWindowHint with error: %s", dlerror());
*(void **) (&glfwWindowHintString_impl) = dlsym(handle, "glfwWindowHintString");
if (glfwWindowHintString_impl == NULL) fail("Failed to load glfw function glfwWindowHintString with error: %s", dlerror());
*(void **) (&glfwCreateWindow_impl) = dlsym(handle, "glfwCreateWindow");
if (glfwCreateWindow_impl == NULL) fail("Failed to load glfw function glfwCreateWindow with error: %s", dlerror());
*(void **) (&glfwToggleFullscreen_impl) = dlsym(handle, "glfwToggleFullscreen");
if (glfwToggleFullscreen_impl == NULL) fail("Failed to load glfw function glfwToggleFullscreen with error: %s", dlerror());
*(void **) (&glfwIsFullscreen_impl) = dlsym(handle, "glfwIsFullscreen");
if (glfwIsFullscreen_impl == NULL) fail("Failed to load glfw function glfwIsFullscreen with error: %s", dlerror());
*(void **) (&glfwAreSwapsAllowed_impl) = dlsym(handle, "glfwAreSwapsAllowed");
if (glfwAreSwapsAllowed_impl == NULL) fail("Failed to load glfw function glfwAreSwapsAllowed with error: %s", dlerror());
*(void **) (&glfwGetLayerShellConfig_impl) = dlsym(handle, "glfwGetLayerShellConfig");
if (glfwGetLayerShellConfig_impl == NULL) fail("Failed to load glfw function glfwGetLayerShellConfig with error: %s", dlerror());
*(void **) (&glfwSetLayerShellConfig_impl) = dlsym(handle, "glfwSetLayerShellConfig");
if (glfwSetLayerShellConfig_impl == NULL) fail("Failed to load glfw function glfwSetLayerShellConfig with error: %s", dlerror());
*(void **) (&glfwDestroyWindow_impl) = dlsym(handle, "glfwDestroyWindow");
if (glfwDestroyWindow_impl == NULL) fail("Failed to load glfw function glfwDestroyWindow with error: %s", dlerror());
*(void **) (&glfwWindowShouldClose_impl) = dlsym(handle, "glfwWindowShouldClose");
if (glfwWindowShouldClose_impl == NULL) fail("Failed to load glfw function glfwWindowShouldClose with error: %s", dlerror());
*(void **) (&glfwSetWindowShouldClose_impl) = dlsym(handle, "glfwSetWindowShouldClose");
if (glfwSetWindowShouldClose_impl == NULL) fail("Failed to load glfw function glfwSetWindowShouldClose with error: %s", dlerror());
*(void **) (&glfwSetWindowTitle_impl) = dlsym(handle, "glfwSetWindowTitle");
if (glfwSetWindowTitle_impl == NULL) fail("Failed to load glfw function glfwSetWindowTitle with error: %s", dlerror());
*(void **) (&glfwSetWindowIcon_impl) = dlsym(handle, "glfwSetWindowIcon");
if (glfwSetWindowIcon_impl == NULL) fail("Failed to load glfw function glfwSetWindowIcon with error: %s", dlerror());
*(void **) (&glfwGetWindowPos_impl) = dlsym(handle, "glfwGetWindowPos");
if (glfwGetWindowPos_impl == NULL) fail("Failed to load glfw function glfwGetWindowPos with error: %s", dlerror());
*(void **) (&glfwSetWindowPos_impl) = dlsym(handle, "glfwSetWindowPos");
if (glfwSetWindowPos_impl == NULL) fail("Failed to load glfw function glfwSetWindowPos with error: %s", dlerror());
*(void **) (&glfwGetWindowSize_impl) = dlsym(handle, "glfwGetWindowSize");
if (glfwGetWindowSize_impl == NULL) fail("Failed to load glfw function glfwGetWindowSize with error: %s", dlerror());
*(void **) (&glfwSetWindowSizeLimits_impl) = dlsym(handle, "glfwSetWindowSizeLimits");
if (glfwSetWindowSizeLimits_impl == NULL) fail("Failed to load glfw function glfwSetWindowSizeLimits with error: %s", dlerror());
*(void **) (&glfwSetWindowSizeIncrements_impl) = dlsym(handle, "glfwSetWindowSizeIncrements");
if (glfwSetWindowSizeIncrements_impl == NULL) fail("Failed to load glfw function glfwSetWindowSizeIncrements with error: %s", dlerror());
*(void **) (&glfwSetWindowAspectRatio_impl) = dlsym(handle, "glfwSetWindowAspectRatio");
if (glfwSetWindowAspectRatio_impl == NULL) fail("Failed to load glfw function glfwSetWindowAspectRatio with error: %s", dlerror());
*(void **) (&glfwSetWindowSize_impl) = dlsym(handle, "glfwSetWindowSize");
if (glfwSetWindowSize_impl == NULL) fail("Failed to load glfw function glfwSetWindowSize with error: %s", dlerror());
*(void **) (&glfwGetFramebufferSize_impl) = dlsym(handle, "glfwGetFramebufferSize");
if (glfwGetFramebufferSize_impl == NULL) fail("Failed to load glfw function glfwGetFramebufferSize with error: %s", dlerror());
*(void **) (&glfwGetWindowFrameSize_impl) = dlsym(handle, "glfwGetWindowFrameSize");
if (glfwGetWindowFrameSize_impl == NULL) fail("Failed to load glfw function glfwGetWindowFrameSize with error: %s", dlerror());
*(void **) (&glfwGetWindowContentScale_impl) = dlsym(handle, "glfwGetWindowContentScale");
if (glfwGetWindowContentScale_impl == NULL) fail("Failed to load glfw function glfwGetWindowContentScale with error: %s", dlerror());
*(void **) (&glfwGetDoubleClickInterval_impl) = dlsym(handle, "glfwGetDoubleClickInterval");
if (glfwGetDoubleClickInterval_impl == NULL) fail("Failed to load glfw function glfwGetDoubleClickInterval with error: %s", dlerror());
*(void **) (&glfwGetWindowOpacity_impl) = dlsym(handle, "glfwGetWindowOpacity");
if (glfwGetWindowOpacity_impl == NULL) fail("Failed to load glfw function glfwGetWindowOpacity with error: %s", dlerror());
*(void **) (&glfwSetWindowOpacity_impl) = dlsym(handle, "glfwSetWindowOpacity");
if (glfwSetWindowOpacity_impl == NULL) fail("Failed to load glfw function glfwSetWindowOpacity with error: %s", dlerror());
*(void **) (&glfwIconifyWindow_impl) = dlsym(handle, "glfwIconifyWindow");
if (glfwIconifyWindow_impl == NULL) fail("Failed to load glfw function glfwIconifyWindow with error: %s", dlerror());
*(void **) (&glfwRestoreWindow_impl) = dlsym(handle, "glfwRestoreWindow");
if (glfwRestoreWindow_impl == NULL) fail("Failed to load glfw function glfwRestoreWindow with error: %s", dlerror());
*(void **) (&glfwMaximizeWindow_impl) = dlsym(handle, "glfwMaximizeWindow");
if (glfwMaximizeWindow_impl == NULL) fail("Failed to load glfw function glfwMaximizeWindow with error: %s", dlerror());
*(void **) (&glfwShowWindow_impl) = dlsym(handle, "glfwShowWindow");
if (glfwShowWindow_impl == NULL) fail("Failed to load glfw function glfwShowWindow with error: %s", dlerror());
*(void **) (&glfwHideWindow_impl) = dlsym(handle, "glfwHideWindow");
if (glfwHideWindow_impl == NULL) fail("Failed to load glfw function glfwHideWindow with error: %s", dlerror());
*(void **) (&glfwFocusWindow_impl) = dlsym(handle, "glfwFocusWindow");
if (glfwFocusWindow_impl == NULL) fail("Failed to load glfw function glfwFocusWindow with error: %s", dlerror());
*(void **) (&glfwRequestWindowAttention_impl) = dlsym(handle, "glfwRequestWindowAttention");
if (glfwRequestWindowAttention_impl == NULL) fail("Failed to load glfw function glfwRequestWindowAttention with error: %s", dlerror());
*(void **) (&glfwWindowBell_impl) = dlsym(handle, "glfwWindowBell");
if (glfwWindowBell_impl == NULL) fail("Failed to load glfw function glfwWindowBell with error: %s", dlerror());
*(void **) (&glfwGetWindowMonitor_impl) = dlsym(handle, "glfwGetWindowMonitor");
if (glfwGetWindowMonitor_impl == NULL) fail("Failed to load glfw function glfwGetWindowMonitor with error: %s", dlerror());
*(void **) (&glfwSetWindowMonitor_impl) = dlsym(handle, "glfwSetWindowMonitor");
if (glfwSetWindowMonitor_impl == NULL) fail("Failed to load glfw function glfwSetWindowMonitor with error: %s", dlerror());
*(void **) (&glfwGetWindowAttrib_impl) = dlsym(handle, "glfwGetWindowAttrib");
if (glfwGetWindowAttrib_impl == NULL) fail("Failed to load glfw function glfwGetWindowAttrib with error: %s", dlerror());
*(void **) (&glfwSetWindowAttrib_impl) = dlsym(handle, "glfwSetWindowAttrib");
if (glfwSetWindowAttrib_impl == NULL) fail("Failed to load glfw function glfwSetWindowAttrib with error: %s", dlerror());
*(void **) (&glfwSetWindowBlur_impl) = dlsym(handle, "glfwSetWindowBlur");
if (glfwSetWindowBlur_impl == NULL) fail("Failed to load glfw function glfwSetWindowBlur with error: %s", dlerror());
*(void **) (&glfwSetWindowUserPointer_impl) = dlsym(handle, "glfwSetWindowUserPointer");
if (glfwSetWindowUserPointer_impl == NULL) fail("Failed to load glfw function glfwSetWindowUserPointer with error: %s", dlerror());
*(void **) (&glfwGetWindowUserPointer_impl) = dlsym(handle, "glfwGetWindowUserPointer");
if (glfwGetWindowUserPointer_impl == NULL) fail("Failed to load glfw function glfwGetWindowUserPointer with error: %s", dlerror());
*(void **) (&glfwSetWindowPosCallback_impl) = dlsym(handle, "glfwSetWindowPosCallback");
if (glfwSetWindowPosCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowPosCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowSizeCallback_impl) = dlsym(handle, "glfwSetWindowSizeCallback");
if (glfwSetWindowSizeCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowSizeCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowCloseCallback_impl) = dlsym(handle, "glfwSetWindowCloseCallback");
if (glfwSetWindowCloseCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowCloseCallback with error: %s", dlerror());
*(void **) (&glfwSetApplicationCloseCallback_impl) = dlsym(handle, "glfwSetApplicationCloseCallback");
if (glfwSetApplicationCloseCallback_impl == NULL) fail("Failed to load glfw function glfwSetApplicationCloseCallback with error: %s", dlerror());
*(void **) (&glfwSetSystemColorThemeChangeCallback_impl) = dlsym(handle, "glfwSetSystemColorThemeChangeCallback");
if (glfwSetSystemColorThemeChangeCallback_impl == NULL) fail("Failed to load glfw function glfwSetSystemColorThemeChangeCallback with error: %s", dlerror());
*(void **) (&glfwSetClipboardLostCallback_impl) = dlsym(handle, "glfwSetClipboardLostCallback");
if (glfwSetClipboardLostCallback_impl == NULL) fail("Failed to load glfw function glfwSetClipboardLostCallback with error: %s", dlerror());
*(void **) (&glfwGetCurrentSystemColorTheme_impl) = dlsym(handle, "glfwGetCurrentSystemColorTheme");
if (glfwGetCurrentSystemColorTheme_impl == NULL) fail("Failed to load glfw function glfwGetCurrentSystemColorTheme with error: %s", dlerror());
*(void **) (&glfwGetTitlebarFont_impl) = dlsym(handle, "glfwGetTitlebarFont");
if (glfwGetTitlebarFont_impl == NULL) fail("Failed to load glfw function glfwGetTitlebarFont with error: %s", dlerror());
*(void **) (&glfwSetWindowRefreshCallback_impl) = dlsym(handle, "glfwSetWindowRefreshCallback");
if (glfwSetWindowRefreshCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowRefreshCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowFocusCallback_impl) = dlsym(handle, "glfwSetWindowFocusCallback");
if (glfwSetWindowFocusCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowFocusCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowOcclusionCallback_impl) = dlsym(handle, "glfwSetWindowOcclusionCallback");
if (glfwSetWindowOcclusionCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowOcclusionCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowIconifyCallback_impl) = dlsym(handle, "glfwSetWindowIconifyCallback");
if (glfwSetWindowIconifyCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowIconifyCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowMaximizeCallback_impl) = dlsym(handle, "glfwSetWindowMaximizeCallback");
if (glfwSetWindowMaximizeCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowMaximizeCallback with error: %s", dlerror());
*(void **) (&glfwSetFramebufferSizeCallback_impl) = dlsym(handle, "glfwSetFramebufferSizeCallback");
if (glfwSetFramebufferSizeCallback_impl == NULL) fail("Failed to load glfw function glfwSetFramebufferSizeCallback with error: %s", dlerror());
*(void **) (&glfwSetWindowContentScaleCallback_impl) = dlsym(handle, "glfwSetWindowContentScaleCallback");
if (glfwSetWindowContentScaleCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowContentScaleCallback with error: %s", dlerror());
*(void **) (&glfwPostEmptyEvent_impl) = dlsym(handle, "glfwPostEmptyEvent");
if (glfwPostEmptyEvent_impl == NULL) fail("Failed to load glfw function glfwPostEmptyEvent with error: %s", dlerror());
*(void **) (&glfwGetIgnoreOSKeyboardProcessing_impl) = dlsym(handle, "glfwGetIgnoreOSKeyboardProcessing");
if (glfwGetIgnoreOSKeyboardProcessing_impl == NULL) fail("Failed to load glfw function glfwGetIgnoreOSKeyboardProcessing with error: %s", dlerror());
*(void **) (&glfwSetIgnoreOSKeyboardProcessing_impl) = dlsym(handle, "glfwSetIgnoreOSKeyboardProcessing");
if (glfwSetIgnoreOSKeyboardProcessing_impl == NULL) fail("Failed to load glfw function glfwSetIgnoreOSKeyboardProcessing with error: %s", dlerror());
*(void **) (&glfwSetModifierRemap_impl) = dlsym(handle, "glfwSetModifierRemap");
if (glfwSetModifierRemap_impl == NULL) fail("Failed to load glfw function glfwSetModifierRemap with error: %s", dlerror());
*(void **) (&glfwGrabKeyboard_impl) = dlsym(handle, "glfwGrabKeyboard");
if (glfwGrabKeyboard_impl == NULL) fail("Failed to load glfw function glfwGrabKeyboard with error: %s", dlerror());
*(void **) (&glfwGetKeyboardRepeatDelay_impl) = dlsym(handle, "glfwGetKeyboardRepeatDelay");
if (glfwGetKeyboardRepeatDelay_impl == NULL) fail("Failed to load glfw function glfwGetKeyboardRepeatDelay with error: %s", dlerror());
*(void **) (&glfwGetInputMode_impl) = dlsym(handle, "glfwGetInputMode");
if (glfwGetInputMode_impl == NULL) fail("Failed to load glfw function glfwGetInputMode with error: %s", dlerror());
*(void **) (&glfwSetInputMode_impl) = dlsym(handle, "glfwSetInputMode");
if (glfwSetInputMode_impl == NULL) fail("Failed to load glfw function glfwSetInputMode with error: %s", dlerror());
*(void **) (&glfwRawMouseMotionSupported_impl) = dlsym(handle, "glfwRawMouseMotionSupported");
if (glfwRawMouseMotionSupported_impl == NULL) fail("Failed to load glfw function glfwRawMouseMotionSupported with error: %s", dlerror());
*(void **) (&glfwGetKeyName_impl) = dlsym(handle, "glfwGetKeyName");
if (glfwGetKeyName_impl == NULL) fail("Failed to load glfw function glfwGetKeyName with error: %s", dlerror());
*(void **) (&glfwGetNativeKeyForKey_impl) = dlsym(handle, "glfwGetNativeKeyForKey");
if (glfwGetNativeKeyForKey_impl == NULL) fail("Failed to load glfw function glfwGetNativeKeyForKey with error: %s", dlerror());
*(void **) (&glfwGetKey_impl) = dlsym(handle, "glfwGetKey");
if (glfwGetKey_impl == NULL) fail("Failed to load glfw function glfwGetKey with error: %s", dlerror());
*(void **) (&glfwGetMouseButton_impl) = dlsym(handle, "glfwGetMouseButton");
if (glfwGetMouseButton_impl == NULL) fail("Failed to load glfw function glfwGetMouseButton with error: %s", dlerror());
*(void **) (&glfwGetCursorPos_impl) = dlsym(handle, "glfwGetCursorPos");
if (glfwGetCursorPos_impl == NULL) fail("Failed to load glfw function glfwGetCursorPos with error: %s", dlerror());
*(void **) (&glfwSetCursorPos_impl) = dlsym(handle, "glfwSetCursorPos");
if (glfwSetCursorPos_impl == NULL) fail("Failed to load glfw function glfwSetCursorPos with error: %s", dlerror());
*(void **) (&glfwCreateCursor_impl) = dlsym(handle, "glfwCreateCursor");
if (glfwCreateCursor_impl == NULL) fail("Failed to load glfw function glfwCreateCursor with error: %s", dlerror());
*(void **) (&glfwCreateStandardCursor_impl) = dlsym(handle, "glfwCreateStandardCursor");
if (glfwCreateStandardCursor_impl == NULL) fail("Failed to load glfw function glfwCreateStandardCursor with error: %s", dlerror());
*(void **) (&glfwDestroyCursor_impl) = dlsym(handle, "glfwDestroyCursor");
if (glfwDestroyCursor_impl == NULL) fail("Failed to load glfw function glfwDestroyCursor with error: %s", dlerror());
*(void **) (&glfwSetCursor_impl) = dlsym(handle, "glfwSetCursor");
if (glfwSetCursor_impl == NULL) fail("Failed to load glfw function glfwSetCursor with error: %s", dlerror());
*(void **) (&glfwSetKeyboardCallback_impl) = dlsym(handle, "glfwSetKeyboardCallback");
if (glfwSetKeyboardCallback_impl == NULL) fail("Failed to load glfw function glfwSetKeyboardCallback with error: %s", dlerror());
*(void **) (&glfwUpdateIMEState_impl) = dlsym(handle, "glfwUpdateIMEState");
if (glfwUpdateIMEState_impl == NULL) fail("Failed to load glfw function glfwUpdateIMEState with error: %s", dlerror());
*(void **) (&glfwSetMouseButtonCallback_impl) = dlsym(handle, "glfwSetMouseButtonCallback");
if (glfwSetMouseButtonCallback_impl == NULL) fail("Failed to load glfw function glfwSetMouseButtonCallback with error: %s", dlerror());
*(void **) (&glfwSetCursorPosCallback_impl) = dlsym(handle, "glfwSetCursorPosCallback");
if (glfwSetCursorPosCallback_impl == NULL) fail("Failed to load glfw function glfwSetCursorPosCallback with error: %s", dlerror());
*(void **) (&glfwSetCursorEnterCallback_impl) = dlsym(handle, "glfwSetCursorEnterCallback");
if (glfwSetCursorEnterCallback_impl == NULL) fail("Failed to load glfw function glfwSetCursorEnterCallback with error: %s", dlerror());
*(void **) (&glfwSetScrollCallback_impl) = dlsym(handle, "glfwSetScrollCallback");
if (glfwSetScrollCallback_impl == NULL) fail("Failed to load glfw function glfwSetScrollCallback with error: %s", dlerror());
*(void **) (&glfwSetTouchCallback_impl) = dlsym(handle, "glfwSetTouchCallback");
if (glfwSetTouchCallback_impl == NULL) fail("Failed to load glfw function glfwSetTouchCallback with error: %s", dlerror());
*(void **) (&glfwSetLiveResizeCallback_impl) = dlsym(handle, "glfwSetLiveResizeCallback");
if (glfwSetLiveResizeCallback_impl == NULL) fail("Failed to load glfw function glfwSetLiveResizeCallback with error: %s", dlerror());
*(void **) (&glfwSetDropEventCallback_impl) = dlsym(handle, "glfwSetDropEventCallback");
if (glfwSetDropEventCallback_impl == NULL) fail("Failed to load glfw function glfwSetDropEventCallback with error: %s", dlerror());
*(void **) (&glfwRequestDropUpdate_impl) = dlsym(handle, "glfwRequestDropUpdate");
if (glfwRequestDropUpdate_impl == NULL) fail("Failed to load glfw function glfwRequestDropUpdate with error: %s", dlerror());
*(void **) (&glfwRequestDropData_impl) = dlsym(handle, "glfwRequestDropData");
if (glfwRequestDropData_impl == NULL) fail("Failed to load glfw function glfwRequestDropData with error: %s", dlerror());
*(void **) (&glfwEndDrop_impl) = dlsym(handle, "glfwEndDrop");
if (glfwEndDrop_impl == NULL) fail("Failed to load glfw function glfwEndDrop with error: %s", dlerror());
*(void **) (&glfwSetDragSourceCallback_impl) = dlsym(handle, "glfwSetDragSourceCallback");
if (glfwSetDragSourceCallback_impl == NULL) fail("Failed to load glfw function glfwSetDragSourceCallback with error: %s", dlerror());
*(void **) (&glfwStartDrag_impl) = dlsym(handle, "glfwStartDrag");
if (glfwStartDrag_impl == NULL) fail("Failed to load glfw function glfwStartDrag with error: %s", dlerror());
*(void **) (&glfwJoystickPresent_impl) = dlsym(handle, "glfwJoystickPresent");
if (glfwJoystickPresent_impl == NULL) fail("Failed to load glfw function glfwJoystickPresent with error: %s", dlerror());
*(void **) (&glfwGetJoystickAxes_impl) = dlsym(handle, "glfwGetJoystickAxes");
if (glfwGetJoystickAxes_impl == NULL) fail("Failed to load glfw function glfwGetJoystickAxes with error: %s", dlerror());
*(void **) (&glfwGetJoystickButtons_impl) = dlsym(handle, "glfwGetJoystickButtons");
if (glfwGetJoystickButtons_impl == NULL) fail("Failed to load glfw function glfwGetJoystickButtons with error: %s", dlerror());
*(void **) (&glfwGetJoystickHats_impl) = dlsym(handle, "glfwGetJoystickHats");
if (glfwGetJoystickHats_impl == NULL) fail("Failed to load glfw function glfwGetJoystickHats with error: %s", dlerror());
*(void **) (&glfwGetJoystickName_impl) = dlsym(handle, "glfwGetJoystickName");
if (glfwGetJoystickName_impl == NULL) fail("Failed to load glfw function glfwGetJoystickName with error: %s", dlerror());
*(void **) (&glfwGetJoystickGUID_impl) = dlsym(handle, "glfwGetJoystickGUID");
if (glfwGetJoystickGUID_impl == NULL) fail("Failed to load glfw function glfwGetJoystickGUID with error: %s", dlerror());
*(void **) (&glfwSetJoystickUserPointer_impl) = dlsym(handle, "glfwSetJoystickUserPointer");
if (glfwSetJoystickUserPointer_impl == NULL) fail("Failed to load glfw function glfwSetJoystickUserPointer with error: %s", dlerror());
*(void **) (&glfwGetJoystickUserPointer_impl) = dlsym(handle, "glfwGetJoystickUserPointer");
if (glfwGetJoystickUserPointer_impl == NULL) fail("Failed to load glfw function glfwGetJoystickUserPointer with error: %s", dlerror());
*(void **) (&glfwJoystickIsGamepad_impl) = dlsym(handle, "glfwJoystickIsGamepad");
if (glfwJoystickIsGamepad_impl == NULL) fail("Failed to load glfw function glfwJoystickIsGamepad with error: %s", dlerror());
*(void **) (&glfwSetJoystickCallback_impl) = dlsym(handle, "glfwSetJoystickCallback");
if (glfwSetJoystickCallback_impl == NULL) fail("Failed to load glfw function glfwSetJoystickCallback with error: %s", dlerror());
*(void **) (&glfwUpdateGamepadMappings_impl) = dlsym(handle, "glfwUpdateGamepadMappings");
if (glfwUpdateGamepadMappings_impl == NULL) fail("Failed to load glfw function glfwUpdateGamepadMappings with error: %s", dlerror());
*(void **) (&glfwGetGamepadName_impl) = dlsym(handle, "glfwGetGamepadName");
if (glfwGetGamepadName_impl == NULL) fail("Failed to load glfw function glfwGetGamepadName with error: %s", dlerror());
*(void **) (&glfwGetGamepadState_impl) = dlsym(handle, "glfwGetGamepadState");
if (glfwGetGamepadState_impl == NULL) fail("Failed to load glfw function glfwGetGamepadState with error: %s", dlerror());
*(void **) (&glfwSetClipboardDataTypes_impl) = dlsym(handle, "glfwSetClipboardDataTypes");
if (glfwSetClipboardDataTypes_impl == NULL) fail("Failed to load glfw function glfwSetClipboardDataTypes with error: %s", dlerror());
*(void **) (&glfwGetClipboard_impl) = dlsym(handle, "glfwGetClipboard");
if (glfwGetClipboard_impl == NULL) fail("Failed to load glfw function glfwGetClipboard with error: %s", dlerror());
*(void **) (&glfwGetTime_impl) = dlsym(handle, "glfwGetTime");
if (glfwGetTime_impl == NULL) fail("Failed to load glfw function glfwGetTime with error: %s", dlerror());
*(void **) (&glfwMakeContextCurrent_impl) = dlsym(handle, "glfwMakeContextCurrent");
if (glfwMakeContextCurrent_impl == NULL) fail("Failed to load glfw function glfwMakeContextCurrent with error: %s", dlerror());
*(void **) (&glfwGetCurrentContext_impl) = dlsym(handle, "glfwGetCurrentContext");
if (glfwGetCurrentContext_impl == NULL) fail("Failed to load glfw function glfwGetCurrentContext with error: %s", dlerror());
*(void **) (&glfwSwapBuffers_impl) = dlsym(handle, "glfwSwapBuffers");
if (glfwSwapBuffers_impl == NULL) fail("Failed to load glfw function glfwSwapBuffers with error: %s", dlerror());
*(void **) (&glfwSwapInterval_impl) = dlsym(handle, "glfwSwapInterval");
if (glfwSwapInterval_impl == NULL) fail("Failed to load glfw function glfwSwapInterval with error: %s", dlerror());
*(void **) (&glfwExtensionSupported_impl) = dlsym(handle, "glfwExtensionSupported");
if (glfwExtensionSupported_impl == NULL) fail("Failed to load glfw function glfwExtensionSupported with error: %s", dlerror());
*(void **) (&glfwGetProcAddress_impl) = dlsym(handle, "glfwGetProcAddress");
if (glfwGetProcAddress_impl == NULL) fail("Failed to load glfw function glfwGetProcAddress with error: %s", dlerror());
*(void **) (&glfwVulkanSupported_impl) = dlsym(handle, "glfwVulkanSupported");
if (glfwVulkanSupported_impl == NULL) fail("Failed to load glfw function glfwVulkanSupported with error: %s", dlerror());
*(void **) (&glfwGetRequiredInstanceExtensions_impl) = dlsym(handle, "glfwGetRequiredInstanceExtensions");
if (glfwGetRequiredInstanceExtensions_impl == NULL) fail("Failed to load glfw function glfwGetRequiredInstanceExtensions with error: %s", dlerror());
*(void **) (&glfwGetCocoaWindow_impl) = dlsym(handle, "glfwGetCocoaWindow");
if (glfwGetCocoaWindow_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetNSGLContext_impl) = dlsym(handle, "glfwGetNSGLContext");
if (glfwGetNSGLContext_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetCocoaMonitor_impl) = dlsym(handle, "glfwGetCocoaMonitor");
if (glfwGetCocoaMonitor_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetCocoaTextInputFilter_impl) = dlsym(handle, "glfwSetCocoaTextInputFilter");
if (glfwSetCocoaTextInputFilter_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetCocoaURLOpenCallback_impl) = dlsym(handle, "glfwSetCocoaURLOpenCallback");
if (glfwSetCocoaURLOpenCallback_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetCocoaToggleFullscreenIntercept_impl) = dlsym(handle, "glfwSetCocoaToggleFullscreenIntercept");
if (glfwSetCocoaToggleFullscreenIntercept_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetApplicationShouldHandleReopen_impl) = dlsym(handle, "glfwSetApplicationShouldHandleReopen");
if (glfwSetApplicationShouldHandleReopen_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetApplicationWillFinishLaunching_impl) = dlsym(handle, "glfwSetApplicationWillFinishLaunching");
if (glfwSetApplicationWillFinishLaunching_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetCocoaKeyEquivalent_impl) = dlsym(handle, "glfwGetCocoaKeyEquivalent");
if (glfwGetCocoaKeyEquivalent_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaRequestRenderFrame_impl) = dlsym(handle, "glfwCocoaRequestRenderFrame");
if (glfwCocoaRequestRenderFrame_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaRecreateGLDrawable_impl) = dlsym(handle, "glfwCocoaRecreateGLDrawable");
if (glfwCocoaRecreateGLDrawable_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaSetWindowResizeCallback_impl) = dlsym(handle, "glfwCocoaSetWindowResizeCallback");
if (glfwCocoaSetWindowResizeCallback_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetX11Display_impl) = dlsym(handle, "glfwGetX11Display");
if (glfwGetX11Display_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetX11Window_impl) = dlsym(handle, "glfwGetX11Window");
if (glfwGetX11Window_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetPrimarySelectionString_impl) = dlsym(handle, "glfwSetPrimarySelectionString");
if (glfwSetPrimarySelectionString_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaCycleThroughOSWindows_impl) = dlsym(handle, "glfwCocoaCycleThroughOSWindows");
if (glfwCocoaCycleThroughOSWindows_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaSetWindowChrome_impl) = dlsym(handle, "glfwCocoaSetWindowChrome");
if (glfwCocoaSetWindowChrome_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaRegisterMIMETypes_impl) = dlsym(handle, "glfwCocoaRegisterMIMETypes");
if (glfwCocoaRegisterMIMETypes_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaPreserveDroppedFilePromises_impl) = dlsym(handle, "glfwCocoaPreserveDroppedFilePromises");
if (glfwCocoaPreserveDroppedFilePromises_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCocoaSetWindowLevel_impl) = dlsym(handle, "glfwCocoaSetWindowLevel");
if (glfwCocoaSetWindowLevel_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetPrimarySelectionString_impl) = dlsym(handle, "glfwGetPrimarySelectionString");
if (glfwGetPrimarySelectionString_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetNativeKeyForName_impl) = dlsym(handle, "glfwGetNativeKeyForName");
if (glfwGetNativeKeyForName_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwRequestWaylandFrameEvent_impl) = dlsym(handle, "glfwRequestWaylandFrameEvent");
if (glfwRequestWaylandFrameEvent_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandActivateWindow_impl) = dlsym(handle, "glfwWaylandActivateWindow");
if (glfwWaylandActivateWindow_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandMissingCapabilities_impl) = dlsym(handle, "glfwWaylandMissingCapabilities");
if (glfwWaylandMissingCapabilities_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandRunWithActivationToken_impl) = dlsym(handle, "glfwWaylandRunWithActivationToken");
if (glfwWaylandRunWithActivationToken_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandSetTitlebarColor_impl) = dlsym(handle, "glfwWaylandSetTitlebarColor");
if (glfwWaylandSetTitlebarColor_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandSetTitlebarHidden_impl) = dlsym(handle, "glfwWaylandSetTitlebarHidden");
if (glfwWaylandSetTitlebarHidden_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandSetInitialWindowSizeCallback_impl) = dlsym(handle, "glfwWaylandSetInitialWindowSizeCallback");
if (glfwWaylandSetInitialWindowSizeCallback_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandRedrawCSDWindowTitle_impl) = dlsym(handle, "glfwWaylandRedrawCSDWindowTitle");
if (glfwWaylandRedrawCSDWindowTitle_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandIsWindowFullyCreated_impl) = dlsym(handle, "glfwWaylandIsWindowFullyCreated");
if (glfwWaylandIsWindowFullyCreated_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandBeep_impl) = dlsym(handle, "glfwWaylandBeep");
if (glfwWaylandBeep_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandCompositorPID_impl) = dlsym(handle, "glfwWaylandCompositorPID");
if (glfwWaylandCompositorPID_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwGetWaylandCurrentMonitorFractionalScale_impl) = dlsym(handle, "glfwGetWaylandCurrentMonitorFractionalScale");
if (glfwGetWaylandCurrentMonitorFractionalScale_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwConfigureMomentumScroller_impl) = dlsym(handle, "glfwConfigureMomentumScroller");
if (glfwConfigureMomentumScroller_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwFeedMomentumScroller_impl) = dlsym(handle, "glfwFeedMomentumScroller");
if (glfwFeedMomentumScroller_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwCancelMomentumScroll_impl) = dlsym(handle, "glfwCancelMomentumScroll");
if (glfwCancelMomentumScroll_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwDBusUserNotify_impl) = dlsym(handle, "glfwDBusUserNotify");
if (glfwDBusUserNotify_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwDBusSetUserNotificationHandler_impl) = dlsym(handle, "glfwDBusSetUserNotificationHandler");
if (glfwDBusSetUserNotificationHandler_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwDBusMonitorSessionState_impl) = dlsym(handle, "glfwDBusMonitorSessionState");
if (glfwDBusMonitorSessionState_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwSetX11LaunchCommand_impl) = dlsym(handle, "glfwSetX11LaunchCommand");
if (glfwSetX11LaunchCommand_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandCreateVirtualDevices_impl) = dlsym(handle, "glfwWaylandCreateVirtualDevices");
if (glfwWaylandCreateVirtualDevices_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandInjectMouseMotionAbsolute_impl) = dlsym(handle, "glfwWaylandInjectMouseMotionAbsolute");
if (glfwWaylandInjectMouseMotionAbsolute_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandInjectMouseButton_impl) = dlsym(handle, "glfwWaylandInjectMouseButton");
if (glfwWaylandInjectMouseButton_impl == NULL) dlerror(); // clear error indicator
*(void **) (&glfwWaylandInjectKey_impl) = dlsym(handle, "glfwWaylandInjectKey");
if (glfwWaylandInjectKey_impl == NULL) dlerror(); // clear error indicator
return NULL;
}
void
unload_glfw(void) {
if (handle) { dlclose(handle); handle = NULL; }
}
+2722
View File
File diff suppressed because it is too large. Load diff
+4471
View File
File diff suppressed because it is too large. Load diff
+165
View File
@@ -0,0 +1,165 @@
/*
* glyph-cache.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "glyph-cache.h"
typedef struct SpritePosKey {
glyph_index ligature_index, count, cell_count, keysz_in_bytes;
uint8_t scale, subscale, multicell_y, vertical_align;
glyph_index key[];
} SpritePosKey;
static_assert(sizeof(SpritePosKey) == sizeof(glyph_index) * 4 + sizeof(uint8_t) * 4, "Fix the ordering of SpritePosKey");
#define NAME sprite_pos_map
#define KEY_TY const SpritePosKey *
#define VAL_TY SpritePosition *
static uint64_t sprite_pos_map_hash(KEY_TY key);
#define HASH_FN sprite_pos_map_hash
static bool sprite_pos_map_cmpr(KEY_TY a, KEY_TY b);
#define CMPR_FN sprite_pos_map_cmpr
#define MA_NAME Key
#define MA_BLOCK_SIZE 16u
static_assert(MA_BLOCK_SIZE > sizeof(SpritePosKey) + 2, "increase arena block size");
#define MA_ARENA_NUM_BLOCKS (2048u / MA_BLOCK_SIZE)
#include "arena.h"
#define MA_NAME Val
#define MA_BLOCK_SIZE sizeof(VAL_TY)
#define MA_ARENA_NUM_BLOCKS (2048u / MA_BLOCK_SIZE)
#include "arena.h"
#include "kitty-verstable.h"
static uint64_t
sprite_pos_map_hash(const SpritePosKey *key) {
return vt_hash_bytes(key, key->keysz_in_bytes + sizeof(SpritePosKey));
}
static bool
sprite_pos_map_cmpr(const SpritePosKey *a, const SpritePosKey *b) {
return a->keysz_in_bytes == b->keysz_in_bytes && memcmp(a, b, a->keysz_in_bytes + sizeof(SpritePosKey)) == 0;
}
typedef struct HashTable {
sprite_pos_map table;
KeyMonotonicArena keys;
ValMonotonicArena vals;
struct {
SpritePosKey *key;
size_t capacity;
} scratch;
} HashTable;
SPRITE_POSITION_MAP_HANDLE
create_sprite_position_hash_table(void) {
HashTable *ans = calloc(1, sizeof(HashTable));
if (ans) vt_init(&ans->table);
return (SPRITE_POSITION_MAP_HANDLE)ans;
}
SpritePosition *
find_or_create_sprite_position(
SPRITE_POSITION_MAP_HANDLE map_,
glyph_index *glyphs,
glyph_index count,
glyph_index ligature_index,
glyph_index cell_count,
uint8_t scale,
uint8_t subscale,
uint8_t multicell_y,
uint8_t vertical_align,
bool *created) {
HashTable *ht = (HashTable *)map_;
sprite_pos_map *map = &ht->table;
const size_t keysz_in_bytes = count * sizeof(glyph_index);
if (!ht->scratch.key || keysz_in_bytes > ht->scratch.capacity) {
const size_t newsz = sizeof(ht->scratch.key[0]) + keysz_in_bytes + 64;
ht->scratch.key = realloc(ht->scratch.key, newsz);
if (!ht->scratch.key) {
ht->scratch.capacity = 0;
return NULL;
}
ht->scratch.capacity = newsz - sizeof(ht->scratch.key[0]);
memset(ht->scratch.key, 0, newsz);
}
#define scratch ht->scratch.key
scratch->keysz_in_bytes = keysz_in_bytes;
scratch->count = count;
scratch->ligature_index = ligature_index;
scratch->cell_count = cell_count;
scratch->scale = scale;
scratch->subscale = subscale;
scratch->multicell_y = multicell_y;
scratch->vertical_align = vertical_align;
memcpy(scratch->key, glyphs, keysz_in_bytes);
sprite_pos_map_itr n = vt_get(map, scratch);
if (!vt_is_end(n)) {
*created = false;
return n.data->val;
}
SpritePosKey *key = Key_get(&ht->keys, sizeof(SpritePosKey) + scratch->keysz_in_bytes);
if (!key) return NULL;
SpritePosition *val = Val_get(&ht->vals, sizeof(SpritePosition));
if (!val) return NULL;
memcpy(key, scratch, sizeof(scratch[0]) + scratch->keysz_in_bytes);
if (vt_is_end(vt_insert(map, key, val))) return NULL;
*created = true;
return val;
#undef scratch
}
void
free_sprite_position_hash_table(SPRITE_POSITION_MAP_HANDLE *map) {
HashTable **mapref = (HashTable **)map;
if (*mapref) {
vt_cleanup(&mapref[0]->table);
Key_free_all(&mapref[0]->keys);
Val_free_all(&mapref[0]->vals);
free(mapref[0]->scratch.key);
free(mapref[0]);
mapref[0] = NULL;
}
}
#define NAME glyph_props_map
#define KEY_TY glyph_index
#define VAL_TY GlyphProperties
#include "kitty-verstable.h"
GLYPH_PROPERTIES_MAP_HANDLE
create_glyph_properties_hash_table(void) {
glyph_props_map *ans = calloc(1, sizeof(glyph_props_map));
if (ans) vt_init(ans);
return (GLYPH_PROPERTIES_MAP_HANDLE)ans;
}
GlyphProperties
find_glyph_properties(GLYPH_PROPERTIES_MAP_HANDLE map_, glyph_index glyph) {
glyph_props_map *map = (glyph_props_map *)map_;
glyph_props_map_itr n = vt_get(map, glyph);
if (vt_is_end(n)) return (GlyphProperties){0};
return n.data->val;
}
bool
set_glyph_properties(GLYPH_PROPERTIES_MAP_HANDLE map_, glyph_index glyph, GlyphProperties val) {
glyph_props_map *map = (glyph_props_map *)map_;
return !vt_is_end(vt_insert(map, glyph, val));
}
void
free_glyph_properties_hash_table(GLYPH_PROPERTIES_MAP_HANDLE *map_) {
glyph_props_map **mapref = (glyph_props_map **)map_;
if (*mapref) {
vt_cleanup(*mapref);
free(*mapref);
*mapref = NULL;
}
}
+61
View File
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
typedef union SpritePosition {
struct {
sprite_index idx : sizeof(sprite_index) * 8;
bool rendered : 1;
bool colored : 1;
uint32_t : 30;
};
uint64_t val;
} SpritePosition;
static_assert(sizeof(SpritePosition) == sizeof(uint64_t), "Fix ordering of SpritePosition");
typedef struct {
int x;
} *SPRITE_POSITION_MAP_HANDLE;
SPRITE_POSITION_MAP_HANDLE
create_sprite_position_hash_table(void);
void free_sprite_position_hash_table(SPRITE_POSITION_MAP_HANDLE *handle);
SpritePosition *find_or_create_sprite_position(
SPRITE_POSITION_MAP_HANDLE map,
glyph_index *glyphs,
glyph_index count,
glyph_index ligature_index,
glyph_index cell_count,
uint8_t scale,
uint8_t subscale,
uint8_t multicell_y,
uint8_t vertical_align,
bool *created);
typedef union GlyphProperties {
struct {
uint8_t special_set : 1;
uint8_t special_val : 1;
uint8_t empty_set : 1;
uint8_t empty_val : 1;
};
uint8_t val;
} GlyphProperties;
typedef struct {
int x;
} *GLYPH_PROPERTIES_MAP_HANDLE;
GLYPH_PROPERTIES_MAP_HANDLE
create_glyph_properties_hash_table(void);
void free_glyph_properties_hash_table(GLYPH_PROPERTIES_MAP_HANDLE *handle);
GlyphProperties find_glyph_properties(GLYPH_PROPERTIES_MAP_HANDLE map, glyph_index glyph);
bool set_glyph_properties(GLYPH_PROPERTIES_MAP_HANDLE map, glyph_index glyph, GlyphProperties val);
+3220
View File
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
/*
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include "monotonic.h"
// Bitmask values for GraphicsCommand.usage_hints
#define GRAPHICS_USAGE_HINT_TRANSIENT 1u
typedef struct {
unsigned char action, transmission_type, compressed, delete_action, report_supported;
uint32_t format, more, id, image_number, data_sz, data_offset, placement_id, quiet, parent_id, parent_placement_id, usage_hints;
uint32_t width, height, x_offset, y_offset;
union {
uint32_t cursor_movement, compose_mode;
};
union {
uint32_t cell_x_offset, blend_mode;
};
union {
uint32_t cell_y_offset, bgcolor;
};
union {
uint32_t data_width, animation_state;
};
union {
uint32_t data_height, loop_count;
};
union {
uint32_t num_lines, frame_number;
};
union {
uint32_t num_cells, other_frame_number;
};
union {
int32_t z_index, gap;
};
size_t payload_sz;
uint32_t unicode_placement;
int32_t offset_from_parent_x, offset_from_parent_y;
} GraphicsCommand;
typedef struct {
float left, top, right, bottom;
} ImageRect;
typedef struct {
ImageRect src_rect, dest_rect;
uint32_t texture_id, group_count;
int z_index;
// Zero for normal images, otherwise the number of bytes per pixel of an indexed color image
uint8_t indexed_px_sz;
// True for indexed color images drawn at their natural size, which can use
// a cheaper shader. Always false for normal images.
bool is_unscaled;
id_type image_id, ref_id;
} ImageRenderData;
typedef struct {
uint32_t texture_id;
unsigned int height, width;
uint8_t *bitmap;
uint32_t refcnt, id;
size_t mmap_size;
} BackgroundImage;
#ifdef GRAPHICS_INTERNAL_APIS
typedef struct {
float src_width, src_height, src_x, src_y;
uint32_t cell_x_offset, cell_y_offset, num_cols, num_rows, effective_num_rows, effective_num_cols;
int32_t z_index;
int32_t start_row, start_column;
uint32_t client_id;
ImageRect src_rect;
// Indicates whether this reference represents a cell ref that should be
// removed when the corresponding cells are modified.
// The internal id of the virtual ref this cell image was created from. Is a cell ref if this is non-zero.
id_type virtual_ref_id;
// Virtual refs are not displayed but they can be used as prototypes for
// refs placed using unicode placeholders.
bool is_virtual_ref;
struct {
id_type img, ref;
struct {
int32_t x, y;
} offset;
} parent;
id_type internal_id;
} ImageRef;
typedef struct {
uint32_t gap, id, width, height, x, y, base_frame_id, bgcolor;
bool is_opaque, is_4byte_aligned, alpha_blend, transient;
} Frame;
typedef enum { ANIMATION_STOPPED = 0, ANIMATION_LOADING = 1, ANIMATION_RUNNING = 2 } AnimationState;
typedef struct TextureRef {
uint32_t id, refcnt;
} TextureRef;
#define NAME ref_map
#define KEY_TY id_type
#define VAL_TY ImageRef *
#include "kitty-verstable.h"
typedef struct {
uint32_t client_id, client_number, width, height;
TextureRef *texture;
id_type internal_id;
// Zero for normal images, otherwise the number of bytes per pixel of an
// indexed color image. Such images cannot have more than one frame.
uint8_t indexed_px_sz;
bool root_frame_data_loaded;
id_type ref_id_counter;
Frame *extra_frames, root_frame;
uint32_t current_frame_index, frame_id_counter, displayed_frame_id;
uint64_t animation_duration;
size_t extra_framecnt;
monotonic_t atime;
size_t used_storage;
bool is_drawn;
AnimationState animation_state;
uint32_t max_loops, current_loop;
monotonic_t current_frame_shown_at;
ref_map refs_by_internal_id;
} Image;
typedef struct {
id_type image_id;
uint32_t frame_id;
} ImageAndFrame;
typedef struct {
uint8_t *buf;
size_t buf_capacity, buf_used;
size_t data_sz;
uint8_t *data;
bool is_4byte_aligned;
bool is_opaque, loading_completed_successfully;
uint8_t indexed_px_sz;
uint32_t width, height;
GraphicsCommand start_command;
ImageAndFrame loading_for;
} LoadData;
#define NAME image_map
#define KEY_TY id_type
#define VAL_TY Image *
#include "kitty-verstable.h"
typedef struct {
PyObject_HEAD
size_t storage_limit;
LoadData currently_loading;
id_type image_id_counter;
struct {
size_t count, capacity;
ImageRenderData *item;
} render_data;
bool layers_dirty;
// The number of images below MIN_ZINDEX / 2, then the number of refs between MIN_ZINDEX / 2 and -1 inclusive, then the number of refs above 0 inclusive.
size_t num_of_below_refs, num_of_negative_refs, num_of_positive_refs;
// The number of visible refs to indexed color images
size_t num_of_indexed_refs;
unsigned int last_scrolled_by;
float last_scroll_offset_lines;
size_t used_storage;
PyObject *disk_cache;
bool has_images_needing_animation, context_made_current_for_this_command;
id_type window_id;
image_map images_by_internal_id;
} GraphicsManager;
#else
typedef struct {
int x;
} *GraphicsManager;
#endif
typedef struct {
int32_t amt, limit;
index_type margin_top, margin_bottom;
bool has_margins;
// The history scrolls with the screen: lines move into it (amt < 0) or are popped back from it (amt > 0)
bool scroll_history;
} ScrollData;
static inline float
gl_size(const unsigned int sz, const unsigned int viewport_size) {
// convert pixel sz to OpenGL coordinate system.
const float px = 2.f / viewport_size;
return px * sz;
}
static inline float
gl_pos_x(const int px_from_left_margin, const unsigned int viewport_size) {
const float px = 2.f / viewport_size;
return -1.f + px_from_left_margin * px;
}
static inline float
tex_pos_x(const int px_from_left_margin, const unsigned texture_width) {
return px_from_left_margin / (float)texture_width;
}
static inline float
gl_pos_y(const int px_from_top_margin, const unsigned int viewport_size) {
const float px = 2.f / viewport_size;
return 1.f - px_from_top_margin * px;
}
static inline float
tex_pos_y(const int px_from_top_margin, const unsigned texture_height) {
const int px_from_bottom_margin = texture_height - px_from_top_margin;
return px_from_bottom_margin / (float)texture_height;
}
typedef struct GraphicsRenderData {
size_t count, capacity, num_of_below_refs, num_of_negative_refs, num_of_positive_refs, num_of_indexed_refs;
ImageRenderData *images;
} GraphicsRenderData;
GraphicsManager *grman_alloc(bool for_paused_rendering);
void grman_clear(GraphicsManager *, bool, CellPixelSize fg);
const char *grman_handle_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, Cursor *c, bool *is_dirty, CellPixelSize fg);
void grman_put_cell_image(
GraphicsManager *self,
uint32_t row,
uint32_t col,
uint32_t image_id,
uint32_t placement_id,
uint32_t x,
uint32_t y,
uint32_t w,
uint32_t h,
CellPixelSize cell);
bool grman_update_layers(
GraphicsManager *self,
unsigned int scrolled_by,
float scroll_offset_lines,
float screen_left,
float screen_top,
float dx,
float dy,
unsigned int num_cols,
unsigned int num_rows,
CellPixelSize);
void grman_scroll_images(GraphicsManager *self, const ScrollData *, CellPixelSize fg);
bool grman_has_any_images(GraphicsManager *self);
void grman_resize(GraphicsManager *, index_type, index_type, index_type, index_type, index_type, index_type);
void grman_rescale(GraphicsManager *self, CellPixelSize fg);
void grman_remove_cell_images(GraphicsManager *self, int32_t top, int32_t bottom);
void grman_remove_all_cell_images(GraphicsManager *self);
void gpu_data_for_image(ImageRenderData *ans, float left, float top, float right, float bottom);
bool png_from_file_pointer(FILE *fp, const char *path, uint8_t **data, unsigned int *width, unsigned int *height, size_t *sz);
bool png_path_to_bitmap(const char *path, uint8_t **data, unsigned int *width, unsigned int *height, size_t *sz);
bool
png_from_data(void *png_data, size_t png_data_sz, const char *path_for_error_messages, uint8_t **data, unsigned int *width, unsigned int *height, size_t *sz);
bool image_path_to_bitmap(const char *path, uint8_t **data, unsigned int *width, unsigned int *height, size_t *sz);
bool scan_active_animations(GraphicsManager *self, const monotonic_t now, monotonic_t *minimum_gap, bool os_window_context_set);
void grman_pause_rendering(GraphicsManager *self, GraphicsManager *dest);
void grman_mark_layers_dirty(GraphicsManager *self);
void grman_set_window_id(GraphicsManager *self, id_type id);
bool grman_has_images(GraphicsManager *self);
GraphicsRenderData grman_render_data(GraphicsManager *self);
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
import stat
from contextlib import suppress
known_extensions = {
'asciidoc': 'text/asciidoctor',
'conf': 'text/config',
'md': 'text/markdown',
'pyj': 'text/rapydscript-ng',
'recipe': 'text/python',
'rst': 'text/restructured-text',
'rb': 'text/ruby',
'toml': 'text/toml',
'vim': 'text/vim',
'yaml': 'text/yaml',
'js': 'text/javascript',
'json': 'text/json',
'nix': 'text/nix',
}
text_mimes = (
'application/x-sh',
'application/x-csh',
'application/x-shellscript',
'application/x-fishscript',
'application/x-awk',
'application/javascript',
'application/json',
'application/xml',
'application/x-yaml',
'application/yaml',
'application/x-toml',
'application/x-lua',
'application/toml',
'application/rss+xml',
'application/xhtml+xml',
'application/x-tex',
'application/x-latex',
)
def is_special_file(path: str) -> str | None:
name = os.path.basename(path)
lname = name.lower()
if lname == 'makefile' or lname.startswith('makefile.'):
return 'text/makefile'
if '.' not in name and name.endswith('rc'):
return 'text/plain' # rc file
return None
def is_folder(path: str) -> bool:
with suppress(OSError):
return os.path.isdir(path)
return False
def initialize_mime_database() -> None:
if hasattr(initialize_mime_database, 'inited'):
return
setattr(initialize_mime_database, 'inited', True)
from mimetypes import init
init(None)
def user_mime_map() -> dict[str, str]:
ans: dict[str, str] | None = getattr(user_mime_map, 'ans', None)
if ans is None:
from mimetypes import read_mime_types
from kitty.constants import config_dir, config_dir_files_ignored
ans = {} if config_dir_files_ignored() else (read_mime_types(os.path.join(config_dir, 'mime.types')) or {})
setattr(user_mime_map, 'ans', ans)
return ans
def clear_mime_cache() -> None:
if hasattr(initialize_mime_database, 'inited'):
delattr(initialize_mime_database, 'inited')
if hasattr(user_mime_map, 'ans'):
delattr(user_mime_map, 'ans')
from kitty.fast_data_types import clear_mime_cache_data
clear_mime_cache_data()
def guess_type_from_user_definitions(path: str) -> str | None:
umap = user_mime_map()
if not umap:
return None
ext = os.path.splitext(path)[1]
return umap.get(ext) or umap.get(ext.lower())
def guess_type_from_stdlib(path: str) -> str | None:
from mimetypes import guess_type as stdlib_guess_type
initialize_mime_database()
try:
return stdlib_guess_type(path)[0]
except Exception:
return None
def guess_type(path: str, allow_filesystem_access: bool = False) -> str | None:
is_dir = is_exe = False
if allow_filesystem_access:
with suppress(OSError):
st = os.stat(path)
is_dir = bool(stat.S_ISDIR(st.st_mode))
is_exe = bool(not is_dir and st.st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) and os.access(path, os.X_OK))
if is_dir:
return 'inode/directory'
from kitty.fast_data_types import mime_type_for_filename
# The stdlib database is only loaded if the faster shared-mime-info cache
# lookup fails, as loading it requires parsing various files
mt = guess_type_from_user_definitions(path) or mime_type_for_filename(path) or guess_type_from_stdlib(path)
if not mt:
ext = path.rpartition('.')[-1].lower()
mt = known_extensions.get(ext)
if mt:
mt = textual_mime_type(mt)
mt = mt or is_special_file(path)
if not mt:
if is_dir:
mt = 'inode/directory'
elif is_exe:
mt = 'inode/executable'
return mt
def textual_mime_type(mt: str) -> str:
return f'text/{mt.split("/", 1)[-1]}' if mt in text_mimes else mt
def mime_types_for_matching(path: str, mt: str) -> set[str]:
"""
Return all names that the MIME type mt, as returned by guess_type() for path,
is known by. This includes the aliases from the shared-mime-info database
as well as the names that were returned by older versions of kitty, so
that matching against user specified MIME types keeps working.
"""
from kitty.fast_data_types import mime_type_aliases
queries = {mt}
if mt.startswith('text/'):
# undo the conversion of textual application/* types done by guess_type()
orig = f'application/{mt[5:]}'
if orig in text_mimes:
queries.add(orig)
ans: set[str] = set()
for q in queries:
for x in mime_type_aliases(q):
ans.add(x)
ans.add(textual_mime_type(x))
legacy = known_extensions.get(path.rpartition('.')[-1].lower()) or is_special_file(path)
if legacy:
ans.add(legacy)
return ans
+775
View File
@@ -0,0 +1,775 @@
/*
* history.c
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "wcswidth.h"
#include "lineops.h"
#include "charsets.h"
#include "resize.h"
#include <structmember.h>
#include <sys/mman.h>
#include "../3rdparty/ringbuf/ringbuf.h"
extern PyTypeObject Line_Type;
#define SEGMENT_SIZE 2048
static void
add_segment(HistoryBuf *self, index_type num) {
self->segments = realloc(self->segments, sizeof(HistoryBufSegment) * (self->num_segments + num));
if (self->segments == NULL) fatal("Out of memory allocating new history buffer segment");
const size_t cpu_cells_size = self->xnum * SEGMENT_SIZE * sizeof(CPUCell);
const size_t gpu_cells_size = self->xnum * SEGMENT_SIZE * sizeof(GPUCell);
const size_t segment_size = cpu_cells_size + gpu_cells_size + SEGMENT_SIZE * sizeof(LineAttrs);
if (num > SIZE_MAX / segment_size) fatal("History buffer segment allocation is too large");
const size_t mmap_size = num * segment_size;
// We use mmap to avoid fragmentation in libc malloc pool, see
// https://github.com/kovidgoyal/kitty/pull/10254
char *mem = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (mem == MAP_FAILED) fatal("Out of memory allocating new history buffer segment");
char *needs_free = mem;
for (HistoryBufSegment *s = self->segments + self->num_segments; s < self->segments + self->num_segments + num; s++, mem += segment_size) {
s->cpu_cells = (CPUCell *)mem;
s->gpu_cells = (GPUCell *)(((uint8_t *)s->cpu_cells) + cpu_cells_size);
s->line_attrs = (LineAttrs *)(((uint8_t *)s->gpu_cells) + gpu_cells_size);
s->mem = NULL;
s->mmap_size = 0;
}
self->segments[self->num_segments].mem = needs_free;
self->segments[self->num_segments].mmap_size = mmap_size;
self->num_segments += num;
}
static void
free_segment(HistoryBufSegment *s) {
if (s->mem && munmap(s->mem, s->mmap_size) != 0) log_error("Failed to unmap history buffer segment: %s", strerror(errno));
zero_at_ptr(s);
}
static index_type
segment_for(HistoryBuf *self, index_type y) {
index_type seg_num = y / SEGMENT_SIZE;
while (UNLIKELY(seg_num >= self->num_segments && SEGMENT_SIZE * self->num_segments < self->ynum)) add_segment(self, 1);
if (UNLIKELY(seg_num >= self->num_segments)) fatal("Out of bounds access to history buffer line number: %u", y);
return seg_num;
}
#define seg_ptr(which, stride) \
{ \
index_type seg_num = segment_for(self, y); \
y -= seg_num * SEGMENT_SIZE; \
return self->segments[seg_num].which + y * stride; \
}
static CPUCell *
cpu_lineptr(HistoryBuf *self, index_type y) {
seg_ptr(cpu_cells, self->xnum);
}
static GPUCell *
gpu_lineptr(HistoryBuf *self, index_type y) {
seg_ptr(gpu_cells, self->xnum);
}
static LineAttrs *
attrptr(HistoryBuf *self, index_type y) {
seg_ptr(line_attrs, 1);
}
static size_t
initial_pagerhist_ringbuf_sz(size_t pagerhist_sz) {
return MIN(1024u * 1024u, pagerhist_sz);
}
static PagerHistoryBuf *
alloc_pagerhist(size_t pagerhist_sz) {
PagerHistoryBuf *ph;
if (!pagerhist_sz) return NULL;
ph = calloc(1, sizeof(PagerHistoryBuf));
if (!ph) return NULL;
size_t sz = initial_pagerhist_ringbuf_sz(pagerhist_sz);
ph->ringbuf = ringbuf_new(sz);
if (!ph->ringbuf) {
free(ph);
return NULL;
}
ph->maximum_size = pagerhist_sz;
return ph;
}
static void
free_pagerhist(HistoryBuf *self) {
if (self->pagerhist && self->pagerhist->ringbuf) ringbuf_free((ringbuf_t *)&self->pagerhist->ringbuf);
free(self->pagerhist);
self->pagerhist = NULL;
}
static bool
pagerhist_extend(PagerHistoryBuf *ph, size_t minsz) {
size_t buffer_size = ringbuf_capacity(ph->ringbuf);
if (buffer_size >= ph->maximum_size) return false;
size_t newsz = MIN(ph->maximum_size, buffer_size + MAX(1024u * 1024u, minsz));
ringbuf_t newbuf = ringbuf_new(newsz);
if (!newbuf) return false;
size_t count = ringbuf_bytes_used(ph->ringbuf);
if (count) ringbuf_copy(newbuf, ph->ringbuf, count);
ringbuf_free((ringbuf_t *)&ph->ringbuf);
ph->ringbuf = newbuf;
return true;
}
static void
pagerhist_clear(HistoryBuf *self) {
if (self->pagerhist && self->pagerhist->ringbuf) {
ringbuf_reset(self->pagerhist->ringbuf);
size_t rsz = initial_pagerhist_ringbuf_sz(self->pagerhist->maximum_size);
void *rbuf = ringbuf_new(rsz);
if (rbuf) {
ringbuf_free((ringbuf_t *)&self->pagerhist->ringbuf);
self->pagerhist->ringbuf = rbuf;
}
}
}
static HistoryBuf *
create_historybuf(PyTypeObject *type, unsigned int xnum, unsigned int ynum, unsigned int pagerhist_sz, TextCache *tc) {
if (xnum == 0 || ynum == 0) {
PyErr_SetString(PyExc_ValueError, "Cannot create an empty history buffer");
return NULL;
}
HistoryBuf *self = (HistoryBuf *)type->tp_alloc(type, 0);
if (self != NULL) {
self->xnum = xnum;
self->ynum = ynum;
self->num_segments = 0;
add_segment(self, 1);
self->text_cache = tc_incref(tc);
self->line = alloc_line(self->text_cache);
self->line->xnum = xnum;
self->pagerhist = alloc_pagerhist(pagerhist_sz);
}
return self;
}
static PyObject *
new_history_object(PyTypeObject *type, PyObject *args, PyObject UNUSED *kwds) {
unsigned int xnum = 1, ynum = 1, pagerhist_sz = 0;
if (!PyArg_ParseTuple(args, "II|I", &ynum, &xnum, &pagerhist_sz)) return NULL;
TextCache *tc = tc_alloc();
if (!tc) return PyErr_NoMemory();
HistoryBuf *ans = create_historybuf(type, xnum, ynum, pagerhist_sz, tc);
tc_decref(tc);
return (PyObject *)ans;
}
static void
dealloc(HistoryBuf *self) {
Py_CLEAR(self->line);
for (size_t i = 0; i < self->num_segments; i++) free_segment(self->segments + i);
free(self->segments);
free_pagerhist(self);
tc_decref(self->text_cache);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static index_type
index_of(HistoryBuf *self, index_type lnum) {
// The index (buffer position) of the line with line number lnum
// This is reverse indexing, i.e. lnum = 0 corresponds to the *last* line in the buffer.
if (self->count == 0) return 0;
index_type idx = self->count - 1 - MIN(self->count - 1, lnum);
return (self->start_of_data + idx) % self->ynum;
}
static bool
hb_line_is_continued(HistoryBuf *self, index_type num) {
if (num == self->start_of_data) {
size_t sz;
if (self->pagerhist && self->pagerhist->ringbuf && (sz = ringbuf_bytes_used(self->pagerhist->ringbuf)) > 0) {
size_t pos = ringbuf_findchr(self->pagerhist->ringbuf, '\n', sz - 1);
if (pos >= sz) return true; // ringbuf does not end with a newline
}
return false;
}
return cpu_lineptr(self, (num + self->ynum - 1) % self->ynum)[self->xnum - 1].next_char_was_wrapped;
}
static void
init_line(HistoryBuf *self, index_type num, Line *l) {
// Initialize the line l, setting its pointer to the offsets for the line at index (buffer position) num
l->cpu_cells = cpu_lineptr(self, num);
l->gpu_cells = gpu_lineptr(self, num);
l->attrs = *attrptr(self, num);
}
void
historybuf_init_line(HistoryBuf *self, index_type lnum, Line *l) {
init_line(self, index_of(self, lnum), l);
}
bool
historybuf_is_line_continued(HistoryBuf *self, index_type lnum) {
return hb_line_is_continued(self, index_of(self, lnum));
}
bool
history_buf_endswith_wrap(HistoryBuf *self) {
return cpu_lineptr(self, index_of(self, 0))[self->xnum - 1].next_char_was_wrapped;
}
CPUCell *
historybuf_cpu_cells(HistoryBuf *self, index_type lnum) {
return cpu_lineptr(self, index_of(self, lnum));
}
void
historybuf_mark_line_clean(HistoryBuf *self, index_type y) {
attrptr(self, index_of(self, y))->has_dirty_text = false;
}
void
historybuf_mark_line_dirty(HistoryBuf *self, index_type y) {
attrptr(self, index_of(self, y))->has_dirty_text = true;
}
void
historybuf_set_line_has_image_placeholders(HistoryBuf *self, index_type y, bool val) {
attrptr(self, index_of(self, y))->has_image_placeholders = val;
}
void
historybuf_clear(HistoryBuf *self) {
pagerhist_clear(self);
self->count = 0;
self->start_of_data = 0;
for (size_t i = 0; i < self->num_segments; i++) free_segment(self->segments + i);
free(self->segments);
self->segments = NULL;
self->num_segments = 0;
add_segment(self, 1);
}
static bool
pagerhist_write_bytes(PagerHistoryBuf *ph, const uint8_t *buf, size_t sz) {
if (sz > ph->maximum_size) return false;
if (!sz) return true;
size_t space_in_ringbuf = ringbuf_bytes_free(ph->ringbuf);
if (sz > space_in_ringbuf) pagerhist_extend(ph, sz);
ringbuf_memcpy_into(ph->ringbuf, buf, sz);
return true;
}
static bool
pagerhist_ensure_start_is_valid_utf8(PagerHistoryBuf *ph) {
uint8_t scratch[8];
size_t num = ringbuf_memcpy_from(scratch, ph->ringbuf, arraysz(scratch));
uint32_t codep;
UTF8State state = UTF8_ACCEPT;
size_t count = 0;
size_t last_reject_at = 0;
while (count < num) {
decode_utf8(&state, &codep, scratch[count++]);
if (state == UTF8_ACCEPT) break;
if (state == UTF8_REJECT) {
state = UTF8_ACCEPT;
last_reject_at = count;
}
}
if (last_reject_at) {
ringbuf_memmove_from(scratch, ph->ringbuf, last_reject_at);
return true;
}
return false;
}
static bool
pagerhist_write_ucs4(PagerHistoryBuf *ph, const Py_UCS4 *buf, size_t sz) {
uint8_t scratch[4];
for (size_t i = 0; i < sz; i++) {
unsigned int num = encode_utf8(buf[i], (char *)scratch);
if (!pagerhist_write_bytes(ph, scratch, num)) return false;
}
return true;
}
static void
pagerhist_push(HistoryBuf *self, ANSIBuf *as_ansi_buf) {
PagerHistoryBuf *ph = self->pagerhist;
if (!ph) return;
Line l = {.xnum = self->xnum, .text_cache = self->text_cache};
init_line(self, self->start_of_data, &l);
ANSILineState s = {.output_buf = as_ansi_buf};
as_ansi_buf->len = 0;
line_as_ansi(&l, &s, 0, l.xnum, 0, true);
pagerhist_write_bytes(ph, (const uint8_t *)"\x1b[m", 3);
if (pagerhist_write_ucs4(ph, as_ansi_buf->buf, as_ansi_buf->len)) {
char line_end[2];
size_t num = 0;
line_end[num++] = '\r';
if (!l.cpu_cells[l.xnum - 1].next_char_was_wrapped) line_end[num++] = '\n';
pagerhist_write_bytes(ph, (const uint8_t *)line_end, num);
}
}
static index_type
historybuf_push(HistoryBuf *self, ANSIBuf *as_ansi_buf, bool *needs_clear) {
index_type idx = (self->start_of_data + self->count) % self->ynum;
if (self->count == self->ynum) {
pagerhist_push(self, as_ansi_buf);
self->start_of_data = (self->start_of_data + 1) % self->ynum;
*needs_clear = true;
} else {
self->count++;
*needs_clear = false;
}
return idx;
}
static void
prefetch_line_for_write(HistoryBuf *self, index_type y) {
// The history buffer is typically much larger than the CPU cache, so the
// line copy in historybuf_add_line() stalls acquiring ownership of the
// destination cache lines. Prefetching the slot that the next call will
// write to overlaps those misses with the parsing/drawing of the next
// line, speeding up bulk text throughput by ~35% (see benchmark.py).
if (y / SEGMENT_SIZE >= self->num_segments) return; // must not trigger segment allocation
const char *cpu = (const char *)cpu_lineptr(self, y);
const char *gpu = (const char *)gpu_lineptr(self, y);
const size_t cache_line_sz = 64;
for (size_t i = 0; i < self->xnum * sizeof(CPUCell); i += cache_line_sz) __builtin_prefetch(cpu + i, 1, 0);
for (size_t i = 0; i < self->xnum * sizeof(GPUCell); i += cache_line_sz) __builtin_prefetch(gpu + i, 1, 0);
}
void
historybuf_add_line(HistoryBuf *self, const Line *line, ANSIBuf *as_ansi_buf) {
bool needs_clear;
index_type idx = historybuf_push(self, as_ansi_buf, &needs_clear);
init_line(self, idx, self->line);
copy_line(line, self->line);
*attrptr(self, idx) = line->attrs;
prefetch_line_for_write(self, (self->start_of_data + self->count) % self->ynum);
}
bool
historybuf_pop_line(HistoryBuf *self, Line *line) {
if (self->count <= 0) return false;
index_type idx = (self->start_of_data + self->count - 1) % self->ynum;
init_line(self, idx, line);
self->count--;
return true;
}
void
historybuf_delete_newest_lines(HistoryBuf *self, index_type count) {
if (!count) return;
count = MIN(self->count, count);
self->count -= count - 1;
// now nuke multi cell chars that overlap onto the last line
index_type idx = (self->start_of_data + self->count - 1) % self->ynum;
init_line(self, idx, self->line);
CPUCell *cells = self->line->cpu_cells;
self->count--;
for (index_type x = 0; x < self->line->xnum; x++) {
CPUCell *c = cells + x;
if (c->is_multicell && c->y) {
for (index_type i = 0, pos = self->count; i < c->y && pos; i++, pos--) {
index_type idx = (self->start_of_data + pos - 1) % self->ynum;
init_line(self, idx, self->line);
CPUCell *m = self->line->cpu_cells + x;
cell_set_char(m, 0);
m->is_multicell = false;
clear_sprite_position(self->line->gpu_cells[x]);
}
}
}
}
static PyObject *
line(HistoryBuf *self, PyObject *val) {
#define line_doc "Return the line with line number val. This buffer grows upwards, i.e. 0 is the most recently added line"
if (self->count == 0) {
PyErr_SetString(PyExc_IndexError, "This buffer is empty");
return NULL;
}
index_type lnum = PyLong_AsUnsignedLong(val);
if (lnum >= self->count) {
PyErr_SetString(PyExc_IndexError, "Out of bounds");
return NULL;
}
init_line(self, index_of(self, lnum), self->line);
Py_INCREF(self->line);
return (PyObject *)self->line;
}
static PyObject *
__str__(HistoryBuf *self) {
PyObject *lines = PyTuple_New(self->count);
if (lines == NULL) return PyErr_NoMemory();
RAII_ANSIBuf(buf);
for (index_type i = 0; i < self->count; i++) {
init_line(self, index_of(self, i), self->line);
PyObject *t = line_as_unicode(self->line, false, &buf);
if (t == NULL) {
Py_CLEAR(lines);
return NULL;
}
PyTuple_SET_ITEM(lines, i, t);
}
PyObject *sep = PyUnicode_FromString("\n");
PyObject *ans = PyUnicode_Join(sep, lines);
Py_CLEAR(lines);
Py_CLEAR(sep);
return ans;
}
static PyObject *
push(HistoryBuf *self, PyObject *args) {
#define push_doc "Push a line into this buffer, removing the oldest line, if necessary"
Line *line;
if (!PyArg_ParseTuple(args, "O!", &Line_Type, &line)) return NULL;
ANSIBuf as_ansi_buf = {0};
historybuf_add_line(self, line, &as_ansi_buf);
free(as_ansi_buf.buf);
Py_RETURN_NONE;
}
static PyObject *
as_ansi(HistoryBuf *self, PyObject *callback) {
#define as_ansi_doc "as_ansi(callback) -> The contents of this buffer as ANSI escaped text. callback is called with each successive line."
Line l = {.xnum = self->xnum, .text_cache = self->text_cache};
ANSIBuf output = {0};
ANSILineState s = {.output_buf = &output};
for (unsigned int i = 0; i < self->count; i++) {
init_line(self, i, &l);
output.len = 0;
line_as_ansi(&l, &s, 0, l.xnum, 0, true);
if (!l.cpu_cells[l.xnum - 1].next_char_was_wrapped) {
ensure_space_for(&output, buf, Py_UCS4, output.len + 1, capacity, 2048, false);
output.buf[output.len++] = '\n';
}
PyObject *ans = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output.buf, output.len);
if (ans == NULL) {
PyErr_NoMemory();
goto end;
}
PyObject *ret = PyObject_CallFunctionObjArgs(callback, ans, NULL);
Py_CLEAR(ans);
if (ret == NULL) goto end;
Py_CLEAR(ret);
}
end:
free(output.buf);
if (PyErr_Occurred()) return NULL;
Py_RETURN_NONE;
}
static char_type
pagerhist_remove_char(PagerHistoryBuf *ph, unsigned *count, uint8_t record[8]) {
uint32_t codep;
UTF8State state = UTF8_ACCEPT;
*count = 0;
size_t num = ringbuf_bytes_used(ph->ringbuf);
while (num--) {
record[*count] = ringbuf_move_char(ph->ringbuf);
decode_utf8(&state, &codep, record[*count]);
*count += 1;
if (state == UTF8_REJECT) {
codep = 0;
break;
}
if (state == UTF8_ACCEPT) break;
}
return codep;
}
static void
pagerhist_rewrap_to(HistoryBuf *self, index_type cells_in_line) {
PagerHistoryBuf *ph = self->pagerhist;
if (!ph->ringbuf || !ringbuf_bytes_used(ph->ringbuf)) return;
PagerHistoryBuf *nph = calloc(1, sizeof(PagerHistoryBuf));
if (!nph) return;
nph->maximum_size = ph->maximum_size;
nph->ringbuf = ringbuf_new(MIN(ph->maximum_size, ringbuf_capacity(ph->ringbuf) + 4096));
if (!nph->ringbuf) {
free(nph);
return;
}
ssize_t ch_width = 0;
unsigned count;
uint8_t record[8];
index_type num_in_current_line = 0;
char_type ch;
WCSState wcs_state;
initialize_wcs_state(&wcs_state);
#define WRITE_CHAR() \
{ \
if (num_in_current_line + ch_width > cells_in_line) { \
pagerhist_write_bytes(nph, (const uint8_t *)"\r", 1); \
num_in_current_line = 0; \
} \
if (ch_width >= 0 || (int)num_in_current_line >= -ch_width) num_in_current_line += ch_width; \
pagerhist_write_bytes(nph, record, count); \
}
while (ringbuf_bytes_used(ph->ringbuf)) {
ch = pagerhist_remove_char(ph, &count, record);
if (ch == '\n') {
initialize_wcs_state(&wcs_state);
ch_width = 1;
WRITE_CHAR();
num_in_current_line = 0;
} else if (ch != '\r') {
ch_width = wcswidth_step(&wcs_state, ch);
WRITE_CHAR();
}
}
free_pagerhist(self);
self->pagerhist = nph;
#undef WRITE_CHAR
}
static PyObject *
pagerhist_write(HistoryBuf *self, PyObject *what) {
if (self->pagerhist && self->pagerhist->maximum_size) {
if (PyBytes_Check(what)) pagerhist_write_bytes(self->pagerhist, (const uint8_t *)PyBytes_AS_STRING(what), PyBytes_GET_SIZE(what));
else if (PyUnicode_Check(what) && PyUnicode_READY(what) == 0) {
Py_UCS4 *buf = PyUnicode_AsUCS4Copy(what);
if (buf) {
pagerhist_write_ucs4(self->pagerhist, buf, PyUnicode_GET_LENGTH(what));
PyMem_Free(buf);
}
}
}
Py_RETURN_NONE;
}
static const uint8_t *
reverse_find(const uint8_t *haystack, size_t haystack_sz, const uint8_t *needle) {
const size_t needle_sz = strlen((const char *)needle);
if (!needle_sz || needle_sz > haystack_sz) return NULL;
const uint8_t *p = haystack + haystack_sz - (needle_sz - 1);
while (--p >= haystack) {
if (*p == needle[0] && memcmp(p, needle, MIN(needle_sz, haystack_sz - (p - haystack))) == 0) return p;
}
return NULL;
}
static PyObject *
pagerhist_as_bytes(HistoryBuf *self, PyObject *args) {
int upto_output_start = 0;
if (!PyArg_ParseTuple(args, "|p", &upto_output_start)) return NULL;
#define ph self->pagerhist
if (!ph || !ringbuf_bytes_used(ph->ringbuf)) return PyBytes_FromStringAndSize("", 0);
pagerhist_ensure_start_is_valid_utf8(ph);
if (ph->rewrap_needed) pagerhist_rewrap_to(self, self->xnum);
size_t sz = ringbuf_bytes_used(ph->ringbuf);
PyObject *ans = PyBytes_FromStringAndSize(NULL, sz);
if (!ans) return NULL;
uint8_t *buf = (uint8_t *)PyBytes_AS_STRING(ans);
ringbuf_memcpy_from(buf, ph->ringbuf, sz);
if (upto_output_start) {
const uint8_t *p = reverse_find(buf, sz, (const uint8_t *)"\x1b]133;C\x1b\\");
if (p) {
PyObject *t = PyBytes_FromStringAndSize((const char *)p, sz - (p - buf));
Py_DECREF(ans);
ans = t;
}
}
return ans;
#undef ph
}
static PyObject *
pagerhist_as_text(HistoryBuf *self, PyObject *args) {
PyObject *ans = NULL;
PyObject *bytes = pagerhist_as_bytes(self, args);
if (bytes) {
ans = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes), "ignore");
Py_DECREF(bytes);
}
return ans;
}
typedef struct {
Line line;
HistoryBuf *self;
} GetLineWrapper;
static Line *
get_line(HistoryBuf *self, index_type y, Line *l) {
init_line(self, index_of(self, self->count - y - 1), l);
return l;
}
static Line *
get_line_wrapper(void *x, int y) {
GetLineWrapper *glw = x;
get_line(glw->self, y, &glw->line);
return &glw->line;
}
PyObject *
as_text_history_buf(HistoryBuf *self, PyObject *args, ANSIBuf *output) {
GetLineWrapper glw = {.self = self};
glw.line.xnum = self->xnum;
glw.line.text_cache = self->text_cache;
PyObject *ans = as_text_generic(args, &glw, get_line_wrapper, self->count, output, true);
return ans;
}
static PyObject *
dirty_lines(HistoryBuf *self, PyObject *a UNUSED) {
#define dirty_lines_doc "dirty_lines() -> Line numbers of all lines that have dirty text."
PyObject *ans = PyList_New(0);
for (index_type i = 0; i < self->count; i++) {
if (attrptr(self, i)->has_dirty_text) { PyList_Append(ans, PyLong_FromUnsignedLong(i)); }
}
return ans;
}
static PyObject *
pagerhist_rewrap(HistoryBuf *self, PyObject *xnum) {
if (self->pagerhist) { pagerhist_rewrap_to(self, PyLong_AsUnsignedLong(xnum)); }
Py_RETURN_NONE;
}
static PyObject *
is_continued(HistoryBuf *self, PyObject *val) {
#define is_continued_doc "is_continued(y) -> Whether the line y is continued or not"
unsigned long y = PyLong_AsUnsignedLong(val);
if (y >= self->count) {
PyErr_SetString(PyExc_ValueError, "Out of bounds.");
return NULL;
}
index_type num = index_of(self, self->count - y - 1);
if (hb_line_is_continued(self, num)) { Py_RETURN_TRUE; }
Py_RETURN_FALSE;
}
static PyObject *
endswith_wrap(HistoryBuf *self, PyObject *val UNUSED) {
#define endswith_wrap_doc "endswith_wrap() -> Whether the last line is wrapped at the end of the buffer"
if (history_buf_endswith_wrap(self)) { Py_RETURN_TRUE; }
Py_RETURN_FALSE;
}
// Boilerplate {{{
static PyObject *rewrap(HistoryBuf *self, PyObject *args);
#define rewrap_doc ""
static PyMethodDef methods[] = {
METHOD(line, METH_O) METHOD(is_continued, METH_O) METHOD(endswith_wrap, METH_NOARGS) METHOD(as_ansi, METH_O) METHODB(pagerhist_write, METH_O),
METHODB(pagerhist_rewrap, METH_O),
METHODB(pagerhist_as_text, METH_VARARGS),
METHODB(pagerhist_as_bytes, METH_VARARGS),
METHOD(dirty_lines, METH_NOARGS) METHOD(push, METH_VARARGS) METHOD(rewrap, METH_VARARGS){NULL, NULL, 0, NULL} /* Sentinel */
};
static PyMemberDef members[] = {
{"xnum", T_UINT, offsetof(HistoryBuf, xnum), READONLY, "xnum"},
{"ynum", T_UINT, offsetof(HistoryBuf, ynum), READONLY, "ynum"},
{"count", T_UINT, offsetof(HistoryBuf, count), READONLY, "count"},
{NULL} /* Sentinel */
};
PyTypeObject HistoryBuf_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.HistoryBuf",
.tp_basicsize = sizeof(HistoryBuf),
.tp_dealloc = (destructor)dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "History buffers",
.tp_methods = methods,
.tp_members = members,
.tp_str = (reprfunc)__str__,
.tp_new = new_history_object};
INIT_TYPE(HistoryBuf)
HistoryBuf *
alloc_historybuf(unsigned int lines, unsigned int columns, unsigned int pagerhist_sz, TextCache *tc) {
return create_historybuf(&HistoryBuf_Type, columns, lines, pagerhist_sz, tc);
}
// }}}
static void
history_buf_set_last_char_as_continuation(HistoryBuf *self, index_type y, bool wrapped) {
if (self->count > 0) { cpu_lineptr(self, index_of(self, y))[self->xnum - 1].next_char_was_wrapped = wrapped; }
}
index_type
historybuf_next_dest_line(HistoryBuf *self, ANSIBuf *as_ansi_buf, Line *src_line, index_type dest_y, Line *dest_line, bool continued) {
history_buf_set_last_char_as_continuation(self, 0, continued);
bool needs_clear;
index_type idx = historybuf_push(self, as_ansi_buf, &needs_clear);
*attrptr(self, idx) = src_line->attrs;
init_line(self, idx, dest_line);
// the slot may hold a stale line from stolen segments
zero_at_ptr_count(dest_line->cpu_cells, dest_line->xnum);
zero_at_ptr_count(dest_line->gpu_cells, dest_line->xnum);
return dest_y + 1;
}
HistoryBuf *
historybuf_alloc_for_rewrap(unsigned int columns, HistoryBuf *self) {
if (!self) return NULL;
HistoryBuf *ans = alloc_historybuf(self->ynum, columns, 0, self->text_cache);
if (ans) {
if (ans->num_segments < self->num_segments) add_segment(ans, self->num_segments - ans->num_segments);
ans->count = 0;
ans->start_of_data = 0;
}
return ans;
}
void
historybuf_finish_rewrap(HistoryBuf *dest, HistoryBuf *src) {
for (index_type i = 0; i < dest->count; i++) attrptr(dest, (dest->start_of_data + i) % dest->ynum)->has_dirty_text = true;
dest->pagerhist = src->pagerhist;
src->pagerhist = NULL;
if (dest->pagerhist && dest->xnum != src->xnum && ringbuf_bytes_used(dest->pagerhist->ringbuf)) dest->pagerhist->rewrap_needed = true;
}
void
historybuf_fast_rewrap(HistoryBuf *dest, HistoryBuf *src, index_type count, bool steal) {
// dest must have been created by historybuf_alloc_for_rewrap() with the same width as src
dest->count = MIN(count, src->count);
dest->start_of_data = src->start_of_data;
if (steal) {
SWAP(dest->segments, src->segments);
SWAP(dest->num_segments, src->num_segments);
src->count = 0;
src->start_of_data = 0;
} else {
for (index_type i = 0; i < src->num_segments; i++) {
memcpy(dest->segments[i].cpu_cells, src->segments[i].cpu_cells, SEGMENT_SIZE * src->xnum * sizeof(CPUCell));
memcpy(dest->segments[i].gpu_cells, src->segments[i].gpu_cells, SEGMENT_SIZE * src->xnum * sizeof(GPUCell));
memcpy(dest->segments[i].line_attrs, src->segments[i].line_attrs, SEGMENT_SIZE * sizeof(LineAttrs));
}
}
}
static PyObject *
rewrap(HistoryBuf *self, PyObject *args) {
unsigned xnum;
if (!PyArg_ParseTuple(args, "I", &xnum)) return NULL;
ANSIBuf as_ansi_buf = {0};
LineBuf *dummy = alloc_linebuf(4, self->xnum, self->text_cache);
if (!dummy) return PyErr_NoMemory();
RAII_PyObject(cleanup, (PyObject *)dummy);
(void)cleanup;
TrackCursor cursors[1] = {{.is_sentinel = true}};
ResizeResult r = resize_screen_buffers(dummy, self, HISTORY_PRESERVE, 8, xnum, &as_ansi_buf, cursors);
free(as_ansi_buf.buf);
if (!r.ok) return PyErr_NoMemory();
Py_CLEAR(r.lb);
return (PyObject *)r.hb;
}
+46
View File
@@ -0,0 +1,46 @@
/*
* history.h
* Copyright (C) 2024 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "line.h"
typedef struct {
GPUCell *gpu_cells;
CPUCell *cpu_cells;
LineAttrs *line_attrs;
void *mem;
size_t mmap_size;
} HistoryBufSegment;
typedef struct {
void *ringbuf;
size_t maximum_size;
bool rewrap_needed;
} PagerHistoryBuf;
typedef struct {
PyObject_HEAD
index_type xnum,
ynum, num_segments;
HistoryBufSegment *segments;
PagerHistoryBuf *pagerhist;
Line *line;
TextCache *text_cache;
index_type start_of_data, count;
} HistoryBuf;
HistoryBuf *alloc_historybuf(unsigned int, unsigned int, unsigned int, TextCache *tc);
HistoryBuf *historybuf_alloc_for_rewrap(unsigned int columns, HistoryBuf *self);
void historybuf_finish_rewrap(HistoryBuf *dest, HistoryBuf *src);
void historybuf_fast_rewrap(HistoryBuf *dest, HistoryBuf *src, index_type count, bool steal);
index_type historybuf_next_dest_line(HistoryBuf *self, ANSIBuf *as_ansi_buf, Line *src_line, index_type dest_y, Line *dest_line, bool continued);
bool historybuf_is_line_continued(HistoryBuf *self, index_type lnum);
void historybuf_delete_newest_lines(HistoryBuf *self, index_type count);
+186
View File
@@ -0,0 +1,186 @@
/*
* hyperlink.c
* Copyright (C) 2020 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "hyperlink.h"
#include "lineops.h"
#include <string.h>
#define MAX_KEY_LEN 2048
#define MAX_ID_LEN 256
#define NAME hyperlink_map
#define KEY_TY const char *
#define VAL_TY hyperlink_id_type
#include "kitty-verstable.h"
#define hyperlink_for_loop vt_create_for_loop(hyperlink_map_itr, itr, &pool->map)
typedef const char *hyperlink;
typedef struct HyperLinks {
hyperlink *items;
size_t count, capacity;
} HyperLinks;
typedef struct {
HyperLinks array;
hyperlink_map map;
hyperlink_id_type adds_since_last_gc;
} HyperLinkPool;
static void
free_hyperlink_items(HyperLinks array) {
for (size_t i = 1; i < array.count; i++) free((void *)array.items[i]);
}
static void
clear_pool(HyperLinkPool *pool) {
if (pool->array.items) {
free_hyperlink_items(pool->array);
free(pool->array.items);
}
vt_cleanup(&pool->map);
zero_at_ptr(&(pool->array));
pool->adds_since_last_gc = 0;
}
HYPERLINK_POOL_HANDLE
alloc_hyperlink_pool(void) {
HyperLinkPool *ans = calloc(1, sizeof(HyperLinkPool));
if (ans) vt_init(&ans->map);
return (HYPERLINK_POOL_HANDLE)ans;
}
void
clear_hyperlink_pool(HYPERLINK_POOL_HANDLE h) {
if (h) clear_pool((HyperLinkPool *)h);
}
void
free_hyperlink_pool(HYPERLINK_POOL_HANDLE h) {
if (h) {
HyperLinkPool *pool = (HyperLinkPool *)h;
clear_pool(pool);
free(pool);
}
}
static const char *
dupstr(const char *src, size_t len) {
char *ans = malloc(len + 1);
if (!ans) fatal("Out of memory");
memcpy(ans, src, len);
ans[len] = 0;
return ans;
}
static void
process_cell(HyperLinkPool *pool, hyperlink_id_type *map, HyperLinks clone, CPUCell *c) {
if (!c->hyperlink_id) return;
if (c->hyperlink_id >= clone.count) {
c->hyperlink_id = 0;
return;
}
hyperlink_id_type new_id = map[c->hyperlink_id];
if (!new_id) {
new_id = pool->array.count++;
map[c->hyperlink_id] = new_id;
pool->array.items[new_id] = clone.items[c->hyperlink_id];
clone.items[c->hyperlink_id] = NULL;
if (vt_is_end(vt_insert(&pool->map, pool->array.items[new_id], new_id))) fatal("Out of memory");
}
c->hyperlink_id = new_id;
}
static void
remap_hyperlink_ids(Screen *self, bool preserve_hyperlinks_in_history, hyperlink_id_type *map, HyperLinks clone) {
HyperLinkPool *pool = (HyperLinkPool *)self->hyperlink_pool;
if (self->historybuf->count && preserve_hyperlinks_in_history) {
for (index_type y = self->historybuf->count; y-- > 0;) {
CPUCell *cells = historybuf_cpu_cells(self->historybuf, y);
for (index_type x = 0; x < self->historybuf->xnum; x++) process_cell(pool, map, clone, cells + x);
}
}
LineBuf *second = self->linebuf, *first = second == self->main_linebuf ? self->alt_linebuf : self->main_linebuf;
for (index_type i = 0; i < self->lines * self->columns; i++) process_cell(pool, map, clone, first->cpu_cell_buf + i);
for (index_type i = 0; i < self->lines * self->columns; i++) process_cell(pool, map, clone, second->cpu_cell_buf + i);
}
static void
_screen_garbage_collect_hyperlink_pool(Screen *screen, bool preserve_hyperlinks_in_history) {
HyperLinkPool *pool = (HyperLinkPool *)screen->hyperlink_pool;
if (!pool->array.count) return;
pool->adds_since_last_gc = 0;
RAII_ALLOC(hyperlink_id_type, map, calloc(pool->array.count, sizeof(hyperlink_id_type)));
RAII_ALLOC(void, buf, malloc(pool->array.count * sizeof(pool->array.items[0])));
if (!map || !buf) fatal("Out of memory");
HyperLinks clone = {.capacity = pool->array.count, .count = pool->array.count, .items = buf};
memcpy(buf, pool->array.items, pool->array.count * sizeof(pool->array.items[0]));
vt_cleanup(&pool->map);
pool->array.count = 1; // First id must be 1
remap_hyperlink_ids(screen, preserve_hyperlinks_in_history, map, clone);
free_hyperlink_items(clone);
}
void
screen_garbage_collect_hyperlink_pool(Screen *screen) {
_screen_garbage_collect_hyperlink_pool(screen, true);
}
hyperlink_id_type
get_id_for_hyperlink(Screen *screen, const char *id, const char *url) {
if (!url) return 0;
HyperLinkPool *pool = (HyperLinkPool *)screen->hyperlink_pool;
static char key[MAX_KEY_LEN] = {0};
int keylen = snprintf(key, MAX_KEY_LEN - 1, "%.*s:%s", MAX_ID_LEN, id ? id : "", url);
if (keylen < 0) keylen = strlen(key);
else keylen = MIN(keylen, MAX_KEY_LEN - 2); // snprintf returns how many chars it would have written in case of truncation
key[keylen] = 0;
hyperlink_map_itr itr = vt_get(&pool->map, key);
if (!vt_is_end(itr)) return itr.data->val;
// Collect before inserting the new hyperlink, which has no cell references yet.
if (++pool->adds_since_last_gc > 8192) screen_garbage_collect_hyperlink_pool(screen);
if (pool->array.count >= HYPERLINK_MAX_NUMBER - 1) {
screen_garbage_collect_hyperlink_pool(screen);
if (pool->array.count >= HYPERLINK_MAX_NUMBER - 128) {
log_error("Too many hyperlinks, discarding hyperlinks in scrollback");
_screen_garbage_collect_hyperlink_pool(screen, false);
if (pool->array.count >= HYPERLINK_MAX_NUMBER) {
log_error("Too many hyperlinks, discarding hyperlink: %s", key);
return 0;
}
}
}
if (!pool->array.count) pool->array.count = 1; // First id must be 1
ensure_space_for(&(pool->array), items, hyperlink, pool->array.count + 1, capacity, 256, false);
hyperlink_id_type new_id = pool->array.count++;
pool->array.items[new_id] = dupstr(key, keylen);
if (vt_is_end(vt_insert(&pool->map, pool->array.items[new_id], new_id))) fatal("Out of memory");
return new_id;
}
const char *
get_hyperlink_for_id(const HYPERLINK_POOL_HANDLE handle, hyperlink_id_type id, bool only_url) {
HyperLinkPool *pool = (HyperLinkPool *)handle;
if (id >= pool->array.count) return NULL;
return only_url ? strstr(pool->array.items[id], ":") + 1 : pool->array.items[id];
}
PyObject *
screen_hyperlinks_as_set(Screen *screen) {
HyperLinkPool *pool = (HyperLinkPool *)screen->hyperlink_pool;
RAII_PyObject(ans, PySet_New(0));
if (ans) {
hyperlink_for_loop {
RAII_PyObject(e, Py_BuildValue("sH", itr.data->key, itr.data->val));
if (!e || PySet_Add(ans, e) != 0) return NULL;
}
}
Py_XINCREF(ans);
return ans;
}
+16
View File
@@ -0,0 +1,16 @@
/*
* Copyright (C) 2020 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "screen.h"
HYPERLINK_POOL_HANDLE alloc_hyperlink_pool(void);
void free_hyperlink_pool(HYPERLINK_POOL_HANDLE);
void clear_hyperlink_pool(HYPERLINK_POOL_HANDLE);
hyperlink_id_type get_id_for_hyperlink(Screen *, const char *, const char *);
PyObject *screen_hyperlinks_as_set(Screen *screen);
void screen_garbage_collect_hyperlink_pool(Screen *screen);
+272
View File
@@ -0,0 +1,272 @@
/* $Id: qsort.h,v 1.5 2008-01-28 18:16:49 mjt Exp $
* Adopted from GNU glibc by Mjt.
* See stdlib/qsort.c in glibc */
/* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/* in-line qsort implementation. Differs from traditional qsort() routine
* in that it is a macro, not a function, and instead of passing an address
* of a comparison routine to the function, it is possible to inline
* comparison routine, thus speeding up sorting a lot.
*
* Usage:
* #include "iqsort.h"
* #define islt(a,b) (strcmp((*a),(*b))<0)
* char *arr[];
* int n;
* QSORT(char*, arr, n, islt);
*
* The "prototype" and 4 arguments are:
* QSORT(TYPE,BASE,NELT,ISLT)
* 1) type of each element, TYPE,
* 2) address of the beginning of the array, of type TYPE*,
* 3) number of elements in the array, and
* 4) comparison routine.
* Array pointer and number of elements are referenced only once.
* This is similar to a call
* qsort(BASE,NELT,sizeof(TYPE),ISLT)
* with the difference in last parameter.
* Note the islt macro/routine (it receives pointers to two elements):
* the only condition of interest is whenever one element is less than
* another, no other conditions (greater than, equal to etc) are tested.
* So, for example, to define integer sort, use:
* #define islt(a,b) ((*a)<(*b))
* QSORT(int, arr, n, islt)
*
* The macro could be used to implement a sorting function (see examples
* below), or to implement the sorting algorithm inline. That is, either
* create a sorting function and use it whenever you want to sort something,
* or use QSORT() macro directly instead a call to such routine. Note that
* the macro expands to quite some code (compiled size of int qsort on x86
* is about 700..800 bytes).
*
* Using this macro directly it isn't possible to implement traditional
* qsort() routine, because the macro assumes sizeof(element) == sizeof(TYPE),
* while qsort() allows element size to be different.
*
* Several ready-to-use examples:
*
* Sorting array of integers:
* void int_qsort(int *arr, unsigned n) {
* #define int_lt(a,b) ((*a)<(*b))
* QSORT(int, arr, n, int_lt);
* }
*
* Sorting array of string pointers:
* void str_qsort(char *arr[], unsigned n) {
* #define str_lt(a,b) (strcmp((*a),(*b)) < 0)
* QSORT(char*, arr, n, str_lt);
* }
*
* Sorting array of structures:
*
* struct elt {
* int key;
* ...
* };
* void elt_qsort(struct elt *arr, unsigned n) {
* #define elt_lt(a,b) ((a)->key < (b)->key)
* QSORT(struct elt, arr, n, elt_lt);
* }
*
* And so on.
*/
/* Swap two items pointed to by A and B using temporary buffer t. */
#define _QSORT_SWAP(a, b, t) ((void)((t = *a), (*a = *b), (*b = t)))
/* Discontinue quicksort algorithm when partition gets below this size.
This particular magic number was chosen to work best on a Sun 4/260. */
#define _QSORT_MAX_THRESH 4
/* Stack node declarations used to store unfulfilled partition obligations
* (inlined in QSORT).
typedef struct {
QSORT_TYPE *_lo, *_hi;
} qsort_stack_node;
*/
/* The next 4 #defines implement a very fast in-line stack abstraction. */
/* The stack needs log (total_elements) entries (we could even subtract
log(MAX_THRESH)). Since total_elements has type unsigned, we get as
upper bound for log (total_elements):
bits per byte (CHAR_BIT) * sizeof(unsigned). */
#define _QSORT_STACK_SIZE (8 * sizeof(unsigned))
#define _QSORT_PUSH(top, low, high) (((top->_lo = (low)), (top->_hi = (high)), ++top))
#define _QSORT_POP(low, high, top) ((--top, (low = top->_lo), (high = top->_hi)))
#define _QSORT_STACK_NOT_EMPTY (_stack < _top)
/* Order size using quicksort. This implementation incorporates
four optimizations discussed in Sedgewick:
1. Non-recursive, using an explicit stack of pointer that store the
next array partition to sort. To save time, this maximum amount
of space required to store an array of SIZE_MAX is allocated on the
stack. Assuming a 32-bit (64 bit) integer for size_t, this needs
only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
Pretty cheap, actually.
2. Chose the pivot element using a median-of-three decision tree.
This reduces the probability of selecting a bad pivot value and
eliminates certain extraneous comparisons.
3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
insertion sort to order the MAX_THRESH items within each partition.
This is a big win, since insertion sort is faster for small, mostly
sorted array segments.
4. The larger of the two sub-partitions is always pushed onto the
stack first, with the algorithm then concentrating on the
smaller partition. This *guarantees* no more than log (total_elems)
stack size is needed (actually O(1) in this case)! */
/* The main code starts here... */
#define QSORT(QSORT_TYPE, QSORT_BASE, QSORT_NELT, QSORT_LT) \
{ \
QSORT_TYPE *const _base = (QSORT_BASE); \
const unsigned _elems = (QSORT_NELT); \
QSORT_TYPE _hold; \
\
/* Don't declare two variables of type QSORT_TYPE in a single \
* statement: eg `TYPE a, b;', in case if TYPE is a pointer, \
* expands to `type* a, b;' which isn't what we want. \
*/ \
\
if (_elems > _QSORT_MAX_THRESH) { \
QSORT_TYPE *_lo = _base; \
QSORT_TYPE *_hi = _lo + _elems - 1; \
struct { \
QSORT_TYPE *_hi; \
QSORT_TYPE *_lo; \
} _stack[_QSORT_STACK_SIZE], *_top = _stack + 1; \
\
while (_QSORT_STACK_NOT_EMPTY) { \
QSORT_TYPE *_left_ptr; \
QSORT_TYPE *_right_ptr; \
\
/* Select median value from among LO, MID, and HI. Rearrange \
LO and HI so the three values are sorted. This lowers the \
probability of picking a pathological pivot value and \
skips a comparison for both the LEFT_PTR and RIGHT_PTR in \
the while loops. */ \
\
QSORT_TYPE *_mid = _lo + ((_hi - _lo) >> 1); \
\
if (QSORT_LT(_mid, _lo)) _QSORT_SWAP(_mid, _lo, _hold); \
if (QSORT_LT(_hi, _mid)) { \
_QSORT_SWAP(_mid, _hi, _hold); \
if (QSORT_LT(_mid, _lo)) _QSORT_SWAP(_mid, _lo, _hold); \
} \
\
_left_ptr = _lo + 1; \
_right_ptr = _hi - 1; \
\
/* Here's the famous ``collapse the walls'' section of quicksort. \
Gotta like those tight inner loops! They are the main reason \
that this algorithm runs much faster than others. */ \
do { \
while (QSORT_LT(_left_ptr, _mid)) ++_left_ptr; \
\
while (QSORT_LT(_mid, _right_ptr)) --_right_ptr; \
\
if (_left_ptr < _right_ptr) { \
_QSORT_SWAP(_left_ptr, _right_ptr, _hold); \
if (_mid == _left_ptr) _mid = _right_ptr; \
else if (_mid == _right_ptr) _mid = _left_ptr; \
++_left_ptr; \
--_right_ptr; \
} else if (_left_ptr == _right_ptr) { \
++_left_ptr; \
--_right_ptr; \
break; \
} \
} while (_left_ptr <= _right_ptr); \
\
/* Set up pointers for next iteration. First determine whether \
left and right partitions are below the threshold size. If so, \
ignore one or both. Otherwise, push the larger partition's \
bounds on the stack and continue sorting the smaller one. */ \
\
if (_right_ptr - _lo <= _QSORT_MAX_THRESH) { \
if (_hi - _left_ptr <= _QSORT_MAX_THRESH) /* Ignore both small partitions. */ \
_QSORT_POP(_lo, _hi, _top); \
else /* Ignore small left partition. */ _lo = _left_ptr; \
} else if (_hi - _left_ptr <= _QSORT_MAX_THRESH) /* Ignore small right partition. */ \
_hi = _right_ptr; \
else if (_right_ptr - _lo > _hi - _left_ptr) { \
/* Push larger left partition indices. */ \
_QSORT_PUSH(_top, _lo, _right_ptr); \
_lo = _left_ptr; \
} else { \
/* Push larger right partition indices. */ \
_QSORT_PUSH(_top, _left_ptr, _hi); \
_hi = _right_ptr; \
} \
} \
} \
\
/* Once the BASE array is partially sorted by quicksort the rest \
is completely sorted using insertion sort, since this is efficient \
for partitions below MAX_THRESH size. BASE points to the \
beginning of the array to sort, and END_PTR points at the very \
last element in the array (*not* one beyond it!). */ \
\
{ \
QSORT_TYPE *const _end_ptr = _base + _elems - 1; \
QSORT_TYPE *_tmp_ptr = _base; \
register QSORT_TYPE *_run_ptr; \
QSORT_TYPE *_thresh; \
\
_thresh = _base + _QSORT_MAX_THRESH; \
if (_thresh > _end_ptr) _thresh = _end_ptr; \
\
/* Find smallest element in first threshold and place it at the \
array's beginning. This is the smallest array element, \
and the operation speeds up insertion sort's inner loop. */ \
\
for (_run_ptr = _tmp_ptr + 1; _run_ptr <= _thresh; ++_run_ptr) \
if (QSORT_LT(_run_ptr, _tmp_ptr)) _tmp_ptr = _run_ptr; \
\
if (_tmp_ptr != _base) _QSORT_SWAP(_tmp_ptr, _base, _hold); \
\
/* Insertion sort, running from left-hand-side \
* up to right-hand-side. */ \
\
_run_ptr = _base + 1; \
while (++_run_ptr <= _end_ptr) { \
_tmp_ptr = _run_ptr - 1; \
while (QSORT_LT(_run_ptr, _tmp_ptr)) --_tmp_ptr; \
\
++_tmp_ptr; \
if (_tmp_ptr != _run_ptr) { \
QSORT_TYPE *_trav = _run_ptr + 1; \
while (--_trav >= _run_ptr) { \
QSORT_TYPE *_hi; \
QSORT_TYPE *_lo; \
_hold = *_trav; \
\
for (_hi = _lo = _trav; --_lo >= _tmp_ptr; _hi = _lo) *_hi = *_lo; \
*_hi = _hold; \
} \
} \
} \
} \
}
+470
View File
@@ -0,0 +1,470 @@
/*
* key_encoding.c
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "keys.h"
#include "charsets.h"
typedef enum { SHIFT = 1, ALT = 2, CTRL = 4, SUPER = 8, HYPER = 16, META = 32, CAPS_LOCK = 64, NUM_LOCK = 128 } ModifierMasks;
typedef enum { PRESS = 0, REPEAT = 1, RELEASE = 2 } KeyAction;
#define LOCK_MASK (CAPS_LOCK | NUM_LOCK)
typedef struct {
uint32_t key, shifted_key, alternate_key;
struct {
bool shift, alt, ctrl, super, hyper, meta, numlock, capslock;
unsigned value;
char encoded[4];
} mods;
KeyAction action;
bool cursor_key_mode, disambiguate, report_all_event_types, report_alternate_key, report_text, embed_text;
const char *text;
bool has_text;
} KeyEvent;
typedef struct {
uint32_t key, shifted_key, alternate_key;
bool add_alternates, has_mods, add_actions, add_text;
char encoded_mods[4];
const char *text;
KeyAction action;
} EncodingData;
static void
convert_glfw_mods(int mods, KeyEvent *ev, const unsigned key_encoding_flags) {
if (!key_encoding_flags) mods &= ~GLFW_LOCK_MASK;
ev->mods.alt = (mods & GLFW_MOD_ALT) > 0, ev->mods.ctrl = (mods & GLFW_MOD_CONTROL) > 0, ev->mods.shift = (mods & GLFW_MOD_SHIFT) > 0,
ev->mods.super = (mods & GLFW_MOD_SUPER) > 0, ev->mods.hyper = (mods & GLFW_MOD_HYPER) > 0, ev->mods.meta = (mods & GLFW_MOD_META) > 0;
ev->mods.numlock = (mods & GLFW_MOD_NUM_LOCK) > 0, ev->mods.capslock = (mods & GLFW_MOD_CAPS_LOCK) > 0;
ev->mods.value = ev->mods.shift ? SHIFT : 0;
if (ev->mods.alt) ev->mods.value |= ALT;
if (ev->mods.ctrl) ev->mods.value |= CTRL;
if (ev->mods.super) ev->mods.value |= SUPER;
if (ev->mods.hyper) ev->mods.value |= HYPER;
if (ev->mods.meta) ev->mods.value |= META;
if (ev->mods.capslock) ev->mods.value |= CAPS_LOCK;
if (ev->mods.numlock) ev->mods.value |= NUM_LOCK;
snprintf(ev->mods.encoded, sizeof(ev->mods.encoded), "%u", ev->mods.value + 1);
}
static void
init_encoding_data(EncodingData *ans, const KeyEvent *ev) {
ans->add_actions = ev->report_all_event_types && ev->action != PRESS;
ans->has_mods = ev->mods.encoded[0] && (ev->mods.encoded[0] != '1' || ev->mods.encoded[1]);
ans->add_alternates = ev->report_alternate_key && ((ev->shifted_key > 0 && ev->mods.shift) || ev->alternate_key > 0);
if (ans->add_alternates) {
if (ev->mods.shift) ans->shifted_key = ev->shifted_key;
ans->alternate_key = ev->alternate_key;
}
ans->action = ev->action;
ans->key = ev->key;
ans->add_text = ev->embed_text && ev->text && ev->text[0];
ans->text = ev->text;
memcpy(ans->encoded_mods, ev->mods.encoded, sizeof(ans->encoded_mods));
}
static int
serialize(const EncodingData *data, char *output, const char csi_trailer) {
int pos = 0;
bool second_field_not_empty = data->has_mods || data->add_actions;
bool third_field_not_empty = data->add_text;
#define P(fmt, ...) pos += snprintf(output + pos, KEY_BUFFER_SIZE - 2 <= pos ? 0 : KEY_BUFFER_SIZE - 2 - pos, fmt, __VA_ARGS__)
P("\x1b%s", "[");
if (data->key != 1 || data->add_alternates || second_field_not_empty || third_field_not_empty) P("%u", data->key);
if (data->add_alternates) {
P("%s", ":");
if (data->shifted_key) P("%u", data->shifted_key);
if (data->alternate_key) P(":%u", data->alternate_key);
}
if (second_field_not_empty || third_field_not_empty) {
P("%s", ";");
if (second_field_not_empty) P("%s", data->encoded_mods);
if (data->add_actions) P(":%u", data->action + 1);
}
if (third_field_not_empty) {
const char *p = data->text;
uint32_t codep;
UTF8State state = UTF8_ACCEPT;
bool first = true;
while (*p) {
if (decode_utf8(&state, &codep, *p) == UTF8_ACCEPT) {
if (first) {
P(";%u", codep);
first = false;
} else P(":%u", codep);
}
p++;
}
}
#undef P
if (pos > KEY_BUFFER_SIZE - 2) pos = KEY_BUFFER_SIZE - 2;
output[pos++] = csi_trailer;
output[pos] = 0;
return pos;
}
static uint32_t
convert_kp_key_to_normal_key(uint32_t key_number) {
#define S(x) \
case GLFW_FKEY_KP_##x: key_number = GLFW_FKEY_##x; break
switch (key_number) {
S(ENTER);
S(HOME);
S(END);
S(INSERT);
S(DELETE);
S(PAGE_UP);
S(PAGE_DOWN);
S(UP);
S(DOWN);
S(LEFT);
S(RIGHT);
#undef S
case GLFW_FKEY_KP_0:
case GLFW_FKEY_KP_9: key_number = '0' + (key_number - GLFW_FKEY_KP_0); break;
case GLFW_FKEY_KP_DECIMAL: key_number = '.'; break;
case GLFW_FKEY_KP_DIVIDE: key_number = '/'; break;
case GLFW_FKEY_KP_MULTIPLY: key_number = '*'; break;
case GLFW_FKEY_KP_SUBTRACT: key_number = '-'; break;
case GLFW_FKEY_KP_ADD: key_number = '+'; break;
case GLFW_FKEY_KP_EQUAL: key_number = '='; break;
}
return key_number;
}
static int
legacy_functional_key_encoding_with_modifiers(uint32_t key_number, const KeyEvent *ev, char *output) {
const char *prefix = ev->mods.value & ALT ? "\x1b" : "";
const char *main_bytes = "";
switch (key_number) {
case GLFW_FKEY_ENTER: main_bytes = "\x0d"; break;
case GLFW_FKEY_ESCAPE: main_bytes = "\x1b"; break;
case GLFW_FKEY_BACKSPACE: main_bytes = ev->mods.value & CTRL ? "\x08" : "\x7f"; break;
case GLFW_FKEY_TAB:
if (ev->mods.value & SHIFT) {
prefix = ev->mods.value & ALT ? "\x1b\x1b" : "\x1b";
main_bytes = "[Z";
} else {
main_bytes = "\t";
}
break;
default: return -1;
}
return snprintf(output, KEY_BUFFER_SIZE, "%s%s", prefix, main_bytes);
}
static int
encode_function_key(const KeyEvent *ev, char *output) {
#define SIMPLE(val) return snprintf(output, KEY_BUFFER_SIZE, "%s", val);
char csi_trailer = 'u';
uint32_t key_number = ev->key;
bool legacy_mode = !ev->report_all_event_types && !ev->disambiguate && !ev->report_text;
if (ev->cursor_key_mode && legacy_mode && !ev->mods.value) {
switch (key_number) {
case GLFW_FKEY_UP: SIMPLE("\x1bOA");
case GLFW_FKEY_DOWN: SIMPLE("\x1bOB");
case GLFW_FKEY_RIGHT: SIMPLE("\x1bOC");
case GLFW_FKEY_LEFT: SIMPLE("\x1bOD");
case GLFW_FKEY_KP_BEGIN: SIMPLE("\x1bOE");
case GLFW_FKEY_END: SIMPLE("\x1bOF");
case GLFW_FKEY_HOME: SIMPLE("\x1bOH");
default: break;
}
}
if (!ev->mods.value) {
if (!ev->disambiguate && !ev->report_text && key_number == GLFW_FKEY_ESCAPE) SIMPLE("\x1b");
if (legacy_mode) {
switch (key_number) {
case GLFW_FKEY_F1: SIMPLE("\x1bOP");
case GLFW_FKEY_F2: SIMPLE("\x1bOQ");
case GLFW_FKEY_F3: SIMPLE("\x1bOR");
case GLFW_FKEY_F4: SIMPLE("\x1bOS");
default: break;
}
}
if (!ev->report_text) {
switch (key_number) {
case GLFW_FKEY_ENTER:
if (ev->action == RELEASE) return -1;
SIMPLE("\r");
case GLFW_FKEY_BACKSPACE:
if (ev->action == RELEASE) return -1;
SIMPLE("\x7f");
case GLFW_FKEY_TAB:
if (ev->action == RELEASE) return -1;
SIMPLE("\t");
default: break;
}
}
} else if (legacy_mode) {
int num = legacy_functional_key_encoding_with_modifiers(key_number, ev, output);
if (num > -1) return num;
}
if (!(ev->mods.value & ~LOCK_MASK) && !ev->report_text) {
switch (key_number) {
case GLFW_FKEY_ENTER:
if (ev->action == RELEASE) return -1;
SIMPLE("\r");
case GLFW_FKEY_BACKSPACE:
if (ev->action == RELEASE) return -1;
SIMPLE("\x7f");
case GLFW_FKEY_TAB:
if (ev->action == RELEASE) return -1;
SIMPLE("\t");
default: break;
}
}
#undef SIMPLE
#define S(number, trailer) \
key_number = number; \
csi_trailer = trailer; \
break
switch (key_number) {
/* start special numbers (auto generated by gen-key-constants.py do not edit) */
case GLFW_FKEY_ESCAPE: S(27, 'u');
case GLFW_FKEY_ENTER: S(13, 'u');
case GLFW_FKEY_TAB: S(9, 'u');
case GLFW_FKEY_BACKSPACE: S(127, 'u');
case GLFW_FKEY_INSERT: S(2, '~');
case GLFW_FKEY_DELETE: S(3, '~');
case GLFW_FKEY_LEFT: S(1, 'D');
case GLFW_FKEY_RIGHT: S(1, 'C');
case GLFW_FKEY_UP: S(1, 'A');
case GLFW_FKEY_DOWN: S(1, 'B');
case GLFW_FKEY_PAGE_UP: S(5, '~');
case GLFW_FKEY_PAGE_DOWN: S(6, '~');
case GLFW_FKEY_HOME: S(1, 'H');
case GLFW_FKEY_END: S(1, 'F');
case GLFW_FKEY_F1: S(1, 'P');
case GLFW_FKEY_F2: S(1, 'Q');
case GLFW_FKEY_F3: S(13, '~');
case GLFW_FKEY_F4: S(1, 'S');
case GLFW_FKEY_F5: S(15, '~');
case GLFW_FKEY_F6: S(17, '~');
case GLFW_FKEY_F7: S(18, '~');
case GLFW_FKEY_F8: S(19, '~');
case GLFW_FKEY_F9: S(20, '~');
case GLFW_FKEY_F10: S(21, '~');
case GLFW_FKEY_F11: S(23, '~');
case GLFW_FKEY_F12: S(24, '~');
case GLFW_FKEY_KP_BEGIN:
S(1, 'E');
/* end special numbers */
case GLFW_FKEY_MENU:
// use the same encoding as xterm for this key in legacy mode (F16)
if (legacy_mode) { S(29, '~'); }
break;
default: break;
}
#undef S
EncodingData ed = {0};
init_encoding_data(&ed, ev);
ed.key = key_number;
ed.add_alternates = false;
return serialize(&ed, output, csi_trailer);
}
static char
ctrled_key(const char key) { // {{{
switch (key) {
/* start ctrl mapping (auto generated by gen-key-constants.py do not edit) */
case ' ': return 0;
case '/': return 31;
case '0': return 48;
case '1': return 49;
case '2': return 0;
case '3': return 27;
case '4': return 28;
case '5': return 29;
case '6': return 30;
case '7': return 31;
case '8': return 127;
case '9': return 57;
case '?': return 127;
case '@': return 0;
case '[': return 27;
case '\\': return 28;
case ']': return 29;
case '^': return 30;
case '_': return 31;
case 'a': return 1;
case 'b': return 2;
case 'c': return 3;
case 'd': return 4;
case 'e': return 5;
case 'f': return 6;
case 'g': return 7;
case 'h': return 8;
case 'i': return 9;
case 'j': return 10;
case 'k': return 11;
case 'l': return 12;
case 'm': return 13;
case 'n': return 14;
case 'o': return 15;
case 'p': return 16;
case 'q': return 17;
case 'r': return 18;
case 's': return 19;
case 't': return 20;
case 'u': return 21;
case 'v': return 22;
case 'w': return 23;
case 'x': return 24;
case 'y': return 25;
case 'z': return 26;
case '~':
return 30;
/* end ctrl mapping */
default: return key;
}
} // }}}
static int
encode_printable_ascii_key_legacy(const KeyEvent *ev, char *output) {
unsigned mods = ev->mods.value;
if (!mods) return snprintf(output, KEY_BUFFER_SIZE, "%c", (char)ev->key);
char key = ev->key;
if (mods & SHIFT) {
const char shifted = ev->shifted_key;
if (shifted && shifted != key && (!(mods & CTRL) || key < 'a' || key > 'z')) {
key = shifted;
mods &= ~SHIFT;
}
}
if (ev->mods.value == SHIFT) return snprintf(output, KEY_BUFFER_SIZE, "%c", key);
if (mods == ALT) return snprintf(output, KEY_BUFFER_SIZE, "\x1b%c", key);
if (mods == CTRL) return snprintf(output, KEY_BUFFER_SIZE, "%c", ctrled_key(key));
if (mods == (CTRL | ALT)) return snprintf(output, KEY_BUFFER_SIZE, "\x1b%c", ctrled_key(key));
if (key == ' ') {
if (mods == (CTRL | SHIFT)) return snprintf(output, KEY_BUFFER_SIZE, "%c", ctrled_key(key));
if (mods == (ALT | SHIFT)) return snprintf(output, KEY_BUFFER_SIZE, "\x1b%c", key);
}
return 0;
}
static bool
is_legacy_ascii_key(uint32_t key) {
START_ALLOW_CASE_RANGE
switch (key) {
case 'a' ... 'z':
case '0' ... '9':
case '!':
case '@':
case '#':
case '$':
case '%':
case '^':
case '&':
case '*':
case '(':
case ')':
case '`':
case '~':
case '-':
case '_':
case '=':
case '+':
case '[':
case '{':
case ']':
case '}':
case '\\':
case '|':
case ';':
case ':':
case '\'':
case '"':
case ',':
case '<':
case '.':
case '>':
case '/':
case '?':
case ' ': return true;
default: return false;
}
END_ALLOW_CASE_RANGE
}
static int
encode_key(const KeyEvent *ev, char *output) {
if (!ev->report_all_event_types && ev->action == RELEASE) return 0;
if (GLFW_FKEY_FIRST <= ev->key && ev->key <= GLFW_FKEY_LAST) return encode_function_key(ev, output);
EncodingData ed = {0};
init_encoding_data(&ed, ev);
bool simple_encoding_ok = !ed.add_actions && !ed.add_alternates && !ed.add_text;
if (simple_encoding_ok) {
if (!ed.has_mods) {
if (ev->report_text) return serialize(&ed, output, 'u');
return encode_utf8(ev->key, output);
}
if (!ev->disambiguate && !ev->report_text) {
if (is_legacy_ascii_key(ev->key) || (ev->shifted_key && is_legacy_ascii_key(ev->shifted_key))) {
int ret = encode_printable_ascii_key_legacy(ev, output);
if (ret > 0) return ret;
}
unsigned mods = ev->mods.value;
if ((mods == CTRL || mods == ALT || mods == (CTRL | ALT)) && ev->alternate_key && !is_legacy_ascii_key(ev->key) &&
is_legacy_ascii_key(ev->alternate_key)) {
KeyEvent alternate = *ev;
alternate.key = ev->alternate_key;
alternate.alternate_key = 0;
alternate.shifted_key = 0;
int ret = encode_printable_ascii_key_legacy(&alternate, output);
if (ret > 0) return ret;
}
}
}
return serialize(&ed, output, 'u');
}
static bool
startswith_ascii_control_char(const char *p) {
if (!p || !*p) return true;
uint32_t codep;
UTF8State state = UTF8_ACCEPT;
while (*p) {
if (decode_utf8(&state, &codep, *p) == UTF8_ACCEPT) { return codep < 32 || codep == 127; }
state = UTF8_ACCEPT;
p++;
}
return false;
}
int
encode_glfw_key_event(const GLFWkeyevent *e, const bool cursor_key_mode, const unsigned key_encoding_flags, char *output) {
KeyEvent ev = {
.key = e->key,
.shifted_key = e->shifted_key,
.alternate_key = e->alternate_key,
.text = e->text,
.cursor_key_mode = cursor_key_mode,
.disambiguate = key_encoding_flags & 1,
.report_all_event_types = key_encoding_flags & 2,
.report_alternate_key = key_encoding_flags & 4,
.report_text = key_encoding_flags & 8,
.embed_text = key_encoding_flags & 16};
if (!ev.report_text && is_modifier_key(e->key)) return 0;
ev.has_text = e->text && !startswith_ascii_control_char(e->text);
if (!ev.key && !ev.has_text) return 0;
bool send_text_standalone = !ev.report_text;
if (!ev.disambiguate && !ev.report_text && GLFW_FKEY_KP_0 <= ev.key && ev.key <= GLFW_FKEY_KP_BEGIN) { ev.key = convert_kp_key_to_normal_key(ev.key); }
switch (e->action) {
case GLFW_PRESS: ev.action = PRESS; break;
case GLFW_REPEAT: ev.action = REPEAT; break;
case GLFW_RELEASE: ev.action = RELEASE; break;
}
if (send_text_standalone && ev.has_text && (ev.action == PRESS || ev.action == REPEAT)) return SEND_TEXT_TO_CHILD;
convert_glfw_mods(e->mods, &ev, key_encoding_flags);
return encode_key(&ev, output);
}
+436
View File
@@ -0,0 +1,436 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntEnum
from functools import lru_cache
from typing import NamedTuple
from . import fast_data_types as defines
from .fast_data_types import KeyEvent as WindowSystemKeyEvent
from .key_names import character_key_name_aliases, functional_key_name_aliases
from .types import ParsedShortcut
# number name mappings {{{
# start csi mapping (auto generated by gen-key-constants.py do not edit)
functional_key_number_to_name_map = {
57344: 'ESCAPE',
57345: 'ENTER',
57346: 'TAB',
57347: 'BACKSPACE',
57348: 'INSERT',
57349: 'DELETE',
57350: 'LEFT',
57351: 'RIGHT',
57352: 'UP',
57353: 'DOWN',
57354: 'PAGE_UP',
57355: 'PAGE_DOWN',
57356: 'HOME',
57357: 'END',
57358: 'CAPS_LOCK',
57359: 'SCROLL_LOCK',
57360: 'NUM_LOCK',
57361: 'PRINT_SCREEN',
57362: 'PAUSE',
57363: 'MENU',
57364: 'F1',
57365: 'F2',
57366: 'F3',
57367: 'F4',
57368: 'F5',
57369: 'F6',
57370: 'F7',
57371: 'F8',
57372: 'F9',
57373: 'F10',
57374: 'F11',
57375: 'F12',
57376: 'F13',
57377: 'F14',
57378: 'F15',
57379: 'F16',
57380: 'F17',
57381: 'F18',
57382: 'F19',
57383: 'F20',
57384: 'F21',
57385: 'F22',
57386: 'F23',
57387: 'F24',
57388: 'F25',
57389: 'F26',
57390: 'F27',
57391: 'F28',
57392: 'F29',
57393: 'F30',
57394: 'F31',
57395: 'F32',
57396: 'F33',
57397: 'F34',
57398: 'F35',
57399: 'KP_0',
57400: 'KP_1',
57401: 'KP_2',
57402: 'KP_3',
57403: 'KP_4',
57404: 'KP_5',
57405: 'KP_6',
57406: 'KP_7',
57407: 'KP_8',
57408: 'KP_9',
57409: 'KP_DECIMAL',
57410: 'KP_DIVIDE',
57411: 'KP_MULTIPLY',
57412: 'KP_SUBTRACT',
57413: 'KP_ADD',
57414: 'KP_ENTER',
57415: 'KP_EQUAL',
57416: 'KP_SEPARATOR',
57417: 'KP_LEFT',
57418: 'KP_RIGHT',
57419: 'KP_UP',
57420: 'KP_DOWN',
57421: 'KP_PAGE_UP',
57422: 'KP_PAGE_DOWN',
57423: 'KP_HOME',
57424: 'KP_END',
57425: 'KP_INSERT',
57426: 'KP_DELETE',
57427: 'KP_BEGIN',
57428: 'MEDIA_PLAY',
57429: 'MEDIA_PAUSE',
57430: 'MEDIA_PLAY_PAUSE',
57431: 'MEDIA_REVERSE',
57432: 'MEDIA_STOP',
57433: 'MEDIA_FAST_FORWARD',
57434: 'MEDIA_REWIND',
57435: 'MEDIA_TRACK_NEXT',
57436: 'MEDIA_TRACK_PREVIOUS',
57437: 'MEDIA_RECORD',
57438: 'LOWER_VOLUME',
57439: 'RAISE_VOLUME',
57440: 'MUTE_VOLUME',
57441: 'LEFT_SHIFT',
57442: 'LEFT_CONTROL',
57443: 'LEFT_ALT',
57444: 'LEFT_SUPER',
57445: 'LEFT_HYPER',
57446: 'LEFT_META',
57447: 'RIGHT_SHIFT',
57448: 'RIGHT_CONTROL',
57449: 'RIGHT_ALT',
57450: 'RIGHT_SUPER',
57451: 'RIGHT_HYPER',
57452: 'RIGHT_META',
57453: 'ISO_LEVEL3_SHIFT',
57454: 'ISO_LEVEL5_SHIFT',
}
csi_number_to_functional_number_map = {
2: 57348,
3: 57349,
5: 57354,
6: 57355,
7: 57356,
8: 57357,
9: 57346,
11: 57364,
12: 57365,
13: 57345,
14: 57367,
15: 57368,
17: 57369,
18: 57370,
19: 57371,
20: 57372,
21: 57373,
23: 57374,
24: 57375,
27: 57344,
127: 57347,
}
letter_trailer_to_csi_number_map = {'A': 57352, 'B': 57353, 'C': 57351, 'D': 57350, 'E': 57427, 'F': 8, 'H': 7, 'P': 11, 'Q': 12, 'S': 14}
tilde_trailers = {57348, 57349, 57354, 57355, 57366, 57368, 57369, 57370, 57371, 57372, 57373, 57374, 57375}
# end csi mapping
# }}}
@lru_cache(2)
def get_name_to_functional_number_map() -> dict[str, int]:
return {v: k for k, v in functional_key_number_to_name_map.items()}
@lru_cache(2)
def get_functional_to_csi_number_map() -> dict[int, int]:
return {v: k for k, v in csi_number_to_functional_number_map.items()}
@lru_cache(2)
def get_csi_number_to_letter_trailer_map() -> dict[int, str]:
return {v: k for k, v in letter_trailer_to_csi_number_map.items()}
PRESS: int = 1
REPEAT: int = 2
RELEASE: int = 4
class EventType(IntEnum):
PRESS = PRESS
REPEAT = REPEAT
RELEASE = RELEASE
@lru_cache(maxsize=128)
def parse_shortcut(spec: str) -> ParsedShortcut:
if spec.endswith('+'):
spec = f'{spec[:-1]}plus'
parts = spec.split('+')
key_name = parts[-1]
key_name = functional_key_name_aliases.get(key_name.upper(), key_name)
is_functional_key = key_name.upper() in get_name_to_functional_number_map()
if is_functional_key:
key_name = key_name.upper()
else:
key_name = character_key_name_aliases.get(key_name.upper(), key_name)
mod_val = 0
if len(parts) > 1:
mods = tuple(config_mod_map.get(x.upper(), META << 8) for x in parts[:-1])
for x in mods:
mod_val |= x
return ParsedShortcut(mod_val, key_name)
class KeyEvent(NamedTuple):
type: EventType = EventType.PRESS
mods: int = 0
key: str = ''
text: str = ''
shifted_key: str = ''
alternate_key: str = ''
shift: bool = False
alt: bool = False
ctrl: bool = False
super: bool = False
hyper: bool = False
meta: bool = False
caps_lock: bool = False
num_lock: bool = False
def matches(self, spec: str | ParsedShortcut, types: int = EventType.PRESS | EventType.REPEAT) -> bool:
mods = self.mods_without_locks
if not self.type & types:
return False
if isinstance(spec, str):
spec = parse_shortcut(spec)
if (mods, self.key) == spec:
return True
is_shifted = bool(self.shifted_key and self.shift)
if is_shifted and (mods & ~SHIFT, self.shifted_key) == spec:
return True
if self.alternate_key and self.key and len(self.key) == 1 and 127 < ord(self.key) < 0xE000 and (mods, self.alternate_key) == spec:
return True
return False
def matches_without_mods(self, spec: str | ParsedShortcut, types: int = EventType.PRESS | EventType.REPEAT) -> bool:
if not self.type & types:
return False
if isinstance(spec, str):
spec = parse_shortcut(spec)
return self.key == spec[1]
def matches_text(self, text: str, case_sensitive: bool = False) -> bool:
if case_sensitive:
return self.text == text
return self.text.lower() == text.lower()
@property
def is_release(self) -> bool:
return self.type is EventType.RELEASE
@property
def mods_without_locks(self) -> int:
return self.mods & ~(NUM_LOCK | CAPS_LOCK)
@property
def has_mods(self) -> bool:
return bool(self.mods_without_locks)
def as_window_system_event(self) -> WindowSystemKeyEvent:
action = defines.GLFW_PRESS
if self.type is EventType.REPEAT:
action = defines.GLFW_REPEAT
elif self.type is EventType.RELEASE:
action = defines.GLFW_RELEASE
mods = 0
if self.mods:
if self.shift:
mods |= defines.GLFW_MOD_SHIFT
if self.alt:
mods |= defines.GLFW_MOD_ALT
if self.ctrl:
mods |= defines.GLFW_MOD_CONTROL
if self.super:
mods |= defines.GLFW_MOD_SUPER
if self.hyper:
mods |= defines.GLFW_MOD_HYPER
if self.meta:
mods |= defines.GLFW_MOD_META
if self.caps_lock:
mods |= defines.GLFW_MOD_CAPS_LOCK
if self.num_lock:
mods |= defines.GLFW_MOD_NUM_LOCK
fnm = get_name_to_functional_number_map()
def as_num(key: str) -> int:
return (fnm.get(key) or ord(key)) if key else 0
return WindowSystemKeyEvent(
key=as_num(self.key), shifted_key=as_num(self.shifted_key), alternate_key=as_num(self.alternate_key), mods=mods, action=action, text=self.text
)
SHIFT, ALT, CTRL, SUPER, HYPER, META, CAPS_LOCK, NUM_LOCK = 1, 2, 4, 8, 16, 32, 64, 128
enter_key = KeyEvent(key='ENTER')
backspace_key = KeyEvent(key='BACKSPACE')
config_mod_map = {
'SHIFT': SHIFT,
'⇧': SHIFT,
'ALT': ALT,
'OPTION': ALT,
'OPT': ALT,
'⌥': ALT,
'SUPER': SUPER,
'COMMAND': SUPER,
'CMD': SUPER,
'⌘': SUPER,
'CONTROL': CTRL,
'CTRL': CTRL,
'⌃': CTRL,
'HYPER': HYPER,
'META': META,
'NUM_LOCK': NUM_LOCK,
'CAPS_LOCK': CAPS_LOCK,
}
def decode_key_event(csi: str, csi_type: str) -> KeyEvent:
parts = csi.split(';')
def get_sub_sections(x: str, missing: int = 0) -> tuple[int, ...]:
return tuple(int(y) if y else missing for y in x.split(':'))
first_section = get_sub_sections(parts[0])
second_section = get_sub_sections(parts[1], 1) if len(parts) > 1 else ()
third_section = get_sub_sections(parts[2]) if len(parts) > 2 else ()
mods = (second_section[0] - 1) if second_section else 0
action = second_section[1] if len(second_section) > 1 else 1
keynum = first_section[0]
if csi_type in 'ABCDEHFPQRS':
keynum = letter_trailer_to_csi_number_map[csi_type]
def key_name(num: int) -> str:
if not num:
return ''
if num != 13:
num = csi_number_to_functional_number_map.get(num, num)
ans = functional_key_number_to_name_map.get(num)
else:
ans = 'ENTER' if csi_type == 'u' else 'F3'
if ans is None:
ans = chr(num)
return ans
return KeyEvent(
mods=mods,
shift=bool(mods & SHIFT),
alt=bool(mods & ALT),
ctrl=bool(mods & CTRL),
super=bool(mods & SUPER),
hyper=bool(mods & HYPER),
meta=bool(mods & META),
caps_lock=bool(mods & CAPS_LOCK),
num_lock=bool(mods & NUM_LOCK),
key=key_name(keynum),
shifted_key=key_name(first_section[1] if len(first_section) > 1 else 0),
alternate_key=key_name(first_section[2] if len(first_section) > 2 else 0),
type={1: EventType.PRESS, 2: EventType.REPEAT, 3: EventType.RELEASE}[action],
text=''.join(map(chr, third_section)),
)
def csi_number_for_name(key_name: str) -> int:
if not key_name:
return 0
if key_name in ('F3', 'ENTER'):
return 13
fn = get_name_to_functional_number_map().get(key_name)
if fn is None:
return ord(key_name)
return get_functional_to_csi_number_map().get(fn, fn)
def encode_key_event(key_event: KeyEvent) -> str:
key = csi_number_for_name(key_event.key)
shifted_key = csi_number_for_name(key_event.shifted_key)
alternate_key = csi_number_for_name(key_event.alternate_key)
lt = get_csi_number_to_letter_trailer_map()
if key_event.key == 'ENTER':
trailer = 'u'
else:
trailer = lt.get(key, 'u')
if trailer != 'u':
key = 1
mods = key_event.mods
text = key_event.text
ans = '\033['
if key != 1 or mods or shifted_key or alternate_key or text:
ans += f'{key}'
if shifted_key or alternate_key:
ans += ':' + (f'{shifted_key}' if shifted_key else '')
if alternate_key:
ans += f':{alternate_key}'
action = 1
if key_event.type is EventType.REPEAT:
action = 2
elif key_event.type is EventType.RELEASE:
action = 3
if mods or action > 1 or text:
m = 0
if key_event.shift:
m |= 1
if key_event.alt:
m |= 2
if key_event.ctrl:
m |= 4
if key_event.super:
m |= 8
if key_event.hyper:
m |= 16
if key_event.meta:
m |= 32
if key_event.caps_lock:
m |= 64
if key_event.num_lock:
m |= 128
if action > 1 or m:
ans += f';{m + 1}'
if action > 1:
ans += f':{action}'
elif text:
ans += ';'
if text:
ans += ';' + ':'.join(map(str, map(ord, text)))
fn = get_name_to_functional_number_map().get(key_event.key)
if fn is not None and fn in tilde_trailers:
trailer = '~'
return ans + trailer
def decode_key_event_as_window_system_key(text: str) -> WindowSystemKeyEvent | None:
csi, trailer = text[2:-1], text[-1]
try:
k = decode_key_event(csi, trailer)
except Exception:
return None
return k.as_window_system_event()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import sys
from collections.abc import Callable
from contextlib import suppress
from typing import Optional
from .constants import is_macos
functional_key_name_aliases: dict[str, str] = {
'ESC': 'ESCAPE',
'PGUP': 'PAGE_UP',
'PAGEUP': 'PAGE_UP',
'PGDN': 'PAGE_DOWN',
'PAGEDOWN': 'PAGE_DOWN',
'RETURN': 'ENTER',
'ARROWUP': 'UP',
'ARROWDOWN': 'DOWN',
'ARROWRIGHT': 'RIGHT',
'ARROWLEFT': 'LEFT',
'DEL': 'DELETE',
'KP_PLUS': 'KP_ADD',
'KP_MINUS': 'KP_SUBTRACT',
}
character_key_name_aliases: dict[str, str] = {
'SPC': ' ',
'SPACE': ' ',
'STAR': '*',
'MULTIPLY': '*',
'PLUS': '+',
'MINUS': '-',
'BAR': '|',
'PIPE': '|',
'HYPHEN': '-',
'EQUAL': '=',
'UNDERSCORE': '_',
'COMMA': ',',
'PERIOD': '.',
'DOT': '.',
'SLASH': '/',
'BACKSLASH': '\\',
'TILDE': '~',
'GRAVE': '`',
'GRAVE_ACCENT': '`',
'APOSTROPHE': "'",
'SEMICOLON': ';',
'COLON': ':',
'LEFT_BRACKET': '[',
'RIGHT_BRACKET': ']',
}
LookupFunc = Callable[[str, bool], Optional[int]]
def null_lookup(name: str, case_sensitive: bool = False) -> int | None:
return None
if is_macos:
def get_key_name_lookup() -> LookupFunc:
return null_lookup
else:
def load_libxkb_lookup() -> LookupFunc:
import ctypes
for suffix in ('.0', ''):
with suppress(Exception):
lib = ctypes.CDLL(f'libxkbcommon.so{suffix}')
break
else:
from ctypes.util import find_library
lname = find_library('xkbcommon')
if lname is None:
raise RuntimeError('Failed to find libxkbcommon')
lib = ctypes.CDLL(lname)
f = lib.xkb_keysym_from_name
f.argtypes = [ctypes.c_char_p, ctypes.c_int]
f.restype = ctypes.c_int
def xkb_lookup(name: str, case_sensitive: bool = False) -> int | None:
q = name.encode('utf-8')
return f(q, int(case_sensitive)) or None
return xkb_lookup
def get_key_name_lookup() -> LookupFunc:
ans: LookupFunc | None = getattr(get_key_name_lookup, 'ans', None)
if ans is None:
try:
ans = load_libxkb_lookup()
except Exception as e:
print('Failed to load libxkbcommon.xkb_keysym_from_name with error:', e, file=sys.stderr)
ans = null_lookup
setattr(get_key_name_lookup, 'ans', ans)
return ans
+702
View File
@@ -0,0 +1,702 @@
/*
* keys.c
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "state.h"
#include "keys.h"
#include "screen.h"
#include "glfw-wrapper.h"
#include <structmember.h>
#ifndef __APPLE__
#include <xkbcommon/xkbcommon.h>
#endif
// python KeyEvent object {{{
typedef struct {
PyObject_HEAD PyObject *key, *shifted_key, *alternate_key;
PyObject *mods, *action, *native_key, *ime_state;
PyObject *text;
} PyKeyEvent;
static PyObject *convert_glfw_key_event_to_python(const GLFWkeyevent *ev);
static PyObject *
new_keyevent_object(PyTypeObject *type UNUSED, PyObject *args, PyObject *kw) {
static char *kwds[] = {"key", "shifted_key", "alternate_key", "mods", "action", "native_key", "ime_state", "text", NULL};
GLFWkeyevent ev = {.action = GLFW_PRESS};
if (!PyArg_ParseTupleAndKeywords(
args, kw, "I|IIiiiiz", kwds, &ev.key, &ev.shifted_key, &ev.alternate_key, &ev.mods, &ev.action, &ev.native_key, &ev.ime_state, &ev.text))
return NULL;
return convert_glfw_key_event_to_python(&ev);
}
bool
is_modifier_key(const uint32_t key) {
START_ALLOW_CASE_RANGE
switch (key) {
case GLFW_FKEY_LEFT_SHIFT ... GLFW_FKEY_ISO_LEVEL5_SHIFT:
case GLFW_FKEY_CAPS_LOCK:
case GLFW_FKEY_SCROLL_LOCK:
case GLFW_FKEY_NUM_LOCK: return true;
default: return false;
}
END_ALLOW_CASE_RANGE
}
static bool
is_no_action_key(const uint32_t key, const uint32_t native_key) {
switch (native_key) {
#ifndef __APPLE__
case XKB_KEY_XF86Fn:
case XKB_KEY_XF86WakeUp: return true;
#endif
default: return is_modifier_key(key);
}
}
static void
dealloc(PyKeyEvent *self) {
Py_CLEAR(self->key);
Py_CLEAR(self->shifted_key);
Py_CLEAR(self->alternate_key);
Py_CLEAR(self->mods);
Py_CLEAR(self->action);
Py_CLEAR(self->native_key);
Py_CLEAR(self->ime_state);
Py_CLEAR(self->text);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyMemberDef members[] = {
#define M(x) {#x, T_OBJECT, offsetof(PyKeyEvent, x), READONLY, #x}
M(key),
M(shifted_key),
M(alternate_key),
M(mods),
M(action),
M(native_key),
M(ime_state),
M(text),
{NULL},
#undef M
};
PyTypeObject PyKeyEvent_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.KeyEvent",
.tp_basicsize = sizeof(PyKeyEvent),
.tp_dealloc = (destructor)dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "A key event",
.tp_members = members,
.tp_new = new_keyevent_object,
};
static PyObject *
convert_glfw_key_event_to_python(const GLFWkeyevent *ev) {
PyKeyEvent *self = (PyKeyEvent *)PyKeyEvent_Type.tp_alloc(&PyKeyEvent_Type, 0);
if (!self) return NULL;
#define C(x) \
{ \
unsigned long t = ev->x; \
self->x = PyLong_FromUnsignedLong(t); \
if (self->x == NULL) { \
Py_CLEAR(self); \
return NULL; \
} \
}
C(key);
C(shifted_key);
C(alternate_key);
C(mods);
C(action);
C(native_key);
C(ime_state);
#undef C
self->text = PyUnicode_FromString(ev->text ? ev->text : "");
if (!self->text) {
Py_CLEAR(self);
return NULL;
}
return (PyObject *)self;
}
// }}}
static Window *
active_window(void) {
Tab *t = global_state.callback_os_window->tabs + global_state.callback_os_window->active_tab;
Window *w = t->windows + t->active_window;
if (!w->render_data.screen) return NULL;
if (w->redirect_keys_to_overlay) {
for (unsigned i = 0; i < t->num_windows; i++) {
if (t->windows[i].id == w->redirect_keys_to_overlay && w->render_data.screen) return t->windows + i;
}
}
return w;
}
void
update_ime_focus(OSWindow *osw, bool focused) {
if (!osw || !osw->handle) return;
GLFWIMEUpdateEvent ev = {.focused = focused, .type = GLFW_IME_UPDATE_FOCUS};
glfwUpdateIMEState(osw->handle, &ev);
}
void
prepare_ime_position_update_event(OSWindow *osw, Window *w, Screen *screen, GLFWIMEUpdateEvent *ev) {
unsigned int cell_width = osw->fonts_data->fcm.cell_width, cell_height = osw->fonts_data->fcm.cell_height;
unsigned int left = w->render_data.geometry.left, top = w->render_data.geometry.top;
if (screen_is_overlay_active(screen)) {
// Anchor to the start of the pre-edit text rather than its end, so the
// IME candidate window does not jump horizontally as the pre-edit grows.
left += screen_overlay_line_start(screen) * cell_width;
top += MIN(screen->overlay_line.ynum + screen->scrolled_by, screen->lines - 1) * cell_height;
} else {
left += screen->cursor->x * cell_width;
top += screen->cursor->y * cell_height;
}
ev->cursor.left = left;
ev->cursor.top = top;
ev->cursor.width = cell_width;
ev->cursor.height = cell_height;
}
void
update_ime_position(Window *w UNUSED, Screen *screen UNUSED) {
GLFWIMEUpdateEvent ev = {.type = GLFW_IME_UPDATE_CURSOR_POSITION};
#ifndef __APPLE__
prepare_ime_position_update_event(global_state.callback_os_window, w, screen, &ev);
#endif
glfwUpdateIMEState(global_state.callback_os_window->handle, &ev);
}
const char *
format_mods(unsigned mods) {
static char buf[128];
char *p = buf, *s;
#define pr(x) p += snprintf(p, sizeof(buf) - (p - buf) - 1, x)
pr("mods: ");
s = p;
if (mods & GLFW_MOD_CONTROL) pr("ctrl+");
if (mods & GLFW_MOD_ALT) pr("alt+");
if (mods & GLFW_MOD_SHIFT) pr("shift+");
if (mods & GLFW_MOD_SUPER) pr("super+");
if (mods & GLFW_MOD_HYPER) pr("hyper+");
if (mods & GLFW_MOD_META) pr("meta+");
if (mods & GLFW_MOD_CAPS_LOCK) pr("capslock+");
if (mods & GLFW_MOD_NUM_LOCK) pr("numlock+");
if (p == s) pr("none");
else p--;
pr(" ");
#undef pr
return buf;
}
static void
send_key_to_child(id_type window_id, Screen *screen, const GLFWkeyevent *ev) {
const int action = ev->action;
const uint32_t key = ev->key, native_key = ev->native_key;
const char *text = ev->text ? ev->text : "";
if (action == GLFW_REPEAT && !screen->modes.mDECARM) {
debug("discarding repeat key event as DECARM is off\n");
return;
}
if ((screen->scrolled_by || screen->pixel_scroll_offset_y != 0) && action == GLFW_PRESS && !is_no_action_key(key, native_key)) {
screen_history_scroll(screen, SCROLL_FULL, false); // scroll back to bottom
}
char encoded_key[KEY_BUFFER_SIZE] = {0};
int size = encode_glfw_key_event(ev, screen->modes.mDECCKM, screen_current_key_encoding_flags(screen), encoded_key);
if (size == SEND_TEXT_TO_CHILD) {
schedule_write_to_child(window_id, 1, text, strlen(text));
debug("sent key as text to child (window_id: %llu): %s\n", window_id, text);
} else if (size > 0) {
if (size == 1 && screen->modes.mHANDLE_TERMIOS_SIGNALS) {
if (screen_send_signal_for_key(screen, *encoded_key)) return;
}
schedule_write_to_child(window_id, 1, encoded_key, size);
if (OPT(debug_keyboard)) {
debug("sent encoded key to child (window_id: %llu): ", window_id);
for (int ki = 0; ki < size; ki++) {
if (encoded_key[ki] == 27) {
debug("^[ ");
} else if (encoded_key[ki] == ' ') {
debug("SPC ");
} else if (isprint(encoded_key[ki])) {
debug("%c ", encoded_key[ki]);
} else {
debug("0x%x ", encoded_key[ki]);
}
}
debug("\n");
}
} else {
debug("ignoring as keyboard mode does not support encoding this event\n");
}
}
void
dispatch_buffered_keys(Window *w) {
if (!w->render_data.screen || !w->buffered_keys.count) return;
GLFWkeyevent *keys = w->buffered_keys.key_data;
for (size_t i = 0; i < w->buffered_keys.count; i++) {
debug("Sending previously buffered key ");
send_key_to_child(w->id, w->render_data.screen, keys + i);
}
free_buffered_keys(w);
}
void
free_buffered_keys(Window *w) {
GLFWkeyevent *keys = w->buffered_keys.key_data;
// the text of buffered events is owned by us, see on_key_input()
for (size_t i = 0; i < w->buffered_keys.count; i++) free((char *)keys[i].text);
free(w->buffered_keys.key_data);
zero_at_ptr(&w->buffered_keys);
}
void
on_key_input(const GLFWkeyevent *ev) {
Window *w = active_window();
const int action = ev->action, mods = ev->mods;
const uint32_t key = ev->key, native_key = ev->native_key;
const char *text = ev->text ? ev->text : "";
if (OPT(debug_keyboard)) {
if (!key && !native_key && text[0]) {
debug("\x1b[33mon_IME_input\x1b[m: text: %s ", text);
} else {
debug(
"\x1b[33mon_key_input\x1b[m: glfw key: 0x%x native_code: 0x%x action: %s %stext: '%s' state: %d ",
key,
native_key,
(action == GLFW_RELEASE ? "RELEASE" : (action == GLFW_PRESS ? "PRESS" : "REPEAT")),
format_mods(mods),
text,
ev->ime_state);
}
}
if (!w) {
debug("no active window, ignoring\n");
return;
}
send_pending_click_to_window(w, -1);
if (OPT(mouse_hide.hide_wait) < 0 && !is_no_action_key(key, native_key)) hide_mouse(global_state.callback_os_window);
Screen *screen = w->render_data.screen;
id_type active_window_id = w->id;
switch (ev->ime_state) {
case GLFW_IME_WAYLAND_DONE_EVENT:
// If we update IME position here it sends GNOME's text input system into
// an infinite loop. See https://github.com/kovidgoyal/kitty/issues/5105
// and also: https://github.com/kovidgoyal/kitty/pull/7283
screen_update_overlay_text(screen, text);
debug("handled wayland IME done event\n");
return;
case GLFW_IME_PREEDIT_CHANGED:
// Empty pre-edit events are also sent without an IME, for example on focus loss
if (*text) global_state.ime_used = true;
screen_update_overlay_text(screen, text);
update_ime_position(w, screen);
debug("updated pre-edit text: '%s'\n", text);
return;
case GLFW_IME_COMMIT_TEXT:
if (*text) {
schedule_write_to_child(w->id, 1, text, strlen(text));
debug("committed pre-edit text: %s sent to child as text.\n", text);
} else debug("committed pre-edit text: (null)\n");
screen_update_overlay_text(screen, NULL);
return;
case GLFW_IME_NONE:
// for macOS, update ime position on every key input
// because the position is required before next input
// On Linux this is needed by Fig integration: https://github.com/kovidgoyal/kitty/issues/5241
update_ime_position(w, screen);
break;
default: debug("invalid state, ignoring\n"); return;
}
bool dispatch_ok = true, consumed = false;
#define dispatch_key_event(name) \
{ \
PyObject *ke = NULL, *ret = NULL; \
ke = convert_glfw_key_event_to_python(ev); \
if (!ke) { \
PyErr_Print(); \
return; \
}; \
ret = PyObject_CallMethod(global_state.boss, #name, "O", ke); \
Py_CLEAR(ke); \
if (ret == NULL) { \
PyErr_Print(); \
dispatch_ok = false; \
} else { \
consumed = ret == Py_True; \
Py_CLEAR(ret); \
} \
w = window_for_window_id(active_window_id); \
}
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
w->last_special_key_pressed = 0;
dispatch_key_event(dispatch_possible_special_key);
if (dispatch_ok) {
if (consumed) {
debug("handled as shortcut\n");
if (w) w->last_special_key_pressed = key;
return;
}
}
if (!w) return;
screen = w->render_data.screen;
} else if (w->last_special_key_pressed == key) {
w->last_special_key_pressed = 0;
dispatch_key_event(on_shortcut_key_release);
debug("dispatched release event for shortcut key\n");
return;
}
if (w->buffered_keys.enabled) {
if (w->buffered_keys.capacity < w->buffered_keys.count + 1) {
w->buffered_keys.capacity = MAX(16u, w->buffered_keys.capacity + 8);
GLFWkeyevent *new = realloc(w->buffered_keys.key_data, w->buffered_keys.capacity * sizeof(GLFWkeyevent));
if (!new) fatal("Out of memory");
w->buffered_keys.key_data = new;
}
GLFWkeyevent *k = (GLFWkeyevent *)w->buffered_keys.key_data + w->buffered_keys.count++;
*k = *ev;
// ev->text is only valid for the duration of this call
if (ev->text && !(k->text = strdup(ev->text))) fatal("Out of memory");
debug("buffering key until child is ready\n");
} else send_key_to_child(w->id, screen, ev);
#undef dispatch_key_event
}
void
fake_scroll(Window *w, int amount, bool upwards) {
if (!w) return;
int key = upwards ? GLFW_FKEY_UP : GLFW_FKEY_DOWN;
GLFWkeyevent ev = {.key = key};
char encoded_key[KEY_BUFFER_SIZE] = {0};
Screen *screen = w->render_data.screen;
uint8_t flags = screen_current_key_encoding_flags(screen);
while (amount-- > 0) {
ev.action = GLFW_PRESS;
int size = encode_glfw_key_event(&ev, screen->modes.mDECCKM, flags, encoded_key);
if (size > 0) schedule_write_to_child(w->id, 1, encoded_key, size);
ev.action = GLFW_RELEASE;
size = encode_glfw_key_event(&ev, screen->modes.mDECCKM, flags, encoded_key);
if (size > 0) schedule_write_to_child(w->id, 1, encoded_key, size);
}
}
#define PYWRAP1(name) static PyObject *py##name(PyObject UNUSED *self, PyObject *args)
#define PA(fmt, ...) \
if (!PyArg_ParseTuple(args, fmt, __VA_ARGS__)) return NULL;
#define M(name, arg_type) {#name, (PyCFunction)(void (*)(void))(py##name), arg_type, NULL}
PYWRAP1(key_for_native_key_name) {
const char *name;
int case_sensitive = 0;
PA("s|p", &name, &case_sensitive);
#ifndef __APPLE__
if (glfwGetNativeKeyForName) { // if this function is called before GLFW is initialized glfwGetNativeKeyForName will be NULL
int native_key = glfwGetNativeKeyForName(name, case_sensitive);
if (native_key) return Py_BuildValue("i", native_key);
}
#endif
Py_RETURN_NONE;
}
static PyObject *
pyencode_key_for_tty(PyObject *self UNUSED, PyObject *args, PyObject *kw) {
static char *kwds[] = {"key", "shifted_key", "alternate_key", "mods", "action", "key_encoding_flags", "text", "cursor_key_mode", NULL};
unsigned int key = 0, shifted_key = 0, alternate_key = 0, mods = 0, action = GLFW_PRESS, key_encoding_flags = 0;
const char *text = NULL;
int cursor_key_mode = 0;
if (!PyArg_ParseTupleAndKeywords(
args, kw, "I|IIIIIzp", kwds, &key, &shifted_key, &alternate_key, &mods, &action, &key_encoding_flags, &text, &cursor_key_mode))
return NULL;
GLFWkeyevent ev = {.key = key, .shifted_key = shifted_key, .alternate_key = alternate_key, .text = text, .action = action, .mods = mods};
char output[KEY_BUFFER_SIZE + 1] = {0};
int num = encode_glfw_key_event(&ev, cursor_key_mode, key_encoding_flags, output);
if (num == SEND_TEXT_TO_CHILD) return PyUnicode_FromString(text);
return PyUnicode_FromStringAndSize(output, MAX(0, num));
}
static PyObject *
pyinject_key(PyObject *self UNUSED, PyObject *args, PyObject *kw) {
static char *kwds[] = {"key", "shifted_key", "alternate_key", "mods", "action", "text", "os_window_id", NULL};
unsigned int key = 0, shifted_key = 0, alternate_key = 0, mods = 0, action = GLFW_PRESS;
unsigned long long os_window_id = 0;
const char *text = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kw, "I|IIIIzK", kwds, &key, &shifted_key, &alternate_key, &mods, &action, &text, &os_window_id)) return NULL;
id_type orig = global_state.callback_os_window ? global_state.callback_os_window->id : 0;
bool found = false;
if (os_window_id) {
for (size_t i = 0; i < global_state.num_os_windows && !found; i++) {
if (global_state.os_windows[i].id == os_window_id) {
global_state.callback_os_window = global_state.os_windows + i;
found = true;
}
}
if (!found) {
PyErr_Format(PyExc_IndexError, "Could not find OS Window with id: %llu", os_window_id);
return NULL;
}
} else {
if (!global_state.callback_os_window) {
for (size_t i = 0; i < global_state.num_os_windows && !found; i++) {
if (global_state.os_windows[i].is_focused) {
global_state.callback_os_window = global_state.os_windows + i;
found = true;
}
}
if (!found && !global_state.num_os_windows) {
PyErr_SetString(PyExc_Exception, "No OS Windows available to inject key presses into");
return NULL;
}
global_state.callback_os_window = global_state.os_windows;
found = true;
}
}
GLFWkeyevent ev = {.key = key, .shifted_key = shifted_key, .alternate_key = alternate_key, .text = text, .action = action, .mods = mods};
on_key_input(&ev);
if (orig) {
found = false;
for (size_t i = 0; i < global_state.num_os_windows && !found; i++) {
if (global_state.os_windows[i].id == orig) {
global_state.callback_os_window = global_state.os_windows + i;
found = true;
}
}
if (!found) global_state.callback_os_window = NULL;
} else global_state.callback_os_window = NULL;
Py_RETURN_NONE;
}
static PyObject *
pyis_modifier_key(PyObject *self UNUSED, PyObject *a) {
unsigned long key = PyLong_AsUnsignedLong(a);
if (PyErr_Occurred()) return NULL;
if (is_modifier_key(key)) { Py_RETURN_TRUE; }
Py_RETURN_FALSE;
}
static PyMethodDef module_methods[] = {
M(key_for_native_key_name, METH_VARARGS),
M(encode_key_for_tty, METH_VARARGS | METH_KEYWORDS),
M(inject_key, METH_VARARGS | METH_KEYWORDS),
M(is_modifier_key, METH_O),
{0}};
// SingleKey {{{
typedef uint64_t keybitfield;
#define KEY_BITS 51
#define MOD_BITS 12
#if 1 << (MOD_BITS - 1) < GLFW_MOD_KITTY
#error "Not enough mod bits"
#endif
typedef union Key {
struct {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
keybitfield mods : MOD_BITS;
keybitfield is_native : 1;
keybitfield key : KEY_BITS;
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
keybitfield key : KEY_BITS;
keybitfield is_native : 1;
keybitfield mods : MOD_BITS;
#else
#error "Unsupported endianness"
#endif
};
keybitfield val;
} Key;
static PyTypeObject SingleKey_Type;
static char *SingleKey_kwds[] = {"mods", "is_native", "key", NULL};
typedef struct {
PyObject_HEAD
Key key;
bool defined_with_kitty_mod;
} SingleKey;
static inline void
SingleKey_set_vals(SingleKey *self, long long key, unsigned short mods, int is_native) {
if (key >= 0 && (unsigned long long)key <= BIT_MASK(keybitfield, KEY_BITS)) {
keybitfield k = (keybitfield)(unsigned long long)key;
self->key.key = k & BIT_MASK(keybitfield, KEY_BITS);
}
if (!(mods & 1 << (MOD_BITS + 1))) self->key.mods = mods & BIT_MASK(uint32_t, MOD_BITS);
if (is_native > -1) self->key.is_native = is_native ? 1 : 0;
}
static PyObject *
SingleKey_new(PyTypeObject *type, PyObject *args, PyObject *kw) {
long long key = -1;
unsigned short mods = 1 << (MOD_BITS + 1);
int is_native = -1;
if (!PyArg_ParseTupleAndKeywords(args, kw, "|HpL", SingleKey_kwds, &mods, &is_native, &key)) return NULL;
SingleKey *self = (SingleKey *)type->tp_alloc(type, 0);
if (self) SingleKey_set_vals(self, key, mods, is_native);
return (PyObject *)self;
}
static void
SingleKey_dealloc(SingleKey *self) {
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
SingleKey_repr(PyObject *s) {
SingleKey *self = (SingleKey *)s;
char buf[128];
int pos = 0;
pos += PyOS_snprintf(buf + pos, sizeof(buf) - pos, "SingleKey(");
unsigned int mods = self->key.mods;
if (mods) pos += PyOS_snprintf(buf + pos, sizeof(buf) - pos, "mods=%u, ", mods);
if (self->key.is_native) pos += PyOS_snprintf(buf + pos, sizeof(buf) - pos, "is_native=True, ");
unsigned long long key = self->key.key;
if (key) pos += PyOS_snprintf(buf + pos, sizeof(buf) - pos, "key=%llu, ", key);
if (buf[pos - 1] == ' ') pos -= 2;
pos += PyOS_snprintf(buf + pos, sizeof(buf) - pos, ")");
return PyUnicode_FromString(buf);
}
static PyObject *
SingleKey_get_key(SingleKey *self, void UNUSED *closure) {
const unsigned long long val = self->key.key;
return PyLong_FromUnsignedLongLong(val);
}
static PyObject *
SingleKey_get_mods(SingleKey *self, void UNUSED *closure) {
const unsigned long mods = self->key.mods;
return PyLong_FromUnsignedLong(mods);
}
static PyObject *
SingleKey_get_is_native(SingleKey *self, void UNUSED *closure) {
if (self->key.is_native) Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject *
SingleKey_defined_with_kitty_mod(SingleKey *self, void UNUSED *closure) {
if (self->defined_with_kitty_mod || (self->key.mods & GLFW_MOD_KITTY)) Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyGetSetDef SingleKey_getsetters[] = {
{"key", (getter)SingleKey_get_key, NULL, "The key as an integer", NULL},
{"mods", (getter)SingleKey_get_mods, NULL, "The modifiers as an integer", NULL},
{"is_native", (getter)SingleKey_get_is_native, NULL, "A bool", NULL},
{"defined_with_kitty_mod", (getter)SingleKey_defined_with_kitty_mod, NULL, "A bool", NULL},
{NULL} /* Sentinel */
};
static Py_hash_t
SingleKey_hash(PyObject *self) {
Py_hash_t ans = ((SingleKey *)self)->key.val;
if (ans == -1) ans = -2;
return ans;
}
static PyObject *
SingleKey_richcompare(PyObject *self, PyObject *other, int op) {
if (!PyObject_TypeCheck(other, &SingleKey_Type)) {
PyErr_SetString(PyExc_TypeError, "Cannot compare SingleKey to other objects");
return NULL;
}
SingleKey *a = (SingleKey *)self, *b = (SingleKey *)other;
Py_RETURN_RICHCOMPARE(a->key.val, b->key.val, op);
}
static Py_ssize_t
SingleKey___len__(PyObject *self UNUSED) {
return 3;
}
static PyObject *
SingleKey_item(PyObject *o, Py_ssize_t i) {
SingleKey *self = (SingleKey *)o;
switch (i) {
case 0: return SingleKey_get_mods(self, NULL);
case 1: return SingleKey_get_is_native(self, NULL);
case 2: return SingleKey_get_key(self, NULL);
}
PyErr_SetString(PyExc_IndexError, "tuple index out of range");
return NULL;
}
static PySequenceMethods SingleKey_sequence_methods = {
.sq_length = SingleKey___len__,
.sq_item = SingleKey_item,
};
static PyObject *
SingleKey_resolve_kitty_mod(SingleKey *self, PyObject *km) {
if (!(self->key.mods & GLFW_MOD_KITTY)) {
Py_INCREF(self);
return (PyObject *)self;
}
unsigned long kitty_mod = PyLong_AsUnsignedLong(km);
if (PyErr_Occurred()) return NULL;
SingleKey *ans = (SingleKey *)SingleKey_Type.tp_alloc(&SingleKey_Type, 0);
if (!ans) return NULL;
ans->key.val = self->key.val;
ans->key.mods = (ans->key.mods & ~GLFW_MOD_KITTY) | kitty_mod;
ans->defined_with_kitty_mod = true;
return (PyObject *)ans;
}
static PyObject *
SingleKey_replace(SingleKey *self, PyObject *args, PyObject *kw) {
long long key = -2;
unsigned short mods = 1 << (MOD_BITS + 1);
int is_native = -1;
if (!PyArg_ParseTupleAndKeywords(args, kw, "|HpL", SingleKey_kwds, &mods, &is_native, &key)) return NULL;
SingleKey *ans = (SingleKey *)SingleKey_Type.tp_alloc(&SingleKey_Type, 0);
if (ans) {
if (key == -1) key = 0;
ans->key.val = self->key.val;
SingleKey_set_vals(ans, key, mods, is_native);
}
return (PyObject *)ans;
}
static PyMethodDef SingleKey_methods[] = {
{"_replace", (PyCFunction)(void (*)(void))SingleKey_replace, METH_VARARGS | METH_KEYWORDS, ""},
{"resolve_kitty_mod", (PyCFunction)SingleKey_resolve_kitty_mod, METH_O, ""},
{NULL} /* Sentinel */
};
static PyTypeObject SingleKey_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fast_data_types.SingleKey",
.tp_basicsize = sizeof(SingleKey),
.tp_dealloc = (destructor)SingleKey_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = "Compact and fast representation of a single key as defined in the config",
.tp_new = SingleKey_new,
.tp_hash = SingleKey_hash,
.tp_richcompare = SingleKey_richcompare,
.tp_as_sequence = &SingleKey_sequence_methods,
.tp_repr = SingleKey_repr,
.tp_methods = SingleKey_methods,
.tp_getset = SingleKey_getsetters,
}; // }}}
bool
init_keys(PyObject *module) {
if (PyModule_AddFunctions(module, module_methods) != 0) return false;
if (PyType_Ready(&PyKeyEvent_Type) < 0) return false;
if (PyModule_AddObject(module, "KeyEvent", (PyObject *)&PyKeyEvent_Type) != 0) return 0;
Py_INCREF(&PyKeyEvent_Type);
ADD_TYPE(SingleKey);
return true;
}
+20
View File
@@ -0,0 +1,20 @@
/*
* keys.h
* Copyright (C) 2021 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include "glfw-wrapper.h"
#include <limits.h>
#define KEY_BUFFER_SIZE 128
#define SEND_TEXT_TO_CHILD INT_MIN
#define debug debug_input
int encode_glfw_key_event(const GLFWkeyevent *e, const bool cursor_key_mode, const unsigned flags, char *output);
bool is_modifier_key(const uint32_t key);
Loaded 100 of 1134 files, more files were not shown because too many files have changed in this diff. Show more