/*
copyright (c) 2005-2012 Kazuki Iwamoto http://www.maid.org/ iwm@maid.org

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.
*/
#include <stdio.h>
#include <tchar.h>
#include <windows.h>


#define NAME 0x656d616e
#define APPLE_UNICODE_PLATFORM_ID 0
#define MACINTOSH_PLATFORM_ID 1
#define ISO_PLATFORM_ID 2
#define MICROSOFT_PLATFORM_ID 3
#define SYMBOL_ENCODING_ID 0
#define UNICODE_ENCODING_ID 1
#define UCS4_ENCODING_ID 10


#define MAX_SYSTEMFONT 6
#define MAX_CHARSET 32


#include <pshpack1.h>
typedef struct _NAMEHEADER
{
  WORD wFormatSelector;
  WORD wNumRecords;
  WORD wStringStorageOffset;
} NAMEHEADER, *LPNAMEHEADER, *PNAMEHEADER;
typedef struct _NAMERECORD
{
  WORD wPlatformID;
  WORD wEncodingID;
  WORD wLanguageID;
  WORD wNameID;
  WORD wStringLength;
  WORD wStringOffset;
} NAMERECORD, *LPNAMERECORD, *PNAMERECORD;
#include <poppack.h>
typedef struct _FONTLIST
{
  int nPriority;
  BOOL fFixed;
  BYTE bFamily;
  DWORD dwCharSet;
  LPSTR lpszName;
  struct _FONTLIST *lpflPrev, *lpflNext;
} FONTLIST, *LPFONTLIST, *PFONTLIST;
typedef struct _FONTINFO
{
  int nCharSet;
  BYTE bCharSet[MAX_CHARSET];
  DWORD dwCurrent;
  HDC hDC;
  LPFONTLIST lpflEnumed;
  LPSTR lpszSystem[MAX_SYSTEMFONT];
} FONTINFO, *LPFONTINFO, *PFONTINFO;


/******************************************************************************
*                                                                             *
******************************************************************************/
static BOOL
GetNameHeader (HDC          hDC,
               LPNAMEHEADER lpnhData)
{
  if (GetFontData (hDC, NAME, 0, lpnhData, sizeof (NAMEHEADER))
                                                        != sizeof (NAMEHEADER))
    return FALSE;
  lpnhData->wFormatSelector
                        = MAKEWORD (HIBYTE (lpnhData->wFormatSelector),
                                    LOBYTE (lpnhData->wFormatSelector));
  lpnhData->wNumRecords = MAKEWORD (HIBYTE (lpnhData->wNumRecords),
                                    LOBYTE (lpnhData->wNumRecords));
  lpnhData->wStringStorageOffset
                        = MAKEWORD (HIBYTE (lpnhData->wStringStorageOffset),
                                    LOBYTE (lpnhData->wStringStorageOffset));
  return TRUE;
}


static BOOL
GetNameRecord (HDC          hDC,
               int          i,
               LPNAMERECORD lpnrData)
{
  if (GetFontData (hDC, NAME, 6 + i * sizeof (NAMERECORD),
                        lpnrData, sizeof (NAMERECORD)) != sizeof (NAMERECORD))
    return FALSE;
  lpnrData->wPlatformID =   MAKEWORD (HIBYTE (lpnrData->wPlatformID),
                                      LOBYTE (lpnrData->wPlatformID));
  lpnrData->wEncodingID =   MAKEWORD (HIBYTE (lpnrData->wEncodingID),
                                      LOBYTE (lpnrData->wEncodingID));
  lpnrData->wLanguageID =   MAKEWORD (HIBYTE (lpnrData->wLanguageID),
                                      LOBYTE (lpnrData->wLanguageID));
  lpnrData->wNameID =       MAKEWORD (HIBYTE (lpnrData->wNameID),
                                      LOBYTE (lpnrData->wNameID));
  lpnrData->wStringLength = MAKEWORD (HIBYTE (lpnrData->wStringLength),
                                      LOBYTE (lpnrData->wStringLength));
  lpnrData->wStringOffset = MAKEWORD (HIBYTE (lpnrData->wStringOffset),
                                      LOBYTE (lpnrData->wStringOffset));
  return TRUE;
}


