From aba6d85ed5e10d74a3dc74b7dfe5e1bf39717ef4 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 6 Nov 2026 11:45:21 +0530 Subject: [PATCH] macOS: shave another 30ms of startup time by initializing while slow python imports are being done --- kitty/glfw.c | 83 ++++++++++++++++++++++------------------- kitty/logout_session.py | 6 ++- kitty/main.py | 31 ++++++++++++--- 3 files changed, 74 insertions(+), 46 deletions(-) diff --git a/kitty/glfw.c b/kitty/glfw.c index edea35cea..f0cebf327 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -2501,11 +2501,10 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { uint32_t bgcolor = OPT(background); uint32_t bgalpha = (uint32_t)((MAX(0.f, MIN((OPT(background_opacity) * 255), 255.f)))); glfwWindowHint(GLFW_WAYLAND_BGCOLOR, ((bgalpha & 0xff) << 24) | bgcolor); - // We use a temp window to avoid the need to set the window size after - // creation, which causes a resize event and all the associated processing. - // The temp window is used to get the DPI. On Wayland no temp window can be - // used, so start with window visible unless hidden window requested. - GLFWwindow *temp_window = NULL; + // The DPI is needed before the window is created to calculate its size, to + // avoid the need to set the window size after creation, which causes a + // resize event and all the associated processing. On Wayland start with + // the window visible unless a hidden window is requested. glfwWindowHint(GLFW_VISIBLE, window_state != WINDOW_HIDDEN && global_state.is_wayland); float xscale, yscale; double xdpi, ydpi; @@ -2541,17 +2540,12 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { #undef QUERY_MONITOR } } else { -#define glfw_failure(is_panel) \ - { \ - set_window_creation_error(is_panel); \ - return NULL; \ - } - - glfwGetError(NULL); // clear any stale error - temp_window = glfwCreateWindow(640, 480, "temp", NULL, NULL); - if (temp_window == NULL) glfw_failure(false); - get_window_content_scale(temp_window, &xscale, &yscale, &xdpi, &ydpi); - startup_timing("Temporary window for DPI created"); + // On X11 the scale is the same for all monitors. On macOS new windows + // are placed on the primary monitor, if the window ends up on a + // monitor with a different scale, the fonts are reloaded below. + // Creating a temporary window to get the scale is slow, particularly on + // macOS where destroying it alone takes ~10ms. + get_window_content_scale(NULL, &xscale, &yscale, &xdpi, &ydpi); } FONTS_DATA_HANDLE fonts_data = load_fonts_data(OPT(font_size), xdpi, ydpi); startup_timing("Fonts loaded"); @@ -2583,12 +2577,10 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { glfwGetError(NULL); // clear any stale error GLFWwindow *glfw_window = glfwCreateWindow(width, height, title_utf8, NULL, lsc); initial_window_size_py_callback = NULL; - if (temp_window) { - glfwDestroyWindow(temp_window); - temp_window = NULL; + if (glfw_window == NULL) { + set_window_creation_error(lsc != NULL); + return NULL; } - if (glfw_window == NULL) glfw_failure(lsc != NULL); -#undef glfw_failure // Set titlebar-only mode before the window becomes visible if (global_state.is_wayland && (OPT(hide_window_decorations) & 2) && glfwWaylandSetTitlebarHidden) { glfwWaylandSetTitlebarHidden(glfw_window, true); } gpu_surface_t gpu_surface; @@ -2941,31 +2933,40 @@ glfw_init(PyObject UNUSED *self, PyObject *args) { #ifdef __APPLE__ cocoa_set_uncaught_exception_handler(); #endif - const char *err = load_glfw(path); + // Loading and initializing glfw is slow, particularly on macOS, where it + // is mostly spent waiting for the window server, so release the GIL to + // allow other Python threads to run, see init_glfw() in main.py. Nothing + // here must use Python, until the GIL is re-acquired. + const char *err; + bool ok = false, supports_window_occlusion = false; + Py_BEGIN_ALLOW_THREADS; + err = load_glfw(path); + if (!err) { + glfw_is_loaded = true; + push_modifier_remap_to_glfw(); + glfwSetErrorCallback(error_callback); + glfwInitHint(GLFW_DEBUG_KEYBOARD, debug_keyboard); + glfwInitHint(GLFW_DEBUG_RENDERING, debug_rendering); + OPT(debug_keyboard) = debug_keyboard != 0; + glfwInitHint(GLFW_WAYLAND_IME, wayland_enable_ime != 0); +#ifdef __APPLE__ + glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, 0); + glfwInitHint(GLFW_COCOA_MENUBAR, 0); +#endif + ok = glfwInit(monotonic_start_time, &supports_window_occlusion); + } + Py_END_ALLOW_THREADS; if (err) { PyErr_SetString(PyExc_RuntimeError, err); return NULL; } - glfw_is_loaded = true; - push_modifier_remap_to_glfw(); - glfwSetErrorCallback(error_callback); - glfwInitHint(GLFW_DEBUG_KEYBOARD, debug_keyboard); - glfwInitHint(GLFW_DEBUG_RENDERING, debug_rendering); - OPT(debug_keyboard) = debug_keyboard != 0; - glfwInitHint(GLFW_WAYLAND_IME, wayland_enable_ime != 0); -#ifdef __APPLE__ - glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, 0); - glfwInitHint(GLFW_COCOA_MENUBAR, 0); -#else - if (glfwDBusSetUserNotificationHandler) { glfwDBusSetUserNotificationHandler(dbus_user_notification_activated); } -#endif - bool supports_window_occlusion = false; - bool ok = glfwInit(monotonic_start_time, &supports_window_occlusion); if (ok) { #ifdef __APPLE__ glfwSetCocoaURLOpenCallback(apple_url_open_callback); #else glfwSetDrawTextFunction(draw_text_callback); + // Set only now as it calls Python + if (glfwDBusSetUserNotificationHandler) { glfwDBusSetUserNotificationHandler(dbus_user_notification_activated); } #endif get_window_dpi(NULL, &global_state.default_dpi.x, &global_state.default_dpi.y); edge_spacing_func = edge_sf; @@ -2985,7 +2986,13 @@ glfw_init(PyObject UNUSED *self, PyObject *args) { // for when the first window is created, see wait_for_gpu_driver(). // libwayland supports using the connection from multiple threads, X11 // connections are not thread safe unless XInitThreads() is called. - if ((err = display.platform == GPU_PLATFORM_WAYLAND ? load_next_gpu_driver_async(&display) : load_next_gpu_driver(&display))) { + if (display.platform == GPU_PLATFORM_WAYLAND) err = load_next_gpu_driver_async(&display); + else { + Py_BEGIN_ALLOW_THREADS; + err = load_next_gpu_driver(&display); + Py_END_ALLOW_THREADS; + } + if (err) { PyErr_Format(PyExc_RuntimeError, "Failed to load a GPU driver:\n%s", err); return NULL; } diff --git a/kitty/logout_session.py b/kitty/logout_session.py index c54b72315..3403c6918 100644 --- a/kitty/logout_session.py +++ b/kitty/logout_session.py @@ -26,9 +26,7 @@ import fcntl import json import os import re -import secrets import shutil -import tempfile import time from collections.abc import Callable, Mapping from contextlib import suppress @@ -203,6 +201,8 @@ def delete_key(key_store: KeyStore, key_id: str, path: str) -> None: def new_key_id() -> str: + import secrets # slow to import and not needed at startup + return secrets.token_hex(KEY_ID_BYTES) @@ -367,6 +367,8 @@ def save_snapshot(base: str, pid: int, session: str, scrollback: Mapping[int, by tdir = '' try: os.makedirs(base, mode=0o700, exist_ok=True) + import tempfile # not needed at startup + tdir = tempfile.mkdtemp(dir=base, prefix=f'{pid}.', suffix='.tmp') if key_id: write_private_file(os.path.join(tdir, KEY_ID_FILE), key_id.encode()) diff --git a/kitty/main.py b/kitty/main.py index 792792578..9a795793b 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -10,6 +10,7 @@ import sys from collections.abc import Generator, Sequence from contextlib import contextmanager, suppress from gettext import gettext as _ +from threading import Thread from . import logout_session from .child import set_default_env, set_LANG_in_default_env @@ -99,7 +100,7 @@ def set_custom_ibeam_cursor() -> None: def load_all_shaders() -> None: - from .shaders.slang import load_shader_programs # see _run_app() for why this is not imported at the top + from .shaders.slang import load_shader_programs # see import_slow_modules() for why this is not imported at the top try: load_shader_programs() @@ -315,15 +316,29 @@ def logout_snapshot_to_restore(opts: Options, args: CLIOptions) -> RestoredSnaps return None +def import_slow_modules() -> None: + # These modules are slow to import, so they are imported in a thread, while + # init_glfw() runs with the GIL released, see glfw_init() in glfw.c. On + # Wayland, they are also imported while the GPU driver is loaded in a thread. + try: + from . import boss, session # noqa: F401 + from .shaders import slang # noqa: F401 + except Exception: + pass # The modules are imported again in the main thread, which reports the error + + +slow_modules_importer: Thread | None = None + + def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), talk_fd: int = -1) -> None: - # These modules are slow to import and are imported here rather than at - # the top of this module, so that they are imported after init_glfw(), - # which on Wayland loads the GPU driver in a thread, see glfw_init() - # in glfw.c, while they are being imported. + # Joined here rather than in kitty_main() so that font selection, started + # in AppRunner.__call__(), runs in parallel with the imports + if slow_modules_importer is not None: + slow_modules_importer.join() + startup_timing('Imported the boss and session modules') from .boss import Boss from .session import create_sessions, get_os_window_sizing_data - startup_timing('Imported the boss and session modules') global _is_panel_kitten _is_panel_kitten = run_app.cached_values_name == 'panel' if _is_panel_kitten and run_app.layer_shell_config and run_app.layer_shell_config.output_name in ('list', 'listjson'): @@ -713,6 +728,10 @@ def kitty_main(called_from_panel: bool = False) -> None: # threads. These threads must not handle the masked signals, to ensure # kitty can handle them. See https://github.com/kovidgoyal/kitty/issues/4636 mask_kitty_signals_process_wide() + # Started after masking signals, so the thread inherits the mask + global slow_modules_importer + slow_modules_importer = Thread(target=import_slow_modules, name='ImportSlowModules', daemon=True) + slow_modules_importer.start() init_glfw(opts, cli_opts.debug_keyboard, cli_opts.debug_rendering) startup_timing('GLFW initialized') try: