summaryrefslogtreecommitdiff
path: root/lib/extensions/lettering_along_path.py
blob: 63ffc817e7f4695dfa882567d4ae96a93adfc6ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# Authors: see git history
#
# Copyright (c) 2021 Authors
# Licensed under the GNU GPL version 3.0 or later.  See the file LICENSE for details.

import json
import sys
from math import atan2, degrees

from inkex import Boolean, Transform, errormsg
from shapely.ops import substring

from ..elements import Stroke
from ..i18n import _
from ..svg import get_correction_transform
from ..svg.tags import EMBROIDERABLE_TAGS, INKSTITCH_LETTERING, SVG_GROUP_TAG
from ..utils import DotDict
from ..utils import Point as InkstitchPoint
from .base import InkstitchExtension


class LetteringAlongPath(InkstitchExtension):
    '''
    This extension aligns an Ink/Stitch Lettering group along a path
    '''
    def __init__(self, *args, **kwargs):
        InkstitchExtension.__init__(self, *args, **kwargs)
        self.arg_parser.add_argument("-o", "--options", type=str, default=None, dest="page_1")
        self.arg_parser.add_argument("-i", "--info", type=str, default=None, dest="page_2")
        self.arg_parser.add_argument("-s", "--stretch-spaces", type=Boolean, default=False, dest="stretch_spaces")

    def effect(self):
        # we ignore everything but the first path/text
        text, path = self.get_selection()
        self.load_settings(text)

        glyphs = [glyph for glyph in text.iterdescendants(SVG_GROUP_TAG) if len(glyph.label) == 1]
        if not glyphs:
            errormsg(_("The text doesn't contain any glyphs."))
            sys.exit(1)

        path = Stroke(path).as_multi_line_string().geoms[0]
        path_length = path.length

        # overall bounding box - get from direct glyph parent
        text_bbox = glyphs[0].getparent().bounding_box()
        text_y = text_bbox.bottom

        if self.options.stretch_spaces:
            text_content = self.settings["text"]
            space_indices = [i for i, t in enumerate(text_content) if t == " "]
            text_width = text_bbox.width

            if len(text_content) - 1 != 0:
                stretch_space = (path_length - text_width) / (len(text_content) - 1)
            else:
                stretch_space = 0
        else:
            stretch_space = 0
            space_indices = []

        self.transform_glyphs(glyphs, path, stretch_space, space_indices, text_y)

    def transform_glyphs(self, glyphs, path, stretch_space, space_indices, text_y):
        text_scale = Transform(f'scale({self.settings["scale"] / 100})')
        distance = 0
        old_bbox = None
        i = 0

        for glyph in glyphs:
            # dimensions
            bbox = glyph.bounding_box()
            left = bbox.left
            width = bbox.width

            # adjust position
            if old_bbox:
                right = old_bbox.right
                distance += left - right + stretch_space

            if self.options.stretch_spaces and i in space_indices:
                distance += stretch_space
                i += 1

            new_distance = distance + width

            # calculate and apply transform
            first = substring(path, distance, distance)
            last = substring(path, new_distance, new_distance)

            angle = degrees(atan2(last.y - first.y, last.x - first.x)) % 360
            translate = InkstitchPoint(first.x, first.y) - InkstitchPoint(left, text_y)

            transform = Transform(f"rotate({angle}, {first.x}, {first.y}) translate({translate.x} {translate.y})")
            correction_transform = Transform(get_correction_transform(glyph))
            glyph.transform = correction_transform @ transform @ glyph.transform @ text_scale

            # set values for next iteration
            distance = new_distance
            old_bbox = bbox
            i += 1

    def load_settings(self, text):
        """Load the settings saved into the text element"""

        self.settings = DotDict({
            "text": "",
            "back_and_forth": False,
            "font": None,
            "scale": 100,
            "trim_option": 0
        })

        if INKSTITCH_LETTERING in text.attrib:
            try:
                self.settings.update(json.loads(text.get(INKSTITCH_LETTERING)))
            except (TypeError, ValueError):
                pass

    def get_selection(self):
        groups = list()
        paths = list()

        for node in self.svg.selection:
            lettering = False
            if node.tag == SVG_GROUP_TAG and INKSTITCH_LETTERING in node.attrib:
                groups.append(node)
                lettering = True
                continue

            for group in node.iterancestors(SVG_GROUP_TAG):
                if INKSTITCH_LETTERING in group.attrib:
                    groups.append(group)
                    lettering = True
                    break

            if not lettering and node.tag in EMBROIDERABLE_TAGS:
                paths.append(node)

        if not groups or not paths:
            errormsg(_("Please select one path and one Ink/Stitch lettering group."))
            sys.exit(1)

        return [groups[0], paths[0]]