static LPSTR
GetFamilyName (HDC hDC)
{
  LPSTR lpszName = NULL;
  NAMEHEADER nhData;

  if (GetNameHeader (hDC, &nhData))
    {
      int i, unicode_ix = -1, mac_ix = -1, microsoft_ix = -1, name_ix = -1;
      NAMERECORD nrData;

      for (i = 0; i < nhData.wNumRecords; i++)
        if (GetNameRecord (hDC, i, &nrData)
                            && (nrData.wNameID == 1 || nrData.wNameID == 16)
                            && nrData.wStringLength > 0)
          {
            if (nrData.wPlatformID == APPLE_UNICODE_PLATFORM_ID ||
                nrData.wPlatformID == ISO_PLATFORM_ID)
              unicode_ix = i;
            else if (nrData.wPlatformID == MACINTOSH_PLATFORM_ID &&
                     nrData.wEncodingID == 0 && /* Roman */
                     nrData.wLanguageID == 0) /* English */
              mac_ix = i;
            else if (nrData.wPlatformID == MICROSOFT_PLATFORM_ID)
              if ((microsoft_ix == -1 ||
                   PRIMARYLANGID (nrData.wLanguageID) == LANG_ENGLISH) &&
                  (nrData.wEncodingID == SYMBOL_ENCODING_ID ||
                   nrData.wEncodingID == UNICODE_ENCODING_ID ||
                   nrData.wEncodingID == UCS4_ENCODING_ID))
                microsoft_ix = i;
          }
      if (microsoft_ix >= 0)
        name_ix = microsoft_ix;
      else if (mac_ix >= 0)
        name_ix = mac_ix;
      else if (unicode_ix >= 0)
        name_ix = unicode_ix;
      if (name_ix >= 0 && GetNameRecord (hDC, name_ix, &nrData))
        {
          LPVOID lpName;

          lpName = HeapAlloc (GetProcessHeap (), 0, nrData.wStringLength);
          if (GetFontData (hDC, NAME,
                        nhData.wStringStorageOffset + nrData.wStringOffset,
                        lpName, nrData.wStringLength) == nrData.wStringLength)
            {
              if (name_ix == microsoft_ix)
                if (nrData.wEncodingID == SYMBOL_ENCODING_ID ||
                    nrData.wEncodingID == UNICODE_ENCODING_ID)
                  {
                    lpszName = HeapAlloc (GetProcessHeap (),
                            HEAP_ZERO_MEMORY, nrData.wStringLength / 2 + 1);
                    for (i = 0; i < nrData.wStringLength / 2; i++)
                      lpszName[i] = ((LPBYTE)lpName)[i * 2 + 1];
                  }
                else
                  {
                    lpszName = HeapAlloc (GetProcessHeap (),
                            HEAP_ZERO_MEMORY, nrData.wStringLength / 4 + 1);
                    for (i = 0; i < nrData.wStringLength / 4; i++)
                      lpszName[i] = ((LPBYTE)lpName)[i * 4 + 3];
                  }
              else if (name_ix == mac_ix)
                {
                  lpszName = HeapAlloc (GetProcessHeap (),
                                HEAP_ZERO_MEMORY, nrData.wStringLength + 1);
                  CopyMemory (lpszName, lpName, nrData.wStringLength);
                }
              else /* name_ix == unicode_ix */
                {
                  lpszName = HeapAlloc (GetProcessHeap (),
                            HEAP_ZERO_MEMORY, nrData.wStringLength / 4 + 1);
                  for (i = 0; i < nrData.wStringLength / 4; i++)
                    lpszName[i] = ((LPBYTE)lpName)[i * 4 + 3];
                }
              for (i = 0; lpszName[i] != '\0' ; i++)
                if (lpszName[i] < ' ' || '~' < lpszName[i]
                                                        || lpszName[i] == ',')
                  {
                    HeapFree (GetProcessHeap (), 0, lpszName);
                    lpszName = NULL;
                    break;
                  }
              CharLowerA (lpszName);
            }
          HeapFree (GetProcessHeap (), 0, lpName);
        }
    }
  return lpszName;
}


