Cleanup previous PR
Some checks are pending
CI / Linux (python=3.14 cc=clang sanitize=1) (push) Waiting to run
CI / Linux (python=3.12 cc=gcc sanitize=0) (push) Waiting to run
CI / Linux (python=3.13 cc=gcc sanitize=1) (push) Waiting to run
CI / Linux package (push) Waiting to run
CI / Bundle test (macos-latest) (push) Waiting to run
CI / Bundle test (ubuntu-latest) (push) Waiting to run
CI / macOS Brew (push) Waiting to run
CI / Test ./dev.sh and benchmark (push) Waiting to run
CodeQL / CodeQL-Build (actions, ubuntu-latest) (push) Waiting to run
CodeQL / CodeQL-Build (c, macos-latest) (push) Waiting to run
CodeQL / CodeQL-Build (c, ubuntu-latest) (push) Waiting to run
CodeQL / CodeQL-Build (go, ubuntu-latest) (push) Waiting to run
CodeQL / CodeQL-Build (python, ubuntu-latest) (push) Waiting to run
Depscan / Scan dependencies for vulnerabilities (push) Waiting to run

Store per color scheme auto theme state in a typed dataclass instead of
string built attribute names. Track which theme files were seen during
the directory scan rather than checking for existence afterwards, so a
file deleted mid-scan cannot invalidate unscanned themes. Reset
applied_theme when the applied theme file is deleted.

Always re-read theme files on config reload and apply the theme for the
current system color scheme. Previously, once the applied theme was
invalidated, reloads stopped refreshing theme files, so re-creating the
file had no effect until the next system color scheme change. This also
means theme files created after startup are now applied on reload.
This commit is contained in:
Kovid Goyal 2026-10-31 17:15:08 +05:30
parent f988590dfa
commit fe55cd1963
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
4 changed files with 134 additions and 113 deletions

View file

@ -429,7 +429,8 @@ Detailed list of changes
containing spaces or quoting characters (:pull:`10784`)
- Automatic color themes: Stop using cached colors and background images after
the corresponding theme file has been deleted
the corresponding theme file has been deleted and apply theme files created
after kitty was started when reloading the config (:pull:`10786`)
- Themes kitten: Fix overwriting the Unicode input kitten's recent entries
and input mode, and vice versa, by using separate caches (:pull:`10780`)

View file

@ -3656,11 +3656,7 @@ class Boss:
for tm in self.all_tab_managers:
tm.apply_options()
# Update colors
if theme_colors.has_applied_theme:
theme_colors.refresh()
if theme_colors.has_applied_theme: # in case the theme file was deleted
assert theme_colors.applied_theme # to make type check happy
theme_colors.apply_theme(theme_colors.applied_theme, notify_on_bg_change=False)
theme_colors.on_config_reload()
for w in self.all_windows:
if w.screen.color_profile.default_bg != bg_colors_before.get(w.id):
self.default_bg_changed_for(w.id)

View file

