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.
Files changed (56) hide show
  1. fontlab_plugmix/__init__.py +41 -0
  2. fontlab_plugmix/backend.py +285 -0
  3. fontlab_plugmix/boot.py +140 -0
  4. fontlab_plugmix/filter.py +83 -0
  5. fontlab_plugmix/filters/__init__.py +4 -0
  6. fontlab_plugmix/filters/apply.py +158 -0
  7. fontlab_plugmix/filters/delete_small_paths.py +57 -0
  8. fontlab_plugmix/filters/dialog.py +119 -0
  9. fontlab_plugmix/filters/host.py +120 -0
  10. fontlab_plugmix/general.py +144 -0
  11. fontlab_plugmix/general_plugins/__init__.py +4 -0
  12. fontlab_plugmix/general_plugins/host.py +137 -0
  13. fontlab_plugmix/general_plugins/zoom_to_selection.py +27 -0
  14. fontlab_plugmix/geometry.py +64 -0
  15. fontlab_plugmix/kinds.py +33 -0
  16. fontlab_plugmix/menu.py +29 -0
  17. fontlab_plugmix/palette.py +24 -0
  18. fontlab_plugmix/palettes/__init__.py +4 -0
  19. fontlab_plugmix/palettes/apply.py +159 -0
  20. fontlab_plugmix/palettes/host.py +369 -0
  21. fontlab_plugmix/palettes/step_and_repeat.py +53 -0
  22. fontlab_plugmix/palettes/ui.py +86 -0
  23. fontlab_plugmix/plugin.py +14 -0
  24. fontlab_plugmix/plugins/__init__.py +4 -0
  25. fontlab_plugmix/plugins/anchor_cloud.py +30 -0
  26. fontlab_plugmix/plugins/angled_handles.py +40 -0
  27. fontlab_plugmix/plugins/center_lines.py +28 -0
  28. fontlab_plugmix/plugins/crosshair.py +39 -0
  29. fontlab_plugmix/plugins/duplicate_anchors.py +50 -0
  30. fontlab_plugmix/plugins/glyph_focus.py +28 -0
  31. fontlab_plugmix/plugins/imprecise_italic_angle.py +44 -0
  32. fontlab_plugmix/plugins/node_indexes.py +26 -0
  33. fontlab_plugmix/plugins/nodes_close_to_zones.py +35 -0
  34. fontlab_plugmix/plugins/offcurve_outside_bounds.py +31 -0
  35. fontlab_plugmix/plugins/only_selected_handles.py +38 -0
  36. fontlab_plugmix/plugins/rsb_line.py +39 -0
  37. fontlab_plugmix/plugins/segment_length.py +36 -0
  38. fontlab_plugmix/plugins/selected_coordinates.py +27 -0
  39. fontlab_plugmix/plugins/smooth_node_angles.py +51 -0
  40. fontlab_plugmix/plugins/tops_and_bottoms.py +34 -0
  41. fontlab_plugmix/plugins/two_point_distance.py +38 -0
  42. fontlab_plugmix/plugins/unitizer.py +35 -0
  43. fontlab_plugmix/plugins/vertical_metrics.py +39 -0
  44. fontlab_plugmix/registry.py +434 -0
  45. fontlab_plugmix/reporter.py +127 -0
  46. fontlab_plugmix/snapshot.py +285 -0
  47. fontlab_plugmix/tool.py +104 -0
  48. fontlab_plugmix/tools/__init__.py +4 -0
  49. fontlab_plugmix/tools/bridge.py +169 -0
  50. fontlab_plugmix/tools/host.py +143 -0
  51. fontlab_plugmix/tools/smart_select.py +77 -0
  52. fontlab_python_plugmix-1.1.18.dist-info/METADATA +444 -0
  53. fontlab_python_plugmix-1.1.18.dist-info/RECORD +56 -0
  54. fontlab_python_plugmix-1.1.18.dist-info/WHEEL +4 -0
  55. fontlab_python_plugmix-1.1.18.dist-info/licenses/LICENSE +201 -0
  56. fontlab_python_plugmix-1.1.18.dist-info/licenses/NOTICE +228 -0
