home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gd201.zip / gd-2.0.1 / gdft.c < prev    next >
C/C++ Source or Header  |  2001-04-03  |  23KB  |  937 lines

  1.  
  2. /********************************************/
  3. /* gd interface to freetype library         */
  4. /*                                          */
  5. /* John Ellson   ellson@lucent.com          */
  6. /********************************************/
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <math.h>
  12. #include "gd.h"
  13. #include "gdhelpers.h"
  14.  
  15. #ifndef MSWIN32
  16. #include <unistd.h>
  17. #else
  18. #define R_OK 2
  19. #endif
  20.  
  21. /* number of antialised colors for indexed bitmaps */
  22. #define NUMCOLORS 8
  23.  
  24. char *
  25. gdImageStringTTF (gdImage * im, int *brect, int fg, char *fontlist,
  26.           double ptsize, double angle, int x, int y, char *string)
  27. {
  28.   gdImageStringFT (im, brect, fg, fontlist, ptsize,
  29.            angle, x, y, string);
  30. }
  31.  
  32. #ifndef HAVE_LIBFREETYPE
  33. char *
  34. gdImageStringFT (gdImage * im, int *brect, int fg, char *fontlist,
  35.          double ptsize, double angle, int x, int y, char *string)
  36. {
  37.   return "libgd was not built with FreeType font support\n";
  38. }
  39. #else
  40.  
  41. #include "gdcache.h"
  42. #include "freetype/freetype.h"
  43. #include "freetype/ftglyph.h"
  44.  
  45. /* number of fonts cached before least recently used is replaced */
  46. #define FONTCACHESIZE 6
  47.  
  48. /* number of antialias color lookups cached */
  49. #define TWEENCOLORCACHESIZE 32
  50.  
  51. /*
  52.  * Line separation as a factor of font height.  
  53.  *      No space between if LINESPACE = 1.00 
  54.  *      Line separation will be rounded up to next pixel row.
  55.  */
  56. #define LINESPACE 1.05
  57.  
  58. /*
  59.  * The character (space) used to separate alternate fonts in the
  60.  * fontlist parameter to gdImageStringFT.
  61.  */
  62. #define LISTSEPARATOR " "
  63.  
  64. /*
  65.  * DEFAULT_FONTPATH and PATHSEPARATOR are host type dependent and
  66.  * are normally set by configure in gvconfig.h.  These are just
  67.  * some last resort values that might match some Un*x system
  68.  * if building this version of gd separate from graphviz.
  69.  */
  70. #ifndef DEFAULT_FONTPATH
  71. #define DEFAULT_FONTPATH "/usr/share/fonts/truetype"
  72. #endif
  73. #ifndef PATHSEPARATOR
  74. #define PATHSEPARATOR ":"
  75. #endif
  76.  
  77. #ifndef TRUE
  78. #define FALSE 0
  79. #define TRUE !FALSE
  80. #endif
  81.  
  82. #define MAX(a,b) ((a)>(b)?(a):(b))
  83. #define MIN(a,b) ((a)<(b)?(a):(b))
  84.  
  85. typedef struct
  86. {
  87.   char *fontlist;        /* key */
  88.   FT_Library *library;
  89.   FT_Face face;
  90.   FT_Bool have_char_map_unicode, have_char_map_big5, have_char_map_sjis,
  91.     have_char_map_apple_roman;
  92.   gdCache_head_t *glyphCache;
  93. }
  94. font_t;
  95.  
  96. typedef struct
  97.   {
  98.     char *fontlist;        /* key */
  99.     FT_Library *library;
  100.   }
  101. fontkey_t;
  102.  
  103. typedef struct
  104.   {
  105.     int pixel;            /* key */
  106.     int bgcolor;        /* key */
  107.     int fgcolor;        /* key *//* -ve means no antialias */
  108.     gdImagePtr im;        /* key */
  109.     int tweencolor;
  110.   }
  111. tweencolor_t;
  112.  
  113. typedef struct
  114.   {
  115.     int pixel;            /* key */
  116.     int bgcolor;        /* key */
  117.     int fgcolor;        /* key *//* -ve means no antialias */
  118.     gdImagePtr im;        /* key */
  119.   }
  120. tweencolorkey_t;
  121.  
  122. /********************************************************************
  123.  * gdTcl_UtfToUniChar is borrowed from Tcl ...
  124.  */
  125. /*
  126.  * tclUtf.c --
  127.  *
  128.  *      Routines for manipulating UTF-8 strings.
  129.  *
  130.  * Copyright (c) 1997-1998 Sun Microsystems, Inc.
  131.  *
  132.  * See the file "license.terms" for information on usage and redistribution
  133.  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  134.  *
  135.  * SCCS: @(#) tclUtf.c 1.25 98/01/28 18:02:43
  136.  */
  137.  
  138. /*
  139.  *---------------------------------------------------------------------------
  140.  *
  141.  * gdTcl_UtfToUniChar --
  142.  *
  143.  *      Extract the Tcl_UniChar represented by the UTF-8 string.  Bad
  144.  *      UTF-8 sequences are converted to valid Tcl_UniChars and processing
  145.  *      continues.  Equivalent to Plan 9 chartorune().
  146.  *
  147.  *      The caller must ensure that the source buffer is long enough that
  148.  *      this routine does not run off the end and dereference non-existent
  149.  *      memory looking for trail bytes.  If the source buffer is known to
  150.  *      be '\0' terminated, this cannot happen.  Otherwise, the caller
  151.  *      should call Tcl_UtfCharComplete() before calling this routine to
  152.  *      ensure that enough bytes remain in the string.
  153.  *
  154.  * Results:
  155.  *      *chPtr is filled with the Tcl_UniChar, and the return value is the
  156.  *      number of bytes from the UTF-8 string that were consumed.
  157.  *
  158.  * Side effects:
  159.  *      None.
  160.  *
  161.  *---------------------------------------------------------------------------
  162.  */
  163.  
  164. #ifdef JISX0208
  165. #include "jisx0208.h"
  166. #endif
  167.  
  168. #define Tcl_UniChar int
  169. #define TCL_UTF_MAX 3
  170. static int
  171. gdTcl_UtfToUniChar (char *str, Tcl_UniChar * chPtr)
  172. /* str is the UTF8 next character pointer */
  173. /* chPtr is the int for the result */
  174. {
  175.   int byte;
  176.  
  177.   /* HTML4.0 entities in decimal form, e.g. Å */
  178.   byte = *((unsigned char *) str);
  179.   if (byte == '&')
  180.     {
  181.       int i, n = 0;
  182.  
  183.       byte = *((unsigned char *) (str + 1));
  184.       if (byte == '#')
  185.     {
  186.       for (i = 2; i < 8; i++)
  187.         {
  188.           byte = *((unsigned char *) (str + i));
  189.           if (byte >= '0' && byte <= '9')
  190.         {
  191.           n = (n * 10) + (byte - '0');
  192.         }
  193.           else
  194.         break;
  195.         }
  196.       if (byte == ';')
  197.         {
  198.           *chPtr = (Tcl_UniChar) n;
  199.           return ++i;
  200.         }
  201.     }
  202.     }
  203.  
  204.   /*
  205.    * Unroll 1 to 3 byte UTF-8 sequences, use loop to handle longer ones.
  206.    */
  207.  
  208.   byte = *((unsigned char *) str);
  209. #ifdef JISX0208
  210.   if (0xA1 <= byte && byte <= 0xFE)
  211.     {
  212.       int ku, ten;
  213.  
  214.       ku = (byte & 0x7F) - 0x20;
  215.       ten = (str[1] & 0x7F) - 0x20;
  216.       if ((ku < 1 || ku > 92) || (ten < 1 || ten > 94))
  217.     {
  218.       *chPtr = (Tcl_UniChar) byte;
  219.       return 1;
  220.     }
  221.  
  222.       *chPtr = (Tcl_UniChar) UnicodeTbl[ku - 1][ten - 1];
  223.       return 2;
  224.     }
  225.   else
  226. #endif /* JISX0208 */
  227.   if (byte < 0xC0)
  228.     {
  229.       /*
  230.        * Handles properly formed UTF-8 characters between
  231.        * 0x01 and 0x7F.  Also treats \0 and naked trail
  232.        * bytes 0x80 to 0xBF as valid characters representing
  233.        * themselves.
  234.        */
  235.  
  236.       *chPtr = (Tcl_UniChar) byte;
  237.       return 1;
  238.     }
  239.   else if (byte < 0xE0)
  240.     {
  241.       if ((str[1] & 0xC0) == 0x80)
  242.     {
  243.       /*
  244.        * Two-byte-character lead-byte followed
  245.        * by a trail-byte.
  246.        */
  247.  
  248.       *chPtr = (Tcl_UniChar) (((byte & 0x1F) << 6)
  249.                   | (str[1] & 0x3F));
  250.       return 2;
  251.     }
  252.       /*
  253.        * A two-byte-character lead-byte not followed by trail-byte
  254.        * represents itself.
  255.        */
  256.  
  257.       *chPtr = (Tcl_UniChar) byte;
  258.       return 1;
  259.     }
  260.   else if (byte < 0xF0)
  261.     {
  262.       if (((str[1] & 0xC0) == 0x80) && ((str[2] & 0xC0) == 0x80))
  263.     {
  264.       /*
  265.        * Three-byte-character lead byte followed by
  266.        * two trail bytes.
  267.        */
  268.  
  269.       *chPtr = (Tcl_UniChar) (((byte & 0x0F) << 12)
  270.                 | ((str[1] & 0x3F) << 6) | (str[2] & 0x3F));
  271.       return 3;
  272.     }
  273.       /*
  274.        * A three-byte-character lead-byte not followed by
  275.        * two trail-bytes represents itself.
  276.        */
  277.  
  278.       *chPtr = (Tcl_UniChar) byte;
  279.       return 1;
  280.     }
  281. #if TCL_UTF_MAX > 3
  282.   else
  283.     {
  284.       int ch, total, trail;
  285.  
  286.       total = totalBytes[byte];
  287.       trail = total - 1;
  288.       if (trail > 0)
  289.     {
  290.       ch = byte & (0x3F >> trail);
  291.       do
  292.         {
  293.           str++;
  294.           if ((*str & 0xC0) != 0x80)
  295.         {
  296.           *chPtr = byte;
  297.           return 1;
  298.         }
  299.           ch <<= 6;
  300.           ch |= (*str & 0x3F);
  301.           trail--;
  302.         }
  303.       while (trail > 0);
  304.       *chPtr = ch;
  305.       return total;
  306.     }
  307.     }
  308. #endif
  309.  
  310.   *chPtr = (Tcl_UniChar) byte;
  311.   return 1;
  312. }
  313.  
  314. /********************************************************************/
  315. /* font cache functions                                             */
  316.  
  317. static int
  318. fontTest (void *element, void *key)
  319. {
  320.   font_t *a = (font_t *) element;
  321.   fontkey_t *b = (fontkey_t *) key;
  322.  
  323.   return (strcmp (a->fontlist, b->fontlist) == 0);
  324. }
  325.  
  326. static void *
  327. fontFetch (char **error, void *key)
  328. {
  329.   font_t *a;
  330.   fontkey_t *b = (fontkey_t *) key;
  331.   int n;
  332.   int font_found = 0;
  333.   unsigned short platform, encoding;
  334.   char *fontsearchpath, *fontpath, *fontlist;
  335.   char *fullname = NULL;
  336.   char *name, *path, *dir;
  337.   char *strtok_ptr;
  338.   FT_Error err;
  339.   FT_CharMap found = 0;
  340.   FT_CharMap charmap;
  341.  
  342.   a = (font_t *) gdMalloc (sizeof (font_t));
  343.   a->fontlist = strdup (b->fontlist);
  344.   a->library = b->library;
  345.  
  346.   /*
  347.    * Search the pathlist for any of a list of font names.
  348.    */
  349.   fontsearchpath = getenv ("GDFONTPATH");
  350.   if (!fontsearchpath)
  351.     fontsearchpath = DEFAULT_FONTPATH;
  352.   path = strdup (fontsearchpath);
  353.   fontlist = strdup (a->fontlist);
  354.  
  355.   /*
  356.    * Must use gd_strtok_r else pointer corrupted by strtok in nested loop.
  357.    */
  358.   for (name = gd_strtok_r (fontlist, LISTSEPARATOR, &strtok_ptr); name;
  359.        name = gd_strtok_r (0, LISTSEPARATOR, &strtok_ptr))
  360.     {
  361.  
  362.       /*
  363.        * Allocate an oversized buffer that is guaranteed to be
  364.        * big enough for all paths to be tested.
  365.        */
  366.       fullname = gdRealloc (fullname,
  367.                 strlen (fontsearchpath) + strlen (name) + 6);
  368.       /* if name is an absolute filename then test directly */
  369.       if (*name == '/')
  370.     {
  371.       sprintf (fullname, "%s", name);
  372.       if (access (fullname, R_OK) == 0)
  373.         {
  374.           font_found++;
  375.           break;
  376.         }
  377.     }
  378.       for (dir = strtok (path, PATHSEPARATOR); dir;
  379.        dir = strtok (0, PATHSEPARATOR))
  380.     {
  381.       sprintf (fullname, "%s/%s.ttf", dir, name);
  382.       if (access (fullname, R_OK) == 0)
  383.         {
  384.           font_found++;
  385.           break;
  386.         }
  387.     }
  388.       if (font_found)
  389.     break;
  390.     }
  391.   gdFree (path);
  392.   gdFree (fontlist);
  393.   if (!font_found)
  394.     {
  395.       *error = "Could not find/open font";
  396.       return NULL;
  397.     }
  398.  
  399.   err = FT_New_Face (*b->library, fullname, 0, &a->face);
  400.   if (err)
  401.     {
  402.       *error = "Could not read font";
  403.       return NULL;
  404.     }
  405.   gdFree (fullname);
  406.  
  407. /* FIXME - This mapping stuff is imcomplete - where is the spec? */
  408.  
  409.   a->have_char_map_unicode = 0;
  410.   a->have_char_map_big5 = 0;
  411.   a->have_char_map_sjis = 0;
  412.   a->have_char_map_apple_roman = 0;
  413.   for (n = 0; n < a->face->num_charmaps; n++)
  414.     {
  415.       charmap = a->face->charmaps[n];
  416.       platform = charmap->platform_id;
  417.       encoding = charmap->encoding_id;
  418.       if ((platform == 3 && encoding == 1)    /* Windows Unicode */
  419.       || (platform == 3 && encoding == 0)    /* Windows Symbol */
  420.       || (platform == 2 && encoding == 1)    /* ISO Unicode */
  421.       || (platform == 0))
  422.     {            /* Apple Unicode */
  423.       a->have_char_map_unicode = 1;
  424.       found = charmap;
  425.     }
  426.       else if (platform == 3 && encoding == 4)
  427.     {            /* Windows Big5 */
  428.       a->have_char_map_big5 = 1;
  429.       found = charmap;
  430.     }
  431.       else if (platform == 3 && encoding == 2)
  432.     {            /* Windows Sjis */
  433.       a->have_char_map_sjis = 1;
  434.       found = charmap;
  435.     }
  436.       else if ((platform == 1 && encoding == 0)        /* Apple Roman */
  437.            || (platform == 2 && encoding == 0))
  438.     {            /* ISO ASCII */
  439.       a->have_char_map_apple_roman = 1;
  440.       found = charmap;
  441.     }
  442.     }
  443.   if (!found)
  444.     {
  445.       *error = "Unable to find a CharMap that I can handle";
  446.       return NULL;
  447.     }
  448.  
  449.   return (void *) a;
  450. }
  451.  
  452. static void
  453. fontRelease (void *element)
  454. {
  455.   font_t *a = (font_t *) element;
  456.  
  457.   FT_Done_Face (a->face);
  458.   gdFree (a->fontlist);
  459.   gdFree ((char *) element);
  460. }
  461.  
  462. /********************************************************************/
  463. /* tweencolor cache functions                                            */
  464.  
  465. static int
  466. tweenColorTest (void *element, void *key)
  467. {
  468.   tweencolor_t *a = (tweencolor_t *) element;
  469.   tweencolorkey_t *b = (tweencolorkey_t *) key;
  470.  
  471.   return (a->pixel == b->pixel
  472.       && a->bgcolor == b->bgcolor
  473.       && a->fgcolor == b->fgcolor
  474.       && a->im == b->im);
  475. }
  476.  
  477. /*
  478.  * Computes a color in im's color table that is part way between
  479.  * the background and foreground colors proportional to the gray
  480.  * pixel value in the range 0-NUMCOLORS. The fg and bg colors must already
  481.  * be in the color table.
  482.  */
  483. static void *
  484. tweenColorFetch (char **error, void *key)
  485. {
  486.   tweencolor_t *a;
  487.   tweencolorkey_t *b = (tweencolorkey_t *) key;
  488.   int pixel, npixel, bg, fg;
  489.   gdImagePtr im;
  490.  
  491.   a = (tweencolor_t *) gdMalloc (sizeof (tweencolor_t));
  492.   pixel = a->pixel = b->pixel;
  493.   bg = a->bgcolor = b->bgcolor;
  494.   fg = a->fgcolor = b->fgcolor;
  495.   im = b->im;
  496.  
  497.   /* if fg is specified by a negative color idx, then don't antialias */
  498.   if (fg < 0)
  499.     {
  500.       a->tweencolor = -fg;
  501.     }
  502.   else
  503.     {
  504.       npixel = NUMCOLORS - pixel;
  505.       if (im->trueColor)
  506.     {
  507.       /* 2.0.1: use gdImageSetPixel to do the alpha blending work,
  508.          or to just store the alpha level. All we have to do here
  509.          is incorporate our knowledge of the percentage of this
  510.          pixel that is really "lit" by pushing the alpha value
  511.          up toward transparency in edge regions. */
  512.       a->tweencolor = gdTrueColorAlpha (
  513.                          gdTrueColorGetRed (fg),
  514.                          gdTrueColorGetGreen (fg),
  515.                          gdTrueColorGetBlue (fg),
  516.            gdAlphaMax - (gdTrueColorGetAlpha (fg) * pixel / NUMCOLORS));
  517.     }
  518.       else
  519.     {
  520.       a->tweencolor = gdImageColorResolve (im,
  521.            (pixel * im->red[fg] + npixel * im->red[bg]) / NUMCOLORS,
  522.            (pixel * im->green[fg] + npixel * im->green[bg]) / NUMCOLORS,
  523.         (pixel * im->blue[fg] + npixel * im->blue[bg]) / NUMCOLORS);
  524.     }
  525.     }
  526.   return (void *) a;
  527. }
  528.  
  529. static void
  530. tweenColorRelease (void *element)
  531. {
  532.   gdFree ((char *) element);
  533. }
  534.  
  535. /* draw_bitmap - transfers glyph bitmap to GD image */
  536. static char *
  537. gdft_draw_bitmap (gdImage * im, int fg, FT_Bitmap bitmap, int pen_x, int pen_y)
  538. {
  539.   unsigned char *pixel;
  540.   int *tpixel;
  541.   int x, y, row, col, pc;
  542.  
  543.   tweencolor_t *tc_elem;
  544.   tweencolorkey_t tc_key;
  545.  
  546.   /* initialize tweenColorCache on first call */
  547.   static gdCache_head_t *tc_cache;
  548.  
  549.   if (!tc_cache)
  550.     {
  551.       tc_cache = gdCacheCreate (TWEENCOLORCACHESIZE,
  552.             tweenColorTest, tweenColorFetch, tweenColorRelease);
  553.     }
  554.  
  555.   /* copy to image, mapping colors */
  556.   tc_key.fgcolor = fg;
  557.   tc_key.im = im;
  558.   for (row = 0; row < bitmap.rows; row++)
  559.     {
  560.       pc = row * bitmap.pitch;
  561.       y = pen_y + row;
  562.  
  563.       /* clip if out of bounds */
  564.       if (y >= im->sy || y < 0)
  565.     continue;
  566.  
  567.       for (col = 0; col < bitmap.width; col++, pc++)
  568.     {
  569.       if (bitmap.pixel_mode == ft_pixel_mode_grays)
  570.         {
  571.           /*
  572.            * Round to NUMCOLORS levels of antialiasing for
  573.            * index color images since only 256 colors are
  574.            * available.
  575.            */
  576.           tc_key.pixel = ((bitmap.buffer[pc] * NUMCOLORS)
  577.                   + bitmap.num_grays / 2)
  578.         / (bitmap.num_grays - 1);
  579.         }
  580.       else if (bitmap.pixel_mode == ft_pixel_mode_mono)
  581.         {
  582.           tc_key.pixel = ((bitmap.buffer[pc / 8]
  583.                    << (pc % 8)) & 128) ? NUMCOLORS : 0;
  584.         }
  585.       else
  586.         {
  587.           return "Unsupported ft_pixel_mode";
  588.         }
  589.  
  590.       if (tc_key.pixel > 0)
  591.         {            /* if not background */
  592.           x = pen_x + col;
  593.  
  594.           /* clip if out of bounds */
  595.           if (x >= im->sx || x < 0)
  596.         continue;
  597.           /* get pixel location in gd buffer */
  598.           if (im->trueColor)
  599.         {
  600.           tpixel = &im->tpixels[y][x];
  601.         }
  602.           else
  603.         {
  604.           pixel = &im->pixels[y][x];
  605.         }
  606.           if (tc_key.pixel == NUMCOLORS)
  607.         {
  608.           /* use fg color directly */
  609.           if (im->trueColor)
  610.             {
  611.               *tpixel = fg;
  612.             }
  613.           else
  614.             {
  615.               *pixel = fg;
  616.             }
  617.         }
  618.           else
  619.         {
  620.           /* find antialised color */
  621.           if (im->trueColor)
  622.             {
  623.               tc_key.bgcolor = *tpixel;
  624.             }
  625.           else
  626.             {
  627.               tc_key.bgcolor = *pixel;
  628.             }
  629.           tc_elem = (tweencolor_t *) gdCacheGet (
  630.                               tc_cache, &tc_key);
  631.           if (im->trueColor)
  632.             {
  633.               *tpixel = tc_elem->tweencolor;
  634.             }
  635.           else
  636.             {
  637.               *pixel = tc_elem->tweencolor;
  638.             }
  639.         }
  640.         }
  641.     }
  642.     }
  643.   return (char *) NULL;
  644. }
  645.  
  646. extern int any2eucjp (char *, char *, unsigned int);
  647.  
  648. /********************************************************************/
  649. /* gdImageStringFT -  render a utf8 string onto a gd image          */
  650.  
  651. char *
  652. gdImageStringFT (gdImage * im, int *brect, int fg, char *fontlist,
  653.          double ptsize, double angle, int x, int y, char *string)
  654. {
  655.   FT_BBox bbox, glyph_bbox;
  656.   FT_Matrix matrix;
  657.   FT_Vector pen, delta, penf;
  658.   FT_Face face;
  659.   FT_Glyph image;
  660.   FT_GlyphSlot slot;
  661.   FT_Error err;
  662.   FT_Bool use_kerning;
  663.   FT_UInt glyph_index, previous;
  664.   double sin_a = sin (angle);
  665.   double cos_a = cos (angle);
  666.   int len, i = 0, ch;
  667.   int x1 = 0, y1 = 0;
  668.   font_t *font;
  669.   fontkey_t fontkey;
  670.   char *next;
  671.   char *tmpstr = 0;
  672.   int render = (im && (im->trueColor || (fg <= 255 && fg >= -255)));
  673.   FT_BitmapGlyph bm;
  674.  
  675. /***** initialize font library and font cache on first call ******/
  676.   static gdCache_head_t *fontCache;
  677.   static FT_Library library;
  678.  
  679.   if (!fontCache)
  680.     {
  681.       if (FT_Init_FreeType (&library))
  682.     {
  683.       return "Failure to initialize font library";
  684.     }
  685.       fontCache = gdCacheCreate (FONTCACHESIZE,
  686.                  fontTest, fontFetch, fontRelease);
  687.     }
  688. /*****/
  689.  
  690.   /* get the font (via font cache) */
  691.   fontkey.fontlist = fontlist;
  692.   fontkey.library = &library;
  693.   font = (font_t *) gdCacheGet (fontCache, &fontkey);
  694.   if (!font)
  695.     {
  696.       return fontCache->error;
  697.     }
  698.   face = font->face;        /* shortcut */
  699.   slot = face->glyph;        /* shortcut */
  700.  
  701.   if (FT_Set_Char_Size (face, 0, (FT_F26Dot6) (ptsize * 64),
  702.             GD_RESOLUTION, GD_RESOLUTION))
  703.     {
  704.       return "Could not set character size";
  705.     }
  706.  
  707.   matrix.xx = (FT_Fixed) (cos_a * (1 << 16));
  708.   matrix.yx = (FT_Fixed) (sin_a * (1 << 16));
  709.   matrix.xy = -matrix.yx;
  710.   matrix.yy = matrix.xx;
  711.  
  712.   penf.x = penf.y = 0;        /* running position of non-rotated string */
  713.   pen.x = pen.y = 0;        /* running position of rotated string */
  714.   bbox.xMin = bbox.xMax = bbox.yMin = bbox.yMax = 0;
  715.  
  716.   use_kerning = FT_HAS_KERNING (face);
  717.   previous = 0;
  718.  
  719. #ifndef JISX0208
  720.   if (font->have_char_map_sjis)
  721.     {
  722. #endif
  723.       if (tmpstr = (char *) gdMalloc (BUFSIZ))
  724.     {
  725.       any2eucjp (tmpstr, string, BUFSIZ);
  726.       next = tmpstr;
  727.     }
  728.       else
  729.     {
  730.       next = string;
  731.     }
  732. #ifndef JISX0208
  733.     }
  734.   else
  735.     {
  736.       next = string;
  737.     }
  738. #endif
  739.   while (*next)
  740.     {
  741.       ch = *next;
  742.  
  743.       /* carriage returns */
  744.       if (ch == '\r')
  745.     {
  746.       penf.x = 0;
  747.       x1 = (penf.x * cos_a - penf.y * sin_a + 32) / 64;
  748.       y1 = (penf.x * sin_a + penf.y * cos_a + 32) / 64;
  749.       pen.x = pen.y = 0;
  750.       previous = 0;        /* clear kerning flag */
  751.       next++;
  752.       continue;
  753.     }
  754.       /* newlines */
  755.       if (ch == '\n')
  756.     {
  757.       penf.y -= face->size->metrics.height * LINESPACE;
  758.       penf.y = (penf.y - 32) & -64;        /* round to next pixel row */
  759.       x1 = (penf.x * cos_a - penf.y * sin_a + 32) / 64;
  760.       y1 = (penf.x * sin_a + penf.y * cos_a + 32) / 64;
  761.       pen.x = pen.y = 0;
  762.       previous = 0;        /* clear kerning flag */
  763.       next++;
  764.       continue;
  765.     }
  766.  
  767.       if (font->have_char_map_unicode)
  768.     {
  769.       /* use UTF-8 mapping from ASCII */
  770.       len = gdTcl_UtfToUniChar (next, &ch);
  771.       next += len;
  772.     }
  773.       else if (font->have_char_map_sjis)
  774.     {
  775.       unsigned char c;
  776.       int jiscode;
  777.  
  778.       c = *next;
  779.       if (0xA1 <= c && c <= 0xFE)
  780.         {
  781.           next++;
  782.           jiscode = 0x100 * (c & 0x7F) + ((*next) & 0x7F);
  783.  
  784.           ch = (jiscode >> 8) & 0xFF;
  785.           jiscode &= 0xFF;
  786.  
  787.           if (ch & 1)
  788.         jiscode += 0x40 - 0x21;
  789.           else
  790.         jiscode += 0x9E - 0x21;
  791.  
  792.           if (jiscode >= 0x7F)
  793.         jiscode++;
  794.           ch = (ch - 0x21) / 2 + 0x81;
  795.           if (ch >= 0xA0)
  796.         ch += 0x40;
  797.  
  798.           ch = (ch << 8) + jiscode;
  799.         }
  800.       else
  801.         {
  802.           ch = c & 0xFF;    /* don't extend sign */
  803.         }
  804.       next++;
  805.     }
  806.       else
  807.     {
  808.       /*
  809.        * Big 5 mapping:
  810.        * use "JIS-8 half-width katakana" coding from 8-bit characters. Ref:
  811.        * ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/japan.inf-032092.sjs
  812.        */
  813.       ch = (*next) & 0xFF;    /* don't extend sign */
  814.       next++;
  815.       if (ch >= 161        /* first code of JIS-8 pair */
  816.           && *next)
  817.         {            /* don't advance past '\0' */
  818.           /* TBB: Fix from Kwok Wah On: & 255 needed */
  819.           ch = (ch * 256) + ((*next) & 255);
  820.           next++;
  821.         }
  822.     }
  823.  
  824.       /* Convert character code to glyph index */
  825.       glyph_index = FT_Get_Char_Index (face, ch);
  826.  
  827.       /* retrieve kerning distance and move pen position */
  828.       if (use_kerning && previous && glyph_index)
  829.     {
  830.       FT_Get_Kerning (face, previous, glyph_index,
  831.               ft_kerning_default, &delta);
  832.       pen.x += delta.x;
  833.     }
  834.  
  835.       /* load glyph image into the slot (erase previous one) */
  836.       err = FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT);
  837.       if (err)
  838.     return "Problem loading glyph";
  839.  
  840.       /* transform glyph image */
  841.       FT_Get_Glyph (slot, &image);
  842.       if (brect)
  843.     {            /* only if need brect */
  844.       FT_Glyph_Get_CBox (image, ft_glyph_bbox_gridfit, &glyph_bbox);
  845.       if (!i)
  846.         {            /* if first character, init BB corner values */
  847.           bbox.xMin = bbox.yMin = (1 << 30) - 1;
  848.           bbox.xMax = bbox.yMax = -bbox.xMin;
  849.         }
  850.       glyph_bbox.xMin += penf.x;
  851.       glyph_bbox.yMin += penf.y;
  852.       glyph_bbox.xMax += penf.x;
  853.       glyph_bbox.yMax += penf.y;
  854.       if (bbox.xMin > glyph_bbox.xMin)
  855.         bbox.xMin = glyph_bbox.xMin;
  856.       if (bbox.yMin > glyph_bbox.yMin)
  857.         bbox.yMin = glyph_bbox.yMin;
  858.       if (bbox.xMax < glyph_bbox.xMax)
  859.         bbox.xMax = glyph_bbox.xMax;
  860.       if (bbox.yMax < glyph_bbox.yMax)
  861.         bbox.yMax = glyph_bbox.yMax;
  862.       i++;
  863.     }
  864.  
  865.       /* transform glyph image */
  866.       FT_Glyph_Transform (image, &matrix, 0);
  867.  
  868.       if (render)
  869.     {
  870.       if (image->format != ft_glyph_format_bitmap)
  871.         {
  872.           err = FT_Glyph_To_Bitmap (&image, ft_render_mode_normal, 0, 1);
  873.           if (err)
  874.         return "Problem rendering glyph";
  875.         }
  876.  
  877.       /* now, draw to our target surface */
  878.       bm = (FT_BitmapGlyph) image;
  879.       gdft_draw_bitmap (im, fg, bm->bitmap,
  880.                 x + x1 + ((pen.x + 31) >> 6) + bm->left,
  881.                 y - y1 + ((pen.y + 31) >> 6) - bm->top);
  882.     }
  883.  
  884.       /* record current glyph index for kerning */
  885.       previous = glyph_index;
  886.  
  887.       /* increment pen position */
  888.       pen.x += image->advance.x >> 10;
  889.       pen.y -= image->advance.y >> 10;
  890.  
  891.       penf.x += slot->metrics.horiAdvance;
  892.  
  893.       FT_Done_Glyph (image);
  894.     }
  895.  
  896.   if (brect)
  897.     {                /* only if need brect */
  898.       /* For perfect rounding, must get sin(a + pi/4) and sin(a - pi/4). */
  899.       double d1 = sin (angle + 0.78539816339744830962);
  900.       double d2 = sin (angle - 0.78539816339744830962);
  901.  
  902.       /* rotate bounding rectangle */
  903.       brect[0] = (int) (bbox.xMin * cos_a - bbox.yMin * sin_a);
  904.       brect[1] = (int) (bbox.xMin * sin_a + bbox.yMin * cos_a);
  905.       brect[2] = (int) (bbox.xMax * cos_a - bbox.yMin * sin_a);
  906.       brect[3] = (int) (bbox.xMax * sin_a + bbox.yMin * cos_a);
  907.       brect[4] = (int) (bbox.xMax * cos_a - bbox.yMax * sin_a);
  908.       brect[5] = (int) (bbox.xMax * sin_a + bbox.yMax * cos_a);
  909.       brect[6] = (int) (bbox.xMin * cos_a - bbox.yMax * sin_a);
  910.       brect[7] = (int) (bbox.xMin * sin_a + bbox.yMax * cos_a);
  911.  
  912.       /* scale, round and offset brect */
  913.       brect[0] = x + gdroundupdown (brect[0], d2 > 0);
  914.       brect[1] = y - gdroundupdown (brect[1], d1 < 0);
  915.       brect[2] = x + gdroundupdown (brect[2], d1 > 0);
  916.       brect[3] = y - gdroundupdown (brect[3], d2 > 0);
  917.       brect[4] = x + gdroundupdown (brect[4], d2 < 0);
  918.       brect[5] = y - gdroundupdown (brect[5], d1 > 0);
  919.       brect[6] = x + gdroundupdown (brect[6], d1 < 0);
  920.       brect[7] = y - gdroundupdown (brect[7], d2 < 0);
  921.     }
  922.  
  923.   if (tmpstr)
  924.     gdFree (tmpstr);
  925.   return (char *) NULL;
  926. }
  927.  
  928. int
  929. gdroundupdown (FT_F26Dot6 v1, int updown)
  930. {
  931.   return (!updown)
  932.     ? (v1 < 0 ? ((v1 - 63) >> 6) : v1 >> 6)
  933.     : (v1 > 0 ? ((v1 + 63) >> 6) : v1 >> 6);
  934. }
  935.  
  936. #endif /* HAVE_LIBFREETYPE */
  937.