@ -3,7 +3,7 @@
import os
from collections.abc import Iterable, Sequence
from contextlib import suppress
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Literal, Optional, TypedDict, cast
@ -50,14 +50,26 @@ class ThemeFile(Enum):
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:
dark_mtime: int = -1
light_mtime: int = -1
no_preference_mtime: int = -1
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
@ -88,72 +100,53 @@ class ThemeColors:
return ans, (() if tbc is None else tbc)
def refresh(self) -> bool:
found = False
"Load new or modified theme files and forget deleted ones. Returns True if any theme changed."
changed = False
if config_dir_files_ignored():
return found
d: BackgroundImageOptions
with suppress(FileNotFoundError):
for x in os.scandir(config_dir):
if x.name == ThemeFile.dark.value:
mtime = x.stat().st_mtime_ns
if mtime > self.dark_mtime:
with open(x.path) as f:
d = {}
self.dark_spec, self.dark_tbc = self.parse_colors(f, d)
self.dark_background_image_options = d
self.dark_mtime = mtime
found = True
elif x.name == ThemeFile.light.value:
mtime = x.stat().st_mtime_ns
if mtime > self.light_mtime:
with open(x.path) as f:
d = {}
self.light_spec, self.light_tbc = self.parse_colors(f, d)
self.light_background_image_options = d
self.light_mtime = mtime
found = True
elif x.name == ThemeFile.no_preference.value:
mtime = x.stat().st_mtime_ns
if mtime > self.no_preference_mtime:
with open(x.path) as f:
d = {}
self.no_preference_spec, self.no_preference_tbc = self.parse_colors(f, d)
self.no_preference_background_image_options = d
self.no_preference_mtime = mtime
found = True
for theme in ThemeFile:
name = theme.name
if getattr(self, f'{name}_mtime') > -1 and not os.path.exists(os.path.join(config_dir, theme.value)):
setattr(self, f'{name}_mtime', -1)
setattr(self, f'{name}_spec', {})
setattr(self, f'{name}_tbc', ())
setattr(self, f'{name}_background_image_options', {})
found = True
return found
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:
match self.applied_theme:
case '':
return False
case 'dark':
return self.has_dark_theme
case 'light':
return self.has_light_theme
case 'no_preference':
return self.has_no_preference_theme
return self.applied_theme != '' and self.themes[self.applied_theme].mtime > -1
@property
def has_dark_theme(self) -> bool:
return self.dark_mtime > -1
return self.themes['dark'].mtime > -1
@property
def has_light_theme(self) -> bool:
return self.light_mtime > -1
return self.themes['light'].mtime > -1
@property
def has_no_preference_theme(self) -> bool:
return self.no_preference_mtime > -1
return self.themes['no_preference'].mtime > -1
def patch_opts(self, opts: Options, debug_rendering: bool = False) -> None:
from .utils import log_error
@ -163,20 +156,10 @@ class ThemeColors:
which = glfw_get_system_color_theme()
if debug_rendering:
log_error('Current system color scheme:', which)
cols: Colors | None = None
bgo: BackgroundImageOptions | None = None
if which == 'dark' and self.has_dark_theme:
cols = self.dark_spec, self.dark_tbc
bgo = self.dark_background_image_options
elif which == 'light' and self.has_light_theme:
cols = self.light_spec, self.light_tbc
bgo = self.light_background_image_options
elif which == 'no_preference' and self.has_no_preference_theme:
cols = self.no_preference_spec, self.no_preference_tbc
bgo = self.no_preference_background_image_options
if cols is not None:
patch_options_with_color_spec(opts, *cols, background_image_options=bgo)
patch_global_colors(cols[0], True)
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')
@ -187,39 +170,26 @@ class ThemeColors:
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
boss = get_boss()
if new_value == 'dark' and self.has_dark_theme:
patch_colors(
self.dark_spec, self.dark_tbc, True, notify_on_bg_change=notify_on_bg_change, background_image_options=self.dark_background_image_options
)
self.applied_theme = new_value
if boss.args.debug_rendering:
log_error(f'Applied color theme {new_value}')
return True
if new_value == 'light' and self.has_light_theme:
patch_colors(
self.light_spec, self.light_tbc, True, notify_on_bg_change=notify_on_bg_change, background_image_options=self.light_background_image_options
)
self.applied_theme = new_value
if boss.args.debug_rendering:
log_error(f'Applied color theme {new_value}')
return True
if new_value == 'no_preference' and self.has_no_preference_theme:
patch_colors(
self.no_preference_spec,
self.no_preference_tbc,
True,
notify_on_bg_change=notify_on_bg_change,
background_image_options=self.no_preference_background_image_options,
)
self.applied_theme = new_value
if boss.args.debug_rendering:
log_error(f'Applied color theme {new_value}')
return True
return False
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()

View file

