/* loader.c - Functions to handle loading fonts and glyphs from files. */
/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2003,2005,2006,2007,2008  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <grub/file.h>
#include <grub/bufio.h>
#include <grub/misc.h>
#include <grub/types.h>
#include <grub/mm.h>
#include <grub/font_internal.h>

/* Definition of font registry. */
struct font_node *grub_font_list;

static int register_font (grub_font_t font);
static void free_font (grub_font_t font);
static void remove_font (grub_font_t font);

struct font_file_section
{
  grub_file_t file;             /* The file this section is in. */
  char name[4];                 /* FOURCC name of the section. */
  grub_uint32_t length;         /* Length of the section contents. */
  int eof;                      /* Set by open_section() on EOF. */
};

/* Font file format constants. */
static const char pff2_magic[4] = { 'P', 'F', 'F', '2' };
static const char section_names_file[4] = { 'F', 'I', 'L', 'E' };
static const char section_names_font_name[4] = { 'N', 'A', 'M', 'E' };
static const char section_names_max_char_width[4] = { 'M', 'A', 'X', 'W' };
static const char section_names_max_char_height[4] = { 'M', 'A', 'X', 'H' };
static const char section_names_ascent[4] = { 'A', 'S', 'C', 'E' };
static const char section_names_descent[4] = { 'D', 'E', 'S', 'C' };
static const char section_names_char_index[4] = { 'C', 'H', 'I', 'X' };
static const char section_names_data[4] = { 'D', 'A', 'T', 'A' };

/* Replace unknown glyphs with a rounded question mark.  */
static grub_uint8_t unknown_glyph_bitmap[] =
{
  /*       76543210 */
  0x7C, /*  ooooo   */
  0x82, /* o     o  */
  0xBA, /* o ooo o  */
  0xAA, /* o o o o  */
  0xAA, /* o o o o  */
  0x8A, /* o   o o  */
  0x9A, /* o  oo o  */
  0x92, /* o  o  o  */
  0x92, /* o  o  o  */
  0x92, /* o  o  o  */
  0x92, /* o  o  o  */
  0x82, /* o     o  */
  0x92, /* o  o  o  */
  0x82, /* o     o  */
  0x7C, /*  ooooo   */
  0x00  /*          */
};

static struct grub_font_glyph *unknown_glyph;

void
grub_font_loader_init (void)
{
  unknown_glyph = grub_malloc(sizeof(struct grub_font_glyph)
                              + sizeof(unknown_glyph_bitmap));
  if (! unknown_glyph)
    return;

  unknown_glyph->width = 8;
  unknown_glyph->height = 16;
  unknown_glyph->offset_x = 0;
  unknown_glyph->offset_y = 0;
  unknown_glyph->device_width = 8;
  grub_memcpy(unknown_glyph->bitmap,
              unknown_glyph_bitmap, sizeof(unknown_glyph_bitmap));
}

/*
   Open the next section in the file.

   On success, the section name is stored in section->name and the length in
   section->length, and 0 is returned.  On failure, 1 is returned and
   grub_errno is set approriately with an error message.

   If 1 is returned due to being at the end of the file, then section->eof is
   set to 1; otherwise, section->eof is set to 0.
 */
static int
open_section (grub_file_t file, struct font_file_section *section)
{
  grub_ssize_t retval;
  grub_uint32_t raw_length;

  section->file = file;
  section->eof = 0;

  /* Read the FOURCC section name. */
  retval = grub_file_read (file, section->name, 4);
  if (retval >= 0 && retval < 4)
    {
      section->eof = 1;
      return 1;                 /* EOF encountered. */
    }
  else if (retval < 0)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font format error: can't read section name");
      return 1;                 /* Read error. */
    }

  /* Read the big-endian 32-bit section length. */
  retval = grub_file_read (file, (char *) &raw_length, 4);
  if (retval >= 0 && retval < 4)
    {
      section->eof = 1;
      return 1;                 /* EOF encountered. */
    }
  else if (retval < 0)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font format error: can't read section length");
      return 1;                 /* Read error. */
    }

  /* Convert byte-order and store in *length. */
  section->length = grub_be_to_cpu32 (raw_length);

  return 0;
}

/* Size in bytes of each character index (CHIX section)
   entry in the font file. */
#define FONT_CHAR_INDEX_ENTRY_SIZE (4 + 1 + 4)

/*
   Load the character index (CHIX) section contents from the font file.  This
   presumes that the position of FILE is positioned immediately after the
   section length for the CHIX section (i.e., at the start of the section
   contents).  Returns 0 upon success, nonzero for failure (in which case
   grub_errno is set appropriately).
 */
