Debian Codegraph @

blueprintcompiler/language/gtk_a11y.py

raw
1 # gtk_a11y.py
2 #
3 # Copyright 2021 James Westman <[email protected]>
4 #
5 # This file is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation; either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # This file is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #
18 # SPDX-License-Identifier: LGPL-3.0-or-later
19
20 import typing as T
21
22 from .common import *
23 from .contexts import ValueTypeCtx
24 from .gobject_object import ObjectContent, validate_parent_type
25 from .values import Value
26
27
28 def get_property_types(gir):
29 # from <https://docs.gtk.org/gtk4/enum.AccessibleProperty.html>
30 return {
31 "autocomplete": gir.get_type("AccessibleAutocomplete", "Gtk"),
32 "description": StringType(),
33 "has-popup": BoolType(),
34 "help-text": StringType(),
35 "key-shortcuts": StringType(),
36 "label": StringType(),
37 "level": IntType(),
38 "modal": BoolType(),
39 "multi-line": BoolType(),
40 "multi-selectable": BoolType(),
41 "orientation": gir.get_type("Orientation", "Gtk"),
42 "placeholder": StringType(),
43 "read-only": BoolType(),
44 "required": BoolType(),
45 "role-description": StringType(),
46 "sort": gir.get_type("AccessibleSort", "Gtk"),
47 "value-max": FloatType(),
48 "value-min": FloatType(),
49 "value-now": FloatType(),
50 "value-text": StringType(),
51 }
52
53
54 def get_relation_types(gir):
55 # from <https://docs.gtk.org/gtk4/enum.AccessibleRelation.html>
56 widget = gir.get_type("Widget", "Gtk")
57 return {
58 "active-descendant": widget,
59 "col-count": IntType(),
60 "col-index": IntType(),
61 "col-index-text": StringType(),
62 "col-span": IntType(),
63 "controls": widget,
64 "described-by": widget,
65 "details": widget,
66 "error-message": widget,
67 "flow-to": widget,
68 "labelled-by": widget,
69 "owns": widget,
70 "pos-in-set": IntType(),
71 "row-count": IntType(),
72 "row-index": IntType(),
73 "row-index-text": StringType(),
74 "row-span": IntType(),
75 "set-size": IntType(),
76 }
77
78
79 def get_state_types(gir):
80 # from <https://docs.gtk.org/gtk4/enum.AccessibleState.html>
81 return {
82 "busy": BoolType(),
83 "checked": gir.get_type("AccessibleTristate", "Gtk"),
84 "disabled": BoolType(),
85 "expanded": BoolType(),
86 "hidden": BoolType(),
87 "invalid": gir.get_type("AccessibleInvalidState", "Gtk"),
88 "pressed": gir.get_type("AccessibleTristate", "Gtk"),
89 "selected": BoolType(),
90 "visited": BoolType(),
91 }
92
93
94 def get_types(gir):
95 return {
96 **get_property_types(gir),
97 **get_relation_types(gir),
98 **get_state_types(gir),
99 }
100
101
102 allow_duplicates = [
103 "controls",
104 "described-by",
105 "details",
106 "flow-to",
107 "labelled-by",
108 "owns",
109 ]
110
111
112 def _get_docs(gir, name):
113 name = name.replace("-", "_")
114 if gir_type := (
115 gir.get_type("AccessibleProperty", "Gtk").members.get(name)
116 or gir.get_type("AccessibleRelation", "Gtk").members.get(name)
117 or gir.get_type("AccessibleState", "Gtk").members.get(name)
118 ):
119 return gir_type.doc
120
121
122 class A11yProperty(AstNode):
123 grammar = Statement(
124 UseIdent("name"),
125 ":",
126 AnyOf(
127 Value, ["[", UseLiteral("list_form", True), Delimited(Value, ","), "]"]
128 ).expected("value"),
129 )
130
131 @property
132 def tag_name(self):
133 name = self.tokens["name"]
134 gir = self.root.gir
135 if name in get_property_types(gir):
136 return "property"
137 elif name in get_relation_types(gir):
138 return "relation"
139 elif name in get_state_types(gir):
140 return "state"
141 else:
142 raise CompilerBugError()
143
144 @property
145 def name(self):
146 return self.tokens["name"].replace("_", "-")
147
148 @property
149 def values(self) -> T.List[Value]:
150 return list(self.children)
151
152 @context(ValueTypeCtx)
153 def value_type(self) -> ValueTypeCtx:
154 return ValueTypeCtx(get_types(self.root.gir).get(self.tokens["name"]))
155
156 @property
157 def document_symbol(self) -> DocumentSymbol:
158 return DocumentSymbol(
159 self.name,
160 SymbolKind.Field,
161 self.range,
162 self.group.tokens["name"].range,
163 ", ".join(v.range.text for v in self.values),
164 )
165
166 @validate("name")
167 def is_valid_property(self):
168 types = get_types(self.root.gir)
169 if self.tokens["name"] not in types:
170 raise CompileError(
171 f"'{self.tokens['name']}' is not an accessibility property, relation, or state",
172 did_you_mean=(self.tokens["name"], types.keys()),
173 )
174
175 @validate("name")
176 def unique_in_parent(self):
177 self.validate_unique_in_parent(
178 f"Duplicate accessibility attribute '{self.tokens['name']}'",
179 check=lambda child: child.tokens["name"] == self.tokens["name"],
180 )
181
182 @validate("name")
183 def list_only_allowed_for_subset(self):
184 if self.tokens["list_form"] and self.tokens["name"] not in allow_duplicates:
185 raise CompileError(
186 f"'{self.tokens['name']}' does not allow a list of values",
187 )
188
189 @validate("name")
190 def list_non_empty(self):
191 if len(self.values) == 0:
192 raise CompileError(
193 f"'{self.tokens['name']}' may not be empty",
194 )
195
196 @docs("name")
197 def prop_docs(self):
198 if self.tokens["name"] in get_types(self.root.gir):
199 return _get_docs(self.root.gir, self.tokens["name"])
200
201
202 class ExtAccessibility(AstNode):
203 grammar = [
204 Keyword("accessibility"),
205 "{",
206 Until(A11yProperty, "}"),
207 ]
208
209 @property
210 def properties(self) -> T.List[A11yProperty]:
211 return self.children[A11yProperty]
212
213 @property
214 def document_symbol(self) -> DocumentSymbol:
215 return DocumentSymbol(
216 "accessibility",
217 SymbolKind.Struct,
218 self.range,
219 self.group.tokens["accessibility"].range,
220 )
221
222 @validate("accessibility")
223 def container_is_widget(self):
224 validate_parent_type(self, "Gtk", "Widget", "accessibility properties")
225
226 @validate("accessibility")
227 def unique_in_parent(self):
228 self.validate_unique_in_parent("Duplicate accessibility block")
229
230 @docs("accessibility")
231 def ref_docs(self):
232 return get_docs_section("Syntax ExtAccessibility")
233
234
235 @completer(
236 applies_in=[ObjectContent],
237 matches=new_statement_patterns,
238 )
239 def a11y_completer(_ctx: CompletionContext):
240 yield Completion(
241 "accessibility",
242 CompletionItemKind.Snippet,
243 snippet="accessibility {\n $0\n}",
244 sort_text=get_sort_key(CompletionPriority.OBJECT_MEMBER, "accessibility"),
245 )
246
247
248 @completer(
249 applies_in=[ExtAccessibility],
250 matches=new_statement_patterns,
251 )
252 def a11y_name_completer(ctx: CompletionContext):
253 for name, type in get_types(ctx.ast_node.root.gir).items():
254 yield Completion(
255 name,
256 CompletionItemKind.Property,
257 docs=_get_docs(ctx.ast_node.root.gir, type.name),
258 )
259
260
261 @decompiler("accessibility", skip_children=True, element=True)
262 def decompile_accessibility(ctx: DecompileCtx, _gir, element):
263 ctx.print("accessibility {")
264 already_printed = set()
265 types = get_types(ctx.gir)
266
267 for child in element.children:
268 name = child["name"]
269
270 if name in allow_duplicates:
271 if name in already_printed:
272 continue
273
274 ctx.print(f"{name}: [")
275 for value in element.children:
276 if value["name"] == name:
277 comments, string = ctx.decompile_value(
278 value.cdata,
279 types.get(value["name"]),
280 (value["translatable"], value["context"], value["comments"]),
281 )
282 ctx.print(f"{comments} {string},")
283 ctx.print("];")
284 else:
285 comments, string = ctx.decompile_value(
286 child.cdata,
287 types.get(child["name"]),
288 (child["translatable"], child["context"], child["comments"]),
289 )
290 ctx.print(f"{comments} {name}: {string};")
291
292 already_printed.add(name)
293 ctx.print("}")
294 ctx.end_block_with("")