| 1 |
#!/usr/bin/python |
| 2 |
# pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-locals |
| 3 |
# pylint: disable=too-many-branches,too-many-statements,too-many-return-statements |
| 4 |
# pylint: disable=too-many-lines |
| 5 |
# gsettings_import_export.py |
| 6 |
# |
| 7 |
# Standalone tool for importing/exporting Orca settings between JSON and GSettings. |
| 8 |
# |
| 9 |
# Examples (run from the repo root): |
| 10 |
# |
| 11 |
# 1. Import your JSON settings into dconf. First preview what will be written: |
| 12 |
# |
| 13 |
# python tools/gsettings_import_export.py import --dry-run $HOME/.local/share/orca |
| 14 |
# |
| 15 |
# If the output looks correct, run the import for real. WARNING: This overwrites |
| 16 |
# any existing Orca settings in your dconf database. To clear imported settings |
| 17 |
# afterwards use "dconf reset -f /org/gnome/orca/" but note that this will not |
| 18 |
# restore whatever was there before the import. |
| 19 |
# |
| 20 |
# python tools/gsettings_import_export.py import $HOME/.local/share/orca |
| 21 |
# |
| 22 |
# View the result: |
| 23 |
# |
| 24 |
# dconf dump /org/gnome/orca/ |
| 25 |
# |
| 26 |
# 2. Export your dconf settings to JSON files that can be copied to another machine: |
| 27 |
# |
| 28 |
# python tools/gsettings_import_export.py export /tmp/orca-export |
| 29 |
# |
| 30 |
# This creates /tmp/orca-export/user-settings.conf and, if there are app-specific |
| 31 |
# overrides, /tmp/orca-export/app-settings/<AppName>.conf. To use the exported |
| 32 |
# files on another machine, copy them to $HOME/.local/share/orca/. |
| 33 |
# |
| 34 |
# 3. Roundtrip test (import → export → diff against original): |
| 35 |
# |
| 36 |
# python tools/gsettings_import_export.py roundtrip \ |
| 37 |
# $HOME/.local/share/orca /tmp/orca-roundtrip |
| 38 |
# |
| 39 |
# |
| 40 |
# Copyright 2026 Igalia, S.L. |
| 41 |
# Author: Joanmarie Diggs <[email protected]> |
| 42 |
# |
| 43 |
# This library is free software; you can redistribute it and/or |
| 44 |
# modify it under the terms of the GNU Lesser General Public |
| 45 |
# License as published by the Free Software Foundation; either |
| 46 |
# version 2.1 of the License, or (at your option) any later version. |
| 47 |
# |
| 48 |
# This library is distributed in the hope that it will be useful, |
| 49 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 50 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 51 |
# Lesser General Public License for more details. |
| 52 |
# |
| 53 |
# You should have received a copy of the GNU Lesser General Public |
| 54 |
# License along with this library; if not, write to the |
| 55 |
# Free Software Foundation, Inc., Franklin Street, Fifth Floor, |
| 56 |
# Boston MA 02110-1301 USA. |
| 57 |
|
| 58 |
# pylint: disable=wrong-import-position |
| 59 |
|
| 60 |
"""Standalone tool for importing/exporting Orca settings between JSON and GSettings.""" |
| 61 |
|
| 62 |
import argparse |
| 63 |
import io |
| 64 |
import json |
| 65 |
import os |
| 66 |
import shutil |
| 67 |
import subprocess |
| 68 |
import sys |
| 69 |
from contextlib import redirect_stdout |
| 70 |
from pathlib import Path |
| 71 |
from typing import Any |
| 72 |
|
| 73 |
from gi.repository import Gio |
| 74 |
|
| 75 |
from generate_gsettings_schemas import _discover_schemas |
| 76 |
|
| 77 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) |
| 78 |
from orca.gsettings_migrator import ( |
| 79 |
KEYBINDINGS_METADATA_KEYS, |
| 80 |
REVERSE_LEGACY_KEY_ALIASES, |
| 81 |
VOICE_FAMILY_FIELDS, |
| 82 |
VOICE_MIGRATION_MAP, |
| 83 |
VOICE_TYPES, |
| 84 |
SettingsMapping, |
| 85 |
add_legacy_aliases, |
| 86 |
apply_legacy_aliases, |
| 87 |
export_keybindings, |
| 88 |
export_pronunciations, |
| 89 |
export_synthesizer, |
| 90 |
export_voice, |
| 91 |
fix_bool_enum_values, |
| 92 |
force_navigation_enabled, |
| 93 |
gsettings_to_json, |
| 94 |
hoist_keybindings_metadata, |
| 95 |
import_keybindings, |
| 96 |
import_pronunciations, |
| 97 |
import_synthesizer, |
| 98 |
import_voice, |
| 99 |
json_to_gsettings, |
| 100 |
populate_per_layout_modifier_keys, |
| 101 |
resolve_enum_nick, |
| 102 |
sanitize_gsettings_path, |
| 103 |
) |
| 104 |
|
| 105 |
GSETTINGS_PATH_PREFIX = "/org/gnome/orca/" |
| 106 |
|
| 107 |
|
| 108 |
# Enum settings where the legacy JSON format used string nicks rather than integers. |
| 109 |
_JSON_STRING_ENUMS: frozenset[str] = frozenset({"capitalizationStyle"}) |
| 110 |
|
| 111 |
|
| 112 |
def _build_schemas_and_mappings() -> tuple[dict[str, str], dict[str, list[SettingsMapping]]]: |
| 113 |
"""Build SCHEMAS and ALL_MAPPINGS from @gsetting decorators via AST parsing.""" |
| 114 |
|
| 115 |
src_dir = Path(__file__).resolve().parent.parent / "src" |
| 116 |
schemas_raw, all_settings, all_enums = _discover_schemas(src_dir) |
| 117 |
|
| 118 |
schemas: dict[str, str] = dict(schemas_raw) |
| 119 |
mappings: dict[str, list[SettingsMapping]] = {} |
| 120 |
|
| 121 |
for setting in all_settings: |
| 122 |
migration_key = setting.get("migration_key") |
| 123 |
if migration_key is None: |
| 124 |
continue |
| 125 |
schema = setting["schema"] |
| 126 |
genum = setting.get("genum") |
| 127 |
enum_map: dict[int, str] | None = None |
| 128 |
string_enum = False |
| 129 |
if genum and genum in all_enums: |
| 130 |
enum_map = {v: k for k, v in all_enums[genum].items()} |
| 131 |
string_enum = migration_key in _JSON_STRING_ENUMS |
| 132 |
gtype = setting.get("gtype", "") |
| 133 |
mapping = SettingsMapping( |
| 134 |
migration_key, setting["key"], gtype, setting["default"], enum_map, string_enum |
| 135 |
) |
| 136 |
mappings.setdefault(schema, []).append(mapping) |
| 137 |
|
| 138 |
return schemas, mappings |
| 139 |
|
| 140 |
|
| 141 |
SCHEMAS, ALL_MAPPINGS = _build_schemas_and_mappings() |
| 142 |
|
| 143 |
|
| 144 |
class SchemaSource: |
| 145 |
"""Loads GSettings schemas and creates Gio.Settings instances.""" |
| 146 |
|
| 147 |
def __init__(self) -> None: |
| 148 |
self._source = Gio.SettingsSchemaSource.get_default() # pylint: disable=no-value-for-parameter |
| 149 |
if self._source is None: |
| 150 |
print( |
| 151 |
"Error: No GSettings schema source found.\nXDG_DATA_DIRS may not be set correctly.", |
| 152 |
file=sys.stderr, |
| 153 |
) |
| 154 |
sys.exit(1) |
| 155 |
self._cache: dict[str, Gio.Settings] = {} |
| 156 |
|
| 157 |
def lookup(self, schema_id: str) -> "Gio.SettingsSchema | None": |
| 158 |
"""Returns the schema for schema_id, or None if not installed.""" |
| 159 |
return self._source.lookup(schema_id, True) |
| 160 |
|
| 161 |
def get_settings(self, schema_id: str, path: str) -> Gio.Settings: |
| 162 |
"""Returns a Gio.Settings for the given schema and path, with caching.""" |
| 163 |
cache_key = f"{schema_id}:{path}" |
| 164 |
if cache_key in self._cache: |
| 165 |
return self._cache[cache_key] |
| 166 |
schema = self._source.lookup(schema_id, True) |
| 167 |
if schema is None: |
| 168 |
print( |
| 169 |
f"Error: {schema_id} not found in the default GSettings schema " |
| 170 |
"directories. \nIf you built Orca with a custom prefix " |
| 171 |
"(e.g. `meson setup -Dprefix=/my/prefix`), re-run with:" |
| 172 |
"\n\n python tools/gsettings_import_export.py --prefix=/my/prefix ..." |
| 173 |
"\n\nNote: This is an experimental and currently unsupported tool.", |
| 174 |
file=sys.stderr, |
| 175 |
) |
| 176 |
sys.exit(1) |
| 177 |
gs = Gio.Settings.new_full(schema, None, path) |
| 178 |
self._cache[cache_key] = gs |
| 179 |
return gs |
| 180 |
|
| 181 |
|
| 182 |
def _build_profile_path(profile: str, suffix: str) -> str: |
| 183 |
return f"{GSETTINGS_PATH_PREFIX}{sanitize_gsettings_path(profile)}/{suffix}/" |
| 184 |
|
| 185 |
|
| 186 |
def _build_app_path(app_name: str, profile: str, suffix: str) -> str: |
| 187 |
profile = sanitize_gsettings_path(profile) |
| 188 |
app = sanitize_gsettings_path(app_name) |
| 189 |
return f"{GSETTINGS_PATH_PREFIX}{profile}/apps/{app}/{suffix}/" |
| 190 |
|
| 191 |
|
| 192 |
def _import_mapped_settings( |
| 193 |
source: SchemaSource, |
| 194 |
schema_name: str, |
| 195 |
path: str, |
| 196 |
json_dict: dict, |
| 197 |
label: str, |
| 198 |
dry_run: bool, |
| 199 |
skip_defaults: bool = True, |
| 200 |
) -> None: |
| 201 |
"""Import mapped settings (speech or typing-echo) for a given path.""" |
| 202 |
mappings = ALL_MAPPINGS.get(schema_name, []) |
| 203 |
if not mappings: |
| 204 |
return |
| 205 |
schema_id = SCHEMAS[schema_name] |
| 206 |
|
| 207 |
if dry_run: |
| 208 |
for m in mappings: |
| 209 |
if m.migration_key not in json_dict: |
| 210 |
continue |
| 211 |
value = json_dict[m.migration_key] |
| 212 |
if m.enum_map is not None: |
| 213 |
nick = resolve_enum_nick(value, m.enum_map) |
| 214 |
if nick is None: |
| 215 |
continue |
| 216 |
if skip_defaults and nick == m.default: |
| 217 |
continue |
| 218 |
print(f" {path}{m.gs_key} = {nick!r}") |
| 219 |
elif not skip_defaults or value != m.default: |
| 220 |
print(f" {path}{m.gs_key} = {value!r}") |
| 221 |
return |
| 222 |
|
| 223 |
gs = source.get_settings(schema_id, path) |
| 224 |
if json_to_gsettings(json_dict, gs, mappings, skip_defaults): |
| 225 |
print(f" Imported {schema_name} for {label}") |
| 226 |
|
| 227 |
|
| 228 |
def _import_synthesizer_for_profile( |
| 229 |
source: SchemaSource, |
| 230 |
profile_prefs: dict, |
| 231 |
profile: str, |
| 232 |
label: str, |
| 233 |
dry_run: bool, |
| 234 |
) -> None: |
| 235 |
"""Import speechServerInfo as speech-server and synthesizer keys.""" |
| 236 |
speech_server_info = profile_prefs.get("speechServerInfo") |
| 237 |
if speech_server_info is None or len(speech_server_info) < 2: |
| 238 |
return |
| 239 |
path = _build_profile_path(profile, "speech") |
| 240 |
|
| 241 |
if dry_run: |
| 242 |
print(f" {path}speech-server = {speech_server_info[0]!r}") |
| 243 |
print(f" {path}synthesizer = {speech_server_info[1]!r}") |
| 244 |
return |
| 245 |
|
| 246 |
gs = source.get_settings(SCHEMAS["speech"], path) |
| 247 |
if import_synthesizer(gs, profile_prefs): |
| 248 |
print( |
| 249 |
f" Imported speech-server={speech_server_info[0]!r}, " |
| 250 |
f"synthesizer={speech_server_info[1]!r} for {label}" |
| 251 |
) |
| 252 |
|
| 253 |
|
| 254 |
def _import_voice_for_path( |
| 255 |
source: SchemaSource, |
| 256 |
voice_data: dict, |
| 257 |
path: str, |
| 258 |
label: str, |
| 259 |
dry_run: bool, |
| 260 |
skip_defaults: bool = True, |
| 261 |
) -> None: |
| 262 |
"""Import ACSS voice data to GSettings.""" |
| 263 |
if dry_run: |
| 264 |
for acss_key, (gs_key, gs_type, default) in VOICE_MIGRATION_MAP.items(): |
| 265 |
if acss_key not in voice_data: |
| 266 |
continue |
| 267 |
value = voice_data[acss_key] |
| 268 |
if skip_defaults: |
| 269 |
if gs_type == "b" and bool(value) == default: |
| 270 |
continue |
| 271 |
if gs_type == "i" and int(value) == default: |
| 272 |
continue |
| 273 |
if gs_type == "d" and float(value) == default: |
| 274 |
continue |
| 275 |
print(f" {path}{gs_key} = {value!r}") |
| 276 |
family = voice_data.get("family", {}) |
| 277 |
if isinstance(family, dict): |
| 278 |
for json_field, gs_key in VOICE_FAMILY_FIELDS.items(): |
| 279 |
val = family.get(json_field) |
| 280 |
if val is not None and str(val): |
| 281 |
print(f" {path}{gs_key} = {str(val)!r}") |
| 282 |
return |
| 283 |
|
| 284 |
gs = source.get_settings(SCHEMAS["voice"], path) |
| 285 |
if import_voice(gs, voice_data, skip_defaults): |
| 286 |
print(f" Imported {label}") |
| 287 |
|
| 288 |
|
| 289 |
def _import_pronunciations_for_path( |
| 290 |
source: SchemaSource, |
| 291 |
pronunciations_dict: dict, |
| 292 |
path: str, |
| 293 |
label: str, |
| 294 |
dry_run: bool, |
| 295 |
) -> None: |
| 296 |
"""Import pronunciation dictionary to GSettings.""" |
| 297 |
if dry_run: |
| 298 |
converted: dict[str, str] = {} |
| 299 |
for key, value in pronunciations_dict.items(): |
| 300 |
if isinstance(value, list) and len(value) >= 2: |
| 301 |
converted[key] = value[1] |
| 302 |
elif isinstance(value, list) and len(value) == 1: |
| 303 |
converted[key] = value[0] |
| 304 |
elif isinstance(value, str): |
| 305 |
converted[key] = value |
| 306 |
if converted: |
| 307 |
print(f" {path}entries = {converted!r}") |
| 308 |
return |
| 309 |
|
| 310 |
gs = source.get_settings(SCHEMAS["pronunciations"], path) |
| 311 |
if import_pronunciations(gs, pronunciations_dict): |
| 312 |
print(f" Imported pronunciations for {label}") |
| 313 |
|
| 314 |
|
| 315 |
def _import_keybindings_for_path( |
| 316 |
source: SchemaSource, |
| 317 |
keybindings_dict: dict, |
| 318 |
path: str, |
| 319 |
label: str, |
| 320 |
dry_run: bool, |
| 321 |
) -> None: |
| 322 |
"""Import keybinding overrides to GSettings.""" |
| 323 |
if dry_run: |
| 324 |
converted: dict[str, list[list[str]]] = {} |
| 325 |
for key, value in keybindings_dict.items(): |
| 326 |
if key in KEYBINDINGS_METADATA_KEYS: |
| 327 |
continue |
| 328 |
if isinstance(value, list): |
| 329 |
bindings = [ |
| 330 |
[str(v) for v in binding] for binding in value if isinstance(binding, list) |
| 331 |
] |
| 332 |
converted[key] = bindings |
| 333 |
if not converted: |
| 334 |
return |
| 335 |
for cmd, cmd_bindings in sorted(converted.items()): |
| 336 |
if not cmd_bindings: |
| 337 |
print(f" {path}entries[{cmd}] = [] (unbound)") |
| 338 |
else: |
| 339 |
for b in cmd_bindings: |
| 340 |
print(f" {path}entries[{cmd}] = {b}") |
| 341 |
return |
| 342 |
|
| 343 |
gs = source.get_settings(SCHEMAS["keybindings"], path) |
| 344 |
if import_keybindings(gs, keybindings_dict): |
| 345 |
print(f" Imported keybindings for {label}") |
| 346 |
|
| 347 |
|
| 348 |
def _write_metadata( |
| 349 |
source: SchemaSource, |
| 350 |
path: str, |
| 351 |
display_name: str, |
| 352 |
internal_name: str, |
| 353 |
label: str, |
| 354 |
dry_run: bool, |
| 355 |
) -> None: |
| 356 |
"""Write display-name and internal-name to the metadata schema at the given path.""" |
| 357 |
if dry_run: |
| 358 |
print(f" {path}display-name = {display_name!r}") |
| 359 |
if internal_name: |
| 360 |
print(f" {path}internal-name = {internal_name!r}") |
| 361 |
return |
| 362 |
gs = source.get_settings(SCHEMAS["metadata"], path) |
| 363 |
gs.set_string("display-name", display_name) |
| 364 |
if internal_name: |
| 365 |
gs.set_string("internal-name", internal_name) |
| 366 |
print(f" Stored metadata for {label}") |
| 367 |
|
| 368 |
|
| 369 |
def _import_per_layout_modifier_keys( |
| 370 |
source: SchemaSource, |
| 371 |
profile_prefs: dict, |
| 372 |
profile: str, |
| 373 |
label: str, |
| 374 |
dry_run: bool, |
| 375 |
skip_defaults: bool = True, |
| 376 |
app_name: str = "", |
| 377 |
) -> None: |
| 378 |
"""Import keyboard-layout and per-layout modifier keys from keybinding metadata.""" |
| 379 |
if dry_run: |
| 380 |
layout = profile_prefs.get("keyboardLayout", 1) |
| 381 |
nick = "desktop" if layout == 1 else "laptop" |
| 382 |
modifier_keys = profile_prefs.get("orcaModifierKeys") |
| 383 |
if not skip_defaults or nick != "desktop": |
| 384 |
path = ( |
| 385 |
_build_app_path(app_name, profile, "keybindings") |
| 386 |
if app_name |
| 387 |
else _build_profile_path(profile, "keybindings") |
| 388 |
) |
| 389 |
print(f" {path}keyboard-layout = {nick!r}") |
| 390 |
if modifier_keys is not None: |
| 391 |
key = "desktop-modifier-keys" if layout == 1 else "laptop-modifier-keys" |
| 392 |
path = ( |
| 393 |
_build_app_path(app_name, profile, "keybindings") |
| 394 |
if app_name |
| 395 |
else _build_profile_path(profile, "keybindings") |
| 396 |
) |
| 397 |
print(f" {path}{key} = {modifier_keys!r}") |
| 398 |
return |
| 399 |
|
| 400 |
if app_name: |
| 401 |
path = _build_app_path(app_name, profile, "keybindings") |
| 402 |
else: |
| 403 |
path = _build_profile_path(profile, "keybindings") |
| 404 |
gs = source.get_settings(SCHEMAS["keybindings"], path) |
| 405 |
if populate_per_layout_modifier_keys(gs, profile_prefs, skip_defaults): |
| 406 |
print(f" Imported per-layout modifier keys for {label}") |
| 407 |
|
| 408 |
|
| 409 |
def _import_profile( |
| 410 |
source: SchemaSource, |
| 411 |
profile_name: str, |
| 412 |
profile_prefs: dict, |
| 413 |
dry_run: bool, |
| 414 |
) -> None: |
| 415 |
"""Import all settings for a single profile.""" |
| 416 |
apply_legacy_aliases(profile_prefs) |
| 417 |
force_navigation_enabled(profile_prefs) |
| 418 |
fix_bool_enum_values(profile_prefs) |
| 419 |
hoist_keybindings_metadata(profile_prefs) |
| 420 |
profile = sanitize_gsettings_path(profile_name) |
| 421 |
skip_defaults = profile_name == "default" |
| 422 |
|
| 423 |
for schema_name in ALL_MAPPINGS: |
| 424 |
path = _build_profile_path(profile, schema_name) |
| 425 |
_import_mapped_settings( |
| 426 |
source, |
| 427 |
schema_name, |
| 428 |
path, |
| 429 |
profile_prefs, |
| 430 |
f"profile:{profile_name}", |
| 431 |
dry_run, |
| 432 |
skip_defaults=skip_defaults, |
| 433 |
) |
| 434 |
|
| 435 |
_import_synthesizer_for_profile( |
| 436 |
source, profile_prefs, profile, f"profile:{profile_name}", dry_run |
| 437 |
) |
| 438 |
|
| 439 |
voices = profile_prefs.get("voices", {}) |
| 440 |
for voice_type in VOICE_TYPES: |
| 441 |
voice_data = voices.get(voice_type, {}) |
| 442 |
if not voice_data: |
| 443 |
continue |
| 444 |
vt = sanitize_gsettings_path(voice_type) |
| 445 |
path = _build_profile_path(profile, f"voices/{vt}") |
| 446 |
_import_voice_for_path( |
| 447 |
source, |
| 448 |
voice_data, |
| 449 |
path, |
| 450 |
f"voice:{voice_type}/profile:{profile_name}", |
| 451 |
dry_run, |
| 452 |
skip_defaults=skip_defaults, |
| 453 |
) |
| 454 |
|
| 455 |
pronunciations = profile_prefs.get("pronunciations", {}) |
| 456 |
if pronunciations: |
| 457 |
path = _build_profile_path(profile, "pronunciations") |
| 458 |
_import_pronunciations_for_path( |
| 459 |
source, pronunciations, path, f"profile:{profile_name}", dry_run |
| 460 |
) |
| 461 |
|
| 462 |
keybindings_data = profile_prefs.get("keybindings", {}) |
| 463 |
if keybindings_data: |
| 464 |
path = _build_profile_path(profile, "keybindings") |
| 465 |
_import_keybindings_for_path( |
| 466 |
source, keybindings_data, path, f"profile:{profile_name}", dry_run |
| 467 |
) |
| 468 |
|
| 469 |
_import_per_layout_modifier_keys( |
| 470 |
source, profile_prefs, profile, f"profile:{profile_name}", dry_run, skip_defaults |
| 471 |
) |
| 472 |
|
| 473 |
profile_label = profile_prefs.get("profile", [profile_name])[0] |
| 474 |
metadata_path = _build_profile_path(profile, "metadata") |
| 475 |
_write_metadata( |
| 476 |
source, metadata_path, profile_label, profile_name, f"profile:{profile_name}", dry_run |
| 477 |
) |
| 478 |
|
| 479 |
|
| 480 |
def _import_app( |
| 481 |
source: SchemaSource, |
| 482 |
app_name: str, |
| 483 |
app_filepath: str, |
| 484 |
dry_run: bool, |
| 485 |
) -> None: |
| 486 |
"""Import all settings for a single app override file.""" |
| 487 |
try: |
| 488 |
with open(app_filepath, encoding="utf-8") as f: |
| 489 |
prefs = json.load(f) |
| 490 |
except (OSError, json.JSONDecodeError) as e: |
| 491 |
print(f" Warning: Could not read {app_filepath}: {e}", file=sys.stderr) |
| 492 |
return |
| 493 |
|
| 494 |
for profile_name, profile_data in prefs.get("profiles", {}).items(): |
| 495 |
general = profile_data.get("general", {}) |
| 496 |
apply_legacy_aliases(general) |
| 497 |
force_navigation_enabled(general) |
| 498 |
fix_bool_enum_values(general) |
| 499 |
pronunciations = profile_data.get("pronunciations", {}) |
| 500 |
app_keybindings = profile_data.get("keybindings", {}) |
| 501 |
if not general and not pronunciations and not app_keybindings: |
| 502 |
continue |
| 503 |
label = f"profile:{profile_name}/app:{app_name}" |
| 504 |
|
| 505 |
for schema_name in ALL_MAPPINGS: |
| 506 |
path = _build_app_path(app_name, profile_name, schema_name) |
| 507 |
_import_mapped_settings( |
| 508 |
source, schema_name, path, general, label, dry_run, skip_defaults=False |
| 509 |
) |
| 510 |
|
| 511 |
voices = general.get("voices", {}) |
| 512 |
for voice_type in VOICE_TYPES: |
| 513 |
voice_data = voices.get(voice_type, {}) |
| 514 |
if not voice_data: |
| 515 |
continue |
| 516 |
vt = sanitize_gsettings_path(voice_type) |
| 517 |
path = _build_app_path(app_name, profile_name, f"voices/{vt}") |
| 518 |
_import_voice_for_path( |
| 519 |
source, |
| 520 |
voice_data, |
| 521 |
path, |
| 522 |
f"voice:{voice_type}/{label}", |
| 523 |
dry_run, |
| 524 |
skip_defaults=False, |
| 525 |
) |
| 526 |
|
| 527 |
if pronunciations: |
| 528 |
path = _build_app_path(app_name, profile_name, "pronunciations") |
| 529 |
_import_pronunciations_for_path(source, pronunciations, path, label, dry_run) |
| 530 |
|
| 531 |
if app_keybindings: |
| 532 |
path = _build_app_path(app_name, profile_name, "keybindings") |
| 533 |
_import_keybindings_for_path(source, app_keybindings, path, label, dry_run) |
| 534 |
|
| 535 |
_import_per_layout_modifier_keys( |
| 536 |
source, |
| 537 |
general, |
| 538 |
sanitize_gsettings_path(profile_name), |
| 539 |
label, |
| 540 |
dry_run, |
| 541 |
skip_defaults=False, |
| 542 |
app_name=app_name, |
| 543 |
) |
| 544 |
|
| 545 |
metadata_path = _build_app_path(app_name, profile_name, "metadata") |
| 546 |
_write_metadata(source, metadata_path, app_name, profile_name, label, dry_run) |
| 547 |
|
| 548 |
profile = sanitize_gsettings_path(profile_name) |
| 549 |
profile_metadata_path = _build_profile_path(profile, "metadata") |
| 550 |
if dry_run: |
| 551 |
print(f" {profile_metadata_path}internal-name = {profile_name!r} (if not set)") |
| 552 |
else: |
| 553 |
gs = source.get_settings(SCHEMAS["metadata"], profile_metadata_path) |
| 554 |
if gs.get_user_value("internal-name") is None: |
| 555 |
gs.set_string("internal-name", profile_name) |
| 556 |
|
| 557 |
|
| 558 |
def _get_dict_entries(source: SchemaSource, schema_name: str, profile: str, app_name: str) -> dict: |
| 559 |
"""Read dict entries (keybindings or pronunciations) from a single dconf layer.""" |
| 560 |
|
| 561 |
if app_name: |
| 562 |
path = _build_app_path(app_name, profile, schema_name) |
| 563 |
else: |
| 564 |
path = _build_profile_path(profile, schema_name) |
| 565 |
gs = source.get_settings(SCHEMAS[schema_name], path) |
| 566 |
user_value = gs.get_user_value("entries") |
| 567 |
if user_value is None: |
| 568 |
return {} |
| 569 |
return user_value.unpack() |
| 570 |
|
| 571 |
|
| 572 |
def _strip_inherited_dict_entries( |
| 573 |
source: SchemaSource, |
| 574 |
settings_dir: str, |
| 575 |
profile_names: list[str], |
| 576 |
) -> None: |
| 577 |
"""After import, strip dict entries that duplicate their parent layer.""" |
| 578 |
|
| 579 |
for schema_name in ("keybindings", "pronunciations"): |
| 580 |
if schema_name not in SCHEMAS: |
| 581 |
continue |
| 582 |
|
| 583 |
default_entries = _get_dict_entries(source, schema_name, "default", "") |
| 584 |
|
| 585 |
for profile_name in profile_names: |
| 586 |
if profile_name == "default": |
| 587 |
continue |
| 588 |
profile = sanitize_gsettings_path(profile_name) |
| 589 |
entries = _get_dict_entries(source, schema_name, profile, "") |
| 590 |
if not entries: |
| 591 |
continue |
| 592 |
diff = {k: v for k, v in entries.items() if default_entries.get(k) != v} |
| 593 |
if len(diff) == len(entries): |
| 594 |
continue |
| 595 |
path = _build_profile_path(profile, schema_name) |
| 596 |
gs = source.get_settings(SCHEMAS[schema_name], path) |
| 597 |
if not diff: |
| 598 |
gs.reset("entries") |
| 599 |
elif schema_name == "keybindings": |
| 600 |
import_keybindings(gs, diff) |
| 601 |
else: |
| 602 |
import_pronunciations(gs, diff) |
| 603 |
print(f" Stripped {schema_name} for {profile_name}: {len(entries)} -> {len(diff)}") |
| 604 |
|
| 605 |
app_dir = os.path.join(settings_dir, "app-settings") |
| 606 |
if not os.path.isdir(app_dir): |
| 607 |
continue |
| 608 |
for filename in sorted(os.listdir(app_dir)): |
| 609 |
if not filename.endswith(".conf"): |
| 610 |
continue |
| 611 |
app_name = filename[:-5] |
| 612 |
try: |
| 613 |
with open(os.path.join(app_dir, filename), encoding="utf-8") as f: |
| 614 |
app_prefs = json.load(f) |
| 615 |
except (OSError, json.JSONDecodeError): |
| 616 |
continue |
| 617 |
for profile_name in app_prefs.get("profiles", {}): |
| 618 |
profile = sanitize_gsettings_path(profile_name) |
| 619 |
parent = dict(default_entries) |
| 620 |
if profile_name != "default": |
| 621 |
parent |= _get_dict_entries(source, schema_name, profile, "") |
| 622 |
entries = _get_dict_entries(source, schema_name, profile, app_name) |
| 623 |
if not entries: |
| 624 |
continue |
| 625 |
diff = {k: v for k, v in entries.items() if parent.get(k) != v} |
| 626 |
if len(diff) == len(entries): |
| 627 |
continue |
| 628 |
path = _build_app_path(app_name, profile, schema_name) |
| 629 |
gs = source.get_settings(SCHEMAS[schema_name], path) |
| 630 |
if not diff: |
| 631 |
gs.reset("entries") |
| 632 |
elif schema_name == "keybindings": |
| 633 |
import_keybindings(gs, diff) |
| 634 |
else: |
| 635 |
import_pronunciations(gs, diff) |
| 636 |
target = f"{profile_name}/{app_name}" |
| 637 |
print(f" Stripped {schema_name} for {target}: {len(entries)} -> {len(diff)}") |
| 638 |
|
| 639 |
|
| 640 |
def import_settings(settings_dir: str, source: SchemaSource, dry_run: bool = False) -> None: |
| 641 |
"""Import JSON settings into GSettings/dconf additively (overlay, no dconf reset first).""" |
| 642 |
settings_file = os.path.join(settings_dir, "user-settings.conf") |
| 643 |
if not os.path.isfile(settings_file): |
| 644 |
print(f"Error: {settings_file} not found", file=sys.stderr) |
| 645 |
sys.exit(1) |
| 646 |
|
| 647 |
with open(settings_file, encoding="utf-8") as f: |
| 648 |
prefs = json.load(f) |
| 649 |
|
| 650 |
profiles = prefs.get("profiles", {}) |
| 651 |
if not profiles: |
| 652 |
print("No profiles found in settings file.", file=sys.stderr) |
| 653 |
return |
| 654 |
|
| 655 |
for profile_name, profile_data in profiles.items(): |
| 656 |
print(f"Profile: {profile_name}") |
| 657 |
_import_profile(source, profile_name, profile_data, dry_run) |
| 658 |
|
| 659 |
app_dir = os.path.join(settings_dir, "app-settings") |
| 660 |
if os.path.isdir(app_dir): |
| 661 |
for filename in sorted(os.listdir(app_dir)): |
| 662 |
if not filename.endswith(".conf"): |
| 663 |
continue |
| 664 |
app_name = filename[:-5] |
| 665 |
print(f"App: {app_name}") |
| 666 |
_import_app(source, app_name, os.path.join(app_dir, filename), dry_run) |
| 667 |
|
| 668 |
if not dry_run: |
| 669 |
_strip_inherited_dict_entries(source, settings_dir, list(profiles.keys())) |
| 670 |
|
| 671 |
|
| 672 |
def _export_profile(source: SchemaSource, profile_name: str) -> dict: |
| 673 |
"""Export all settings for a profile from dconf to a JSON-compatible dict.""" |
| 674 |
profile_data: dict[str, Any] = {} |
| 675 |
profile = sanitize_gsettings_path(profile_name) |
| 676 |
|
| 677 |
# Mapped settings (speech, typing-echo, caret-navigation, etc.) |
| 678 |
for schema_name, mappings in ALL_MAPPINGS.items(): |
| 679 |
try: |
| 680 |
path = _build_profile_path(profile, schema_name) |
| 681 |
gs = source.get_settings(SCHEMAS[schema_name], path) |
| 682 |
profile_data.update(gsettings_to_json(gs, mappings)) |
| 683 |
except ValueError: |
| 684 |
pass |
| 685 |
|
| 686 |
try: |
| 687 |
path = _build_profile_path(profile, "speech") |
| 688 |
gs = source.get_settings(SCHEMAS["speech"], path) |
| 689 |
synth_result = export_synthesizer(gs) |
| 690 |
if synth_result is not None: |
| 691 |
profile_data["speechServerInfo"] = list(synth_result) |
| 692 |
except ValueError: |
| 693 |
pass |
| 694 |
|
| 695 |
# Voice settings |
| 696 |
voices: dict[str, Any] = {} |
| 697 |
for voice_type in VOICE_TYPES: |
| 698 |
try: |
| 699 |
vt = sanitize_gsettings_path(voice_type) |
| 700 |
path = _build_profile_path(profile, f"voices/{vt}") |
| 701 |
gs = source.get_settings(SCHEMAS["voice"], path) |
| 702 |
voice_data = export_voice(gs) |
| 703 |
if voice_data: |
| 704 |
voices[voice_type] = voice_data |
| 705 |
except ValueError: |
| 706 |
pass |
| 707 |
if voices: |
| 708 |
profile_data["voices"] = voices |
| 709 |
|
| 710 |
# Pronunciations |
| 711 |
try: |
| 712 |
path = _build_profile_path(profile, "pronunciations") |
| 713 |
gs = source.get_settings(SCHEMAS["pronunciations"], path) |
| 714 |
pronunciations = export_pronunciations(gs) |
| 715 |
if pronunciations: |
| 716 |
profile_data["pronunciations"] = pronunciations |
| 717 |
except ValueError: |
| 718 |
pass |
| 719 |
|
| 720 |
# Keybindings |
| 721 |
try: |
| 722 |
path = _build_profile_path(profile, "keybindings") |
| 723 |
gs = source.get_settings(SCHEMAS["keybindings"], path) |
| 724 |
kb = export_keybindings(gs) |
| 725 |
if kb: |
| 726 |
profile_data["keybindings"] = kb |
| 727 |
except ValueError: |
| 728 |
pass |
| 729 |
|
| 730 |
add_legacy_aliases(profile_data) |
| 731 |
return profile_data |
| 732 |
|
| 733 |
|
| 734 |
def _dconf_list(path: str) -> list[str]: |
| 735 |
"""List dconf entries under a path. Returns empty list on failure.""" |
| 736 |
try: |
| 737 |
output = subprocess.check_output(["dconf", "list", path], text=True) |
| 738 |
return [e.strip("/") for e in output.strip().split("\n") if e.strip()] |
| 739 |
except (subprocess.CalledProcessError, FileNotFoundError): |
| 740 |
return [] |
| 741 |
|
| 742 |
|
| 743 |
def _export_apps( |
| 744 |
source: SchemaSource, |
| 745 |
profile_name: str, |
| 746 |
output_dir: str, |
| 747 |
original_profile_name: str = "", |
| 748 |
) -> None: |
| 749 |
"""Export app-specific settings for a profile.""" |
| 750 |
profile = sanitize_gsettings_path(profile_name) |
| 751 |
original_profile_name = original_profile_name or profile_name |
| 752 |
apps_prefix = f"{GSETTINGS_PATH_PREFIX}{profile}/apps/" |
| 753 |
app_entries = _dconf_list(apps_prefix) |
| 754 |
if not app_entries: |
| 755 |
return |
| 756 |
|
| 757 |
app_settings_dir = os.path.join(output_dir, "app-settings") |
| 758 |
os.makedirs(app_settings_dir, exist_ok=True) |
| 759 |
|
| 760 |
for sanitized_app in app_entries: |
| 761 |
metadata_path = _build_app_path(sanitized_app, profile, "metadata") |
| 762 |
app_display_name, _ = _read_metadata(source, metadata_path) |
| 763 |
original_app_name = app_display_name or sanitized_app |
| 764 |
|
| 765 |
app_data: dict[str, Any] = {} |
| 766 |
|
| 767 |
for schema_name, mappings in ALL_MAPPINGS.items(): |
| 768 |
try: |
| 769 |
path = _build_app_path(sanitized_app, profile, schema_name) |
| 770 |
gs = source.get_settings(SCHEMAS[schema_name], path) |
| 771 |
app_data.update(gsettings_to_json(gs, mappings)) |
| 772 |
except ValueError: |
| 773 |
pass |
| 774 |
|
| 775 |
try: |
| 776 |
path = _build_app_path(sanitized_app, profile, "speech") |
| 777 |
gs = source.get_settings(SCHEMAS["speech"], path) |
| 778 |
synth_result = export_synthesizer(gs) |
| 779 |
if synth_result is not None: |
| 780 |
app_data["speechServerInfo"] = list(synth_result) |
| 781 |
except ValueError: |
| 782 |
pass |
| 783 |
|
| 784 |
voices: dict[str, Any] = {} |
| 785 |
for voice_type in VOICE_TYPES: |
| 786 |
try: |
| 787 |
vt = sanitize_gsettings_path(voice_type) |
| 788 |
path = _build_app_path(sanitized_app, profile, f"voices/{vt}") |
| 789 |
gs = source.get_settings(SCHEMAS["voice"], path) |
| 790 |
voice_data = export_voice(gs) |
| 791 |
if voice_data: |
| 792 |
voices[voice_type] = voice_data |
| 793 |
except ValueError: |
| 794 |
pass |
| 795 |
if voices: |
| 796 |
app_data["voices"] = voices |
| 797 |
|
| 798 |
app_pronunciations: dict[str, list[str]] = {} |
| 799 |
try: |
| 800 |
path = _build_app_path(sanitized_app, profile, "pronunciations") |
| 801 |
gs = source.get_settings(SCHEMAS["pronunciations"], path) |
| 802 |
app_pronunciations = export_pronunciations(gs) |
| 803 |
except ValueError: |
| 804 |
pass |
| 805 |
|
| 806 |
app_kb: dict = {} |
| 807 |
try: |
| 808 |
path = _build_app_path(sanitized_app, profile, "keybindings") |
| 809 |
gs = source.get_settings(SCHEMAS["keybindings"], path) |
| 810 |
app_kb = export_keybindings(gs) |
| 811 |
except ValueError: |
| 812 |
pass |
| 813 |
|
| 814 |
if not app_data and not app_pronunciations and not app_kb: |
| 815 |
continue |
| 816 |
|
| 817 |
filepath = os.path.join(app_settings_dir, f"{original_app_name}.conf") |
| 818 |
if os.path.isfile(filepath): |
| 819 |
with open(filepath, encoding="utf-8") as f: |
| 820 |
existing = json.load(f) |
| 821 |
else: |
| 822 |
existing = {"profiles": {}} |
| 823 |
add_legacy_aliases(app_data) |
| 824 |
profile_entry: dict[str, Any] = {"general": app_data} |
| 825 |
if app_pronunciations: |
| 826 |
profile_entry["pronunciations"] = app_pronunciations |
| 827 |
if app_kb: |
| 828 |
profile_entry["keybindings"] = app_kb |
| 829 |
existing.setdefault("profiles", {})[original_profile_name] = profile_entry |
| 830 |
with open(filepath, "w", encoding="utf-8") as f: |
| 831 |
json.dump(existing, f, indent=4) |
| 832 |
print(f" Exported app:{original_app_name}/profile:{profile_name}") |
| 833 |
|
| 834 |
|
| 835 |
def _read_metadata(source: SchemaSource, path: str) -> tuple[str, str]: |
| 836 |
"""Read display-name and internal-name from metadata. Returns ("", "") if not set.""" |
| 837 |
display_name = "" |
| 838 |
internal_name = "" |
| 839 |
try: |
| 840 |
gs = source.get_settings(SCHEMAS["metadata"], path) |
| 841 |
user_value = gs.get_user_value("display-name") |
| 842 |
if user_value is not None: |
| 843 |
display_name = user_value.get_string() |
| 844 |
user_value = gs.get_user_value("internal-name") |
| 845 |
if user_value is not None: |
| 846 |
internal_name = user_value.get_string() |
| 847 |
except ValueError: |
| 848 |
pass |
| 849 |
return display_name, internal_name |
| 850 |
|
| 851 |
|
| 852 |
def export_settings(source: SchemaSource, output_dir: str) -> None: |
| 853 |
"""Export GSettings/dconf settings to JSON format.""" |
| 854 |
entries = _dconf_list(GSETTINGS_PATH_PREFIX) |
| 855 |
if not entries: |
| 856 |
print("No Orca settings found in dconf.", file=sys.stderr) |
| 857 |
return |
| 858 |
|
| 859 |
result: dict[str, Any] = {"profiles": {}} |
| 860 |
profile_name_map: dict[str, str] = {} |
| 861 |
|
| 862 |
for sanitized_name in entries: |
| 863 |
metadata_path = _build_profile_path(sanitized_name, "metadata") |
| 864 |
display_name, internal_name = _read_metadata(source, metadata_path) |
| 865 |
profile_key = internal_name or sanitized_name |
| 866 |
profile_name_map[sanitized_name] = profile_key |
| 867 |
|
| 868 |
profile_data = _export_profile(source, sanitized_name) |
| 869 |
if profile_data: |
| 870 |
profile_label = display_name or profile_key.replace("-", " ").title() |
| 871 |
profile_data["profile"] = [profile_label, profile_key] |
| 872 |
result["profiles"][profile_key] = profile_data |
| 873 |
print(f" Exported profile:{profile_key}") |
| 874 |
|
| 875 |
output_file = os.path.join(output_dir, "user-settings.conf") |
| 876 |
with open(output_file, "w", encoding="utf-8") as f: |
| 877 |
json.dump(result, f, indent=4) |
| 878 |
print(f"Wrote {output_file}") |
| 879 |
|
| 880 |
for sanitized_name in entries: |
| 881 |
original_name = profile_name_map.get(sanitized_name, sanitized_name) |
| 882 |
_export_apps(source, sanitized_name, output_dir, original_name) |
| 883 |
|
| 884 |
|
| 885 |
_LEGACY_ROOT_KEYS = {"general", "keybindings", "pronunciations", "startingProfile"} |
| 886 |
|
| 887 |
_KNOWN_UNMIGRATED_KEYS: set[str] = { |
| 888 |
"doubleClickTimeout", |
| 889 |
"enableExperimentalFeatures", |
| 890 |
"enableSadPidginHack", |
| 891 |
"playSoundForPositionInSet", |
| 892 |
"playSoundForRole", |
| 893 |
"playSoundForState", |
| 894 |
"playSoundForValue", |
| 895 |
"useGSettings", |
| 896 |
} |
| 897 |
|
| 898 |
_LEGACY_CONSTANT_KEYS: set[str] = { |
| 899 |
"caretNavigationEnabled", |
| 900 |
"structuralNavigationEnabled", |
| 901 |
} |
| 902 |
|
| 903 |
_LEGACY_ALIAS_KEYS = {"progressBarVerbosity", "progressBarUpdateInterval"} |
| 904 |
|
| 905 |
_BOOL_ENUM_FIXES: dict[str, dict[bool, int]] = { |
| 906 |
"findResultsVerbosity": {True: 2, False: 2}, |
| 907 |
} |
| 908 |
|
| 909 |
|
| 910 |
def _build_default_info() -> dict[str, tuple[Any, dict[int, str] | None]]: |
| 911 |
"""Build a map of migration_key → (default_value, enum_map) from all known mappings.""" |
| 912 |
defaults: dict[str, tuple[Any, dict[int, str] | None]] = {} |
| 913 |
for mappings in ALL_MAPPINGS.values(): |
| 914 |
for m in mappings: |
| 915 |
defaults[m.migration_key] = (m.default, m.enum_map) |
| 916 |
return defaults |
| 917 |
|
| 918 |
|
| 919 |
_DEFAULT_INFO: dict[str, tuple[Any, dict[int, str] | None]] = {} |
| 920 |
|
| 921 |
|
| 922 |
def _get_default_info() -> dict[str, tuple[Any, dict[int, str] | None]]: |
| 923 |
"""Lazily build and cache the defaults map.""" |
| 924 |
if not _DEFAULT_INFO: |
| 925 |
_DEFAULT_INFO.update(_build_default_info()) |
| 926 |
return _DEFAULT_INFO |
| 927 |
|
| 928 |
|
| 929 |
def _diff_dicts( |
| 930 |
original: Any, |
| 931 |
exported: Any, |
| 932 |
path: str = "", |
| 933 |
diffs: list[tuple[str, str, Any]] | None = None, |
| 934 |
) -> list[tuple[str, str, Any]]: |
| 935 |
"""Recursively compare two dicts/values. Returns list of (kind, path, original_value).""" |
| 936 |
if diffs is None: |
| 937 |
diffs = [] |
| 938 |
if isinstance(original, dict) and isinstance(exported, dict): |
| 939 |
all_keys = sorted(set(original) | set(exported)) |
| 940 |
for key in all_keys: |
| 941 |
child_path = f"{path}.{key}" if path else key |
| 942 |
if key not in exported: |
| 943 |
diffs.append(("removed", child_path, original[key])) |
| 944 |
elif key not in original: |
| 945 |
diffs.append(("added", child_path, exported[key])) |
| 946 |
else: |
| 947 |
_diff_dicts(original[key], exported[key], child_path, diffs) |
| 948 |
elif original != exported: |
| 949 |
diffs.append(("changed", path, (original, exported))) |
| 950 |
return diffs |
| 951 |
|
| 952 |
|
| 953 |
def _is_default_voice_entry(value: Any) -> bool: |
| 954 |
"""Return True if value is a voice dict containing only default values.""" |
| 955 |
if not isinstance(value, dict): |
| 956 |
return False |
| 957 |
for key, val in value.items(): |
| 958 |
if key == "established" and val is False: |
| 959 |
continue |
| 960 |
return False |
| 961 |
return True |
| 962 |
|
| 963 |
|
| 964 |
_VOICE_FAMILY_FIELD_NAMES = frozenset(VOICE_FAMILY_FIELDS.keys()) |
| 965 |
|
| 966 |
|
| 967 |
def _classify_diff(kind: str, path: str, value: Any) -> str: |
| 968 |
"""Classify a diff item into a known category, or return empty string for unexpected.""" |
| 969 |
parts = path.split(".") |
| 970 |
if parts[0] in _LEGACY_ROOT_KEYS: |
| 971 |
return "legacy_root" |
| 972 |
if parts[-1] in _KNOWN_UNMIGRATED_KEYS: |
| 973 |
return "unmigrated" |
| 974 |
if parts[-1] in _LEGACY_CONSTANT_KEYS: |
| 975 |
return "legacy_constant" |
| 976 |
if parts[-1] in _LEGACY_ALIAS_KEYS: |
| 977 |
return "legacy_alias" |
| 978 |
if parts[-1] in REVERSE_LEGACY_KEY_ALIASES: |
| 979 |
return "legacy_alias" |
| 980 |
if ( |
| 981 |
kind == "removed" |
| 982 |
and ".voices." in path |
| 983 |
and parts[-1] in _VOICE_FAMILY_FIELD_NAMES |
| 984 |
and (value is None or value == "") |
| 985 |
): |
| 986 |
return "null_voice_field" |
| 987 |
if kind == "removed" and ".voices." in path and _is_default_voice_entry(value): |
| 988 |
return "default_voice" |
| 989 |
if kind == "removed": |
| 990 |
leaf = parts[-1] |
| 991 |
if leaf in ("pronunciations", "keybindings") and isinstance(value, dict) and not value: |
| 992 |
return "empty_dict" |
| 993 |
if leaf in ("pronunciations", "keybindings") and isinstance(value, dict): |
| 994 |
if _is_stripped_inherited_dict(parts): |
| 995 |
return "stripped_inherited" |
| 996 |
if _is_stripped_inherited_entry(parts): |
| 997 |
return "stripped_inherited" |
| 998 |
info = _get_default_info() |
| 999 |
if leaf in info: |
| 1000 |
default, enum_map = info[leaf] |
| 1001 |
if _values_match_default(value, default, enum_map): |
| 1002 |
return "default_value" |
| 1003 |
if leaf in _BOOL_ENUM_FIXES and isinstance(value, bool): |
| 1004 |
converted = _BOOL_ENUM_FIXES[leaf].get(value) |
| 1005 |
if converted is not None and _values_match_default(converted, default, enum_map): |
| 1006 |
return "bool_enum_fix" |
| 1007 |
if leaf in KEYBINDINGS_METADATA_KEYS: |
| 1008 |
return "hoisted_metadata" |
| 1009 |
if _is_empty_synthesizer(leaf, value): |
| 1010 |
return "default_value" |
| 1011 |
if kind == "added" and parts[-1] in KEYBINDINGS_METADATA_KEYS: |
| 1012 |
return "hoisted_metadata" |
| 1013 |
if kind == "changed" and _is_bool_enum_fix(parts[-1], value): |
| 1014 |
return "bool_enum_fix" |
| 1015 |
return "" |
| 1016 |
|
| 1017 |
|
| 1018 |
def _is_hoisted_keybinding_metadata(parts: list[str]) -> bool: |
| 1019 |
"""Return True if this is a keyboardLayout/orcaModifierKeys inside a keybindings dict.""" |
| 1020 |
return len(parts) >= 3 and parts[-2] == "keybindings" |
| 1021 |
|
| 1022 |
|
| 1023 |
def _is_stripped_inherited_dict(parts: list[str]) -> bool: |
| 1024 |
"""Return True if this is a keybindings/pronunciations dict on a non-default profile.""" |
| 1025 |
if len(parts) < 2 or parts[0] != "profiles": |
| 1026 |
return False |
| 1027 |
profile = parts[1] |
| 1028 |
if profile == "default": |
| 1029 |
return _has_app_context(parts) |
| 1030 |
return True |
| 1031 |
|
| 1032 |
|
| 1033 |
def _is_stripped_inherited_entry(parts: list[str]) -> bool: |
| 1034 |
"""Return True if this is an individual entry under a stripped keybindings/pronunciations.""" |
| 1035 |
if len(parts) < 3 or parts[0] != "profiles": |
| 1036 |
return False |
| 1037 |
profile = parts[1] |
| 1038 |
parent = _find_dict_parent(parts) |
| 1039 |
if parent not in ("keybindings", "pronunciations"): |
| 1040 |
return False |
| 1041 |
if profile == "default": |
| 1042 |
return _has_app_context(parts) |
| 1043 |
return True |
| 1044 |
|
| 1045 |
|
| 1046 |
def _has_app_context(parts: list[str]) -> bool: |
| 1047 |
"""Return True if the path has an app-specific segment.""" |
| 1048 |
return "apps" in parts |
| 1049 |
|
| 1050 |
|
| 1051 |
def _find_dict_parent(parts: list[str]) -> str: |
| 1052 |
"""Find the keybindings/pronunciations ancestor in a path, or empty string.""" |
| 1053 |
for part in parts: |
| 1054 |
if part in ("keybindings", "pronunciations"): |
| 1055 |
return part |
| 1056 |
return "" |
| 1057 |
|
| 1058 |
|
| 1059 |
def _is_bool_enum_fix(key: str, value: Any) -> bool: |
| 1060 |
"""Return True if this is a bool→enum conversion from fix_bool_enum_values.""" |
| 1061 |
if key != "findResultsVerbosity": |
| 1062 |
return False |
| 1063 |
if not isinstance(value, tuple): |
| 1064 |
return False |
| 1065 |
original, converted = value |
| 1066 |
return isinstance(original, bool) and isinstance(converted, int) |
| 1067 |
|
| 1068 |
|
| 1069 |
def _is_empty_synthesizer(key: str, value: Any) -> bool: |
| 1070 |
"""Return True if this is an empty speechServerInfo.""" |
| 1071 |
return key == "speechServerInfo" and isinstance(value, list) and all(v == "" for v in value) |
| 1072 |
|
| 1073 |
|
| 1074 |
def _values_match_default(value: Any, default: Any, enum_map: dict[int, str] | None = None) -> bool: |
| 1075 |
"""Check if a JSON value matches a schema default, handling type coercion and enums.""" |
| 1076 |
if value == default: |
| 1077 |
return True |
| 1078 |
if enum_map is not None: |
| 1079 |
nick = resolve_enum_nick(value, enum_map) |
| 1080 |
return nick == default |
| 1081 |
if isinstance(default, bool): |
| 1082 |
return bool(value) == default |
| 1083 |
if isinstance(default, int): |
| 1084 |
try: |
| 1085 |
return int(value) == default |
| 1086 |
except (TypeError, ValueError): |
| 1087 |
return False |
| 1088 |
return False |
| 1089 |
|
| 1090 |
|
| 1091 |
def _diff_json_files( |
| 1092 |
original_path: str, exported_path: str, label: str, verbose: bool = False |
| 1093 |
) -> None: |
| 1094 |
"""Load two JSON files and print a categorized diff (ignoring key order).""" |
| 1095 |
with open(original_path, encoding="utf-8") as f: |
| 1096 |
original = json.load(f) |
| 1097 |
with open(exported_path, encoding="utf-8") as f: |
| 1098 |
exported = json.load(f) |
| 1099 |
diffs = _diff_dicts(original, exported) |
| 1100 |
if not diffs: |
| 1101 |
if verbose: |
| 1102 |
print(f"* {label}: (no differences)") |
| 1103 |
return |
| 1104 |
|
| 1105 |
category_labels = { |
| 1106 |
"legacy_root": "Legacy root-level keys (not part of profiles)", |
| 1107 |
"unmigrated": "Settings not yet migrated to GSettings", |
| 1108 |
"legacy_constant": "Legacy constants (data migrated under a different key)", |
| 1109 |
"legacy_alias": "Legacy key aliases at default value", |
| 1110 |
"null_voice_field": "Null/empty voice family fields (no GSettings representation)", |
| 1111 |
"default_voice": "Voice entries with only default values", |
| 1112 |
"default_value": "Settings at their schema default (normalized away)", |
| 1113 |
"empty_dict": "Empty dicts", |
| 1114 |
"stripped_inherited": "Dict entries stripped (inherited from default profile)", |
| 1115 |
"hoisted_metadata": "Keybinding metadata hoisted to profile/app level", |
| 1116 |
"bool_enum_fix": "Boolean-to-enum conversion", |
| 1117 |
} |
| 1118 |
|
| 1119 |
categories: dict[str, list[tuple[str, str, Any]]] = {} |
| 1120 |
unexpected: list[tuple[str, str, Any]] = [] |
| 1121 |
for kind, path, value in diffs: |
| 1122 |
cat = _classify_diff(kind, path, value) |
| 1123 |
if cat: |
| 1124 |
categories.setdefault(cat, []).append((kind, path, value)) |
| 1125 |
else: |
| 1126 |
unexpected.append((kind, path, value)) |
| 1127 |
|
| 1128 |
if not unexpected and not verbose: |
| 1129 |
return |
| 1130 |
|
| 1131 |
print(f"* {label}") |
| 1132 |
|
| 1133 |
if verbose and categories: |
| 1134 |
print(" Expected/known losses:") |
| 1135 |
for cat, items in categories.items(): |
| 1136 |
desc = category_labels.get(cat, cat) |
| 1137 |
print(f" {desc} ({len(items)}):") |
| 1138 |
for kind, path, value in items: |
| 1139 |
if kind == "changed": |
| 1140 |
orig, exp = value |
| 1141 |
print( |
| 1142 |
f" {path}: {_truncate(json.dumps(orig, default=str))} → " |
| 1143 |
f"{_truncate(json.dumps(exp, default=str))}" |
| 1144 |
) |
| 1145 |
elif cat == "default_value": |
| 1146 |
print(f" {path}: {_format_diff_value(path, value)}") |
| 1147 |
else: |
| 1148 |
print(f" {path}: {_truncate(json.dumps(value, default=str))}") |
| 1149 |
|
| 1150 |
if unexpected: |
| 1151 |
not_in_dconf = [(p, v) for k, p, v in unexpected if k == "removed"] |
| 1152 |
not_in_json = [(p, v) for k, p, v in unexpected if k == "added"] |
| 1153 |
differs = [(p, v) for k, p, v in unexpected if k == "changed"] |
| 1154 |
if not_in_dconf: |
| 1155 |
print(f" Not in dconf ({len(not_in_dconf)}):") |
| 1156 |
for path, val in not_in_dconf: |
| 1157 |
print(f" {path}: {_truncate(json.dumps(val, default=str))}") |
| 1158 |
if not_in_json: |
| 1159 |
print(f" Not in JSON ({len(not_in_json)}):") |
| 1160 |
for path, val in not_in_json: |
| 1161 |
print(f" {path}: {_truncate(json.dumps(val, default=str))}") |
| 1162 |
if differs: |
| 1163 |
print(f" Differs ({len(differs)}):") |
| 1164 |
for path, val in differs: |
| 1165 |
orig, exp = val |
| 1166 |
print( |
| 1167 |
f" {path}: {_truncate(json.dumps(orig, default=str))} (JSON) → " |
| 1168 |
f"{_truncate(json.dumps(exp, default=str))} (dconf)" |
| 1169 |
) |
| 1170 |
elif verbose and not categories: |
| 1171 |
print(" (no differences)") |
| 1172 |
|
| 1173 |
|
| 1174 |
def _format_diff_value(path: str, value: Any) -> str: |
| 1175 |
"""Format a diff value, resolving enum nicks when possible.""" |
| 1176 |
raw = _truncate(json.dumps(value, default=str)) |
| 1177 |
leaf = path.rsplit(".", maxsplit=1)[-1] |
| 1178 |
info = _get_default_info() |
| 1179 |
if leaf not in info: |
| 1180 |
return raw |
| 1181 |
default, enum_map = info[leaf] |
| 1182 |
if enum_map is None: |
| 1183 |
return raw |
| 1184 |
nick = resolve_enum_nick(value, enum_map) |
| 1185 |
if nick is None: |
| 1186 |
return raw |
| 1187 |
return f"{raw} (= {nick!r}, schema default {default!r})" |
| 1188 |
|
| 1189 |
|
| 1190 |
def _print_file_summary(filepath: str) -> None: |
| 1191 |
"""Print a summary of a JSON file's contents.""" |
| 1192 |
try: |
| 1193 |
with open(filepath, encoding="utf-8") as f: |
| 1194 |
data = json.load(f) |
| 1195 |
print(f" Contents: {json.dumps(data, indent=2)}") |
| 1196 |
except (OSError, json.JSONDecodeError) as err: |
| 1197 |
print(f" (could not read: {err})") |
| 1198 |
|
| 1199 |
|
| 1200 |
def _truncate(text: str, max_length: int = 120) -> str: |
| 1201 |
"""Truncate a string with ellipsis if it exceeds max_length.""" |
| 1202 |
if len(text) <= max_length: |
| 1203 |
return text |
| 1204 |
return text[: max_length - 3] + "..." |
| 1205 |
|
| 1206 |
|
| 1207 |
def diff_settings(original_dir: str, exported_dir: str, verbose: bool = False) -> None: |
| 1208 |
"""Diff two settings directories (original JSON vs exported JSON).""" |
| 1209 |
|
| 1210 |
original_conf = os.path.join(original_dir, "user-settings.conf") |
| 1211 |
exported_conf = os.path.join(exported_dir, "user-settings.conf") |
| 1212 |
if os.path.isfile(original_conf) and os.path.isfile(exported_conf): |
| 1213 |
_diff_json_files(original_conf, exported_conf, "user-settings.conf", verbose) |
| 1214 |
|
| 1215 |
original_app_dir = os.path.join(original_dir, "app-settings") |
| 1216 |
exported_app_dir = os.path.join(exported_dir, "app-settings") |
| 1217 |
if os.path.isdir(original_app_dir): |
| 1218 |
original_apps = {f for f in os.listdir(original_app_dir) if f.endswith(".conf")} |
| 1219 |
exported_apps = set() |
| 1220 |
if os.path.isdir(exported_app_dir): |
| 1221 |
exported_apps = {f for f in os.listdir(exported_app_dir) if f.endswith(".conf")} |
| 1222 |
|
| 1223 |
for app in sorted(original_apps | exported_apps): |
| 1224 |
orig = os.path.join(original_app_dir, app) |
| 1225 |
exp = os.path.join(exported_app_dir, app) |
| 1226 |
if not os.path.isfile(orig): |
| 1227 |
print(f"* app-settings/{app}: only in dconf") |
| 1228 |
_print_file_summary(exp) |
| 1229 |
elif not os.path.isfile(exp): |
| 1230 |
print(f"* app-settings/{app}: only in JSON") |
| 1231 |
_print_file_summary(orig) |
| 1232 |
else: |
| 1233 |
_diff_json_files(orig, exp, f"app-settings/{app}", verbose) |
| 1234 |
|
| 1235 |
|
| 1236 |
def roundtrip(settings_dir: str, output_dir: str, verbose: bool = False) -> None: |
| 1237 |
"""Import JSON → dconf, export dconf → JSON, diff original vs exported.""" |
| 1238 |
|
| 1239 |
source = SchemaSource() |
| 1240 |
subprocess.run(["dconf", "reset", "-f", "/org/gnome/orca/"], check=True) |
| 1241 |
with redirect_stdout(io.StringIO()): |
| 1242 |
import_settings(settings_dir, source) |
| 1243 |
Gio.Settings.sync() # pylint: disable=no-value-for-parameter |
| 1244 |
|
| 1245 |
if os.path.isdir(output_dir): |
| 1246 |
shutil.rmtree(output_dir) |
| 1247 |
os.makedirs(output_dir, exist_ok=True) |
| 1248 |
export_settings(source, output_dir) |
| 1249 |
|
| 1250 |
diff_settings(settings_dir, output_dir, verbose) |
| 1251 |
|
| 1252 |
|
| 1253 |
def main() -> None: |
| 1254 |
"""CLI entry point for import, export, roundtrip, and diff commands.""" |
| 1255 |
parser = argparse.ArgumentParser(description="Orca GSettings tool: import/export settings") |
| 1256 |
parser.add_argument( |
| 1257 |
"--prefix", |
| 1258 |
help="Orca install prefix (e.g. /usr/local). Adds <prefix>/share to XDG_DATA_DIRS.", |
| 1259 |
) |
| 1260 |
subparsers = parser.add_subparsers(dest="command", required=True) |
| 1261 |
|
| 1262 |
imp = subparsers.add_parser("import", help="Import JSON settings into GSettings/dconf") |
| 1263 |
imp.add_argument( |
| 1264 |
"settings_dir", |
| 1265 |
help="Directory containing user-settings.conf (and optionally app-settings/)", |
| 1266 |
) |
| 1267 |
imp.add_argument( |
| 1268 |
"--dry-run", action="store_true", help="Show what would be written without changes" |
| 1269 |
) |
| 1270 |
|
| 1271 |
exp = subparsers.add_parser("export", help="Export GSettings/dconf settings to JSON") |
| 1272 |
exp.add_argument("output_dir", help="Directory to write exported settings") |
| 1273 |
|
| 1274 |
rt = subparsers.add_parser("roundtrip", help="Import JSON → dconf → export JSON, then diff") |
| 1275 |
rt.add_argument( |
| 1276 |
"settings_dir", |
| 1277 |
help="Directory containing user-settings.conf (e.g. ~/.local/share/orca)", |
| 1278 |
) |
| 1279 |
rt.add_argument("output_dir", help="Directory for exported JSON (e.g. /tmp/orca-roundtrip)") |
| 1280 |
rt.add_argument("-v", "--verbose", action="store_true", help="Show expected/known losses too") |
| 1281 |
|
| 1282 |
di = subparsers.add_parser("diff", help="Export dconf → JSON, then diff against original JSON") |
| 1283 |
di.add_argument( |
| 1284 |
"settings_dir", |
| 1285 |
help="Directory containing original user-settings.conf (e.g. ~/.local/share/orca)", |
| 1286 |
) |
| 1287 |
di.add_argument("output_dir", help="Directory for exported JSON (e.g. /tmp/orca-diff)") |
| 1288 |
di.add_argument("-v", "--verbose", action="store_true", help="Show expected/known losses too") |
| 1289 |
|
| 1290 |
args = parser.parse_args() |
| 1291 |
|
| 1292 |
if args.prefix: |
| 1293 |
share_dir = os.path.join(args.prefix, "share") |
| 1294 |
if os.path.isdir(share_dir): |
| 1295 |
xdg = os.environ.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share") |
| 1296 |
if share_dir not in xdg.split(":"): |
| 1297 |
os.environ["XDG_DATA_DIRS"] = f"{share_dir}:{xdg}" |
| 1298 |
|
| 1299 |
if args.command == "import": |
| 1300 |
source = SchemaSource() |
| 1301 |
print(f"Importing from {args.settings_dir}...") |
| 1302 |
import_settings(args.settings_dir, source, dry_run=args.dry_run) |
| 1303 |
if args.dry_run: |
| 1304 |
print("(dry run - no changes made)") |
| 1305 |
else: |
| 1306 |
Gio.Settings.sync() # pylint: disable=no-value-for-parameter |
| 1307 |
print("Import complete.") |
| 1308 |
|
| 1309 |
elif args.command == "export": |
| 1310 |
source = SchemaSource() |
| 1311 |
os.makedirs(args.output_dir, exist_ok=True) |
| 1312 |
print(f"Exporting to {args.output_dir}...") |
| 1313 |
export_settings(source, args.output_dir) |
| 1314 |
|
| 1315 |
elif args.command == "roundtrip": |
| 1316 |
roundtrip(args.settings_dir, args.output_dir, args.verbose) |
| 1317 |
|
| 1318 |
elif args.command == "diff": |
| 1319 |
source = SchemaSource() |
| 1320 |
if os.path.isdir(args.output_dir): |
| 1321 |
shutil.rmtree(args.output_dir) |
| 1322 |
os.makedirs(args.output_dir, exist_ok=True) |
| 1323 |
if args.verbose: |
| 1324 |
print(f"Exporting current dconf to {args.output_dir}...") |
| 1325 |
export_settings(source, args.output_dir) |
| 1326 |
else: |
| 1327 |
with redirect_stdout(io.StringIO()): |
| 1328 |
export_settings(source, args.output_dir) |
| 1329 |
diff_settings(args.settings_dir, args.output_dir, args.verbose) |
| 1330 |
|
| 1331 |
|
| 1332 |
if __name__ == "__main__": |
| 1333 |
main() |