static int
load_font_index (grub_file_t file, grub_uint32_t sect_length, struct
                 grub_font *font)
{
  unsigned i;

#if FONT_DEBUG >= 2
  grub_printf("load_font_index(sect_length=%d)\n", sect_length);
#endif

  /* Sanity check: ensure section length is divisible by the entry size.  */
  if (sect_length % FONT_CHAR_INDEX_ENTRY_SIZE != 0)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font file format error: character index length %d "
                  "is not a multiple of the entry size %d",
                  sect_length, FONT_CHAR_INDEX_ENTRY_SIZE);
      return 1;                 /* Invalid index section length. */
    }

  /* Calculate the number of characters. */
  font->num_chars = sect_length / FONT_CHAR_INDEX_ENTRY_SIZE;

  /* Allocate the character index array. */
  font->char_index = grub_malloc (font->num_chars
                                  * sizeof (struct char_index_entry));
  if (!font->char_index)
    return 1;                   /* Error allocating memory. */

#if FONT_DEBUG >= 2
  grub_printf("num_chars=%d)\n", font->num_chars);
#endif

  /* Load the character index data from the file. */
  for (i = 0; i < font->num_chars; i++)
    {
      struct char_index_entry *entry = &font->char_index[i];

      /* Read code point value; convert to native byte order. */
      if (grub_file_read (file, (char *) &entry->code, 4) != 4)
        return 1;
      entry->code = grub_be_to_cpu32 (entry->code);

      /* Read storage flags byte. */
      if (grub_file_read (file, (char *) &entry->storage_flags, 1) != 1)
        return 1;

      /* Read glyph data offset; convert to native byte order. */
      if (grub_file_read (file, (char *) &entry->offset, 4) != 4)
        return 1;
      entry->offset = grub_be_to_cpu32 (entry->offset);

      /* No glyph loaded.  Will be loaded on demand and cached thereafter. */
      entry->glyph = 0;

#if FONT_DEBUG >= 5
      if (i < 10)  /* Print the 1st 10 characters. */
        grub_printf("c=%d o=%d\n", entry->code, entry->offset);
#endif
    }

  return 0;                     /* Index loaded OK. */
}

/*
   Read the contents of the specified section as a string, which is
   allocated on the heap.  Returns 0 if there is an error.
 */
static char *
read_section_as_string (struct font_file_section *section)
{
  char *str;
  grub_ssize_t ret;

  str = grub_malloc (section->length + 1);
  if (!str)
    return 0;

  ret = grub_file_read (section->file, str, section->length);
  if (ret < 0 || ret != (grub_ssize_t) section->length)
    {
      grub_free (str);
      return 0;
    }

  str[section->length] = '\0';
  return str;
}

/*
   Read the contents of the current section as a 16-bit integer value,
   which is stored into *VALUE.  Returns 0 upon success, nonzero upon failure.
 */
static int
read_section_as_short (struct font_file_section *section, grub_int16_t *value)
{
  grub_uint16_t raw_value;

  if (section->length != 2)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font file format error: section %c%c%c%c length "
                  "is %d but should be 2",
                  section->name[0], section->name[1],
                  section->name[2], section->name[3],
                  section->length);
      return 1;   /* An error occurred. */
    }
  if (grub_file_read (section->file, (char *) &raw_value, 2) != 2)
    return 1;   /* An error occurred. */

  *value = grub_be_to_cpu16 (raw_value);
  return 0;   /* Successfully read the value. */
}

/*
   Load a font and add it to the beginning of the global font list.
   Returns 0 upon success, nonzero upon failure.
 */
int
grub_font_load (const char *filename)
{
  grub_file_t file = 0;
  struct font_file_section section;
  char magic[4];
  grub_font_t font = 0;

#if FONT_DEBUG >= 1
  grub_printf("add_font(%s)\n", filename);
#endif

  file = grub_buffile_open (filename, 1024);
  if (!file)
    goto fail;

#if FONT_DEBUG >= 3
  grub_printf("file opened\n");
#endif

  /* Read the FILE section.  It indicates the file format. */
  if (open_section (file, &section) != 0)
    goto fail;

#if FONT_DEBUG >= 3
  grub_printf("opened FILE section\n");
#endif
  if (grub_memcmp (section.name, section_names_file, 4) != 0)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font file format error: 1st section must be FILE");
      goto fail;
    }

#if FONT_DEBUG >= 3
  grub_printf("section name ok\n");
#endif
  if (section.length != 4)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Font file format error (file type ID length is %d "
                  "but should be 4)", section.length);
      goto fail;
    }

#if FONT_DEBUG >= 3
  grub_printf("section length ok\n");
#endif
  /* Check the file format type code. */
  if (grub_file_read (file, magic, 4) != 4)
    goto fail;

