PBKittyConfigStudio 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. pb_kitty_config_studio/__init__.py +3 -0
  2. pb_kitty_config_studio/__main__.py +153 -0
  3. pb_kitty_config_studio/argparse_qt.py +99 -0
  4. pb_kitty_config_studio/config/__init__.py +81 -0
  5. pb_kitty_config_studio/config/_babel_extractor.py +35 -0
  6. pb_kitty_config_studio/config/schema.json +3654 -0
  7. pb_kitty_config_studio/core/__init__.py +0 -0
  8. pb_kitty_config_studio/core/kitty_conf.py +316 -0
  9. pb_kitty_config_studio/i18n.py +115 -0
  10. pb_kitty_config_studio/locale/en/LC_MESSAGES/pb_kitty_config_studio.mo +0 -0
  11. pb_kitty_config_studio/locale/en/LC_MESSAGES/pb_kitty_config_studio.po +978 -0
  12. pb_kitty_config_studio/locale/fr/LC_MESSAGES/pb_kitty_config_studio.mo +0 -0
  13. pb_kitty_config_studio/locale/fr/LC_MESSAGES/pb_kitty_config_studio.po +983 -0
  14. pb_kitty_config_studio/platform/__init__.py +1 -0
  15. pb_kitty_config_studio/platform/auto_update.py +267 -0
  16. pb_kitty_config_studio/platform/desktop.py +174 -0
  17. pb_kitty_config_studio/resources/__init__.py +54 -0
  18. pb_kitty_config_studio/resources/cancel.svg +1 -0
  19. pb_kitty_config_studio/resources/clear-all-data.svg +1 -0
  20. pb_kitty_config_studio/resources/help-about.svg +1 -0
  21. pb_kitty_config_studio/resources/pbkittyconfigstudio.icns +0 -0
  22. pb_kitty_config_studio/resources/pbkittyconfigstudio.ico +0 -0
  23. pb_kitty_config_studio/resources/pbkittyconfigstudio.png +0 -0
  24. pb_kitty_config_studio/resources/quit.svg +1 -0
  25. pb_kitty_config_studio/resources/refresh.svg +1 -0
  26. pb_kitty_config_studio/resources/save-as.svg +1 -0
  27. pb_kitty_config_studio/resources/save.svg +1 -0
  28. pb_kitty_config_studio/ui/__init__.py +0 -0
  29. pb_kitty_config_studio/ui/about_dialog.py +160 -0
  30. pb_kitty_config_studio/ui/main_window.py +491 -0
  31. pb_kitty_config_studio/ui/widgets.py +363 -0
  32. pbkittyconfigstudio-0.1.0.dist-info/METADATA +161 -0
  33. pbkittyconfigstudio-0.1.0.dist-info/RECORD +36 -0
  34. pbkittyconfigstudio-0.1.0.dist-info/WHEEL +4 -0
  35. pbkittyconfigstudio-0.1.0.dist-info/entry_points.txt +2 -0
  36. pbkittyconfigstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
