#!/usr/bin/env python

"""
Copyright (c) 2009, 2010 Barry Schwartz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

#--------------------------------------------------------------------------

import fontforge
import optparse
import os
import re
import subprocess
import sys

from sortsmill import licensing
from sortsmill import make_tt_font
from sortsmill import readfeatures

layer_to_use = "Fore"
unwanted_glyphs = ['DONT_KEEP', 'NOTUSED']
generation_flags = ("opentype", "round")
font_extension = ".otf"
ofl_prefix = 'OFL'

def remove_glyph(glyph):
    sys.stdout.write("(Removing " + glyph.glyphname + ") ")
    glyph.font.removeGlyph(glyph.glyphname)

#--------------------------------------------------------------------------

parser = optparse.OptionParser(usage='%prog [OPTIONS] FONTNAME...')
parser.set_defaults(licensing_inferred=False, no_instructions=False)
parser.add_option('-C', '--input-directory', dest='input_dir', metavar='DIR',
                  help='where to read source files')
parser.add_option('--output-directory', dest='output_dir', metavar='DIR',
                  help='where to put generated fonts')
parser.add_option('--infer-licensing', dest='licensing_inferred', action='store_true',
                  help='set license (MIT or OFL) inferred from font name')
parser.add_option('--ttf-emsize', dest='ttf_emsize', metavar='UNITS',
                  help='set the units-per-em in TrueType versions')
parser.add_option('--no-instructions', dest='no_instructions', action='store_true',
                  help='omit TrueType instructions')
parser.add_option('--graphite', '--enable-graphite', dest='graphite_enabled', action='store_true',
                  help='enables inclusion of Graphite tables')
(options, args) = parser.parse_args()

input_dir = os.path.abspath(options.input_dir if options.input_dir else '.')
output_dir = os.path.abspath(options.output_dir if options.output_dir else '.')
licensing_inferred = options.licensing_inferred
ttf_emsize = int(options.ttf_emsize) if options.ttf_emsize != None else None
no_instructions = options.no_instructions
graphite_enabled = options.graphite_enabled

os.chdir(input_dir)

for sfd_filename in args:

    is_ofl = (sfd_filename[:len(ofl_prefix)] == ofl_prefix)
    if is_ofl:
        sfd_filename = sfd_filename[len(ofl_prefix):]

    tt_match = re.match('(^.*)TT(-[^-]*)?$', sfd_filename)
    if tt_match:
        sfd_filename = tt_match.group(1)
        if tt_match.group(2):
            sfd_filename += tt_match.group(2)

    if sfd_filename[-4:] != ".sfd":
        sfd_filename += ".sfd"

    f = fontforge.open(sfd_filename)

    if licensing_inferred:
        if is_ofl:
            licensing.apply_license(f, licensing.ofl_notice, licensing.ofl_url, name_prefix = 'OFL')
        else:
            licensing.apply_license(f, licensing.mit_notice, licensing.mit_url)

    for glyph_name in f:
        for suffix in unwanted_glyphs:
            if glyph_name[-len(suffix) - 1:] == "." + suffix:
                remove_glyph(f[glyph_name])

    sys.stdout.write("\n")
    sys.stdout.flush()

    # The anchors are for development only.
    for lookup in f.gpos_lookups:
        if f.getLookupInfo(lookup)[0] == 'gpos_mark2base':
            f.removeLookup(lookup)

    f.selection.all()
    f.canonicalStart()
    f.canonicalContours()
    if tt_match:
        f.replaceWithReference()
        f.correctReferences()
    f.selection.none()

    readfeatures.merge_pair_positioning_subtables(f)

    if tt_match:
        make_tt_font.generate_tt_font(f, sfd_filename[:-4], 'TT',
                                      output_dir = output_dir,
                                      emsize = ttf_emsize,
                                      no_instructions = no_instructions,
                                      graphite_enabled = graphite_enabled)
    else:
        font_file = os.path.join(output_dir, f.fontname + font_extension)
        print("Generating", font_file)
        f.generate(font_file, flags = generation_flags, layer = layer_to_use)
        print("Validating", font_file)
        subprocess.call(["fontlint", font_file])

    f.close()

#--------------------------------------------------------------------------
