Debian Codegraph @

tools/generate_gsettings_documentation.py

raw
1 #!/usr/bin/python
2 # generate_gsettings_documentation.py
3 #
4 # Generate markdown documentation for Orca's GSettings schemas.
5 #
6 # Copyright 2026 Igalia, S.L.
7 # Author: Joanmarie Diggs <[email protected]>
8 #
9 # This library is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU Lesser General Public
11 # License as published by the Free Software Foundation; either
12 # version 2.1 of the License, or (at your option) any later version.
13 #
14 # This library is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 # Lesser General Public License for more details.
18 #
19 # You should have received a copy of the GNU Lesser General Public
20 # License along with this library; if not, write to the
21 # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
22 # Boston MA 02110-1301 USA.
23
24 """Generate markdown documentation for Orca's GSettings schemas."""
25
26 import argparse
27 import sys
28 import tempfile
29 import xml.etree.ElementTree as ET
30 from pathlib import Path
31
32 from generate_gsettings_schemas import _discover_schemas, generate_schema_xml
33
34
35 def _normalize_summary(summary: str | None) -> str:
36 if summary is None:
37 return "(No summary provided.)"
38 summary = summary.strip()
39 return summary or "(No summary provided.)"
40
41
42 def _escape_cell(value: str) -> str:
43 """Escape markdown table cell content."""
44
45 return value.replace("|", "\\|").replace("\n", " ")
46
47
48 def _format_key_row(
49 key_el: ET.Element,
50 enum_values: dict[str, list[tuple[str, str]]],
51 include_enum_allowed: bool,
52 ) -> str:
53 key_name = key_el.get("name", "")
54 enum_id = key_el.get("enum")
55 key_type = key_el.get("type")
56 default = key_el.findtext("default", default="")
57 summary = _normalize_summary(key_el.findtext("summary"))
58
59 if enum_id:
60 enum_name = enum_id.rsplit(".", 1)[-1]
61 if include_enum_allowed:
62 values = enum_values.get(enum_id, [])
63 allowed = ", ".join(f"`{nick}`" for nick, _ in values)
64 if allowed:
65 type_info = f"`enum`<br>`{enum_name}`<br>allowed: {allowed}"
66 else:
67 type_info = f"`enum`<br>`{enum_name}`"
68 else:
69 type_info = f"`enum`<br>`{enum_name}`"
70 else:
71 type_info = f"`{key_type or ''}`"
72
73 return (
74 f"| `{_escape_cell(key_name)}` | {_escape_cell(type_info)} | "
75 f"`{_escape_cell(default)}` | {_escape_cell(summary)} |"
76 )
77
78
79 # pylint: disable-next=too-many-locals, too-many-statements
80 def generate_documentation(
81 src_dir: Path,
82 include_enum_allowed: bool = False,
83 ) -> str:
84 """Generate markdown documentation from generated schema XML."""
85
86 with tempfile.TemporaryDirectory(prefix="orca-gsettings-") as tmpdir:
87 xml_path = Path(tmpdir) / "org.gnome.Orca.gschema.xml"
88 generate_schema_xml(src_dir, str(xml_path))
89 root = ET.parse(xml_path).getroot()
90
91 schemas, _settings, _enums = _discover_schemas(src_dir)
92 schema_names_by_id = {schema_id: schema_name for schema_name, schema_id in schemas.items()}
93
94 enum_values: dict[str, list[tuple[str, str]]] = {}
95 for enum_el in sorted(root.findall("enum"), key=lambda el: el.get("id", "")):
96 enum_id = enum_el.get("id", "")
97 pairs = []
98 for value_el in enum_el.findall("value"):
99 nick = value_el.get("nick", "")
100 value = value_el.get("value", "")
101 pairs.append((nick, value))
102 enum_values[enum_id] = pairs
103
104 schema_els = sorted(root.findall("schema"), key=lambda el: el.get("id", ""))
105 lines: list[str] = []
106 lines.append("# Orca GSettings Schemas Reference")
107 lines.append("")
108 lines.append("[TOC]")
109 lines.append("")
110 lines.append("## Overview")
111 lines.append("")
112 lines.append("Orca stores settings under `/org/gnome/orca/`.")
113 lines.append("- Profile-level settings: `/org/gnome/orca/<profile>/<schema-name>/`")
114 lines.append("- App-specific overrides: `/org/gnome/orca/<profile>/apps/<app>/<schema-name>/`")
115 lines.append("- Voice settings: `/org/gnome/orca/<profile>/voices/<voice-type>/`")
116 lines.append(
117 "- App-specific voice overrides: "
118 "`/org/gnome/orca/<profile>/apps/<app>/voices/<voice-type>/`"
119 )
120 lines.append("")
121 lines.append("Path variables:")
122 lines.append(
123 "- `<profile>`: profile ID. `default` is the standard profile; "
124 "users can add others, e.g. `italian`."
125 )
126 lines.append("- `<schema-name>`: Orca schema name, e.g. `typing-echo`, `speech`, `braille`.")
127 lines.append("- `<app>`: app ID used for app-specific overrides.")
128 lines.append("- `<voice-type>`: voice type (`default`, `uppercase`, `hyperlink`, `system`).")
129 lines.append("")
130 lines.append(
131 "When Orca reads a setting, it checks several layers from most specific to least specific:"
132 )
133 lines.append("")
134 lines.append(
135 "- Scalars and enums: runtime override -> app override -> active profile -> "
136 "`default` profile (if active profile is not `default`) -> schema default"
137 )
138 lines.append(
139 "- Dictionary settings (pronunciation entries, keybinding overrides): "
140 "runtime override -> `default` profile entries (base) merged with active "
141 "profile entries, then app-specific entries overlaid on top -> schema default. "
142 "An empty list (`[]`) explicitly unbinds an inherited keybinding; "
143 "an empty-string replacement removes an inherited pronunciation."
144 )
145 lines.append("")
146 lines.append("## Inspecting and Modifying Settings")
147 lines.append("")
148 lines.append("You can read and write individual Orca settings with `dconf`.")
149 lines.append("")
150 lines.append("- `dconf list /org/gnome/orca/`: list profiles")
151 lines.append("- `dconf read /org/gnome/orca/default/speech/enable`: read a single key")
152 lines.append("- `dconf write /org/gnome/orca/default/speech/enable false`: write a single key")
153 lines.append("")
154 lines.append(
155 "`gsettings` also works but requires both the schema ID and path, since Orca "
156 "uses relocatable schemas:"
157 )
158 lines.append("")
159 lines.append("- `gsettings get org.gnome.Orca.Speech:/org/gnome/orca/default/speech/ enable`")
160 lines.append(
161 "- `gsettings set org.gnome.Orca.Speech:/org/gnome/orca/default/speech/ enable false`"
162 )
163 lines.append("")
164 lines.append("## Monitoring Changes")
165 lines.append("")
166 lines.append(
167 "`dconf watch` is path-based and can monitor any subtree. "
168 "`gsettings monitor` is schema-based and shows key names instead of raw paths."
169 )
170 lines.append("")
171 lines.append("- `dconf watch /org/gnome/orca/`: all Orca changes")
172 lines.append("- `dconf watch /org/gnome/orca/default/speech/`: one schema path")
173 lines.append("- `gsettings monitor org.gnome.Orca.Speech:/org/gnome/orca/default/speech/`")
174 lines.append("")
175 lines.append("## Migrating to GSettings")
176 lines.append("")
177 lines.append(
178 "On launch, Orca automatically migrates JSON settings from `~/.local/share/orca/` "
179 "into dconf if there are no dconf settings found."
180 )
181 lines.append("")
182 lines.append(
183 "`orca -i DIR` / `orca --import-dir DIR` can also import JSON settings manually. "
184 "This replaces the current `/org/gnome/orca/` settings in dconf, so back up first "
185 "if needed (see Transferring, Backing Up, and Restoring Settings)."
186 )
187 lines.append("")
188 lines.append(
189 "There is also a stand-alone tool mainly for testing and debugging the migration: "
190 "`python tools/gsettings_import_export.py <subcommand> ...`"
191 )
192 lines.append("")
193 lines.append(
194 "- `import DIR`: load JSON settings from `DIR` into dconf. "
195 "Use `import --dry-run` to preview writes without changing anything."
196 )
197 lines.append("- `export DIR`: save current dconf settings to JSON files in `DIR`.")
198 lines.append(
199 "- `diff SRC_DIR OUT_DIR`: export current dconf to JSON in `OUT_DIR` and compare "
200 "against `SRC_DIR`. Nothing is imported; useful for verifying migration results."
201 )
202 lines.append(
203 "- `roundtrip SRC_DIR OUT_DIR`: reset `/org/gnome/orca/`, import from `SRC_DIR`, "
204 "export to `OUT_DIR`, then diff. Tests the full import/export cycle from a clean state."
205 )
206 lines.append("")
207 lines.append(
208 "`diff` and `roundtrip` accept `-v` / `--verbose` for fuller output. "
209 "Use `--prefix <orca-prefix>` if schemas are installed in a non-default prefix."
210 )
211 lines.append("")
212 lines.append("## Transferring, Backing Up, and Restoring Settings")
213 lines.append("")
214 lines.append(
215 "All Orca settings live in dconf under `/org/gnome/orca/`. You can dump them "
216 "to a file, load them from a file, or reset them to defaults. These operations "
217 "work for transferring settings between machines, creating backups, or starting fresh."
218 )
219 lines.append("")
220 lines.append("- Dump all settings to a file: `dconf dump /org/gnome/orca/ > orca-settings.ini`")
221 lines.append("- Load settings from a file: `dconf load /org/gnome/orca/ < orca-settings.ini`")
222 lines.append("- Reset all settings to defaults: `dconf reset -f /org/gnome/orca/`")
223 lines.append("")
224 lines.append(
225 "Note: `dconf load` merges at the key level: it overwrites keys present in the "
226 "ini file but leaves other existing keys untouched. To get an exact copy "
227 "of the ini file (for example, when transferring settings from another machine), "
228 "reset before loading: "
229 "`dconf reset -f /org/gnome/orca/ && dconf load /org/gnome/orca/ < orca-settings.ini`"
230 )
231 lines.append("")
232 lines.append("These operations also work at the profile level:")
233 lines.append("")
234 lines.append("- Dump one profile: `dconf dump /org/gnome/orca/default/ > default-profile.ini`")
235 lines.append("- Load one profile: `dconf load /org/gnome/orca/default/ < default-profile.ini`")
236 lines.append("- Reset one profile to start fresh: `dconf reset -f /org/gnome/orca/default/`")
237 lines.append("")
238 lines.append("---")
239 lines.append("")
240 lines.append("## Schemas")
241 lines.append("")
242
243 for schema_el in schema_els:
244 schema_id = schema_el.get("id", "")
245 schema_name = schema_names_by_id.get(schema_id, "")
246 keys_all = sorted(
247 schema_el.findall("key"),
248 key=lambda el: (el.get("name", "") != "version", el.get("name", "")),
249 )
250 keys = [key for key in keys_all if key.get("name", "") != "version"]
251
252 lines.append(f"### `{schema_id}` (schema-name: `{schema_name}`)")
253 lines.append("")
254
255 lines.append("| Key | Type | Default | Summary |")
256 lines.append("| --- | --- | --- | --- |")
257 lines.extend(_format_key_row(key_el, enum_values, include_enum_allowed) for key_el in keys)
258
259 lines.append("")
260 lines.append("---")
261 lines.append("")
262
263 return "\n".join(lines)
264
265
266 def main() -> int:
267 """Parse arguments and write generated documentation."""
268
269 parser = argparse.ArgumentParser(description="Generate Orca GSettings markdown docs")
270 parser.add_argument(
271 "src_dir",
272 nargs="?",
273 default=str(Path(__file__).resolve().parent.parent / "src"),
274 help="Path to src directory (default: ../src)",
275 )
276 parser.add_argument(
277 "output",
278 nargs="?",
279 default=str(Path(__file__).resolve().parent.parent / "GSETTINGS-SCHEMAS.md"),
280 help="Output markdown path (default: ../GSETTINGS-SCHEMAS.md)",
281 )
282 parser.add_argument(
283 "--enum-allowed",
284 action="store_true",
285 help="Include inline enum allowed-value lists in the Type column.",
286 )
287 args = parser.parse_args()
288
289 try:
290 content = generate_documentation(
291 Path(args.src_dir),
292 include_enum_allowed=args.enum_allowed,
293 )
294 except Exception as error: # pylint: disable=broad-exception-caught
295 print(f"Error generating GSettings documentation: {error}", file=sys.stderr)
296 return 1
297
298 try:
299 with open(args.output, "w", encoding="utf-8") as output_file:
300 output_file.write(content)
301 output_file.write("\n")
302 except OSError as error:
303 print(f"Error writing {args.output}: {error}", file=sys.stderr)
304 return 1
305
306 print(f"Documentation written to {args.output}", file=sys.stderr)
307 return 0
308
309
310 if __name__ == "__main__":
311 sys.exit(main())