/******************************************************************************
*                                                                             *
******************************************************************************/
static LPFONTLIST
FirstFontList (LPFONTLIST lpflSource)
{
  LPFONTLIST p = NULL;

  if (lpflSource)
    for (p = lpflSource; p->lpflPrev; p = p->lpflPrev);
  return p;
}


static LPFONTLIST
LastFontList (LPFONTLIST lpflSource)
{
  LPFONTLIST p = NULL;

  if (lpflSource)
    for (p = lpflSource; p->lpflNext; p = p->lpflNext);
  return p;
}


static VOID
AppendFontList (LPSTR      lpszName,
                BOOL       fFixed,
                BYTE       bFamily,
                DWORD      dwCharSet,
                LPFONTINFO lpfiData)
{
  int i;
  LPFONTLIST p, q;

  for (p = FirstFontList (lpfiData->lpflEnumed); p; p = p->lpflNext)
    if (lstrcmpA (p->lpszName, lpszName) == 0)
      {
        if ((p->dwCharSet & dwCharSet) == 0)
          {
            p->dwCharSet |= dwCharSet;
            p->nPriority++;
            if (p == lpfiData->lpflEnumed)
              lpfiData->lpflEnumed = lpfiData->lpflEnumed->lpflPrev
                                            ? lpfiData->lpflEnumed->lpflPrev
                                            : lpfiData->lpflEnumed->lpflNext;
            if (p->lpflPrev)
              p->lpflPrev->lpflNext = p->lpflNext;
            if (p->lpflNext)
              p->lpflNext->lpflPrev = p->lpflPrev;
            break;
          }
        else
          {
            return;
          }
      }
  if (!p)
    {
      p = HeapAlloc (GetProcessHeap (), 0, sizeof (FONTLIST));
      p->lpszName = HeapAlloc (GetProcessHeap (), 0, lstrlenA (lpszName) + 1);
      p->nPriority = 0;
      p->fFixed = fFixed;
      p->bFamily = bFamily;
      p->dwCharSet = dwCharSet;
      lstrcpyA (p->lpszName, lpszName);
    }
  for (i = 0; i < MAX_SYSTEMFONT; i++)
    if (lpfiData->lpszSystem[i]
                    && lstrcmpA (lpfiData->lpszSystem[i], p->lpszName) == 0)
      {
        p->nPriority = MAX_CHARSET + (MAX_SYSTEMFONT - i);
        break;
      }
  for (q = FirstFontList (lpfiData->lpflEnumed); q; q = q->lpflNext)
    if (p->nPriority > MAX_CHARSET && p->nPriority > q->nPriority
            || (p->dwCharSet & lpfiData->dwCurrent)
                                        > (q->dwCharSet & lpfiData->dwCurrent)
            || (p->dwCharSet & lpfiData->dwCurrent)
                                        == (q->dwCharSet & lpfiData->dwCurrent)
                && p->nPriority > q->nPriority
            || (p->dwCharSet & lpfiData->dwCurrent)
                                        == (q->dwCharSet & lpfiData->dwCurrent)
                && p->nPriority == q->nPriority
                && lstrcmpA (p->lpszName, q->lpszName) < 0)
      {
        p->lpflPrev = q->lpflPrev;
        p->lpflNext = q;
        if (q->lpflPrev)
          q->lpflPrev->lpflNext = p;
        q->lpflPrev = p;
        return;
      }
  q = LastFontList (lpfiData->lpflEnumed);
  p->lpflPrev = q;
  p->lpflNext = NULL;
  if (q)
    q->lpflNext = p;
  else
    lpfiData->lpflEnumed = p;
}


