1 /****************************************************************************
   2  *
   3  * afcjk.c
   4  *
   5  *   Auto-fitter hinting routines for CJK writing system (body).
   6  *
   7  * Copyright (C) 2006-2019 by
   8  * David Turner, Robert Wilhelm, and Werner Lemberg.
   9  *
  10  * This file is part of the FreeType project, and may only be used,
  11  * modified, and distributed under the terms of the FreeType project
  12  * license, LICENSE.TXT.  By continuing to use, modify, or distribute
  13  * this file you indicate that you have read the license and
  14  * understand and accept it fully.
  15  *
  16  */
  17 
  18   /*
  19    * The algorithm is based on akito's autohint patch, archived at
  20    *
  21    * https://web.archive.org/web/20051219160454/http://www.kde.gr.jp:80/~akito/patch/freetype2/2.1.7/
  22    *
  23    */
  24 
  25 #include <ft2build.h>
  26 #include FT_ADVANCES_H
  27 #include FT_INTERNAL_DEBUG_H
  28 
  29 #include "afglobal.h"
  30 #include "aflatin.h"
  31 #include "afcjk.h"
  32 
  33 
  34 #ifdef AF_CONFIG_OPTION_CJK
  35 
  36 #undef AF_CONFIG_OPTION_CJK_BLUE_HANI_VERT
  37 
  38 #include "aferrors.h"
  39 
  40 
  41 #ifdef AF_CONFIG_OPTION_USE_WARPER
  42 #include "afwarp.h"
  43 #endif
  44 
  45 
  46   /**************************************************************************
  47    *
  48    * The macro FT_COMPONENT is used in trace mode.  It is an implicit
  49    * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
  50    * messages during execution.
  51    */
  52 #undef  FT_COMPONENT
  53 #define FT_COMPONENT  afcjk
  54 
  55 
  56   /*************************************************************************/
  57   /*************************************************************************/
  58   /*****                                                               *****/
  59   /*****              C J K   G L O B A L   M E T R I C S              *****/
  60   /*****                                                               *****/
  61   /*************************************************************************/
  62   /*************************************************************************/
  63 
  64 
  65   /* Basically the Latin version with AF_CJKMetrics */
  66   /* to replace AF_LatinMetrics.                    */
  67 
  68   FT_LOCAL_DEF( void )
  69   af_cjk_metrics_init_widths( AF_CJKMetrics  metrics,
  70                               FT_Face        face )
  71   {
  72     /* scan the array of segments in each direction */
  73     AF_GlyphHintsRec  hints[1];
  74 
  75 
  76     FT_TRACE5(( "\n"
  77                 "cjk standard widths computation (style `%s')\n"
  78                 "===================================================\n"
  79                 "\n",
  80                 af_style_names[metrics->root.style_class->style] ));
  81 
  82     af_glyph_hints_init( hints, face->memory );
  83 
  84     metrics->axis[AF_DIMENSION_HORZ].width_count = 0;
  85     metrics->axis[AF_DIMENSION_VERT].width_count = 0;
  86 
  87     {
  88       FT_Error          error;
  89       FT_ULong          glyph_index;
  90       int               dim;
  91       AF_CJKMetricsRec  dummy[1];
  92       AF_Scaler         scaler = &dummy->root.scaler;
  93 
  94       AF_StyleClass   style_class  = metrics->root.style_class;
  95       AF_ScriptClass  script_class = af_script_classes[style_class->script];
  96 
  97       /* If HarfBuzz is not available, we need a pointer to a single */
  98       /* unsigned long value.                                        */
  99 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 100       void*     shaper_buf;
 101 #else
 102       FT_ULong  shaper_buf_;
 103       void*     shaper_buf = &shaper_buf_;
 104 #endif
 105 
 106       const char*  p;
 107 
 108 #ifdef FT_DEBUG_LEVEL_TRACE
 109       FT_ULong  ch = 0;
 110 #endif
 111 
 112       p = script_class->standard_charstring;
 113 
 114 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 115       shaper_buf = af_shaper_buf_create( face );
 116 #endif
 117 
 118       /* We check a list of standard characters.  The first match wins. */
 119 
 120       glyph_index = 0;
 121       while ( *p )
 122       {
 123         unsigned int  num_idx;
 124 
 125 #ifdef FT_DEBUG_LEVEL_TRACE
 126         const char*  p_old;
 127 #endif
 128 
 129 
 130         while ( *p == ' ' )
 131           p++;
 132 
 133 #ifdef FT_DEBUG_LEVEL_TRACE
 134         p_old = p;
 135         GET_UTF8_CHAR( ch, p_old );
 136 #endif
 137 
 138         /* reject input that maps to more than a single glyph */
 139         p = af_shaper_get_cluster( p, &metrics->root, shaper_buf, &num_idx );
 140         if ( num_idx > 1 )
 141           continue;
 142 
 143         /* otherwise exit loop if we have a result */
 144         glyph_index = af_shaper_get_elem( &metrics->root,
 145                                           shaper_buf,
 146                                           0,
 147                                           NULL,
 148                                           NULL );
 149         if ( glyph_index )
 150           break;
 151       }
 152 
 153       af_shaper_buf_destroy( face, shaper_buf );
 154 
 155       if ( !glyph_index )
 156         goto Exit;
 157 
 158       if ( !glyph_index )
 159         goto Exit;
 160 
 161       FT_TRACE5(( "standard character: U+%04lX (glyph index %d)\n",
 162                   ch, glyph_index ));
 163 
 164       error = FT_Load_Glyph( face, glyph_index, FT_LOAD_NO_SCALE );
 165       if ( error || face->glyph->outline.n_points <= 0 )
 166         goto Exit;
 167 
 168       FT_ZERO( dummy );
 169 
 170       dummy->units_per_em = metrics->units_per_em;
 171 
 172       scaler->x_scale = 0x10000L;
 173       scaler->y_scale = 0x10000L;
 174       scaler->x_delta = 0;
 175       scaler->y_delta = 0;
 176 
 177       scaler->face        = face;
 178       scaler->render_mode = FT_RENDER_MODE_NORMAL;
 179       scaler->flags       = 0;
 180 
 181       af_glyph_hints_rescale( hints, (AF_StyleMetrics)dummy );
 182 
 183       error = af_glyph_hints_reload( hints, &face->glyph->outline );
 184       if ( error )
 185         goto Exit;
 186 
 187       for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
 188       {
 189         AF_CJKAxis    axis    = &metrics->axis[dim];
 190         AF_AxisHints  axhints = &hints->axis[dim];
 191         AF_Segment    seg, limit, link;
 192         FT_UInt       num_widths = 0;
 193 
 194 
 195         error = af_latin_hints_compute_segments( hints,
 196                                                  (AF_Dimension)dim );
 197         if ( error )
 198           goto Exit;
 199 
 200         /*
 201          * We assume that the glyphs selected for the stem width
 202          * computation are `featureless' enough so that the linking
 203          * algorithm works fine without adjustments of its scoring
 204          * function.
 205          */
 206         af_latin_hints_link_segments( hints,
 207                                       0,
 208                                       NULL,
 209                                       (AF_Dimension)dim );
 210 
 211         seg   = axhints->segments;
 212         limit = seg + axhints->num_segments;
 213 
 214         for ( ; seg < limit; seg++ )
 215         {
 216           link = seg->link;
 217 
 218           /* we only consider stem segments there! */
 219           if ( link && link->link == seg && link > seg )
 220           {
 221             FT_Pos  dist;
 222 
 223 
 224             dist = seg->pos - link->pos;
 225             if ( dist < 0 )
 226               dist = -dist;
 227 
 228             if ( num_widths < AF_CJK_MAX_WIDTHS )
 229               axis->widths[num_widths++].org = dist;
 230           }
 231         }
 232 
 233         /* this also replaces multiple almost identical stem widths */
 234         /* with a single one (the value 100 is heuristic)           */
 235         af_sort_and_quantize_widths( &num_widths, axis->widths,
 236                                      dummy->units_per_em / 100 );
 237         axis->width_count = num_widths;
 238       }
 239 
 240     Exit:
 241       for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
 242       {
 243         AF_CJKAxis  axis = &metrics->axis[dim];
 244         FT_Pos      stdw;
 245 
 246 
 247         stdw = ( axis->width_count > 0 ) ? axis->widths[0].org
 248                                          : AF_LATIN_CONSTANT( metrics, 50 );
 249 
 250         /* let's try 20% of the smallest width */
 251         axis->edge_distance_threshold = stdw / 5;
 252         axis->standard_width          = stdw;
 253         axis->extra_light             = 0;
 254 
 255 #ifdef FT_DEBUG_LEVEL_TRACE
 256         {
 257           FT_UInt  i;
 258 
 259 
 260           FT_TRACE5(( "%s widths:\n",
 261                       dim == AF_DIMENSION_VERT ? "horizontal"
 262                                                : "vertical" ));
 263 
 264           FT_TRACE5(( "  %d (standard)", axis->standard_width ));
 265           for ( i = 1; i < axis->width_count; i++ )
 266             FT_TRACE5(( " %d", axis->widths[i].org ));
 267 
 268           FT_TRACE5(( "\n" ));
 269         }
 270 #endif
 271       }
 272     }
 273 
 274     FT_TRACE5(( "\n" ));
 275 
 276     af_glyph_hints_done( hints );
 277   }
 278 
 279 
 280   /* Find all blue zones. */
 281 
 282   static void
 283   af_cjk_metrics_init_blues( AF_CJKMetrics  metrics,
 284                              FT_Face        face )
 285   {
 286     FT_Pos      fills[AF_BLUE_STRING_MAX_LEN];
 287     FT_Pos      flats[AF_BLUE_STRING_MAX_LEN];
 288 
 289     FT_UInt     num_fills;
 290     FT_UInt     num_flats;
 291 
 292     FT_Bool     fill;
 293 
 294     AF_CJKBlue  blue;
 295     FT_Error    error;
 296     AF_CJKAxis  axis;
 297     FT_Outline  outline;
 298 
 299     AF_StyleClass  sc = metrics->root.style_class;
 300 
 301     AF_Blue_Stringset         bss = sc->blue_stringset;
 302     const AF_Blue_StringRec*  bs  = &af_blue_stringsets[bss];
 303 
 304     /* If HarfBuzz is not available, we need a pointer to a single */
 305     /* unsigned long value.                                        */
 306 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 307     void*     shaper_buf;
 308 #else
 309     FT_ULong  shaper_buf_;
 310     void*     shaper_buf = &shaper_buf_;
 311 #endif
 312 
 313 
 314     /* we walk over the blue character strings as specified in the   */
 315     /* style's entry in the `af_blue_stringset' array, computing its */
 316     /* extremum points (depending on the string properties)          */
 317 
 318     FT_TRACE5(( "cjk blue zones computation\n"
 319                 "==========================\n"
 320                 "\n" ));
 321 
 322 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 323     shaper_buf = af_shaper_buf_create( face );
 324 #endif
 325 
 326     for ( ; bs->string != AF_BLUE_STRING_MAX; bs++ )
 327     {
 328       const char*  p = &af_blue_strings[bs->string];
 329       FT_Pos*      blue_ref;
 330       FT_Pos*      blue_shoot;
 331 
 332 
 333       if ( AF_CJK_IS_HORIZ_BLUE( bs ) )
 334         axis = &metrics->axis[AF_DIMENSION_HORZ];
 335       else
 336         axis = &metrics->axis[AF_DIMENSION_VERT];
 337 
 338 #ifdef FT_DEBUG_LEVEL_TRACE
 339       {
 340         FT_String*  cjk_blue_name[4] =
 341         {
 342           (FT_String*)"bottom",    /* --   , --  */
 343           (FT_String*)"top",       /* --   , TOP */
 344           (FT_String*)"left",      /* HORIZ, --  */
 345           (FT_String*)"right"      /* HORIZ, TOP */
 346         };
 347 
 348 
 349         FT_TRACE5(( "blue zone %d (%s):\n",
 350                     axis->blue_count,
 351                     cjk_blue_name[AF_CJK_IS_HORIZ_BLUE( bs ) |
 352                                   AF_CJK_IS_TOP_BLUE( bs )   ] ));
 353       }
 354 #endif /* FT_DEBUG_LEVEL_TRACE */
 355 
 356       num_fills = 0;
 357       num_flats = 0;
 358 
 359       fill = 1;  /* start with characters that define fill values */
 360       FT_TRACE5(( "  [overshoot values]\n" ));
 361 
 362       while ( *p )
 363       {
 364         FT_ULong    glyph_index;
 365         FT_Pos      best_pos;       /* same as points.y or points.x, resp. */
 366         FT_Int      best_point;
 367         FT_Vector*  points;
 368 
 369         unsigned int  num_idx;
 370 
 371 #ifdef FT_DEBUG_LEVEL_TRACE
 372         const char*  p_old;
 373         FT_ULong     ch;
 374 #endif
 375 
 376 
 377         while ( *p == ' ' )
 378           p++;
 379 
 380 #ifdef FT_DEBUG_LEVEL_TRACE
 381         p_old = p;
 382         GET_UTF8_CHAR( ch, p_old );
 383 #endif
 384 
 385         /* switch to characters that define flat values */
 386         if ( *p == '|' )
 387         {
 388           fill = 0;
 389           FT_TRACE5(( "  [reference values]\n" ));
 390           p++;
 391           continue;
 392         }
 393 
 394         /* reject input that maps to more than a single glyph */
 395         p = af_shaper_get_cluster( p, &metrics->root, shaper_buf, &num_idx );
 396         if ( num_idx > 1 )
 397           continue;
 398 
 399         /* load the character in the face -- skip unknown or empty ones */
 400         glyph_index = af_shaper_get_elem( &metrics->root,
 401                                           shaper_buf,
 402                                           0,
 403                                           NULL,
 404                                           NULL );
 405         if ( glyph_index == 0 )
 406         {
 407           FT_TRACE5(( "  U+%04lX unavailable\n", ch ));
 408           continue;
 409         }
 410 
 411         error   = FT_Load_Glyph( face, glyph_index, FT_LOAD_NO_SCALE );
 412         outline = face->glyph->outline;
 413         if ( error || outline.n_points <= 2 )
 414         {
 415           FT_TRACE5(( "  U+%04lX contains no (usable) outlines\n", ch ));
 416           continue;
 417         }
 418 
 419         /* now compute min or max point indices and coordinates */
 420         points     = outline.points;
 421         best_point = -1;
 422         best_pos   = 0;  /* make compiler happy */
 423 
 424         {
 425           FT_Int  nn;
 426           FT_Int  first = 0;
 427           FT_Int  last  = -1;
 428 
 429 
 430           for ( nn = 0; nn < outline.n_contours; first = last + 1, nn++ )
 431           {
 432             FT_Int  pp;
 433 
 434 
 435             last = outline.contours[nn];
 436 
 437             /* Avoid single-point contours since they are never rasterized. */
 438             /* In some fonts, they correspond to mark attachment points     */
 439             /* which are way outside of the glyph's real outline.           */
 440             if ( last <= first )
 441               continue;
 442 
 443             if ( AF_CJK_IS_HORIZ_BLUE( bs ) )
 444             {
 445               if ( AF_CJK_IS_RIGHT_BLUE( bs ) )
 446               {
 447                 for ( pp = first; pp <= last; pp++ )
 448                   if ( best_point < 0 || points[pp].x > best_pos )
 449                   {
 450                     best_point = pp;
 451                     best_pos   = points[pp].x;
 452                   }
 453               }
 454               else
 455               {
 456                 for ( pp = first; pp <= last; pp++ )
 457                   if ( best_point < 0 || points[pp].x < best_pos )
 458                   {
 459                     best_point = pp;
 460                     best_pos   = points[pp].x;
 461                   }
 462               }
 463             }
 464             else
 465             {
 466               if ( AF_CJK_IS_TOP_BLUE( bs ) )
 467               {
 468                 for ( pp = first; pp <= last; pp++ )
 469                   if ( best_point < 0 || points[pp].y > best_pos )
 470                   {
 471                     best_point = pp;
 472                     best_pos   = points[pp].y;
 473                   }
 474               }
 475               else
 476               {
 477                 for ( pp = first; pp <= last; pp++ )
 478                   if ( best_point < 0 || points[pp].y < best_pos )
 479                   {
 480                     best_point = pp;
 481                     best_pos   = points[pp].y;
 482                   }
 483               }
 484             }
 485           }
 486 
 487           FT_TRACE5(( "  U+%04lX: best_pos = %5ld\n", ch, best_pos ));
 488         }
 489 
 490         if ( fill )
 491           fills[num_fills++] = best_pos;
 492         else
 493           flats[num_flats++] = best_pos;
 494 
 495       } /* end while loop */
 496 
 497       if ( num_flats == 0 && num_fills == 0 )
 498       {
 499         /*
 500          * we couldn't find a single glyph to compute this blue zone,
 501          * we will simply ignore it then
 502          */
 503         FT_TRACE5(( "  empty\n" ));
 504         continue;
 505       }
 506 
 507       /* we have computed the contents of the `fill' and `flats' tables,   */
 508       /* now determine the reference and overshoot position of the blue -- */
 509       /* we simply take the median value after a simple sort               */
 510       af_sort_pos( num_fills, fills );
 511       af_sort_pos( num_flats, flats );
 512 
 513       blue       = &axis->blues[axis->blue_count];
 514       blue_ref   = &blue->ref.org;
 515       blue_shoot = &blue->shoot.org;
 516 
 517       axis->blue_count++;
 518 
 519       if ( num_flats == 0 )
 520       {
 521         *blue_ref   =
 522         *blue_shoot = fills[num_fills / 2];
 523       }
 524       else if ( num_fills == 0 )
 525       {
 526         *blue_ref   =
 527         *blue_shoot = flats[num_flats / 2];
 528       }
 529       else
 530       {
 531         *blue_ref   = fills[num_fills / 2];
 532         *blue_shoot = flats[num_flats / 2];
 533       }
 534 
 535       /* make sure blue_ref >= blue_shoot for top/right or */
 536       /* vice versa for bottom/left                        */
 537       if ( *blue_shoot != *blue_ref )
 538       {
 539         FT_Pos   ref       = *blue_ref;
 540         FT_Pos   shoot     = *blue_shoot;
 541         FT_Bool  under_ref = FT_BOOL( shoot < ref );
 542 
 543 
 544         /* AF_CJK_IS_TOP_BLUE covers `right' and `top' */
 545         if ( AF_CJK_IS_TOP_BLUE( bs ) ^ under_ref )
 546         {
 547           *blue_ref   =
 548           *blue_shoot = ( shoot + ref ) / 2;
 549 
 550           FT_TRACE5(( "  [reference smaller than overshoot,"
 551                       " taking mean value]\n" ));
 552         }
 553       }
 554 
 555       blue->flags = 0;
 556       if ( AF_CJK_IS_TOP_BLUE( bs ) )
 557         blue->flags |= AF_CJK_BLUE_TOP;
 558 
 559       FT_TRACE5(( "    -> reference = %ld\n"
 560                   "       overshoot = %ld\n",
 561                   *blue_ref, *blue_shoot ));
 562 
 563     } /* end for loop */
 564 
 565     af_shaper_buf_destroy( face, shaper_buf );
 566 
 567     FT_TRACE5(( "\n" ));
 568 
 569     return;
 570   }
 571 
 572 
 573   /* Basically the Latin version with type AF_CJKMetrics for metrics. */
 574 
 575   FT_LOCAL_DEF( void )
 576   af_cjk_metrics_check_digits( AF_CJKMetrics  metrics,
 577                                FT_Face        face )
 578   {
 579     FT_Bool   started = 0, same_width = 1;
 580     FT_Fixed  advance = 0, old_advance = 0;
 581 
 582     /* If HarfBuzz is not available, we need a pointer to a single */
 583     /* unsigned long value.                                        */
 584 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 585     void*     shaper_buf;
 586 #else
 587     FT_ULong  shaper_buf_;
 588     void*     shaper_buf = &shaper_buf_;
 589 #endif
 590 
 591     /* in all supported charmaps, digits have character codes 0x30-0x39 */
 592     const char   digits[] = "0 1 2 3 4 5 6 7 8 9";
 593     const char*  p;
 594 
 595 
 596     p = digits;
 597 
 598 #ifdef FT_CONFIG_OPTION_USE_HARFBUZZ
 599     shaper_buf = af_shaper_buf_create( face );
 600 #endif
 601 
 602     while ( *p )
 603     {
 604       FT_ULong      glyph_index;
 605       unsigned int  num_idx;
 606 
 607 
 608       /* reject input that maps to more than a single glyph */
 609       p = af_shaper_get_cluster( p, &metrics->root, shaper_buf, &num_idx );
 610       if ( num_idx > 1 )
 611         continue;
 612 
 613       glyph_index = af_shaper_get_elem( &metrics->root,
 614                                         shaper_buf,
 615                                         0,
 616                                         &advance,
 617                                         NULL );
 618       if ( !glyph_index )
 619         continue;
 620 
 621       if ( started )
 622       {
 623         if ( advance != old_advance )
 624         {
 625           same_width = 0;
 626           break;
 627         }
 628       }
 629       else
 630       {
 631         old_advance = advance;
 632         started     = 1;
 633       }
 634     }
 635 
 636     af_shaper_buf_destroy( face, shaper_buf );
 637 
 638     metrics->root.digits_have_same_width = same_width;
 639   }
 640 
 641 
 642   /* Initialize global metrics. */
 643 
 644   FT_LOCAL_DEF( FT_Error )
 645   af_cjk_metrics_init( AF_CJKMetrics  metrics,
 646                        FT_Face        face )
 647   {
 648     FT_CharMap  oldmap = face->charmap;
 649 
 650 
 651     metrics->units_per_em = face->units_per_EM;
 652 
 653     if ( !FT_Select_Charmap( face, FT_ENCODING_UNICODE ) )
 654     {
 655       af_cjk_metrics_init_widths( metrics, face );
 656       af_cjk_metrics_init_blues( metrics, face );
 657       af_cjk_metrics_check_digits( metrics, face );
 658     }
 659 
 660     FT_Set_Charmap( face, oldmap );
 661     return FT_Err_Ok;
 662   }
 663 
 664 
 665   /* Adjust scaling value, then scale and shift widths   */
 666   /* and blue zones (if applicable) for given dimension. */
 667 
 668   static void
 669   af_cjk_metrics_scale_dim( AF_CJKMetrics  metrics,
 670                             AF_Scaler      scaler,
 671                             AF_Dimension   dim )
 672   {
 673     FT_Fixed    scale;
 674     FT_Pos      delta;
 675     AF_CJKAxis  axis;
 676     FT_UInt     nn;
 677 
 678 
 679     if ( dim == AF_DIMENSION_HORZ )
 680     {
 681       scale = scaler->x_scale;
 682       delta = scaler->x_delta;
 683     }
 684     else
 685     {
 686       scale = scaler->y_scale;
 687       delta = scaler->y_delta;
 688     }
 689 
 690     axis = &metrics->axis[dim];
 691 
 692     if ( axis->org_scale == scale && axis->org_delta == delta )
 693       return;
 694 
 695     axis->org_scale = scale;
 696     axis->org_delta = delta;
 697 
 698     axis->scale = scale;
 699     axis->delta = delta;
 700 
 701     /* scale the blue zones */
 702     for ( nn = 0; nn < axis->blue_count; nn++ )
 703     {
 704       AF_CJKBlue  blue = &axis->blues[nn];
 705       FT_Pos      dist;
 706 
 707 
 708       blue->ref.cur   = FT_MulFix( blue->ref.org, scale ) + delta;
 709       blue->ref.fit   = blue->ref.cur;
 710       blue->shoot.cur = FT_MulFix( blue->shoot.org, scale ) + delta;
 711       blue->shoot.fit = blue->shoot.cur;
 712       blue->flags    &= ~AF_CJK_BLUE_ACTIVE;
 713 
 714       /* a blue zone is only active if it is less than 3/4 pixels tall */
 715       dist = FT_MulFix( blue->ref.org - blue->shoot.org, scale );
 716       if ( dist <= 48 && dist >= -48 )
 717       {
 718         FT_Pos  delta1, delta2;
 719 
 720 
 721         blue->ref.fit  = FT_PIX_ROUND( blue->ref.cur );
 722 
 723         /* shoot is under shoot for cjk */
 724         delta1 = FT_DivFix( blue->ref.fit, scale ) - blue->shoot.org;
 725         delta2 = delta1;
 726         if ( delta1 < 0 )
 727           delta2 = -delta2;
 728 
 729         delta2 = FT_MulFix( delta2, scale );
 730 
 731         FT_TRACE5(( "delta: %d", delta1 ));
 732         if ( delta2 < 32 )
 733           delta2 = 0;
 734 #if 0
 735         else if ( delta2 < 64 )
 736           delta2 = 32 + ( ( ( delta2 - 32 ) + 16 ) & ~31 );
 737 #endif
 738         else
 739           delta2 = FT_PIX_ROUND( delta2 );
 740         FT_TRACE5(( "/%d\n", delta2 ));
 741 
 742         if ( delta1 < 0 )
 743           delta2 = -delta2;
 744 
 745         blue->shoot.fit = blue->ref.fit - delta2;
 746 
 747         FT_TRACE5(( ">> active cjk blue zone %c%d[%ld/%ld]:\n"
 748                     "     ref:   cur=%.2f fit=%.2f\n"
 749                     "     shoot: cur=%.2f fit=%.2f\n",
 750                     ( dim == AF_DIMENSION_HORZ ) ? 'H' : 'V',
 751                     nn, blue->ref.org, blue->shoot.org,
 752                     blue->ref.cur / 64.0, blue->ref.fit / 64.0,
 753                     blue->shoot.cur / 64.0, blue->shoot.fit / 64.0 ));
 754 
 755         blue->flags |= AF_CJK_BLUE_ACTIVE;
 756       }
 757     }
 758   }
 759 
 760 
 761   /* Scale global values in both directions. */
 762 
 763   FT_LOCAL_DEF( void )
 764   af_cjk_metrics_scale( AF_CJKMetrics  metrics,
 765                         AF_Scaler      scaler )
 766   {
 767     /* we copy the whole structure since the x and y scaling values */
 768     /* are not modified, contrary to e.g. the `latin' auto-hinter   */
 769     metrics->root.scaler = *scaler;
 770 
 771     af_cjk_metrics_scale_dim( metrics, scaler, AF_DIMENSION_HORZ );
 772     af_cjk_metrics_scale_dim( metrics, scaler, AF_DIMENSION_VERT );
 773   }
 774 
 775 
 776   /* Extract standard_width from writing system/script specific */
 777   /* metrics class.                                             */
 778 
 779   FT_LOCAL_DEF( void )
 780   af_cjk_get_standard_widths( AF_CJKMetrics  metrics,
 781                               FT_Pos*        stdHW,
 782                               FT_Pos*        stdVW )
 783   {
 784     if ( stdHW )
 785       *stdHW = metrics->axis[AF_DIMENSION_VERT].standard_width;
 786 
 787     if ( stdVW )
 788       *stdVW = metrics->axis[AF_DIMENSION_HORZ].standard_width;
 789   }
 790 
 791 
 792   /*************************************************************************/
 793   /*************************************************************************/
 794   /*****                                                               *****/
 795   /*****              C J K   G L Y P H   A N A L Y S I S              *****/
 796   /*****                                                               *****/
 797   /*************************************************************************/
 798   /*************************************************************************/
 799 
 800 
 801   /* Walk over all contours and compute its segments. */
 802 
 803   static FT_Error
 804   af_cjk_hints_compute_segments( AF_GlyphHints  hints,
 805                                  AF_Dimension   dim )
 806   {
 807     AF_AxisHints  axis          = &hints->axis[dim];
 808     AF_Segment    segments      = axis->segments;
 809     AF_Segment    segment_limit = segments + axis->num_segments;
 810     FT_Error      error;
 811     AF_Segment    seg;
 812 
 813 
 814     error = af_latin_hints_compute_segments( hints, dim );
 815     if ( error )
 816       return error;
 817 
 818     /* a segment is round if it doesn't have successive */
 819     /* on-curve points.                                 */
 820     for ( seg = segments; seg < segment_limit; seg++ )
 821     {
 822       AF_Point  pt   = seg->first;
 823       AF_Point  last = seg->last;
 824       FT_UInt   f0   = pt->flags & AF_FLAG_CONTROL;
 825       FT_UInt   f1;
 826 
 827 
 828       seg->flags &= ~AF_EDGE_ROUND;
 829 
 830       for ( ; pt != last; f0 = f1 )
 831       {
 832         pt = pt->next;
 833         f1 = pt->flags & AF_FLAG_CONTROL;
 834 
 835         if ( !f0 && !f1 )
 836           break;
 837 
 838         if ( pt == last )
 839           seg->flags |= AF_EDGE_ROUND;
 840       }
 841     }
 842 
 843     return FT_Err_Ok;
 844   }
 845 
 846 
 847   static void
 848   af_cjk_hints_link_segments( AF_GlyphHints  hints,
 849                               AF_Dimension   dim )
 850   {
 851     AF_AxisHints  axis          = &hints->axis[dim];
 852     AF_Segment    segments      = axis->segments;
 853     AF_Segment    segment_limit = segments + axis->num_segments;
 854     AF_Direction  major_dir     = axis->major_dir;
 855     AF_Segment    seg1, seg2;
 856     FT_Pos        len_threshold;
 857     FT_Pos        dist_threshold;
 858 
 859 
 860     len_threshold = AF_LATIN_CONSTANT( hints->metrics, 8 );
 861 
 862     dist_threshold = ( dim == AF_DIMENSION_HORZ ) ? hints->x_scale
 863                                                   : hints->y_scale;
 864     dist_threshold = FT_DivFix( 64 * 3, dist_threshold );
 865 
 866     /* now compare each segment to the others */
 867     for ( seg1 = segments; seg1 < segment_limit; seg1++ )
 868     {
 869       if ( seg1->dir != major_dir )
 870         continue;
 871 
 872       for ( seg2 = segments; seg2 < segment_limit; seg2++ )
 873         if ( seg2 != seg1 && seg1->dir + seg2->dir == 0 )
 874         {
 875           FT_Pos  dist = seg2->pos - seg1->pos;
 876 
 877 
 878           if ( dist < 0 )
 879             continue;
 880 
 881           {
 882             FT_Pos  min = seg1->min_coord;
 883             FT_Pos  max = seg1->max_coord;
 884             FT_Pos  len;
 885 
 886 
 887             if ( min < seg2->min_coord )
 888               min = seg2->min_coord;
 889 
 890             if ( max > seg2->max_coord )
 891               max = seg2->max_coord;
 892 
 893             len = max - min;
 894             if ( len >= len_threshold )
 895             {
 896               if ( dist * 8 < seg1->score * 9                        &&
 897                    ( dist * 8 < seg1->score * 7 || seg1->len < len ) )
 898               {
 899                 seg1->score = dist;
 900                 seg1->len   = len;
 901                 seg1->link  = seg2;
 902               }
 903 
 904               if ( dist * 8 < seg2->score * 9                        &&
 905                    ( dist * 8 < seg2->score * 7 || seg2->len < len ) )
 906               {
 907                 seg2->score = dist;
 908                 seg2->len   = len;
 909                 seg2->link  = seg1;
 910               }
 911             }
 912           }
 913         }
 914     }
 915 
 916     /*
 917      * now compute the `serif' segments
 918      *
 919      * In Hanzi, some strokes are wider on one or both of the ends.
 920      * We either identify the stems on the ends as serifs or remove
 921      * the linkage, depending on the length of the stems.
 922      *
 923      */
 924 
 925     {
 926       AF_Segment  link1, link2;
 927 
 928 
 929       for ( seg1 = segments; seg1 < segment_limit; seg1++ )
 930       {
 931         link1 = seg1->link;
 932         if ( !link1 || link1->link != seg1 || link1->pos <= seg1->pos )
 933           continue;
 934 
 935         if ( seg1->score >= dist_threshold )
 936           continue;
 937 
 938         for ( seg2 = segments; seg2 < segment_limit; seg2++ )
 939         {
 940           if ( seg2->pos > seg1->pos || seg1 == seg2 )
 941             continue;
 942 
 943           link2 = seg2->link;
 944           if ( !link2 || link2->link != seg2 || link2->pos < link1->pos )
 945             continue;
 946 
 947           if ( seg1->pos == seg2->pos && link1->pos == link2->pos )
 948             continue;
 949 
 950           if ( seg2->score <= seg1->score || seg1->score * 4 <= seg2->score )
 951             continue;
 952 
 953           /* seg2 < seg1 < link1 < link2 */
 954 
 955           if ( seg1->len >= seg2->len * 3 )
 956           {
 957             AF_Segment  seg;
 958 
 959 
 960             for ( seg = segments; seg < segment_limit; seg++ )
 961             {
 962               AF_Segment  link = seg->link;
 963 
 964 
 965               if ( link == seg2 )
 966               {
 967                 seg->link  = NULL;
 968                 seg->serif = link1;
 969               }
 970               else if ( link == link2 )
 971               {
 972                 seg->link  = NULL;
 973                 seg->serif = seg1;
 974               }
 975             }
 976           }
 977           else
 978           {
 979             seg1->link = link1->link = NULL;
 980 
 981             break;
 982           }
 983         }
 984       }
 985     }
 986 
 987     for ( seg1 = segments; seg1 < segment_limit; seg1++ )
 988     {
 989       seg2 = seg1->link;
 990 
 991       if ( seg2 )
 992       {
 993         if ( seg2->link != seg1 )
 994         {
 995           seg1->link = NULL;
 996 
 997           if ( seg2->score < dist_threshold || seg1->score < seg2->score * 4 )
 998             seg1->serif = seg2->link;
 999         }
1000       }
1001     }
1002   }
1003 
1004 
1005   static FT_Error
1006   af_cjk_hints_compute_edges( AF_GlyphHints  hints,
1007                               AF_Dimension   dim )
1008   {
1009     AF_AxisHints  axis   = &hints->axis[dim];
1010     FT_Error      error  = FT_Err_Ok;
1011     FT_Memory     memory = hints->memory;
1012     AF_CJKAxis    laxis  = &((AF_CJKMetrics)hints->metrics)->axis[dim];
1013 
1014     AF_Segment    segments      = axis->segments;
1015     AF_Segment    segment_limit = segments + axis->num_segments;
1016     AF_Segment    seg;
1017 
1018     FT_Fixed      scale;
1019     FT_Pos        edge_distance_threshold;
1020 
1021 
1022     axis->num_edges = 0;
1023 
1024     scale = ( dim == AF_DIMENSION_HORZ ) ? hints->x_scale
1025                                          : hints->y_scale;
1026 
1027     /**********************************************************************
1028      *
1029      * We begin by generating a sorted table of edges for the current
1030      * direction.  To do so, we simply scan each segment and try to find
1031      * an edge in our table that corresponds to its position.
1032      *
1033      * If no edge is found, we create and insert a new edge in the
1034      * sorted table.  Otherwise, we simply add the segment to the edge's
1035      * list which is then processed in the second step to compute the
1036      * edge's properties.
1037      *
1038      * Note that the edges table is sorted along the segment/edge
1039      * position.
1040      *
1041      */
1042 
1043     edge_distance_threshold = FT_MulFix( laxis->edge_distance_threshold,
1044                                          scale );
1045     if ( edge_distance_threshold > 64 / 4 )
1046       edge_distance_threshold = FT_DivFix( 64 / 4, scale );
1047     else
1048       edge_distance_threshold = laxis->edge_distance_threshold;
1049 
1050     for ( seg = segments; seg < segment_limit; seg++ )
1051     {
1052       AF_Edge  found = NULL;
1053       FT_Pos   best  = 0xFFFFU;
1054       FT_Int   ee;
1055 
1056 
1057       /* look for an edge corresponding to the segment */
1058       for ( ee = 0; ee < axis->num_edges; ee++ )
1059       {
1060         AF_Edge  edge = axis->edges + ee;
1061         FT_Pos   dist;
1062 
1063 
1064         if ( edge->dir != seg->dir )
1065           continue;
1066 
1067         dist = seg->pos - edge->fpos;
1068         if ( dist < 0 )
1069           dist = -dist;
1070 
1071         if ( dist < edge_distance_threshold && dist < best )
1072         {
1073           AF_Segment  link = seg->link;
1074 
1075 
1076           /* check whether all linked segments of the candidate edge */
1077           /* can make a single edge.                                 */
1078           if ( link )
1079           {
1080             AF_Segment  seg1  = edge->first;
1081             FT_Pos      dist2 = 0;
1082 
1083 
1084             do
1085             {
1086               AF_Segment  link1 = seg1->link;
1087 
1088 
1089               if ( link1 )
1090               {
1091                 dist2 = AF_SEGMENT_DIST( link, link1 );
1092                 if ( dist2 >= edge_distance_threshold )
1093                   break;
1094               }
1095 
1096             } while ( ( seg1 = seg1->edge_next ) != edge->first );
1097 
1098             if ( dist2 >= edge_distance_threshold )
1099               continue;
1100           }
1101 
1102           best  = dist;
1103           found = edge;
1104         }
1105       }
1106 
1107       if ( !found )
1108       {
1109         AF_Edge  edge;
1110 
1111 
1112         /* insert a new edge in the list and */
1113         /* sort according to the position    */
1114         error = af_axis_hints_new_edge( axis, seg->pos,
1115                                         (AF_Direction)seg->dir, 0,
1116                                         memory, &edge );
1117         if ( error )
1118           goto Exit;
1119 
1120         /* add the segment to the new edge's list */
1121         FT_ZERO( edge );
1122 
1123         edge->first    = seg;
1124         edge->last     = seg;
1125         edge->dir      = seg->dir;
1126         edge->fpos     = seg->pos;
1127         edge->opos     = FT_MulFix( seg->pos, scale );
1128         edge->pos      = edge->opos;
1129         seg->edge_next = seg;
1130       }
1131       else
1132       {
1133         /* if an edge was found, simply add the segment to the edge's */
1134         /* list                                                       */
1135         seg->edge_next         = found->first;
1136         found->last->edge_next = seg;
1137         found->last            = seg;
1138       }
1139     }
1140 
1141     /*******************************************************************
1142      *
1143      * Good, we now compute each edge's properties according to the
1144      * segments found on its position.  Basically, these are
1145      *
1146      * - the edge's main direction
1147      * - stem edge, serif edge or both (which defaults to stem then)
1148      * - rounded edge, straight or both (which defaults to straight)
1149      * - link for edge
1150      *
1151      */
1152 
1153     /* first of all, set the `edge' field in each segment -- this is */
1154     /* required in order to compute edge links                       */
1155 
1156     /*
1157      * Note that removing this loop and setting the `edge' field of each
1158      * segment directly in the code above slows down execution speed for
1159      * some reasons on platforms like the Sun.
1160      */
1161     {
1162       AF_Edge  edges      = axis->edges;
1163       AF_Edge  edge_limit = edges + axis->num_edges;
1164       AF_Edge  edge;
1165 
1166 
1167       for ( edge = edges; edge < edge_limit; edge++ )
1168       {
1169         seg = edge->first;
1170         if ( seg )
1171           do
1172           {
1173             seg->edge = edge;
1174             seg       = seg->edge_next;
1175 
1176           } while ( seg != edge->first );
1177       }
1178 
1179       /* now compute each edge properties */
1180       for ( edge = edges; edge < edge_limit; edge++ )
1181       {
1182         FT_Int  is_round    = 0;  /* does it contain round segments?    */
1183         FT_Int  is_straight = 0;  /* does it contain straight segments? */
1184 
1185 
1186         seg = edge->first;
1187         if ( !seg )
1188           goto Skip_Loop;
1189 
1190         do
1191         {
1192           FT_Bool  is_serif;
1193 
1194 
1195           /* check for roundness of segment */
1196           if ( seg->flags & AF_EDGE_ROUND )
1197             is_round++;
1198           else
1199             is_straight++;
1200 
1201           /* check for links -- if seg->serif is set, then seg->link must */
1202           /* be ignored                                                   */
1203           is_serif = FT_BOOL( seg->serif && seg->serif->edge != edge );
1204 
1205           if ( seg->link || is_serif )
1206           {
1207             AF_Edge     edge2;
1208             AF_Segment  seg2;
1209 
1210 
1211             edge2 = edge->link;
1212             seg2  = seg->link;
1213 
1214             if ( is_serif )
1215             {
1216               seg2  = seg->serif;
1217               edge2 = edge->serif;
1218             }
1219 
1220             if ( edge2 )
1221             {
1222               FT_Pos  edge_delta;
1223               FT_Pos  seg_delta;
1224 
1225 
1226               edge_delta = edge->fpos - edge2->fpos;
1227               if ( edge_delta < 0 )
1228                 edge_delta = -edge_delta;
1229 
1230               seg_delta = AF_SEGMENT_DIST( seg, seg2 );
1231 
1232               if ( seg_delta < edge_delta )
1233                 edge2 = seg2->edge;
1234             }
1235             else
1236               edge2 = seg2->edge;
1237 
1238             if ( is_serif )
1239             {
1240               edge->serif   = edge2;
1241               edge2->flags |= AF_EDGE_SERIF;
1242             }
1243             else
1244               edge->link = edge2;
1245           }
1246 
1247           seg = seg->edge_next;
1248 
1249         } while ( seg != edge->first );
1250 
1251       Skip_Loop:
1252         /* set the round/straight flags */
1253         edge->flags = AF_EDGE_NORMAL;
1254 
1255         if ( is_round > 0 && is_round >= is_straight )
1256           edge->flags |= AF_EDGE_ROUND;
1257 
1258         /* get rid of serifs if link is set                 */
1259         /* XXX: This gets rid of many unpleasant artefacts! */
1260         /*      Example: the `c' in cour.pfa at size 13     */
1261 
1262         if ( edge->serif && edge->link )
1263           edge->serif = NULL;
1264       }
1265     }
1266 
1267   Exit:
1268     return error;
1269   }
1270 
1271 
1272   /* Detect segments and edges for given dimension. */
1273 
1274   static FT_Error
1275   af_cjk_hints_detect_features( AF_GlyphHints  hints,
1276                                 AF_Dimension   dim )
1277   {
1278     FT_Error  error;
1279 
1280 
1281     error = af_cjk_hints_compute_segments( hints, dim );
1282     if ( !error )
1283     {
1284       af_cjk_hints_link_segments( hints, dim );
1285 
1286       error = af_cjk_hints_compute_edges( hints, dim );
1287     }
1288     return error;
1289   }
1290 
1291 
1292   /* Compute all edges which lie within blue zones. */
1293 
1294   static void
1295   af_cjk_hints_compute_blue_edges( AF_GlyphHints  hints,
1296                                    AF_CJKMetrics  metrics,
1297                                    AF_Dimension   dim )
1298   {
1299     AF_AxisHints  axis       = &hints->axis[dim];
1300     AF_Edge       edge       = axis->edges;
1301     AF_Edge       edge_limit = edge + axis->num_edges;
1302     AF_CJKAxis    cjk        = &metrics->axis[dim];
1303     FT_Fixed      scale      = cjk->scale;
1304     FT_Pos        best_dist0;  /* initial threshold */
1305 
1306 
1307     /* compute the initial threshold as a fraction of the EM size */
1308     best_dist0 = FT_MulFix( metrics->units_per_em / 40, scale );
1309 
1310     if ( best_dist0 > 64 / 2 ) /* maximum 1/2 pixel */
1311       best_dist0 = 64 / 2;
1312 
1313     /* compute which blue zones are active, i.e. have their scaled */
1314     /* size < 3/4 pixels                                           */
1315 
1316     /* If the distant between an edge and a blue zone is shorter than */
1317     /* best_dist0, set the blue zone for the edge.  Then search for   */
1318     /* the blue zone with the smallest best_dist to the edge.         */
1319 
1320     for ( ; edge < edge_limit; edge++ )
1321     {
1322       FT_UInt   bb;
1323       AF_Width  best_blue = NULL;
1324       FT_Pos    best_dist = best_dist0;
1325 
1326 
1327       for ( bb = 0; bb < cjk->blue_count; bb++ )
1328       {
1329         AF_CJKBlue  blue = cjk->blues + bb;
1330         FT_Bool     is_top_right_blue, is_major_dir;
1331 
1332 
1333         /* skip inactive blue zones (i.e., those that are too small) */
1334         if ( !( blue->flags & AF_CJK_BLUE_ACTIVE ) )
1335           continue;
1336 
1337         /* if it is a top zone, check for right edges -- if it is a bottom */
1338         /* zone, check for left edges                                      */
1339         /*                                                                 */
1340         /* of course, that's for TrueType                                  */
1341         is_top_right_blue =
1342           (FT_Byte)( ( blue->flags & AF_CJK_BLUE_TOP ) != 0 );
1343         is_major_dir =
1344           FT_BOOL( edge->dir == axis->major_dir );
1345 
1346         /* if it is a top zone, the edge must be against the major    */
1347         /* direction; if it is a bottom zone, it must be in the major */
1348         /* direction                                                  */
1349         if ( is_top_right_blue ^ is_major_dir )
1350         {
1351           FT_Pos    dist;
1352           AF_Width  compare;
1353 
1354 
1355           /* Compare the edge to the closest blue zone type */
1356           if ( FT_ABS( edge->fpos - blue->ref.org ) >
1357                FT_ABS( edge->fpos - blue->shoot.org ) )
1358             compare = &blue->shoot;
1359           else
1360             compare = &blue->ref;
1361 
1362           dist = edge->fpos - compare->org;
1363           if ( dist < 0 )
1364             dist = -dist;
1365 
1366           dist = FT_MulFix( dist, scale );
1367           if ( dist < best_dist )
1368           {
1369             best_dist = dist;
1370             best_blue = compare;
1371           }
1372         }
1373       }
1374 
1375       if ( best_blue )
1376         edge->blue_edge = best_blue;
1377     }
1378   }
1379 
1380 
1381   /* Initalize hinting engine. */
1382 
1383   FT_LOCAL_DEF( FT_Error )
1384   af_cjk_hints_init( AF_GlyphHints  hints,
1385                      AF_CJKMetrics  metrics )
1386   {
1387     FT_Render_Mode  mode;
1388     FT_UInt32       scaler_flags, other_flags;
1389 
1390 
1391     af_glyph_hints_rescale( hints, (AF_StyleMetrics)metrics );
1392 
1393     /*
1394      * correct x_scale and y_scale when needed, since they may have
1395      * been modified af_cjk_scale_dim above
1396      */
1397     hints->x_scale = metrics->axis[AF_DIMENSION_HORZ].scale;
1398     hints->x_delta = metrics->axis[AF_DIMENSION_HORZ].delta;
1399     hints->y_scale = metrics->axis[AF_DIMENSION_VERT].scale;
1400     hints->y_delta = metrics->axis[AF_DIMENSION_VERT].delta;
1401 
1402     /* compute flags depending on render mode, etc. */
1403     mode = metrics->root.scaler.render_mode;
1404 
1405 #if 0 /* AF_CONFIG_OPTION_USE_WARPER */
1406     if ( mode == FT_RENDER_MODE_LCD || mode == FT_RENDER_MODE_LCD_V )
1407       metrics->root.scaler.render_mode = mode = FT_RENDER_MODE_NORMAL;
1408 #endif
1409 
1410     scaler_flags = hints->scaler_flags;
1411     other_flags  = 0;
1412 
1413     /*
1414      * We snap the width of vertical stems for the monochrome and
1415      * horizontal LCD rendering targets only.
1416      */
1417     if ( mode == FT_RENDER_MODE_MONO || mode == FT_RENDER_MODE_LCD )
1418       other_flags |= AF_LATIN_HINTS_HORZ_SNAP;
1419 
1420     /*
1421      * We snap the width of horizontal stems for the monochrome and
1422      * vertical LCD rendering targets only.
1423      */
1424     if ( mode == FT_RENDER_MODE_MONO || mode == FT_RENDER_MODE_LCD_V )
1425       other_flags |= AF_LATIN_HINTS_VERT_SNAP;
1426 
1427     /*
1428      * We adjust stems to full pixels unless in `light' or `lcd' mode.
1429      */
1430     if ( mode != FT_RENDER_MODE_LIGHT && mode != FT_RENDER_MODE_LCD )
1431       other_flags |= AF_LATIN_HINTS_STEM_ADJUST;
1432 
1433     if ( mode == FT_RENDER_MODE_MONO )
1434       other_flags |= AF_LATIN_HINTS_MONO;
1435 
1436     scaler_flags |= AF_SCALER_FLAG_NO_ADVANCE;
1437 
1438 #ifdef AF_CONFIG_OPTION_USE_WARPER
1439     /* get (global) warper flag */
1440     if ( !metrics->root.globals->module->warping )
1441       scaler_flags |= AF_SCALER_FLAG_NO_WARPER;
1442 #endif
1443 
1444     hints->scaler_flags = scaler_flags;
1445     hints->other_flags  = other_flags;
1446 
1447     return FT_Err_Ok;
1448   }
1449 
1450 
1451   /*************************************************************************/
1452   /*************************************************************************/
1453   /*****                                                               *****/
1454   /*****          C J K   G L Y P H   G R I D - F I T T I N G          *****/
1455   /*****                                                               *****/
1456   /*************************************************************************/
1457   /*************************************************************************/
1458 
1459   /* Snap a given width in scaled coordinates to one of the */
1460   /* current standard widths.                               */
1461 
1462   static FT_Pos
1463   af_cjk_snap_width( AF_Width  widths,
1464                      FT_UInt   count,
1465                      FT_Pos    width )
1466   {
1467     FT_UInt  n;
1468     FT_Pos   best      = 64 + 32 + 2;
1469     FT_Pos   reference = width;
1470     FT_Pos   scaled;
1471 
1472 
1473     for ( n = 0; n < count; n++ )
1474     {
1475       FT_Pos  w;
1476       FT_Pos  dist;
1477 
1478 
1479       w = widths[n].cur;
1480       dist = width - w;
1481       if ( dist < 0 )
1482         dist = -dist;
1483       if ( dist < best )
1484       {
1485         best      = dist;
1486         reference = w;
1487       }
1488     }
1489 
1490     scaled = FT_PIX_ROUND( reference );
1491 
1492     if ( width >= reference )
1493     {
1494       if ( width < scaled + 48 )
1495         width = reference;
1496     }
1497     else
1498     {
1499       if ( width > scaled - 48 )
1500         width = reference;
1501     }
1502 
1503     return width;
1504   }
1505 
1506 
1507   /* Compute the snapped width of a given stem.                          */
1508   /* There is a lot of voodoo in this function; changing the hard-coded  */
1509   /* parameters influence the whole hinting process.                     */
1510 
1511   static FT_Pos
1512   af_cjk_compute_stem_width( AF_GlyphHints  hints,
1513                              AF_Dimension   dim,
1514                              FT_Pos         width,
1515                              FT_UInt        base_flags,
1516                              FT_UInt        stem_flags )
1517   {
1518     AF_CJKMetrics  metrics  = (AF_CJKMetrics)hints->metrics;
1519     AF_CJKAxis     axis     = &metrics->axis[dim];
1520     FT_Pos         dist     = width;
1521     FT_Int         sign     = 0;
1522     FT_Bool        vertical = FT_BOOL( dim == AF_DIMENSION_VERT );
1523 
1524     FT_UNUSED( base_flags );
1525     FT_UNUSED( stem_flags );
1526 
1527 
1528     if ( !AF_LATIN_HINTS_DO_STEM_ADJUST( hints ) )
1529       return width;
1530 
1531     if ( dist < 0 )
1532     {
1533       dist = -width;
1534       sign = 1;
1535     }
1536 
1537     if ( (  vertical && !AF_LATIN_HINTS_DO_VERT_SNAP( hints ) ) ||
1538          ( !vertical && !AF_LATIN_HINTS_DO_HORZ_SNAP( hints ) ) )
1539     {
1540       /* smooth hinting process: very lightly quantize the stem width */
1541 
1542       if ( axis->width_count > 0 )
1543       {
1544         if ( FT_ABS( dist - axis->widths[0].cur ) < 40 )
1545         {
1546           dist = axis->widths[0].cur;
1547           if ( dist < 48 )
1548             dist = 48;
1549 
1550           goto Done_Width;
1551         }
1552       }
1553 
1554       if ( dist < 54 )
1555         dist += ( 54 - dist ) / 2;
1556       else if ( dist < 3 * 64 )
1557       {
1558         FT_Pos  delta;
1559 
1560 
1561         delta  = dist & 63;
1562         dist  &= -64;
1563 
1564         if ( delta < 10 )
1565           dist += delta;
1566         else if ( delta < 22 )
1567           dist += 10;
1568         else if ( delta < 42 )
1569           dist += delta;
1570         else if ( delta < 54 )
1571           dist += 54;
1572         else
1573           dist += delta;
1574       }
1575     }
1576     else
1577     {
1578       /* strong hinting process: snap the stem width to integer pixels */
1579 
1580       dist = af_cjk_snap_width( axis->widths, axis->width_count, dist );
1581 
1582       if ( vertical )
1583       {
1584         /* in the case of vertical hinting, always round */
1585         /* the stem heights to integer pixels            */
1586 
1587         if ( dist >= 64 )
1588           dist = ( dist + 16 ) & ~63;
1589         else
1590           dist = 64;
1591       }
1592       else
1593       {
1594         if ( AF_LATIN_HINTS_DO_MONO( hints ) )
1595         {
1596           /* monochrome horizontal hinting: snap widths to integer pixels */
1597           /* with a different threshold                                   */
1598 
1599           if ( dist < 64 )
1600             dist = 64;
1601           else
1602             dist = ( dist + 32 ) & ~63;
1603         }
1604         else
1605         {
1606           /* for horizontal anti-aliased hinting, we adopt a more subtle */
1607           /* approach: we strengthen small stems, round stems whose size */
1608           /* is between 1 and 2 pixels to an integer, otherwise nothing  */
1609 
1610           if ( dist < 48 )
1611             dist = ( dist + 64 ) >> 1;
1612 
1613           else if ( dist < 128 )
1614             dist = ( dist + 22 ) & ~63;
1615           else
1616             /* round otherwise to prevent color fringes in LCD mode */
1617             dist = ( dist + 32 ) & ~63;
1618         }
1619       }
1620     }
1621 
1622   Done_Width:
1623     if ( sign )
1624       dist = -dist;
1625 
1626     return dist;
1627   }
1628 
1629 
1630   /* Align one stem edge relative to the previous stem edge. */
1631 
1632   static void
1633   af_cjk_align_linked_edge( AF_GlyphHints  hints,
1634                             AF_Dimension   dim,
1635                             AF_Edge        base_edge,
1636                             AF_Edge        stem_edge )
1637   {
1638     FT_Pos  dist = stem_edge->opos - base_edge->opos;
1639 
1640     FT_Pos  fitted_width = af_cjk_compute_stem_width( hints, dim, dist,
1641                                                       base_edge->flags,
1642                                                       stem_edge->flags );
1643 
1644 
1645     stem_edge->pos = base_edge->pos + fitted_width;
1646 
1647     FT_TRACE5(( "  CJKLINK: edge %d @%d (opos=%.2f) linked to %.2f,"
1648                 " dist was %.2f, now %.2f\n",
1649                 stem_edge - hints->axis[dim].edges, stem_edge->fpos,
1650                 stem_edge->opos / 64.0, stem_edge->pos / 64.0,
1651                 dist / 64.0, fitted_width / 64.0 ));
1652   }
1653 
1654 
1655   /* Shift the coordinates of the `serif' edge by the same amount */
1656   /* as the corresponding `base' edge has been moved already.     */
1657 
1658   static void
1659   af_cjk_align_serif_edge( AF_GlyphHints  hints,
1660                            AF_Edge        base,
1661                            AF_Edge        serif )
1662   {
1663     FT_UNUSED( hints );
1664 
1665     serif->pos = base->pos + ( serif->opos - base->opos );
1666   }
1667 
1668 
1669   /*************************************************************************/
1670   /*************************************************************************/
1671   /*************************************************************************/
1672   /****                                                                 ****/
1673   /****                    E D G E   H I N T I N G                      ****/
1674   /****                                                                 ****/
1675   /*************************************************************************/
1676   /*************************************************************************/
1677   /*************************************************************************/
1678 
1679 
1680 #define AF_LIGHT_MODE_MAX_HORZ_GAP    9
1681 #define AF_LIGHT_MODE_MAX_VERT_GAP   15
1682 #define AF_LIGHT_MODE_MAX_DELTA_ABS  14
1683 
1684 
1685   static FT_Pos
1686   af_hint_normal_stem( AF_GlyphHints  hints,
1687                        AF_Edge        edge,
1688                        AF_Edge        edge2,
1689                        FT_Pos         anchor,
1690                        AF_Dimension   dim )
1691   {
1692     FT_Pos  org_len, cur_len, org_center;
1693     FT_Pos  cur_pos1, cur_pos2;
1694     FT_Pos  d_off1, u_off1, d_off2, u_off2, delta;
1695     FT_Pos  offset;
1696     FT_Pos  threshold = 64;
1697 
1698 
1699     if ( !AF_LATIN_HINTS_DO_STEM_ADJUST( hints ) )
1700     {
1701       if ( ( edge->flags  & AF_EDGE_ROUND ) &&
1702            ( edge2->flags & AF_EDGE_ROUND ) )
1703       {
1704         if ( dim == AF_DIMENSION_VERT )
1705           threshold = 64 - AF_LIGHT_MODE_MAX_HORZ_GAP;
1706         else
1707           threshold = 64 - AF_LIGHT_MODE_MAX_VERT_GAP;
1708       }
1709       else
1710       {
1711         if ( dim == AF_DIMENSION_VERT )
1712           threshold = 64 - AF_LIGHT_MODE_MAX_HORZ_GAP / 3;
1713         else
1714           threshold = 64 - AF_LIGHT_MODE_MAX_VERT_GAP / 3;
1715       }
1716     }
1717 
1718     org_len    = edge2->opos - edge->opos;
1719     cur_len    = af_cjk_compute_stem_width( hints, dim, org_len,
1720                                             edge->flags,
1721                                             edge2->flags );
1722 
1723     org_center = ( edge->opos + edge2->opos ) / 2 + anchor;
1724     cur_pos1   = org_center - cur_len / 2;
1725     cur_pos2   = cur_pos1 + cur_len;
1726     d_off1     = cur_pos1 - FT_PIX_FLOOR( cur_pos1 );
1727     d_off2     = cur_pos2 - FT_PIX_FLOOR( cur_pos2 );
1728     u_off1     = 64 - d_off1;
1729     u_off2     = 64 - d_off2;
1730     delta      = 0;
1731 
1732 
1733     if ( d_off1 == 0 || d_off2 == 0 )
1734       goto Exit;
1735 
1736     if ( cur_len <= threshold )
1737     {
1738       if ( d_off2 < cur_len )
1739       {
1740         if ( u_off1 <= d_off2 )
1741           delta =  u_off1;
1742         else
1743           delta = -d_off2;
1744       }
1745 
1746       goto Exit;
1747     }
1748 
1749     if ( threshold < 64 )
1750     {
1751       if ( d_off1 >= threshold || u_off1 >= threshold ||
1752            d_off2 >= threshold || u_off2 >= threshold )
1753         goto Exit;
1754     }
1755 
1756     offset = cur_len & 63;
1757 
1758     if ( offset < 32 )
1759     {
1760       if ( u_off1 <= offset || d_off2 <= offset )
1761         goto Exit;
1762     }
1763     else
1764       offset = 64 - threshold;
1765 
1766     d_off1 = threshold - u_off1;
1767     u_off1 = u_off1    - offset;
1768     u_off2 = threshold - d_off2;
1769     d_off2 = d_off2    - offset;
1770 
1771     if ( d_off1 <= u_off1 )
1772       u_off1 = -d_off1;
1773 
1774     if ( d_off2 <= u_off2 )
1775       u_off2 = -d_off2;
1776 
1777     if ( FT_ABS( u_off1 ) <= FT_ABS( u_off2 ) )
1778       delta = u_off1;
1779     else
1780       delta = u_off2;
1781 
1782   Exit:
1783 
1784 #if 1
1785     if ( !AF_LATIN_HINTS_DO_STEM_ADJUST( hints ) )
1786     {
1787       if ( delta > AF_LIGHT_MODE_MAX_DELTA_ABS )
1788         delta = AF_LIGHT_MODE_MAX_DELTA_ABS;
1789       else if ( delta < -AF_LIGHT_MODE_MAX_DELTA_ABS )
1790         delta = -AF_LIGHT_MODE_MAX_DELTA_ABS;
1791     }
1792 #endif
1793 
1794     cur_pos1 += delta;
1795 
1796     if ( edge->opos < edge2->opos )
1797     {
1798       edge->pos  = cur_pos1;
1799       edge2->pos = cur_pos1 + cur_len;
1800     }
1801     else
1802     {
1803       edge->pos  = cur_pos1 + cur_len;
1804       edge2->pos = cur_pos1;
1805     }
1806 
1807     return delta;
1808   }
1809 
1810 
1811   /* The main grid-fitting routine. */
1812 
1813   static void
1814   af_cjk_hint_edges( AF_GlyphHints  hints,
1815                      AF_Dimension   dim )
1816   {
1817     AF_AxisHints  axis       = &hints->axis[dim];
1818     AF_Edge       edges      = axis->edges;
1819     AF_Edge       edge_limit = edges + axis->num_edges;
1820     FT_PtrDist    n_edges;
1821     AF_Edge       edge;
1822     AF_Edge       anchor   = NULL;
1823     FT_Pos        delta    = 0;
1824     FT_Int        skipped  = 0;
1825     FT_Bool       has_last_stem = FALSE;
1826     FT_Pos        last_stem_pos = 0;
1827 
1828 #ifdef FT_DEBUG_LEVEL_TRACE
1829     FT_UInt       num_actions = 0;
1830 #endif
1831 
1832 
1833     FT_TRACE5(( "cjk %s edge hinting (style `%s')\n",
1834                 dim == AF_DIMENSION_VERT ? "horizontal" : "vertical",
1835                 af_style_names[hints->metrics->style_class->style] ));
1836 
1837     /* we begin by aligning all stems relative to the blue zone */
1838 
1839     if ( AF_HINTS_DO_BLUES( hints ) )
1840     {
1841       for ( edge = edges; edge < edge_limit; edge++ )
1842       {
1843         AF_Width  blue;
1844         AF_Edge   edge1, edge2;
1845 
1846 
1847         if ( edge->flags & AF_EDGE_DONE )
1848           continue;
1849 
1850         blue  = edge->blue_edge;
1851         edge1 = NULL;
1852         edge2 = edge->link;
1853 
1854         if ( blue )
1855         {
1856           edge1 = edge;
1857         }
1858         else if ( edge2 && edge2->blue_edge )
1859         {
1860           blue  = edge2->blue_edge;
1861           edge1 = edge2;
1862           edge2 = edge;
1863         }
1864 
1865         if ( !edge1 )
1866           continue;
1867 
1868 #ifdef FT_DEBUG_LEVEL_TRACE
1869         FT_TRACE5(( "  CJKBLUE: edge %d @%d (opos=%.2f) snapped to %.2f,"
1870                     " was %.2f\n",
1871                     edge1 - edges, edge1->fpos, edge1->opos / 64.0,
1872                     blue->fit / 64.0, edge1->pos / 64.0 ));
1873 
1874         num_actions++;
1875 #endif
1876 
1877         edge1->pos    = blue->fit;
1878         edge1->flags |= AF_EDGE_DONE;
1879 
1880         if ( edge2 && !edge2->blue_edge )
1881         {
1882           af_cjk_align_linked_edge( hints, dim, edge1, edge2 );
1883           edge2->flags |= AF_EDGE_DONE;
1884 
1885 #ifdef FT_DEBUG_LEVEL_TRACE
1886           num_actions++;
1887 #endif
1888         }
1889 
1890         if ( !anchor )
1891           anchor = edge;
1892       }
1893     }
1894 
1895     /* now we align all stem edges. */
1896     for ( edge = edges; edge < edge_limit; edge++ )
1897     {
1898       AF_Edge  edge2;
1899 
1900 
1901       if ( edge->flags & AF_EDGE_DONE )
1902         continue;
1903 
1904       /* skip all non-stem edges */
1905       edge2 = edge->link;
1906       if ( !edge2 )
1907       {
1908         skipped++;
1909         continue;
1910       }
1911 
1912       /* Some CJK characters have so many stems that
1913        * the hinter is likely to merge two adjacent ones.
1914        * To solve this problem, if either edge of a stem
1915        * is too close to the previous one, we avoid
1916        * aligning the two edges, but rather interpolate
1917        * their locations at the end of this function in
1918        * order to preserve the space between the stems.
1919        */
1920       if ( has_last_stem                       &&
1921            ( edge->pos  < last_stem_pos + 64 ||
1922              edge2->pos < last_stem_pos + 64 ) )
1923       {
1924         skipped++;
1925         continue;
1926       }
1927 
1928       /* now align the stem */
1929 
1930       /* this should not happen, but it's better to be safe */
1931       if ( edge2->blue_edge )
1932       {
1933         FT_TRACE5(( "ASSERTION FAILED for edge %d\n", edge2-edges ));
1934 
1935         af_cjk_align_linked_edge( hints, dim, edge2, edge );
1936         edge->flags |= AF_EDGE_DONE;
1937 
1938 #ifdef FT_DEBUG_LEVEL_TRACE
1939         num_actions++;
1940 #endif
1941 
1942         continue;
1943       }
1944 
1945       if ( edge2 < edge )
1946       {
1947         af_cjk_align_linked_edge( hints, dim, edge2, edge );
1948         edge->flags |= AF_EDGE_DONE;
1949 
1950 #ifdef FT_DEBUG_LEVEL_TRACE
1951         num_actions++;
1952 #endif
1953 
1954         /* We rarely reaches here it seems;
1955          * usually the two edges belonging
1956          * to one stem are marked as DONE together
1957          */
1958         has_last_stem = TRUE;
1959         last_stem_pos = edge->pos;
1960         continue;
1961       }
1962 
1963       if ( dim != AF_DIMENSION_VERT && !anchor )
1964       {
1965 
1966 #if 0
1967         if ( fixedpitch )
1968         {
1969           AF_Edge     left  = edge;
1970           AF_Edge     right = edge_limit - 1;
1971           AF_EdgeRec  left1, left2, right1, right2;
1972           FT_Pos      target, center1, center2;
1973           FT_Pos      delta1, delta2, d1, d2;
1974 
1975 
1976           while ( right > left && !right->link )
1977             right--;
1978 
1979           left1  = *left;
1980           left2  = *left->link;
1981           right1 = *right->link;
1982           right2 = *right;
1983 
1984           delta  = ( ( ( hinter->pp2.x + 32 ) & -64 ) - hinter->pp2.x ) / 2;
1985           target = left->opos + ( right->opos - left->opos ) / 2 + delta - 16;
1986 
1987           delta1  = delta;
1988           delta1 += af_hint_normal_stem( hints, left, left->link,
1989                                          delta1, 0 );
1990 
1991           if ( left->link != right )
1992             af_hint_normal_stem( hints, right->link, right, delta1, 0 );
1993 
1994           center1 = left->pos + ( right->pos - left->pos ) / 2;
1995 
1996           if ( center1 >= target )
1997             delta2 = delta - 32;
1998           else
1999             delta2 = delta + 32;
2000 
2001           delta2 += af_hint_normal_stem( hints, &left1, &left2, delta2, 0 );
2002 
2003           if ( delta1 != delta2 )
2004           {
2005             if ( left->link != right )
2006               af_hint_normal_stem( hints, &right1, &right2, delta2, 0 );
2007 
2008             center2 = left1.pos + ( right2.pos - left1.pos ) / 2;
2009 
2010             d1 = center1 - target;
2011             d2 = center2 - target;
2012 
2013             if ( FT_ABS( d2 ) < FT_ABS( d1 ) )
2014             {
2015               left->pos       = left1.pos;
2016               left->link->pos = left2.pos;
2017 
2018               if ( left->link != right )
2019               {
2020                 right->link->pos = right1.pos;
2021                 right->pos       = right2.pos;
2022               }
2023 
2024               delta1 = delta2;
2025             }
2026           }
2027 
2028           delta               = delta1;
2029           right->link->flags |= AF_EDGE_DONE;
2030           right->flags       |= AF_EDGE_DONE;
2031         }
2032         else
2033 
2034 #endif /* 0 */
2035 
2036           delta = af_hint_normal_stem( hints, edge, edge2, 0,
2037                                        AF_DIMENSION_HORZ );
2038       }
2039       else
2040         af_hint_normal_stem( hints, edge, edge2, delta, dim );
2041 
2042 #if 0
2043       printf( "stem (%d,%d) adjusted (%.1f,%.1f)\n",
2044                edge - edges, edge2 - edges,
2045                ( edge->pos - edge->opos ) / 64.0,
2046                ( edge2->pos - edge2->opos ) / 64.0 );
2047 #endif
2048 
2049       anchor = edge;
2050       edge->flags  |= AF_EDGE_DONE;
2051       edge2->flags |= AF_EDGE_DONE;
2052       has_last_stem = TRUE;
2053       last_stem_pos = edge2->pos;
2054     }
2055 
2056     /* make sure that lowercase m's maintain their symmetry */
2057 
2058     /* In general, lowercase m's have six vertical edges if they are sans */
2059     /* serif, or twelve if they are with serifs.  This implementation is  */
2060     /* based on that assumption, and seems to work very well with most    */
2061     /* faces.  However, if for a certain face this assumption is not      */
2062     /* true, the m is just rendered like before.  In addition, any stem   */
2063     /* correction will only be applied to symmetrical glyphs (even if the */
2064     /* glyph is not an m), so the potential for unwanted distortion is    */
2065     /* relatively low.                                                    */
2066 
2067     /* We don't handle horizontal edges since we can't easily assure that */
2068     /* the third (lowest) stem aligns with the base line; it might end up */
2069     /* one pixel higher or lower.                                         */
2070 
2071     n_edges = edge_limit - edges;
2072     if ( dim == AF_DIMENSION_HORZ && ( n_edges == 6 || n_edges == 12 ) )
2073     {
2074       AF_Edge  edge1, edge2, edge3;
2075       FT_Pos   dist1, dist2, span;
2076 
2077 
2078       if ( n_edges == 6 )
2079       {
2080         edge1 = edges;
2081         edge2 = edges + 2;
2082         edge3 = edges + 4;
2083       }
2084       else
2085       {
2086         edge1 = edges + 1;
2087         edge2 = edges + 5;
2088         edge3 = edges + 9;
2089       }
2090 
2091       dist1 = edge2->opos - edge1->opos;
2092       dist2 = edge3->opos - edge2->opos;
2093 
2094       span = dist1 - dist2;
2095       if ( span < 0 )
2096         span = -span;
2097 
2098       if ( edge1->link == edge1 + 1 &&
2099            edge2->link == edge2 + 1 &&
2100            edge3->link == edge3 + 1 && span < 8 )
2101       {
2102         delta = edge3->pos - ( 2 * edge2->pos - edge1->pos );
2103         edge3->pos -= delta;
2104         if ( edge3->link )
2105           edge3->link->pos -= delta;
2106 
2107         /* move the serifs along with the stem */
2108         if ( n_edges == 12 )
2109         {
2110           ( edges + 8 )->pos -= delta;
2111           ( edges + 11 )->pos -= delta;
2112         }
2113 
2114         edge3->flags |= AF_EDGE_DONE;
2115         if ( edge3->link )
2116           edge3->link->flags |= AF_EDGE_DONE;
2117       }
2118     }
2119 
2120     if ( !skipped )
2121       goto Exit;
2122 
2123     /*
2124      * now hint the remaining edges (serifs and single) in order
2125      * to complete our processing
2126      */
2127     for ( edge = edges; edge < edge_limit; edge++ )
2128     {
2129       if ( edge->flags & AF_EDGE_DONE )
2130         continue;
2131 
2132       if ( edge->serif )
2133       {
2134         af_cjk_align_serif_edge( hints, edge->serif, edge );
2135         edge->flags |= AF_EDGE_DONE;
2136         skipped--;
2137       }
2138     }
2139 
2140     if ( !skipped )
2141       goto Exit;
2142 
2143     for ( edge = edges; edge < edge_limit; edge++ )
2144     {
2145       AF_Edge  before, after;
2146 
2147 
2148       if ( edge->flags & AF_EDGE_DONE )
2149         continue;
2150 
2151       before = after = edge;
2152 
2153       while ( --before >= edges )
2154         if ( before->flags & AF_EDGE_DONE )
2155           break;
2156 
2157       while ( ++after < edge_limit )
2158         if ( after->flags & AF_EDGE_DONE )
2159           break;
2160 
2161       if ( before >= edges || after < edge_limit )
2162       {
2163         if ( before < edges )
2164           af_cjk_align_serif_edge( hints, after, edge );
2165         else if ( after >= edge_limit )
2166           af_cjk_align_serif_edge( hints, before, edge );
2167         else
2168         {
2169           if ( after->fpos == before->fpos )
2170             edge->pos = before->pos;
2171           else
2172             edge->pos = before->pos +
2173                         FT_MulDiv( edge->fpos - before->fpos,
2174                                    after->pos - before->pos,
2175                                    after->fpos - before->fpos );
2176         }
2177       }
2178     }
2179 
2180   Exit:
2181 
2182 #ifdef FT_DEBUG_LEVEL_TRACE
2183     if ( !num_actions )
2184       FT_TRACE5(( "  (none)\n" ));
2185     FT_TRACE5(( "\n" ));
2186 #endif
2187 
2188     return;
2189   }
2190 
2191 
2192   static void
2193   af_cjk_align_edge_points( AF_GlyphHints  hints,
2194                             AF_Dimension   dim )
2195   {
2196     AF_AxisHints  axis       = & hints->axis[dim];
2197     AF_Edge       edges      = axis->edges;
2198     AF_Edge       edge_limit = edges + axis->num_edges;
2199     AF_Edge       edge;
2200     FT_Bool       snapping;
2201 
2202 
2203     snapping = FT_BOOL( ( dim == AF_DIMENSION_HORZ             &&
2204                           AF_LATIN_HINTS_DO_HORZ_SNAP( hints ) )  ||
2205                         ( dim == AF_DIMENSION_VERT             &&
2206                           AF_LATIN_HINTS_DO_VERT_SNAP( hints ) )  );
2207 
2208     for ( edge = edges; edge < edge_limit; edge++ )
2209     {
2210       /* move the points of each segment     */
2211       /* in each edge to the edge's position */
2212       AF_Segment  seg = edge->first;
2213 
2214 
2215       if ( snapping )
2216       {
2217         do
2218         {
2219           AF_Point  point = seg->first;
2220 
2221 
2222           for (;;)
2223           {
2224             if ( dim == AF_DIMENSION_HORZ )
2225             {
2226               point->x      = edge->pos;
2227               point->flags |= AF_FLAG_TOUCH_X;
2228             }
2229             else
2230             {
2231               point->y      = edge->pos;
2232               point->flags |= AF_FLAG_TOUCH_Y;
2233             }
2234 
2235             if ( point == seg->last )
2236               break;
2237 
2238             point = point->next;
2239           }
2240 
2241           seg = seg->edge_next;
2242 
2243         } while ( seg != edge->first );
2244       }
2245       else
2246       {
2247         FT_Pos  delta = edge->pos - edge->opos;
2248 
2249 
2250         do
2251         {
2252           AF_Point  point = seg->first;
2253 
2254 
2255           for (;;)
2256           {
2257             if ( dim == AF_DIMENSION_HORZ )
2258             {
2259               point->x     += delta;
2260               point->flags |= AF_FLAG_TOUCH_X;
2261             }
2262             else
2263             {
2264               point->y     += delta;
2265               point->flags |= AF_FLAG_TOUCH_Y;
2266             }
2267 
2268             if ( point == seg->last )
2269               break;
2270 
2271             point = point->next;
2272           }
2273 
2274           seg = seg->edge_next;
2275 
2276         } while ( seg != edge->first );
2277       }
2278     }
2279   }
2280 
2281 
2282   /* Apply the complete hinting algorithm to a CJK glyph. */
2283 
2284   FT_LOCAL_DEF( FT_Error )
2285   af_cjk_hints_apply( FT_UInt        glyph_index,
2286                       AF_GlyphHints  hints,
2287                       FT_Outline*    outline,
2288                       AF_CJKMetrics  metrics )
2289   {
2290     FT_Error  error;
2291     int       dim;
2292 
2293     FT_UNUSED( metrics );
2294     FT_UNUSED( glyph_index );
2295 
2296 
2297     error = af_glyph_hints_reload( hints, outline );
2298     if ( error )
2299       goto Exit;
2300 
2301     /* analyze glyph outline */
2302     if ( AF_HINTS_DO_HORIZONTAL( hints ) )
2303     {
2304       error = af_cjk_hints_detect_features( hints, AF_DIMENSION_HORZ );
2305       if ( error )
2306         goto Exit;
2307 
2308       af_cjk_hints_compute_blue_edges( hints, metrics, AF_DIMENSION_HORZ );
2309     }
2310 
2311     if ( AF_HINTS_DO_VERTICAL( hints ) )
2312     {
2313       error = af_cjk_hints_detect_features( hints, AF_DIMENSION_VERT );
2314       if ( error )
2315         goto Exit;
2316 
2317       af_cjk_hints_compute_blue_edges( hints, metrics, AF_DIMENSION_VERT );
2318     }
2319 
2320     /* grid-fit the outline */
2321     for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
2322     {
2323       if ( ( dim == AF_DIMENSION_HORZ && AF_HINTS_DO_HORIZONTAL( hints ) ) ||
2324            ( dim == AF_DIMENSION_VERT && AF_HINTS_DO_VERTICAL( hints ) )   )
2325       {
2326 
2327 #ifdef AF_CONFIG_OPTION_USE_WARPER
2328         if ( dim == AF_DIMENSION_HORZ                                  &&
2329              metrics->root.scaler.render_mode == FT_RENDER_MODE_NORMAL &&
2330              AF_HINTS_DO_WARP( hints )                                 )
2331         {
2332           AF_WarperRec  warper;
2333           FT_Fixed      scale;
2334           FT_Pos        delta;
2335 
2336 
2337           af_warper_compute( &warper, hints, (AF_Dimension)dim,
2338                              &scale, &delta );
2339           af_glyph_hints_scale_dim( hints, (AF_Dimension)dim,
2340                                     scale, delta );
2341           continue;
2342         }
2343 #endif /* AF_CONFIG_OPTION_USE_WARPER */
2344 
2345         af_cjk_hint_edges( hints, (AF_Dimension)dim );
2346         af_cjk_align_edge_points( hints, (AF_Dimension)dim );
2347         af_glyph_hints_align_strong_points( hints, (AF_Dimension)dim );
2348         af_glyph_hints_align_weak_points( hints, (AF_Dimension)dim );
2349       }
2350     }
2351 
2352     af_glyph_hints_save( hints, outline );
2353 
2354   Exit:
2355     return error;
2356   }
2357 
2358 
2359   /*************************************************************************/
2360   /*************************************************************************/
2361   /*****                                                               *****/
2362   /*****                C J K   S C R I P T   C L A S S                *****/
2363   /*****                                                               *****/
2364   /*************************************************************************/
2365   /*************************************************************************/
2366 
2367 
2368   AF_DEFINE_WRITING_SYSTEM_CLASS(
2369     af_cjk_writing_system_class,
2370 
2371     AF_WRITING_SYSTEM_CJK,
2372 
2373     sizeof ( AF_CJKMetricsRec ),
2374 
2375     (AF_WritingSystem_InitMetricsFunc) af_cjk_metrics_init,        /* style_metrics_init    */
2376     (AF_WritingSystem_ScaleMetricsFunc)af_cjk_metrics_scale,       /* style_metrics_scale   */
2377     (AF_WritingSystem_DoneMetricsFunc) NULL,                       /* style_metrics_done    */
2378     (AF_WritingSystem_GetStdWidthsFunc)af_cjk_get_standard_widths, /* style_metrics_getstdw */
2379 
2380     (AF_WritingSystem_InitHintsFunc)   af_cjk_hints_init,          /* style_hints_init      */
2381     (AF_WritingSystem_ApplyHintsFunc)  af_cjk_hints_apply          /* style_hints_apply     */
2382   )
2383 
2384 
2385 #else /* !AF_CONFIG_OPTION_CJK */
2386 
2387 
2388   AF_DEFINE_WRITING_SYSTEM_CLASS(
2389     af_cjk_writing_system_class,
2390 
2391     AF_WRITING_SYSTEM_CJK,
2392 
2393     sizeof ( AF_CJKMetricsRec ),
2394 
2395     (AF_WritingSystem_InitMetricsFunc) NULL, /* style_metrics_init    */
2396     (AF_WritingSystem_ScaleMetricsFunc)NULL, /* style_metrics_scale   */
2397     (AF_WritingSystem_DoneMetricsFunc) NULL, /* style_metrics_done    */
2398     (AF_WritingSystem_GetStdWidthsFunc)NULL, /* style_metrics_getstdw */
2399 
2400     (AF_WritingSystem_InitHintsFunc)   NULL, /* style_hints_init      */
2401     (AF_WritingSystem_ApplyHintsFunc)  NULL  /* style_hints_apply     */
2402   )
2403 
2404 
2405 #endif /* !AF_CONFIG_OPTION_CJK */
2406 
2407 
2408 /* END */