fontlab-python-plugmix 1.1.18__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.
- fontlab_plugmix/__init__.py +41 -0
- fontlab_plugmix/backend.py +285 -0
- fontlab_plugmix/boot.py +140 -0
- fontlab_plugmix/filter.py +83 -0
- fontlab_plugmix/filters/__init__.py +4 -0
- fontlab_plugmix/filters/apply.py +158 -0
- fontlab_plugmix/filters/delete_small_paths.py +57 -0
- fontlab_plugmix/filters/dialog.py +119 -0
- fontlab_plugmix/filters/host.py +120 -0
- fontlab_plugmix/general.py +144 -0
- fontlab_plugmix/general_plugins/__init__.py +4 -0
- fontlab_plugmix/general_plugins/host.py +137 -0
- fontlab_plugmix/general_plugins/zoom_to_selection.py +27 -0
- fontlab_plugmix/geometry.py +64 -0
- fontlab_plugmix/kinds.py +33 -0
- fontlab_plugmix/menu.py +29 -0
- fontlab_plugmix/palette.py +24 -0
- fontlab_plugmix/palettes/__init__.py +4 -0
- fontlab_plugmix/palettes/apply.py +159 -0
- fontlab_plugmix/palettes/host.py +369 -0
- fontlab_plugmix/palettes/step_and_repeat.py +53 -0
- fontlab_plugmix/palettes/ui.py +86 -0
- fontlab_plugmix/plugin.py +14 -0
- fontlab_plugmix/plugins/__init__.py +4 -0
- fontlab_plugmix/plugins/anchor_cloud.py +30 -0
- fontlab_plugmix/plugins/angled_handles.py +40 -0
- fontlab_plugmix/plugins/center_lines.py +28 -0
- fontlab_plugmix/plugins/crosshair.py +39 -0
- fontlab_plugmix/plugins/duplicate_anchors.py +50 -0
- fontlab_plugmix/plugins/glyph_focus.py +28 -0
- fontlab_plugmix/plugins/imprecise_italic_angle.py +44 -0
- fontlab_plugmix/plugins/node_indexes.py +26 -0
- fontlab_plugmix/plugins/nodes_close_to_zones.py +35 -0
- fontlab_plugmix/plugins/offcurve_outside_bounds.py +31 -0
- fontlab_plugmix/plugins/only_selected_handles.py +38 -0
- fontlab_plugmix/plugins/rsb_line.py +39 -0
- fontlab_plugmix/plugins/segment_length.py +36 -0
- fontlab_plugmix/plugins/selected_coordinates.py +27 -0
- fontlab_plugmix/plugins/smooth_node_angles.py +51 -0
- fontlab_plugmix/plugins/tops_and_bottoms.py +34 -0
- fontlab_plugmix/plugins/two_point_distance.py +38 -0
- fontlab_plugmix/plugins/unitizer.py +35 -0
- fontlab_plugmix/plugins/vertical_metrics.py +39 -0
- fontlab_plugmix/registry.py +434 -0
- fontlab_plugmix/reporter.py +127 -0
- fontlab_plugmix/snapshot.py +285 -0
- fontlab_plugmix/tool.py +104 -0
- fontlab_plugmix/tools/__init__.py +4 -0
- fontlab_plugmix/tools/bridge.py +169 -0
- fontlab_plugmix/tools/host.py +143 -0
- fontlab_plugmix/tools/smart_select.py +77 -0
- fontlab_python_plugmix-1.1.18.dist-info/METADATA +444 -0
- fontlab_python_plugmix-1.1.18.dist-info/RECORD +56 -0
- fontlab_python_plugmix-1.1.18.dist-info/WHEEL +4 -0
- fontlab_python_plugmix-1.1.18.dist-info/licenses/LICENSE +201 -0
- fontlab_python_plugmix-1.1.18.dist-info/licenses/NOTICE +228 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/registry.py
|
|
2
|
+
"""Discover plugin kinds and persist their explicit enable choices."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import pkgutil
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from importlib import import_module, metadata
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .filter import Filter
|
|
12
|
+
from .general import General
|
|
13
|
+
from .palette import Palette
|
|
14
|
+
from .plugin import Plugin
|
|
15
|
+
from .reporter import Reporter
|
|
16
|
+
from .tool import Tool
|
|
17
|
+
|
|
18
|
+
ENTRY_GROUP = "fontlab_plugmix.plugins"
|
|
19
|
+
RENAMED = {"nodes_outside_paths": "offcurve_outside_bounds"}
|
|
20
|
+
DEFAULT_FILE = (
|
|
21
|
+
Path.home()
|
|
22
|
+
/ "Library/Application Support/FontLab/FontLab 9/Data/fontlab-plugmix.json"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
ErrorSink = Callable[[Exception, object], object]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _report(error: Exception, source: object, sink: ErrorSink | None) -> None:
|
|
30
|
+
"""Report a broken plugin or preference without interrupting discovery."""
|
|
31
|
+
try:
|
|
32
|
+
if sink is None:
|
|
33
|
+
print(f"Plugmix {source}: {error}")
|
|
34
|
+
else:
|
|
35
|
+
sink(error, source)
|
|
36
|
+
except Exception: # noqa: BLE001, S110 - diagnostics must not block startup
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _accept(found: dict[str, type[Plugin]], cls: Any) -> None:
|
|
41
|
+
"""Add one valid plugin class, preserving the first name owner."""
|
|
42
|
+
if (
|
|
43
|
+
not isinstance(cls, type)
|
|
44
|
+
or not issubclass(cls, Plugin)
|
|
45
|
+
or cls.kind not in {"reporter", "filter", "palette", "tool", "general"}
|
|
46
|
+
or (cls.kind == "reporter" and not issubclass(cls, Reporter))
|
|
47
|
+
or (cls.kind == "filter" and not issubclass(cls, Filter))
|
|
48
|
+
or (cls.kind == "palette" and not issubclass(cls, Palette))
|
|
49
|
+
or (cls.kind == "tool" and not issubclass(cls, Tool))
|
|
50
|
+
or (cls.kind == "general" and not issubclass(cls, General))
|
|
51
|
+
or not cls.name
|
|
52
|
+
or not cls.title
|
|
53
|
+
):
|
|
54
|
+
raise TypeError(f"Invalid plugmix plugin: {cls!r}")
|
|
55
|
+
if cls.name in found:
|
|
56
|
+
raise ValueError(f"Duplicate plugmix plugin name: {cls.name}")
|
|
57
|
+
found[cls.name] = cls
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _scan(
|
|
61
|
+
package_name: str, found: dict[str, type[Plugin]], sink: ErrorSink | None
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Discover one built-in package, isolating broken modules."""
|
|
64
|
+
package = import_module(f".{package_name}", "fontlab_plugmix")
|
|
65
|
+
for entry in pkgutil.iter_modules(package.__path__):
|
|
66
|
+
try:
|
|
67
|
+
module = import_module(f"{package.__name__}.{entry.name}")
|
|
68
|
+
for cls in vars(module).values():
|
|
69
|
+
if (
|
|
70
|
+
isinstance(cls, type)
|
|
71
|
+
and not cls.__name__.startswith("_")
|
|
72
|
+
and cls.__module__ == module.__name__
|
|
73
|
+
and issubclass(cls, Plugin)
|
|
74
|
+
):
|
|
75
|
+
_accept(found, cls)
|
|
76
|
+
except Exception as error: # noqa: BLE001 - one plugin cannot block startup
|
|
77
|
+
_report(error, entry.name, sink)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def discover(error_sink: ErrorSink | None = None) -> dict[str, type[Plugin]]:
|
|
81
|
+
"""Find built-in classes and third-party entry points on demand."""
|
|
82
|
+
found: dict[str, type[Plugin]] = {}
|
|
83
|
+
for package_name in ("plugins", "filters", "palettes", "tools", "general_plugins"):
|
|
84
|
+
_scan(package_name, found, error_sink)
|
|
85
|
+
try:
|
|
86
|
+
points = metadata.entry_points().select(group=ENTRY_GROUP)
|
|
87
|
+
except Exception as error: # noqa: BLE001 - broken entry-point metadata
|
|
88
|
+
_report(error, ENTRY_GROUP, error_sink)
|
|
89
|
+
points = ()
|
|
90
|
+
for point in points:
|
|
91
|
+
try:
|
|
92
|
+
_accept(found, point.load())
|
|
93
|
+
except Exception as error: # noqa: BLE001 - third-party plugin boundary
|
|
94
|
+
_report(error, point, error_sink)
|
|
95
|
+
return found
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Registry:
|
|
99
|
+
"""Own active painter tokens and the one JSON preference file."""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self, config_dir: str | Path | None = None, error_sink: ErrorSink | None = None
|
|
103
|
+
) -> None:
|
|
104
|
+
self.path = (
|
|
105
|
+
DEFAULT_FILE if config_dir is None else Path(config_dir) / DEFAULT_FILE.name
|
|
106
|
+
)
|
|
107
|
+
self._classes: dict[str, type[Plugin]] | None = None
|
|
108
|
+
self._wanted: set[str] = set()
|
|
109
|
+
self._filter_wanted: set[str] | None = None
|
|
110
|
+
self._palette_wanted: set[str] | None = None
|
|
111
|
+
self._tool_wanted: set[str] | None = None
|
|
112
|
+
self._general_wanted: set[str] | None = None
|
|
113
|
+
self._params: dict[str, dict[str, Any]] = {}
|
|
114
|
+
self._extras: dict[str, Any] = {}
|
|
115
|
+
self._tokens: dict[str, int] = {}
|
|
116
|
+
self._painters: Any = None
|
|
117
|
+
self._qt: Any = None
|
|
118
|
+
self._sink: Any = None
|
|
119
|
+
self._error_sink = error_sink
|
|
120
|
+
self._load()
|
|
121
|
+
|
|
122
|
+
def _load(self) -> None:
|
|
123
|
+
"""Read persisted names, leaving missing plugin names restorable later."""
|
|
124
|
+
try:
|
|
125
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
126
|
+
if not isinstance(data, dict) or not isinstance(data.get("enabled"), list):
|
|
127
|
+
raise TypeError(f"Invalid plugmix preferences: {self.path}")
|
|
128
|
+
if any(not isinstance(name, str) for name in data["enabled"]):
|
|
129
|
+
raise ValueError(f"Invalid plugmix enabled names: {self.path}")
|
|
130
|
+
filters = data.get("enabled_filters")
|
|
131
|
+
palettes = data.get("enabled_palettes")
|
|
132
|
+
tools = data.get("enabled_tools")
|
|
133
|
+
generals = data.get("enabled_general")
|
|
134
|
+
params = data.get("params", {})
|
|
135
|
+
if filters is not None and (
|
|
136
|
+
not isinstance(filters, list)
|
|
137
|
+
or any(not isinstance(n, str) for n in filters)
|
|
138
|
+
):
|
|
139
|
+
raise ValueError(f"Invalid plugmix enabled filters: {self.path}")
|
|
140
|
+
if palettes is not None and (
|
|
141
|
+
not isinstance(palettes, list)
|
|
142
|
+
or any(not isinstance(n, str) for n in palettes)
|
|
143
|
+
):
|
|
144
|
+
raise ValueError(f"Invalid plugmix enabled palettes: {self.path}")
|
|
145
|
+
for key, names in (("enabled_tools", tools), ("enabled_general", generals)):
|
|
146
|
+
if names is not None and (
|
|
147
|
+
not isinstance(names, list)
|
|
148
|
+
or any(not isinstance(n, str) for n in names)
|
|
149
|
+
):
|
|
150
|
+
raise ValueError(f"Invalid plugmix {key}: {self.path}")
|
|
151
|
+
if not isinstance(params, dict) or any(
|
|
152
|
+
not isinstance(v, dict) for v in params.values()
|
|
153
|
+
):
|
|
154
|
+
raise ValueError(f"Invalid plugmix params: {self.path}")
|
|
155
|
+
except FileNotFoundError:
|
|
156
|
+
return
|
|
157
|
+
except (OSError, ValueError, TypeError) as error:
|
|
158
|
+
_report(error, self.path, self._error_sink)
|
|
159
|
+
return
|
|
160
|
+
self._wanted = {RENAMED.get(name, name) for name in data["enabled"]}
|
|
161
|
+
self._filter_wanted = None if filters is None else set(filters)
|
|
162
|
+
self._palette_wanted = None if palettes is None else set(palettes)
|
|
163
|
+
self._tool_wanted = None if tools is None else set(tools)
|
|
164
|
+
self._general_wanted = None if generals is None else set(generals)
|
|
165
|
+
self._params = params
|
|
166
|
+
self._extras = {
|
|
167
|
+
k: v
|
|
168
|
+
for k, v in data.items()
|
|
169
|
+
if k
|
|
170
|
+
not in {
|
|
171
|
+
"enabled",
|
|
172
|
+
"enabled_filters",
|
|
173
|
+
"enabled_palettes",
|
|
174
|
+
"enabled_tools",
|
|
175
|
+
"enabled_general",
|
|
176
|
+
"params",
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
def _save(self) -> None:
|
|
181
|
+
"""Write one sorted preference document after a user toggle."""
|
|
182
|
+
data = {**self._extras, "enabled": sorted(self._wanted), "params": self._params}
|
|
183
|
+
if self._filter_wanted is not None:
|
|
184
|
+
data["enabled_filters"] = sorted(self._filter_wanted)
|
|
185
|
+
if self._palette_wanted is not None:
|
|
186
|
+
data["enabled_palettes"] = sorted(self._palette_wanted)
|
|
187
|
+
if self._tool_wanted is not None:
|
|
188
|
+
data["enabled_tools"] = sorted(self._tool_wanted)
|
|
189
|
+
if self._general_wanted is not None:
|
|
190
|
+
data["enabled_general"] = sorted(self._general_wanted)
|
|
191
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
self.path.write_text(
|
|
193
|
+
json.dumps(data, indent=2) + "\n",
|
|
194
|
+
encoding="utf-8",
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def available(self, kind: str | None = None) -> dict[str, type[Plugin]]:
|
|
198
|
+
"""Return all known classes or only one kind, keyed by stable name."""
|
|
199
|
+
if self._classes is None:
|
|
200
|
+
self._classes = discover(self._error_sink)
|
|
201
|
+
return {
|
|
202
|
+
name: cls
|
|
203
|
+
for name, cls in self._classes.items()
|
|
204
|
+
if kind is None or cls.kind == kind
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
def enabled_filters(self) -> tuple[str, ...]:
|
|
208
|
+
"""Default new filters on; an explicit saved list controls their menu."""
|
|
209
|
+
names = (
|
|
210
|
+
self.available("filter").keys()
|
|
211
|
+
if self._filter_wanted is None
|
|
212
|
+
else self._filter_wanted
|
|
213
|
+
)
|
|
214
|
+
return tuple(sorted(names))
|
|
215
|
+
|
|
216
|
+
def enabled_palettes(self) -> tuple[str, ...]:
|
|
217
|
+
"""Return shown palettes; old preference files default to hidden."""
|
|
218
|
+
return tuple(sorted(self._palette_wanted or ()))
|
|
219
|
+
|
|
220
|
+
def enabled_tools(self) -> tuple[str, ...]:
|
|
221
|
+
"""Default new native tools on until the user chooses otherwise."""
|
|
222
|
+
return tuple(
|
|
223
|
+
sorted(
|
|
224
|
+
self.available("tool")
|
|
225
|
+
if self._tool_wanted is None
|
|
226
|
+
else self._tool_wanted
|
|
227
|
+
)
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
def enabled_general(self) -> tuple[str, ...]:
|
|
231
|
+
"""Default new General commands on until the user chooses otherwise."""
|
|
232
|
+
return tuple(
|
|
233
|
+
sorted(
|
|
234
|
+
self.available("general")
|
|
235
|
+
if self._general_wanted is None
|
|
236
|
+
else self._general_wanted
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def _set_kind_enabled(self, name: str, enabled: bool, kind: str) -> None:
|
|
241
|
+
"""Persist one explicit kind choice, restoring memory on I/O failure."""
|
|
242
|
+
if name not in self.available(kind):
|
|
243
|
+
raise KeyError(name)
|
|
244
|
+
field = "_tool_wanted" if kind == "tool" else "_general_wanted"
|
|
245
|
+
previous = getattr(self, field)
|
|
246
|
+
wanted = set(self.enabled_tools() if kind == "tool" else self.enabled_general())
|
|
247
|
+
wanted.add(name) if enabled else wanted.discard(name)
|
|
248
|
+
setattr(self, field, wanted)
|
|
249
|
+
try:
|
|
250
|
+
self._save()
|
|
251
|
+
except Exception:
|
|
252
|
+
setattr(self, field, previous)
|
|
253
|
+
raise
|
|
254
|
+
|
|
255
|
+
def set_tool_enabled(self, name: str, enabled: bool) -> None:
|
|
256
|
+
"""Persist whether a native tool is registered."""
|
|
257
|
+
self._set_kind_enabled(name, enabled, "tool")
|
|
258
|
+
|
|
259
|
+
def set_general_enabled(self, name: str, enabled: bool) -> None:
|
|
260
|
+
"""Persist whether a General plugin is started."""
|
|
261
|
+
self._set_kind_enabled(name, enabled, "general")
|
|
262
|
+
|
|
263
|
+
def set_palette_enabled(self, name: str, enabled: bool) -> None:
|
|
264
|
+
"""Persist an explicit panel visibility choice, rolling back on failure."""
|
|
265
|
+
if name not in self.available("palette"):
|
|
266
|
+
raise KeyError(name)
|
|
267
|
+
previous = self._palette_wanted
|
|
268
|
+
wanted = set(self.enabled_palettes())
|
|
269
|
+
wanted.add(name) if enabled else wanted.discard(name)
|
|
270
|
+
self._palette_wanted = wanted
|
|
271
|
+
try:
|
|
272
|
+
self._save()
|
|
273
|
+
except Exception:
|
|
274
|
+
self._palette_wanted = previous
|
|
275
|
+
raise
|
|
276
|
+
|
|
277
|
+
def values(self, name: str) -> dict[str, Any]:
|
|
278
|
+
"""Return validated saved filter values, falling back to defaults."""
|
|
279
|
+
cls = self.available("filter")[name]
|
|
280
|
+
try:
|
|
281
|
+
return cls.validate(self._params.get(name, {}))
|
|
282
|
+
except (TypeError, ValueError, OverflowError) as error:
|
|
283
|
+
_report(error, name, self._error_sink)
|
|
284
|
+
return cls.validate({})
|
|
285
|
+
|
|
286
|
+
def set_params(self, name: str, values: dict[str, Any]) -> None:
|
|
287
|
+
"""Validate and persist last-used filter values, rolling back on I/O failure."""
|
|
288
|
+
cls = self.available("filter")[name]
|
|
289
|
+
previous = self._params.get(name)
|
|
290
|
+
self._params[name] = cls.validate(values)
|
|
291
|
+
try:
|
|
292
|
+
self._save()
|
|
293
|
+
except Exception:
|
|
294
|
+
if previous is None:
|
|
295
|
+
del self._params[name]
|
|
296
|
+
else:
|
|
297
|
+
self._params[name] = previous
|
|
298
|
+
raise
|
|
299
|
+
|
|
300
|
+
def set_filter_enabled(self, name: str, enabled: bool) -> None:
|
|
301
|
+
"""Persist whether a filter contributes its Glyph-menu command."""
|
|
302
|
+
if name not in self.available("filter"):
|
|
303
|
+
raise KeyError(name)
|
|
304
|
+
previous = self._filter_wanted
|
|
305
|
+
wanted = set(self.enabled_filters())
|
|
306
|
+
wanted.add(name) if enabled else wanted.discard(name)
|
|
307
|
+
self._filter_wanted = wanted
|
|
308
|
+
try:
|
|
309
|
+
self._save()
|
|
310
|
+
except Exception:
|
|
311
|
+
self._filter_wanted = previous
|
|
312
|
+
raise
|
|
313
|
+
|
|
314
|
+
def enabled(self) -> tuple[str, ...]:
|
|
315
|
+
"""Return names requested as enabled, including pending restoration."""
|
|
316
|
+
return tuple(sorted(self._wanted))
|
|
317
|
+
|
|
318
|
+
def attach(self, painters: Any, qt: Any, sink: Any) -> None:
|
|
319
|
+
"""Bind restored reporters to one App painter owner."""
|
|
320
|
+
if self._painters is painters:
|
|
321
|
+
return
|
|
322
|
+
self.detach()
|
|
323
|
+
self._painters, self._qt, self._sink = painters, qt, sink
|
|
324
|
+
for name in sorted(self._wanted & self.available("reporter").keys()):
|
|
325
|
+
try:
|
|
326
|
+
self._activate(name)
|
|
327
|
+
except Exception as error: # noqa: BLE001 - one plugin cannot block restore
|
|
328
|
+
_report(error, name, self._error_sink)
|
|
329
|
+
|
|
330
|
+
def detach(self) -> None:
|
|
331
|
+
"""Remove active painters while retaining saved enabled names."""
|
|
332
|
+
try:
|
|
333
|
+
if self._painters is not None:
|
|
334
|
+
for token in tuple(self._tokens.values()):
|
|
335
|
+
try:
|
|
336
|
+
self._painters.remove(token)
|
|
337
|
+
except Exception as error: # noqa: BLE001 - teardown boundary
|
|
338
|
+
_report(error, token, self._error_sink)
|
|
339
|
+
finally:
|
|
340
|
+
self._tokens.clear()
|
|
341
|
+
self._painters = self._qt = self._sink = None
|
|
342
|
+
|
|
343
|
+
def _activate(self, name: str) -> None:
|
|
344
|
+
"""Install a single reporter if a painter owner exists."""
|
|
345
|
+
if self._painters is not None and name not in self._tokens:
|
|
346
|
+
plugin = self.available()[name]()
|
|
347
|
+
self._tokens[name] = plugin.bind(self._painters, self._qt, self._sink)
|
|
348
|
+
|
|
349
|
+
def enable(self, name: str) -> bool:
|
|
350
|
+
"""Enable a reporter, rolling its overlay back if persistence fails."""
|
|
351
|
+
if name not in self.available("reporter"):
|
|
352
|
+
raise KeyError(name)
|
|
353
|
+
if name in self._wanted:
|
|
354
|
+
self._activate(name)
|
|
355
|
+
return True
|
|
356
|
+
self._wanted.add(name)
|
|
357
|
+
try:
|
|
358
|
+
self._activate(name)
|
|
359
|
+
self._save()
|
|
360
|
+
except Exception:
|
|
361
|
+
self._wanted.remove(name)
|
|
362
|
+
token = self._tokens.pop(name, None)
|
|
363
|
+
if token is not None and self._painters is not None:
|
|
364
|
+
try:
|
|
365
|
+
self._painters.remove(token)
|
|
366
|
+
except Exception as error: # noqa: BLE001 - retain save error
|
|
367
|
+
_report(error, token, self._error_sink)
|
|
368
|
+
raise
|
|
369
|
+
return True
|
|
370
|
+
|
|
371
|
+
def disable(self, name: str) -> bool:
|
|
372
|
+
"""Disable a known reporter and remove its painter token."""
|
|
373
|
+
if name not in self.available("reporter"):
|
|
374
|
+
raise KeyError(name)
|
|
375
|
+
if name in self._wanted:
|
|
376
|
+
self._wanted.remove(name)
|
|
377
|
+
try:
|
|
378
|
+
self._save()
|
|
379
|
+
except Exception:
|
|
380
|
+
self._wanted.add(name)
|
|
381
|
+
raise
|
|
382
|
+
token = self._tokens.pop(name, None)
|
|
383
|
+
if token is not None and self._painters is not None:
|
|
384
|
+
self._painters.remove(token)
|
|
385
|
+
return False
|
|
386
|
+
|
|
387
|
+
def toggle(self, name: str) -> bool:
|
|
388
|
+
"""Switch a reporter and return the new checked state."""
|
|
389
|
+
return self.disable(name) if name in self._wanted else self.enable(name)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
_current: Registry | None = None
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def configure(
|
|
396
|
+
config_dir: str | Path | None = None, error_sink: ErrorSink | None = None
|
|
397
|
+
) -> Registry:
|
|
398
|
+
"""Select the process registry; boot calls this once per installation."""
|
|
399
|
+
global _current
|
|
400
|
+
_current = Registry(config_dir, error_sink)
|
|
401
|
+
return _current
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def current() -> Registry:
|
|
405
|
+
"""Lazily create the default registry without writing preferences."""
|
|
406
|
+
global _current
|
|
407
|
+
if _current is None:
|
|
408
|
+
_current = Registry()
|
|
409
|
+
return _current
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def available(kind: str | None = None) -> dict[str, type[Plugin]]:
|
|
413
|
+
"""Discover all plugins or only those of one kind."""
|
|
414
|
+
return current().available(kind)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def enabled() -> tuple[str, ...]:
|
|
418
|
+
"""Return saved enabled names."""
|
|
419
|
+
return current().enabled()
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def enable(name: str) -> bool:
|
|
423
|
+
"""Enable a reporter."""
|
|
424
|
+
return current().enable(name)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def disable(name: str) -> bool:
|
|
428
|
+
"""Disable a reporter."""
|
|
429
|
+
return current().disable(name)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def toggle(name: str) -> bool:
|
|
433
|
+
"""Toggle a reporter."""
|
|
434
|
+
return current().toggle(name)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/reporter.py
|
|
2
|
+
"""Pure mark protocol and guarded rendering through backend contexts."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from itertools import pairwise
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
from .plugin import Plugin
|
|
10
|
+
from .snapshot import GlyphSnapshot
|
|
11
|
+
|
|
12
|
+
Point = tuple[float, float]
|
|
13
|
+
Color = tuple[int, int, int]
|
|
14
|
+
Kind = Literal["ring", "line", "text", "polyline", "polygon"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Mark:
|
|
19
|
+
"""Glyph-unit points with pixel-sized stroke, text and ring diameter."""
|
|
20
|
+
|
|
21
|
+
kind: Kind
|
|
22
|
+
points: tuple[Point, ...]
|
|
23
|
+
color: Color = (220, 50, 45)
|
|
24
|
+
stroke_px: float = 1.5
|
|
25
|
+
text: str = ""
|
|
26
|
+
text_px: int = 12
|
|
27
|
+
diameter_px: float = 16.0
|
|
28
|
+
fill: tuple[int, int, int, int] | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _view_point(context: Any, qt: Any, point: Point) -> Any:
|
|
32
|
+
"""Map glyph units through both native transforms into view pixels."""
|
|
33
|
+
native = qt.QtCore.QPointF(*point)
|
|
34
|
+
return context.canvas_to_view.map(context.glyph_to_canvas.map(native))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _draw(mark: Mark, context: Any, qt: Any) -> None:
|
|
38
|
+
"""Draw one mark without changing the context's world transform."""
|
|
39
|
+
painter = context.painter
|
|
40
|
+
if mark.kind == "polygon" and len(mark.points) < 3:
|
|
41
|
+
return
|
|
42
|
+
points = tuple(_view_point(context, qt, p) for p in mark.points)
|
|
43
|
+
if mark.kind == "polygon":
|
|
44
|
+
if mark.fill is None:
|
|
45
|
+
raise ValueError("Polygon mark needs an RGBA fill")
|
|
46
|
+
painter.save()
|
|
47
|
+
try:
|
|
48
|
+
painter.setPen(qt.QtCore.Qt.NoPen)
|
|
49
|
+
painter.setBrush(qt.QtGui.QColor(*mark.fill))
|
|
50
|
+
painter.drawPolygon(qt.QtGui.QPolygonF(list(points)))
|
|
51
|
+
finally:
|
|
52
|
+
painter.restore()
|
|
53
|
+
return
|
|
54
|
+
pen = qt.QtGui.QPen(qt.QtGui.QColor(*mark.color))
|
|
55
|
+
pen.setWidthF(mark.stroke_px)
|
|
56
|
+
painter.setPen(pen)
|
|
57
|
+
if mark.kind == "ring":
|
|
58
|
+
painter.setBrush(qt.QtGui.QBrush())
|
|
59
|
+
p, radius = points[0], mark.diameter_px / 2
|
|
60
|
+
painter.drawEllipse(
|
|
61
|
+
qt.QtCore.QRectF(p.x() - radius, p.y() - radius, radius * 2, radius * 2)
|
|
62
|
+
)
|
|
63
|
+
elif mark.kind == "text":
|
|
64
|
+
font = qt.QtGui.QFont()
|
|
65
|
+
font.setPixelSize(mark.text_px)
|
|
66
|
+
painter.setFont(font)
|
|
67
|
+
painter.drawText(points[0], mark.text)
|
|
68
|
+
elif mark.kind in {"line", "polyline"}:
|
|
69
|
+
for start, end in pairwise(points):
|
|
70
|
+
painter.drawLine(start, end)
|
|
71
|
+
else:
|
|
72
|
+
raise ValueError(f"Unknown mark kind: {mark.kind}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def render_marks(marks: list[Mark], context: Any, qt: Any) -> None:
|
|
76
|
+
"""Paint marks in view coordinates, preserving view-pixel widths."""
|
|
77
|
+
for mark in marks:
|
|
78
|
+
_draw(mark, context, qt)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Reporter(Plugin):
|
|
82
|
+
"""Subclass with a name, title and pure ``compute(snapshot)`` method."""
|
|
83
|
+
|
|
84
|
+
name = ""
|
|
85
|
+
title = ""
|
|
86
|
+
kind = "reporter"
|
|
87
|
+
layer: Literal["foreground", "background"] = "foreground"
|
|
88
|
+
needs_zones = False
|
|
89
|
+
needs_bounds = False
|
|
90
|
+
|
|
91
|
+
def compute(self, snapshot: GlyphSnapshot) -> list[Mark]:
|
|
92
|
+
"""Return marks for one glyph occurrence."""
|
|
93
|
+
raise NotImplementedError
|
|
94
|
+
|
|
95
|
+
def paint(
|
|
96
|
+
self,
|
|
97
|
+
context: Any,
|
|
98
|
+
qt: Any,
|
|
99
|
+
sink: Callable[[Exception, object], object],
|
|
100
|
+
capture: Callable[[Any], GlyphSnapshot] | None = None,
|
|
101
|
+
) -> None:
|
|
102
|
+
"""Never allow capture, computation or Qt errors into paintEvent."""
|
|
103
|
+
try:
|
|
104
|
+
if context.layer is None:
|
|
105
|
+
return
|
|
106
|
+
if capture is None:
|
|
107
|
+
from . import snapshot
|
|
108
|
+
|
|
109
|
+
data = snapshot.capture(
|
|
110
|
+
context.layer,
|
|
111
|
+
include_zones=self.needs_zones,
|
|
112
|
+
include_bounds=self.needs_bounds,
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
data = capture(context.layer)
|
|
116
|
+
render_marks(self.compute(data), context, qt)
|
|
117
|
+
except Exception as error: # noqa: BLE001 - Qt paint boundary must not raise
|
|
118
|
+
try:
|
|
119
|
+
sink(error, self)
|
|
120
|
+
except Exception: # noqa: BLE001, S110 - even an error sink must not unwind
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
def bind(
|
|
124
|
+
self, painters: Any, qt: Any, sink: Callable[[Exception, object], object]
|
|
125
|
+
) -> int:
|
|
126
|
+
"""Register with the selected native or fallback painter backend."""
|
|
127
|
+
return painters.register(self, qt, sink)
|