static VOID
FreeFontList (LPFONTLIST lpflSource)
{
  LPFONTLIST p;

  p = FirstFontList (lpflSource);
  while (p)
    {
      LPFONTLIST q;

      q = p->lpflNext;
      HeapFree (GetProcessHeap (), 0, p->lpszName);
      HeapFree (GetProcessHeap (), 0, p);
      p = q;
    }
}


/******************************************************************************
*                                                                             *
******************************************************************************/
static DWORD
GetCharSet (LPFONTINFO lpfiData,
            BYTE       bCharSet)
{
  DWORD dwCharSet = 0;

  if (lpfiData)
    {
      int i;

      for (i = 0; i < lpfiData->nCharSet; i++)
        if (lpfiData->bCharSet[i] == bCharSet)
          break;
      if (i < MAX_CHARSET)
        {
          dwCharSet = 1 << i;
          if (i == lpfiData->nCharSet)
            {
              lpfiData->bCharSet[i] = bCharSet;
              lpfiData->nCharSet++;
            }
        }
    }
  return dwCharSet;
}


static int CALLBACK
EnumFontFamExFunc (ENUMLOGFONTEX   *lpelfe,
                   NEWTEXTMETRICEX *lpntme,
                   DWORD            FontType,
                   LPARAM           lParam)
{
  int nRet = 1;
  LPFONTINFO lpfiData;

  lpfiData = (LPFONTINFO)lParam;
  if (FontType == TRUETYPE_FONTTYPE
                            && lpelfe->elfLogFont.lfCharSet != SYMBOL_CHARSET
                            && lpelfe->elfLogFont.lfFaceName[0] != '@')
    nRet = GetCharSet (lpfiData, lpelfe->elfLogFont.lfCharSet);
  return nRet;
}


static int CALLBACK
EnumFontFamExProc (ENUMLOGFONTEX   *lpelfe,
                   NEWTEXTMETRICEX *lpntme,
                   DWORD            FontType,
                   LPARAM           lParam)
{
  if (FontType == TRUETYPE_FONTTYPE
                            && lpelfe->elfLogFont.lfCharSet != SYMBOL_CHARSET
                            && lpelfe->elfLogFont.lfFaceName[0] != '@')
    {
      HFONT hFont;
      LPSTR lpszName = NULL;
      LPFONTINFO lpfiData;

      lpfiData = (LPFONTINFO)lParam;
      hFont = CreateFontIndirect (&lpelfe->elfLogFont);
      if (hFont)
        {
          hFont = SelectObject (lpfiData->hDC, hFont);
          lpszName = GetFamilyName (lpfiData->hDC);
          hFont = SelectObject (lpfiData->hDC, hFont);
          DeleteObject (hFont);
        }
      if (lpszName)
        {
          AppendFontList (
                lpszName,
                (lpelfe->elfLogFont.lfPitchAndFamily & 0x0f) == FIXED_PITCH,
                lpelfe->elfLogFont.lfPitchAndFamily & 0xf0,
                GetCharSet (lpfiData, lpelfe->elfLogFont.lfCharSet),
                lpfiData);
          HeapFree (GetProcessHeap (), 0, lpszName);
        }
    }
  return 1;
}