@@ -0,0 +1,137 @@
1
+ # this_file: src/fontlab_plugmix/general_plugins/host.py
2
+ """Own General menu commands, timers and font lifecycle polling."""
3
+
4
+ from dataclasses import dataclass
5
+ from importlib import import_module
6
+ from typing import Any
7
+
8
+ from fontlab_plugmix.general import GeneralContext
9
+ from fontlab_plugmix.kinds import Services, guarded
10
+
11
+
12
+ @dataclass
13
+ class _Running:
14
+ """Retain one started plugin, its owned context and menu token."""
15
+
16
+ plugin: Any
17
+ context: GeneralContext
18
+ token: int | None
19
+
20
+
21
+ class GeneralHost:
22
+ """Start General plugins and share PaletteHost's existing 250 ms timer."""
23
+
24
+ def __init__(self, services: Services, registry: Any, palettes: Any) -> None:
25
+ self.services, self.registry, self.palettes = services, registry, palettes
26
+ self.running: dict[str, _Running] = {}
27
+ self._fonts: set[int] | None = None
28
+
29
+ def _font_ids(self) -> set[int]:
30
+ """Read stable font fgIds from the workspace, not wrapper object ids."""
31
+ workspace = self.services.fontlab.flWorkspace.instance()
32
+ items = import_module("fontlabapp.qtsafe").qt_list
33
+ # packages() yields flObject wrappers; only flPackage(item) exposes fgId.
34
+ package = self.services.fontlab.flPackage
35
+ return {int(package(item).fgId) for item in items(workspace.packages)}
36
+
37
+ def _shortcut(self, token: int, shortcut: str) -> None:
38
+ """Compare Qt-normalized sequences and leave conflicts unassigned."""
39
+ menus, qt = self.services.menus, self.services.qt
40
+ qt_value = import_module("fontlabapp.qt_properties").value
41
+ action = menus.action(token)
42
+ sequence = qt.QtGui.QKeySequence(shortcut)
43
+ wanted = str(sequence.toString())
44
+ siblings = menus.main_window().findChildren(qt.QtGui.QAction)
45
+ for other in siblings:
46
+ if (
47
+ other is not action
48
+ and str(qt_value(other, "shortcut").toString()) == wanted
49
+ ):
50
+ raise ValueError(f"Shortcut {shortcut} is already in use")
51
+ action.setShortcut(sequence)
52
+
53
+ def _start(self, name: str) -> None:
54
+ """Install the command first; unwind it if start fails."""
55
+ plugin = self.registry.available("general")[name]()
56
+ context = GeneralContext(self.services, plugin)
57
+ token = None
58
+ try:
59
+ if plugin.menu is not None:
60
+ token = self.services.menus.add_action(
61
+ plugin.menu,
62
+ plugin.title,
63
+ lambda *args: guarded(plugin, self.services.sink, plugin.run),
64
+ checkable=False,
65
+ )
66
+ plugin.start(context)
67
+ if token is not None and plugin.shortcut:
68
+ guarded(
69
+ plugin,
70
+ self.services.sink,
71
+ lambda: self._shortcut(token, plugin.shortcut),
72
+ )
73
+ except Exception:
74
+ guarded(plugin, self.services.sink, plugin.stop)
75
+ context.close()
76
+ if token is not None:
77
+ guarded(
78
+ plugin,
79
+ self.services.sink,
80
+ lambda: self.services.menus.remove(token),
81
+ )
82
+ raise
83
+ self.running[name] = _Running(plugin, context, token)
84
+
85
+ def install(self) -> None:
86
+ """Start saved General plugins and attach their shared font watcher."""
87
+ self._fonts = guarded(self, self.services.sink, self._font_ids)
88
+ for name in self.registry.enabled_general():
89
+ if name not in self.registry.available("general"):
90
+ continue
91
+ guarded(self, self.services.sink, lambda name=name: self._start(name))
92
+ if self.running:
93
+ self.palettes.subscribe("general", self._poll)
94
+
95
+ def _poll(self) -> None:
96
+ """Deliver set-difference font events once per open or close."""
97
+ current = self._font_ids()
98
+ if self._fonts is None:
99
+ self._fonts = current
100
+ return
101
+ opened, closed = current - self._fonts, self._fonts - current
102
+ self._fonts = current
103
+ for running in tuple(self.running.values()):
104
+ for identifier in sorted(opened):
105
+ guarded(
106
+ running.plugin,
107
+ self.services.sink,
108
+ lambda n=identifier, p=running.plugin: p.on_font_opened(n),
109
+ )
110
+ for identifier in sorted(closed):
111
+ guarded(
112
+ running.plugin,
113
+ self.services.sink,
114
+ lambda n=identifier, p=running.plugin: p.on_font_closed(n),
115
+ )
116
+
117
+ def _stop(self, name: str) -> None:
118
+ """Stop plugin before removing its command and extra actions."""
119
+ running = self.running.pop(name, None)
120
+ if running is None:
121
+ return
122
+ try:
123
+ guarded(running.plugin, self.services.sink, running.plugin.stop)
124
+ finally:
125
+ running.context.close()
126
+ if running.token is not None:
127
+ guarded(
128
+ running.plugin,
129
+ self.services.sink,
130
+ lambda: self.services.menus.remove(running.token),
131
+ )
132
+
133
+ def close(self) -> None:
134
+ """Stop shared polling and every started General plugin."""
135
+ self.palettes.unsubscribe("general")
136
+ for name in tuple(self.running):
137
+ self._stop(name)
@@ -0,0 +1,27 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # this_file: src/fontlab_plugmix/general_plugins/zoom_to_selection.py
3
+ """Fit selected nodes in the active Glyph canvas without changing font data.
4
+
5
+ This keeps the menu action from TzuYuan Yin's Zoom to Selection behaviour;
6
+ the source's delayed viewport adjustment and shortcut are omitted.
7
+ """
8
+
9
+ from fontlab_plugmix.general import General, GeneralContext
10
+
11
+
12
+ class ZoomToSelection(General):
13
+ """Zoom the active canvas to the current node selection."""
14
+
15
+ name = "zoom_to_selection"
16
+ title = "Plugmix: Zoom to Selection"
17
+ menu = "View"
18
+
19
+ def start(self, ctx: GeneralContext) -> None:
20
+ self.ctx = ctx
21
+
22
+ def stop(self) -> None:
23
+ self.ctx = None
24
+
25
+ def run(self) -> None:
26
+ if not self.ctx.zoom_selected():
27
+ self.ctx.notify("Zoom to Selection", "Select nodes in a Glyph window first")
@@ -0,0 +1,64 @@
1
+ # this_file: src/fontlab_plugmix/geometry.py
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Small pure contour-segment operations shared by reporter computations."""
4
+
5
+ from itertools import pairwise
6
+ from math import comb, hypot
7
+
8
+ from .snapshot import Contour, Node
9
+
10
+
11
+ def segments(contour: Contour) -> tuple[tuple[Node, ...], ...]:
12
+ """Split lines, quadratic and cubic segments; skip longer control runs."""
13
+ nodes = contour.nodes
14
+ on = [index for index, node in enumerate(nodes) if node.on_curve]
15
+ if len(on) < 2:
16
+ return ()
17
+ pairs = list(pairwise(on))
18
+ if contour.closed:
19
+ pairs.append((on[-1], on[0]))
20
+ rows = []
21
+ for start, end in pairs:
22
+ row = (
23
+ nodes[start : end + 1] if end > start else nodes[start:] + nodes[: end + 1]
24
+ )
25
+ # Three or more off-curves may imply TrueType on-curves. Without curve
26
+ # type in the snapshot, skip that run rather than mismeasure a segment.
27
+ if len(row) in (2, 3, 4):
28
+ rows.append(row)
29
+ return tuple(rows)
30
+
31
+
32
+ def neighbours(contour: Contour, index: int) -> tuple[Node | None, Node | None]:
33
+ """Return neighbours without wrapping the ends of an open contour."""
34
+ nodes = contour.nodes
35
+ before = nodes[index - 1] if index else (nodes[-1] if contour.closed else None)
36
+ after = (
37
+ nodes[index + 1]
38
+ if index + 1 < len(nodes)
39
+ else (nodes[0] if contour.closed else None)
40
+ )
41
+ return before, after
42
+
43
+
44
+ def point_at(segment: tuple[Node, ...], t: float) -> tuple[float, float]:
45
+ """Evaluate a line, quadratic or cubic segment at fractional position t."""
46
+ n = len(segment) - 1
47
+ weights = tuple(comb(n, i) * (1 - t) ** (n - i) * t**i for i in range(n + 1))
48
+ return (
49
+ sum(node.x * weight for node, weight in zip(segment, weights, strict=True)),
50
+ sum(node.y * weight for node, weight in zip(segment, weights, strict=True)),
51
+ )
52
+
53
+
54
+ def length(segment: tuple[Node, ...], steps: int = 25) -> float:
55
+ """Measure a line exactly and a Bézier by uniform flattening."""
56
+ if len(segment) == 2:
57
+ start, end = segment
58
+ return hypot(end.x - start.x, end.y - start.y)
59
+ previous, total = (segment[0].x, segment[0].y), 0.0
60
+ for index in range(1, steps + 1):
61
+ current = point_at(segment, index / steps)
62
+ total += hypot(current[0] - previous[0], current[1] - previous[1])
63
+ previous = current
64
+ return total
@@ -0,0 +1,33 @@
1
+ # this_file: src/fontlab_plugmix/kinds.py
2
+ """Runtime services and the shared native callback boundary."""
3
+
4
+ from collections.abc import Callable
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Services:
11
+ """Host objects owned by boot, passed to kind-specific binders."""
12
+
13
+ qt: Any
14
+ fontlab: Any
15
+ menus: Any
16
+ painters: Any
17
+ sink: Callable[[Exception, object], object]
18
+
19
+
20
+ def guarded(
21
+ plugin: object,
22
+ sink: Callable[[Exception, object], object],
23
+ action: Callable[[], Any],
24
+ ) -> Any:
25
+ """Never let a plugin or diagnostic failure escape into Qt dispatch."""
26
+ try:
27
+ return action()
28
+ except Exception as error: # noqa: BLE001 - native callback boundary
29
+ try:
30
+ sink(error, plugin)
31
+ except Exception: # noqa: BLE001, S110 - sink is also untrusted
32
+ pass
33
+ return None
@@ -0,0 +1,29 @@
1
+ # this_file: src/fontlab_plugmix/menu.py
2
+ """Install checkable reporter actions in a Plugmix section of View."""
3
+
4
+ from typing import Any
5
+
6
+
7
+ def install(owner: Any, registry: Any) -> dict[str, int]:
8
+ """Add one owned QAction per reporter and return action tokens."""
9
+ tokens = {}
10
+ for name, cls in sorted(registry.available("reporter").items()):
11
+ action_token = owner.add_action(
12
+ "View",
13
+ f"Plugmix: Show {cls.title}",
14
+ lambda name=name: _toggle(owner, registry, tokens[name], name),
15
+ checkable=True,
16
+ )
17
+ tokens[name] = action_token
18
+ owner.action(action_token).setChecked(name in registry.enabled())
19
+ return tokens
20
+
21
+
22
+ def _toggle(owner: Any, registry: Any, token: int, name: str) -> None:
23
+ """Restore QAction state if activation or persistence fails."""
24
+ action = owner.action(token)
25
+ try:
26
+ registry.toggle(name)
27
+ finally:
28
+ if action is not None:
29
+ action.setChecked(name in registry.enabled())
@@ -0,0 +1,24 @@
1
+ # this_file: src/fontlab_plugmix/palette.py
2
+ """Qt-free contract for dockable palettes."""
3
+
4
+ from typing import ClassVar, Literal
5
+
6
+ from .plugin import Plugin
7
+ from .snapshot import GlyphSnapshot
8
+
9
+
10
+ class Palette(Plugin):
11
+ """Build controls once, refresh on active glyph changes, release on close."""
12
+
13
+ kind = "palette"
14
+ area: ClassVar[Literal["left", "right", "top", "bottom"]] = "right"
15
+
16
+ def build(self, ui: object) -> None:
17
+ """Create controls through a host-provided UI facade."""
18
+ raise NotImplementedError
19
+
20
+ def refresh(self, context: GlyphSnapshot | None) -> None:
21
+ """React to a new active glyph, master, revision or selection."""
22
+
23
+ def close(self) -> None:
24
+ """Release plugin-owned resources when the panel closes."""
@@ -0,0 +1,4 @@
1
+ # this_file: src/fontlab_plugmix/palettes/__init__.py
2
+ """Built-in dockable palettes."""
3
+
4
+ __all__: list[str] = []
@@ -0,0 +1,159 @@
1
+ # this_file: src/fontlab_plugmix/palettes/apply.py
2
+ """Stage selected contour copies and commit them through the shared writer."""
3
+
4
+ from importlib import import_module
5
+ from math import isfinite
6
+ from typing import Any
7
+
8
+ from fontlab_plugmix import snapshot
9
+ from fontlab_plugmix.filters.apply import _targets_safe
10
+ from fontlab_plugmix.kinds import Services
11
+
12
+
13
+ def _values(values: dict[str, Any]) -> tuple[int, float, float]:
14
+ """Accept finite offsets and a nonnegative number of additional copies."""
15
+ count, dx, dy = values["count"], values["dx"], values["dy"]
16
+ if type(count) is not int or count < 0 or count > 100:
17
+ raise ValueError("Count must be between 0 and 100")
18
+ if any(
19
+ type(value) not in (int, float) or not isfinite(value) for value in (dx, dy)
20
+ ):
21
+ raise ValueError("Offsets must be finite numbers")
22
+ if count and dx == 0 and dy == 0:
23
+ raise ValueError("X and Y offsets cannot both be zero")
24
+ return count, float(dx), float(dy)
25
+
26
+
27
+ def selected_indices(glyph: snapshot.GlyphSnapshot) -> tuple[int, ...]:
28
+ """A contour is selected when at least one of its nodes is selected."""
29
+ return tuple(
30
+ index
31
+ for index, contour in enumerate(glyph.contours)
32
+ if any(node.selected for node in contour.nodes)
33
+ )
34
+
35
+
36
+ class RepeatEditor:
37
+ """Clone each selected native contour before history, then add its copies."""
38
+
39
+ def __init__(
40
+ self, outlines: Any, qt: Any, repair: Any, expected_count: int | None = None
41
+ ) -> None:
42
+ self.outlines, self.qt, self.repair = outlines, qt, repair
43
+ self.expected_count = expected_count
44
+
45
+ def prepare(self, layer: Any, edits: list[Any]) -> list[tuple[Any, Any]]:
46
+ """Refuse a changed unsafe layer before opening the Undo transaction."""
47
+ rows = [
48
+ (shape, contour)
49
+ for shape in layer.shapes
50
+ if not shape.isComponent
51
+ for contour in shape.contours
52
+ ]
53
+ if self.expected_count is not None and len(rows) != self.expected_count:
54
+ raise ValueError("Step and Repeat contour count changed; select again")
55
+ staged = []
56
+ for indices, offsets in edits:
57
+ if not _targets_safe(layer, indices, self.outlines):
58
+ raise ValueError(
59
+ "Step and Repeat cannot copy a shared or transformed outline"
60
+ )
61
+ for index in indices:
62
+ shape, contour = rows[index]
63
+ for dx, dy in offsets:
64
+ transform = self.qt.QtGui.QTransform()
65
+ transform.translate(dx, dy)
66
+ copy = contour.cloneMapped(transform)
67
+ self.repair(contour, copy)
68
+ staged.append((shape, copy))
69
+ return staged
70
+
71
+ def write(self, layer: Any, steps: list[tuple[Any, Any]]) -> None:
72
+ """Attach staged copies to their original owning shapes."""
73
+ for shape, copy in steps:
74
+ shape.addContour(copy, True)
75
+
76
+ def check(self, prepared: list[tuple[Any, list[tuple[Any, Any]]]]) -> list[str]:
77
+ """Report a copy that native shape attachment did not retain."""
78
+ return [
79
+ "repeated contour missing after write"
80
+ for _, steps in prepared
81
+ for shape, copy in steps
82
+ if not any(int(item.id) == int(copy.id) for item in shape.contours)
83
+ ]
84
+
85
+ def retain(self, steps: list[Any]) -> list[Any]:
86
+ """New copies remove no native objects that history must pin."""
87
+ return []
88
+
89
+
90
+ def repeat_selected(
91
+ values: dict[str, Any],
92
+ services: Services,
93
+ *,
94
+ outlines: Any = None,
95
+ writer: Any = None,
96
+ history: Any = None,
97
+ repair: Any = None,
98
+ ) -> tuple[Any, Any, str]:
99
+ """Copy the current glyph's selected contours in one geometry Undo step."""
100
+ count, dx, dy = _values(values)
101
+ if count == 0:
102
+ return None, None, "Count is zero; nothing to repeat."
103
+ active = snapshot.active_glyph(services.fontlab)
104
+ if active is None:
105
+ return None, None, "No active glyph."
106
+ outlines = outlines or import_module("fontlabapp.outline_writer")
107
+ master_layer = outlines.layer_of(active.glyph, str(active.package.master))
108
+ same_id = (
109
+ master_layer is not None
110
+ and getattr(active.layer, "id", None) is not None
111
+ and int(active.layer.id) == int(master_layer.id)
112
+ )
113
+ if active.layer is not master_layer and not same_id:
114
+ return None, None, "Step and Repeat requires the current master layer."
115
+ before = snapshot.capture(
116
+ snapshot.NativeSource(active.package, active.layer), fontlab=services.fontlab
117
+ )
118
+ indices = selected_indices(before)
119
+ if not indices:
120
+ return None, None, "Select a contour first."
121
+ writer = writer or import_module("fontlabapp.layer_writer")
122
+ history = history or import_module("fontlabapp.history")
123
+ repair = repair or import_module("fontlabapp.contour_copy").repair_nodes
124
+ offsets = tuple((dx * step, dy * step) for step in range(1, count + 1))
125
+ facts = history.scan_auto_facts(active.package)
126
+ unsafe = []
127
+
128
+ def planner(glyph: Any, master: str, layer: Any) -> list[Any]:
129
+ if not _targets_safe(layer, indices, outlines):
130
+ unsafe.append(str(glyph.name))
131
+ return [
132
+ outlines.Change(
133
+ "contours", "", "shared or transformed outline, skipped"
134
+ )
135
+ ]
136
+ return [
137
+ outlines.Change(
138
+ "contours",
139
+ str(len(before.contours)),
140
+ str(len(before.contours) + len(indices) * count),
141
+ edit=(indices, offsets),
142
+ key=(indices, count),
143
+ )
144
+ ]
145
+
146
+ plan = outlines.collect(
147
+ [active.glyph], [str(active.package.master)], planner, facts
148
+ )
149
+ plan.refused.extend(unsafe)
150
+ if not plan.work:
151
+ return plan, None, "Skipped: " + ", ".join((*plan.refused, *plan.skipped))
152
+ result = writer.apply_work(
153
+ plan.work,
154
+ "Step and Repeat",
155
+ facts,
156
+ RepeatEditor(outlines, services.qt, repair, len(before.contours)),
157
+ )
158
+ services.fontlab.UpdateActiveCanvas()
159
+ return plan, result, f"Added {len(indices) * count} contour copies."