glyphtools 0.9.0__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.
glyphtools/__init__.py ADDED
@@ -0,0 +1,387 @@
1
+ """glyphtools is a set of routines for extracting information from font glyphs."""
2
+
3
+ import statistics
4
+ from .ckmeans import ckmeans
5
+ from beziers.path import BezierPath
6
+ from beziers.point import Point
7
+ import glyphtools.glyphs
8
+ import glyphtools.babelfont
9
+ import warnings
10
+ from beziers.path.representations.fontparts import FontParts
11
+
12
+
13
+ __author__ = """Simon Cozens"""
14
+ __email__ = "simon@simon-cozens.org"
15
+ __version__ = "0.9.0"
16
+
17
+
18
+ def categorize_glyph(font, glyphname):
19
+ """Return the category of the given glyph.
20
+
21
+ Args:
22
+ font: a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster
23
+ object OR a ``babelfont`` Font object.
24
+ glyphname: name of the glyph.
25
+
26
+ Returns:
27
+ A two-element tuple. The first element is one of the following
28
+ strings: ``unknown``, ``base``, ``mark``, ``ligature``, ``component``.
29
+ If the glyph is a mark, the second element is the mark attachment
30
+ class number.
31
+ """
32
+ if glyphtools.glyphs.isglyphs(font):
33
+ return glyphtools.glyphs.categorize_glyph(font, glyphname)
34
+ if glyphtools.babelfont.isbabelfont(font):
35
+ if glyphtools.babelfont.isbabelfont3(font):
36
+ return (font.glyphs[glyphname].category, None)
37
+ else:
38
+ return (font[glyphname].category, None)
39
+ if "GDEF" not in font:
40
+ return ("unknown", None)
41
+ gdef = font["GDEF"].table
42
+ classdefs = gdef.GlyphClassDef.classDefs
43
+ if glyphname not in classdefs:
44
+ return ("unknown", None)
45
+ if classdefs[glyphname] == 1:
46
+ return ("base", None)
47
+ if classdefs[glyphname] == 2:
48
+ return ("ligature", None)
49
+ if classdefs[glyphname] == 3:
50
+ # Now find attachment class
51
+ mclass = None
52
+ if gdef.MarkAttachClassDef:
53
+ classdef = gdef.MarkAttachClassDef.classDefs
54
+ if glyphname in classdef:
55
+ mclass = classdef[glyphname]
56
+ return ("mark", mclass)
57
+ if classdefs[glyphname] == 4:
58
+ return ("component", None)
59
+ return ("unknown", None)
60
+
61
+
62
+ def set_glyph_category(font, glyphname, category, maClass=None):
63
+ """Set the category of the glyph in the font.
64
+
65
+ Args:
66
+ font: a ``fontTools`` TTFont object or a ``glyphsLib`` GSFontMaster
67
+ object OR a ``babelfont`` Font object.
68
+ glyphname: name of the glyph.
69
+ category: one of ``base``, ``mark``, ``ligature``, ``component``.
70
+ maClass: If the category is ``base``, the mark attachment class number.
71
+ """
72
+ if glyphtools.glyphs.isglyphs(font):
73
+ return glyphtools.glyphs.set_glyph_category(font, glyphname, category)
74
+ if glyphtools.babelfont.isbabelfont(font):
75
+ font[glyphname].category = category
76
+ return
77
+
78
+ gdef = font["GDEF"].table
79
+ classdefs = gdef.GlyphClassDef.classDefs
80
+ if category == "base":
81
+ classdefs[glyphname] = 1
82
+ elif category == "ligature":
83
+ classdefs[glyphname] = 2
84
+ elif category == "mark":
85
+ classdefs[glyphname] = 3
86
+ if maClass and gdef.MarkAttachClassDef:
87
+ gdef.MarkAttachClassDef.classDefs[glyphname] = maClass
88
+ elif category == "component":
89
+ classdefs[glyphname] = 4
90
+ else:
91
+ raise ValueError("Unknown category")
92
+
93
+
94
+ def get_glyph_metrics(font, glyphname, **kwargs):
95
+ """Return glyph metrics as a dictionary.
96
+
97
+ Args:
98
+ font: a ``fontTools`` TTFont object or a ``glyphsLib`` GSFontMaster
99
+ object OR a ``babelfont`` Font object.
100
+ glyphname: name of the glyph.
101
+
102
+ Returns: A dictionary with the following keys:
103
+ - ``width``: Advance width of the glyph.
104
+ - ``lsb``: Left side-bearing
105
+ - ``rsb``: Right side-bearing
106
+ - ``xMin``: minimum X coordinate
107
+ - ``xMax``: maximum X coordinate
108
+ - ``yMin``: minimum Y coordinate
109
+ - ``yMax``: maximum Y coordinate
110
+ - ``fullwidth``: xMax - xMin
111
+ - ``rise``: difference in Y coordinate between cursive entry and exit
112
+ """
113
+ if glyphtools.glyphs.isglyphs(font):
114
+ return glyphtools.glyphs.get_glyph_metrics(font, glyphname, **kwargs)
115
+ if glyphtools.babelfont.isbabelfont(font):
116
+ return glyphtools.babelfont.get_glyph_metrics(font, glyphname, **kwargs)
117
+ metrics = {}
118
+ if "hmtx" in font:
119
+ metrics = {
120
+ "width": font["hmtx"][glyphname][0],
121
+ "lsb": font["hmtx"][glyphname][1],
122
+ }
123
+ else:
124
+ warnings.warn("No hmtx table in this font!")
125
+ metrics = {"width": font["head"].unitsPerEm, "lsb": 0}
126
+ if "glyf" in font:
127
+ glyf = font["glyf"][glyphname]
128
+ try:
129
+ metrics["xMin"], metrics["xMax"], metrics["yMin"], metrics["yMax"] = (
130
+ glyf.xMin,
131
+ glyf.xMax,
132
+ glyf.yMin,
133
+ glyf.yMax,
134
+ )
135
+ except Exception:
136
+ metrics["xMin"], metrics["xMax"], metrics["yMin"], metrics["yMax"] = (
137
+ 0,
138
+ 0,
139
+ 0,
140
+ 0,
141
+ )
142
+ else:
143
+ bounds = font.getGlyphSet()[glyphname]._glyph.calcBounds(font.getGlyphSet())
144
+ try:
145
+ metrics["xMin"], metrics["yMin"], metrics["xMax"], metrics["yMax"] = bounds
146
+ except Exception:
147
+ metrics["xMin"], metrics["xMax"], metrics["yMin"], metrics["yMax"] = (
148
+ 0,
149
+ 0,
150
+ 0,
151
+ 0,
152
+ )
153
+ metrics["rise"] = get_rise(font, glyphname)
154
+ metrics["run"] = get_run(font, glyphname)
155
+ metrics["rsb"] = metrics["width"] - metrics["xMax"]
156
+ metrics["fullwidth"] = metrics["xMax"] - metrics["xMin"]
157
+ return metrics
158
+
159
+
160
+ def get_rise(font, glyphname, **kwargs):
161
+ """Return the Arabic rise of the glyph (Y difference between entry and exit)."""
162
+ if glyphtools.glyphs.isglyphs(font):
163
+ return glyphtools.glyphs.get_rise(font, glyphname, **kwargs)
164
+ if glyphtools.babelfont.isbabelfont(font):
165
+ return glyphtools.babelfont.get_rise(
166
+ glyphtools.babelfont.get_glyph(font, glyphname)
167
+ )
168
+ # Find a cursive positioning feature or it's game over
169
+ if "GPOS" not in font:
170
+ return 0
171
+ cursives = filter(lambda x: x.LookupType == 3, font["GPOS"].table.LookupList.Lookup)
172
+ entry, exit = None, None
173
+ for c in cursives:
174
+ for s in c.SubTable:
175
+ for glyph, record in zip(s.Coverage.glyphs, s.EntryExitRecord):
176
+ if glyph != glyphname:
177
+ continue
178
+ if record.EntryAnchor:
179
+ entry = (
180
+ record.EntryAnchor.XCoordinate,
181
+ record.EntryAnchor.YCoordinate,
182
+ )
183
+ if record.ExitAnchor:
184
+ exit = (
185
+ record.ExitAnchor.XCoordinate,
186
+ record.ExitAnchor.YCoordinate,
187
+ )
188
+ if not entry and not exit:
189
+ return 0
190
+ if entry and not exit:
191
+ return entry[1]
192
+ if exit and not entry:
193
+ return 0
194
+ return entry[1] - exit[1]
195
+
196
+
197
+ def get_run(font, glyphname, **kwargs):
198
+ """Return the Arabic run of the glyph (X difference between entry and exit)."""
199
+ if glyphtools.glyphs.isglyphs(font):
200
+ return glyphtools.glyphs.get_run(font, glyphname, **kwargs)
201
+ if glyphtools.babelfont.isbabelfont(font):
202
+ return glyphtools.babelfont.get_run(
203
+ glyphtools.babelfont.get_glyph(font, glyphname)
204
+ )
205
+ # Find a cursive positioning feature or it's game over
206
+ width = font["hmtx"][glyphname][0]
207
+ if "GPOS" not in font:
208
+ return width
209
+ cursives = filter(lambda x: x.LookupType == 3, font["GPOS"].table.LookupList.Lookup)
210
+ entry, exit = None, None
211
+ for c in cursives:
212
+ for s in c.SubTable:
213
+ for glyph, record in zip(s.Coverage.glyphs, s.EntryExitRecord):
214
+ if glyph != glyphname:
215
+ continue
216
+ if record.EntryAnchor:
217
+ entry = (
218
+ record.EntryAnchor.XCoordinate,
219
+ record.EntryAnchor.YCoordinate,
220
+ )
221
+ if record.ExitAnchor:
222
+ exit = (
223
+ record.ExitAnchor.XCoordinate,
224
+ record.ExitAnchor.YCoordinate,
225
+ )
226
+ if not entry and not exit:
227
+ return width
228
+ if entry and not exit:
229
+ return entry[0]
230
+ if exit and not entry:
231
+ return width - exit[0]
232
+ return entry[0] - exit[0]
233
+
234
+
235
+ def bin_dictionary(d, bincount=5):
236
+ """Organise a dictionary into a number of bins.
237
+
238
+ The bins are not guaranteed to contain the same number of entries; the
239
+ one-dimensional ckmeans clustering algorithm is used to cluster entries
240
+ based on value similarity. For example, if there are five entries in the
241
+ dictionary with values of 100, 102, 105, 210, and 220 respectively, and
242
+ you ask for two bins, the first bin will contain three entries and the
243
+ second will contain two. This is usually what you want.
244
+
245
+ Returns: An list ``bincount`` two-element tuples. The first element is a
246
+ list of dictionary keys in this bin; the second is the average
247
+ value of the items in this bin.
248
+ """
249
+ justvalues = d.values()
250
+ if bincount > len(d.keys()):
251
+ bincount = len(d.keys())
252
+ clusters = ckmeans(list(justvalues), bincount)
253
+ binned = []
254
+ for c in clusters:
255
+ thiscluster = []
256
+ for k, v in d.items():
257
+ if v in c:
258
+ thiscluster.append((k, v))
259
+ thiscluster = (
260
+ [x[0] for x in thiscluster],
261
+ int(statistics.mean([x[1] for x in thiscluster])),
262
+ )
263
+ binned.append(thiscluster)
264
+ return binned
265
+
266
+
267
+ def bin_glyphs_by_metric(font, glyphs, category, bincount=5):
268
+ """Organise glyphs according to a given metric.
269
+
270
+ Organises similar glyphs into a number of bins. See documentation for
271
+ :func:`bin_dictionary` above.
272
+
273
+ Args:
274
+ font: a ``fontTools`` TTFont object or a ``glyphsLib`` GSFontMaster
275
+ object OR a ``babelfont`` Font object.
276
+ glyphs: a collection of glyph names
277
+ category: the metric (see metric keys in :func:`get_glyph_metrics`.)
278
+ bincount: number of bins to return
279
+
280
+ Returns:
281
+ A list of
282
+ """
283
+ metrics = {g: get_glyph_metrics(font, g)[category] for g in glyphs}
284
+ return bin_dictionary(metrics, bincount)
285
+
286
+
287
+ def get_beziers(font, glyph):
288
+ """Return the glyph as a set of ``beziers.BezierPath`` objects.
289
+
290
+ Args:
291
+ font: a ``fontTools`` TTFont object or a ``glyphsLib`` GSFontMaster
292
+ object OR a ``babelfont`` Font object.
293
+ glyph: name of the glyph.
294
+
295
+ Returns: A list of ``BezierPath`` objects.
296
+
297
+ """
298
+ if glyphtools.glyphs.isglyphs(font):
299
+ return glyphtools.glyphs.beziers(font, glyph)
300
+ elif glyphtools.babelfont.isbabelfont3(font):
301
+ return BezierPath.fromDrawable(
302
+ glyphtools.babelfont.get_glyph(font, glyph),
303
+ {k: font.default_master.get_glyph_layer(k) for k in font.glyphs.keys()},
304
+ )
305
+ elif glyphtools.babelfont.isbabelfont(font):
306
+ return BezierPath.fromDrawable(font[glyph], font)
307
+ else:
308
+ return BezierPath.fromFonttoolsGlyph(font, glyph)
309
+
310
+
311
+ def determine_kern(
312
+ font, glyph1, glyph2, targetdistance, offset1=(0, 0), offset2=(0, 0), maxtuck=0.4
313
+ ):
314
+ """Determine a kerning value required to set two glyphs at given ink-to-ink distance.
315
+
316
+ The value is bounded by the ``maxtuck`` parameter. For example, if
317
+ ``maxtuck`` is 0.20, the right glyph will not be placed any further
318
+ left than 80% of the width of left glyph, even if this places the
319
+ ink further than ``targetdistance`` units away.
320
+
321
+ Args:
322
+ font: a ``fontTools`` TTFont object or a ``glyphsLib`` GSFontMaster
323
+ object OR a ``babelfont`` Font object.
324
+ glyph1: name of the left glyph.
325
+ glyph2: name of the right glyph.
326
+ targetdistance: distance to set the glyphs apart.
327
+ offset1: offset (X-coordinate, Y-coordinate) to place left glyph.
328
+ offset2: offset (X-coordinate, Y-coordinate) to place right glyph.
329
+ maxtuck: maximum proportion of the left glyph's width to kern.
330
+
331
+ Returns: A kerning value, in units.
332
+ """
333
+ paths1 = get_beziers(font, glyph1)
334
+ paths2 = get_beziers(font, glyph2)
335
+ metrics1 = get_glyph_metrics(font, glyph1)
336
+ offset1 = Point(*offset1)
337
+ offset2 = Point(offset2[0] + metrics1["width"], offset2[1])
338
+ kern = 0
339
+ last_best = None
340
+
341
+ iterations = 0
342
+ while True:
343
+ # Compute min distance
344
+ min_distance = None
345
+ for p1 in paths1:
346
+ p1 = p1.clone().translate(offset1)
347
+ for p2 in paths2:
348
+ p2 = p2.clone().translate(Point(offset2.x + kern, offset2.y))
349
+ d = p1.distanceToPath(p2, samples=3)
350
+ if not min_distance or d[0] < min_distance:
351
+ min_distance = d[0]
352
+ if not last_best or min_distance < last_best:
353
+ last_best = min_distance
354
+ else:
355
+ break # Nothing helped
356
+ if abs(min_distance - targetdistance) < 1 or iterations > 10:
357
+ break
358
+ iterations = iterations + 1
359
+ kern = kern + (targetdistance - min_distance)
360
+
361
+ kern = kern - metrics1["rsb"]
362
+ if maxtuck:
363
+ kern = max(kern, -(metrics1["xMax"] * (1 + maxtuck)) + metrics1["rsb"])
364
+ else:
365
+ kern = max(kern, -(metrics1["xMax"]) + metrics1["rsb"])
366
+ kern = max(kern, -metrics1["width"])
367
+ return int(kern)
368
+
369
+
370
+ def duplicate_glyph(babelfont, existing, new):
371
+ """Add a new glyph to the font duplicating an existing one.
372
+
373
+ Args:
374
+ font: a ``babelfont``/``fontParts`` Font object.
375
+ existing: name of the glyph to duplicate.
376
+ new: name of the glyph to add.
377
+ """
378
+ existing_glyph = glyphtools.layers[0][existing]
379
+ new_glyph = glyphtools.layers[0].newGlyph(new)
380
+
381
+ for c in existing_glyph.contours:
382
+ new_glyph.appendContour(c)
383
+ for c in existing_glyph.components:
384
+ new_glyph.appendComponent(c)
385
+ new_glyph.width = existing_glyph.width
386
+ old_category = babelfont[existing].category # babelfont only
387
+ set_glyph_category(babelfont, new, old_category[0], old_category[1])
@@ -0,0 +1,55 @@
1
+ def isbabelfont(font):
2
+ if hasattr(font, "_set_kerning"): # BBF 1
3
+ return True
4
+ if isbabelfont3(font):
5
+ return True
6
+ return False
7
+
8
+
9
+ def isbabelfont3(font):
10
+ if hasattr(font, "_master_map"): # BBF 3 Font
11
+ return True
12
+ if hasattr(font, "get_glyph_layer"): # BBF 3 Master
13
+ return True
14
+ return False
15
+
16
+
17
+ def get_glyph(font, glyphname):
18
+ if hasattr(font, "_master_map"): # BBF 3 Font
19
+ return font.default_master.get_glyph_layer(glyphname)
20
+ if hasattr(font, "get_glyph_layer"): # BBF 3 Master
21
+ return font.get_glyph_layer(glyphname)
22
+ return font[glyphname]
23
+
24
+ def get_glyph_metrics(font, glyphname):
25
+ g = get_glyph(font, glyphname)
26
+ if isbabelfont3(font):
27
+ metrics = {"width": g.width, "lsb": g.lsb, "rsb": g.rsb}
28
+ else:
29
+ metrics = {"width": g.width, "lsb": g.leftMargin, "rsb": g.rightMargin}
30
+ bounds = g.bounds
31
+ if bounds:
32
+ (metrics["xMin"], metrics["yMin"], metrics["xMax"], metrics["yMax"]) = g.bounds
33
+ else:
34
+ (metrics["xMin"], metrics["yMin"], metrics["xMax"], metrics["yMax"]) = (0,0,0,0)
35
+ metrics["rise"] = get_rise(g)
36
+ metrics["run"] = get_run(g)
37
+ metrics["fullwidth"] = metrics["xMax"] - metrics["xMin"]
38
+ return metrics
39
+
40
+
41
+ def get_rise(glyph):
42
+ entry = [a.y for a in glyph.anchors if a.name == "entry"]
43
+ entry.append(0) # In case there isn't one
44
+ exit = [a.y for a in glyph.anchors if a.name == "exit"]
45
+ exit.append(0)
46
+
47
+ return entry[0] - exit[0]
48
+
49
+ def get_run(glyph):
50
+ entry = [a.x for a in glyph.anchors if a.name == "entry"]
51
+ entry.append(glyph.width) # In case there isn't one
52
+ exit = [a.x for a in glyph.anchors if a.name == "exit"]
53
+ exit.append(0)
54
+
55
+ return entry[0] - exit[0]
glyphtools/ckmeans.py ADDED
@@ -0,0 +1,111 @@
1
+ import numpy as np
2
+
3
+ def ssq(j, i, sum_x, sum_x_sq):
4
+ if (j > 0):
5
+ muji = (sum_x[i] - sum_x[j-1]) / (i - j + 1)
6
+ sji = sum_x_sq[i] - sum_x_sq[j-1] - (i - j + 1) * muji ** 2
7
+ else:
8
+ sji = sum_x_sq[i] - sum_x[i] ** 2 / (i+1)
9
+
10
+ return 0 if sji < 0 else sji
11
+
12
+ def fill_row_k(imin, imax, k, S, J, sum_x, sum_x_sq, N):
13
+ if imin > imax: return
14
+
15
+ i = (imin+imax) // 2
16
+ S[k][i] = S[k-1][i-1]
17
+ J[k][i] = i
18
+
19
+ jlow = k
20
+
21
+ if imin > k:
22
+ jlow = int(max(jlow, J[k][imin-1]))
23
+ jlow = int(max(jlow, J[k-1][i]))
24
+
25
+ jhigh = i-1
26
+ if imax < N-1:
27
+ jhigh = int(min(jhigh, J[k][imax+1]))
28
+
29
+ for j in range(jhigh, jlow-1, -1):
30
+ sji = ssq(j, i, sum_x, sum_x_sq)
31
+
32
+ if sji + S[k-1][jlow-1] >= S[k][i]: break
33
+
34
+ # Examine the lower bound of the cluster border
35
+ # compute s(jlow, i)
36
+ sjlowi = ssq(jlow, i, sum_x, sum_x_sq)
37
+
38
+ SSQ_jlow = sjlowi + S[k-1][jlow-1]
39
+
40
+ if SSQ_jlow < S[k][i]:
41
+ S[k][i] = SSQ_jlow
42
+ J[k][i] = jlow
43
+
44
+ jlow += 1
45
+
46
+ SSQ_j = sji + S[k-1][j-1]
47
+ if SSQ_j < S[k][i]:
48
+ S[k][i] = SSQ_j
49
+ J[k][i] = j
50
+
51
+ fill_row_k(imin, i-1, k, S, J, sum_x, sum_x_sq, N)
52
+ fill_row_k(i+1, imax, k, S, J, sum_x, sum_x_sq, N)
53
+
54
+ def fill_dp_matrix(data, S, J, K, N):
55
+ sum_x = np.zeros(N, dtype=np.float64)
56
+ sum_x_sq = np.zeros(N, dtype=np.float64)
57
+
58
+ # median. used to shift the values of x to improve numerical stability
59
+ shift = data[N//2]
60
+
61
+ for i in range(N):
62
+ if i == 0:
63
+ sum_x[0] = data[0] - shift
64
+ sum_x_sq[0] = (data[0] - shift) ** 2
65
+ else:
66
+ sum_x[i] = sum_x[i-1] + data[i] - shift
67
+ sum_x_sq[i] = sum_x_sq[i-1] + (data[i] - shift) ** 2
68
+
69
+ S[0][i] = ssq(0, i, sum_x, sum_x_sq)
70
+ J[0][i] = 0
71
+
72
+ for k in range(1, K):
73
+ if (k < K-1):
74
+ imin = max(1, k)
75
+ else:
76
+ imin = N-1
77
+
78
+ fill_row_k(imin, N-1, k, S, J, sum_x, sum_x_sq, N)
79
+
80
+ def ckmeans(data, n_clusters):
81
+ if n_clusters <= 0:
82
+ raise ValueError("Cannot classify into 0 or less clusters")
83
+ if n_clusters > len(data):
84
+ raise ValueError("Cannot generate more classes than there are data values")
85
+
86
+ # if there's only one value, return it; there's no sensible way to split
87
+ # it. This means that len(ckmeans([data], 2)) may not == 2. Is that OK?
88
+ unique = len(set(data))
89
+ if unique == 1:
90
+ return [data]
91
+
92
+ data.sort()
93
+ n = len(data)
94
+
95
+ S = np.zeros((n_clusters, n), dtype=np.float64)
96
+
97
+ J = np.zeros((n_clusters, n), dtype=np.uint64)
98
+
99
+ fill_dp_matrix(data, S, J, n_clusters, n)
100
+
101
+ clusters = []
102
+ cluster_right = n-1
103
+
104
+ for cluster in range(n_clusters-1, -1, -1):
105
+ cluster_left = int(J[cluster][cluster_right])
106
+ clusters.append(data[cluster_left:cluster_right+1])
107
+
108
+ if cluster > 0:
109
+ cluster_right = cluster_left - 1
110
+
111
+ return list(reversed(clusters))
glyphtools/glyphs.py ADDED
@@ -0,0 +1,78 @@
1
+ from beziers.path import BezierPath
2
+
3
+
4
+ def isglyphs(fontmaster):
5
+ return hasattr(fontmaster, "userData")
6
+
7
+
8
+ def categorize_glyph(fontmaster, glyphname):
9
+ c = fontmaster.font.glyphs[glyphname].category
10
+ sc = fontmaster.font.glyphs[glyphname].subCategory
11
+ if sc == "Ligature":
12
+ return ("ligature", None)
13
+ if c == "Mark":
14
+ return ("mark", None)
15
+ return ("base", None)
16
+
17
+
18
+ def set_glyph_category(fontmaster, glyphname, category):
19
+ glyph = fontmaster.font.glyphs[glyphname]
20
+ if category == "ligature":
21
+ glyph.storeSubCategory = True
22
+ glyph.subCategory = "Ligature"
23
+ elif category == "mark":
24
+ glyph.storeCategory = True
25
+ glyph.category = "Mark"
26
+ else:
27
+ glyph.storeCategory = True
28
+ glyph.category = "Letter"
29
+
30
+
31
+ def get_glyph_metrics(fontmaster, glyphname):
32
+ glyph = fontmaster.font.glyphs[glyphname]
33
+ layer = glyph.layers[fontmaster.id]
34
+ metrics = {"width": layer.width}
35
+ # If it's a nonspacing mark then its advance width is really zero
36
+ if glyph.subCategory == "Nonspacing":
37
+ metrics["width"] = 0
38
+
39
+ bounds = layer.bounds
40
+ if bounds:
41
+ metrics["lsb"] = bounds.origin.x
42
+ metrics["xMin"] = bounds.origin.x # That doesn't look right
43
+ metrics["yMin"] = bounds.origin.y
44
+ metrics["xMax"] = bounds.origin.x + bounds.size.width
45
+ metrics["yMax"] = bounds.origin.y + bounds.size.height
46
+ else:
47
+ metrics["lsb"], metrics["xMin"], metrics["xMax"] = 0,0,0
48
+ metrics["yMin"], metrics["yMax"] = 0,0
49
+ metrics["rsb"] = metrics["width"] - metrics["xMax"]
50
+ metrics["rise"] = get_rise(fontmaster, glyphname)
51
+ metrics["run"] = get_run(fontmaster, glyphname)
52
+ metrics["fullwidth"] = metrics["xMax"] - metrics["xMin"]
53
+ return metrics
54
+
55
+
56
+ def get_rise(fontmaster, glyphname):
57
+ # Don't import glyphsLib until we know we're dealing with a glyphs obj
58
+ from glyphsLib import GSAnchor
59
+ from glyphsLib.types import Point
60
+
61
+ layer = fontmaster.font.glyphs[glyphname].layers[fontmaster.id]
62
+ entry = layer.anchors["entry"] or GSAnchor("entry", Point(0, 0))
63
+ exit = layer.anchors["exit"] or GSAnchor("exit", Point(0, 0))
64
+ return entry.position.y - exit.position.y
65
+
66
+ def get_run(fontmaster, glyphname):
67
+ from glyphsLib import GSAnchor
68
+ from glyphsLib.types import Point
69
+ layer = fontmaster.font.glyphs[glyphname].layers[fontmaster.id]
70
+ entry = layer.anchors["entry"] or GSAnchor("entry", Point(layer.width, 0))
71
+ exit = layer.anchors["exit"] or GSAnchor("exit", Point(0, 0))
72
+ return entry.position.x - exit.position.x
73
+
74
+
75
+
76
+ def beziers(fontmaster, glyphname):
77
+ layer = fontmaster.font.glyphs[glyphname].layers[fontmaster.id]
78
+ return BezierPath.fromGlyphsLayer(layer)
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: glyphtools
3
+ Version: 0.9.0
4
+ Summary: Routines for extracting information from fontTools glyphs
5
+ Author-email: Simon Cozens <simon@simon-cozens.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/simoncozens/glyphtools
8
+ Project-URL: Documentation, https://glyphtools.readthedocs.io
9
+ Project-URL: Source, https://github.com/simoncozens/glyphtools
10
+ Project-URL: Changelog, https://github.com/simoncozens/glyphtools/blob/master/HISTORY.rst
11
+ Project-URL: Issues, https://github.com/simoncozens/glyphtools/issues
12
+ Keywords: glyphtools
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: English
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>2.0.0
27
+ Requires-Dist: beziers
28
+ Requires-Dist: babelfont>0.2.0
29
+ Requires-Dist: glyphsLib
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest; extra == "test"
32
+ Provides-Extra: docs
33
+ Requires-Dist: sphinx; extra == "docs"
34
+ Requires-Dist: sphinxcontrib-restbuilder; extra == "docs"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest; extra == "dev"
37
+ Requires-Dist: black; extra == "dev"
38
+ Requires-Dist: ruff; extra == "dev"
39
+ Requires-Dist: build; extra == "dev"
40
+ Requires-Dist: twine; extra == "dev"
41
+ Requires-Dist: bump-my-version; extra == "dev"
42
+ Requires-Dist: sphinx; extra == "dev"
43
+ Requires-Dist: sphinxcontrib-restbuilder; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ ===========
47
+ glyphtools
48
+ ===========
49
+
50
+
51
+ .. image:: https://img.shields.io/pypi/v/glyphtools.svg
52
+ :target: https://pypi.python.org/pypi/glyphtools
53
+
54
+ .. image:: https://github.com/simoncozens/glyphtools/actions/workflows/ci.yml/badge.svg
55
+ :target: https://github.com/simoncozens/glyphtools/actions/workflows/ci.yml
56
+
57
+ .. image:: https://readthedocs.org/projects/glyphtools/badge/?version=latest
58
+ :target: https://glyphtools.readthedocs.io/en/latest/?badge=latest
59
+ :alt: Documentation Status
60
+
61
+
62
+ Routines for extracting information from font glyphs
63
+
64
+
65
+ **glyphtools.bin_glyphs_by_metric(font, glyphs, category,
66
+ bincount=5)**
67
+
68
+ Organise glyphs according to a given metric.
69
+
70
+ Organises similar glyphs into a number of bins. The bins are not
71
+ guaranteed to contain the same number of glyphs; the
72
+ one-dimensional ckmeans clustering algorithm is used to cluster
73
+ glyphs based on metric similarity. For example, if there are five
74
+ glyphs of width 100, 102, 105, 210, and 220 units respectively, and
75
+ you ask for two bins, the first bin will contain three glyphs and
76
+ the second will contain two. This is usually what you want.
77
+
78
+ :Parameters:
79
+ * **font** – a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster object OR a ``babelfont`` Font object.
80
+
81
+ * **glyphs** – a collection of glyph names
82
+
83
+ * **category** – the metric (see metric keys in
84
+ get_glyph_metrics().)
85
+
86
+ * **bincount** – number of bins to return
87
+
88
+ :Returns:
89
+ A list of ``bincount`` two-element tuples. The first element is
90
+ a list of glyphnames in this bin; the second is the average
91
+ metric value of the glyphs in this bin.
92
+
93
+ **glyphtools.categorize_glyph(font, glyphname)**
94
+
95
+ Returns the category of the given glyph.
96
+
97
+ :Parameters:
98
+ * **font** – a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster object OR a ``babelfont`` Font object.
99
+
100
+ * **glyphname** – name of the glyph.
101
+
102
+ :Returns:
103
+ A two-element tuple. The first element is one of the following
104
+ strings: ``unknown``, ``base``, ``mark``, ``ligature``,
105
+ ``component``. If the glyph is a mark, the second element is the
106
+ mark attachment class number.
107
+
108
+ **glyphtools.determine_kern(font, glyph1, glyph2, targetdistance,
109
+ offset1=0, 0, offset2=0, 0, maxtuck=0.4)**
110
+
111
+ Determine a kerning value required to set two glyphs at given
112
+ ink-to-ink distance.
113
+
114
+ The value is bounded by the ``maxtuck`` parameter. For example, if
115
+ ``maxtuck`` is 0.20, the right glyph will not be placed any further
116
+ left than 80% of the width of left glyph, even if this places the
117
+ ink further than ``targetdistance`` units away.
118
+
119
+ :Parameters:
120
+ * **font** – a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster object OR a ``babelfont`` Font object.
121
+
122
+ * **glyph1** – name of the left glyph.
123
+
124
+ * **glyph2** – name of the right glyph.
125
+
126
+ * **targetdistance** – distance to set the glyphs apart.
127
+
128
+ * **offset1** – offset (X-coordinate, Y-coordinate) to place
129
+ left glyph.
130
+
131
+ * **offset2** – offset (X-coordinate, Y-coordinate) to place
132
+ right glyph.
133
+
134
+ * **maxtuck** – maximum proportion of the left glyph’s width to
135
+ kern.
136
+
137
+ Returns: A kerning value, in units.
138
+
139
+ **glyphtools.duplicate_glyph(font, existing, new)**
140
+
141
+ Add a new glyph to the font duplicating an existing one.
142
+
143
+ :Parameters:
144
+ * **font** – a ``babelfont`` Font object.
145
+
146
+ * **existing** – name of the glyph to duplicate.
147
+
148
+ * **new** – name of the glyph to add.
149
+
150
+ **glyphtools.get_glyph_metrics(font, glyphname)**
151
+
152
+ Returns glyph metrics as a dictionary.
153
+
154
+ :Parameters:
155
+ * **font** – a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster object OR a ``babelfont`` Font object.
156
+
157
+ * **glyphname** – name of the glyph.
158
+
159
+ :Returns:
160
+ width: Advance width of the glyph. lsb: Left side-bearing rsb:
161
+ Right side-bearing xMin: minimum X coordinate xMax: maximum X
162
+ coordinate yMin: minimum Y coordinate yMax: maximum Y coordinate
163
+ rise: difference in Y coordinate between cursive entry and exit
164
+
165
+ :Return type:
166
+ A dictionary with the following keys
167
+
168
+ **glyphtools.set_glyph_category(font, glyphname, category,
169
+ maClass=None)**
170
+
171
+ Sets the category of the glyph in the font.
172
+
173
+ :Parameters:
174
+ * **font** – a ``fontTools`` TTFont object OR a ``glyphsLib`` GSFontMaster object OR a ``babelfont`` Font object.
175
+
176
+ * **glyphname** – name of the glyph.
177
+
178
+ * **category** – one of ``base``, ``mark``, ``ligature``,
179
+ ``component``.
180
+
181
+ * **maClass** – If the category is ``base``, the mark
182
+ attachment class number.
183
+
184
+
185
+
186
+ * Free software: Apache Software License 2.0
187
+ * Documentation: https://glyphtools.readthedocs.io.
@@ -0,0 +1,9 @@
1
+ glyphtools/__init__.py,sha256=pvh-pFaXEmSCKYM2oP504IALxDHlTWTPvOHbajqTl3Q,14212
2
+ glyphtools/babelfont.py,sha256=N3JtyqIPFG5UWy6UmOzPAQEJDWq2IxMOYpXR3UcyrGg,1741
3
+ glyphtools/ckmeans.py,sha256=3LeUu_z-swNB6G-0yKUMN7LgfJWoEWo6lGwTQSCEhgc,2966
4
+ glyphtools/glyphs.py,sha256=i5ms1OMI-Vvd3Sd8rjmZAniRYEZqPIkWvxSjVRmDhvk,2736
5
+ glyphtools-0.9.0.dist-info/licenses/LICENSE,sha256=EKigCCw1_P39HSgbiZwa-xpC6Mk-G9awOD6aicHxRA0,584
6
+ glyphtools-0.9.0.dist-info/METADATA,sha256=UXjXu3-ZIfFFJZC4pReqR-PfRPsICSlfRhUcpx7Qguk,6607
7
+ glyphtools-0.9.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ glyphtools-0.9.0.dist-info/top_level.txt,sha256=3m7FN8LPiXuu6eaelFHg0vHnw3p4zBA-oJJ9cuTdfOY,11
9
+ glyphtools-0.9.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,16 @@
1
+ Apache Software License 2.0
2
+
3
+ Copyright (c) 2020, Simon Cozens
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
@@ -0,0 +1 @@
1
+ glyphtools