int
main (int   argc,
      char *argv[])
{
  FONTINFO fiData;

  memset (&fiData, 0, sizeof (FONTINFO));
  fiData.hDC = CreateDC (_T("DISPLAY"), NULL, NULL, NULL);
  if (fiData.hDC)
    {
      int i;
      HFONT hFont;
      LOGFONT lf;

      for (i = MAX_SYSTEMFONT - 1; i >= 0; i--)
        {
          int nObject[MAX_SYSTEMFONT] = {DEFAULT_GUI_FONT, ANSI_VAR_FONT,
            SYSTEM_FONT, ANSI_FIXED_FONT, SYSTEM_FIXED_FONT, OEM_FIXED_FONT};

          hFont = GetStockObject (nObject[i]);
          if (hFont)
            {
              int j;
              TEXTMETRIC tm;

              hFont = SelectObject (fiData.hDC, hFont);
              fiData.lpszSystem[i] = GetFamilyName (fiData.hDC);
              GetTextMetrics (fiData.hDC, &tm);
              SelectObject (fiData.hDC, hFont);
              if (fiData.lpszSystem[i])
                fiData.dwCurrent |= GetCharSet (&fiData, tm.tmCharSet);
            }
        }
      memset (&lf, 0, sizeof (LOGFONT));
      lf.lfCharSet = DEFAULT_CHARSET;
      EnumFontFamiliesEx (fiData.hDC, &lf, (FONTENUMPROC)EnumFontFamExFunc,
                                                        (LPARAM)&fiData, 0);
      memset (&lf, 0, sizeof (LOGFONT));
      lf.lfCharSet = DEFAULT_CHARSET;
      EnumFontFamiliesEx (fiData.hDC, &lf, (FONTENUMPROC)EnumFontFamExProc,
                                                        (LPARAM)&fiData, 0);
      if (fiData.lpflEnumed)
        {
          BOOL fComma;
          LPFONTLIST p;

          /* courier */
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (lstrcmpA (p->lpszName, "courier new") == 0)
              {
                printf ("courier = \"courier new\"\n");
                break;
              }

          /* monospace */
          fComma = FALSE;
          printf ("monospace = \"");
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (p->fFixed && (p->dwCharSet & fiData.dwCurrent) != 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              if ((p->dwCharSet & fiData.dwCurrent) != 0)
                {
                  if (fComma)
                    printf (",");
                  printf ("%s", p->lpszName);
                  fComma = TRUE;
                }
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (p->fFixed && (p->dwCharSet & fiData.dwCurrent) == 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          printf ("\"\n");

          /* serif */
          fComma = FALSE;
          printf ("serif = \"");
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (!p->fFixed && p->bFamily == FF_ROMAN
                                    && (p->dwCharSet & fiData.dwCurrent) != 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              if ((p->dwCharSet & fiData.dwCurrent) != 0)
                {
                  if (fComma)
                    printf (",");
                  printf ("%s", p->lpszName);
                  fComma = TRUE;
                }
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (!p->fFixed && p->bFamily == FF_ROMAN
                                    && (p->dwCharSet & fiData.dwCurrent) == 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          printf ("\"\n");

          /* sans */
          fComma = FALSE;
          printf ("sans = \"");
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (!p->fFixed && p->bFamily == FF_SWISS
                                    && (p->dwCharSet & fiData.dwCurrent) != 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              if ((p->dwCharSet & fiData.dwCurrent) != 0)
                {
                  if (fComma)
                    printf (",");
                  printf ("%s", p->lpszName);
                  fComma = TRUE;
                }
          for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
            if (!p->fFixed && p->bFamily == FF_SWISS
                                    && (p->dwCharSet & fiData.dwCurrent) == 0)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          if (!fComma)
            for (p = FirstFontList (fiData.lpflEnumed); p; p = p->lpflNext)
              {
                if (fComma)
                  printf (",");
                printf ("%s", p->lpszName);
                fComma = TRUE;
              }
          printf ("\"\n");
        }
      FreeFontList (fiData.lpflEnumed);
      for (i = 0; i < MAX_SYSTEMFONT; i++)
        if (fiData.lpszSystem[i])
          HeapFree (GetProcessHeap (), 0, fiData.lpszSystem[i]);
      DeleteDC (fiData.hDC);
    }

  return 0;
}
