#!/usr/bin/python3.12
"""Assemble Vicentino TrueType fonts from mftrace output (base + swash/alt set)."""
import fontforge, psMat, math, sys, os

MT = sys.argv[1]      # dir with mftrace .pfa/.afm
OUT = sys.argv[2]
os.makedirs(OUT, exist_ok=True)

STYLES = [
    # base, alt, family, sub, bold, slant(tan), design params for space
    ('vcxc10', 'vcca10',  'Vicentino Corsiva', 'Regular', False, 7/30, 11/60),
    ('vcxcb10', 'vccba10', 'Vicentino Corsiva', 'Bold',    True,  7/30, 11/60),
    ('vcxm10', 'vcma10',  'Vicentino Modern',  'Regular', False, 1/6, 1/6),
    ('vcxmb10', 'vcmba10', 'Vicentino Modern',  'Bold',    True,  1/6, 1/6),
    ('vcxt10', 'vcta10',  'Vicentino Twist',   'Regular', False, -2/60, -2/60),
    ('vcxtb10', 'vctba10', 'Vicentino Twist',   'Bold',    True,  -2/60, -2/60),
]

# alt-font glyph -> name in merged font
ALT_RENAME = {
    'f_f': 's_t', 'f_i': 'c_t', 's_p': 's_p', 's': 'longs',
    'germandbls': 'longs_s', 'ampersand': 'ampersand.alt',
}
for d in 'zero one two three four five six seven eight nine'.split():
    ALT_RENAME[d] = d + '.lf'

COPYRIGHT = ('Copyright (c) 1991-1992, 2026 Willibald Kraml. '
             'Designed in METAFONT 1991; TrueType conversion 2026.')
LICENSE = ('This Font Software is licensed under the SIL Open Font License, Version 1.1. '
           'This license is available with a FAQ at: https://openfontlicense.org')

ACCENTED = [
    'Adieresis', 'Odieresis', 'Udieresis', 'adieresis', 'odieresis', 'udieresis',
    'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Aring', 'Ccedilla',
    'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute',
    'Icircumflex', 'Idieresis', 'Ntilde', 'Ograve', 'Oacute', 'Ocircumflex',
    'Otilde', 'Ugrave', 'Uacute', 'Ucircumflex', 'Yacute',
    'agrave', 'aacute', 'acircumflex', 'atilde', 'aring', 'ccedilla',
    'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', 'iacute',
    'icircumflex', 'idieresis', 'ntilde', 'ograve', 'oacute', 'ocircumflex',
    'otilde', 'ugrave', 'uacute', 'ucircumflex', 'yacute', 'ydieresis',
    'Scaron', 'scaron', 'Zcaron', 'zcaron', 'Ccaron', 'ccaron', 'Ecaron', 'ecaron',
    'Rcaron', 'rcaron', 'Ydieresis',
]


def clean(g):
    g.removeOverlap()
    g.simplify(0.5, ('mergelines',))
    g.addExtrema('all')
    g.round()
    g.correctDirection()


