forked from Shriinivas/inkscapestrokefont
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stroke_font_common.py
429 lines (344 loc) · 14 KB
/
stroke_font_common.py
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Defintion of Common functions and variables used by stroke font extensions
Copyright (C) 2019 Shrinivas Kulkarni
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
'''
import sys, os, fileinput, re, locale
from inkex import errormsg, addNS, NSS
from xml.dom.minidom import parse, Document
from math import ceil
# TODO: Find inkscape version
try:
from lxml import etree
from inkex import Style, Boolean
from inkex.paths import Path, CubicSuperPath, Transform
from inkex import bezier
ver = 1.0
except:
from inkex import etree
import simplestyle, cubicsuperpath, simplepath, simpletransform
from cubicsuperpath import CubicSuperPath
ver = 0.92
try:
from simpletransform import computePointInNode
oldVersion = False
except:
oldVersion = True # older than 0.92
# sys path already includes the module folder
from stroke_font_manager import CharData, getFontNames, xAscent, \
xDescent, xCapHeight, xXHeight, xSpaceROff, xFontId, xSize
class CommonDefs:
inkVer = ver
pyVer = sys.version_info.major
# inx filed that have the font list to be synchronized
inxFilesWithDynFont = ['render_stroke_font_text.inx', 'edit_stroke_font.inx']
vgScaleFact = 2.
lineT = .005
idAttribName = 'id'
hGuideIDPrefix = 'h_'
lvGuideIDPrefix = 'lv_'
rvGuideIDPrefix = 'rv_'
fontOtherInfo = 'otherInfo'
encoding = sys.stdin.encoding
if(encoding == 'cp0' or encoding is None):
encoding = locale.getpreferredencoding()
######### Function variants for 1.0 and 0.92 - Start ##########
# Used only in 0.92
def getPartsFromCubicSuper(csp):
parts = []
for subpath in csp:
part = []
prevBezPt = None
for i, bezierPt in enumerate(subpath):
if(prevBezPt != None):
seg = [prevBezPt[1], prevBezPt[2], bezierPt[0], bezierPt[1]]
part.append(seg)
prevBezPt = bezierPt
parts.append(part)
return parts
def formatStyle(styleStr):
if(CommonDefs.inkVer == 1.0):
return str(Style(styleStr))
else:
return simplestyle.formatStyle(styleStr)
def getCubicSuperPath(d = None):
if(CommonDefs.inkVer == 1.0):
if(d == None): return CubicSuperPath([])
return CubicSuperPath(Path(d).to_superpath())
else:
if(d == None): return []
return CubicSuperPath(simplepath.parsePath(d))
def getCubicLength(csp):
if(CommonDefs.inkVer == 1.0):
return bezier.csplength(csp)[1]
else:
parts = getPartsFromCubicSuper(cspath)
curveLen = 0
for i, part in enumerate(parts):
for j, seg in enumerate(part):
curveLen += bezmisc.bezierlengthSimpson((seg[0], seg[1], seg[2], seg[3]), \
tolerance = tolerance)
return curveLen
def getCubicBoundingBox(csp):
if(CommonDefs.inkVer == 1.0):
bbox = csp.to_path().bounding_box()
return bbox.left, bbox.right, bbox.top, bbox.bottom
else:
return simpletransform.refinedBBox(csp)
def formatSuperPath(csp):
if(CommonDefs.inkVer == 1.0):
return csp.__str__()
else:
return cubicsuperpath.formatPath(csp)
def getParsedPath(d):
if(CommonDefs.inkVer == 1.0):
# Copied from Path.to_arrays for compatibility
return [[seg.letter, list(seg.args)] for seg in Path(d).to_absolute()]
else:
return simplepath.parsePath(d)
def applyTransform(mat, csp):
if(CommonDefs.inkVer == 1.0):
csp.transform(mat)
else:
simpletransform.applyTransformToPath(mat, csp)
def getTranslatedPath(d, posX, posY):
if(CommonDefs.inkVer == 1.0):
path = Path(d)
path.translate(posX, posY, inplace = True)
return path.to_superpath().__str__()
else:
path = simplepath.parsePath(d)
simplepath.translatePath(path, posX, posY)
return simplepath.formatPath(path)
def getTransformMat(matAttr):
if(CommonDefs.inkVer == 1.0):
return Transform(matAttr)
else:
return simpletransform.parseTransform(matAttr)
def getCurrentLayer(effect):
if(CommonDefs.inkVer == 1.0):
return effect.svg.get_current_layer()
else:
return effect.current_layer
def getViewCenter(effect):
if(CommonDefs.inkVer == 1.0):
return effect.svg.namedview.center
else:
return effect.view_center
def computePtInNode(vc, layer):
if(CommonDefs.inkVer == 1.0):
# ~ return (-Transform(layer.transform * mat)).apply_to_point(vc)
return (-layer.transform).apply_to_point(vc)
else:
if(oldVersion):
return list(vc)
else:
return computePointInNode(list(vc), layer)
def getSelectedElements(effect):
if(CommonDefs.inkVer == 1.0):
return effect.svg.selected
else:
return effect.selected
def getEtree():
return etree
def getAddFnTypes(effect):
if(CommonDefs.inkVer == 1.0):
addFn = effect.arg_parser.add_argument
typeFloat = float
typeInt = int
typeString = str
typeBool = Boolean
else:
addFn = effect.OptionParser.add_option
typeFloat = 'float'
typeInt = 'int'
typeString = 'string'
typeBool = 'inkbool'
return addFn, typeFloat, typeInt, typeString, typeBool
def runEffect(effect):
if(CommonDefs.inkVer == 1.0): effect.run()
else: effect.affect()
######### Function variants for 1.0 and 0.92 - End ##########
def getDecodedChars(chars):
if(CommonDefs.pyVer == 2):
return chars.decode(CommonDefs.encoding)
else: #if?
return chars
def indentStr(cnt):
ostr = ''
for i in range(0, cnt):
ostr += ' '
return ostr
def getXMLItemsStr(sectMarkerLine, sectMarker, fontNames):
lSpaces = sectMarkerLine.find(sectMarker)
outStr = indentStr(lSpaces) + sectMarker + ' [start] -->\n'
for fName in fontNames:
outStr += indentStr(lSpaces + 4) + '<item value="' + fName + '">' + fName + '</item>\n'
outStr += indentStr(lSpaces) + sectMarker + ' [end] -->\n'
return outStr
def syncFontList(extPath):
sectMarker = '<!-- ##! dynamically generated portion'
sectMarkerLine = None
xmlFilePaths = [extPath + "/" + f for f in CommonDefs.inxFilesWithDynFont]
try:
fontNames = getFontNames(extPath)
for xf in xmlFilePaths:
for line in fileinput.input(xf, inplace = True):
if sectMarker in line:
if(sectMarkerLine != None):
if(CommonDefs.pyVer == 3):
# For some reasons python2 giving syntax error without eval
eval("print(getXMLItemsStr(sectMarkerLine, sectMarker, fontNames), end = '')")
else:
print(getXMLItemsStr(sectMarkerLine, sectMarker, fontNames)),
sectMarkerLine = None
else:
sectMarkerLine = line
else:
if(sectMarkerLine == None):
if(CommonDefs.pyVer == 3):
eval("print(line, end = '')")
else:
print(line),
except Exception as e:
errormsg('Error updating font list...\n' + str(e))
def addGridLine(layer, posX, posY, length, lType, style, attribs):
line = etree.Element(addNS('path','svg'))
d = 'M '+str(posX) + ' ' + str(posY) +' '+ lType +' '
if(lType == 'H'):
d += str(posX + length)
if(lType == 'V'):
d += str(posY + length)
line.set('style', formatStyle(style))
line.set('d', d)
for key in attribs:
line.set(key, attribs[key])
layer.append(line)
def addText(layer, textStr, posX, posY, style):
text = etree.Element(addNS('text','svg'))
text.text = textStr
text.set('x', str(posX))
text.set('y', str(posY))
text.set('style', formatStyle(style))
layer.append(text)
def createTempl(callback, effect, extraInfo, rowCnt, glyphCnt, \
vgScaleFact, createRvGuides, lineT, newCallBackLayerName = None):
hgStyle = {'stroke-width':str(lineT), 'opacity':'1', 'stroke':'#ff0066'}
lvgStyle = {'stroke-width':str(lineT), 'opacity':'1', 'stroke':'#00aa88'}
rvgStyle = {'stroke-width':str(lineT), 'opacity':'1', 'stroke':'#1b46ff'}
fontSize = extraInfo[xSize]
spcY = fontSize * 3
spcX = fontSize * 3
fontSize = extraInfo[xSize]
vLineH = fontSize * vgScaleFact
colCnt = int(ceil(float(glyphCnt) / float(rowCnt)))
docW = (colCnt + 1) * spcX
docH = (rowCnt + 1) * spcY
svg = effect.document.getroot()
svg.set('width', str(docW))
svg.set('height', str(docH))
#Remove viewbox
if('viewBox' in svg.attrib):
svg.attrib.pop('viewBox')
currLayers = svg.xpath('//svg:g', namespaces = NSS)
for layer in currLayers:
# Note: getparent()
parentLayer = layer.getparent() if(CommonDefs.inkVer == 1.0) \
else effect.getParentNode(layer)
if(parentLayer != None):
parentLayer.remove(layer)
currExtraElems = svg.xpath('//svg:' + CommonDefs.fontOtherInfo, namespaces = NSS)
for elem in currExtraElems:
parentElem = elem.getparent() if(CommonDefs.inkVer == 1.0) \
else effect.getParentNode(elem)
parentElem.remove(elem)
extraInfoElem = etree.SubElement(svg, CommonDefs.fontOtherInfo)
extraInfoElem.set(xAscent, str(extraInfo[xAscent]))
extraInfoElem.set(xDescent, str(extraInfo[xDescent]))
extraInfoElem.set(xCapHeight, str(extraInfo[xCapHeight]))
extraInfoElem.set(xXHeight, str(extraInfo[xXHeight]))
extraInfoElem.set(xSpaceROff, str(extraInfo[xSpaceROff]))
extraInfoElem.set(xFontId, str(extraInfo[xFontId]))
extraInfoElem.set(xSize, str(extraInfo[xSize]))
templLayer = etree.SubElement(svg, 'g')
templLayer.set(addNS('label', 'inkscape'), 'Guides')
templLayer.set(addNS('groupmode', 'inkscape'), 'layer')
if(newCallBackLayerName != None):
callbackLayer = etree.SubElement(svg, 'g')
callbackLayer.set(addNS('label', 'inkscape'), newCallBackLayerName)
callbackLayer.set(addNS('groupmode', 'inkscape'), 'layer')
else:
callbackLayer = templLayer
editLayer = etree.SubElement(svg, 'g')
editLayer.set(addNS('label', 'inkscape'), 'Glyphs')
editLayer.set(addNS('groupmode', 'inkscape'), 'layer')
editLayer.set('id', 'glyph')#TODO: How to make this dynamic?
view = svg.namedview if CommonDefs.inkVer == 1.0 else effect.getNamedView()
view.set(addNS('current-layer', 'inkscape'), editLayer.get('id'))
for row in range(0, rowCnt):
hAttribs = {CommonDefs.idAttribName : CommonDefs.hGuideIDPrefix + str(row)}
addGridLine(templLayer, 0, \
(row + 1) * spcY, docW, 'H', hgStyle, hAttribs)
for col in range(0, colCnt):
glyphIdx = row * colCnt + col
if(glyphIdx >= glyphCnt):
break
posX = (col + 1) * spcX
posY = (row + 1) * spcY# + lineT / 2
#Caller can create whatever it wants at this position
rOffset = callback(callbackLayer, editLayer, glyphIdx, posX, posY)
if(rOffset == None):
rOffset = fontSize
lvAttribs = {CommonDefs.idAttribName : CommonDefs.lvGuideIDPrefix + \
str(row).zfill(4) + '_' + str(col).zfill(4)}
addGridLine(templLayer, \
posX, posY + fontSize / 1.5, -vLineH, 'V', \
lvgStyle, lvAttribs)
if(createRvGuides):
rvAttribs = {CommonDefs.idAttribName : CommonDefs.rvGuideIDPrefix + \
str(row).zfill(4) + '_' + str(col).zfill(4)}
addGridLine(templLayer, \
posX + rOffset, posY + fontSize / 1.5, -vLineH, 'V', \
rvgStyle, rvAttribs)
def getCharStyle(strokeWidth, naChar):
#na character is a filled box
naStyle = { 'stroke': '#000000', 'fill': '#000000', 'stroke-width': strokeWidth}
charStyle = { 'stroke': '#000000', 'fill': 'none', 'stroke-width': strokeWidth,
'stroke-linecap':'round', 'stroke-linejoin':'round'}
if(naChar):
return naStyle
else:
return charStyle
class InkscapeCharData(CharData):
def __init__(self, char, rOffset, pathStr, glyphName):
self.pathStr = pathStr
super(InkscapeCharData, self).__init__(char, rOffset, glyphName)
def getBBox(self):
return getCubicBoundingBox(getCubicSuperPath(self.pathStr))
def scaleGlyph(self, scaleX, scaleY):
self.rOffset *= scaleX
cspath = getCubicSuperPath(self.pathStr)
for subpath in cspath:
for bezierPts in subpath:
for i in range(0, len(bezierPts)):
#No worries about origin...
bezierPts[i] = [bezierPts[i][0] * scaleX, bezierPts[i][1] * scaleY]
self.pathStr = formatSuperPath(cspath)
self.bbox = getCubicBoundingBox(cspath)
class InkscapeCharDataFactory:
def __init__(self):
pass
def getCharData(self, char, rOffset, pathStr, glyphName):
return InkscapeCharData(char, rOffset, pathStr, glyphName)