-
Notifications
You must be signed in to change notification settings - Fork 35
/
uniData.py
1161 lines (1037 loc) · 42.5 KB
/
uniData.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
import weakref
import unicodedata
from fontTools.agl import AGL2UV
from defcon.tools import unicodeTools
from defcon.objects.base import BaseDictObject
class UnicodeData(BaseDictObject):
"""
This object serves Unicode data for the font.
**This object posts the following notifications:**
- UnicodeData.Changed
This object behaves like a dict. The keys are Unicode values and the
values are lists of glyph names associated with that unicode value::
{
65 : ["A"],
66 : ["B"],
}
To get the list of glyph names associated with a particular Unicode
value, do this::
glyphList = unicodeData[65]
The object defines many more convenient ways of interacting
with this data.
.. warning::
Setting data into this object manually is *highly* discouraged.
The object automatically keeps itself in sync with the font and the
glyphs contained in the font. No manual intervention is required.
"""
changeNotificationName = "UnicodeData.Changed"
representationFactories = {}
def __init__(self, layer=None):
self._layer = None
if layer is not None:
self._layer = weakref.ref(layer)
super(UnicodeData, self).__init__()
self.beginSelfNotificationObservation()
self._glyphNameToForcedUnicode = {}
self._forcedUnicodeToGlyphName = {}
# --------------
# Parent Objects
# --------------
def getParent(self):
return self.layer
def _get_font(self):
layerSet = self.layerSet
if layerSet is None:
return None
return layerSet.font
font = property(_get_font, doc="The :class:`Font` that this object belongs to.")
def _get_layerSet(self):
layer = self.layer
if layer is None:
return None
return layer.layerSet
layerSet = property(_get_layerSet, doc="The :class:`LayerSet` that this object belongs to.")
def _get_layer(self):
if self._layer is None:
return None
return self._layer()
layer = property(_get_layer, doc="The :class:`Layer` that this object belongs to.")
# -----------
# set and get
# -----------
def removeGlyphData(self, glyphName, values):
"""
Remove the data for the glyph with **glyphName** and
the Unicode values **values**.
This should never be called directly.
"""
for value in values:
if value not in self:
continue
glyphList = self[value]
if glyphName in glyphList:
glyphList.remove(glyphName)
if not glyphList:
super(UnicodeData, self).__delitem__(value)
# remove the forced reference to the glyph
if glyphName in self._glyphNameToForcedUnicode:
fourcedValue = self._glyphNameToForcedUnicode[glyphName]
del self._glyphNameToForcedUnicode[glyphName]
del self._forcedUnicodeToGlyphName[fourcedValue]
self.postNotification(notification=self.changeNotificationName)
def addGlyphData(self, glyphName, values):
"""
Add the data for the glyph with **glyphName** and
the Unicode values **values**.
This should never be called directly.
"""
for value in values:
# update unicode to glyph name
glyphList = self.get(value, [])
if glyphName not in glyphList:
glyphList.append(glyphName)
super(UnicodeData, self).__setitem__(value, glyphList)
self.postNotification(notification=self.changeNotificationName)
def __delitem__(self, value):
glyphList = self.get(value)
if glyphList is None:
return
for glyphName in glyphList:
# remove forced references
if glyphName in self._glyphNameToForcedUnicode:
forcedValue = self._glyphNameToForcedUnicode[glyphName]
del self._forcedUnicodeToGlyphName[forcedValue]
del self._glyphNameToForcedUnicode[glyphName]
super(UnicodeData, self).__delitem__(value)
self.postNotification(notification=self.changeNotificationName)
def __setitem__(self, value, glyphList):
if value not in self:
super(UnicodeData, self).__setitem__(value, [])
for glyphName in glyphList:
self[value].append(glyphName)
# remove now out dated forced references
if glyphName in self._glyphNameToForcedUnicode:
forcedValue = self._glyphNameToForcedUnicode[glyphName]
del self._forcedUnicodeToGlyphName[forcedValue]
del self._glyphNameToForcedUnicode[glyphName]
self.postNotification(notification=self.changeNotificationName)
def clear(self):
"""
Completely remove all stored data.
This should never be called directly.
"""
super(UnicodeData, self).clear()
self._forcedUnicodeToGlyphName.clear()
self._glyphNameToForcedUnicode.clear()
def update(self, other):
"""
Update the data int this object with the data from **other**.
This should never be called directly.
"""
for value, glyphList in other.items():
for glyphName in glyphList:
if glyphName in self._glyphNameToForcedUnicode:
forcedValue = self._glyphNameToForcedUnicode[glyphName]
del self._forcedUnicodeToGlyphName[forcedValue]
del self._glyphNameToForcedUnicode[glyphName]
super(UnicodeData, self).__setitem__(value, list(glyphList))
self.postNotification(notification=self.changeNotificationName)
# -------
# Loaders
# -------
def _setupForcedValueDict(self):
for value, glyphList in self.values():
if not glyphList:
glyphName = None
else:
glyphName = glyphList[0]
if value >= _privateUse1Min and value <= _privateUse1Max:
self._forcedUnicodeToGlyphName[value] = glyphName
elif value >= _privateUse2Min and value <= _privateUse2Max:
self._forcedUnicodeToGlyphName[value] = glyphName
elif value >= _privateUse3Min and value <= _privateUse3Max:
self._forcedUnicodeToGlyphName[value] = glyphName
def _loadForcedUnicodeValue(self, glyphName):
# already loaded
if glyphName in self._glyphNameToForcedUnicode:
return
# glyph has a real unicode
if self.unicodeForGlyphName(glyphName) is not None:
return
# start at the highest point, falling back to the bottom of the PUA
startPoint = max(list(self._forcedUnicodeToGlyphName.keys()) + [_privateUse1Min])
# find the value and store it
value = _findAvailablePUACode(self._forcedUnicodeToGlyphName)
self._forcedUnicodeToGlyphName[value] = glyphName
self._glyphNameToForcedUnicode[glyphName] = value
# ---------------
# Value Retrieval
# ---------------
def unicodeForGlyphName(self, glyphName):
"""
Get the Unicode value for **glyphName**. Returns *None*
if no value is found.
"""
font = self.font
if glyphName not in font:
return None
glyph = font[glyphName]
unicodes = glyph.unicodes
if not unicodes:
return None
return unicodes[0]
def glyphNameForUnicode(self, value):
"""
Get the first glyph assigned to the Unicode specified
as **value**. This will return *None* if no glyph is found.
"""
glyphList = self.get(value)
if not glyphList:
return None
return glyphList[0]
def pseudoUnicodeForGlyphName(self, glyphName):
"""
Get the pseudo-Unicode value for **glyphName**.
This will return *None* if nothing is found.
"""
realValue = self.unicodeForGlyphName(glyphName)
if realValue is not None:
return realValue
# glyph doesn't have a suffix
if glyphName.startswith(".") or glyphName.startswith("_"):
return None
if "." not in glyphName and "_" not in glyphName:
return None
# get the base
base = glyphName.split(".")[0]
# in the case of ligatures, grab the first glyph
base = base.split("_")[0]
# get the value for the base
return self.unicodeForGlyphName(base)
def forcedUnicodeForGlyphName(self, glyphName):
"""
Get the forced-Unicode value for **glyphName**.
"""
realValue = self.unicodeForGlyphName(glyphName)
if realValue is not None:
return realValue
if glyphName not in self._glyphNameToForcedUnicode:
self._loadForcedUnicodeValue(glyphName)
return self._glyphNameToForcedUnicode[glyphName]
def glyphNameForForcedUnicode(self, value):
"""
Get the glyph name assigned to the forced-Unicode
specified by **value**.
"""
if value in self:
glyphName = self[value]
if isinstance(glyphName, list):
glyphName = glyphName[0]
return glyphName
# A value will not be considered valid until it has
# been mapped to a glyph name. Therefore, unknown
# values should return None
if value not in self._forcedUnicodeToGlyphName:
return None
return self._forcedUnicodeToGlyphName[value]
# ---------------------
# Description Retrieval
# ---------------------
def scriptForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the script for **glyphName**. If **allowPseudoUnicode** is
True, a pseudo-Unicode value will be used if needed. This will
return *None* if nothing can be found.
"""
if allowPseudoUnicode:
value = self.pseudoUnicodeForGlyphName(glyphName)
else:
value = self.unicodeForGlyphName(glyphName)
if value is None:
return "Unknown"
return unicodeTools.script(value)
def blockForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the block for **glyphName**. If **allowPseudoUnicode** is
True, a pseudo-Unicode value will be used if needed. This will
return *None* if nothing can be found.
"""
if allowPseudoUnicode:
value = self.pseudoUnicodeForGlyphName(glyphName)
else:
value = self.unicodeForGlyphName(glyphName)
if value is None:
return "No_Block"
return unicodeTools.block(value)
def categoryForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the category for **glyphName**. If **allowPseudoUnicode** is
True, a pseudo-Unicode value will be used if needed. This will
return *None* if nothing can be found.
"""
if allowPseudoUnicode:
value = self.pseudoUnicodeForGlyphName(glyphName)
else:
value = self.unicodeForGlyphName(glyphName)
if value is None:
return "Cn"
return unicodeTools.category(value)
def decompositionBaseForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the decomposition base for **glyphName**. If **allowPseudoUnicode**
is True, a pseudo-Unicode value will be used if needed. This will
return *glyphName* if nothing can be found.
"""
if allowPseudoUnicode:
uniValue = self.pseudoUnicodeForGlyphName(glyphName)
else:
uniValue = self.unicodeForGlyphName(glyphName)
if uniValue is None:
return glyphName
if uniValue is not None:
font = self.font
decomposition = unicodeTools.decompositionBase(uniValue)
if decomposition != -1:
if decomposition in font.unicodeData:
baseGlyphName = font.unicodeData[decomposition][0]
if "." in glyphName:
suffix = glyphName.split(".", 1)[1]
baseWithSuffix = baseGlyphName + "." + suffix
if baseWithSuffix in font:
baseGlyphName = baseWithSuffix
return baseGlyphName
return glyphName
def closeRelativeForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the close relative for **glyphName**. For example, if you
request the close relative of the glyph name for the character (,
you will be given the glyph name for the character ) if it exists
in the font. If **allowPseudoUnicode** is True, a pseudo-Unicode
value will be used if needed. This will return *None* if nothing
can be found.
"""
return self._openCloseSearch(glyphName, allowPseudoUnicode, unicodeTools.closeRelative)
def openRelativeForGlyphName(self, glyphName, allowPseudoUnicode=True):
"""
Get the open relative for **glyphName**. For example, if you
request the open relative of the glyph name for the character ),
you will be given the glyph name for the character ( if it exists
in the font. If **allowPseudoUnicode** is True, a pseudo-Unicode
value will be used if needed. This will return *None* if nothing
can be found.
"""
return self._openCloseSearch(glyphName, allowPseudoUnicode, unicodeTools.openRelative)
def _openCloseSearch(self, glyphName, allowPseudoUnicode, lookup):
if allowPseudoUnicode:
uniValue = self.pseudoUnicodeForGlyphName(glyphName)
else:
uniValue = self.unicodeForGlyphName(glyphName)
if uniValue is None:
return
relativeValue = lookup(uniValue)
# no defined relative value. return.
if relativeValue is None:
return
# look for a hit on the unicode value.
# if none exists, return.
preciseMatch = self.glyphNameForUnicode(relativeValue)
if preciseMatch is None:
return
# pseudo unicode is not allowed. use precise match.
if not allowPseudoUnicode:
return preciseMatch
# add the suffix from the provided glyph name to the
# recise match and test for existence. if it does
# exist, return it. otherwise fallback to the
# precise match.
if "." in glyphName:
suffix = glyphName.split(".", 1)[1]
pseudoMatch = preciseMatch + "." + suffix
if pseudoMatch in self.font:
return pseudoMatch
return preciseMatch
# -------
# Sorting
# -------
def sortGlyphNames(self, glyphNames, sortDescriptors=[dict(type="unicode")]):
"""
This sorts the list of **glyphNames** following the sort descriptors
provided in the **sortDescriptors** list. This works by iterating over
the sort descriptors and subdividing. For example, if the first
sort descriptor is a suffix type, internally, the result of the
sort will look something like this::
[
[glyphsWithNoSuffix],
[glyphsWith.suffix1],
[glyphsWith.suffix2]
]
When the second sort descriptor is processed, the results of previous
sorts are subdivided even further. For example, if the second
sort type is script::
[[
[glyphsWithNoSuffix, script1], [glyphsWithNoSuffix, script2],
[glyphsWith.suffix1, script1], [glyphsWith.suffix1, script2],
[glyphsWith.suffix2, script1], [glyphsWith.suffix2, script2]
]]
And so on. The returned list will be flattened into a list of glyph names.
Each item in **sortDescriptors** should be a dict of the following form:
================== ===========
Key Description
================== ===========
type The type of sort to perform. See below for options.
ascending Boolean representing if the glyphs should be in
ascending or descending order. Optional. The default is True.
allowPseudoUnicode Boolean representing if pseudo-Unicode
values are used. If not, real Unicode values will be used
if necessary. Optional. The default is False.
function A function. Used only for **custom** sort types. See details below.
================== ===========
*Available Sort Types:*
There are four types of sort types: simple, complex, canned and custom.
Simple sorts are based on sorting non-magical values, such as Unicode values.
Complex sorts are heuristic based sorts based on common glyph name practices,
aesthetic preferences and other hard to quantify ideas. Custom sorts are just
that, custom sorts. Canned sorts are combinations of simple, complex and custom
sorts that give optimized ordering results. Complex and canned sorts may change
with further updates, so they should not be relied on for persistent ordering.
================== ==============================================================
Simple Sort Types Description
================== ==============================================================
alphabetical Self-explanatory.
unicode Sort based on Unicode value.
script Sort based on Unicode script.
category Sort based on Unicode category.
block Sort based on Unicode block.
suffix Sort based on glyph name suffix.
decompositionBase Sort based on the base glyph defined in the decomposition rules.
================== ==============================================================
================== ==============================================================
Complex Sort Types Description
================== ==============================================================
weightedSuffix Sort based on glyph names suffix. The ordering of the
suffixes is based on the calculated "weight" of the suffix.
This value is calculated by noting what type of glyphs have
the same suffix. The more glyph types, the more important the
suffix. Additionally, glyphs with suffixes that have only
numerical differences are grouped together. For example,
a.alt, a.alt1 and a.alt319 will be grouped together.
ligature Sort into to groups: non-ligatures and ligatures.
The determination of whether a glyph is a ligature or
not is based on the Unicode value, common glyph names
or the use of an underscore in the name.
================== ==============================================================
================== ==============================================================
Canned Sort Types Description
================== ==============================================================
cannedDesign Sort glyphs into a design process friendly order.
================== ==============================================================
================== ==============================================================
Custom Sort Type Description
================== ==============================================================
custom Sort using a custom function. See details below.
================== ==============================================================
*Sorting with a custom function:*
If the builtin sort types don't do exactly what you need, you can use a **custom** sort type
that contains an arbitrary function that handles sorting externally. This follows the same
sorting logic as detailed above. The custom sort type can be used in conjunction with the
builtin sort types.
The function should follow this form::
mySortFunction(font, glyphNames, ascending=True, allowPseudoUnicode=False)
The **ascending** and **allowPseudoUnicode** arguments will be the values defined
in the sort descriptors.
The function should return a list of lists of glyph names.
An example::
def sortByE(font, glyphNames, ascending=True, allowsPseudoUnicodes=False):
startsWithE = []
doesNotStartWithE = []
for glyphName in glyphNames:
if glyphName.startswith("startsWithE"):
startsWithE.append(glyphName)
else:
doesNotStartWithE.append(glyphName)
return [startsWithE, doesNotStartWithE]
"""
blocks = [glyphNames]
typeToMethod = dict(
# simple
alphabetical=self._sortByAlphabet,
unicode=self._sortByUnicode,
category=self._sortByCategory,
block=self._sortByBlock,
script=self._sortByScript,
suffix=self._sortBySuffix,
decompositionBase=self._sortByDecompositionBase,
# complex
weightedSuffix=self._sortByWeightedSuffix,
ligature=self._sortByLigature,
# custom
custom=self._sortByCustomFunction,
# canned
cannedDesign=self._cannedSortDesign,
# private
_generalType=self._sortByGeneralType,
_whitespaceCategory=self._sortByWhitespace,
_containerPartners=self._sortByContainerPartners,
_manualGroups=self._sortByManualGroups,
_notdef=self._sortByNotdef,
)
for sortDescriptor in sortDescriptors:
sortType = sortDescriptor["type"]
ascending = sortDescriptor.get("ascending", True)
allowPseudoUnicode = sortDescriptor.get("allowPseudoUnicode", False)
function = sortDescriptor.get("function", None)
sortMethod = typeToMethod[sortType]
newBlocks = []
for block in blocks:
sortedBlock = self._sortRecurse(blocks, sortMethod, ascending, allowPseudoUnicode, function)
newBlocks.append(sortedBlock)
blocks = newBlocks
return self._flattenSortResult(blocks)
def _flattenSortResult(self, result):
final = []
for i in result:
if isinstance(i, list):
final.extend(self._flattenSortResult(i))
else:
final.append(i)
return final
def _sortRecurse(self, blocks, sortMethod, ascending, allowPseudoUnicode, function):
if not blocks:
return []
if not isinstance(list(blocks)[0], str):
sortedBlocks = []
for block in blocks:
block = self._sortRecurse(block, sortMethod, ascending, allowPseudoUnicode, function)
sortedBlocks.append(block)
return sortedBlocks
else:
if sortMethod == self._sortByCustomFunction:
return sortMethod(blocks, ascending, allowPseudoUnicode, function)
else:
return sortMethod(blocks, ascending, allowPseudoUnicode)
# simple sorts
def _sortByAlphabet(self, glyphNames, ascending, allowPseudoUnicode):
result = sorted(glyphNames)
if not ascending:
result.reverse()
return result
def _sortBySuffix(self, glyphNames, ascending, allowPseudoUnicode):
suffixToGlyphs = {None : []}
for glyphName in glyphNames:
if "." not in glyphName or glyphName.startswith("."):
suffix = None
else:
suffix = glyphName.split(".", 1)[1]
if suffix not in suffixToGlyphs:
suffixToGlyphs[suffix] = []
suffixToGlyphs[suffix].append(glyphName)
result = []
result.append(suffixToGlyphs.pop(None))
for suffix, glyphList in sorted(suffixToGlyphs.items()):
result.append(glyphList)
return result
def _sortByUnicode(self, glyphNames, ascending, allowPseudoUnicode):
withValue = []
withoutValue = []
for glyphName in glyphNames:
if allowPseudoUnicode:
value = self.pseudoUnicodeForGlyphName(glyphName)
else:
value = self.unicodeForGlyphName(glyphName)
if value is None:
withoutValue.append(glyphName)
else:
withValue.append((value, glyphName))
withValue = [glyphName for uniValue, glyphName in sorted(withValue)]
if not ascending:
withValue.reverse()
withoutValue.reverse()
result = [withoutValue, withValue]
else:
result = [withValue, withoutValue]
return result
def _sortByScript(self, glyphNames, ascending, allowPseudoUnicode):
return self._sortByUnicodeLookup(glyphNames, ascending, allowPseudoUnicode, self.scriptForGlyphName, unicodeTools.orderedScripts)
def _sortByBlock(self, glyphNames, ascending, allowPseudoUnicode):
return self._sortByUnicodeLookup(glyphNames, ascending, allowPseudoUnicode, self.blockForGlyphName, unicodeTools.orderedBlocks)
def _sortByCategory(self, glyphNames, ascending, allowPseudoUnicode):
return self._sortByUnicodeLookup(glyphNames, ascending, allowPseudoUnicode, self.categoryForGlyphName, unicodeTools.orderedCategories)
def _sortByUnicodeLookup(self, glyphNames, ascending, allowPseudoUnicode, tagLookup, orderedTags):
tagToGlyphs = {}
for glyphName in glyphNames:
tag = tagLookup(glyphName, allowPseudoUnicode)
if tag not in tagToGlyphs:
tagToGlyphs[tag] = []
tagToGlyphs[tag].append(glyphName)
if not orderedTags:
orderedTags = sorted(tagToGlyphs.keys())
if None in orderedTags:
orderedTags.remove(None)
sortedResult = []
for tag in orderedTags + [None]:
if tag in tagToGlyphs:
sortedResult.append(tagToGlyphs[tag])
if not ascending:
sortedResult.reverse()
return sortedResult
def _sortByDecompositionBase(self, glyphNames, ascending, allowPseudoUnicode):
baseToGlyphNames = {None:[]}
for glyphName in glyphNames:
if allowPseudoUnicode:
value = self.pseudoUnicodeForGlyphName(glyphName)
else:
value = self.unicodeForGlyphName(glyphName)
if value is None:
base = None
else:
base = unicodeTools.decompositionBase(value)
base = self.glyphNameForUnicode(base)
# try to add the glyph names suffix to the base.
# this will handle mapping aacute.alt to a.alt
# instead of aacute.alt to a.
if base is not None:
if "." in glyphName and not glyphName.startswith("."):
suffix = glyphName.split(".")[1]
if base + "." + suffix in self.font:
base = base + "." + suffix
if base not in baseToGlyphNames:
baseToGlyphNames[base] = []
baseToGlyphNames[base].append(glyphName)
# get the list of glyphs with no base.
noBase = baseToGlyphNames.pop(None)
# find all bases that are not in the overall glyph names list
missingBase = []
for base in sorted(baseToGlyphNames):
if base is None:
continue
if base not in noBase:
missingBase.append(base)
# work through the found bases
processedBases = set()
sortedResult = []
for base in noBase:
if base in processedBases:
continue
processedBases.add(base)
# the base could be in the list more than once.
# if so, add the proper number of instances of the base.
count = noBase.count(base)
r = [base for i in range(count)]
# add the referencing glyphs
r += baseToGlyphNames.get(base, [])
sortedResult.append(r)
# work through the missing bases
for base in sorted(missingBase):
sortedResult.append(baseToGlyphNames[base])
# reverse if necessary
if not ascending:
sortedResult.reverse()
return sortedResult
# custom sorts
def _sortByCustomFunction(self, glyphNames, ascending, allowPseudoUnicode, function):
return function(self.font, glyphNames, ascending, allowPseudoUnicode)
# complex sorts
def _sortByWeightedSuffix(self, glyphNames, ascending, allowPseudoUnicode):
# split into two groups
noSuffix = []
suffixed = []
for glyphName in glyphNames:
if glyphName.startswith(".") or "." not in glyphName:
noSuffix.append(glyphName)
else:
suffixed.append(glyphName)
if not suffixed:
return noSuffix
# magnetize the suffixes
allSuffixes = set([glyphName.split(".", 1)[-1] for glyphName in suffixed])
allSuffixes = sorted(allSuffixes)
magnets = {}
while allSuffixes:
toMatch = toMatchOriginal = allSuffixes.pop(0)
# split off trailing digits
# this makes .alt1 match .alt2
stripped = toMatch
while stripped:
c = stripped[-1]
if c.isdigit():
stripped = stripped[:-1]
else:
break
if stripped:
toMatch = stripped
# search for suffixes that start with toMatch
# and have only numerical differences
matches = []
for suffix in allSuffixes:
if suffix.lower().startswith(toMatch.lower()):
if len(suffix) == len(toMatch):
matches.append(suffix)
else:
diffLength = len(suffix) - len(toMatch)
misMatch = suffix[:-diffLength]
allDigits = False not in [c.isdigit() for c in misMatch]
if allDigits:
matches.append(suffix)
for suffix in matches:
allSuffixes.remove(suffix)
if not matches:
toMatch = toMatchOriginal
# store the result
magnets[toMatch] = [toMatchOriginal] + matches
# make a flat mapping of suffix : magnet
suffixToMagnet = {}
for magnet, suffixes in magnets.items():
for suffix in suffixes:
suffixToMagnet[suffix] = magnet
# gather data about the suffixes
suffixMap = {}
for glyphName in suffixed:
# get the suffix data dict from the map
suffix = glyphName.split(".", 1)[-1]
# get the magnet group
suffix = suffixToMagnet[suffix]
if suffix not in suffixMap:
suffixMap[suffix] = dict(glyphNames=[], letter=0, mark=0, number=0, punctuation=0, symbol=0, space=0)
suffixData = suffixMap[suffix]
# add the glyph name
suffixData["glyphNames"].append(glyphName)
# update the category flags
category = self.categoryForGlyphName(glyphName, allowPseudoUnicode=allowPseudoUnicode)
if category in "Lu Ll Lt":
suffixData["letter"] = True
elif category in "Lm Mn Mc Me":
suffixData["mark"] = True
elif category in "Nd Nl No":
suffixData["number"] = True
elif category in "Pc Pd Pe Pf Pi Po Ps":
suffixData["punctuation"] = True
elif category in "Sc Sk Sm So":
suffixData["symbol"] = True
elif category == "Zs":
suffixData["space"] = True
# rank the suffixes
sorter = []
for suffix, suffixData in suffixMap.items():
sortable = (
suffixData["letter"],
suffixData["number"],
suffixData["symbol"],
suffixData["punctuation"],
suffixData["mark"],
suffixData["space"],
-len(suffixData["glyphNames"]),
len(suffix),
suffix,
suffixData
)
sorter.append(sortable)
suffixSortedGlyphsNames = [item[-1]["glyphNames"] for item in sorted(sorter)]
if not ascending:
for i in suffixSortedGlyphsNames:
i.reverse()
sortedResult = [noSuffix] + suffixSortedGlyphsNames
if not ascending:
sortedResult.reverse()
return sortedResult
def _sortByLigature(self, glyphNames, ascending, allowPseudoUnicode):
notLigature = []
ligature = []
for glyphName in glyphNames:
base = glyphName.split(".")[0]
if "_" in base and base not in _notReallyLigatures:
ligature.append(glyphName)
elif not allowPseudoUnicode and self.unicodeForGlyphName(glyphName) in _ligatureUniValues:
ligature.append(glyphName)
elif allowPseudoUnicode and self.pseudoUnicodeForGlyphName(glyphName) in _ligatureUniValues:
ligature.append(glyphName)
elif base in ("ff", "fi", "fl", "ffi", "ffl"):
ligature.append(glyphName)
else:
notLigature.append(glyphName)
final = [notLigature, ligature]
if not ascending:
notLigature.reverse()
ligature.reverse()
final.reverse()
return final
# canned sorts
def _cannedSortDesign(self, glyphNames, ascending, allowPseudoUnicode):
sortDescriptors = [
dict(type="weightedSuffix", allowPseudoUnicode=allowPseudoUnicode),
dict(type="ligature", allowPseudoUnicode=allowPseudoUnicode),
dict(type="_generalType", allowPseudoUnicode=allowPseudoUnicode),
dict(type="_whitespaceCategory", allowPseudoUnicode=allowPseudoUnicode),
dict(type="alphabetical", allowPseudoUnicode=allowPseudoUnicode),
dict(type="unicode", allowPseudoUnicode=allowPseudoUnicode),
dict(type="category", allowPseudoUnicode=allowPseudoUnicode),
dict(type="script", allowPseudoUnicode=allowPseudoUnicode),
dict(type="decompositionBase", allowPseudoUnicode=allowPseudoUnicode),
]
glyphNames = self.sortGlyphNames(glyphNames, sortDescriptors)
sortDescriptors = [
dict(type="_containerPartners", allowPseudoUnicode=allowPseudoUnicode),
dict(type="_manualGroups", allowPseudoUnicode=allowPseudoUnicode),
dict(type="_notdef", allowPseudoUnicode=allowPseudoUnicode),
]
glyphNames = self.sortGlyphNames(glyphNames, sortDescriptors)
if not ascending:
glyphNames.reverse()
return glyphNames
# private sorts
def _sortByGeneralType(self, glyphNames, ascending, allowPseudoUnicode):
noSuffixUnicode = []
noSuffixNoUnicode = []
suffix = []
for glyphName in glyphNames:
if glyphName.startswith("."):
noSuffixNoUnicode.append(glyphName)
elif "." in glyphName:
suffix.append(glyphName)
elif self.unicodeForGlyphName(glyphName):
noSuffixUnicode.append(glyphName)
else:
noSuffixNoUnicode.append(glyphName)
final = [noSuffixUnicode, noSuffixNoUnicode, suffix]
if not ascending:
noSuffixUnicode.reverse()
noSuffixNoUnicode.reverse()
suffix.reverse()
final.reverse
return final
def _sortByWhitespace(self, glyphNames, ascending, allowPseudoUnicode):
space = []
notSpace = []
for glyphName in glyphNames:
if self.categoryForGlyphName(glyphName, allowPseudoUnicode=allowPseudoUnicode) == "Zs":
space.append(glyphName)
else:
notSpace.append(glyphName)
final = [space, notSpace]
if not ascending:
space.reverse()
notSpace.reverse()
final.reverse()
return final
def _sortByContainerPartners(self, glyphNames, ascending, allowPseudoUnicode):
glyphOrder = []
while glyphNames:
glyphName = glyphNames[0]
glyphOrder.append(glyphName)
glyphNames = glyphNames[1:]
# get the close relative
closeRelative = self.closeRelativeForGlyphName(glyphName, allowPseudoUnicode=allowPseudoUnicode)
if closeRelative is not None:
if closeRelative not in glyphOrder:
glyphOrder.append(closeRelative)
if closeRelative in glyphNames:
glyphNames.remove(closeRelative)
if not ascending:
glyphOrder.reverse()
return glyphOrder
def _sortByNotdef(self, glyphNames, ascending, allowPseudoUnicode):
notDef = []
notNotDef = []
for glyphName in glyphNames:
if glyphName.startswith(".notdef"):
notDef.append(glyphName)
else:
notNotDef.append(glyphName)
return notNotDef + notDef
def _sortByManualGroups(self, glyphNames, ascending, allowPseudoUnicode):
# build a unicode map for all glyphs
pseudoUnicodeMapping = {}
for glyphName in glyphNames:
if allowPseudoUnicode:
uniValue = self.pseudoUnicodeForGlyphName(glyphName)
else:
uniValue = self.unicodeForGlyphName(glyphName)
if uniValue not in pseudoUnicodeMapping:
pseudoUnicodeMapping[uniValue] = []
pseudoUnicodeMapping[uniValue].append(glyphName)
for pairGroup in _manualSortGroups:
# find the matching glyphs
matched = []
for uniValue in pairGroup:
matched += pseudoUnicodeMapping.get(uniValue, [])
# break the matched into suffix groups
suffixes = {}
for glyphName in matched:
if "." not in glyphName:
suffix = None
else:
suffix = glyphName.split(".", 1)[-1]
if suffix not in suffixes:
suffixes[suffix] = []
suffixes[suffix].append(glyphName)
# wor through the suffixes
for matched in suffixes.values():
# remove matched[1:] them after matched[0]
if len(matched) > 1:
for glyphName in matched[1:]:
glyphNames.remove(glyphName)
insertionPoint = glyphNames.index(matched[0])
glyphNames = glyphNames[:insertionPoint + 1] + matched[1:] + glyphNames[insertionPoint + 1:]
return glyphNames
# ------------------------
# Notification Observation
# ------------------------
def endSelfNotificationObservation(self):
super(UnicodeData, self).endSelfNotificationObservation()
self._layer = None
# -----
# Tools
# -----
# PUA lookups
_privateUse1Min = int("E000", 16)
_privateUse1Max = int("F8FF", 16)
_privateUse2Min = int("F0000", 16)
_privateUse2Max = int("FFFFD", 16)
_privateUse3Min = int("100000", 16)
_privateUse3Max = int("10FFFD", 16)
_viablePUACount = (_privateUse1Max - _privateUse1Min) + (_privateUse2Max - _privateUse2Min) + (_privateUse3Max - _privateUse3Min)
def _findAvailablePUACode(existing, code=None):
assert len(existing) < _viablePUACount
if code is None:
code = _privateUse1Min