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,158 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/filters/apply.py
|
|
2
|
+
"""Plan deletion-only LayerEdits and commit them through fontlabapp's writer."""
|
|
3
|
+
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fontlab_plugmix import snapshot
|
|
8
|
+
from fontlab_plugmix.filter import Filter, LayerEdit
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _removed(before: snapshot.GlyphSnapshot, edit: LayerEdit) -> tuple[int, ...]:
|
|
12
|
+
"""Resolve retained snapshot contour identities; reject unsupported writes."""
|
|
13
|
+
if edit.advance is not None or edit.anchors is not None:
|
|
14
|
+
raise ValueError("This Filter host currently supports contour deletion only")
|
|
15
|
+
if edit.contours is None:
|
|
16
|
+
return ()
|
|
17
|
+
original = {id(contour) for contour in before.contours}
|
|
18
|
+
kept = [id(contour) for contour in edit.contours]
|
|
19
|
+
if len(set(kept)) != len(kept) or not set(kept) <= original:
|
|
20
|
+
raise ValueError("Filter returned new or repeated contours")
|
|
21
|
+
keep_set = set(kept)
|
|
22
|
+
if kept != [id(contour) for contour in before.contours if id(contour) in keep_set]:
|
|
23
|
+
raise ValueError("This Filter host cannot reorder contours")
|
|
24
|
+
return tuple(
|
|
25
|
+
index
|
|
26
|
+
for index, contour in enumerate(before.contours)
|
|
27
|
+
if id(contour) not in kept
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _targets_safe(layer: Any, removed: tuple[int, ...], outlines: Any) -> bool:
|
|
32
|
+
"""Allow deletion only from owned, unshared and untransformed shapes."""
|
|
33
|
+
allowed = {int(shape.id) for shape in outlines.outline_shapes(layer)[0]}
|
|
34
|
+
owners = [
|
|
35
|
+
shape
|
|
36
|
+
for shape in layer.shapes
|
|
37
|
+
if not shape.isComponent
|
|
38
|
+
for _contour in shape.contours
|
|
39
|
+
]
|
|
40
|
+
return all(
|
|
41
|
+
index < len(owners) and int(owners[index].id) in allowed for index in removed
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def plan_filter(
|
|
46
|
+
plugin: Filter, values: dict[str, Any], selected: Any, outlines: Any, history: Any
|
|
47
|
+
) -> tuple[Any, Any]:
|
|
48
|
+
"""Use outline_writer's auto-layer policy for selected current-master glyphs."""
|
|
49
|
+
if not selected.occurrences:
|
|
50
|
+
return outlines.Plan(), None
|
|
51
|
+
package = selected.occurrences[0].package
|
|
52
|
+
master = str(package.master)
|
|
53
|
+
glyphs = list(
|
|
54
|
+
{int(row.glyph.id): row.glyph for row in selected.occurrences}.values()
|
|
55
|
+
)
|
|
56
|
+
facts = history.scan_auto_facts(package)
|
|
57
|
+
unsafe: list[str] = []
|
|
58
|
+
|
|
59
|
+
def planner(glyph: Any, master_name: str, layer: Any) -> list[Any]:
|
|
60
|
+
before = snapshot.capture(snapshot.NativeSource(package, layer))
|
|
61
|
+
removed = _removed(before, plugin.compute(before, values))
|
|
62
|
+
if not removed:
|
|
63
|
+
return []
|
|
64
|
+
if not _targets_safe(layer, removed, outlines):
|
|
65
|
+
unsafe.append(str(glyph.name))
|
|
66
|
+
return [
|
|
67
|
+
outlines.Change(
|
|
68
|
+
"contours",
|
|
69
|
+
str(len(before.contours)),
|
|
70
|
+
"shared or transformed outline, skipped",
|
|
71
|
+
)
|
|
72
|
+
]
|
|
73
|
+
return [
|
|
74
|
+
outlines.Change(
|
|
75
|
+
"contours",
|
|
76
|
+
str(len(before.contours)),
|
|
77
|
+
str(len(before.contours) - len(removed)),
|
|
78
|
+
edit=removed,
|
|
79
|
+
key=removed,
|
|
80
|
+
)
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
plan = outlines.collect(glyphs, [master], planner, facts)
|
|
84
|
+
plan.refused.extend(unsafe)
|
|
85
|
+
return plan, facts
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class LayerEditEditor:
|
|
89
|
+
"""Remove own native contours, retaining them for one Undo step."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, outlines: Any) -> None:
|
|
92
|
+
self.outlines = outlines
|
|
93
|
+
|
|
94
|
+
def prepare(
|
|
95
|
+
self, layer: Any, edits: list[tuple[int, ...]]
|
|
96
|
+
) -> list[tuple[Any, Any, int]]:
|
|
97
|
+
"""Resolve and validate all deletion targets before opening history."""
|
|
98
|
+
allowed = {int(shape.id) for shape in self.outlines.outline_shapes(layer)[0]}
|
|
99
|
+
rows = [
|
|
100
|
+
(shape, contour)
|
|
101
|
+
for shape in layer.shapes
|
|
102
|
+
if not shape.isComponent
|
|
103
|
+
for contour in shape.contours
|
|
104
|
+
]
|
|
105
|
+
indices = {index for group in edits for index in group}
|
|
106
|
+
if any(
|
|
107
|
+
index >= len(rows) or int(rows[index][0].id) not in allowed
|
|
108
|
+
for index in indices
|
|
109
|
+
):
|
|
110
|
+
raise ValueError("Filter cannot edit a shared or transformed outline")
|
|
111
|
+
return [
|
|
112
|
+
(*rows[index], int(rows[index][1].id))
|
|
113
|
+
for index in sorted(indices, reverse=True)
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
def write(self, layer: Any, steps: list[tuple[Any, Any, int]]) -> None:
|
|
117
|
+
"""Remove selected contours from their native owning shapes."""
|
|
118
|
+
for shape, contour, _identifier in steps:
|
|
119
|
+
shape.removeContour(contour)
|
|
120
|
+
|
|
121
|
+
def check(
|
|
122
|
+
self, prepared: list[tuple[Any, list[tuple[Any, Any, int]]]]
|
|
123
|
+
) -> list[str]:
|
|
124
|
+
"""Detect a native writer that retained a supposedly deleted contour."""
|
|
125
|
+
return [
|
|
126
|
+
"contour remained after Filter write"
|
|
127
|
+
for _, steps in prepared
|
|
128
|
+
for shape, _contour, identifier in steps
|
|
129
|
+
if any(int(item.id) == identifier for item in shape.contours)
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
def retain(self, steps: list[tuple[Any, Any, int]]) -> list[Any]:
|
|
133
|
+
"""Pin removed native contours for FontLab's deep history notification."""
|
|
134
|
+
return [contour for _, contour, _identifier in steps]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def apply_filter(
|
|
138
|
+
plugin: Filter,
|
|
139
|
+
values: dict[str, Any],
|
|
140
|
+
*,
|
|
141
|
+
selected: Any = None,
|
|
142
|
+
outlines: Any = None,
|
|
143
|
+
writer: Any = None,
|
|
144
|
+
history: Any = None,
|
|
145
|
+
) -> tuple[Any, Any]:
|
|
146
|
+
"""Apply one selected-layer plan with exactly one geometry history commit."""
|
|
147
|
+
values = type(plugin).validate(values)
|
|
148
|
+
selected = selected if selected is not None else snapshot.selected_layers()
|
|
149
|
+
outlines = outlines or import_module("fontlabapp.outline_writer")
|
|
150
|
+
writer = writer or import_module("fontlabapp.layer_writer")
|
|
151
|
+
history = history or import_module("fontlabapp.history")
|
|
152
|
+
plan, facts = plan_filter(plugin, values, selected, outlines, history)
|
|
153
|
+
if not plan.work:
|
|
154
|
+
return plan, None
|
|
155
|
+
result = writer.apply_work(
|
|
156
|
+
plan.work, plugin.title, facts, LayerEditEditor(outlines)
|
|
157
|
+
)
|
|
158
|
+
return plan, result
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/filters/delete_small_paths.py
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Remove closed contours whose flattened area or bounds are small."""
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from itertools import pairwise
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from fontlab_plugmix.filter import Filter, LayerEdit, Param
|
|
10
|
+
from fontlab_plugmix.geometry import point_at, segments
|
|
11
|
+
from fontlab_plugmix.snapshot import Contour, GlyphSnapshot
|
|
12
|
+
|
|
13
|
+
FLATTEN_STEPS = 25
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _path_points(contour: Contour) -> tuple[tuple[float, float], ...] | None:
|
|
17
|
+
"""Flatten each supported segment; None means an unsupported control run."""
|
|
18
|
+
runs = segments(contour)
|
|
19
|
+
if len(runs) != sum(node.on_curve for node in contour.nodes):
|
|
20
|
+
return None
|
|
21
|
+
points = []
|
|
22
|
+
for run in runs:
|
|
23
|
+
count = 1 if len(run) == 2 else FLATTEN_STEPS
|
|
24
|
+
points.extend(point_at(run, index / count) for index in range(1, count + 1))
|
|
25
|
+
return tuple(points)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _small(contour: Contour, threshold: float) -> bool:
|
|
29
|
+
"""Measure flattened ink area and bounds, excluding Bézier controls."""
|
|
30
|
+
if not contour.closed:
|
|
31
|
+
return False
|
|
32
|
+
if len(contour.nodes) < 3:
|
|
33
|
+
return threshold > 0
|
|
34
|
+
points = _path_points(contour)
|
|
35
|
+
if not points:
|
|
36
|
+
return False
|
|
37
|
+
area = (
|
|
38
|
+
abs(sum(a[0] * b[1] - b[0] * a[1] for a, b in pairwise((*points, points[0]))))
|
|
39
|
+
/ 2
|
|
40
|
+
)
|
|
41
|
+
xs, ys = zip(*points, strict=True)
|
|
42
|
+
bounds_area = (max(xs) - min(xs)) * (max(ys) - min(ys))
|
|
43
|
+
return area < threshold or bounds_area < threshold
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DeleteSmallPaths(Filter):
|
|
47
|
+
"""Drop closed contours smaller than the supplied area threshold."""
|
|
48
|
+
|
|
49
|
+
name = "delete_small_paths"
|
|
50
|
+
title = "Delete Small Paths"
|
|
51
|
+
params = (Param("threshold", "Maximum area", "float", 400.0, minimum=0.0),)
|
|
52
|
+
|
|
53
|
+
def compute(self, snapshot: GlyphSnapshot, values: Mapping[str, Any]) -> LayerEdit:
|
|
54
|
+
"""Keep open paths and contours at or above the threshold."""
|
|
55
|
+
threshold = self.validate(values)["threshold"]
|
|
56
|
+
kept = tuple(c for c in snapshot.contours if not _small(c, threshold))
|
|
57
|
+
return LayerEdit(contours=kept if len(kept) != len(snapshot.contours) else None)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/filters/dialog.py
|
|
2
|
+
"""Small owned, non-modal PythonQt dialog built from Filter Params."""
|
|
3
|
+
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fontlab_plugmix.filter import Filter, Param
|
|
8
|
+
from fontlab_plugmix.kinds import guarded
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _control(gui: Any, param: Param, value: Any, parent: Any) -> Any:
|
|
12
|
+
"""Create one typed Qt editor for a declarative parameter."""
|
|
13
|
+
if param.kind in {"float", "int"}:
|
|
14
|
+
widget = (gui.QDoubleSpinBox if param.kind == "float" else gui.QSpinBox)(parent)
|
|
15
|
+
if param.kind == "float":
|
|
16
|
+
widget.setDecimals(3)
|
|
17
|
+
low = param.minimum if param.minimum is not None else -1_000_000
|
|
18
|
+
high = param.maximum if param.maximum is not None else 1_000_000
|
|
19
|
+
if param.kind == "float":
|
|
20
|
+
widget.setRange(float(low), float(high))
|
|
21
|
+
else:
|
|
22
|
+
widget.setRange(int(low), int(high))
|
|
23
|
+
widget.setValue(value)
|
|
24
|
+
elif param.kind == "bool":
|
|
25
|
+
widget = gui.QCheckBox(parent)
|
|
26
|
+
widget.setChecked(value)
|
|
27
|
+
else:
|
|
28
|
+
widget = gui.QComboBox(parent)
|
|
29
|
+
widget.addItems(list(param.choices))
|
|
30
|
+
widget.setCurrentIndex(param.choices.index(value))
|
|
31
|
+
return widget
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _value(widget: Any, kind: str) -> Any:
|
|
35
|
+
"""Read a control without relying on PythonQt property-call ambiguity."""
|
|
36
|
+
field = (
|
|
37
|
+
"value"
|
|
38
|
+
if kind in {"float", "int"}
|
|
39
|
+
else ("isChecked" if kind == "bool" else "currentText")
|
|
40
|
+
)
|
|
41
|
+
found = getattr(widget, field)
|
|
42
|
+
return found() if callable(found) else found
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class FilterDialog:
|
|
46
|
+
"""Own signal connections and expose the widget to OwnedMenus.tool_window."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
qt: Any,
|
|
51
|
+
plugin: Filter,
|
|
52
|
+
values: dict[str, Any],
|
|
53
|
+
on_apply: Callable[[dict[str, Any]], Any],
|
|
54
|
+
on_cancel: Callable[[], Any],
|
|
55
|
+
sink: Callable[[Exception, object], object],
|
|
56
|
+
) -> None:
|
|
57
|
+
gui = qt.QtGui
|
|
58
|
+
self.plugin, self.sink = plugin, sink
|
|
59
|
+
self.widget = gui.QWidget()
|
|
60
|
+
self.controls: dict[str, tuple[Param, Any]] = {}
|
|
61
|
+
self.connections: list[tuple[Any, Any]] = []
|
|
62
|
+
layout = gui.QVBoxLayout(self.widget)
|
|
63
|
+
form = gui.QFormLayout()
|
|
64
|
+
layout.addLayout(form)
|
|
65
|
+
for param in plugin.params:
|
|
66
|
+
control = _control(gui, param, values[param.key], self.widget)
|
|
67
|
+
self.controls[param.key] = (param, control)
|
|
68
|
+
form.addRow(param.label, control)
|
|
69
|
+
self.status = gui.QLabel("", self.widget)
|
|
70
|
+
layout.addWidget(self.status)
|
|
71
|
+
buttons = gui.QHBoxLayout()
|
|
72
|
+
layout.addLayout(buttons)
|
|
73
|
+
cancel, apply = (
|
|
74
|
+
gui.QPushButton("Cancel", self.widget),
|
|
75
|
+
gui.QPushButton("Apply", self.widget),
|
|
76
|
+
)
|
|
77
|
+
buttons.addWidget(cancel)
|
|
78
|
+
buttons.addWidget(apply)
|
|
79
|
+
self._connect(
|
|
80
|
+
cancel.clicked, lambda *args: guarded(plugin, self._report, on_cancel)
|
|
81
|
+
)
|
|
82
|
+
self._connect(
|
|
83
|
+
apply.clicked,
|
|
84
|
+
lambda *args: guarded(
|
|
85
|
+
plugin, self._report, lambda: on_apply(self.values())
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _report(self, error: Exception, source: object) -> None:
|
|
90
|
+
"""Show an Apply failure and forward it to the host's error sink."""
|
|
91
|
+
try:
|
|
92
|
+
self.status.setText(str(error))
|
|
93
|
+
except Exception: # noqa: BLE001, S110 - keep forwarding the cause
|
|
94
|
+
pass
|
|
95
|
+
self.sink(error, source)
|
|
96
|
+
|
|
97
|
+
def _connect(self, signal: Any, callback: Callable[..., Any]) -> None:
|
|
98
|
+
signal.connect(callback)
|
|
99
|
+
self.connections.append((signal, callback))
|
|
100
|
+
|
|
101
|
+
def values(self) -> dict[str, Any]:
|
|
102
|
+
"""Read and validate every control before Apply."""
|
|
103
|
+
raw = {
|
|
104
|
+
key: _value(widget, param.kind)
|
|
105
|
+
for key, (param, widget) in self.controls.items()
|
|
106
|
+
}
|
|
107
|
+
return type(self.plugin).validate(raw)
|
|
108
|
+
|
|
109
|
+
def close(self) -> None:
|
|
110
|
+
"""Disconnect before OwnedMenus schedules widget teardown; repeat safely."""
|
|
111
|
+
for signal, callback in self.connections:
|
|
112
|
+
try:
|
|
113
|
+
signal.disconnect(callback)
|
|
114
|
+
except Exception as error: # noqa: BLE001 - stale PythonQt receiver
|
|
115
|
+
try:
|
|
116
|
+
self.sink(error, self.plugin)
|
|
117
|
+
except Exception: # noqa: BLE001, S110 - teardown must finish
|
|
118
|
+
pass
|
|
119
|
+
self.connections.clear()
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/filters/host.py
|
|
2
|
+
"""Own Glyph-menu Filter actions and their parameter dialogs."""
|
|
3
|
+
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from fontlab_plugmix import snapshot
|
|
8
|
+
from fontlab_plugmix.kinds import Services, guarded
|
|
9
|
+
|
|
10
|
+
from .apply import apply_filter
|
|
11
|
+
from .dialog import FilterDialog
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FilterHost:
|
|
15
|
+
"""Bind filters to owned actions and guarded Apply callbacks."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, services: Services, registry: Any) -> None:
|
|
18
|
+
self.services, self.registry = services, registry
|
|
19
|
+
self.actions: list[int] = []
|
|
20
|
+
self.windows: dict[int, FilterDialog] = {}
|
|
21
|
+
|
|
22
|
+
def install(self) -> None:
|
|
23
|
+
"""Add one non-checkable Glyph command for every enabled filter."""
|
|
24
|
+
for name in self.registry.enabled_filters():
|
|
25
|
+
cls = self.registry.available("filter").get(name)
|
|
26
|
+
if cls is None:
|
|
27
|
+
continue
|
|
28
|
+
token = self.services.menus.add_action(
|
|
29
|
+
"Glyph",
|
|
30
|
+
f"Plugmix: {cls.title}…",
|
|
31
|
+
lambda name=name, cls=cls: guarded(
|
|
32
|
+
cls, self.services.sink, lambda: self.run(name)
|
|
33
|
+
),
|
|
34
|
+
checkable=False,
|
|
35
|
+
)
|
|
36
|
+
self.actions.append(token)
|
|
37
|
+
|
|
38
|
+
def run(self, name: str) -> None:
|
|
39
|
+
"""Open on a selection; Apply re-reads the selection at click time."""
|
|
40
|
+
selected = snapshot.selected_layers()
|
|
41
|
+
if not selected.occurrences:
|
|
42
|
+
return
|
|
43
|
+
plugin = self.registry.available("filter")[name]()
|
|
44
|
+
token_box: list[int] = []
|
|
45
|
+
|
|
46
|
+
def close() -> None:
|
|
47
|
+
# OwnedMenus cannot remove a tool window inside our button signal.
|
|
48
|
+
self.services.qt.QtCore.QTimer.singleShot(
|
|
49
|
+
0,
|
|
50
|
+
lambda: guarded(
|
|
51
|
+
plugin,
|
|
52
|
+
self.services.sink,
|
|
53
|
+
lambda: self.services.menus.remove(token_box[0]),
|
|
54
|
+
),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def apply(values: dict[str, Any]) -> None:
|
|
58
|
+
"""Save a preference opportunistically, then edit the live selection."""
|
|
59
|
+
guarded(
|
|
60
|
+
plugin,
|
|
61
|
+
self.services.sink,
|
|
62
|
+
lambda: self.registry.set_params(name, values),
|
|
63
|
+
)
|
|
64
|
+
plan, result = apply_filter(plugin, values)
|
|
65
|
+
if result is None and (plan.refused or plan.skipped):
|
|
66
|
+
dialog.status.setText(
|
|
67
|
+
"Skipped: " + ", ".join((*plan.refused, *plan.skipped))
|
|
68
|
+
)
|
|
69
|
+
return
|
|
70
|
+
if result is not None:
|
|
71
|
+
self.services.fontlab.UpdateActiveCanvas()
|
|
72
|
+
if plan.refused or plan.skipped:
|
|
73
|
+
dialog.status.setText(
|
|
74
|
+
"Skipped: " + ", ".join((*plan.refused, *plan.skipped))
|
|
75
|
+
)
|
|
76
|
+
return
|
|
77
|
+
close()
|
|
78
|
+
|
|
79
|
+
dialog = FilterDialog(
|
|
80
|
+
self.services.qt,
|
|
81
|
+
plugin,
|
|
82
|
+
self.registry.values(name),
|
|
83
|
+
apply,
|
|
84
|
+
close,
|
|
85
|
+
self.services.sink,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def finished() -> None:
|
|
89
|
+
dialog.close()
|
|
90
|
+
if token_box:
|
|
91
|
+
self.windows.pop(token_box[0], None)
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
# PythonQt exposes the sizeHint Q_PROPERTY as a QSize value, not a method.
|
|
95
|
+
size = import_module("fontlabapp.qt_properties").value(dialog.widget, "sizeHint")
|
|
96
|
+
dialog.widget.resize(size)
|
|
97
|
+
token, window = self.services.menus.tool_window(
|
|
98
|
+
dialog.widget, plugin.title, on_close=finished
|
|
99
|
+
)
|
|
100
|
+
token_box.append(token)
|
|
101
|
+
self.windows[token] = dialog
|
|
102
|
+
window.resize(size)
|
|
103
|
+
except Exception:
|
|
104
|
+
if token_box:
|
|
105
|
+
self.services.menus.remove(token_box[0])
|
|
106
|
+
dialog.close()
|
|
107
|
+
raise
|
|
108
|
+
|
|
109
|
+
def close(self) -> None:
|
|
110
|
+
"""Remove windows and commands before their OwnedMenus owner closes."""
|
|
111
|
+
for token in (*self.windows, *self.actions):
|
|
112
|
+
try:
|
|
113
|
+
self.services.menus.remove(token)
|
|
114
|
+
except Exception as error: # noqa: BLE001 - teardown boundary
|
|
115
|
+
try:
|
|
116
|
+
self.services.sink(error, self)
|
|
117
|
+
except Exception: # noqa: BLE001, S110 - sink cannot block teardown
|
|
118
|
+
pass
|
|
119
|
+
self.windows.clear()
|
|
120
|
+
self.actions.clear()
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# this_file: src/fontlab_plugmix/general.py
|
|
2
|
+
"""Menu-oriented General plugin contract and owned runtime helpers."""
|
|
3
|
+
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
from typing import Any, ClassVar
|
|
6
|
+
|
|
7
|
+
from . import snapshot
|
|
8
|
+
from .backend import active_glyph_map
|
|
9
|
+
from .kinds import guarded
|
|
10
|
+
from .plugin import Plugin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _ActionOwner:
|
|
14
|
+
"""Keep extra actions added by a General plugin within its lifetime."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, menus: Any, sink: Any, plugin: Plugin) -> None:
|
|
17
|
+
self.menus, self.sink, self.plugin = menus, sink, plugin
|
|
18
|
+
self.tokens: list[int] = []
|
|
19
|
+
|
|
20
|
+
def add_action(self, *args: Any, **kwargs: Any) -> int:
|
|
21
|
+
"""Record an additional owned action for automatic teardown."""
|
|
22
|
+
token = self.menus.add_action(*args, **kwargs)
|
|
23
|
+
self.tokens.append(token)
|
|
24
|
+
return token
|
|
25
|
+
|
|
26
|
+
def __getattr__(self, name: str) -> Any:
|
|
27
|
+
return getattr(self.menus, name)
|
|
28
|
+
|
|
29
|
+
def remove(self, token: int) -> None:
|
|
30
|
+
"""Avoid removing an action twice if the plugin already closed it."""
|
|
31
|
+
self.menus.remove(token)
|
|
32
|
+
if token in self.tokens:
|
|
33
|
+
self.tokens.remove(token)
|
|
34
|
+
|
|
35
|
+
def close(self) -> None:
|
|
36
|
+
"""Remove extra actions even when one removal fails."""
|
|
37
|
+
for token in reversed(self.tokens):
|
|
38
|
+
guarded(
|
|
39
|
+
self.plugin, self.sink, lambda token=token: self.menus.remove(token)
|
|
40
|
+
)
|
|
41
|
+
self.tokens.clear()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class GeneralContext:
|
|
45
|
+
"""Expose menus, status, snapshot, edit and owned timers to a General."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, services: Any, plugin: Plugin) -> None:
|
|
48
|
+
self.services, self.plugin = services, plugin
|
|
49
|
+
self.menus = _ActionOwner(services.menus, services.sink, plugin)
|
|
50
|
+
self._timers: list[tuple[Any, Any]] = []
|
|
51
|
+
|
|
52
|
+
def notify(self, title: str, message: str) -> None:
|
|
53
|
+
"""Put a short status message in FontLab's main window."""
|
|
54
|
+
self.menus.main_window().statusBar().showMessage(f"{title}: {message}")
|
|
55
|
+
|
|
56
|
+
def snapshot(self) -> snapshot.GlyphSnapshot | None:
|
|
57
|
+
"""Capture the current glyph through the flWorkspace route."""
|
|
58
|
+
active = snapshot.active_glyph(self.services.fontlab)
|
|
59
|
+
if active is None:
|
|
60
|
+
return None
|
|
61
|
+
return snapshot.capture(
|
|
62
|
+
snapshot.NativeSource(active.package, active.layer),
|
|
63
|
+
fontlab=self.services.fontlab,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def edit(self, plan_fn: Any, title: str) -> Any:
|
|
67
|
+
"""Commit a prepared geometry plan as one App history operation."""
|
|
68
|
+
work, facts, editor = plan_fn(self.snapshot())
|
|
69
|
+
return import_module("fontlabapp.layer_writer").apply_work(
|
|
70
|
+
work, title, facts, editor
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def timer(self, ms: int, fn: Any) -> Any:
|
|
74
|
+
"""Start an owned timer whose callback cannot escape into Qt."""
|
|
75
|
+
timer = self.services.qt.QtCore.QTimer()
|
|
76
|
+
tick = lambda: guarded(self.plugin, self.services.sink, fn)
|
|
77
|
+
try:
|
|
78
|
+
timer.setInterval(ms)
|
|
79
|
+
timer.timeout.connect(tick)
|
|
80
|
+
timer.start()
|
|
81
|
+
except Exception:
|
|
82
|
+
guarded(self.plugin, self.services.sink, timer.deleteLater)
|
|
83
|
+
raise
|
|
84
|
+
self._timers.append((timer, tick))
|
|
85
|
+
return timer
|
|
86
|
+
|
|
87
|
+
def zoom_selected(self) -> bool:
|
|
88
|
+
"""Fit selected nodes of the active occurrence with a small canvas margin."""
|
|
89
|
+
glyph = self.snapshot()
|
|
90
|
+
if glyph is None:
|
|
91
|
+
return False
|
|
92
|
+
points = [(n.x, n.y) for c in glyph.contours for n in c.nodes if n.selected]
|
|
93
|
+
if not points:
|
|
94
|
+
return False
|
|
95
|
+
canvas = self.services.fontlab.flWorkspace.instance().getActiveCanvas()
|
|
96
|
+
transform = active_glyph_map(canvas)
|
|
97
|
+
if transform is None:
|
|
98
|
+
return False
|
|
99
|
+
mapped = [
|
|
100
|
+
transform.map(self.services.qt.QtCore.QPointF(*point)) for point in points
|
|
101
|
+
]
|
|
102
|
+
xs, ys = [p.x() for p in mapped], [p.y() for p in mapped]
|
|
103
|
+
left, top = min(xs) - 25, min(ys) - 25
|
|
104
|
+
rect = self.services.qt.QtCore.QRectF(
|
|
105
|
+
left, top, max(xs) - min(xs) + 50, max(ys) - min(ys) + 50
|
|
106
|
+
)
|
|
107
|
+
canvas.zoomTo(rect)
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
def close(self) -> None:
|
|
111
|
+
"""Stop plugin-owned timers before dropping Qt callbacks."""
|
|
112
|
+
for timer, tick in self._timers:
|
|
113
|
+
guarded(self.plugin, self.services.sink, timer.stop)
|
|
114
|
+
guarded(
|
|
115
|
+
self.plugin,
|
|
116
|
+
self.services.sink,
|
|
117
|
+
lambda t=timer, f=tick: t.timeout.disconnect(f),
|
|
118
|
+
)
|
|
119
|
+
guarded(self.plugin, self.services.sink, timer.deleteLater)
|
|
120
|
+
self._timers.clear()
|
|
121
|
+
self.menus.close()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class General(Plugin):
|
|
125
|
+
"""A menu command with font hooks receiving stable ``flPackage.fgId`` ids."""
|
|
126
|
+
|
|
127
|
+
kind: ClassVar[str] = "general"
|
|
128
|
+
menu: ClassVar[str | None] = "Window"
|
|
129
|
+
shortcut: ClassVar[str | None] = None
|
|
130
|
+
|
|
131
|
+
def start(self, ctx: GeneralContext) -> None:
|
|
132
|
+
"""Begin a session after its command is installed."""
|
|
133
|
+
|
|
134
|
+
def stop(self) -> None:
|
|
135
|
+
"""End the session before its command is removed."""
|
|
136
|
+
|
|
137
|
+
def run(self) -> None:
|
|
138
|
+
"""Handle the menu command."""
|
|
139
|
+
|
|
140
|
+
def on_font_opened(self, font_id: int) -> None:
|
|
141
|
+
"""Observe a newly opened font."""
|
|
142
|
+
|
|
143
|
+
def on_font_closed(self, font_id: int) -> None:
|
|
144
|
+
"""Observe a newly closed font."""
|