def build(base, alt, family, sub, bold, slant, upslant):
    f = fontforge.open(os.path.join(MT, base + '.pfa'))
    f.encoding = 'UnicodeFull'
    f.mergeFeature(os.path.join(MT, base + '.afm'))  # TFM kerning -> GPOS kern

    # --- bring in the alternate (swash) set
    a = fontforge.open(os.path.join(MT, alt + '.pfa'))
    alt_names = []
    for g in a.glyphs():
        if not g.isWorthOutputting() or g.glyphname in ('.notdef', 'space'):
            continue
        n = g.glyphname
        if n in ALT_RENAME:
            new = ALT_RENAME[n]
        elif len(n) == 1 and n.islower():
            new = n + '.swsh'
        else:
            continue  # punctuation identical to base set
        a.selection.select(n)
        a.copy()
        f.createChar(-1, new)
        f.selection.select(new)
        f.paste()
        f[new].width = g.width
        alt_names.append((n, new))
    a.close()

    for g in f.glyphs():
        if g.glyphname == '.notdef':
            continue
        u = fontforge.unicodeFromName(g.glyphname)
        if u >= 0:
            g.unicode = u
        clean(g)

    # space (TFM: 2tw + .6s)
    k = 1.08 if bold else 1.0
    sp = f.createChar(32, 'space')
    sp.width = round(1000 * (2 * 0.1 * k + 0.6 * 0.05 * k))
    nb = f.createChar(0xA0, 'uni00A0'); nb.width = sp.width
    # straight quotes / misc. mapped from existing shapes
    for src, dst, u in [('quoteright', 'quotesingle', 0x27), ('quotedblright', 'quotedbl', 0x22),
                        ('hyphen', 'uni00AD', 0xAD), ('quoteright', 'quotesinglbase', 0x201A),
                        ('quotedblright', 'quotedblbase', 0x201E)]:
        if src in f and dst not in f:
            f.selection.select(src); f.copy()
            g = f.createChar(u, dst); f.selection.select(dst); f.paste()
            if dst.endswith('base'):
                g.transform(psMat.translate(0, -f[src].boundingBox()[3] + 60))
    # quotedbl/quotesingle were the TeX positions of quoteright, keep proper ones
    f['quoteright'].unicode = 0x2019
    f['quotedblright'].unicode = 0x201D
    f['quoteleft'].unicode = 0x2018
    f['quotedblleft'].unicode = 0x201C

    # accented letters
    f.italicangle = -math.degrees(math.atan(slant))
    xh = 437.5  # x-height of design (7/16 em); accents are drawn for it
    ACC = {'dieresis': 'dieresis', 'acute': 'acute', 'grave': 'grave', 'circumflex': 'circumflex',
           'tilde': 'tilde', 'ring': 'ring', 'cedilla': 'cedilla', 'caron': 'caron'}
    for n in ACCENTED:
        base, acc = n[0], n[1:]
        if acc not in ACC or ACC[acc] not in f:
            print('skip', n); continue
        bname = {'i': 'dotlessi', 'j': 'uni0237'}.get(base, base)
        if bname not in f:
            continue
        bg, ag = f[bname], f[ACC[acc]]
        h = 712.5 if base.isupper() else xh   # cap height 11/16 em (TeX: char height)
        raise_ = 0 if acc == 'cedilla' else h - xh
        dx = (bg.width - ag.width) / 2 + (upslant if base.isupper() else slant) * raise_
        g = f.createChar(fontforge.unicodeFromName(n), n)
        g.clear()
        g.addReference(bname)
        g.addReference(ACC[acc], psMat.translate(dx, raise_))
        g.width = bg.width
    # German capital sharp s fallback is not drawn; leave unmapped.

    # --- OpenType features
    f.addLookup('liga', 'gsub_ligature', (), (('liga', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),))
    f.addLookupSubtable('liga', 'liga1')
    f['f_f'].addPosSub('liga1', ('f', 'f'))
    f['f_i'].addPosSub('liga1', ('f', 'i'))
    f['c_h'].addPosSub('liga1', ('c', 'h'))

    f.addLookup('dlig', 'gsub_ligature', (), (('dlig', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),))
    f.addLookupSubtable('dlig', 'dlig1')
    f['s_t'].addPosSub('dlig1', ('s', 't'))
    f['c_t'].addPosSub('dlig1', ('c', 't'))
    f['s_p'].addPosSub('dlig1', ('s', 'p'))

    f.addLookup('swsh', 'gsub_single', (),
                (('swsh', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),
                 ('ss01', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),
                 ('salt', (('DFLT', ('dflt',)), ('latn', ('dflt',))))))
    f.addLookupSubtable('swsh', 'swsh1')
    for n in 'abcdefghklmnpqrtuvwxyz':
        if n + '.swsh' in f:
            f[n].addPosSub('swsh1', n + '.swsh')
    f['ampersand'].addPosSub('swsh1', 'ampersand.alt')

    f.addLookup('hist', 'gsub_single', (), (('hist', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),))
    f.addLookupSubtable('hist', 'hist1')
    f['s'].addPosSub('hist1', 'longs')
    f['germandbls'].addPosSub('hist1', 'longs_s')

    f.addLookup('lnum', 'gsub_single', (), (('lnum', (('DFLT', ('dflt',)), ('latn', ('dflt',)))),))
    f.addLookupSubtable('lnum', 'lnum1')
    for d in 'zero one two three four five six seven eight nine'.split():
        f[d].addPosSub('lnum1', d + '.lf')

    # --- names / metadata
    ps_family = family.replace(' ', '')
    f.familyname = family
    f.fontname = ps_family + '-' + sub
    f.fullname = family + ('' if sub == 'Regular' else ' ' + sub)
    f.weight = sub
    f.copyright = COPYRIGHT
    f.version = '1.000'
    f.sfntRevision = 1.0
    f.os2_vendor = 'KRML'
    f.os2_weight = 700 if bold else 400
    f.macstyle = 1 if bold else 0
    f.os2_stylemap = 0x20 if bold else 0x40
    for lang in ('English (US)',):
        f.appendSFNTName(lang, 'Family', family)
        f.appendSFNTName(lang, 'SubFamily', sub)
        f.appendSFNTName(lang, 'Fullname', f.fullname)
        f.appendSFNTName(lang, 'Designer', 'Willi Kraml')
        f.appendSFNTName(lang, 'Manufacturer', 'Willi Kraml')
        f.appendSFNTName(lang, 'Vendor URL', 'https://www.kraml.cc')
        f.appendSFNTName(lang, 'Designer URL', 'https://www.kraml.cc')
        f.appendSFNTName(lang, 'Descriptor',
                         'Calligraphic cursive in the style of the Vicentine renaissance '
                         '(Ludovico degli Arrighi, called Vicentino). Converted from the '
                         '1991 METAFONT sources with mftrace/potrace.')
        f.appendSFNTName(lang, 'License', LICENSE)
        f.appendSFNTName(lang, 'License URL', 'https://openfontlicense.org')
        f.appendSFNTName(lang, 'Version', 'Version 1.000')
        f.appendSFNTName(lang, 'UniqueID', 'Willi Kraml: ' + f.fullname + ': 2026')

    # vertical metrics: design ascender .75em, descender .25em
    bb = [0, 0, 0, 0]
    for g in f.glyphs():
        b = g.boundingBox()
        bb[1] = min(bb[1], b[1]); bb[3] = max(bb[3], b[3])
    f.ascent, f.descent = 750, 250
    f.os2_typoascent, f.os2_typodescent, f.os2_typolinegap = 750, -250, 250
    f.os2_typoascent_add = f.os2_typodescent_add = 0
    f.hhea_ascent, f.hhea_descent, f.hhea_linegap = 750 + 125, -250 - 125, 0
    f.hhea_ascent_add = f.hhea_descent_add = 0
    f.os2_winascent, f.os2_windescent = int(bb[3]) + 10, int(-bb[1]) + 10
    f.os2_winascent_add = f.os2_windescent_add = 0
    f.os2_use_typo_metrics = True

    out = os.path.join(OUT, ps_family + '-' + sub)
    f.save(out + '.sfd')
    f.generate(out + '.ttf', flags=('opentype', 'round', 'dummy-dsig'))
    print('wrote', out + '.ttf', 'glyphs:', sum(1 for g in f.glyphs() if g.isWorthOutputting()))
    f.close()


for st in STYLES:
    build(*st)