#if FONT_DEBUG >= 3
  grub_printf("read magic ok\n");
#endif

  if (grub_memcmp (magic, pff2_magic, 4) != 0)
    {
      grub_error (GRUB_ERR_BAD_FONT, "Invalid font magic %x %x %x %x",
                  magic[0], magic[1], magic[2], magic[3]);
      goto fail;
    }

#if FONT_DEBUG >= 3
  grub_printf("compare magic ok\n");
#endif

  /* Allocate the font object. */
  font = (grub_font_t) grub_malloc (sizeof (struct grub_font));
  if (!font)
    goto fail;

  font->file = file;
  font->name = 0;
  font->ascent = 0;
  font->descent = 0;
  font->max_char_width = 0;
  font->max_char_height = 0;
  font->num_chars = 0;
  font->char_index = 0;

#if FONT_DEBUG >= 3
  grub_printf("allocate font ok; loading font info\n");
#endif

  /* Load the font information. */
  while (1)
    {
      if (open_section (file, &section) != 0)
        {
          if (section.eof)
            break;              /* Done reading the font file. */
          else
            goto fail;
        }

#if FONT_DEBUG >= 2
      grub_printf("opened section %c%c%c%c ok\n",
                  section.name[0], section.name[1],
                  section.name[2], section.name[3]);
#endif

      if (grub_memcmp (section.name, section_names_font_name, 4) == 0)
        {
          font->name = read_section_as_string (&section);
          if (!font->name)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_max_char_width, 4) == 0)
        {
          if (read_section_as_short (&section, &font->max_char_width) != 0)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_max_char_height, 4) == 0)
        {
          if (read_section_as_short (&section, &font->max_char_height) != 0)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_ascent, 4) == 0)
        {
          if (read_section_as_short (&section, &font->ascent) != 0)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_descent, 4) == 0)
        {
          if (read_section_as_short (&section, &font->descent) != 0)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_char_index, 4) == 0)
        {
          /* Load the font index. */
          if (load_font_index (file, section.length, font) != 0)
            goto fail;
        }
      else if (grub_memcmp (section.name, section_names_data, 4) == 0)
        {
          /* When the DATA section marker is reached, we stop reading. */
          break;
        }
      else
        {
          /* Unhandled section type, simply skip past it. */
#if FONT_DEBUG >= 3
          grub_printf("Unhandled section type, skipping.\n");
#endif
          grub_off_t section_end = grub_file_tell (file) + section.length;
          if ((int) grub_file_seek (file, section_end) == -1)
            goto fail;
        }
    }

  if (!font->name)
    {
      grub_printf ("Note: Font has no name.\n");
      font->name = grub_strdup ("Unknown");
    }

#if FONT_DEBUG >= 1
  grub_printf ("Loaded font `%s'.\n"
               "Ascent=%d Descent=%d MaxW=%d MaxH=%d Number of characters=%d.\n",
               font->name,
               font->ascent, font->descent,
               font->max_char_width, font->max_char_height,
               font->num_chars);
#endif

  if (font->max_char_width == 0
      || font->max_char_height == 0
      || font->num_chars == 0
      || font->char_index == 0
      || font->ascent == 0
      || font->descent == 0)
    {
      grub_error (GRUB_ERR_BAD_FONT,
                  "Invalid font file: missing some required data.");
      goto fail;
    }

  /* Add the font to the global font registry. */
  if (register_font (font) != 0)
    goto fail;

  return 0;             /* Font loaded ok. */

fail:
  free_font (font);
  return 1;                     /* Failed to load font. */
}

/*
   Read a 16-bit big-endian integer from FILE, convert it to native byte
   order, and store it in *VALUE.
   Returns 0 on success, 1 on failure.
 */
static int
read_be_uint16 (grub_file_t file, grub_uint16_t * value)
{
  if (grub_file_read (file, (char *) value, 2) != 2)
    return 1;
  *value = grub_be_to_cpu16 (*value);
  return 0;
}

static int
read_be_int16 (grub_file_t file, grub_int16_t * value)
{
  /* For the signed integer version, use the same code as for unsigned. */
  return read_be_uint16 (file, (grub_uint16_t *) value);
}

/*
   Return a pointer to the character index entry for the glyph corresponding to
   the codepoint CODE in the font FONT.  If not found, return zero.
 */
static struct char_index_entry *
find_glyph (const grub_font_t font, grub_uint32_t code)
{
  grub_uint32_t i;
  grub_uint32_t len = font->num_chars;
  struct char_index_entry *table = font->char_index;

  /* Do a linear search.  */
  for (i = 0; i < len; i++)
    {
      if (table[i].code == code)
        return &table[i];
    }

  return 0;                     /* No entry found for code point CODE. */
}

