| 1 |
import logging |
| 2 |
|
| 3 |
from babelfont.Font import Font |
| 4 |
from babelfont.Layer import Layer |
| 5 |
from babelfont.Anchor import Anchor |
| 6 |
|
| 7 |
logger = logging.getLogger(__name__) |
| 8 |
|
| 9 |
|
| 10 |
def propagate_anchors(font: Font): |
| 11 |
logger.info("Propagating anchors") |
| 12 |
processed = set() |
| 13 |
|
| 14 |
for glyph in font.glyphs: |
| 15 |
for layer in glyph.layers: |
| 16 |
_propagate_anchors(layer, glyph.name, processed) |
| 17 |
|
| 18 |
|
| 19 |
def _propagate_anchors(layer: Layer, glyphname: str, processed: set): |
| 20 |
if layer.id in processed: |
| 21 |
return |
| 22 |
processed.add(layer.id) |
| 23 |
|
| 24 |
base_components = [] |
| 25 |
mark_components = [] |
| 26 |
anchor_names = set() |
| 27 |
to_add = {} |
| 28 |
for component in layer.components: |
| 29 |
component_layer = component.component_layer |
| 30 |
if not component_layer: |
| 31 |
continue |
| 32 |
_propagate_anchors(component_layer, component.ref, processed) |
| 33 |
if any(a.name.startswith("_") for a in component_layer.anchors): |
| 34 |
mark_components.append(component) |
| 35 |
else: |
| 36 |
base_components.append(component) |
| 37 |
anchor_names |= {a.name for a in component_layer.anchors} |
| 38 |
|
| 39 |
if mark_components and not base_components and _is_ligature_mark(layer): |
| 40 |
try: |
| 41 |
component = _component_closest_to_origin(mark_components) |
| 42 |
except Exception as e: |
| 43 |
raise ValueError( |
| 44 |
"Error while determining which component of composite " |
| 45 |
"'{}' is the lowest: {}".format(glyphname, str(e)) |
| 46 |
) from e |
| 47 |
mark_components.remove(component) |
| 48 |
base_components.append(component) |
| 49 |
component_layer = component.component_layer |
| 50 |
anchor_names |= {a.name for a in component_layer.anchors} |
| 51 |
|
| 52 |
for anchor_name in anchor_names: |
| 53 |
# don't add if parent already contains this anchor OR any associated |
| 54 |
# ligature anchors (e.g. "top_1, top_2" for "top") |
| 55 |
if not any(a.name.startswith(anchor_name) for a in layer.anchors): |
| 56 |
_get_anchor_data(to_add, base_components, anchor_name) |
| 57 |
|
| 58 |
for component in mark_components: |
| 59 |
_adjust_anchors(to_add, layer, component) |
| 60 |
|
| 61 |
# we sort propagated anchors to append in a deterministic order |
| 62 |
for name, (x, y) in sorted(to_add.items()): |
| 63 |
layer.anchors.append(Anchor(name=name, x=x, y=y)) |
| 64 |
|
| 65 |
|
| 66 |
def _is_ligature_mark(glyph): |
| 67 |
return not glyph.name.startswith("_") and "_" in glyph.name |