1 /*
   2  * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "awt.h"
  27 #include <math.h>
  28 #include "jlong.h"
  29 #include "awt_Font.h"
  30 #include "awt_Toolkit.h"
  31 
  32 #include "java_awt_Font.h"
  33 #include "java_awt_FontMetrics.h"
  34 #include "java_awt_Dimension.h"
  35 
  36 #include "sun_awt_FontDescriptor.h"
  37 #include "sun_awt_windows_WDefaultFontCharset.h"
  38 #include "sun_awt_windows_WFontPeer.h"
  39 #include "awt_Component.h"
  40 #include "Disposer.h"
  41 
  42 /* IMPORTANT! Read the README.JNI file for notes on JNI converted AWT code.
  43  */
  44 
  45 AwtFontCache fontCache;
  46 
  47 extern jboolean IsMultiFont(JNIEnv *env, jobject obj)
  48 {
  49     if (obj == NULL) {
  50         return JNI_FALSE;
  51     }
  52     if (env->EnsureLocalCapacity(2)) {
  53         env->ExceptionClear();
  54         return JNI_FALSE;
  55     }
  56     jobject peer = env->CallObjectMethod(obj, AwtFont::peerMID);
  57     env->ExceptionClear();
  58     if (peer == NULL) {
  59         return JNI_FALSE;
  60     }
  61     jobject fontConfig = env->GetObjectField(peer, AwtFont::fontConfigID);
  62     jboolean result = fontConfig != NULL;
  63     env->DeleteLocalRef(peer);
  64     env->DeleteLocalRef(fontConfig);
  65     return result;
  66 }
  67 
  68 extern jstring GetTextComponentFontName(JNIEnv *env, jobject font)
  69 {
  70     DASSERT(font != NULL);
  71     if (env->EnsureLocalCapacity(2)) {
  72         env->ExceptionClear();
  73         return NULL;
  74     }
  75     jobject peer = env->CallObjectMethod(font, AwtFont::peerMID);
  76     DASSERT(peer != NULL);
  77     if (peer == NULL) return NULL;
  78     jstring textComponentFontName =
  79             (jstring) env->GetObjectField(peer, AwtFont::textComponentFontNameID);
  80     env->DeleteLocalRef(peer);
  81     return textComponentFontName;
  82 }
  83 
  84 /************************************************************************
  85  * AwtFont fields
  86  */
  87 
  88 /* sun.awt.windows.WFontMetrics fields */
  89 jfieldID AwtFont::widthsID;
  90 jfieldID AwtFont::ascentID;
  91 jfieldID AwtFont::descentID;
  92 jfieldID AwtFont::leadingID;
  93 jfieldID AwtFont::heightID;
  94 jfieldID AwtFont::maxAscentID;
  95 jfieldID AwtFont::maxDescentID;
  96 jfieldID AwtFont::maxHeightID;
  97 jfieldID AwtFont::maxAdvanceID;
  98 
  99 /* java.awt.FontDescriptor fields */
 100 jfieldID AwtFont::nativeNameID;
 101 jfieldID AwtFont::useUnicodeID;
 102 
 103 /* java.awt.Font fields */
 104 jfieldID AwtFont::pDataID;
 105 jfieldID AwtFont::nameID;
 106 jfieldID AwtFont::sizeID;
 107 jfieldID AwtFont::styleID;
 108 
 109 /* java.awt.FontMetrics fields */
 110 jfieldID AwtFont::fontID;
 111 
 112 /* sun.awt.PlatformFont fields */
 113 jfieldID AwtFont::fontConfigID;
 114 jfieldID AwtFont::componentFontsID;
 115 
 116 /* sun.awt.windows.WFontPeer fields */
 117 jfieldID AwtFont::textComponentFontNameID;
 118 
 119 /* sun.awt.windows.WDefaultFontCharset fields */
 120 jfieldID AwtFont::fontNameID;
 121 
 122 /* java.awt.Font methods */
 123 jmethodID AwtFont::peerMID;
 124 
 125 /* sun.awt.PlatformFont methods */
 126 jmethodID AwtFont::makeConvertedMultiFontStringMID;
 127 
 128 /* sun.awt.PlatformFont methods */
 129 jmethodID AwtFont::getFontMID;
 130 
 131 /* java.awt.FontMetrics methods */
 132 jmethodID AwtFont::getHeightMID;
 133 
 134 
 135 /************************************************************************
 136  * AwtFont methods
 137  */
 138 AwtFont::AwtFont(int num, JNIEnv *env, jobject javaFont)
 139 {
 140     if (num == 0) {  // not multi-font
 141         num = 1;
 142     }
 143 
 144     m_hFontNum = num;
 145     m_hFont = new HFONT[num];
 146 
 147     for (int i = 0; i < num; i++) {
 148         m_hFont[i] = NULL;
 149     }
 150 
 151     m_textInput = -1;
 152     m_ascent = -1;
 153     m_overhang = 0;
 154 }
 155 
 156 AwtFont::~AwtFont()
 157 {
 158     delete[] m_hFont;
 159 }
 160 
 161 void AwtFont::Dispose() {
 162     for (int i = 0; i < m_hFontNum; i++) {
 163         HFONT font = m_hFont[i];
 164         if (font != NULL && fontCache.Search(font)) {
 165             fontCache.Remove(font);
 166             /*  NOTE: delete of windows HFONT happens in FontCache::Remove
 167                       only when the final reference to the font is disposed */
 168         } else if (font != NULL) {
 169             // if font was not in cache, its not shared and we delete it now
 170             DASSERT(::GetObjectType(font) == OBJ_FONT);
 171             VERIFY(::DeleteObject(font));
 172         }
 173         m_hFont[i] = NULL;
 174     }
 175 
 176     AwtObject::Dispose();
 177 }
 178 
 179 static void pDataDisposeMethod(JNIEnv *env, jlong pData)
 180 {
 181     TRY_NO_VERIFY;
 182 
 183     AwtObject::_Dispose((PDATA)pData);
 184 
 185     CATCH_BAD_ALLOC;
 186 }
 187 
 188 AwtFont* AwtFont::GetFont(JNIEnv *env, jobject font,
 189                           jint angle, jfloat awScale)
 190 {
 191     jlong pData = env->GetLongField(font, AwtFont::pDataID);
 192     AwtFont* awtFont = (AwtFont*)jlong_to_ptr(pData);
 193 
 194     if (awtFont != NULL) {
 195         return awtFont;
 196     }
 197 
 198     awtFont = Create(env, font, angle, awScale);
 199     if (awtFont == NULL) {
 200         return NULL;
 201     }
 202 
 203     env->SetLongField(font, AwtFont::pDataID,
 204         reinterpret_cast<jlong>(awtFont));
 205     return awtFont;
 206 }
 207 
 208 // Get suitable CHARSET from charset string provided by font configuration.
 209 static int GetNativeCharset(LPCWSTR name)
 210 {
 211     if (wcsstr(name, L"ANSI_CHARSET"))
 212         return ANSI_CHARSET;
 213     if (wcsstr(name, L"DEFAULT_CHARSET"))
 214         return DEFAULT_CHARSET;
 215     if (wcsstr(name, L"SYMBOL_CHARSET") || wcsstr(name, L"WingDings"))
 216         return SYMBOL_CHARSET;
 217     if (wcsstr(name, L"SHIFTJIS_CHARSET"))
 218         return SHIFTJIS_CHARSET;
 219     if (wcsstr(name, L"GB2312_CHARSET"))
 220         return GB2312_CHARSET;
 221     if (wcsstr(name, L"HANGEUL_CHARSET"))
 222         return HANGEUL_CHARSET;
 223     if (wcsstr(name, L"CHINESEBIG5_CHARSET"))
 224         return CHINESEBIG5_CHARSET;
 225     if (wcsstr(name, L"OEM_CHARSET"))
 226         return OEM_CHARSET;
 227     if (wcsstr(name, L"JOHAB_CHARSET"))
 228         return JOHAB_CHARSET;
 229     if (wcsstr(name, L"HEBREW_CHARSET"))
 230         return HEBREW_CHARSET;
 231     if (wcsstr(name, L"ARABIC_CHARSET"))
 232         return ARABIC_CHARSET;
 233     if (wcsstr(name, L"GREEK_CHARSET"))
 234         return GREEK_CHARSET;
 235     if (wcsstr(name, L"TURKISH_CHARSET"))
 236         return TURKISH_CHARSET;
 237     if (wcsstr(name, L"VIETNAMESE_CHARSET"))
 238         return VIETNAMESE_CHARSET;
 239     if (wcsstr(name, L"THAI_CHARSET"))
 240         return THAI_CHARSET;
 241     if (wcsstr(name, L"EASTEUROPE_CHARSET"))
 242         return EASTEUROPE_CHARSET;
 243     if (wcsstr(name, L"RUSSIAN_CHARSET"))
 244         return RUSSIAN_CHARSET;
 245     if (wcsstr(name, L"MAC_CHARSET"))
 246         return MAC_CHARSET;
 247     if (wcsstr(name, L"BALTIC_CHARSET"))
 248         return BALTIC_CHARSET;
 249     return ANSI_CHARSET;
 250 }
 251 
 252 AwtFont* AwtFont::Create(JNIEnv *env, jobject font, jint angle, jfloat awScale)
 253 {
 254     int fontSize = env->GetIntField(font, AwtFont::sizeID);
 255     int fontStyle = env->GetIntField(font, AwtFont::styleID);
 256 
 257     AwtFont* awtFont = NULL;
 258     jobjectArray compFont = NULL;
 259     int cfnum = 0;
 260 
 261     try {
 262         if (env->EnsureLocalCapacity(3) < 0)
 263             return 0;
 264 
 265         if (IsMultiFont(env, font)) {
 266             compFont = GetComponentFonts(env, font);
 267             if (compFont != NULL) {
 268                 cfnum = env->GetArrayLength(compFont);
 269             }
 270         } else {
 271             compFont = NULL;
 272             cfnum = 0;
 273         }
 274 
 275         LPCWSTR wName = NULL;
 276 
 277         awtFont = new AwtFont(cfnum, env, font);
 278 
 279         awtFont->textAngle = angle;
 280         awtFont->awScale = awScale;
 281 
 282         if (cfnum > 0) {
 283             // Ask peer class for the text component font name
 284             jstring jTextComponentFontName = GetTextComponentFontName(env, font);
 285             if (jTextComponentFontName == NULL) {
 286                 return NULL;
 287             }
 288             LPCWSTR textComponentFontName = JNU_GetStringPlatformChars(env, jTextComponentFontName, NULL);
 289 
 290             awtFont->m_textInput = -1;
 291             for (int i = 0; i < cfnum; i++) {
 292                 // nativeName is a pair of platform fontname and its charset
 293                 // tied with a comma; "Times New Roman,ANSI_CHARSET".
 294                 jobject fontDescriptor = env->GetObjectArrayElement(compFont,
 295                                                                     i);
 296                 jstring nativeName =
 297                     (jstring)env->GetObjectField(fontDescriptor,
 298                                                  AwtFont::nativeNameID);
 299                 wName = JNU_GetStringPlatformChars(env, nativeName, NULL);
 300                 DASSERT(wName);
 301                 if (wName == NULL) {
 302                     wName = L"Arial";
 303                 }
 304 
 305                 //On NT platforms, if the font is not Symbol or Dingbats
 306                 //use "W" version of Win32 APIs directly, info the FontDescription
 307                 //no need to convert characters from Unicode to locale encodings.
 308                 if (GetNativeCharset(wName) != SYMBOL_CHARSET) {
 309                     env->SetBooleanField(fontDescriptor, AwtFont::useUnicodeID, TRUE);
 310                 }
 311 
 312                 // Check to see if this font is suitable for input
 313                 // on AWT TextComponent
 314                 if ((awtFont->m_textInput == -1) &&
 315                         (textComponentFontName != NULL) &&
 316                         (wcscmp(wName, textComponentFontName) == 0)) {
 317                     awtFont->m_textInput = i;
 318                 }
 319                 HFONT hfonttmp = CreateHFont(const_cast<LPWSTR>(wName), fontStyle, fontSize,
 320                                              angle, awScale);
 321                 awtFont->m_hFont[i] = hfonttmp;
 322 
 323                 JNU_ReleaseStringPlatformChars(env, nativeName, wName);
 324 
 325                 env->DeleteLocalRef(fontDescriptor);
 326                 env->DeleteLocalRef(nativeName);
 327             }
 328             if (awtFont->m_textInput == -1) {
 329                 // no text component font was identified, so default
 330                 // to first component
 331                 awtFont->m_textInput = 0;
 332             }
 333 
 334             JNU_ReleaseStringPlatformChars(env, jTextComponentFontName, textComponentFontName);
 335             env->DeleteLocalRef(jTextComponentFontName);
 336         } else {
 337             // Instantiation for English version.
 338             jstring fontName = (jstring)env->GetObjectField(font,
 339                                                             AwtFont::nameID);
 340             if (fontName != NULL) {
 341             wName = JNU_GetStringPlatformChars(env, fontName, NULL);
 342             }
 343             if (wName == NULL) {
 344                 wName = L"Arial";
 345             }
 346 
 347             WCHAR* wEName;
 348             if (!wcscmp(wName, L"Helvetica") || !wcscmp(wName, L"SansSerif")) {
 349                 wEName = L"Arial";
 350             } else if (!wcscmp(wName, L"TimesRoman") ||
 351                        !wcscmp(wName, L"Serif")) {
 352                 wEName = L"Times New Roman";
 353             } else if (!wcscmp(wName, L"Courier") ||
 354                        !wcscmp(wName, L"Monospaced")) {
 355                 wEName = L"Courier New";
 356             } else if (!wcscmp(wName, L"Dialog")) {
 357                 wEName = L"MS Sans Serif";
 358             } else if (!wcscmp(wName, L"DialogInput")) {
 359                 wEName = L"MS Sans Serif";
 360             } else if (!wcscmp(wName, L"ZapfDingbats")) {
 361                 wEName = L"WingDings";
 362             } else
 363                 wEName = L"Arial";
 364 
 365             awtFont->m_textInput = 0;
 366             awtFont->m_hFont[0] = CreateHFont(wEName, fontStyle, fontSize,
 367                                               angle, awScale);
 368 
 369             JNU_ReleaseStringPlatformChars(env, fontName, wName);
 370 
 371             env->DeleteLocalRef(fontName);
 372         }
 373         /* The several callers of this method also set the pData field.
 374          * That's unnecessary but harmless duplication. However we definitely
 375          * want only one disposer record.
 376          */
 377         env->SetLongField(font, AwtFont::pDataID,
 378         reinterpret_cast<jlong>(awtFont));
 379         Disposer_AddRecord(env, font, pDataDisposeMethod,
 380                        reinterpret_cast<jlong>(awtFont));
 381     } catch (...) {
 382         env->DeleteLocalRef(compFont);
 383         throw;
 384     }
 385 
 386     env->DeleteLocalRef(compFont);
 387     return awtFont;
 388 }
 389 
 390 static void strip_tail(wchar_t* text, wchar_t* tail) { // strips tail and any possible whitespace before it from the end of text
 391     if (wcslen(text)<=wcslen(tail)) {
 392         return;
 393     }
 394     wchar_t* p = text+wcslen(text)-wcslen(tail);
 395     if (!wcscmp(p, tail)) {
 396         while(p>text && iswspace(*(p-1)))
 397             p--;
 398         *p = 0;
 399     }
 400 
 401 }
 402 
 403 static HFONT CreateHFont_sub(LPCWSTR name, int style, int height,
 404                              int angle=0, float awScale=1.0f)
 405 {
 406     LOGFONTW logFont;
 407 
 408     logFont.lfWidth = 0;
 409     logFont.lfEscapement = angle;
 410     logFont.lfOrientation = angle;
 411     logFont.lfUnderline = FALSE;
 412     logFont.lfStrikeOut = FALSE;
 413     logFont.lfCharSet = GetNativeCharset(name);
 414     if (angle == 0 && awScale == 1.0f) {
 415         logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
 416     } else {
 417         logFont.lfOutPrecision = OUT_TT_ONLY_PRECIS;
 418     }
 419     logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
 420     logFont.lfQuality = DEFAULT_QUALITY;
 421     logFont.lfPitchAndFamily = DEFAULT_PITCH;
 422 
 423     // Set style
 424     logFont.lfWeight = (style & java_awt_Font_BOLD) ? FW_BOLD : FW_NORMAL;
 425     logFont.lfItalic = (style & java_awt_Font_ITALIC) != 0;
 426     logFont.lfUnderline = 0;//(style & java_awt_Font_UNDERLINE) != 0;
 427 
 428     // Get point size
 429     logFont.lfHeight = -height;
 430 
 431     // Set font name
 432     WCHAR tmpname[80];
 433     wcscpy(tmpname, name);
 434     WCHAR* delimit = wcschr(tmpname, L',');
 435     if (delimit != NULL)
 436         *delimit = L'\0';  // terminate the string after the font name.
 437     // strip "Bold" and "Italic" from the end of the name
 438     strip_tail(tmpname,L""); //strip possible trailing whitespace
 439     strip_tail(tmpname,L"Italic");
 440     strip_tail(tmpname,L"Bold");
 441     wcscpy(&(logFont.lfFaceName[0]), tmpname);
 442     HFONT hFont = ::CreateFontIndirect(&logFont);
 443     DASSERT(hFont != NULL);
 444     // get a expanded or condensed version if its specified.
 445     if (awScale != 1.0f) {
 446         HDC hDC = ::GetDC(0);
 447         HFONT oldFont = (HFONT)::SelectObject(hDC, hFont);
 448         TEXTMETRIC tm;
 449         DWORD avgWidth;
 450         GetTextMetrics(hDC, &tm);
 451         oldFont = (HFONT)::SelectObject(hDC, oldFont);
 452         if (oldFont != NULL) { // should be the same as hFont
 453             VERIFY(::DeleteObject(oldFont));
 454         }
 455         avgWidth = tm.tmAveCharWidth;
 456         logFont.lfWidth = (LONG)((fabs)(avgWidth*awScale));
 457         hFont = ::CreateFontIndirect(&logFont);
 458         DASSERT(hFont != NULL);
 459         VERIFY(::ReleaseDC(0, hDC));
 460     }
 461 
 462     return hFont;
 463 }
 464 
 465 HFONT AwtFont::CreateHFont(WCHAR* name, int style, int height,
 466                            int angle, float awScale)
 467 {
 468     WCHAR longName[80];
 469     // 80 > (max face name(=30) + strlen("CHINESEBIG5_CHARSET"))
 470     // longName doesn't have to be printable.  So, it is OK not to convert.
 471 
 472     wsprintf(longName, L"%ls-%d-%d", name, style, height);
 473 
 474     HFONT hFont = NULL;
 475 
 476     // only cache & share unrotated, unexpanded/uncondensed fonts
 477     if (angle == 0 && awScale == 1.0f) {
 478         hFont = fontCache.Lookup(longName);
 479         if (hFont != NULL) {
 480             fontCache.IncRefCount(hFont);
 481             return hFont;
 482         }
 483     }
 484 
 485     hFont = CreateHFont_sub(name, style, height, angle, awScale);
 486     if (angle == 0 && awScale == 1.0f) {
 487         fontCache.Add(longName, hFont);
 488     }
 489     return hFont;
 490 }
 491 
 492 void AwtFont::Cleanup()
 493 {
 494     fontCache.Clear();
 495 }
 496 
 497 void AwtFont::SetupAscent(AwtFont* font)
 498 {
 499     HDC hDC = ::GetDC(0);
 500     DASSERT(hDC != NULL);
 501     HGDIOBJ oldFont = ::SelectObject(hDC, font->GetHFont());
 502 
 503     TEXTMETRIC metrics;
 504     VERIFY(::GetTextMetrics(hDC, &metrics));
 505     font->SetAscent(metrics.tmAscent);
 506 
 507     ::SelectObject(hDC, oldFont);
 508     VERIFY(::ReleaseDC(0, hDC));
 509 }
 510 
 511 void AwtFont::LoadMetrics(JNIEnv *env, jobject fontMetrics)
 512 {
 513     if (env->EnsureLocalCapacity(3) < 0)
 514         return;
 515     jintArray widths = env->NewIntArray(256);
 516     if (widths == NULL) {
 517         /* no local refs to delete yet. */
 518         return;
 519     }
 520     jobject font = env->GetObjectField(fontMetrics, AwtFont::fontID);
 521     AwtFont* awtFont = AwtFont::GetFont(env, font);
 522 
 523     if (!awtFont) {
 524         /* failed to get font */
 525         return;
 526     }
 527 
 528     HDC hDC = ::GetDC(0);
 529     DASSERT(hDC != NULL);
 530 
 531     HGDIOBJ oldFont = ::SelectObject(hDC, awtFont->GetHFont());
 532     TEXTMETRIC metrics;
 533     VERIFY(::GetTextMetrics(hDC, &metrics));
 534 
 535     awtFont->m_ascent = metrics.tmAscent;
 536 
 537     int ascent = metrics.tmAscent;
 538     int descent = metrics.tmDescent;
 539     int leading = metrics.tmExternalLeading;
 540     env->SetIntField(fontMetrics, AwtFont::ascentID, ascent);
 541     env->SetIntField(fontMetrics, AwtFont::descentID, descent);
 542     env->SetIntField(fontMetrics, AwtFont::leadingID, leading);
 543     env->SetIntField(fontMetrics, AwtFont::heightID, metrics.tmAscent +
 544                      metrics.tmDescent + leading);
 545     env->SetIntField(fontMetrics, AwtFont::maxAscentID, ascent);
 546     env->SetIntField(fontMetrics, AwtFont::maxDescentID, descent);
 547 
 548     int maxHeight =  ascent + descent + leading;
 549     env->SetIntField(fontMetrics, AwtFont::maxHeightID, maxHeight);
 550 
 551     int maxAdvance = metrics.tmMaxCharWidth;
 552     env->SetIntField(fontMetrics, AwtFont::maxAdvanceID, maxAdvance);
 553 
 554     awtFont->m_overhang = metrics.tmOverhang;
 555 
 556     jint intWidths[256];
 557     memset(intWidths, 0, 256 * sizeof(int));
 558     VERIFY(::GetCharWidth(hDC, metrics.tmFirstChar,
 559                           min(metrics.tmLastChar, 255),
 560                           (int *)&intWidths[metrics.tmFirstChar]));
 561     env->SetIntArrayRegion(widths, 0, 256, intWidths);
 562     env->SetObjectField(fontMetrics, AwtFont::widthsID, widths);
 563 
 564     // Get font metrics on remaining fonts (if multifont).
 565     for (int j = 1; j < awtFont->GetHFontNum(); j++) {
 566         ::SelectObject(hDC, awtFont->GetHFont(j));
 567         VERIFY(::GetTextMetrics(hDC, &metrics));
 568         env->SetIntField(fontMetrics, AwtFont::maxAscentID,
 569                          ascent = max(ascent, metrics.tmAscent));
 570         env->SetIntField(fontMetrics, AwtFont::maxDescentID,
 571                          descent = max(descent, metrics.tmDescent));
 572         env->SetIntField(fontMetrics, AwtFont::maxHeightID,
 573                          maxHeight = max(maxHeight,
 574                                          metrics.tmAscent +
 575                                          metrics.tmDescent +
 576                                          metrics.tmExternalLeading));
 577         env->SetIntField(fontMetrics, AwtFont::maxAdvanceID,
 578                          maxAdvance = max(maxAdvance, metrics.tmMaxCharWidth));
 579     }
 580 
 581     VERIFY(::SelectObject(hDC, oldFont));
 582     VERIFY(::ReleaseDC(0, hDC));
 583     env->DeleteLocalRef(font);
 584     env->DeleteLocalRef(widths);
 585 }
 586 
 587 SIZE AwtFont::TextSize(AwtFont* font, int columns, int rows)
 588 {
 589     HDC hDC = ::GetDC(0);
 590     DASSERT(hDC != NULL);
 591     HGDIOBJ oldFont = ::SelectObject(hDC, (font == NULL)
 592                                            ? ::GetStockObject(SYSTEM_FONT)
 593                                            : font->GetHFont());
 594 
 595     SIZE size;
 596     VERIFY(::GetTextExtentPoint(hDC,
 597         TEXT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 52, &size));
 598 
 599     VERIFY(::SelectObject(hDC, oldFont));
 600     VERIFY(::ReleaseDC(0, hDC));
 601 
 602     size.cx = size.cx * columns / 52;
 603     size.cy = size.cy * rows;
 604     return size;
 605 }
 606 
 607 int AwtFont::getFontDescriptorNumber(JNIEnv *env, jobject font,
 608                                      jobject fontDescriptor)
 609 {
 610     int i, num = 0;
 611     jobject refFontDescriptor;
 612     jobjectArray array;
 613 
 614     if (env->EnsureLocalCapacity(2) < 0)
 615         return 0;
 616 
 617     if (IsMultiFont(env, font)) {
 618         array = GetComponentFonts(env, font);
 619         if (array != NULL) {
 620             num = env->GetArrayLength(array);
 621         }
 622     } else {
 623         array = NULL;
 624         num = 0;
 625     }
 626 
 627     for (i = 0; i < num; i++){
 628         // Trying to identify the same FontDescriptor by comparing the
 629         // pointers.
 630         refFontDescriptor = env->GetObjectArrayElement(array, i);
 631         if (env->IsSameObject(refFontDescriptor, fontDescriptor)) {
 632             env->DeleteLocalRef(refFontDescriptor);
 633             env->DeleteLocalRef(array);
 634             return i;
 635         }
 636         env->DeleteLocalRef(refFontDescriptor);
 637     }
 638     env->DeleteLocalRef(array);
 639     return 0;   // Not found.  Use default.
 640 }
 641 
 642 /*
 643  * This is a faster version of the same function, which does most of
 644  * the work in Java.
 645  */
 646 SIZE  AwtFont::DrawStringSize_sub(jstring str, HDC hDC,
 647                                   jobject font, long x, long y, BOOL draw,
 648                                   UINT codePage)
 649 {
 650     SIZE size, temp;
 651     size.cx = size.cy = 0;
 652 
 653     if (str == NULL) {
 654         return size;
 655     }
 656 
 657     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 658     if (env->EnsureLocalCapacity(3) < 0)
 659         return size;
 660     jobjectArray array = 0;
 661 
 662     int arrayLength = 0;
 663 
 664     if (env->GetStringLength(str) == 0) {
 665         return size;
 666     }
 667 
 668     //Init AwtFont object, which will "create" a AwtFont object if necessry,
 669     //before calling makeconvertedMultiFontString(), otherwise, the FontDescriptor's
 670     //"useUnicode" field might not be initialized correctly (font in Menu Component,
 671     //for example").
 672     AwtFont* awtFont = AwtFont::GetFont(env, font);
 673     if (awtFont == NULL) {
 674         return size;
 675     }
 676 
 677     if (IsMultiFont(env, font)) {
 678         jobject peer = env->CallObjectMethod(font, AwtFont::peerMID);
 679         if (peer != NULL) {
 680             array = (jobjectArray)(env->CallObjectMethod(
 681             peer, AwtFont::makeConvertedMultiFontStringMID, str));
 682             DASSERT(!safe_ExceptionOccurred(env));
 683 
 684             if (array != NULL) {
 685                 arrayLength = env->GetArrayLength(array);
 686             }
 687             env->DeleteLocalRef(peer);
 688         }
 689     } else {
 690         array = NULL;
 691         arrayLength = 0;
 692     }
 693 
 694     HFONT oldFont = (HFONT)::SelectObject(hDC, awtFont->GetHFont());
 695 
 696     if (arrayLength == 0) {
 697         int length = env->GetStringLength(str);
 698         LPCWSTR strW = JNU_GetStringPlatformChars(env, str, NULL);
 699         if (strW == NULL) {
 700             return size;
 701         }
 702         VERIFY(::SelectObject(hDC, awtFont->GetHFont()));
 703         if (AwtComponent::GetRTLReadingOrder()){
 704             VERIFY(!draw || ::ExtTextOut(hDC, x, y, ETO_RTLREADING, NULL,
 705                                           strW, length, NULL));
 706         } else {
 707             VERIFY(!draw || ::TextOut(hDC, x, y, strW, length));
 708         }
 709         VERIFY(::GetTextExtentPoint32(hDC, strW, length, &size));
 710         JNU_ReleaseStringPlatformChars(env, str, strW);
 711     } else {
 712         for (int i = 0; i < arrayLength; i = i + 2) {
 713             jobject fontDescriptor = env->GetObjectArrayElement(array, i);
 714             if (fontDescriptor == NULL) {
 715                 break;
 716             }
 717 
 718             jbyteArray convertedBytes =
 719                 (jbyteArray)env->GetObjectArrayElement(array, i + 1);
 720             if (convertedBytes == NULL) {
 721                 env->DeleteLocalRef(fontDescriptor);
 722                 break;
 723             }
 724 
 725             int fdIndex = getFontDescriptorNumber(env, font, fontDescriptor);
 726             if (env->ExceptionCheck()) {
 727                 return size;  //fdIndex==0 return could be exception or not.
 728             }
 729             VERIFY(::SelectObject(hDC, awtFont->GetHFont(fdIndex)));
 730 
 731             /*
 732              * The strange-looking code that follows this comment is
 733              * the result of upstream optimizations. In the array of
 734              * alternating font descriptor and buffers, the buffers
 735              * contain their length in the first four bytes, a la
 736              * Pascal arrays.
 737              *
 738              * Note: the buffer MUST be unsigned, or VC++ will sign
 739              * extend buflen and bad things will happen.
 740              */
 741             unsigned char* buffer = NULL;
 742             jboolean unicodeUsed =
 743                 env->GetBooleanField(fontDescriptor, AwtFont::useUnicodeID);
 744             try {
 745                 buffer = (unsigned char *)
 746                     env->GetPrimitiveArrayCritical(convertedBytes, 0);
 747                 if (buffer == NULL) {
 748                     return size;
 749                 }
 750                 int buflen = (buffer[0] << 24) | (buffer[1] << 16) |
 751                     (buffer[2] << 8) | buffer[3];
 752 
 753                 DASSERT(buflen >= 0);
 754 
 755                 /*
 756                  * the offsetBuffer, on the other hand, must be signed because
 757                  * TextOutA and GetTextExtentPoint32A expect it.
 758                  */
 759                 char* offsetBuffer = (char *)(buffer + 4);
 760 
 761                 if (unicodeUsed) {
 762                     VERIFY(!draw || ::TextOutW(hDC, x, y, (LPCWSTR)offsetBuffer, buflen / 2));
 763                     VERIFY(::GetTextExtentPoint32W(hDC, (LPCWSTR)offsetBuffer, buflen / 2, &temp));
 764                 }
 765                 else {
 766                     VERIFY(!draw || ::TextOutA(hDC, x, y, offsetBuffer, buflen));
 767                     VERIFY(::GetTextExtentPoint32A(hDC, offsetBuffer, buflen, &temp));
 768                 }
 769             } catch (...) {
 770                 if (buffer != NULL) {
 771                     env->ReleasePrimitiveArrayCritical(convertedBytes, buffer,
 772                                                        0);
 773                 }
 774                 throw;
 775             }
 776             env->ReleasePrimitiveArrayCritical(convertedBytes, buffer, 0);
 777 
 778             if (awtFont->textAngle == 0) {
 779                 x += temp.cx;
 780             } else {
 781                // account for rotation of the text used in 2D printing.
 782                double degrees = 360.0 - (awtFont->textAngle/10.0);
 783                double rads = degrees/(180.0/3.1415926535);
 784                double dx = temp.cx * cos(rads);
 785                double dy = temp.cx * sin(rads);
 786                x += (long)floor(dx+0.5);
 787                y += (long)floor(dy+0.5);
 788             }
 789             size.cx += temp.cx;
 790             size.cy = (size.cy < temp.cy) ? temp.cy : size.cy;
 791             env->DeleteLocalRef(fontDescriptor);
 792             env->DeleteLocalRef(convertedBytes);
 793         }
 794     }
 795     env->DeleteLocalRef(array);
 796 
 797     VERIFY(::SelectObject(hDC, oldFont));
 798     return size;
 799 }
 800 
 801 /************************************************************************
 802  * WFontMetrics native methods
 803  */
 804 
 805 extern "C" {
 806 
 807 /*
 808  * Class:     sun_awt_windows_WFontMetrics
 809  * Method:    stringWidth
 810  * Signature: (Ljava/lang/String;)I
 811  */
 812 JNIEXPORT jint JNICALL
 813 Java_sun_awt_windows_WFontMetrics_stringWidth(JNIEnv *env, jobject self,
 814                                               jstring str)
 815 {
 816     TRY;
 817 
 818     if (str == NULL) {
 819         JNU_ThrowNullPointerException(env, "str argument");
 820         return NULL;
 821     }
 822     HDC hDC = ::GetDC(0);    DASSERT(hDC != NULL);
 823 
 824     jobject font = env->GetObjectField(self, AwtFont::fontID);
 825 
 826     long ret = AwtFont::getMFStringWidth(hDC, font, str);
 827     VERIFY(::ReleaseDC(0, hDC));
 828     return ret;
 829 
 830     CATCH_BAD_ALLOC_RET(0);
 831 }
 832 
 833 /*
 834  * Class:     sun_awt_windows_WFontMetrics
 835  * Method:    charsWidth
 836  * Signature: ([CII)I
 837  */
 838 JNIEXPORT jint JNICALL
 839 Java_sun_awt_windows_WFontMetrics_charsWidth(JNIEnv *env, jobject self,
 840                                              jcharArray str,
 841                                              jint off, jint len)
 842 {
 843     TRY;
 844 
 845     if (str == NULL) {
 846         JNU_ThrowNullPointerException(env, "str argument");
 847         return NULL;
 848     }
 849     if ((len < 0) || (off < 0) || (len + off > (env->GetArrayLength(str)))) {
 850         JNU_ThrowArrayIndexOutOfBoundsException(env, "off/len argument");
 851         return NULL;
 852     }
 853 
 854     jchar *strp = new jchar[len];
 855     env->GetCharArrayRegion(str, off, len, strp);
 856     jstring jstr = env->NewString(strp, len);
 857     jint result = 0;
 858     if (jstr != NULL) {
 859         result = Java_sun_awt_windows_WFontMetrics_stringWidth(env, self,
 860                                                                 jstr);
 861     }
 862     delete [] strp;
 863     return result;
 864 
 865     CATCH_BAD_ALLOC_RET(0);
 866 }
 867 
 868 
 869 /*
 870  * Class:     sun_awt_windows_WFontMetrics
 871  * Method:    bytesWidth
 872  * Signature: ([BII)I
 873  */
 874 JNIEXPORT jint JNICALL
 875 Java_sun_awt_windows_WFontMetrics_bytesWidth(JNIEnv *env, jobject self,
 876                                              jbyteArray str,
 877                                              jint off, jint len)
 878 {
 879     TRY;
 880 
 881     if (str == NULL) {
 882         JNU_ThrowNullPointerException(env, "bytes argument");
 883         return NULL;
 884     }
 885     if ((len < 0) || (off < 0) || (len + off > (env->GetArrayLength(str)))) {
 886         JNU_ThrowArrayIndexOutOfBoundsException(env, "off or len argument");
 887         return NULL;
 888     }
 889     char *pStrBody = NULL;
 890     jint result = 0;
 891     try {
 892         jintArray array = (jintArray)env->GetObjectField(self,
 893                                                          AwtFont::widthsID);
 894         if (array == NULL) {
 895             JNU_ThrowNullPointerException(env, "Can't access widths array.");
 896             return NULL;
 897         }
 898         pStrBody = (char *)env->GetPrimitiveArrayCritical(str, 0);
 899         if (pStrBody == NULL) {
 900             JNU_ThrowNullPointerException(env, "Can't access str bytes.");
 901             return NULL;
 902         }
 903         char *pStr = pStrBody + off;
 904 
 905         jint *widths = NULL;
 906         try {
 907             widths = (jint *)env->GetPrimitiveArrayCritical(array, 0);
 908             if (widths == NULL) {
 909                 env->ReleasePrimitiveArrayCritical(str, pStrBody, 0);
 910                 JNU_ThrowNullPointerException(env, "Can't access widths.");
 911                 return NULL;
 912             }
 913             for (; len; len--) {
 914                 result += widths[*pStr++];
 915             }
 916         } catch (...) {
 917             if (widths != NULL) {
 918                 env->ReleasePrimitiveArrayCritical(array, widths, 0);
 919             }
 920             throw;
 921         }
 922 
 923         env->ReleasePrimitiveArrayCritical(array, widths, 0);
 924 
 925     } catch (...) {
 926         if (pStrBody != NULL) {
 927             env->ReleasePrimitiveArrayCritical(str, pStrBody, 0);
 928         }
 929         throw;
 930     }
 931 
 932     env->ReleasePrimitiveArrayCritical(str, pStrBody, 0);
 933     return result;
 934 
 935     CATCH_BAD_ALLOC_RET(0);
 936 }
 937 
 938 
 939 /*
 940  * Class:     sun_awt_windows_WFontMetrics
 941  * Method:    init
 942  * Signature: ()V
 943  */
 944 JNIEXPORT void JNICALL
 945 Java_sun_awt_windows_WFontMetrics_init(JNIEnv *env, jobject self)
 946 {
 947     TRY;
 948 
 949     jobject font = env->GetObjectField(self, AwtFont::fontID);
 950     if (font == NULL) {
 951         JNU_ThrowNullPointerException(env, "fontMetrics' font");
 952         return;
 953     }
 954     // This local variable is unused. Is there some subtle side-effect here?
 955     jlong pData = env->GetLongField(font, AwtFont::pDataID);
 956 
 957     AwtFont::LoadMetrics(env, self);
 958 
 959     CATCH_BAD_ALLOC;
 960 }
 961 
 962 
 963 /*
 964  * Class:     sun_awt_windows_WFontMetrics
 965  * Method:    initIDs
 966  * Signature: ()V
 967  */
 968 JNIEXPORT void JNICALL
 969 Java_sun_awt_windows_WFontMetrics_initIDs(JNIEnv *env, jclass cls)
 970 {
 971    CHECK_NULL(AwtFont::widthsID = env->GetFieldID(cls, "widths", "[I"));
 972    CHECK_NULL(AwtFont::ascentID = env->GetFieldID(cls, "ascent", "I"));
 973    CHECK_NULL(AwtFont::descentID = env->GetFieldID(cls, "descent", "I"));
 974    CHECK_NULL(AwtFont::leadingID = env->GetFieldID(cls, "leading", "I"));
 975    CHECK_NULL(AwtFont::heightID = env->GetFieldID(cls, "height", "I"));
 976    CHECK_NULL(AwtFont::maxAscentID = env->GetFieldID(cls, "maxAscent", "I"));
 977    CHECK_NULL(AwtFont::maxDescentID = env->GetFieldID(cls, "maxDescent", "I"));
 978    CHECK_NULL(AwtFont::maxHeightID = env->GetFieldID(cls, "maxHeight", "I"));
 979     AwtFont::maxAdvanceID = env->GetFieldID(cls, "maxAdvance", "I");
 980 }
 981 
 982 } /* extern "C" */
 983 
 984 
 985 /************************************************************************
 986  * java.awt.Font native methods
 987  */
 988 
 989 extern "C" {
 990 
 991 JNIEXPORT void JNICALL
 992 Java_java_awt_Font_initIDs(JNIEnv *env, jclass cls)
 993 {
 994     CHECK_NULL(AwtFont::peerMID = env->GetMethodID(cls, "getPeer",
 995          "()Ljava/awt/peer/FontPeer;"));
 996     CHECK_NULL(AwtFont::pDataID = env->GetFieldID(cls, "pData", "J"));
 997     CHECK_NULL(AwtFont::nameID =
 998          env->GetFieldID(cls, "name", "Ljava/lang/String;"));
 999     CHECK_NULL(AwtFont::sizeID = env->GetFieldID(cls, "size", "I"));
1000     CHECK_NULL(AwtFont::styleID = env->GetFieldID(cls, "style", "I"));
1001     AwtFont::getFontMID =
1002       env->GetStaticMethodID(cls, "getFont",
1003                              "(Ljava/lang/String;)Ljava/awt/Font;");
1004 }
1005 
1006 } /* extern "C" */
1007 
1008 
1009 /************************************************************************
1010  * java.awt.FontMetric native methods
1011  */
1012 
1013 extern "C" {
1014 
1015 JNIEXPORT void JNICALL
1016 Java_java_awt_FontMetrics_initIDs(JNIEnv *env, jclass cls)
1017 {
1018     CHECK_NULL(AwtFont::fontID =
1019           env->GetFieldID(cls, "font", "Ljava/awt/Font;"));
1020     AwtFont::getHeightMID = env->GetMethodID(cls, "getHeight", "()I");
1021 }
1022 
1023 } /* extern "C" */
1024 
1025 /************************************************************************
1026  * sun.awt.FontDescriptor native methods
1027  */
1028 
1029 extern "C" {
1030 
1031 JNIEXPORT void JNICALL
1032 Java_sun_awt_FontDescriptor_initIDs(JNIEnv *env, jclass cls)
1033 {
1034     CHECK_NULL(AwtFont::nativeNameID =
1035                env->GetFieldID(cls, "nativeName", "Ljava/lang/String;"));
1036     AwtFont::useUnicodeID = env->GetFieldID(cls, "useUnicode", "Z");
1037 
1038 }
1039 
1040 } /* extern "C" */
1041 
1042 
1043 /************************************************************************
1044  * sun.awt.PlatformFont native methods
1045  */
1046 
1047 extern "C" {
1048 
1049 JNIEXPORT void JNICALL
1050 Java_sun_awt_PlatformFont_initIDs(JNIEnv *env, jclass cls)
1051 {
1052     CHECK_NULL(AwtFont::fontConfigID =
1053         env->GetFieldID(cls, "fontConfig", "Lsun/awt/FontConfiguration;"));
1054     CHECK_NULL(AwtFont::componentFontsID =
1055         env->GetFieldID(cls, "componentFonts", "[Lsun/awt/FontDescriptor;"));
1056     AwtFont::makeConvertedMultiFontStringMID =
1057         env->GetMethodID(cls, "makeConvertedMultiFontString",
1058                          "(Ljava/lang/String;)[Ljava/lang/Object;");
1059 }
1060 
1061 } /* extern "C" */
1062 
1063 
1064 /************************************************************************
1065  * sun.awt.windows.WFontPeer native methods
1066  */
1067 
1068 extern "C" {
1069 
1070 JNIEXPORT void JNICALL
1071 Java_sun_awt_windows_WFontPeer_initIDs(JNIEnv *env, jclass cls)
1072 {
1073     TRY;
1074 
1075     AwtFont::textComponentFontNameID = env->GetFieldID(cls, "textComponentFontName", "Ljava/lang/String;");
1076 
1077     DASSERT(AwtFont::textComponentFontNameID != NULL);
1078 
1079     CATCH_BAD_ALLOC;
1080 }
1081 
1082 } /* extern "C" */
1083 
1084 
1085 /************************************************************************
1086  * FontCache methods
1087  */
1088 
1089 void AwtFontCache::Add(WCHAR* name, HFONT font)
1090 {
1091     fontCache.m_head = new Item(name, font, fontCache.m_head);
1092 }
1093 
1094 HFONT AwtFontCache::Lookup(WCHAR* name)
1095 {
1096     Item* item = fontCache.m_head;
1097     Item* lastItem = NULL;
1098 
1099     while (item != NULL) {
1100         if (wcscmp(item->name, name) == 0) {
1101             return item->font;
1102         }
1103         lastItem = item;
1104         item = item->next;
1105     }
1106     return NULL;
1107 }
1108 
1109 BOOL AwtFontCache::Search(HFONT font)
1110 {
1111     Item* item = fontCache.m_head;
1112 
1113     while (item != NULL) {
1114         if (item->font == font) {
1115             return TRUE;
1116         }
1117         item = item->next;
1118     }
1119     return FALSE;
1120 }
1121 
1122 void AwtFontCache::Remove(HFONT font)
1123 {
1124     Item* item = fontCache.m_head;
1125     Item* lastItem = NULL;
1126 
1127     while (item != NULL) {
1128         if (item->font == font) {
1129             if (DecRefCount(item) <= 0){
1130                 if (lastItem == NULL) {
1131                     fontCache.m_head = item->next;
1132                 } else {
1133                 lastItem->next = item->next;
1134                 }
1135              delete item;
1136              }
1137              return;
1138         }
1139         lastItem = item;
1140         item = item->next;
1141     }
1142 }
1143 
1144 void AwtFontCache::Clear()
1145 {
1146     Item* item = m_head;
1147     Item* next;
1148 
1149     while (item != NULL) {
1150         next = item->next;
1151         delete item;
1152         item = next;
1153     }
1154 
1155     m_head = NULL;
1156 }
1157 
1158 /* NOTE: In the interlock calls below the return value is different
1159          depending on which version of windows. However, all versions
1160          return a 0 or less than value when the count gets there. Only
1161          under NT 4.0 & 98 does the value actaully represent the new value. */
1162 
1163 void AwtFontCache::IncRefCount(HFONT hFont){
1164     Item* item = fontCache.m_head;
1165 
1166     while (item != NULL){
1167 
1168         if (item->font == hFont){
1169             IncRefCount(item);
1170             return;
1171         }
1172         item = item->next;
1173     }
1174 }
1175 
1176 LONG AwtFontCache::IncRefCount(Item* item){
1177     LONG    newVal = 0;
1178 
1179     if(NULL != item){
1180         newVal = InterlockedIncrement((long*)&item->refCount);
1181     }
1182     return(newVal);
1183 }
1184 
1185 LONG AwtFontCache::DecRefCount(Item* item){
1186     LONG    newVal = 0;
1187 
1188     if(NULL != item){
1189         newVal = InterlockedDecrement((long*)&item->refCount);
1190     }
1191     return(newVal);
1192 }
1193 
1194 AwtFontCache::Item::Item(const WCHAR* s, HFONT f, AwtFontCache::Item* n )
1195 {
1196     name = _wcsdup(s);
1197     font = f;
1198     next = n;
1199     refCount = 1;
1200 }
1201 
1202 AwtFontCache::Item::~Item() {
1203   VERIFY(::DeleteObject(font));
1204   free(name);
1205 }
1206 
1207 /////////////////////////////////////////////////////////////////////////////
1208 // for canConvert native method of WDefaultFontCharset
1209 
1210 class CSegTableComponent
1211 {
1212 public:
1213     CSegTableComponent();
1214     virtual ~CSegTableComponent();
1215     virtual void Create(LPCWSTR name);
1216     virtual BOOL In(USHORT iChar) { DASSERT(FALSE); return FALSE; };
1217     LPWSTR GetFontName(){
1218         DASSERT(m_lpszFontName != NULL); return m_lpszFontName;
1219     };
1220 
1221 private:
1222     LPWSTR m_lpszFontName;
1223 };
1224 
1225 CSegTableComponent::CSegTableComponent()
1226 {
1227     m_lpszFontName = NULL;
1228 }
1229 
1230 CSegTableComponent::~CSegTableComponent()
1231 {
1232     if (m_lpszFontName != NULL) {
1233         free(m_lpszFontName);
1234         m_lpszFontName = NULL;
1235     }
1236 }
1237 
1238 void CSegTableComponent::Create(LPCWSTR name)
1239 {
1240     if (m_lpszFontName != NULL) {
1241         free(m_lpszFontName);
1242         m_lpszFontName = NULL;
1243     }
1244     m_lpszFontName = _wcsdup(name);
1245     DASSERT(m_lpszFontName);
1246 }
1247 
1248 #define CMAPHEX 0x70616d63 // = "cmap" (reversed)
1249 
1250 // CSegTable: Segment table describing character coverage for a font
1251 class CSegTable : public CSegTableComponent
1252 {
1253 public:
1254     CSegTable();
1255     virtual ~CSegTable();
1256     virtual BOOL In(USHORT iChar);
1257     BOOL HasCmap();
1258     virtual BOOL IsEUDC() { DASSERT(FALSE); return FALSE; };
1259 
1260 protected:
1261     virtual void GetData(DWORD dwOffset, LPVOID lpData, DWORD cbData) {
1262         DASSERT(FALSE); };
1263     void MakeTable();
1264     static void SwapShort(USHORT& p);
1265     static void SwapULong(ULONG& p);
1266 
1267 private:
1268     USHORT m_cSegCount;     // number of segments
1269     PUSHORT m_piStart;      // pointer to array of starting values
1270     PUSHORT m_piEnd;        // pointer to array of ending values (inclusive)
1271     USHORT m_cSeg;          // current segment (cache)
1272 };
1273 
1274 CSegTable::CSegTable()
1275 {
1276     m_cSegCount = 0;
1277     m_piStart = NULL;
1278     m_piEnd = NULL;
1279     m_cSeg = 0;
1280 }
1281 
1282 CSegTable::~CSegTable()
1283 {
1284     if (m_piStart != NULL)
1285         delete[] m_piStart;
1286     if (m_piEnd != NULL)
1287         delete[] m_piEnd;
1288 }
1289 
1290 #define OFFSETERROR 0
1291 
1292 void CSegTable::MakeTable()
1293 {
1294 typedef struct tagTABLE{
1295     USHORT  platformID;
1296     USHORT  encodingID;
1297     ULONG   offset;
1298 } TABLE, *PTABLE;
1299 
1300 typedef struct tagSUBTABLE{
1301     USHORT  format;
1302     USHORT  length;
1303     USHORT  version;
1304     USHORT  segCountX2;
1305     USHORT  searchRange;
1306     USHORT  entrySelector;
1307     USHORT  rangeShift;
1308 } SUBTABLE, *PSUBTABLE;
1309 
1310     USHORT aShort[2];
1311     (void) GetData(0, aShort, sizeof(aShort));
1312     USHORT nTables = aShort[1];
1313     SwapShort(nTables);
1314 
1315     // allocate buffer to hold encoding tables
1316     DWORD cbData = nTables * sizeof(TABLE);
1317     PTABLE pTables = new TABLE[nTables];
1318     PTABLE pTable = pTables;
1319 
1320     // get array of encoding tables.
1321     (void) GetData(4, (PBYTE) pTable, cbData);
1322 
1323     ULONG offsetFormat4 = OFFSETERROR;
1324     USHORT i;
1325     for (i = 0; i < nTables; i++) {
1326         SwapShort(pTable->encodingID);
1327         SwapShort(pTable->platformID);
1328         //for a Unicode font for Windows, platformID == 3, encodingID == 1
1329         if ((pTable->platformID == 3)&&(pTable->encodingID == 1)) {
1330             offsetFormat4 = pTable->offset;
1331             SwapULong(offsetFormat4);
1332             break;
1333         }
1334         pTable++;
1335     }
1336     delete[] pTables;
1337     if (offsetFormat4 == OFFSETERROR) {
1338         return;
1339     }
1340 //    DASSERT(offsetFormat4 != OFFSETERROR);
1341 
1342     SUBTABLE subTable;
1343     (void) GetData(offsetFormat4, &subTable, sizeof(SUBTABLE));
1344     SwapShort(subTable.format);
1345     SwapShort(subTable.segCountX2);
1346     DASSERT(subTable.format == 4);
1347 
1348     m_cSegCount = subTable.segCountX2/2;
1349 
1350     // read in the array of segment end values
1351     m_piEnd = new USHORT[m_cSegCount];
1352 
1353     ULONG offset = offsetFormat4
1354         + sizeof(SUBTABLE); //skip constant # bytes in subtable
1355     cbData = m_cSegCount * sizeof(USHORT);
1356     (void) GetData(offset, m_piEnd, cbData);
1357     for (i = 0; i < m_cSegCount; i++)
1358         SwapShort(m_piEnd[i]);
1359     DASSERT(m_piEnd[m_cSegCount-1] == 0xffff);
1360 
1361     // read in the array of segment start values
1362     try {
1363         m_piStart = new USHORT[m_cSegCount];
1364     } catch (std::bad_alloc&) {
1365         delete [] m_piEnd;
1366         m_piEnd = NULL;
1367         throw;
1368     }
1369 
1370     offset += cbData        //skip SegEnd array
1371         + sizeof(USHORT);   //skip reservedPad
1372     (void) GetData(offset, m_piStart, cbData);
1373     for (i = 0; i < m_cSegCount; i++)
1374         SwapShort(m_piStart[i]);
1375     DASSERT(m_piStart[m_cSegCount-1] == 0xffff);
1376 }
1377 
1378 BOOL CSegTable::In(USHORT iChar)
1379 {
1380     if (!HasCmap()) {
1381         return FALSE;
1382     }
1383 //    DASSERT(m_piStart);
1384 //    DASSERT(m_piEnd);
1385 
1386     if (iChar > m_piEnd[m_cSeg]) {
1387         for (; (m_cSeg < m_cSegCount)&&(iChar > m_piEnd[m_cSeg]); m_cSeg++);
1388     } else if (iChar < m_piStart[m_cSeg]) {
1389         for (; (m_cSeg > 0)&&(iChar < m_piStart[m_cSeg]); m_cSeg--);
1390     }
1391 
1392     if ((iChar <= m_piEnd[m_cSeg])&&(iChar >= m_piStart[m_cSeg])&&(iChar != 0xffff))
1393         return TRUE;
1394     else
1395         return FALSE;
1396 }
1397 
1398 inline BOOL CSegTable::HasCmap()
1399 {
1400     return (((m_piEnd)&&(m_piStart)) ? TRUE : FALSE);
1401 }
1402 
1403 inline void CSegTable::SwapShort(USHORT& p)
1404 {
1405     SHORT temp;
1406 
1407     temp = (SHORT)(HIBYTE(p) + (LOBYTE(p) << 8));
1408     p = temp;
1409 }
1410 
1411 inline void CSegTable::SwapULong(ULONG& p)
1412 {
1413     ULONG temp;
1414 
1415     temp = (LONG) ((BYTE) p);
1416     temp <<= 8;
1417     p >>= 8;
1418 
1419     temp += (LONG) ((BYTE) p);
1420     temp <<= 8;
1421     p >>= 8;
1422 
1423     temp += (LONG) ((BYTE) p);
1424     temp <<= 8;
1425     p >>= 8;
1426 
1427     temp += (LONG) ((BYTE) p);
1428     p = temp;
1429 }
1430 
1431 class CStdSegTable : public CSegTable
1432 {
1433 public:
1434     CStdSegTable();
1435     virtual ~CStdSegTable();
1436     BOOL IsEUDC() { return FALSE; };
1437     virtual void Create(LPCWSTR name);
1438 
1439 protected:
1440     void GetData(DWORD dwOffset, LPVOID lpData, DWORD cbData);
1441 
1442 private:
1443     HDC m_hTmpDC;
1444 };
1445 
1446 CStdSegTable::CStdSegTable()
1447 {
1448     m_hTmpDC = NULL;
1449 }
1450 
1451 CStdSegTable::~CStdSegTable()
1452 {
1453     DASSERT(m_hTmpDC == NULL);
1454 }
1455 
1456 inline void CStdSegTable::GetData(DWORD dwOffset,
1457                                   LPVOID lpData, DWORD cbData)
1458 {
1459     DASSERT(m_hTmpDC);
1460     DWORD nBytes =
1461         ::GetFontData(m_hTmpDC, CMAPHEX, dwOffset, lpData, cbData);
1462     DASSERT(nBytes != GDI_ERROR);
1463 }
1464 
1465 void CStdSegTable::Create(LPCWSTR name)
1466 {
1467     CSegTableComponent::Create(name);
1468 
1469     HWND hWnd = ::GetDesktopWindow();
1470     DASSERT(hWnd);
1471     m_hTmpDC = ::GetWindowDC(hWnd);
1472     DASSERT(m_hTmpDC);
1473 
1474     HFONT hFont = CreateHFont_sub(name, 0, 20);
1475 
1476     HFONT hOldFont = (HFONT)::SelectObject(m_hTmpDC, hFont);
1477     DASSERT(hOldFont);
1478 
1479     (void) MakeTable();
1480 
1481     VERIFY(::SelectObject(m_hTmpDC, hOldFont));
1482     VERIFY(::DeleteObject(hFont));
1483     VERIFY(::ReleaseDC(hWnd, m_hTmpDC) != 0);
1484     m_hTmpDC = NULL;
1485 }
1486 
1487 class CEUDCSegTable : public CSegTable
1488 {
1489 public:
1490     CEUDCSegTable();
1491     virtual ~CEUDCSegTable();
1492     BOOL IsEUDC() { return TRUE; };
1493     virtual void Create(LPCWSTR name);
1494 
1495 protected:
1496     void GetData(DWORD dwOffset, LPVOID lpData, DWORD cbData);
1497 
1498 private:
1499     HANDLE m_hTmpFile;
1500     ULONG m_hTmpCMapOffset;
1501 };
1502 
1503 CEUDCSegTable::CEUDCSegTable()
1504 {
1505     m_hTmpFile = NULL;
1506     m_hTmpCMapOffset = 0;
1507 }
1508 
1509 CEUDCSegTable::~CEUDCSegTable()
1510 {
1511     DASSERT(m_hTmpFile == NULL);
1512     DASSERT(m_hTmpCMapOffset == 0);
1513 }
1514 
1515 inline void CEUDCSegTable::GetData(DWORD dwOffset,
1516                                    LPVOID lpData, DWORD cbData)
1517 {
1518     DASSERT(m_hTmpFile);
1519     DASSERT(m_hTmpCMapOffset);
1520     ::SetFilePointer(m_hTmpFile, m_hTmpCMapOffset + dwOffset,
1521         NULL, FILE_BEGIN);
1522     DWORD dwRead;
1523     VERIFY(::ReadFile(m_hTmpFile, lpData, cbData, &dwRead, NULL));
1524     DASSERT(dwRead == cbData);
1525 }
1526 
1527 void CEUDCSegTable::Create(LPCWSTR name)
1528 {
1529 typedef struct tagHEAD{
1530     FIXED   sfnt_version;
1531     USHORT  numTables;
1532     USHORT  searchRange;
1533     USHORT  entrySelector;
1534     USHORT  rangeShift;
1535 } HEAD, *PHEAD;
1536 
1537 typedef struct tagENTRY{
1538     ULONG   tag;
1539     ULONG   checkSum;
1540     ULONG   offset;
1541     ULONG   length;
1542 } ENTRY, *PENTRY;
1543 
1544     CSegTableComponent::Create(name);
1545 
1546     // create EUDC font file and make EUDCSegTable
1547     // after wrapper function for CreateFileW, we use only CreateFileW
1548     m_hTmpFile = ::CreateFile(name, GENERIC_READ,
1549                                FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1550     if (m_hTmpFile == INVALID_HANDLE_VALUE){
1551         m_hTmpFile = NULL;
1552         return;
1553     }
1554 
1555     HEAD head;
1556     DWORD dwRead;
1557     VERIFY(::ReadFile(m_hTmpFile, &head, sizeof(head), &dwRead, NULL));
1558     DASSERT(dwRead == sizeof(HEAD));
1559     SwapShort(head.numTables);
1560     ENTRY entry;
1561     for (int i = 0; i < head.numTables; i++){
1562         VERIFY(::ReadFile(m_hTmpFile, &entry, sizeof(entry), &dwRead, NULL));
1563         DASSERT(dwRead == sizeof(ENTRY));
1564         if (entry.tag == CMAPHEX)
1565             break;
1566     }
1567     DASSERT(entry.tag == CMAPHEX);
1568     SwapULong(entry.offset);
1569     m_hTmpCMapOffset = entry.offset;
1570 
1571     (void) MakeTable();
1572 
1573     m_hTmpCMapOffset = 0;
1574     VERIFY(::CloseHandle(m_hTmpFile));
1575     m_hTmpFile = NULL;
1576 }
1577 
1578 class CSegTableManagerComponent
1579 {
1580 public:
1581     CSegTableManagerComponent();
1582     ~CSegTableManagerComponent();
1583 
1584 protected:
1585     void MakeBiggerTable();
1586     CSegTableComponent **m_tables;
1587     int m_nTable;
1588     int m_nMaxTable;
1589 };
1590 
1591 #define TABLENUM 20
1592 
1593 CSegTableManagerComponent::CSegTableManagerComponent()
1594 {
1595     m_nTable = 0;
1596     m_nMaxTable = TABLENUM;
1597     m_tables = new CSegTableComponent*[m_nMaxTable];
1598 }
1599 
1600 CSegTableManagerComponent::~CSegTableManagerComponent()
1601 {
1602     for (int i = 0; i < m_nTable; i++) {
1603         DASSERT(m_tables[i]);
1604         delete m_tables[i];
1605     }
1606     delete [] m_tables;
1607     m_tables = NULL;
1608 }
1609 
1610 void CSegTableManagerComponent::MakeBiggerTable()
1611 {
1612     CSegTableComponent **tables =
1613         new CSegTableComponent*[m_nMaxTable + TABLENUM];
1614 
1615     for (int i = 0; i < m_nMaxTable; i++)
1616         tables[i] = m_tables[i];
1617 
1618     delete[] m_tables;
1619 
1620     m_tables = tables;
1621     m_nMaxTable += TABLENUM;
1622 }
1623 
1624 class CSegTableManager : public CSegTableManagerComponent
1625 {
1626 public:
1627     CSegTable* GetTable(LPCWSTR lpszFontName, BOOL fEUDC);
1628 };
1629 
1630 CSegTable* CSegTableManager::GetTable(LPCWSTR lpszFontName, BOOL fEUDC)
1631 {
1632     for (int i = 0; i < m_nTable; i++) {
1633         if ((((CSegTable*)m_tables[i])->IsEUDC() == fEUDC) &&
1634             (wcscmp(m_tables[i]->GetFontName(),lpszFontName) == 0))
1635             return (CSegTable*) m_tables[i];
1636     }
1637 
1638     if (m_nTable == m_nMaxTable) {
1639         (void) MakeBiggerTable();
1640     }
1641     DASSERT(m_nTable < m_nMaxTable);
1642 
1643     if (!fEUDC) {
1644         m_tables[m_nTable] = new CStdSegTable;
1645     } else {
1646         m_tables[m_nTable] = new CEUDCSegTable;
1647     }
1648     m_tables[m_nTable]->Create(lpszFontName);
1649     return (CSegTable*) m_tables[m_nTable++];
1650 }
1651 
1652 CSegTableManager g_segTableManager;
1653 
1654 class CCombinedSegTable : public CSegTableComponent
1655 {
1656 public:
1657     CCombinedSegTable();
1658     void Create(LPCWSTR name);
1659     BOOL In(USHORT iChar);
1660 
1661 private:
1662     LPSTR GetCodePageSubkey();
1663     void GetEUDCFileName(LPWSTR lpszFileName, int cchFileName);
1664     static char m_szCodePageSubkey[16];
1665     static WCHAR m_szDefaultEUDCFile[_MAX_PATH];
1666     static BOOL m_fEUDCSubKeyExist;
1667     static BOOL m_fTTEUDCFileExist;
1668     CStdSegTable* m_pStdSegTable;
1669     CEUDCSegTable* m_pEUDCSegTable;
1670 };
1671 
1672 char CCombinedSegTable::m_szCodePageSubkey[16] = "";
1673 
1674 WCHAR CCombinedSegTable::m_szDefaultEUDCFile[_MAX_PATH] = L"";
1675 
1676 BOOL CCombinedSegTable::m_fEUDCSubKeyExist = TRUE;
1677 
1678 BOOL CCombinedSegTable::m_fTTEUDCFileExist = TRUE;
1679 
1680 CCombinedSegTable::CCombinedSegTable()
1681 {
1682     m_pStdSegTable = NULL;
1683     m_pEUDCSegTable = NULL;
1684 }
1685 
1686 #include <locale.h>
1687 LPSTR CCombinedSegTable::GetCodePageSubkey()
1688 {
1689     if (strlen(m_szCodePageSubkey) > 0) {
1690         return m_szCodePageSubkey;
1691     }
1692 
1693     LPSTR lpszLocale = setlocale(LC_CTYPE, "");
1694     // cf lpszLocale = "Japanese_Japan.932"
1695     if (lpszLocale == NULL) {
1696         return NULL;
1697     }
1698     LPSTR lpszCP = strchr(lpszLocale, (int) '.');
1699     if (lpszCP == NULL) {
1700         return NULL;
1701     }
1702     lpszCP++; // cf lpszCP = "932"
1703 
1704     char szSubKey[80];
1705     strcpy(szSubKey, "EUDC\\");
1706     strcpy(&(szSubKey[strlen(szSubKey)]), lpszCP);
1707     strcpy(m_szCodePageSubkey, szSubKey);
1708     return m_szCodePageSubkey;
1709 }
1710 
1711 void CCombinedSegTable::GetEUDCFileName(LPWSTR lpszFileName, int cchFileName)
1712 {
1713     if (m_fEUDCSubKeyExist == FALSE)
1714         return;
1715 
1716     // get filename of typeface-specific TureType EUDC font
1717     LPSTR lpszSubKey = GetCodePageSubkey();
1718     if (lpszSubKey == NULL) {
1719         m_fEUDCSubKeyExist = FALSE;
1720         return; // can not get codepage information
1721     }
1722     HKEY hRootKey = HKEY_CURRENT_USER;
1723     HKEY hKey;
1724     LONG lRet = ::RegOpenKeyExA(hRootKey, lpszSubKey, 0, KEY_ALL_ACCESS, &hKey);
1725     if (lRet != ERROR_SUCCESS) {
1726         m_fEUDCSubKeyExist = FALSE;
1727         return; // no EUDC font
1728     }
1729 
1730     // get EUDC font file name
1731     WCHAR szFamilyName[80];
1732     wcscpy(szFamilyName, GetFontName());
1733     WCHAR* delimit = wcschr(szFamilyName, L',');
1734     if (delimit != NULL)
1735         *delimit = L'\0';
1736     DWORD dwType;
1737     UCHAR szFileName[_MAX_PATH];
1738     ::ZeroMemory(szFileName, sizeof(szFileName));
1739     DWORD dwBytes = sizeof(szFileName);
1740     // try Typeface-specific EUDC font
1741     char szTmpName[80];
1742     VERIFY(::WideCharToMultiByte(CP_ACP, 0, szFamilyName, -1,
1743         szTmpName, sizeof(szTmpName), NULL, NULL));
1744     LONG lStatus = ::RegQueryValueExA(hKey, (LPCSTR) szTmpName,
1745         NULL, &dwType, szFileName, &dwBytes);
1746     BOOL fUseDefault = FALSE;
1747     if (lStatus != ERROR_SUCCESS){ // try System default EUDC font
1748         if (m_fTTEUDCFileExist == FALSE)
1749             return;
1750         if (wcslen(m_szDefaultEUDCFile) > 0) {
1751             wcscpy(lpszFileName, m_szDefaultEUDCFile);
1752             return;
1753         }
1754         char szDefault[] = "SystemDefaultEUDCFont";
1755         lStatus = ::RegQueryValueExA(hKey, (LPCSTR) szDefault,
1756             NULL, &dwType, szFileName, &dwBytes);
1757         fUseDefault = TRUE;
1758         if (lStatus != ERROR_SUCCESS) {
1759             m_fTTEUDCFileExist = FALSE;
1760             // This font is associated with no EUDC font
1761             // and there is no system default EUDC font
1762             return;
1763         }
1764     }
1765 
1766     if (strcmp((LPCSTR) szFileName, "userfont.fon") == 0) {
1767         // This font is associated with no EUDC font
1768         // and the system default EUDC font is not TrueType
1769         m_fTTEUDCFileExist = FALSE;
1770         return;
1771     }
1772 
1773     DASSERT(strlen((LPCSTR)szFileName) > 0);
1774     VERIFY(::MultiByteToWideChar(CP_ACP, 0,
1775         (LPCSTR)szFileName, -1, lpszFileName, cchFileName) != 0);
1776     if (fUseDefault)
1777         wcscpy(m_szDefaultEUDCFile, lpszFileName);
1778 }
1779 
1780 void CCombinedSegTable::Create(LPCWSTR name)
1781 {
1782     CSegTableComponent::Create(name);
1783 
1784     m_pStdSegTable =
1785         (CStdSegTable*) g_segTableManager.GetTable(name, FALSE/*not EUDC*/);
1786     WCHAR szEUDCFileName[_MAX_PATH];
1787     ::ZeroMemory(szEUDCFileName, sizeof(szEUDCFileName));
1788     (void) GetEUDCFileName(szEUDCFileName,
1789         sizeof(szEUDCFileName)/sizeof(WCHAR));
1790     if (wcslen(szEUDCFileName) > 0) {
1791         m_pEUDCSegTable = (CEUDCSegTable*) g_segTableManager.GetTable(
1792             szEUDCFileName, TRUE/*EUDC*/);
1793         if (m_pEUDCSegTable->HasCmap() == FALSE)
1794             m_pEUDCSegTable = NULL;
1795     }
1796 }
1797 
1798 BOOL CCombinedSegTable::In(USHORT iChar)
1799 {
1800     DASSERT(m_pStdSegTable);
1801     if (m_pStdSegTable->In(iChar))
1802         return TRUE;
1803 
1804     if (m_pEUDCSegTable != NULL)
1805         return m_pEUDCSegTable->In(iChar);
1806 
1807     return FALSE;
1808 }
1809 
1810 class CCombinedSegTableManager : public CSegTableManagerComponent
1811 {
1812 public:
1813     CCombinedSegTable* GetTable(LPCWSTR lpszFontName);
1814 };
1815 
1816 CCombinedSegTable* CCombinedSegTableManager::GetTable(LPCWSTR lpszFontName)
1817 {
1818     for (int i = 0; i < m_nTable; i++) {
1819         if (wcscmp(m_tables[i]->GetFontName(),lpszFontName) == 0)
1820             return (CCombinedSegTable*) m_tables[i];
1821     }
1822 
1823     if (m_nTable == m_nMaxTable) {
1824         (void) MakeBiggerTable();
1825     }
1826     DASSERT(m_nTable < m_nMaxTable);
1827 
1828     m_tables[m_nTable] = new CCombinedSegTable;
1829     m_tables[m_nTable]->Create(lpszFontName);
1830 
1831     return (CCombinedSegTable*) m_tables[m_nTable++];
1832 }
1833 
1834 
1835 /************************************************************************
1836  * WDefaultFontCharset native methos
1837  */
1838 
1839 extern "C" {
1840 
1841 JNIEXPORT void JNICALL
1842 Java_sun_awt_windows_WDefaultFontCharset_initIDs(JNIEnv *env, jclass cls)
1843 {
1844     TRY;
1845 
1846     AwtFont::fontNameID = env->GetFieldID(cls, "fontName",
1847                                           "Ljava/lang/String;");
1848     DASSERT(AwtFont::fontNameID != NULL);
1849 
1850     CATCH_BAD_ALLOC;
1851 }
1852 
1853 
1854 /*
1855  * !!!!!!!!!!!!!!!!!!!! this does not work. I am not sure why, but
1856  * when active, this will reliably crash HJ, with no hope of debugging
1857  * for java.  It doesn't seem to crash the _g version.
1858  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!
1859  *
1860  * I suspect may be running out of C stack: see alloca in
1861  * JNI_GET_STRING, the alloca in it.
1862  *
1863  * (the method is prefixed with XXX so that the linker won't find it) */
1864 JNIEXPORT jboolean JNICALL
1865 Java_sun_awt_windows_WDefaultFontCharset_canConvert(JNIEnv *env, jobject self,
1866                                                     jchar ch)
1867 {
1868     TRY;
1869 
1870     static CCombinedSegTableManager tableManager;
1871 
1872     jstring fontName = (jstring)env->GetObjectField(self, AwtFont::fontNameID);
1873     DASSERT(fontName != NULL); // leave in for debug mode.
1874     CHECK_NULL_RETURN(fontName, FALSE);  // in production, just return
1875     LPCWSTR fontNameW = JNU_GetStringPlatformChars(env, fontName, NULL);
1876     CHECK_NULL_RETURN(fontNameW, FALSE);
1877     CCombinedSegTable* pTable = tableManager.GetTable(fontNameW);
1878     JNU_ReleaseStringPlatformChars(env, fontName, fontNameW);
1879     return (pTable->In((USHORT) ch) ? JNI_TRUE : JNI_FALSE);
1880 
1881     CATCH_BAD_ALLOC_RET(FALSE);
1882 }
1883 
1884 } /* extern "C" */