static struct grub_font_glyph *
grub_font_get_glyph_internal (grub_font_t font, grub_uint32_t code)
{
  struct char_index_entry *index_entry;

  index_entry = find_glyph (font, code);
  if (index_entry)
    {
      struct grub_font_glyph *glyph = 0;
      grub_uint16_t width;
      grub_uint16_t height;
      grub_int16_t xoff;
      grub_int16_t yoff;
      grub_int16_t dwidth;
      int len;

      if (index_entry->glyph)
        return index_entry->glyph;   /* Return cached glyph. */

      /* Make sure we can find glyphs for error messages.  Push active
         error message to error stack and reset error message.  */
      grub_error_push ();

      grub_file_seek (font->file, index_entry->offset);

      /* Read the glyph width, height, and baseline. */
      if (read_be_uint16(font->file, &width) != 0
          || read_be_uint16(font->file, &height) != 0
          || read_be_int16(font->file, &xoff) != 0
          || read_be_int16(font->file, &yoff) != 0
          || read_be_int16(font->file, &dwidth) != 0)
        {
          //remove_font (font);
          return 0;
        }

      len = (width * height + 7) / 8;
      glyph = grub_malloc (sizeof (struct grub_font_glyph) + len);
      if (! glyph)
        {
          //remove_font (font);
          return 0;
        }

      glyph->font = font;
      glyph->width = width;
      glyph->height = height;
      glyph->offset_x = xoff;
      glyph->offset_y = yoff;
      glyph->device_width = dwidth;

      /* Don't try to read empty bitmaps (e.g., space characters). */
      if (len != 0)
        {
          if (grub_file_read (font->file, (char *) glyph->bitmap, len) != len)
            {
              //remove_font (font);
              return 0;
            }
        }

      /* Restore old error message.  */
      grub_error_pop ();

      /* Cache the glyph. */
      index_entry->glyph = glyph;

      return glyph;  /* Glyph loaded ok. */
    }

  return 0;
}

/* Get the glyph for FONT corresponding to the Unicode code point CODE.
   Returns a pointer to an glyph indicating there is no glyph available
   if CODE does not exist in the font.  The glyphs are cached once loaded. */
struct grub_font_glyph *
grub_font_get_glyph (grub_font_t font, grub_uint32_t code)
{
  struct grub_font_glyph *glyph;
  glyph = grub_font_get_glyph_internal (font, code);
  if (glyph == 0)
    glyph = unknown_glyph;
  return glyph;
}

/* Get a glyph corresponding to the codepoint CODE.  If no glyph is available
   for CODE in the available fonts, then a glyph representing an unknown
   character is returned.  This function never returns NULL.
   The returned glyph is owned by the font manager and should not be freed
   by the caller.  The glyphs are cached. */
struct grub_font_glyph *
grub_font_get_glyph_any (grub_uint32_t code)
{
  struct font_node *node;
  /* Keep track of next node, in case there's an I/O error in
     grub_font_get_glyph() and the font is removed from the list. */
  struct font_node *next;

  for (node = grub_font_list; node; node = next)
    {
      grub_font_t font;
      struct grub_font_glyph *glyph;

      font = node->value;
      next = node->next;

      glyph = grub_font_get_glyph_internal (font, code);
      if (glyph)
        return glyph;
    }

  /* Uggh...  Glyph was not found in any font. */
  return unknown_glyph;  /* Failed to load glyph. */
}

/*
   Free the memory used by a font.
   This should not be called if the font has been made available to
   users (once it is added to the global font list), since there would
   be the possibility of a dangling pointer.
 */
static void
free_font (grub_font_t font)
{
  if (font)
    {
      if (font->file)
        grub_file_close (font->file);
      if (font->name)
        grub_free (font->name);
      if (font->char_index)
        grub_free (font->char_index);
      grub_free (font);
    }
}

/*
   Add FONT to the global font registry.
   Returns 0 upon success, nonzero on failure (the font was not registered).
 */
static int
register_font (grub_font_t font)
{
  struct font_node *node = 0;

  node = grub_malloc (sizeof (struct font_node));
  if (!node)
    return 1;  /* Error. */

  node->value = font;
  node->next = grub_font_list;
  grub_font_list = node;

  return 0;  /* Success. */
}

/*
   Remove the font from the global font list.  We don't actually free the
   font's memory since users could be holding references to the font.
 */
static void
remove_font (grub_font_t font)
{
  struct font_node **nextp, *cur;

  for (nextp = &grub_font_list, cur = *nextp;
       cur;
       nextp = &cur->next, cur = cur->next)
    {
      if (cur->value == font)
        {
          *nextp = cur->next;

          /* Free the node, but not the font itself. */
          grub_free (cur);

          return;
        }
    }
}

