summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/doc/fonts/amiri/tools/build.py
blob: 72e9993d768f442199f90feaf1e204cb0493a580 (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
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
#!/usr/bin/python
# coding=utf-8
#
# build.py - Amiri font build utility
#
# Written in 2010-2012 by Khaled Hosny <khaledhosny@eglug.org>
#
# To the extent possible under law, the author have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

import fontforge
import psMat
import sys
import os
import getopt
import math
from tempfile import mkstemp
from fontTools.ttLib import TTFont

def genCSS(font, base):
    """Generates a CSS snippet for webfont usage based on:
    http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax"""

    style = ("slanted" in font.fullname.lower()) and "oblique" or "normal"
    weight = font.os2_weight
    family = font.familyname + "Web"

    css = """
@font-face {
    font-family: %(family)s;
    font-style: %(style)s;
    font-weight: %(weight)s;
    src: url('%(base)s.eot?') format('eot'),
         url('%(base)s.woff') format('woff'),
         url('%(base)s.ttf')  format('truetype');
}
""" %{"style":style, "weight":weight, "family":family, "base":base}

    return css

def cleanAnchors(font):
    """Removes anchor classes (and associated lookups) that are used only
    internally for building composite glyph."""

    klasses = (
            "Dash",
            "DigitAbove",
            "DigitBelow",
            "DotAbove",
            "DotAlt",
            "DotBelow",
            "DotBelowAlt",
            "DotHmaza",
            "HamzaBelow",
            "HighHamza",
            "MarkDotAbove",
            "MarkDotBelow",
            "RingBelow",
            "RingDash",
            "Stroke",
            "TaaAbove",
            "TaaBelow",
            "Tail",
            "TashkilAboveDot",
            "TashkilBelowDot",
            "TwoDotsAbove",
            "TwoDotsBelow",
            "TwoDotsBelowAlt",
            "VAbove",
            )

    for klass in klasses:
        subtable = font.getSubtableOfAnchor(klass)
        lookup = font.getLookupOfSubtable(subtable)
        font.removeLookup(lookup)

def flattenNestedReferences(font, ref, new_transform=(1, 0, 0, 1, 0, 0)):
    """Flattens nested references by replacing them with the ultimate reference
    and applying any transformation matrices involved, so that the final font
    has only simple composite glyphs. This to work around what seems to be an
    Apple bug that results in ignoring transformation matrix of nested
    references."""

    name = ref[0]
    transform = ref[1]
    glyph = font[name]
    new_ref = []
    if glyph.references and glyph.foreground.isEmpty():
        for nested_ref in glyph.references:
            for i in flattenNestedReferences(font, nested_ref, transform):
                matrix = psMat.compose(i[1], new_transform)
                new_ref.append((i[0], matrix))
    else:
        matrix = psMat.compose(transform, new_transform)
        new_ref.append((name, matrix))

    return new_ref

def validateGlyphs(font):
    """Fixes some common FontForge validation warnings, currently handles:
        * wrong direction
        * flipped references
    In addition to flattening nested references."""

    wrong_dir = 0x8
    flipped_ref = 0x10
    for glyph in font.glyphs():
        state = glyph.validate(True)
        refs = []

        if state & flipped_ref:
            glyph.unlinkRef()
            glyph.correctDirection()
        if state & wrong_dir:
            glyph.correctDirection()

        for ref in glyph.references:
            for i in flattenNestedReferences(font, ref):
                refs.append(i)
        if refs:
            glyph.references = refs

def setVersion(font, version):
    font.version = "%07.3f" % float(version)
    for name in font.sfnt_names:
        if name[0] == "Arabic (Egypt)" and name[1] == "Version":
            font.appendSFNTName(name[0], name[1],
                                name[2].replace("VERSION", font.version.replace(".", "\xD9\xAB")))

def mergeFeatures(font, feafile):
    """Merges feature file into the font while making sure mark positioning
    lookups (already in the font) come after kerning lookups (from the feature
    file), which is required by Uniscribe to get correct mark positioning for
    kerned glyphs."""

    oldfea = mkstemp(suffix='.fea')[1]
    font.generateFeatureFile(oldfea)

    for lookup in font.gpos_lookups:
        font.removeLookup(lookup)

    font.mergeFeature(feafile)
    font.mergeFeature(oldfea)
    os.remove(oldfea)

def makeCss(infiles, outfile):
    """Builds a CSS file for the entire font family."""

    css = ""

    for f in infiles.split():
        base = os.path.splitext(os.path.basename(f))[0]
        font = fontforge.open(f)
        css += genCSS(font, base)
        font.close()

    out = open(outfile, "w")
    out.write(css)
    out.close()

def generateFont(font, outfile, hack=False):
    flags  = ("opentype", "dummy-dsig", "round", "omit-instructions")

    font.selection.all()
    font.correctReferences()
    font.selection.none()

    # fix some common font issues
    validateGlyphs(font)

    if hack:
        # ff takes long to write the file, so generate to tmp file then rename
        # it to keep fontview happy
        import subprocess
        tmpout = mkstemp(dir=".", suffix=os.path.basename(outfile))[1]
        font.generate(tmpout, flags=flags)
        #os.rename(tmpout, outfile) # file monitor will not see this, why?
        p = subprocess.Popen("cat %s > %s" %(tmpout, outfile), shell=True)
        p.wait()
        os.remove(tmpout)
    else:
        font.generate(outfile, flags=flags)
    font.close()

def drawOverUnderline(glyph, pos, thickness, width):
    pen = glyph.glyphPen()

    pen.moveTo((-50, pos))
    pen.lineTo((-50, pos + thickness))
    pen.lineTo((width + 50, pos + thickness))
    pen.lineTo((width + 50, pos))
    pen.closePath()

def makeOverUnderline(font):
    # test string:
    # صِ̅فْ̅ ̅خَ̅ل̅قَ̅ ̅بًّ̅ صِ̲فْ̲ ̲خَ̲ل̲قَ̲ ̲بِ̲

    thickness = font.uwidth # underline width (thickness)
    o_pos = font.os2_typoascent
    u_pos = font.upos - thickness # underline pos
    minwidth = 100.0

    widths = {}

    for glyph in font.glyphs():
        if glyph.glyphclass == 'baseglyph':
            width = round(glyph.width/100) * 100
            width = width > minwidth and width or minwidth
            if not width in widths:
                widths[width] = []
            widths[width].append(glyph.glyphname)

    o_encoded = font.createChar(0x0305, 'uni0305')
    u_encoded = font.createChar(0x0332, 'uni0332')
    o_encoded.width = u_encoded.width = 0
    o_encoded.glyphclass = u_encoded.glyphclass = 'mark'
    drawOverUnderline(o_encoded, o_pos, thickness, 500)
    drawOverUnderline(u_encoded, u_pos, thickness, 500)

    o_base = font.createChar(-1, 'uni0305.0')
    u_base = font.createChar(-1, 'uni0332.0')
    o_base.width = u_base.width = 0
    o_base.glyphclass = u_base.glyphclass = 'baseglyph'
    drawOverUnderline(o_base, o_pos, thickness, 500)
    drawOverUnderline(u_base, u_pos, thickness, 500)

    font.addLookup('mark hack', 'gsub_single', (), (("mark",(("arab",("dflt")),)),), font.gsub_lookups[-1])
    font.addLookupSubtable('mark hack', 'mark hack 1')

    o_encoded.addPosSub('mark hack 1', o_base.glyphname)
    u_encoded.addPosSub('mark hack 1', u_base.glyphname)

    context_lookup_name = 'OverUnderLine'
    font.addLookup(context_lookup_name, 'gsub_contextchain', ('ignore_marks'), (("mark",(("arab",("dflt")),)),), font.gsub_lookups[-1])

    for width in sorted(widths.keys()):
        o_name = 'uni0305.%d' % width
        u_name = 'uni0332.%d' % width
        o_glyph = font.createChar(-1, o_name)
        u_glyph = font.createChar(-1, u_name)

        o_glyph.glyphclass = u_glyph.glyphclass = 'mark'

        drawOverUnderline(o_glyph, o_pos, thickness, width)
        drawOverUnderline(u_glyph, u_pos, thickness, width)

        single_lookup_name = str(width)

        font.addLookup(single_lookup_name, 'gsub_single', (), (), font.gsub_lookups[-1])
        font.addLookupSubtable(single_lookup_name, single_lookup_name + '1')

        o_base.addPosSub(single_lookup_name + '1', o_name)
        u_base.addPosSub(single_lookup_name + '1', u_name)

        rule = '| [%s] [%s %s] @<%s> | ' %(" ".join(widths[width]), o_base.glyphname, u_base.glyphname, single_lookup_name)

        font.addContextualSubtable(context_lookup_name, context_lookup_name + str(width), 'coverage', rule)

def centerGlyph(glyph):
    width = glyph.width
    glyph.right_side_bearing = glyph.left_side_bearing = (glyph.right_side_bearing + glyph.left_side_bearing)/2
    glyph.width = width

def buildLatinExtras(font, italic):
    for ltr, rtl in (("question", "uni061F"), ("radical", "radical.rtlm")):
        font[rtl].clear()
        font[rtl].addReference(ltr, psMat.scale(-1, 1))
        font[rtl].left_side_bearing = font[ltr].right_side_bearing
        font[rtl].right_side_bearing = font[ltr].left_side_bearing

    # slanted arabic question mark
    if italic:
        question = font.createChar(-1, "uni061F.rtl")
        question.addReference("uni061F", italic)
        question.useRefsMetrics("uni061F")

    for name in ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"):
        if italic:
            # they are only used in Arabic contexts, so always reference the
            # italic rtl variant
            refname = name +".rtl"
        else:
            refname = name
        small = font.createChar(-1, name + ".small")
        small.clear()
        small.addReference(refname, psMat.scale(0.6))
        small.transform(psMat.translate(0, -40))
        small.width = 600
        centerGlyph(small)

        medium = font.createChar(-1, name + ".medium")
        medium.clear()
        medium.addReference(refname, psMat.scale(0.8))
        medium.transform(psMat.translate(0, 50))
        medium.width = 900
        centerGlyph(medium)

def mergeLatin(font, italic=False):
    styles = {"Regular": "Roman",
              "Slanted": "Italic",
              "Bold": "Bold",
              "BoldSlanted": "BoldItalic"}

    style = styles[font.fontname.split("-")[1]]

    latinfile = "Crimson-%s.sfd" %style

    tmpfont = mkstemp(suffix=os.path.basename(latinfile))[1]
    latinfont = fontforge.open("sources/crimson/sources/%s" %latinfile)
    latinfont.em = 2048

    # convert to quadratic splines then simplify
    latinfont.is_quadratic = True
    for glyph in latinfont.glyphs():
        glyph.simplify()

    validateGlyphs(latinfont) # to flatten nested refs mainly

    # collect latin glyphs we want to keep
    latinglyphs = []

    # we want all glyphs in latin0-9 encodings
    for i in range(0, 9):
        latinfont.encoding = 'latin%d' %i
        for glyph in latinfont.glyphs("encoding"):
            if glyph.encoding <= 255:
                if glyph.glyphname not in latinglyphs:
                    latinglyphs.append(glyph.glyphname)
            elif glyph.unicode != -1 and glyph.unicode <= 0x017F:
                # keep also Unicode Latin Extended-A block
                if glyph.glyphname not in latinglyphs:
                    latinglyphs.append(glyph.glyphname)

    # keep ligatures too
    ligatures = ("f_f", "f_i", "f_f_i", "f_l", "f_f_l", "f_b", "f_f_b", "f_k",
            "f_f_k", "f_h", "f_f_h", "f_j", "f_f_j", "T_h")

    # and Arabic romanisation characters
    romanisation = ("afii57929", "uni02BE", "uni02BE", "amacron", "uni02BE",
            "amacron", "eacute", "uni1E6F", "ccedilla", "uni1E6F", "gcaron",
            "ycircumflex", "uni1E29", "uni1E25", "uni1E2B", "uni1E96",
            "uni1E0F", "dcroat", "scaron", "scedilla", "uni1E63", "uni1E11",
            "uni1E0D", "uni1E6D", "uni1E93", "dcroat", "uni02BB", "uni02BF",
            "rcaron", "grave", "gdotaccent", "gbreve", "umacron", "imacron",
            "amacron", "amacron", "uni02BE", "amacron", "uni02BE",
            "acircumflex", "amacron", "uni1E97", "tbar", "aacute", "amacron",
            "ygrave", "agrave", "uni02BE", "aacute", "Amacron", "Amacron",
            "Eacute", "uni1E6E", "Ccedilla", "uni1E6E", "Gcaron",
            "Ycircumflex", "uni1E28", "uni1E24", "uni1E2A", "uni1E0E",
            "Dcroat", "Scaron", "Scedilla", "uni1E62", "uni1E10", "uni1E0C",
            "uni1E6C", "uni1E92", "Dcroat", "Rcaron", "Gdotaccent", "Gbreve",
            "Umacron", "Imacron", "Amacron", "Amacron", "Amacron",
            "Acircumflex", "Amacron", "Tbar", "Aacute", "Amacron", "Ygrave",
            "Agrave", "Aacute")

    # and some typographic characters
    typographic = ("uni2010", "uni2011", "figuredash", "endash", "emdash",
            "afii00208", "quoteleft", "quoteright", "quotesinglbase",
            "quotereversed", "quotedblleft", "quotedblright", "quotedblbase",
            "uni201F", "dagger", "daggerdbl", "bullet", "onedotenleader",
            "ellipsis", "uni202F", "perthousand", "minute", "second",
            "uni2038", "guilsinglleft", "guilsinglright", "uni203E",
            "fraction", "i.TRK", "minus", "uni2213", "radical", "uni2042")

    for l in (ligatures, romanisation, typographic):
        for name in l:
            if name not in latinglyphs:
                latinglyphs.append(name)

    # keep any glyph referenced by previous glyphs
    for name in latinglyphs:
        if name in latinfont:
            glyph = latinfont[name]
            for ref in glyph.references:
                latinglyphs.append(ref[0])
        else:
            print 'Font ‘%s’ is missing glyph: %s' %(font.fontname, name)

    # remove everything else
    for glyph in latinfont.glyphs():
        if glyph.glyphname not in latinglyphs:
            latinfont.removeGlyph(glyph)

    # common characters that can be used in Arabic and Latin need to be handled
    # carefully in the slanted font so that right leaning italic is used with
    # Latin, and left leaning slanted is used with Arabic, using ltra and rtla
    # features respectively, for less OpenType savvy apps we make the default
    # upright so it works reasonably with bot scripts
    if italic:
        if "Bold" in style:
            upright = fontforge.open("sources/crimson/sources/Crimson-Bold.sfd")
        else:
            upright = fontforge.open("sources/crimson/sources/Crimson-Roman.sfd")
        upright.em = 2048

        shared = ("exclam", "quotedbl", "numbersign", "dollar", "percent",
                  "quotesingle", "parenleft", "parenright", "asterisk", "plus",
                  "slash", "zero", "one", "two", "three", "four", "five",
                  "six", "seven", "eight", "nine", "colon", "semicolon",
                  "less", "equal", "greater", "question", "at", "bracketleft",
                  "backslash", "bracketright", "asciicircum", "braceleft",
                  "bar", "braceright", "brokenbar", "section", "copyright",
                  "guillemotleft", "logicalnot", "registered", "plusminus",
                  "uni00B2", "uni00B3", "paragraph", "uni00B9", "ordmasculine",
                  "guillemotright", "onequarter", "onehalf", "threequarters",
                  "questiondown", "quoteleft", "quoteright", "quotesinglbase",
                  "quotereversed", "quotedblleft", "quotedblright",
                  "quotedblbase", "uni201F", "dagger", "daggerdbl",
                  "perthousand", "minute", "second", "guilsinglleft",
                  "guilsinglright", "fraction", "uni2213")

        for name in shared:
            glyph = latinfont[name]
            glyph.glyphname += '.ltr'
            glyph.unicode = -1
            upright.selection.select(name)
            upright.copy()
            latinfont.createChar(upright[name].encoding, name)
            latinfont.selection.select(name)
            latinfont.paste()

            if not name + ".ara" in font:
                rtl = latinfont.createChar(-1, name + ".rtl")
                rtl.addReference(name, italic)
                rtl.useRefsMetrics(name)

    # copy kerning classes
    kern_lookups = {}
    for lookup in latinfont.gpos_lookups:
        kern_lookups[lookup] = {}
        kern_lookups[lookup]["subtables"] = []
        kern_lookups[lookup]["type"], kern_lookups[lookup]["flags"], dummy = latinfont.getLookupInfo(lookup)
        for subtable in latinfont.getLookupSubtables(lookup):
            if latinfont.isKerningClass(subtable):
                kern_lookups[lookup]["subtables"].append((subtable, latinfont.getKerningClass(subtable)))

    for lookup in latinfont.gpos_lookups:
        latinfont.removeLookup(lookup)

    for lookup in latinfont.gsub_lookups:
        latinfont.removeLookup(lookup)

    latinfont.save(tmpfont)
    latinfont.close()

    font.mergeFonts(tmpfont)
    os.remove(tmpfont)

    buildLatinExtras(font, italic)

    # we want to merge features after merging the latin font because many
    # referenced glyphs are in the latin font
    if font.sfd_path:
        feafile = os.path.splitext(font.sfd_path)[0] + '.fea'
        mergeFeatures(font, feafile)

    font.mergeFeature("sources/latin_gsub.fea")

    if italic:
        font.mergeFeature("sources/italic_ltra.fea")
        font.mergeFeature("sources/italic_rtla.fea")

    for lookup in kern_lookups:
        font.addLookup(lookup,
                kern_lookups[lookup]["type"],
                kern_lookups[lookup]["flags"],
                (('kern',
                        (
                            ('DFLT', ('dflt',)),
                            ('latn', ('dflt', 'TRK ')),
                        )
                    ),)
                )

        for subtable in kern_lookups[lookup]["subtables"]:
            font.addKerningClass(lookup, subtable[0], subtable[1][0], subtable[1][1], subtable[1][2])

def makeWeb(infile, outfile):
    """If we are building a web version then try to minimise file size"""

    # "short-post" generates a post table without glyph names to save some KBs
    # since glyph names are only needed for PDF's as readers use them to
    # "guess" characters when copying text, which is of little use in web fonts.
    flags = ("opentype", "short-post", "omit-instructions")

    font = fontforge.open(infile)

    # removed compatibility glyphs that of little use on the web
    compat_ranges = (
            (0xfb50, 0xfbb1),
            (0xfbd3, 0xfd3d),
            (0xfd50, 0xfdf9),
            (0xfdfc, 0xfdfc),
            (0xfe70, 0xfefc),
            )

    for glyph in font.glyphs():
        for i in compat_ranges:
            start = i[0]
            end = i[1]
            if start <= glyph.unicode <= end:
                font.removeGlyph(glyph)
                break

    tmpfont = mkstemp(suffix=os.path.basename(outfile))[1]
    font.generate(tmpfont, flags=flags)
    font.close()

    # now open in fontTools
    font = TTFont(tmpfont, recalcBBoxes=0)

    # our 'name' table is a bit bulky, and of almost no use in for web fonts,
    # so we strip all unnecessary entries.
    name = font['name']
    names = []
    for record in name.names:
        platID = record.platformID
        langID = record.langID
        nameID = record.nameID

        # we keep only en_US entries in Windows and Mac platform id, every
        # thing else is dropped
        if (platID == 1 and langID == 0) or (platID == 3 and langID == 1033):
            if nameID == 13:
                # the full OFL text is too much, replace it with a simple
                # string
                if platID == 3:
                    # MS strings are UTF-16 encoded
                    text = 'OFL v1.1'.encode('utf_16_be')
                else:
                    text = 'OFL v1.1'
                record.string = text
                names.append(record)
            # keep every thing else except Descriptor, Sample Text
            elif nameID not in (10, 19):
                names.append(record)

    name.names = names

    # FFTM is FontForge specific, remove it
    del(font['FFTM'])

    # force compiling GPOS/GSUB tables by fontTools, saves few tens of KBs
    for tag in ('GPOS', 'GSUB'):
        font[tag].compile(font)

    font.save(outfile)
    font.close()

    os.remove(tmpfont)

def makeSlanted(infile, outfile, version, slant):

    font = makeDesktop(infile, outfile, version, False, False)

    # compute amout of skew, magic formula copied from fontforge sources
    skew = psMat.skew(-slant * math.pi/180.0)

    font.selection.all()
    font.transform(skew)

    # fix metadata
    font.italicangle = slant
    font.fullname += " Slanted"
    if font.weight == "Bold":
        font.fontname = font.fontname.replace("Bold", "BoldSlanted")
        font.appendSFNTName("Arabic (Egypt)", "SubFamily", "عريض مائل")
        font.appendSFNTName("English (US)",   "SubFamily", "Bold Slanted")
    else:
        font.fontname = font.fontname.replace("Regular", "Slanted")
        font.appendSFNTName("Arabic (Egypt)", "SubFamily", "مائل")

    mergeLatin(font, skew)

    generateFont(font, outfile)

def makeDesktop(infile, outfile, version, latin=True, generate=True):
    font = fontforge.open(infile)

    if version:
        setVersion(font, version)

    # remove anchors that are not needed in the production font
    cleanAnchors(font)

    #makeOverUnderline(font)

    # sample text to be used by font viewers
    sample = 'صِفْ خَلْقَ خَوْدٍ كَمِثْلِ ٱلشَّمْسِ إِذْ بَزَغَتْ يَحْظَىٰ ٱلضَّجِيعُ بِهَا نَجْلَاءَ مِعْطَارِ.'

    for lang in ('Arabic (Egypt)', 'English (US)'):
        font.appendSFNTName(lang, 'Sample Text', sample)

    if latin:
        mergeLatin(font)

    if generate:
        generateFont(font, outfile, True)
    else:
        return font

def usage(extramessage, code):
    if extramessage:
        print extramessage

    message = """Usage: %s OPTIONS...

Options:
  --input=FILE          file name of input font
  --output=FILE         file name of output font
  --version=VALUE       set font version to VALUE
  --slant=VALUE         autoslant
  --css                 output is a CSS file
  --web                 output is web version

  -h, --help            print this message and exit
""" % os.path.basename(sys.argv[0])

    print message
    sys.exit(code)

if __name__ == "__main__":
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:],
                "h",
                ["help","input=","output=", "version=", "slant=", "css", "web"])
    except getopt.GetoptError, err:
        usage(str(err), -1)

    infile = None
    outfile = None
    version = None
    slant = False
    css = False
    web = False

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage("", 0)
        elif opt == "--input": infile = arg
        elif opt == "--output": outfile = arg
        elif opt == "--version": version = arg
        elif opt == "--slant": slant = float(arg)
        elif opt == "--css": css = True
        elif opt == "--web": web = True

    if not infile:
        usage("No input file", -1)
    if not outfile:
        usage("No output file", -1)

    if css:
        makeCss(infile, outfile)
    elif web:
        makeWeb(infile, outfile)
    else:
        if not version:
            usage("No version specified", -1)

        if slant:
            makeSlanted(infile, outfile, version, slant)
        else:
            makeDesktop(infile, outfile, version)