File without changes
@@ -0,0 +1,316 @@
1
+ """Reading, editing and reloading kitty's own ``kitty.conf``.
2
+
3
+ kitty.conf is a flat ``key value`` text format (one setting per line, ``#``
4
+ starts a comment). We never attempt a full parse/re-serialize of the file:
5
+ like the original Node.js prototype this project is based on, each setting
6
+ is located and rewritten with a targeted regex so that the rest of the file
7
+ — comments, unrelated directives, ``include`` lines — is left untouched.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import tempfile
18
+ import time
19
+ from datetime import datetime
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ _log = logging.getLogger(__name__)
24
+
25
+
26
+ def default_config_path() -> Path:
27
+ """Return the path kitty itself would use for ``kitty.conf``.
28
+
29
+ Mirrors kitty's own search order (see kitty's ``config.py``):
30
+ ``KITTY_CONFIG_DIRECTORY`` first, then the platform's XDG-style config
31
+ directory, i.e. ``$XDG_CONFIG_HOME/kitty`` (or ``~/.config/kitty`` on
32
+ Linux/macOS) and ``%APPDATA%\\kitty`` on Windows.
33
+ """
34
+ override = os.environ.get("KITTY_CONFIG_DIRECTORY")
35
+ if override:
36
+ return Path(override) / "kitty.conf"
37
+
38
+ if os.name == "nt":
39
+ base = os.environ.get("APPDATA")
40
+ config_dir = Path(base) if base else Path.home() / "AppData" / "Roaming"
41
+ else:
42
+ base = os.environ.get("XDG_CONFIG_HOME")
43
+ config_dir = Path(base) if base else Path.home() / ".config"
44
+
45
+ return config_dir / "kitty" / "kitty.conf"
46
+
47
+
48
+ def _line_regex_for(key: str) -> re.Pattern[str]:
49
+ """Match a single active *or* commented-out line for *key* — used to
50
+ locate the (first) line to rewrite in place when saving.
51
+ """
52
+ return re.compile(rf"^[ \t]*#?[ \t]*{re.escape(key)}[ \t]+(.*)$", re.MULTILINE)
53
+
54
+
55
+ def _all_lines_regex_for(key: str) -> re.Pattern[str]:
56
+ """Match *every* active-or-commented line for *key*, each including its
57
+ trailing newline — used to remove all occurrences of a multi-value
58
+ setting before rewriting the full set.
59
+ """
60
+ return re.compile(rf"^[ \t]*#?[ \t]*{re.escape(key)}[ \t]+.*\n?", re.MULTILINE)
61
+
62
+
63
+ def _active_regex_for(key: str) -> re.Pattern[str]:
64
+ """Match only an active (non-commented) line — used when reading the
65
+ current value, so a commented-out setting counts as unset.
66
+ """
67
+ return re.compile(rf"^[ \t]*{re.escape(key)}[ \t]+(.*)$", re.MULTILINE)
68
+
69
+
70
+ def read_raw(path: Path) -> str:
71
+ """Return the file's contents, or "" if it does not exist yet."""
72
+ if not path.is_file():
73
+ return ""
74
+ return path.read_text(encoding="utf-8")
75
+
76
+
77
+ def parse_config(
78
+ config_text: str, schema: dict[str, Any]
79
+ ) -> dict[str, str | list[str]]:
80
+ """Extract the current value of every schema setting from *config_text*.
81
+
82
+ A single-value setting absent from the file (or only present
83
+ commented-out) falls back to its schema default (a string). A
84
+ multi-value setting (``setting["multi"]`` is true, e.g. ``font_features``,
85
+ ``modify_font``) returns the list of every active line's value, in file
86
+ order — or the schema's declared default values if none are active.
87
+ """
88
+ from pb_kitty_config_studio.config import iter_settings
89
+
90
+ result: dict[str, str | list[str]] = {}
91
+ for _group_path, _group, key, setting in iter_settings(schema):
92
+ if setting.get("multi"):
93
+ matches = [
94
+ m.group(1).strip() for m in _active_regex_for(key).finditer(config_text)
95
+ ]
96
+ result[key] = matches or [
97
+ d["value"]
98
+ for d in setting.get("defaults", [])
99
+ if d.get("add_to_default")
100
+ ]
101
+ else:
102
+ match = _active_regex_for(key).search(config_text)
103
+ result[key] = match.group(1).strip() if match else str(setting["default"])
104
+ return result
105
+
106
+
107
+ def is_default_value(value: str | list[str], setting: dict[str, Any]) -> bool:
108
+ """True if *value* equals the setting's schema default.
109
+
110
+ For a multi-value setting, *value* is either a single line's worth of
111
+ text (checked against the set of declared default values — used by
112
+ ``apply_settings``, deciding one line at a time) or the *whole* current
113
+ list of values (checked against the whole default set — used by the UI,
114
+ badging a row as "unchanged" from ``widget.value()``).
115
+ """
116
+ if setting.get("multi"):
117
+ default_values = {
118
+ d["value"] for d in setting.get("defaults", []) if d.get("add_to_default")
119
+ }
120
+ if isinstance(value, list):
121
+ return set(value) == default_values
122
+ return value in default_values
123
+ return _scalars_equal(value, setting["default"])
124
+
125
+
126
+ def default_value(setting: dict[str, Any]) -> str | list[str]:
127
+ """Return *setting*'s schema default, in the same shape ``widget.value()``
128
+ returns (a list for a multi-value setting, a string otherwise) — used to
129
+ reset a row's widget to its default.
130
+ """
131
+ if setting.get("multi"):
132
+ return [
133
+ d["value"] for d in setting.get("defaults", []) if d.get("add_to_default")
134
+ ]
135
+ return str(setting["default"])
136
+
137
+
138
+ def _scalars_equal(value: Any, default: Any) -> bool:
139
+ """Compare as numbers when both sides parse as one (a spin box may
140
+ format "1.5" as "1.50", which is still the default), else as stripped
141
+ strings.
142
+ """
143
+ try:
144
+ return float(value) == float(default)
145
+ except (TypeError, ValueError):
146
+ return str(value).strip() == str(default).strip()
147
+
148
+
149
+ def apply_settings(
150
+ config_text: str, settings: dict[str, str | list[str]], schema: dict[str, Any]
151
+ ) -> str:
152
+ """Return *config_text* with every setting in *settings* applied.
153
+
154
+ Lines for a key are rewritten in place at their first existing
155
+ occurrence (multi-value settings: all existing occurrences are removed
156
+ and the full current set re-inserted there); a key with no existing
157
+ line is appended at the end, in schema order. A value equal to the
158
+ setting's schema default is written as a commented-out line (documents
159
+ it without forcing it), any other value as an active line.
160
+ """
161
+ from pb_kitty_config_studio.config import iter_settings
162
+
163
+ ordered_settings = [
164
+ (key, setting)
165
+ for _gp, _g, key, setting in iter_settings(schema)
166
+ if key in settings
167
+ ]
168
+
169
+ for key, setting in ordered_settings:
170
+ value = settings[key]
171
+ values = value if isinstance(value, list) else [value]
172
+ lines = [
173
+ f"{'# ' if is_default_value(v, setting) else ''}{key} {v}" for v in values
174
+ ] or [f"# {key}"]
175
+ replacement = "\n".join(lines)
176
+
177
+ if setting.get("multi"):
178
+ all_regex = _all_lines_regex_for(key)
179
+ first_match = all_regex.search(config_text)
180
+ if first_match:
181
+ config_text = (
182
+ config_text[: first_match.start()]
183
+ + replacement
184
+ + "\n"
185
+ + all_regex.sub("", config_text[first_match.end() :], count=0)
186
+ )
187
+ else:
188
+ config_text += f"\n{replacement}"
189
+ else:
190
+ regex = _line_regex_for(key)
191
+ if regex.search(config_text):
192
+ config_text = regex.sub(replacement, config_text, count=1)
193
+ else:
194
+ config_text += f"\n{replacement}"
195
+ return config_text.strip() + "\n"
196
+
197
+
198
+ def backup(path: Path) -> Path | None:
199
+ """Copy *path* to a timestamped sibling before it gets overwritten.
200
+
201
+ Returns the backup path, or None if *path* did not exist yet (nothing
202
+ to back up).
203
+ """
204
+ if not path.is_file():
205
+ return None
206
+ stamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
207
+ backup_path = path.with_name(f"{path.name}.bak_{stamp}")
208
+ shutil.copyfile(path, backup_path)
209
+ _log.info("Backup created: %s", backup_path)
210
+ return backup_path
211
+
212
+
213
+ def write_config(path: Path, config_text: str) -> None:
214
+ path.parent.mkdir(parents=True, exist_ok=True)
215
+ path.write_text(config_text, encoding="utf-8")
216
+
217
+
218
+ def reload_kitty() -> bool:
219
+ """Best-effort hot-reload: send SIGUSR1 to every running kitty process.
220
+
221
+ Returns True if the signal command ran without error. Failure (e.g. no
222
+ kitty running, or ``pkill`` missing on this platform) is not fatal —
223
+ the config file has already been saved either way.
224
+ """
225
+ if os.name == "nt":
226
+ return False
227
+ try:
228
+ subprocess.run(
229
+ ["pkill", "-USR1", "kitty"], check=True, capture_output=True, timeout=5
230
+ )
231
+ return True
232
+ except (subprocess.SubprocessError, FileNotFoundError, OSError) as exc:
233
+ _log.debug("Could not signal kitty for reload: %s", exc)
234
+ return False
235
+
236
+
237
+ def kitty_available() -> bool:
238
+ """True if a ``kitty`` executable can be found on ``PATH``."""
239
+ return shutil.which("kitty") is not None
240
+
241
+
242
+ def generate_default_config(timeout: float = 10.0) -> str:
243
+ """Return kitty's own pristine, fully-commented example ``kitty.conf``.
244
+
245
+ kitty writes this template itself the first time it needs to edit a
246
+ config file that doesn't exist yet — the same thing that happens when
247
+ the user presses Ctrl+Shift+F2 inside kitty. There is no library call
248
+ or CLI flag that produces it directly, so this launches a throwaway
249
+ kitty instance pointed at an empty, temporary config directory,
250
+ triggers that same ``edit_config_file`` action over kitty's
251
+ remote-control protocol, and reads back what it wrote. ``EDITOR`` is
252
+ pointed at a no-op so the editor kitty opens exits immediately without
253
+ touching the freshly-written file.
254
+
255
+ Raises FileNotFoundError if kitty isn't installed, and RuntimeError if
256
+ it doesn't play along within *timeout* seconds.
257
+ """
258
+ if not kitty_available():
259
+ raise FileNotFoundError("kitty executable not found on PATH")
260
+ noop_editor = shutil.which("true") or "/bin/true"
261
+
262
+ with tempfile.TemporaryDirectory(prefix="pbkittyconfigstudio-") as tmp:
263
+ conf_dir = Path(tmp) / "config"
264
+ conf_dir.mkdir()
265
+ socket_path = Path(tmp) / "kitty.sock"
266
+ env = os.environ | {
267
+ "KITTY_CONFIG_DIRECTORY": str(conf_dir),
268
+ "EDITOR": noop_editor,
269
+ }
270
+
271
+ kitty = subprocess.Popen(
272
+ [
273
+ "kitty",
274
+ "--start-as",
275
+ "minimized",
276
+ "--listen-on",
277
+ f"unix:{socket_path}",
278
+ "-o",
279
+ "allow_remote_control=yes",
280
+ ],
281
+ env=env,
282
+ )
283
+ try:
284
+ deadline = time.monotonic() + timeout
285
+ while not socket_path.exists():
286
+ if time.monotonic() > deadline:
287
+ raise RuntimeError(
288
+ "kitty did not create its control socket in time"
289
+ )
290
+ time.sleep(0.05)
291
+
292
+ subprocess.run(
293
+ [
294
+ "kitty",
295
+ "@",
296
+ "--to",
297
+ f"unix:{socket_path}",
298
+ "action",
299
+ "edit_config_file",
300
+ ],
301
+ check=True,
302
+ capture_output=True,
303
+ timeout=timeout,
304
+ )
305
+ finally:
306
+ kitty.terminate()
307
+ try:
308
+ kitty.wait(timeout=5)
309
+ except subprocess.TimeoutExpired:
310
+ kitty.kill()
311
+ kitty.wait(timeout=5)
312
+
313
+ generated = conf_dir / "kitty.conf"
314
+ if not generated.is_file():
315
+ raise RuntimeError("kitty did not write a kitty.conf")
316
+ return generated.read_text(encoding="utf-8")
@@ -0,0 +1,115 @@
1
+ """Internationalisation bootstrap.
2
+
3
+ Call ``setup(app)`` once, before creating the main window. It:
4
+ * reads the language override from QSettings (if set),
5
+ * detects the system language as a fallback,
6
+ * loads the matching gettext catalogue (falls back to a no-op),
7
+ * installs ``_()`` as a builtin for every Python-side string.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import gettext
13
+ import locale
14
+ import os
15
+ from pathlib import Path
16
+
17
+ from PySide6.QtCore import QLibraryInfo, QSettings, QTranslator
18
+ from PySide6.QtWidgets import QApplication
19
+
20
+ _DOMAIN = "pb_kitty_config_studio"
21
+ _LOCALE_DIR = Path(__file__).parent / "locale"
22
+ _ORG = "cardolan"
23
+ _APP = "PBKittyConfigStudio"
24
+ _SETTINGS_KEY = "language/override"
25
+
26
+
27
+ def system_language() -> str:
28
+ """Best-effort system language code (e.g. "fr", "en")."""
29
+ for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):
30
+ val = os.environ.get(var)
31
+ if val:
32
+ return val.split(":")[0].split(".")[0].split("_")[0]
33
+ try:
34
+ lang, _enc = locale.getlocale()
35
+ if lang:
36
+ return lang.split("_")[0]
37
+ except (ValueError, TypeError):
38
+ pass
39
+ return "en"
40
+
41
+
42
+ def available_languages() -> list[tuple[str, str]]:
43
+ """Return ``[(lang_code, lang_name_in_that_language), …]`` sorted by code.
44
+
45
+ Discovered dynamically from the ``.mo`` files under the locale
46
+ directory; each catalogue must define a ``language_name`` msgid.
47
+ """
48
+ result: list[tuple[str, str]] = []
49
+ for mo_path in sorted(_LOCALE_DIR.glob(f"*/LC_MESSAGES/{_DOMAIN}.mo")):
50
+ lang_code = mo_path.parts[-3]
51
+ try:
52
+ t = gettext.translation(
53
+ _DOMAIN, localedir=str(_LOCALE_DIR), languages=[lang_code]
54
+ )
55
+ except FileNotFoundError:
56
+ continue
57
+ lang_name = t.gettext("language_name")
58
+ result.append(
59
+ (lang_code, lang_name if lang_name != "language_name" else lang_code)
60
+ )
61
+ return result
62
+
63
+
64
+ def _settings() -> QSettings:
65
+ return QSettings(QSettings.Format.IniFormat, QSettings.Scope.UserScope, _ORG, _APP)
66
+
67
+
68
+ def get_language_override() -> str:
69
+ """Return the saved language code, or "" for the system default."""
70
+ val = _settings().value(_SETTINGS_KEY, "")
71
+ return val if isinstance(val, str) else ""
72
+
73
+
74
+ def set_language_override(code: str) -> None:
75
+ """Persist *code* as the language override ("" clears the override)."""
76
+ _settings().setValue(_SETTINGS_KEY, code)
77
+
78
+
79
+ class _GettextTranslator(QTranslator):
80
+ """Qt translator delegating every lookup to a gettext catalogue."""
81
+
82
+ def __init__(
83
+ self, translation: gettext.NullTranslations, parent: QApplication
84
+ ) -> None:
85
+ super().__init__(parent)
86
+ self._t = translation
87
+
88
+ def translate(self, context, source_text, disambiguation=None, n=-1) -> str: # noqa: ANN001
89
+ return self._t.gettext(source_text)
90
+
91
+
92
+ def setup(app: QApplication) -> None:
93
+ """Install translations for *app*. Safe to call more than once."""
94
+ override = get_language_override()
95
+ lang = override if override else system_language()
96
+
97
+ try:
98
+ t: gettext.NullTranslations = gettext.translation(
99
+ _DOMAIN, localedir=str(_LOCALE_DIR), languages=[lang]
100
+ )
101
+ except FileNotFoundError:
102
+ t = gettext.NullTranslations()
103
+
104
+ t.install()
105
+ # Marks "language_name" for pybabel extraction: available_languages()
106
+ # below looks it up dynamically via a per-catalogue gettext.translation()
107
+ # object, which pybabel's static `_()` scan cannot see.
108
+ _("language_name")
109
+
110
+ app.installTranslator(_GettextTranslator(t, app))
111
+
112
+ qt_translations = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath)
113
+ qt_translator = QTranslator(app)
114
+ if qt_translator.load(f"qtbase_{lang.split('_')[0]}", qt_translations):
115
+ app.installTranslator(qt_translator)