@ -106,11 +106,12 @@ action two
from types import SimpleNamespace
from unittest.mock import patch
from kitty.colors import ThemeColors, ThemeFile
from kitty.colors import ThemeColors, ThemeFile, theme_file_schemes
self.set_options()
boss = SimpleNamespace(args=SimpleNamespace(debug_rendering=False))
for theme in ThemeFile:
scheme = theme_file_schemes[theme.value]
for remove_directory in (False, True):
with self.subTest(theme=theme.name, remove_directory=remove_directory), tempfile.TemporaryDirectory() as tdir:
config_dir = os.path.join(tdir, 'kitty')
@ -126,20 +127,21 @@ action two
):
tc = ThemeColors()
self.assertTrue(tc.refresh())
self.assertTrue(tc.apply_theme(theme.name))
mtime = getattr(tc, f'{theme.name}_mtime')
self.assertTrue(tc.apply_theme(scheme))
mtime = tc.themes[scheme].mtime
apply.reset_mock()
if remove_directory:
shutil.rmtree(config_dir)
else:
os.unlink(os.path.join(config_dir, theme.value))
changed = tc.refresh()
self.assertFalse(tc.apply_theme(theme.name), 'Deleted automatic theme was applied again')
self.assertFalse(tc.apply_theme(scheme), 'Deleted automatic theme was applied again')
self.assertFalse(tc.has_applied_theme)
self.ae(tc.applied_theme, '')
for other in ThemeFile:
self.ae(getattr(tc, f'has_{other.name}_theme'), not remove_directory and other is not theme)
self.assertFalse(tc.refresh())
self.assertFalse(tc.on_system_color_scheme_change(theme.name))
self.assertFalse(tc.on_system_color_scheme_change(scheme))
apply.assert_not_called()
self.assertTrue(changed)
os.makedirs(config_dir, exist_ok=True)
@ -148,13 +150,65 @@ action two
f.write('background #abcdef\n')
os.utime(path, ns=(mtime, mtime))
self.assertTrue(tc.refresh())
self.assertTrue(tc.apply_theme(theme.name))
self.assertTrue(tc.apply_theme(scheme))
apply.assert_called_once()
self.ae(apply.call_args.args[0]['background'], 0xABCDEF)
self.ae(apply.call_args.args[1], ())
self.ae(apply.call_args.kwargs['background_image_options']['background_image'], ())
self.assertFalse(tc.refresh())
def test_auto_theme_config_reload(self):
import tempfile
from types import SimpleNamespace
from unittest.mock import patch
from kitty.colors import ThemeColors, ThemeFile
self.set_options()
boss = SimpleNamespace(args=SimpleNamespace(debug_rendering=False))
with tempfile.TemporaryDirectory() as config_dir:
path = os.path.join(config_dir, ThemeFile.dark.value)
with (
patch('kitty.colors.config_dir', config_dir),
patch('kitty.colors.config_dir_files_ignored', return_value=False),
patch('kitty.colors.get_boss', return_value=boss),
patch('kitty.colors.glfw_get_system_color_theme', return_value='dark'),
patch('kitty.colors.patch_colors') as apply,
):
tc = ThemeColors()
# No theme file: reloading applies nothing
tc.on_config_reload()
apply.assert_not_called()
self.ae(tc.applied_theme, '')
# A theme file created after startup is applied on reload
with open(path, 'w') as f:
f.write('background #111111\n')
tc.on_config_reload()
apply.assert_called_once()
self.ae(apply.call_args.args[0]['background'], 0x111111)
self.ae(tc.applied_theme, 'dark')
# Deleting it stops it from being applied
apply.reset_mock()
os.unlink(path)
tc.on_config_reload()
apply.assert_not_called()
self.ae(tc.applied_theme, '')
# Re-creating it applies it again
with open(path, 'w') as f:
f.write('background #222222\n')
tc.on_config_reload()
apply.assert_called_once()
self.ae(apply.call_args.args[0]['background'], 0x222222)
self.ae(tc.applied_theme, 'dark')
# A theme only for a different color scheme is not applied
apply.reset_mock()
os.rename(path, os.path.join(config_dir, ThemeFile.light.value))
tc.on_config_reload()
apply.assert_not_called()
self.ae(tc.applied_theme, '')
self.assertTrue(tc.has_light_theme)
self.assertFalse(tc.has_dark_theme)
def test_mime_cache(self):
import shutil
import subprocess