Debian Codegraph @

tools/generate_dbus_documentation.py

raw
1 #!/usr/bin/python
2 # generate_dbus_documentation.py
3 #
4 # Generate markdown documentation for Orca's D-Bus remote controller.
5 # Must be run while Orca is active with the D-Bus service enabled.
6 #
7 # Copyright 2025 Igalia, S.L.
8 # Author: Joanmarie Diggs <[email protected]>
9 #
10 # This library is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU Lesser General Public
12 # License as published by the Free Software Foundation; either
13 # version 2.1 of the License, or (at your option) any later version.
14 #
15 # This library is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
19 #
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with this library; if not, write to the
22 # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
23 # Boston MA 02110-1301 USA.
24
25 """Generate markdown documentation for Orca's D-Bus remote controller."""
26
27 import os
28 import sys
29
30 from dasbus.connection import SessionMessageBus
31 from dasbus.error import DBusError
32
33 SERVICE_NAME = "org.gnome.Orca.Service"
34 SERVICE_PATH = "/org/gnome/Orca/Service"
35
36
37 def get_system_commands(proxy):
38 """Get system-level commands from the main service interface."""
39 try:
40 commands = proxy.ListCommands()
41 return sorted(commands, key=lambda x: x[0])
42 except DBusError as e:
43 print(f"Error getting system commands: {e}", file=sys.stderr)
44 return []
45
46
47 def get_modules(proxy):
48 """Get list of registered modules."""
49 try:
50 modules = proxy.ListModules()
51 return sorted(modules)
52 except DBusError as e:
53 print(f"Error getting modules: {e}", file=sys.stderr)
54 return []
55
56
57 def get_module_info(bus, module_name):
58 """Get all commands, parameterized commands, getters, and setters for a module."""
59 object_path = f"{SERVICE_PATH}/{module_name}"
60
61 try:
62 module_proxy = bus.get_proxy(SERVICE_NAME, object_path)
63
64 commands = module_proxy.ListCommands()
65 parameterized_commands = module_proxy.ListParameterizedCommands()
66 getters = module_proxy.ListRuntimeGetters()
67 setters = module_proxy.ListRuntimeSetters()
68
69 return {
70 "commands": sorted(commands, key=lambda x: x[0]),
71 "parameterized_commands": sorted(parameterized_commands, key=lambda x: x[0]),
72 "getters": sorted(getters, key=lambda x: x[0]),
73 "setters": sorted(setters, key=lambda x: x[0]),
74 }
75 except DBusError as e:
76 print(f"Error getting info for module {module_name}: {e}", file=sys.stderr)
77 return {"commands": [], "parameterized_commands": [], "getters": [], "setters": []}
78
79
80 def format_system_commands(commands):
81 """Format system-level commands as markdown."""
82 lines = []
83 lines.append("## Service-Level Commands")
84 lines.append("")
85 lines.append(
86 "These commands are available directly on the main service object "
87 "at `/org/gnome/Orca/Service`."
88 )
89 lines.append("")
90
91 for name, description in commands:
92 lines.append(f"- **`{name}`:** {description}")
93
94 lines.append("")
95 return "\n".join(lines)
96
97
98 def format_module_commands(module_name, info):
99 """Format module-level commands as markdown."""
100
101 lines = []
102 lines.append(f"### {module_name}")
103 lines.append("")
104 lines.append(f"**Object Path:** `/org/gnome/Orca/Service/{module_name}`")
105 lines.append("")
106
107 if info["commands"]:
108 lines.append("#### Commands")
109 lines.append("")
110 lines.append("**Method:** `org.gnome.Orca.Module.ExecuteCommand`")
111 lines.append("")
112 lines.append(
113 "**Parameters:** `CommandName` (string), "
114 "[`NotifyUser`](README-REMOTE-CONTROLLER.md#user-notification-applicability) (boolean)"
115 )
116 lines.append("")
117 for name, description in info["commands"]:
118 lines.append(f"- **`{name}`:** {description}")
119 lines.append("")
120
121 if info["parameterized_commands"]:
122 lines.append("#### Parameterized Commands")
123 lines.append("")
124 lines.append("**Method:** `org.gnome.Orca.Module.ExecuteParameterizedCommand`")
125 lines.append("")
126 for name, description, parameters in info["parameterized_commands"]:
127 param_list = ", ".join([f"`{pname}` ({ptype})" for pname, ptype in parameters])
128 if param_list:
129 lines.append(f"- **`{name}`:** {description} Parameters: {param_list}")
130 else:
131 lines.append(f"- **`{name}`:** {description}")
132 lines.append("")
133
134 if info["getters"] or info["setters"]:
135 lines.append("#### Settings")
136 lines.append("")
137 lines.append(
138 "**Methods:** `org.gnome.Orca.Module.ExecuteRuntimeGetter` / "
139 "`org.gnome.Orca.Module.ExecuteRuntimeSetter`"
140 )
141 lines.append("")
142 lines.append("**Parameters:** `PropertyName` (string), `Value` (variant, setter only)")
143 lines.append("")
144
145 # Build a merged dictionary of properties
146 # Prefer setter descriptions as they may contain range/default info
147 properties = {}
148 for name, description in info["getters"]:
149 properties[name] = {"description": description, "getter": True, "setter": False}
150 for name, description in info["setters"]:
151 if name in properties:
152 properties[name]["setter"] = True
153 properties[name]["description"] = description
154 else:
155 properties[name] = {"description": description, "getter": False, "setter": True}
156
157 # Output sorted properties with annotations
158 for name in sorted(properties.keys()):
159 prop = properties[name]
160 description = prop["description"]
161 annotation = ""
162
163 if prop["getter"] and not prop["setter"]:
164 annotation = " (getter only)"
165 elif prop["setter"] and not prop["getter"]:
166 annotation = " (setter only)"
167 # Both getter and setter - change "Returns" or "Sets" to "Gets/Sets"
168 elif description.startswith("Returns "):
169 description = description.replace("Returns ", "Gets/Sets ", 1)
170 elif description.startswith("Sets "):
171 description = description.replace("Sets ", "Gets/Sets ", 1)
172
173 lines.append(f"- **`{name}`:** {description}{annotation}")
174 lines.append("")
175
176 return "\n".join(lines)
177
178
179 def generate_documentation():
180 """Generate the complete documentation."""
181 try:
182 bus = SessionMessageBus()
183 except DBusError as e:
184 print(f"Error connecting to D-Bus: {e}", file=sys.stderr)
185 return None
186
187 try:
188 proxy = bus.get_proxy(SERVICE_NAME, SERVICE_PATH)
189 except DBusError as e:
190 print(f"Error connecting to Orca service: {e}", file=sys.stderr)
191 print("Make sure Orca is running with the D-Bus service enabled.", file=sys.stderr)
192 return None
193
194 system_commands = get_system_commands(proxy)
195 modules = get_modules(proxy)
196 if not system_commands and not modules:
197 print(
198 "No commands or modules found. Is Orca running with the D-Bus service enabled?",
199 file=sys.stderr,
200 )
201 return None
202
203 module_infos = {}
204 for module_name in modules:
205 module_infos[module_name] = get_module_info(bus, module_name)
206
207 lines = []
208 lines.append("# Orca D-Bus Service Commands Reference")
209 lines.append("")
210 lines.append("The service can be accessed at:")
211 lines.append("")
212 lines.append("- **Service Name:** `org.gnome.Orca.Service`")
213 lines.append("- **Main Object Path:** `/org/gnome/Orca/Service`")
214 lines.append("- **Module Object Paths:** `/org/gnome/Orca/Service/ModuleName`")
215 lines.append("")
216 lines.append(
217 "Additional information about using the remote controller can be found in "
218 "[README-REMOTE-CONTROLLER.md](README-REMOTE-CONTROLLER.md)."
219 )
220 lines.append("")
221 lines.append("---")
222 lines.append("")
223
224 lines.append(format_system_commands(system_commands))
225 lines.append("---")
226 lines.append("")
227
228 lines.append("## Modules")
229 lines.append("")
230 lines.append(
231 "Each module exposes commands, getters, and setters on its object "
232 "at `/org/gnome/Orca/Service/ModuleName`."
233 )
234 lines.append("")
235
236 for module_name in modules:
237 lines.append(format_module_commands(module_name, module_infos[module_name]))
238 lines.append("---")
239 lines.append("")
240
241 return "\n".join(lines)
242
243
244 def main():
245 """Main entry point."""
246
247 # Write to parent directory since script is in tools/
248 script_dir = os.path.dirname(os.path.abspath(__file__))
249 parent_dir = os.path.dirname(script_dir)
250 output_file = os.path.join(parent_dir, "REMOTE-CONTROLLER-COMMANDS.md")
251
252 print("Generating D-Bus documentation...", file=sys.stderr)
253 documentation = generate_documentation()
254
255 if documentation is None:
256 print("Failed to generate documentation.", file=sys.stderr)
257 return 1
258
259 try:
260 with open(output_file, "w", encoding="utf-8") as f:
261 f.write(documentation)
262 print(f"Documentation written to {output_file}", file=sys.stderr)
263 return 0
264 except OSError as e:
265 print(f"Error writing to {output_file}: {e}", file=sys.stderr)
266 return 1
267
268
269 if __name__ == "__main__":
270 sys.exit(main())