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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
|
# 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
from math import atan2, degrees
from inkex import Transform, errormsg
from inkex.units import convert_unit
from ..elements import Stroke
from ..i18n import _
from ..lettering import get_font_by_id
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("--notebook")
self.arg_parser.add_argument("-p", "--text-position", type=str, default='left', dest="text_position")
def effect(self):
# we ignore everything but the first path/text
text, path = self.get_selection()
if text is None or path is None:
errormsg(_("Please select one path and one Ink/Stitch lettering group."))
return
TextAlongPath(self.svg, text, path, self.options.text_position)
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:
return [None, None]
return [groups[0], paths[0]]
class TextAlongPath:
'''
Aligns an Ink/Stitch Lettering group along a path
'''
def __init__(self, svg, text, path, text_position):
self.svg = svg
self.text = text
self.path = Stroke(path).as_multi_line_string().geoms[0]
self.text_position = text_position
self.glyphs = []
self.load_settings()
self.font = get_font_by_id(self.settings.font, False)
if self.font is None:
errormsg(_("Couldn't identify the font specified in the lettering group."))
return
self.font_scale = self.settings.scale / 100
self._reset_glyph_transforms()
if not self.glyphs:
errormsg(_("The text doesn't contain any glyphs."))
return
hidden_commands = self.hide_commands()
self.glyphs_along_path()
self.restore_commands(hidden_commands)
def _reset_glyph_transforms(self):
# reset text transforms
self.text.set('transform', get_correction_transform(self.text))
if self.font is not None:
try:
text_group = list(self.text.iterchildren(SVG_GROUP_TAG))[0]
text_group.set('transform', f'scale({self.font_scale})')
except IndexError:
pass
for glyph in text_group.iterchildren():
glyph.delete()
rendered_text = self.font.render_text(
self.settings.text,
text_group,
None, # we don't know the font variant (?)
self.settings.back_and_forth,
self.settings.trim_option,
self.settings.use_trim_symbols,
0, # color sort breaks the glyph structure needed for this method
self.settings.text_align,
self.settings.letter_spacing,
self.settings.word_spacing,
self.settings.line_height
)
self.glyphs = [glyph for glyph in rendered_text.iterdescendants(SVG_GROUP_TAG) if glyph.get('inkstitch:letter-group', '') == 'glyph']
self.bake_transforms_recursively(text_group)
def bake_transforms_recursively(self, element):
'''applies transforms of the text group to the glyph group'''
for child in element:
child.transform = element.transform @ child.transform
if child.tag == SVG_GROUP_TAG and not child.get('inkstitch:letter-group', '') == 'glyph':
self.bake_transforms_recursively(child)
element.transform = None
def glyphs_along_path(self):
path = self.path
for i, text_line in enumerate(self.text.getchildren()[0].iterchildren()):
self.transform_glyphs(path, text_line, i)
# offset path for the next line
line_offset = self.font.leading * self.font_scale
path = path.offset_curve(line_offset)
def transform_glyphs(self, path, line, iterator):
text_width = line.bounding_box().width
text_baseline = line.bounding_box().bottom
backwards = self.settings.back_and_forth and iterator % 1 == 1
if self.text_position == 'stretch':
num_spaces = len(line) - 1
line_glyphs = [glyph for glyph in line.iterdescendants(SVG_GROUP_TAG) if glyph.get('inkstitch:letter-group', '') == 'glyph']
total_stretch_spaces = len(line_glyphs) - 1 + num_spaces
stretch_space = (path.length - text_width) / total_stretch_spaces
else:
stretch_space = 0
start_position = self.get_start_position(text_width, path.length)
distance = start_position
old_bbox = None
words = line.getchildren()
if backwards:
words.reverse()
if self.font.text_direction == "rtl":
words.reverse()
for word in words:
glyphs = word.getchildren()
if backwards:
glyphs.reverse()
if self.font.text_direction == "rtl":
glyphs.reverse()
for glyph in glyphs:
# dimensions
bbox = glyph.bounding_box()
transformed_bbox = glyph.bounding_box(word.composed_transform())
left = bbox.left
transformed_left = transformed_bbox.left
width = convert_unit(transformed_bbox.width, 'px', self.svg.unit)
# adjust position
if old_bbox:
distance += convert_unit(transformed_left - old_bbox.right, 'px', self.svg.unit) + stretch_space
new_distance = distance + width
# calculate and apply transform
first = path.interpolate(distance)
last = path.interpolate(new_distance)
if not first or not last:
# unusable path, nothing we can do
continue
angle = degrees(atan2(last.y - first.y, last.x - first.x)) % 360
translate = InkstitchPoint(first.x, first.y) - InkstitchPoint(left, text_baseline)
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
# set values for next iteration
distance = new_distance
old_bbox = transformed_bbox
distance += stretch_space
def get_start_position(self, text_length, path_length):
start_position = 0
if self.text_position == 'center':
start_position = (path_length - text_length) / 2
if self.text_position == 'right':
start_position = path_length - text_length
return start_position
def text_length(self, line):
return convert_unit(line.bounding_box().width, 'px', self.svg.unit)
def hide_commands(self):
# hide commmands for bounding box calculation
hidden_commands = []
for glyph in self.glyphs:
for group in glyph.iterdescendants(SVG_GROUP_TAG):
if group.get_id().startswith("command_group") and group.style('display', 'inline') != 'none':
hidden_commands.append(group)
group.style['display'] = 'none'
return hidden_commands
def restore_commands(self, hidden_commands):
for command in hidden_commands:
command.style['display'] = "inline"
def load_settings(self):
"""Load the settings saved into the text element"""
self.settings = DotDict({
"text": "",
"back_and_forth": False,
"font": None,
"scale": 100,
"trim_option": 0,
"use_trim_symbols": False,
"color_sort": 0,
"text_align": 0,
"letter_spacing": 0,
"word_spacing": 0,
"line_height": 0
})
if INKSTITCH_LETTERING in self.text.attrib:
try:
self.settings.update(json.loads(self.text.get(INKSTITCH_LETTERING)))
except (TypeError, ValueError):
pass
|