""" Stupid little scriptlet to determine how a PC is handling the application font.
"""

import os
import sys
from PyQt4 import QtCore, QtGui
from misc import config

# Shut up Qt error messages.  (Get a lot from QRawFont.)
def handler(*args):
    pass
QtCore.qInstallMsgHandler(handler)

# Set up the application font the same as APEX3.
a = QtGui.QApplication([])
font = a.font()
if config.fontfamily is not None:
    font.setFamily(config.fontfamily)
elif sys.platform == "win32":
    font.setFamily("MS Shell Dlg")
a.setFont(font)

# Get the font family name.
name = str(font.family())
print "FONT asked to be used is '%s'." % (name,)

# Get the substitute for an inexact match and use that as the name if needed.
substitute = ""
if not font.exactMatch():
    substitute = str(font.substitute(name))
    if substitute == name: substitute = str(font.lastResortFamily())
    if substitute == name: substitute = str(font.lastResortFont())
if substitute == name:
    substitute = "" # Could not resolve.
    print "Font '%s' was NOT found by Qt and could NOT be substituted."
elif substitute:
    print "Font '%s' was NOT found by Qt, so '%s' was substituted." % (name, substitute)
else:
    print "Font '%s' is found by Qt." % (name,)
name = substitute or name

# Get the mapped name of the font family.
mapped =  name
if sys.platform == "win32":
    import _winreg
    k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes")
    i = 0
    while True:
        try:
            f = _winreg.EnumValue(k, i)
        except WindowsError:
            break
        if str(f[0]) == name:
            mapped = str(f[1])
        i += 1
if name == mapped:
    print "Font '%s' is not mapped." % (name,)
else:
    print "Font '%s' maps to '%s'." % (name, mapped)

# Get the file name of the mapped font name.
fontDir = str(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.FontsLocation))
fn = ""
for f in [os.path.join(fontDir, f) for f in os.listdir(fontDir) if os.path.splitext(f)[1].lower() in (".ttf", ".ttc", ".otf", ".fon")]:
    r = QtGui.QRawFont(f, font.pixelSize())
    if str(r.familyName()) == mapped:
        fn = f
        break
if fn:
    print "Font '%s' is file '%s'." % (mapped, fn)
else:
    print "Font '%s' cound not be found in '%s'." % (mapped, fontDir)
