Add a gpu_driver option to choose between GPU drivers with fallback

The gpu_driver option is an ordered list of the GPU drivers to try,
defaulting to metal, vulkan, opengl. Drivers that are not part of the
build are skipped.

Add connect() to the GPU driver API. It is called once the windowing
system has been initialized, with the connection to the display, so
that drivers can check that they are able to render to windows on it,
before any windows are created. The driver is now loaded after
glfwInit() for this reason. If a driver cannot connect, the next one is
tried. If the driver fails to choose a visual or create a surface for
the first window, before any GPU resources exist, kitty switches to the
next usable driver and creates the window again.

--debug-rendering reports the driver used and why others were rejected.
This commit is contained in:
Kovid Goyal 2026-11-03 21:35:56 +05:30
parent 0b386f5564
commit 9367df7010
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
13 changed files with 248 additions and 32 deletions

View file

@ -322,8 +322,17 @@ typedef struct GPUDriverAPI {
const char *(*shader_target)(void *driver);
// Lifecycle {{{
// Called once, after the driver is loaded and before any surfaces are
// created, with the connection to the windowing system: only the
// platform, display and screen fields of display are used. The driver
// must check, as far as is possible without a window, that it can render
// to windows on this display, for example, that the needed system
// libraries are present and that there is a GPU that can present to the
// display. If it returns false, last_error() describes the problem and
// kitty unloads the driver and tries the next one.
bool (*connect)(void *driver, const GPUNativeWindow *display);
// Called once, when the first surface has been created and made current.
// Must be called before any other function except destroy(),
// Must be called before any other function except connect(), destroy(),
// last_error() and the surface functions.
bool (*initialize)(void *driver);
void (*destroy)(void *driver);

View file

@ -1056,6 +1056,11 @@ ensure_platform(Driver *d, GPUPlatform type) {
return true;
}
static bool
connect_to_display(void *driver, const GPUNativeWindow *display) {
return ensure_platform(driver, display->platform);
}
static bool
choose_native_visual(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) {
Driver *d = driver;
@ -1310,6 +1315,7 @@ kitty_gpu_driver_load(uint32_t api_version, const GPUDriverInitParams *params, G
.name = "OpenGL",
#define F(name) .name = name
F(shader_target),
.connect = connect_to_display,
F(initialize),
F(destroy),
F(last_error),

View file

@ -4,7 +4,7 @@
import os
import pwd
import sys
from collections.abc import Iterator
from collections.abc import Iterable, Iterator
from contextlib import suppress
from typing import TYPE_CHECKING, Any, NamedTuple, Optional
@ -237,6 +237,17 @@ def gpu_driver_path(driver: str = 'opengl') -> str:
return os.path.join(extensions_dir, f'{prefix}{driver}.so')
def available_gpu_drivers(names: Iterable[str]) -> list[tuple[str, str]]:
# The (name, path) of the specified GPU drivers that are present in this
# build of kitty, in the specified order
ans = []
for name in names:
path = gpu_driver_path(name)
if os.path.exists(path):
ans.append((name, path))
return ans
def detect_if_wayland_ok() -> bool:
if not os.environ.get('WAYLAND_DISPLAY') and not os.environ.get('WAYLAND_SOCKET'):
return False

View file

@ -637,7 +637,7 @@ def glfw_terminate() -> None:
def glfw_init(
path: str,
gpu_driver_path: str,
gpu_drivers: Sequence[tuple[str, str]], # (name, path) of the GPU drivers to try in order
edge_spacing_func: Callable[[EdgeLiteral], float],
debug_keyboard: bool = False,
debug_rendering: bool = False,

View file

@ -2328,6 +2328,34 @@ is_visible_on_a_monitor(int x, int y, int width, int height) {
return false;
}
typedef char GPUFailure[2048];
static void
describe_gpu_failure(GPUFailure failure, const char *what) {
snprintf(failure, sizeof(GPUFailure), "Failed to %s with the %s GPU driver with error: %s", what, gpu_driver_name(), gpu_last_error());
}
// Called when the GPU driver fails while creating the first window, before
// any GPU resources exist, to switch to the next GPU driver, see the
// gpu_driver option. Any surfaces must have been destroyed. Returns false,
// with a Python exception set, if there is no other usable driver.
static bool
switch_gpu_driver_after_failure(bool is_first_window, const GPUFailure failure) {
if (is_first_window && has_untried_gpu_drivers()) {
GPUNativeWindow display;
native_window_for_gpu(NULL, &display);
const char *err = load_next_gpu_driver(&display);
if (!err) {
log_error("%s, using the %s GPU driver instead", failure, gpu_driver_name());
return true;
}
PyErr_Format(PyExc_OSError, "%s. Other GPU drivers are also not usable:\n%s", failure, err);
return false;
}
PyErr_Format(PyExc_OSError, "%s. This usually happens because of old/broken GPU drivers.", failure);
return false;
}
static PyObject *
create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
int x = INT_MIN, y = INT_MIN, window_state = WINDOW_NORMAL, disallow_override_title = 0;
@ -2446,7 +2474,9 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
native_window_for_gpu(NULL, &display);
uint64_t visual_id = 0;
if (!gpu_choose_native_visual(&display, &surface_config, &visual_id)) {
PyErr_Format(PyExc_OSError, "Failed to choose an X11 visual for the window with error: %s", gpu_last_error());
GPUFailure failure;
describe_gpu_failure(failure, "choose an X11 visual for the window");
if (switch_gpu_driver_after_failure(is_first_window, failure)) return create_os_window(self, args, kw);
return NULL;
}
glfwWindowHint(GLFW_X11_VISUAL_ID, (int)visual_id);
@ -2551,12 +2581,11 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
glfwGetFramebufferSize(glfw_window, &fw, &fh);
gpu_surface = gpu_surface_create(&native, &surface_config, (uint32_t)MAX(1, fw), (uint32_t)MAX(1, fh));
if (!gpu_surface || !gpu_make_surface_current(gpu_surface)) {
PyErr_Format(
PyExc_OSError,
"Failed to create a GPU surface for the window with error: %s. This usually happens because of old/broken GPU drivers.",
gpu_last_error());
GPUFailure failure;
describe_gpu_failure(failure, "create a GPU surface for the window");
if (gpu_surface) gpu_surface_destroy(gpu_surface);
glfwDestroyWindow(glfw_window);
if (switch_gpu_driver_after_failure(is_first_window, failure)) return create_os_window(self, args, kw);
return NULL;
}
}
@ -2848,16 +2877,38 @@ dbus_monitor_session_state(PyObject *self UNUSED, PyObject *callback) {
}
#endif
// Parse a sequence of (name, path) pairs of GPU drivers into candidates
static bool
set_gpu_drivers(PyObject *gpu_drivers, bool debug_rendering) {
RAII_PyObject(seq, PySequence_Fast(gpu_drivers, "gpu_drivers must be a sequence of (name, path) pairs"));
if (!seq) return false;
const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
RAII_ALLOC(GPUDriverCandidate, items, calloc(MAX(1, n), sizeof(GPUDriverCandidate)));
if (!items) {
PyErr_NoMemory();
return false;
}
for (Py_ssize_t i = 0; i < n; i++) {
if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "ss", &items[i].name, &items[i].path)) return false;
}
if (!set_gpu_driver_candidates(items, (size_t)n, debug_rendering)) {
PyErr_NoMemory();
return false;
}
return true;
}
static PyObject *
glfw_init(PyObject UNUSED *self, PyObject *args) {
const char *path, *gpu_driver_path;
const char *path;
int debug_keyboard = 0, debug_rendering = 0, wayland_enable_ime = 0;
PyObject *edge_sf;
if (!PyArg_ParseTuple(args, "ssO|ppp", &path, &gpu_driver_path, &edge_sf, &debug_keyboard, &debug_rendering, &wayland_enable_ime)) return NULL;
PyObject *edge_sf, *gpu_drivers;
if (!PyArg_ParseTuple(args, "sOO|ppp", &path, &gpu_drivers, &edge_sf, &debug_keyboard, &debug_rendering, &wayland_enable_ime)) return NULL;
if (!PyCallable_Check(edge_sf)) {
PyErr_SetString(PyExc_TypeError, "edge_spacing_func must be a callable");
return NULL;
}
if (!set_gpu_drivers(gpu_drivers, debug_rendering != 0)) return NULL;
Py_CLEAR(edge_spacing_func);
#ifdef __APPLE__
cocoa_set_uncaught_exception_handler();
@ -2868,11 +2919,6 @@ glfw_init(PyObject UNUSED *self, PyObject *args) {
return NULL;
}
glfw_is_loaded = true;
err = load_gpu_driver(gpu_driver_path, debug_rendering != 0);
if (err) {
PyErr_SetString(PyExc_RuntimeError, err);
return NULL;
}
push_modifier_remap_to_glfw();
glfwSetErrorCallback(error_callback);
glfwInitHint(GLFW_DEBUG_KEYBOARD, debug_keyboard);
@ -2896,6 +2942,21 @@ glfw_init(PyObject UNUSED *self, PyObject *args) {
get_window_dpi(NULL, &global_state.default_dpi.x, &global_state.default_dpi.y);
edge_spacing_func = edge_sf;
Py_INCREF(edge_spacing_func);
// The GPU driver needs the connection to the windowing system to
// check that it can render to windows, see connect() in gpu/api.h.
// global_state.is_wayland is not yet set, so use the loaded glfw
// module, which exports only the functions of its own platform.
#ifdef __APPLE__
const GPUNativeWindow display = {.platform = GPU_PLATFORM_COCOA};
#else
void *wl_display = glfwGetWaylandDisplay ? glfwGetWaylandDisplay() : NULL;
const GPUNativeWindow display = wl_display ? (GPUNativeWindow){.platform = GPU_PLATFORM_WAYLAND, .display = wl_display}
: (GPUNativeWindow){.platform = GPU_PLATFORM_X11, .display = glfwGetX11Display(), .screen = -1};
#endif
if ((err = load_next_gpu_driver(&display))) {
PyErr_Format(PyExc_RuntimeError, "Failed to load a GPU driver:\n%s", err);
return NULL;
}
}
return Py_BuildValue("OO", ok ? Py_True : Py_False, supports_window_occlusion ? Py_True : Py_False);
}

View file

@ -86,6 +86,68 @@ load_gpu_driver(const char *path, bool debug_rendering) {
return NULL;
}
static struct {
GPUDriverCandidate items[8];
size_t count, next;
bool debug_rendering;
} candidates = {0};
bool
set_gpu_driver_candidates(const GPUDriverCandidate *items, size_t count, bool debug_rendering) {
for (size_t i = 0; i < candidates.count; i++) {
free((void *)candidates.items[i].name);
free((void *)candidates.items[i].path);
}
zero_at_ptr(&candidates);
candidates.debug_rendering = debug_rendering;
for (size_t i = 0; i < count && i < arraysz(candidates.items); i++) {
GPUDriverCandidate *c = candidates.items + candidates.count++;
c->name = strdup(items[i].name);
c->path = strdup(items[i].path);
if (!c->name || !c->path) return false;
}
return true;
}
bool
has_untried_gpu_drivers(void) {
return candidates.next < candidates.count;
}
const char *
load_next_gpu_driver(const GPUNativeWindow *display) {
static char errbuf[8192];
size_t pos = 0;
errbuf[0] = 0;
#define add_error(...) \
if (pos < sizeof(errbuf)) pos += snprintf(errbuf + pos, sizeof(errbuf) - pos, __VA_ARGS__);
if (gpu_driver.driver) {
if (gpu_driver.initialized) fatal("Cannot switch GPU drivers after the driver has been initialized");
gpu_release_native_resources();
unload_gpu_driver();
}
if (!candidates.count) {
add_error("No GPU drivers are available");
return errbuf;
}
while (candidates.next < candidates.count) {
const GPUDriverCandidate *c = candidates.items + candidates.next++;
const char *err = load_gpu_driver(c->path, candidates.debug_rendering);
if (!err) {
if (gpu_driver.api.connect(gpu_driver.driver, display)) {
if (candidates.debug_rendering) timed_debug_print("Using the %s GPU driver\n", c->name);
return NULL;
}
err = gpu_last_error();
}
if (candidates.debug_rendering) timed_debug_print("The %s GPU driver is not usable: %s\n", c->name, err);
add_error("%sThe %s GPU driver is not usable: %s", pos ? "\n" : "", c->name, err);
if (gpu_driver.driver) unload_gpu_driver();
}
#undef add_error
return errbuf;
}
void
initialize_gpu_driver(void) {
if (gpu_driver.initialized) return;

View file

@ -25,6 +25,23 @@ extern GPUDriver gpu_driver;
// Load the GPU driver shared library at path. Returns NULL on success or an error message.
const char *load_gpu_driver(const char *path, bool debug_rendering);
// Choosing between GPU drivers {{{
// The drivers to try, in order of preference, see the gpu_driver option
typedef struct GPUDriverCandidate {
const char *name, *path;
} GPUDriverCandidate;
// Remember the drivers to try. Copies the strings.
bool set_gpu_driver_candidates(const GPUDriverCandidate *candidates, size_t count, bool debug_rendering);
// Unload the current driver, if any, and load the next candidate that can
// render to windows on the specified display, see connect() in gpu/api.h.
// Returns NULL on success or a description of why every remaining
// candidate failed. Must be called before any GPU resources are created.
const char *load_next_gpu_driver(const GPUNativeWindow *display);
// Whether there are candidates that have not yet been tried
bool has_untried_gpu_drivers(void);
// }}}
// Must be called once a surface has been created and made current, before any
// other GPU functions, except the surface functions, are used
void initialize_gpu_driver(void);

View file

@ -20,10 +20,10 @@ from .conf.utils import BadLine
from .config import cached_values_for
from .constants import (
appname,
available_gpu_drivers,
beam_cursor_data_file,
clear_handled_signals,
glfw_path,
gpu_driver_path,
is_macos,
is_quick_access_terminal_app,
is_wayland,
@ -65,7 +65,7 @@ from .logout_session import (
remove_all_snapshots,
restore_snapshots,
)
from .options.types import Options
from .options.types import Options, defaults
from .options.utils import DELETE_ENV_VAR
from .os_window_size import edge_spacing, initial_window_size_func
from .session import create_sessions, get_os_window_sizing_data
@ -105,8 +105,17 @@ def load_all_shaders() -> None:
raise SystemExit(err)
def init_glfw_module(glfw_module: str = 'wayland', debug_keyboard: bool = False, debug_rendering: bool = False, wayland_enable_ime: bool = True) -> None:
ok, swo = glfw_init(glfw_path(glfw_module), gpu_driver_path(), edge_spacing, debug_keyboard, debug_rendering, wayland_enable_ime)
def init_glfw_module(
glfw_module: str = 'wayland',
debug_keyboard: bool = False,
debug_rendering: bool = False,
wayland_enable_ime: bool = True,
gpu_drivers: Sequence[str] = defaults.gpu_driver,
) -> None:
drivers = available_gpu_drivers(gpu_drivers)
if not drivers:
raise SystemExit(f'None of the GPU drivers: {", ".join(gpu_drivers)} are available in this build of kitty, check the gpu_driver option')
ok, swo = glfw_init(glfw_path(glfw_module), drivers, edge_spacing, debug_keyboard, debug_rendering, wayland_enable_ime)
if not ok:
raise SystemExit('GLFW initialization failed')
supports_window_occlusion(swo)
@ -114,7 +123,7 @@ def init_glfw_module(glfw_module: str = 'wayland', debug_keyboard: bool = False,
def init_glfw(opts: Options, debug_keyboard: bool = False, debug_rendering: bool = False) -> str:
glfw_module = 'cocoa' if is_macos else ('wayland' if is_wayland(opts) else 'x11')
init_glfw_module(glfw_module, debug_keyboard, debug_rendering, wayland_enable_ime=opts.wayland_enable_ime)
init_glfw_module(glfw_module, debug_keyboard, debug_rendering, wayland_enable_ime=opts.wayland_enable_ime, gpu_drivers=opts.gpu_driver)
return glfw_module

View file

@ -1569,6 +1569,22 @@ monitor. With a very high speed mouse/high keyboard repeat rate, you may notice
some slight input latency. If so, set this to :code:`no`.
""",
)
opt(
'gpu_driver',
'metal vulkan opengl',
option_type='gpu_driver',
long_text="""
The GPU drivers kitty uses to render, as a space or comma separated list, in
order of preference. kitty uses the first driver in the list that works on your
system, skipping drivers that are not available on your platform or were not
included in the build of kitty. The available drivers are: :code:`metal`
(macOS), :code:`vulkan` (Linux and BSD) and :code:`opengl` (all platforms).
Use :option:`kitty --debug-rendering` to see which driver is used and why
others were rejected. Changing this option by reloading the config is not
supported.
""",
)
egr() # }}}

25
kitty/options/parse.py generated
View file

@ -15,17 +15,17 @@ from kitty.options.utils import (
custom_shaders, deprecated_adjust_line_height, deprecated_hide_window_decorations_aliases,
deprecated_macos_show_window_title_in_menubar_alias, deprecated_scrollback_indicator_opacity,
deprecated_send_text, disable_ligatures, edge_width, env, filter_notification, font_features,
hide_window_decorations, macos_option_as_alt, macos_titlebar_color, menu_map, modify_font,
mouse_hide_wait, narrow_symbols, notify_on_cmd_finish, optional_edge_width, parse_font_spec,
parse_map, parse_mouse_map, paste_actions, pointer_shape_when_dragging, remap_modifiers,
remote_control_password, resize_debounce_time, scrollback_lines, scrollback_pager_history_size,
scrollbar_color, shell_integration, show_hyperlink_targets, store_multiple, symbol_map,
tab_activity_symbol, tab_bar_edge, tab_bar_margin_height, tab_bar_min_tabs, tab_fade,
tab_font_style, tab_separator, tab_title_template, tab_title_wrap, text_fg_override_threshold,
titlebar_color, to_cursor_shape, to_cursor_unfocused_shape, to_font_size, to_layout_names,
to_modifiers, transparent_background_colors, underline_exclusion, url_prefixes, url_style,
visual_bell_duration, visual_window_select_characters, window_border_width, window_logo_scale,
window_size
gpu_driver, hide_window_decorations, macos_option_as_alt, macos_titlebar_color, menu_map,
modify_font, mouse_hide_wait, narrow_symbols, notify_on_cmd_finish, optional_edge_width,
parse_font_spec, parse_map, parse_mouse_map, paste_actions, pointer_shape_when_dragging,
remap_modifiers, remote_control_password, resize_debounce_time, scrollback_lines,
scrollback_pager_history_size, scrollbar_color, shell_integration, show_hyperlink_targets,
store_multiple, symbol_map, tab_activity_symbol, tab_bar_edge, tab_bar_margin_height,
tab_bar_min_tabs, tab_fade, tab_font_style, tab_separator, tab_title_template, tab_title_wrap,
text_fg_override_threshold, titlebar_color, to_cursor_shape, to_cursor_unfocused_shape,
to_font_size, to_layout_names, to_modifiers, transparent_background_colors, underline_exclusion,
url_prefixes, url_style, visual_bell_duration, visual_window_select_characters, window_border_width,
window_logo_scale, window_size
)
@ -1049,6 +1049,9 @@ class Parser:
def forward_stdio(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['forward_stdio'] = to_bool(val)
def gpu_driver(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['gpu_driver'] = gpu_driver(val)
def hide_window_decorations(self, val: str, ans: dict[str, typing.Any]) -> None:
ans['hide_window_decorations'] = hide_window_decorations(val)

View file

@ -375,6 +375,7 @@ option_names = (
'force_ltr',
'foreground',
'forward_stdio',
'gpu_driver',
'hide_window_decorations',
'hyperlink_target_position',
'inactive_border_color',
@ -601,6 +602,7 @@ class Options:
force_ltr: bool = False
foreground: Color = Color(221, 221, 221)
forward_stdio: bool = False
gpu_driver: tuple[str, ...] = ('metal', 'vulkan', 'opengl')
hide_window_decorations: int = 0
hyperlink_target_position: choices_for_hyperlink_target_position = 'top'
inactive_border_color: Color = Color(204, 204, 204)

View file

@ -1034,6 +1034,22 @@ def clipboard_control(x: str) -> tuple[str, ...]:
return tuple(x.lower().split())
GPU_DRIVERS = ('metal', 'vulkan', 'opengl')
def gpu_driver(x: str) -> tuple[str, ...]:
ans: list[str] = []
for name in re.split(r'[\s,]+', x.strip().lower()):
if name:
if name not in GPU_DRIVERS:
raise ValueError(f'Unknown GPU driver: {name}, must be one of: {", ".join(GPU_DRIVERS)}')
if name not in ans:
ans.append(name)
if not ans:
raise ValueError('At least one GPU driver must be specified')
return tuple(ans)
def custom_shaders(x: str) -> tuple[str, ...]:
return tuple(shlex_split(x)) if x else ()

View file

@ -404,6 +404,10 @@ def conf_parsing(self):
opts = p('font_size 11.37', 'clear_all_shortcuts y', 'color23 red')
self.ae(opts.font_size, 11.37)
self.ae(defaults.gpu_driver, ('metal', 'vulkan', 'opengl'))
self.ae(p('gpu_driver vulkan, opengl opengl').gpu_driver, ('vulkan', 'opengl'))
self.ae(p('gpu_driver opengl,vulkan').gpu_driver, ('opengl', 'vulkan'))
self.ae(p('gpu_driver directx opengl', bad_line_num=1).gpu_driver, defaults.gpu_driver)
radius_opts = p('window_border_radius 7px')
self.ae(radius_opts.window_border_radius, (7.0, 'px'))
self.ae(defaults.hyperlink_target_position, 'top')