1 /*
   2  * Copyright (c) 2003, 2020, 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 package sun.font;
  27 
  28 import java.awt.Font;
  29 import java.awt.FontFormatException;
  30 import java.awt.GraphicsEnvironment;
  31 import java.awt.geom.Point2D;
  32 import java.io.FileNotFoundException;
  33 import java.io.IOException;
  34 import java.io.RandomAccessFile;
  35 import java.io.UnsupportedEncodingException;
  36 import java.nio.ByteBuffer;
  37 import java.nio.CharBuffer;
  38 import java.nio.IntBuffer;
  39 import java.nio.ShortBuffer;
  40 import java.nio.channels.ClosedChannelException;
  41 import java.nio.channels.FileChannel;
  42 import java.security.AccessController;
  43 import java.security.PrivilegedActionException;
  44 import java.security.PrivilegedExceptionAction;
  45 import java.util.HashMap;
  46 import java.util.HashSet;
  47 import java.util.Locale;
  48 import java.util.Map;
  49 
  50 import sun.java2d.Disposer;
  51 import sun.java2d.DisposerRecord;
  52 import sun.security.action.GetPropertyAction;
  53 
  54 /**
  55  * TrueTypeFont is not called SFntFont because it is not expected
  56  * to handle all types that may be housed in a such a font file.
  57  * If additional types are supported later, it may make sense to
  58  * create an SFnt superclass. Eg to handle sfnt-housed postscript fonts.
  59  * OpenType fonts are handled by this class, and possibly should be
  60  * represented by a subclass.
  61  * An instance stores some information from the font file to faciliate
  62  * faster access. File size, the table directory and the names of the font
  63  * are the most important of these. It amounts to approx 400 bytes
  64  * for a typical font. Systems with mutiple locales sometimes have up to 400
  65  * font files, and an app which loads all font files would need around
  66  * 160Kbytes. So storing any more info than this would be expensive.
  67  */
  68 public class TrueTypeFont extends FileFont {
  69 
  70    /* -- Tags for required TrueType tables */
  71     public static final int cmapTag = 0x636D6170; // 'cmap'
  72     public static final int glyfTag = 0x676C7966; // 'glyf'
  73     public static final int headTag = 0x68656164; // 'head'
  74     public static final int hheaTag = 0x68686561; // 'hhea'
  75     public static final int hmtxTag = 0x686D7478; // 'hmtx'
  76     public static final int locaTag = 0x6C6F6361; // 'loca'
  77     public static final int maxpTag = 0x6D617870; // 'maxp'
  78     public static final int nameTag = 0x6E616D65; // 'name'
  79     public static final int postTag = 0x706F7374; // 'post'
  80     public static final int os_2Tag = 0x4F532F32; // 'OS/2'
  81 
  82     /* -- Tags for opentype related tables */
  83     public static final int GDEFTag = 0x47444546; // 'GDEF'
  84     public static final int GPOSTag = 0x47504F53; // 'GPOS'
  85     public static final int GSUBTag = 0x47535542; // 'GSUB'
  86     public static final int mortTag = 0x6D6F7274; // 'mort'
  87     public static final int morxTag = 0x6D6F7278; // 'morx'
  88 
  89     /* -- Tags for non-standard tables */
  90     public static final int fdscTag = 0x66647363; // 'fdsc' - gxFont descriptor
  91     public static final int fvarTag = 0x66766172; // 'fvar' - gxFont variations
  92     public static final int featTag = 0x66656174; // 'feat' - layout features
  93     public static final int EBLCTag = 0x45424C43; // 'EBLC' - embedded bitmaps
  94     public static final int gaspTag = 0x67617370; // 'gasp' - hint/smooth sizes
  95 
  96     /* --  Other tags */
  97     public static final int ttcfTag = 0x74746366; // 'ttcf' - TTC file
  98     public static final int v1ttTag = 0x00010000; // 'v1tt' - Version 1 TT font
  99     public static final int trueTag = 0x74727565; // 'true' - Version 2 TT font
 100     public static final int ottoTag = 0x4f54544f; // 'otto' - OpenType font
 101 
 102     /* -- ID's used in the 'name' table */
 103     public static final int MAC_PLATFORM_ID = 1;
 104     public static final int MACROMAN_SPECIFIC_ID = 0;
 105     public static final int MACROMAN_ENGLISH_LANG = 0;
 106 
 107     public static final int MS_PLATFORM_ID = 3;
 108     /* MS locale id for US English is the "default" */
 109     public static final short ENGLISH_LOCALE_ID = 0x0409; // 1033 decimal
 110     public static final int FAMILY_NAME_ID = 1;
 111     // public static final int STYLE_WEIGHT_ID = 2; // currently unused.
 112     public static final int FULL_NAME_ID = 4;
 113     public static final int POSTSCRIPT_NAME_ID = 6;
 114 
 115     private static final short US_LCID = 0x0409;  // US English - default
 116 
 117     private static Map<String, Short> lcidMap;
 118 
 119     static class DirectoryEntry {
 120         int tag;
 121         int offset;
 122         int length;
 123     }
 124 
 125     /* There is a pool which limits the number of fd's that are in
 126      * use. Normally fd's are closed as they are replaced in the pool.
 127      * But if an instance of this class becomes unreferenced, then there
 128      * needs to be a way to close the fd. A finalize() method could do this,
 129      * but using the Disposer class will ensure its called in a more timely
 130      * manner. This is not something which should be relied upon to free
 131      * fd's - its a safeguard.
 132      */
 133     private static class TTDisposerRecord implements DisposerRecord {
 134 
 135         FileChannel channel = null;
 136 
 137         public synchronized void dispose() {
 138             try {
 139                 if (channel != null) {
 140                     channel.close();
 141                 }
 142             } catch (IOException e) {
 143             } finally {
 144                 channel = null;
 145             }
 146         }
 147     }
 148 
 149     TTDisposerRecord disposerRecord = new TTDisposerRecord();
 150 
 151     /* > 0 only if this font is a part of a collection */
 152     int fontIndex = 0;
 153 
 154     /* Number of fonts in this collection. ==1 if not a collection */
 155     int directoryCount = 1;
 156 
 157     /* offset in file of table directory for this font */
 158     int directoryOffset; // 12 if its not a collection.
 159 
 160     /* number of table entries in the directory/offsets table */
 161     int numTables;
 162 
 163     /* The contents of the directory/offsets table */
 164     DirectoryEntry []tableDirectory;
 165 
 166 //     protected byte []gposTable = null;
 167 //     protected byte []gdefTable = null;
 168 //     protected byte []gsubTable = null;
 169 //     protected byte []mortTable = null;
 170 //     protected boolean hintsTabledChecked = false;
 171 //     protected boolean containsHintsTable = false;
 172 
 173     /* These fields are set from os/2 table info. */
 174     private boolean supportsJA;
 175     private boolean supportsCJK;
 176 
 177     /* These are for faster access to the name of the font as
 178      * typically exposed via API to applications.
 179      */
 180     private Locale nameLocale;
 181     private String localeFamilyName;
 182     private String localeFullName;
 183 
 184     /*
 185      * Used on Windows to validate the font selected by GDI for (sub-pixel
 186      * antialiased) rendering. For 'standalone' fonts it's equal to the font
 187      * file size, for collection (TTC, OTC) members it's the number of bytes in
 188      * the collection file from the start of this font's offset table till the
 189      * end of the file.
 190      */
 191     int fontDataSize;
 192 
 193     public TrueTypeFont(String platname, Object nativeNames, int fIndex,
 194                  boolean javaRasterizer)
 195         throws FontFormatException
 196     {
 197         this(platname, nativeNames, fIndex, javaRasterizer, true);
 198     }
 199 
 200     /**
 201      * - does basic verification of the file
 202      * - reads the header table for this font (within a collection)
 203      * - reads the names (full, family).
 204      * - determines the style of the font.
 205      * - initializes the CMAP
 206      * @throws FontFormatException if the font can't be opened
 207      * or fails verification,  or there's no usable cmap
 208      */
 209     public TrueTypeFont(String platname, Object nativeNames, int fIndex,
 210                  boolean javaRasterizer, boolean useFilePool)
 211         throws FontFormatException {
 212         super(platname, nativeNames);
 213         useJavaRasterizer = javaRasterizer;
 214         fontRank = Font2D.TTF_RANK;
 215         try {
 216             verify(useFilePool);
 217             init(fIndex);
 218             if (!useFilePool) {
 219                close();
 220             }
 221         } catch (Throwable t) {
 222             close();
 223             if (t instanceof FontFormatException) {
 224                 throw (FontFormatException)t;
 225             } else {
 226                 throw new FontFormatException("Unexpected runtime exception.");
 227             }
 228         }
 229         Disposer.addObjectRecord(this, disposerRecord);
 230     }
 231 
 232     /* Enable natives just for fonts picked up from the platform that
 233      * may have external bitmaps on Solaris. Could do this just for
 234      * the fonts that are specified in font configuration files which
 235      * would lighten the burden (think about that).
 236      * The EBLCTag is used to skip natives for fonts that contain embedded
 237      * bitmaps as there's no need to use X11 for those fonts.
 238      * Skip all the latin fonts as they don't need this treatment.
 239      * Further refine this to fonts that are natively accessible (ie
 240      * as PCF bitmap fonts on the X11 font path).
 241      * This method is called when creating the first strike for this font.
 242      */
 243     @Override
 244     protected boolean checkUseNatives() {
 245         if (checkedNatives) {
 246             return useNatives;
 247         }
 248         if (!FontUtilities.isSolaris || useJavaRasterizer ||
 249             FontUtilities.useJDKScaler || nativeNames == null ||
 250             getDirectoryEntry(EBLCTag) != null ||
 251             GraphicsEnvironment.isHeadless()) {
 252             checkedNatives = true;
 253             return false; /* useNatives is false */
 254         } else if (nativeNames instanceof String) {
 255             String name = (String)nativeNames;
 256             /* Don't do this for Latin fonts */
 257             if (name.indexOf("8859") > 0) {
 258                 checkedNatives = true;
 259                 return false;
 260             } else if (NativeFont.hasExternalBitmaps(name)) {
 261                 nativeFonts = new NativeFont[1];
 262                 try {
 263                     nativeFonts[0] = new NativeFont(name, true);
 264                     /* If reach here we have an non-latin font that has
 265                      * external bitmaps and we successfully created it.
 266                      */
 267                     useNatives = true;
 268                 } catch (FontFormatException e) {
 269                     nativeFonts = null;
 270                 }
 271             }
 272         } else if (nativeNames instanceof String[]) {
 273             String[] natNames = (String[])nativeNames;
 274             int numNames = natNames.length;
 275             boolean externalBitmaps = false;
 276             for (int nn = 0; nn < numNames; nn++) {
 277                 if (natNames[nn].indexOf("8859") > 0) {
 278                     checkedNatives = true;
 279                     return false;
 280                 } else if (NativeFont.hasExternalBitmaps(natNames[nn])) {
 281                     externalBitmaps = true;
 282                 }
 283             }
 284             if (!externalBitmaps) {
 285                 checkedNatives = true;
 286                 return false;
 287             }
 288             useNatives = true;
 289             nativeFonts = new NativeFont[numNames];
 290             for (int nn = 0; nn < numNames; nn++) {
 291                 try {
 292                     nativeFonts[nn] = new NativeFont(natNames[nn], true);
 293                 } catch (FontFormatException e) {
 294                     useNatives = false;
 295                     nativeFonts = null;
 296                 }
 297             }
 298         }
 299         if (useNatives) {
 300             glyphToCharMap = new char[getMapper().getNumGlyphs()];
 301         }
 302         checkedNatives = true;
 303         return useNatives;
 304     }
 305 
 306 
 307     private synchronized FileChannel open() throws FontFormatException {
 308         return open(true);
 309      }
 310 
 311     /* This is intended to be called, and the returned value used,
 312      * from within a block synchronized on this font object.
 313      * ie the channel returned may be nulled out at any time by "close()"
 314      * unless the caller holds a lock.
 315      * Deadlock warning: FontManager.addToPool(..) acquires a global lock,
 316      * which means nested locks may be in effect.
 317      */
 318     private synchronized FileChannel open(boolean usePool)
 319                                      throws FontFormatException {
 320         if (disposerRecord.channel == null) {
 321             if (FontUtilities.isLogging()) {
 322                 FontUtilities.getLogger().info("open TTF: " + platName);
 323             }
 324             try {
 325                 RandomAccessFile raf = AccessController.doPrivileged(
 326                     new PrivilegedExceptionAction<RandomAccessFile>() {
 327                         public RandomAccessFile run() throws FileNotFoundException {
 328                             return new RandomAccessFile(platName, "r");
 329                     }
 330                 });
 331                 disposerRecord.channel = raf.getChannel();
 332                 fileSize = (int)disposerRecord.channel.size();
 333                 if (usePool) {
 334                     FontManager fm = FontManagerFactory.getInstance();
 335                     if (fm instanceof SunFontManager) {
 336                         ((SunFontManager) fm).addToPool(this);
 337                     }
 338                 }
 339             } catch (PrivilegedActionException e) {
 340                 close();
 341                 Throwable reason = e.getCause();
 342                 if (reason == null) {
 343                     reason = e;
 344                 }
 345                 throw new FontFormatException(reason.toString());
 346             } catch (ClosedChannelException e) {
 347                 /* NIO I/O is interruptible, recurse to retry operation.
 348                  * The call to channel.size() above can throw this exception.
 349                  * Clear interrupts before recursing in case NIO didn't.
 350                  * Note that close() sets disposerRecord.channel to null.
 351                  */
 352                 Thread.interrupted();
 353                 close();
 354                 open();
 355             } catch (IOException e) {
 356                 close();
 357                 throw new FontFormatException(e.toString());
 358             }
 359         }
 360         return disposerRecord.channel;
 361     }
 362 
 363     protected synchronized void close() {
 364         disposerRecord.dispose();
 365     }
 366 
 367 
 368     int readBlock(ByteBuffer buffer, int offset, int length) {
 369         int bread = 0;
 370         try {
 371             synchronized (this) {
 372                 if (disposerRecord.channel == null) {
 373                     open();
 374                 }
 375                 if (offset + length > fileSize) {
 376                     if (offset >= fileSize) {
 377                         /* Since the caller ensures that offset is < fileSize
 378                          * this condition suggests that fileSize is now
 379                          * different than the value we originally provided
 380                          * to native when the scaler was created.
 381                          * Also fileSize is updated every time we
 382                          * open() the file here, but in native the value
 383                          * isn't updated. If the file has changed whilst we
 384                          * are executing we want to bail, not spin.
 385                          */
 386                         if (FontUtilities.isLogging()) {
 387                             String msg = "Read offset is " + offset +
 388                                 " file size is " + fileSize+
 389                                 " file is " + platName;
 390                             FontUtilities.getLogger().severe(msg);
 391                         }
 392                         return -1;
 393                     } else {
 394                         length = fileSize - offset;
 395                     }
 396                 }
 397                 buffer.clear();
 398                 disposerRecord.channel.position(offset);
 399                 while (bread < length) {
 400                     int cnt = disposerRecord.channel.read(buffer);
 401                     if (cnt == -1) {
 402                         String msg = "Unexpected EOF " + this;
 403                         int currSize = (int)disposerRecord.channel.size();
 404                         if (currSize != fileSize) {
 405                             msg += " File size was " + fileSize +
 406                                 " and now is " + currSize;
 407                         }
 408                         if (FontUtilities.isLogging()) {
 409                             FontUtilities.getLogger().severe(msg);
 410                         }
 411                         // We could still flip() the buffer here because
 412                         // it's possible that we did read some data in
 413                         // an earlier loop, and we probably should
 414                         // return that to the caller. Although if
 415                         // the caller expected 8K of data and we return
 416                         // only a few bytes then maybe it's better instead to
 417                         // set bread = -1 to indicate failure.
 418                         // The following is therefore using arbitrary values
 419                         // but is meant to allow cases where enough
 420                         // data was read to probably continue.
 421                         if (bread > length/2 || bread > 16384) {
 422                             buffer.flip();
 423                             if (FontUtilities.isLogging()) {
 424                                 msg = "Returning " + bread +
 425                                     " bytes instead of " + length;
 426                                 FontUtilities.getLogger().severe(msg);
 427                             }
 428                         } else {
 429                             bread = -1;
 430                         }
 431                         throw new IOException(msg);
 432                     }
 433                     bread += cnt;
 434                 }
 435                 buffer.flip();
 436                 if (bread > length) { // possible if buffer.size() > length
 437                     bread = length;
 438                 }
 439             }
 440         } catch (FontFormatException e) {
 441             if (FontUtilities.isLogging()) {
 442                 FontUtilities.getLogger().severe(
 443                                        "While reading " + platName, e);
 444             }
 445             bread = -1; // signal EOF
 446             deregisterFontAndClearStrikeCache();
 447         } catch (ClosedChannelException e) {
 448             /* NIO I/O is interruptible, recurse to retry operation.
 449              * Clear interrupts before recursing in case NIO didn't.
 450              */
 451             Thread.interrupted();
 452             close();
 453             return readBlock(buffer, offset, length);
 454         } catch (IOException e) {
 455             /* If we did not read any bytes at all and the exception is
 456              * not a recoverable one (ie is not ClosedChannelException) then
 457              * we should indicate that there is no point in re-trying.
 458              * Other than an attempt to read past the end of the file it
 459              * seems unlikely this would occur as problems opening the
 460              * file are handled as a FontFormatException.
 461              */
 462             if (FontUtilities.isLogging()) {
 463                 FontUtilities.getLogger().severe(
 464                                        "While reading " + platName, e);
 465             }
 466             if (bread == 0) {
 467                 bread = -1; // signal EOF
 468                 deregisterFontAndClearStrikeCache();
 469             }
 470         }
 471         return bread;
 472     }
 473 
 474     ByteBuffer readBlock(int offset, int length) {
 475 
 476         ByteBuffer buffer = ByteBuffer.allocate(length);
 477         try {
 478             synchronized (this) {
 479                 if (disposerRecord.channel == null) {
 480                     open();
 481                 }
 482                 if (offset + length > fileSize) {
 483                     if (offset > fileSize) {
 484                         return null; // assert?
 485                     } else {
 486                         buffer = ByteBuffer.allocate(fileSize-offset);
 487                     }
 488                 }
 489                 disposerRecord.channel.position(offset);
 490                 disposerRecord.channel.read(buffer);
 491                 buffer.flip();
 492             }
 493         } catch (FontFormatException e) {
 494             return null;
 495         } catch (ClosedChannelException e) {
 496             /* NIO I/O is interruptible, recurse to retry operation.
 497              * Clear interrupts before recursing in case NIO didn't.
 498              */
 499             Thread.interrupted();
 500             close();
 501             readBlock(buffer, offset, length);
 502         } catch (IOException e) {
 503             return null;
 504         }
 505         return buffer;
 506     }
 507 
 508     /* This is used by native code which can't allocate a direct byte
 509      * buffer because of bug 4845371. It, and references to it in native
 510      * code in scalerMethods.c can be removed once that bug is fixed.
 511      * 4845371 is now fixed but we'll keep this around as it doesn't cost
 512      * us anything if its never used/called.
 513      */
 514     byte[] readBytes(int offset, int length) {
 515         ByteBuffer buffer = readBlock(offset, length);
 516         if (buffer.hasArray()) {
 517             return buffer.array();
 518         } else {
 519             byte[] bufferBytes = new byte[buffer.limit()];
 520             buffer.get(bufferBytes);
 521             return bufferBytes;
 522         }
 523     }
 524 
 525     private void verify(boolean usePool) throws FontFormatException {
 526         open(usePool);
 527     }
 528 
 529     /* sizes, in bytes, of TT/TTC header records */
 530     private static final int TTCHEADERSIZE = 12;
 531     private static final int DIRECTORYHEADERSIZE = 12;
 532     private static final int DIRECTORYENTRYSIZE = 16;
 533 
 534     protected void init(int fIndex) throws FontFormatException  {
 535         int headerOffset = 0;
 536         ByteBuffer buffer = readBlock(0, TTCHEADERSIZE);
 537         try {
 538             switch (buffer.getInt()) {
 539 
 540             case ttcfTag:
 541                 buffer.getInt(); // skip TTC version ID
 542                 directoryCount = buffer.getInt();
 543                 if (fIndex >= directoryCount) {
 544                     throw new FontFormatException("Bad collection index");
 545                 }
 546                 fontIndex = fIndex;
 547                 buffer = readBlock(TTCHEADERSIZE+4*fIndex, 4);
 548                 headerOffset = buffer.getInt();
 549                 fontDataSize = Math.max(0, fileSize - headerOffset);
 550                 break;
 551 
 552             case v1ttTag:
 553             case trueTag:
 554             case ottoTag:
 555                 fontDataSize = fileSize;
 556                 break;
 557 
 558             default:
 559                 throw new FontFormatException("Unsupported sfnt " +
 560                                               getPublicFileName());
 561             }
 562 
 563             /* Now have the offset of this TT font (possibly within a TTC)
 564              * After the TT version/scaler type field, is the short
 565              * representing the number of tables in the table directory.
 566              * The table directory begins at 12 bytes after the header.
 567              * Each table entry is 16 bytes long (4 32-bit ints)
 568              */
 569             buffer = readBlock(headerOffset+4, 2);
 570             numTables = buffer.getShort();
 571             directoryOffset = headerOffset+DIRECTORYHEADERSIZE;
 572             ByteBuffer bbuffer = readBlock(directoryOffset,
 573                                            numTables*DIRECTORYENTRYSIZE);
 574             IntBuffer ibuffer = bbuffer.asIntBuffer();
 575             DirectoryEntry table;
 576             tableDirectory = new DirectoryEntry[numTables];
 577             for (int i=0; i<numTables;i++) {
 578                 tableDirectory[i] = table = new DirectoryEntry();
 579                 table.tag   =  ibuffer.get();
 580                 /* checksum */ ibuffer.get();
 581                 table.offset = ibuffer.get();
 582                 table.length = ibuffer.get();
 583                 if (table.offset + table.length > fileSize) {
 584                     throw new FontFormatException("bad table, tag="+table.tag);
 585                 }
 586             }
 587 
 588             if (getDirectoryEntry(headTag) == null) {
 589                 throw new FontFormatException("missing head table");
 590             }
 591             if (getDirectoryEntry(maxpTag) == null) {
 592                 throw new FontFormatException("missing maxp table");
 593             }
 594             if (getDirectoryEntry(hmtxTag) != null
 595                     && getDirectoryEntry(hheaTag) == null) {
 596                 throw new FontFormatException("missing hhea table");
 597             }
 598             initNames();
 599         } catch (Exception e) {
 600             if (FontUtilities.isLogging()) {
 601                 FontUtilities.getLogger().severe(e.toString());
 602             }
 603             if (e instanceof FontFormatException) {
 604                 throw (FontFormatException)e;
 605             } else {
 606                 throw new FontFormatException(e.toString());
 607             }
 608         }
 609         if (familyName == null || fullName == null) {
 610             throw new FontFormatException("Font name not found");
 611         }
 612         /* The os2_Table is needed to gather some info, but we don't
 613          * want to keep it around (as a field) so obtain it once and
 614          * pass it to the code that needs it.
 615          */
 616         ByteBuffer os2_Table = getTableBuffer(os_2Tag);
 617         setStyle(os2_Table);
 618         setCJKSupport(os2_Table);
 619     }
 620 
 621     /* The array index corresponds to a bit offset in the TrueType
 622      * font's OS/2 compatibility table's code page ranges fields.
 623      * These are two 32 bit unsigned int fields at offsets 78 and 82.
 624      * We are only interested in determining if the font supports
 625      * the windows encodings we expect as the default encoding in
 626      * supported locales, so we only map the first of these fields.
 627      */
 628     static final String[] encoding_mapping = {
 629         "cp1252",    /*  0:Latin 1  */
 630         "cp1250",    /*  1:Latin 2  */
 631         "cp1251",    /*  2:Cyrillic */
 632         "cp1253",    /*  3:Greek    */
 633         "cp1254",    /*  4:Turkish/Latin 5  */
 634         "cp1255",    /*  5:Hebrew   */
 635         "cp1256",    /*  6:Arabic   */
 636         "cp1257",    /*  7:Windows Baltic   */
 637         "",          /*  8:reserved for alternate ANSI */
 638         "",          /*  9:reserved for alternate ANSI */
 639         "",          /* 10:reserved for alternate ANSI */
 640         "",          /* 11:reserved for alternate ANSI */
 641         "",          /* 12:reserved for alternate ANSI */
 642         "",          /* 13:reserved for alternate ANSI */
 643         "",          /* 14:reserved for alternate ANSI */
 644         "",          /* 15:reserved for alternate ANSI */
 645         "ms874",     /* 16:Thai     */
 646         "ms932",     /* 17:JIS/Japanese */
 647         "gbk",       /* 18:PRC GBK Cp950  */
 648         "ms949",     /* 19:Korean Extended Wansung */
 649         "ms950",     /* 20:Chinese (Taiwan, Hongkong, Macau) */
 650         "ms1361",    /* 21:Korean Johab */
 651         "",          /* 22 */
 652         "",          /* 23 */
 653         "",          /* 24 */
 654         "",          /* 25 */
 655         "",          /* 26 */
 656         "",          /* 27 */
 657         "",          /* 28 */
 658         "",          /* 29 */
 659         "",          /* 30 */
 660         "",          /* 31 */
 661     };
 662 
 663     /* This maps two letter language codes to a Windows code page.
 664      * Note that eg Cp1252 (the first subarray) is not exactly the same as
 665      * Latin-1 since Windows code pages are do not necessarily correspond.
 666      * There are two codepages for zh and ko so if a font supports
 667      * only one of these ranges then we need to distinguish based on
 668      * country. So far this only seems to matter for zh.
 669      * REMIND: Unicode locales such as Hindi do not have a code page so
 670      * this whole mechanism needs to be revised to map languages to
 671      * the Unicode ranges either when this fails, or as an additional
 672      * validating test. Basing it on Unicode ranges should get us away
 673      * from needing to map to this small and incomplete set of Windows
 674      * code pages which looks odd on non-Windows platforms.
 675      */
 676     private static final String[][] languages = {
 677 
 678         /* cp1252/Latin 1 */
 679         { "en", "ca", "da", "de", "es", "fi", "fr", "is", "it",
 680           "nl", "no", "pt", "sq", "sv", },
 681 
 682          /* cp1250/Latin2 */
 683         { "cs", "cz", "et", "hr", "hu", "nr", "pl", "ro", "sk",
 684           "sl", "sq", "sr", },
 685 
 686         /* cp1251/Cyrillic */
 687         { "bg", "mk", "ru", "sh", "uk" },
 688 
 689         /* cp1253/Greek*/
 690         { "el" },
 691 
 692          /* cp1254/Turkish,Latin 5 */
 693         { "tr" },
 694 
 695          /* cp1255/Hebrew */
 696         { "he" },
 697 
 698         /* cp1256/Arabic */
 699         { "ar" },
 700 
 701          /* cp1257/Windows Baltic */
 702         { "et", "lt", "lv" },
 703 
 704         /* ms874/Thai */
 705         { "th" },
 706 
 707          /* ms932/Japanese */
 708         { "ja" },
 709 
 710         /* gbk/Chinese (PRC GBK Cp950) */
 711         { "zh", "zh_CN", },
 712 
 713         /* ms949/Korean Extended Wansung */
 714         { "ko" },
 715 
 716         /* ms950/Chinese (Taiwan, Hongkong, Macau) */
 717         { "zh_HK", "zh_TW", },
 718 
 719         /* ms1361/Korean Johab */
 720         { "ko" },
 721     };
 722 
 723     private static final String[] codePages = {
 724         "cp1252",
 725         "cp1250",
 726         "cp1251",
 727         "cp1253",
 728         "cp1254",
 729         "cp1255",
 730         "cp1256",
 731         "cp1257",
 732         "ms874",
 733         "ms932",
 734         "gbk",
 735         "ms949",
 736         "ms950",
 737         "ms1361",
 738     };
 739 
 740     private static String defaultCodePage = null;
 741     static String getCodePage() {
 742 
 743         if (defaultCodePage != null) {
 744             return defaultCodePage;
 745         }
 746 
 747         if (FontUtilities.isWindows) {
 748             defaultCodePage =
 749                 AccessController.doPrivileged(new GetPropertyAction("file.encoding"));
 750         } else {
 751             if (languages.length != codePages.length) {
 752                 throw new InternalError("wrong code pages array length");
 753             }
 754             Locale locale = sun.awt.SunToolkit.getStartupLocale();
 755 
 756             String language = locale.getLanguage();
 757             if (language != null) {
 758                 if (language.equals("zh")) {
 759                     String country = locale.getCountry();
 760                     if (country != null) {
 761                         language = language + "_" + country;
 762                     }
 763                 }
 764                 for (int i=0; i<languages.length;i++) {
 765                     for (int l=0;l<languages[i].length; l++) {
 766                         if (language.equals(languages[i][l])) {
 767                             defaultCodePage = codePages[i];
 768                             return defaultCodePage;
 769                         }
 770                     }
 771                 }
 772             }
 773         }
 774         if (defaultCodePage == null) {
 775             defaultCodePage = "";
 776         }
 777         return defaultCodePage;
 778     }
 779 
 780     /* Theoretically, reserved bits must not be set, include symbol bits */
 781     public static final int reserved_bits1 = 0x80000000;
 782     public static final int reserved_bits2 = 0x0000ffff;
 783     @Override
 784     boolean supportsEncoding(String encoding) {
 785         if (encoding == null) {
 786             encoding = getCodePage();
 787         }
 788         if ("".equals(encoding)) {
 789             return false;
 790         }
 791 
 792         encoding = encoding.toLowerCase();
 793 
 794         /* java_props_md.c has a couple of special cases
 795          * if language packs are installed. In these encodings the
 796          * fontconfig files pick up different fonts :
 797          * SimSun-18030 and MingLiU_HKSCS. Since these fonts will
 798          * indicate they support the base encoding, we need to rewrite
 799          * these encodings here before checking the map/array.
 800          */
 801         if (encoding.equals("gb18030")) {
 802             encoding = "gbk";
 803         } else if (encoding.equals("ms950_hkscs")) {
 804             encoding = "ms950";
 805         }
 806 
 807         ByteBuffer buffer = getTableBuffer(os_2Tag);
 808         /* required info is at offsets 78 and 82 */
 809         if (buffer == null || buffer.capacity() < 86) {
 810             return false;
 811         }
 812 
 813         int range1 = buffer.getInt(78); /* ulCodePageRange1 */
 814         // int range2 = buffer.getInt(82); /* ulCodePageRange2 */
 815 
 816         /* This test is too stringent for Arial on Solaris (and perhaps
 817          * other fonts). Arial has at least one reserved bit set for an
 818          * unknown reason.
 819          */
 820         // if (((range1 & reserved_bits1) | (range2 & reserved_bits2)) != 0) {
 821         //     return false;
 822         // }
 823 
 824         for (int em=0; em<encoding_mapping.length; em++) {
 825             if (encoding_mapping[em].equals(encoding)) {
 826                 if (((1 << em) & range1) != 0) {
 827                     return true;
 828                 }
 829             }
 830         }
 831         return false;
 832     }
 833 
 834 
 835     /* Use info in the os_2Table to test CJK support */
 836     private void setCJKSupport(ByteBuffer os2Table) {
 837         /* required info is in ulong at offset 46 */
 838         if (os2Table == null || os2Table.capacity() < 50) {
 839             return;
 840         }
 841         int range2 = os2Table.getInt(46); /* ulUnicodeRange2 */
 842 
 843         /* Any of these bits set in the 32-63 range indicate a font with
 844          * support for a CJK range. We aren't looking at some other bits
 845          * in the 64-69 range such as half width forms as its unlikely a font
 846          * would include those and none of these.
 847          */
 848         supportsCJK = ((range2 & 0x29bf0000) != 0);
 849 
 850         /* This should be generalised, but for now just need to know if
 851          * Hiragana or Katakana ranges are supported by the font.
 852          * In the 4 longs representing unicode ranges supported
 853          * bits 49 & 50 indicate hiragana and katakana
 854          * This is bits 17 & 18 in the 2nd ulong. If either is supported
 855          * we presume this is a JA font.
 856          */
 857         supportsJA = ((range2 & 0x60000) != 0);
 858     }
 859 
 860     boolean supportsJA() {
 861         return supportsJA;
 862     }
 863 
 864      ByteBuffer getTableBuffer(int tag) {
 865         DirectoryEntry entry = null;
 866 
 867         for (int i=0;i<numTables;i++) {
 868             if (tableDirectory[i].tag == tag) {
 869                 entry = tableDirectory[i];
 870                 break;
 871             }
 872         }
 873         if (entry == null || entry.length == 0 ||
 874             entry.offset+entry.length > fileSize) {
 875             return null;
 876         }
 877 
 878         int bread = 0;
 879         ByteBuffer buffer = ByteBuffer.allocate(entry.length);
 880         synchronized (this) {
 881             try {
 882                 if (disposerRecord.channel == null) {
 883                     open();
 884                 }
 885                 disposerRecord.channel.position(entry.offset);
 886                 bread = disposerRecord.channel.read(buffer);
 887                 buffer.flip();
 888             } catch (ClosedChannelException e) {
 889                 /* NIO I/O is interruptible, recurse to retry operation.
 890                  * Clear interrupts before recursing in case NIO didn't.
 891                  */
 892                 Thread.interrupted();
 893                 close();
 894                 return getTableBuffer(tag);
 895             } catch (IOException e) {
 896                 return null;
 897             } catch (FontFormatException e) {
 898                 return null;
 899             }
 900 
 901             if (bread < entry.length) {
 902                 return null;
 903             } else {
 904                 return buffer;
 905             }
 906         }
 907     }
 908 
 909     @Override
 910     protected byte[] getTableBytes(int tag) {
 911         ByteBuffer buffer = getTableBuffer(tag);
 912         if (buffer == null) {
 913             return null;
 914         } else if (buffer.hasArray()) {
 915             try {
 916                 return buffer.array();
 917             } catch (Exception re) {
 918             }
 919         }
 920         byte []data = new byte[getTableSize(tag)];
 921         buffer.get(data);
 922         return data;
 923     }
 924 
 925     int getTableSize(int tag) {
 926         for (int i=0;i<numTables;i++) {
 927             if (tableDirectory[i].tag == tag) {
 928                 return tableDirectory[i].length;
 929             }
 930         }
 931         return 0;
 932     }
 933 
 934     int getTableOffset(int tag) {
 935         for (int i=0;i<numTables;i++) {
 936             if (tableDirectory[i].tag == tag) {
 937                 return tableDirectory[i].offset;
 938             }
 939         }
 940         return 0;
 941     }
 942 
 943     DirectoryEntry getDirectoryEntry(int tag) {
 944         for (int i=0;i<numTables;i++) {
 945             if (tableDirectory[i].tag == tag) {
 946                 return tableDirectory[i];
 947             }
 948         }
 949         return null;
 950     }
 951 
 952     /* Used to determine if this size has embedded bitmaps, which
 953      * for CJK fonts should be used in preference to LCD glyphs.
 954      */
 955     boolean useEmbeddedBitmapsForSize(int ptSize) {
 956         if (!supportsCJK) {
 957             return false;
 958         }
 959         if (getDirectoryEntry(EBLCTag) == null) {
 960             return false;
 961         }
 962         ByteBuffer eblcTable = getTableBuffer(EBLCTag);
 963         int numSizes = eblcTable.getInt(4);
 964         /* The bitmapSizeTable's start at offset of 8.
 965          * Each bitmapSizeTable entry is 48 bytes.
 966          * The offset of ppemY in the entry is 45.
 967          */
 968         for (int i=0;i<numSizes;i++) {
 969             int ppemY = eblcTable.get(8+(i*48)+45) &0xff;
 970             if (ppemY == ptSize) {
 971                 return true;
 972             }
 973         }
 974         return false;
 975     }
 976 
 977     public String getFullName() {
 978         return fullName;
 979     }
 980 
 981     /* This probably won't get called but is there to support the
 982      * contract() of setStyle() defined in the superclass.
 983      */
 984     @Override
 985     protected void setStyle() {
 986         setStyle(getTableBuffer(os_2Tag));
 987     }
 988 
 989     private int fontWidth = 0;
 990     @Override
 991     public int getWidth() {
 992        return (fontWidth > 0) ? fontWidth : super.getWidth();
 993     }
 994 
 995     private int fontWeight = 0;
 996     @Override
 997     public int getWeight() {
 998        return (fontWeight > 0) ? fontWeight : super.getWeight();
 999     }
1000 
1001     /* TrueTypeFont can use the fsSelection fields of OS/2 table
1002      * to determine the style. In the unlikely case that doesn't exist,
1003      * can use macStyle in the 'head' table but simpler to
1004      * fall back to super class algorithm of looking for well known string.
1005      * A very few fonts don't specify this information, but I only
1006      * came across one: Lucida Sans Thai Typewriter Oblique in
1007      * /usr/openwin/lib/locale/th_TH/X11/fonts/TrueType/lucidai.ttf
1008      * that explicitly specified the wrong value. It says its regular.
1009      * I didn't find any fonts that were inconsistent (ie regular plus some
1010      * other value).
1011      */
1012     private static final int fsSelectionItalicBit  = 0x00001;
1013     private static final int fsSelectionBoldBit    = 0x00020;
1014     private static final int fsSelectionRegularBit = 0x00040;
1015     private void setStyle(ByteBuffer os_2Table) {
1016         if (os_2Table == null) {
1017             return;
1018         }
1019         if (os_2Table.capacity() >= 8) {
1020             fontWeight = os_2Table.getChar(4) & 0xffff;
1021             fontWidth  = os_2Table.getChar(6) & 0xffff;
1022         }
1023         /* fsSelection is unsigned short at buffer offset 62 */
1024         if (os_2Table.capacity() < 64) {
1025             super.setStyle();
1026             return;
1027         }
1028         int fsSelection = os_2Table.getChar(62) & 0xffff;
1029         int italic  = fsSelection & fsSelectionItalicBit;
1030         int bold    = fsSelection & fsSelectionBoldBit;
1031         int regular = fsSelection & fsSelectionRegularBit;
1032 //      System.out.println("platname="+platName+" font="+fullName+
1033 //                         " family="+familyName+
1034 //                         " R="+regular+" I="+italic+" B="+bold);
1035         if (regular!=0 && ((italic|bold)!=0)) {
1036             /* This is inconsistent. Try using the font name algorithm */
1037             super.setStyle();
1038             return;
1039         } else if ((regular|italic|bold) == 0) {
1040             /* No style specified. Try using the font name algorithm */
1041             super.setStyle();
1042             return;
1043         }
1044         switch (bold|italic) {
1045         case fsSelectionItalicBit:
1046             style = Font.ITALIC;
1047             break;
1048         case fsSelectionBoldBit:
1049             if (FontUtilities.isSolaris && platName.endsWith("HG-GothicB.ttf")) {
1050                 /* Workaround for Solaris's use of a JA font that's marked as
1051                  * being designed bold, but is used as a PLAIN font.
1052                  */
1053                 style = Font.PLAIN;
1054             } else {
1055                 style = Font.BOLD;
1056             }
1057             break;
1058         case fsSelectionBoldBit|fsSelectionItalicBit:
1059             style = Font.BOLD|Font.ITALIC;
1060         }
1061     }
1062 
1063     private float stSize, stPos, ulSize, ulPos;
1064 
1065     private void setStrikethroughMetrics(ByteBuffer os_2Table, int upem) {
1066         if (os_2Table == null || os_2Table.capacity() < 30 || upem < 0) {
1067             stSize = .05f;
1068             stPos = -.4f;
1069             return;
1070         }
1071         ShortBuffer sb = os_2Table.asShortBuffer();
1072         stSize = sb.get(13) / (float)upem;
1073         stPos = -sb.get(14) / (float)upem;
1074     }
1075 
1076     private void setUnderlineMetrics(ByteBuffer postTable, int upem) {
1077         if (postTable == null || postTable.capacity() < 12 || upem < 0) {
1078             ulSize = .05f;
1079             ulPos = .1f;
1080             return;
1081         }
1082         ShortBuffer sb = postTable.asShortBuffer();
1083         ulSize = sb.get(5) / (float)upem;
1084         ulPos = -sb.get(4) / (float)upem;
1085     }
1086 
1087     @Override
1088     public void getStyleMetrics(float pointSize, float[] metrics, int offset) {
1089 
1090         if (ulSize == 0f && ulPos == 0f) {
1091 
1092             ByteBuffer head_Table = getTableBuffer(headTag);
1093             int upem = -1;
1094             if (head_Table != null && head_Table.capacity() >= 18) {
1095                 ShortBuffer sb = head_Table.asShortBuffer();
1096                 upem = sb.get(9) & 0xffff;
1097                 if (upem < 16 || upem > 16384) {
1098                     upem = 2048;
1099                 }
1100             }
1101 
1102             ByteBuffer os2_Table = getTableBuffer(os_2Tag);
1103             setStrikethroughMetrics(os2_Table, upem);
1104 
1105             ByteBuffer post_Table = getTableBuffer(postTag);
1106             setUnderlineMetrics(post_Table, upem);
1107         }
1108 
1109         metrics[offset] = stPos * pointSize;
1110         metrics[offset+1] = stSize * pointSize;
1111 
1112         metrics[offset+2] = ulPos * pointSize;
1113         metrics[offset+3] = ulSize * pointSize;
1114     }
1115 
1116     private String makeString(byte[] bytes, int len,
1117                              short platformID, short encoding) {
1118 
1119         if (platformID == MAC_PLATFORM_ID) {
1120             encoding = -1; // hack so we can re-use the code below.
1121         }
1122 
1123         /* Check for fonts using encodings 2->6 is just for
1124          * some old DBCS fonts, apparently mostly on Solaris.
1125          * Some of these fonts encode ascii names as double-byte characters.
1126          * ie with a leading zero byte for what properly should be a
1127          * single byte-char.
1128          */
1129         if (encoding >=2 && encoding <= 6) {
1130              byte[] oldbytes = bytes;
1131              int oldlen = len;
1132              bytes = new byte[oldlen];
1133              len = 0;
1134              for (int i=0; i<oldlen; i++) {
1135                  if (oldbytes[i] != 0) {
1136                      bytes[len++] = oldbytes[i];
1137                  }
1138              }
1139          }
1140 
1141         String charset;
1142         switch (encoding) {
1143             case -1: charset = "US-ASCII";break;
1144             case 1:  charset = "UTF-16";  break; // most common case first.
1145             case 0:  charset = "UTF-16";  break; // symbol uses this
1146             case 2:  charset = "SJIS";    break;
1147             case 3:  charset = "GBK";     break;
1148             case 4:  charset = "MS950";   break;
1149             case 5:  charset = "EUC_KR";  break;
1150             case 6:  charset = "Johab";   break;
1151             default: charset = "UTF-16";  break;
1152         }
1153 
1154         try {
1155             return new String(bytes, 0, len, charset);
1156         } catch (UnsupportedEncodingException e) {
1157             if (FontUtilities.isLogging()) {
1158                 FontUtilities.getLogger().warning(e + " EncodingID=" + encoding);
1159             }
1160             return new String(bytes, 0, len);
1161         } catch (Throwable t) {
1162             return null;
1163         }
1164     }
1165 
1166     protected void initNames() {
1167 
1168         byte[] name = new byte[256];
1169         ByteBuffer buffer = getTableBuffer(nameTag);
1170 
1171         if (buffer != null) {
1172             ShortBuffer sbuffer = buffer.asShortBuffer();
1173             sbuffer.get(); // format - not needed.
1174             short numRecords = sbuffer.get();
1175             /* The name table uses unsigned shorts. Many of these
1176              * are known small values that fit in a short.
1177              * The values that are sizes or offsets into the table could be
1178              * greater than 32767, so read and store those as ints
1179              */
1180             int stringPtr = sbuffer.get() & 0xffff;
1181 
1182             nameLocale = sun.awt.SunToolkit.getStartupLocale();
1183             short nameLocaleID = getLCIDFromLocale(nameLocale);
1184             languageCompatibleLCIDs =
1185                 getLanguageCompatibleLCIDsFromLocale(nameLocale);
1186 
1187             for (int i=0; i<numRecords; i++) {
1188                 short platformID = sbuffer.get();
1189                 if (platformID != MS_PLATFORM_ID &&
1190                     platformID != MAC_PLATFORM_ID) {
1191                     sbuffer.position(sbuffer.position()+5);
1192                     continue; // skip over this record.
1193                 }
1194                 short encodingID = sbuffer.get();
1195                 short langID     = sbuffer.get();
1196                 short nameID     = sbuffer.get();
1197                 int nameLen    = ((int) sbuffer.get()) & 0xffff;
1198                 int namePtr    = (((int) sbuffer.get()) & 0xffff) + stringPtr;
1199                 String tmpName = null;
1200 
1201                 // only want MacRoman encoding and English name on Mac.
1202                 if ((platformID == MAC_PLATFORM_ID) &&
1203                     (encodingID != MACROMAN_SPECIFIC_ID ||
1204                      langID != MACROMAN_ENGLISH_LANG)) {
1205                     continue;
1206                 }
1207 
1208                 switch (nameID) {
1209 
1210                 case FAMILY_NAME_ID:
1211                     boolean compatible = false;
1212                     if (familyName == null || langID == ENGLISH_LOCALE_ID ||
1213                         langID == nameLocaleID ||
1214                         (localeFamilyName == null &&
1215                          (compatible = isLanguageCompatible(langID))))
1216                     {
1217                         buffer.position(namePtr);
1218                         buffer.get(name, 0, nameLen);
1219                         tmpName = makeString(name, nameLen, platformID, encodingID);
1220                         if (familyName == null || langID == ENGLISH_LOCALE_ID){
1221                             familyName = tmpName;
1222                         }
1223                         if (langID == nameLocaleID ||
1224                             (localeFamilyName == null && compatible))
1225                         {
1226                             localeFamilyName = tmpName;
1227                         }
1228                     }
1229 /*
1230                     for (int ii=0;ii<nameLen;ii++) {
1231                         int val = (int)name[ii]&0xff;
1232                         System.err.print(Integer.toHexString(val)+ " ");
1233                     }
1234                     System.err.println();
1235                     System.err.println("familyName="+familyName +
1236                                        " nameLen="+nameLen+
1237                                        " langID="+langID+ " eid="+encodingID +
1238                                        " str len="+familyName.length());
1239 
1240 */
1241                     break;
1242 
1243                 case FULL_NAME_ID:
1244                     compatible = false;
1245                     if (fullName == null || langID == ENGLISH_LOCALE_ID ||
1246                         langID == nameLocaleID ||
1247                         (localeFullName == null &&
1248                          (compatible = isLanguageCompatible(langID))))
1249                     {
1250                         buffer.position(namePtr);
1251                         buffer.get(name, 0, nameLen);
1252                         tmpName = makeString(name, nameLen, platformID, encodingID);
1253 
1254                         if (fullName == null || langID == ENGLISH_LOCALE_ID) {
1255                             fullName = tmpName;
1256                         }
1257                         if (langID == nameLocaleID ||
1258                             (localeFullName == null && compatible))
1259                         {
1260                             localeFullName = tmpName;
1261                         }
1262                     }
1263                     break;
1264                 }
1265             }
1266             if (localeFamilyName == null) {
1267                 localeFamilyName = familyName;
1268             }
1269             if (localeFullName == null) {
1270                 localeFullName = fullName;
1271             }
1272         }
1273     }
1274 
1275     /* Return the requested name in the requested locale, for the
1276      * MS platform ID. If the requested locale isn't found, return US
1277      * English, if that isn't found, return null and let the caller
1278      * figure out how to handle that.
1279      */
1280     protected String lookupName(short findLocaleID, int findNameID) {
1281         String foundName = null;
1282         byte[] name = new byte[1024];
1283 
1284         ByteBuffer buffer = getTableBuffer(nameTag);
1285         if (buffer != null) {
1286             ShortBuffer sbuffer = buffer.asShortBuffer();
1287             sbuffer.get(); // format - not needed.
1288             short numRecords = sbuffer.get();
1289 
1290             /* The name table uses unsigned shorts. Many of these
1291              * are known small values that fit in a short.
1292              * The values that are sizes or offsets into the table could be
1293              * greater than 32767, so read and store those as ints
1294              */
1295             int stringPtr = ((int) sbuffer.get()) & 0xffff;
1296 
1297             for (int i=0; i<numRecords; i++) {
1298                 short platformID = sbuffer.get();
1299                 if (platformID != MS_PLATFORM_ID) {
1300                     sbuffer.position(sbuffer.position()+5);
1301                     continue; // skip over this record.
1302                 }
1303                 short encodingID = sbuffer.get();
1304                 short langID     = sbuffer.get();
1305                 short nameID     = sbuffer.get();
1306                 int   nameLen    = ((int) sbuffer.get()) & 0xffff;
1307                 int   namePtr    = (((int) sbuffer.get()) & 0xffff) + stringPtr;
1308                 if (nameID == findNameID &&
1309                     ((foundName == null && langID == ENGLISH_LOCALE_ID)
1310                      || langID == findLocaleID)) {
1311                     buffer.position(namePtr);
1312                     buffer.get(name, 0, nameLen);
1313                     foundName = makeString(name, nameLen, platformID, encodingID);
1314                     if (langID == findLocaleID) {
1315                         return foundName;
1316                     }
1317                 }
1318             }
1319         }
1320         return foundName;
1321     }
1322 
1323     /**
1324      * @return number of logical fonts. Is "1" for all but TTC files
1325      */
1326     public int getFontCount() {
1327         return directoryCount;
1328     }
1329 
1330     protected synchronized FontScaler getScaler() {
1331         if (scaler == null) {
1332             scaler = FontScaler.getScaler(this, fontIndex,
1333                 supportsCJK, fileSize);
1334         }
1335         return scaler;
1336     }
1337 
1338 
1339     /* Postscript name is rarely requested. Don't waste cycles locating it
1340      * as part of font creation, nor storage to hold it. Get it only on demand.
1341      */
1342     @Override
1343     public String getPostscriptName() {
1344         String name = lookupName(ENGLISH_LOCALE_ID, POSTSCRIPT_NAME_ID);
1345         if (name == null) {
1346             return fullName;
1347         } else {
1348             return name;
1349         }
1350     }
1351 
1352     @Override
1353     public String getFontName(Locale locale) {
1354         if (locale == null) {
1355             return fullName;
1356         } else if (locale.equals(nameLocale) && localeFullName != null) {
1357             return localeFullName;
1358         } else {
1359             short localeID = getLCIDFromLocale(locale);
1360             String name = lookupName(localeID, FULL_NAME_ID);
1361             if (name == null) {
1362                 return fullName;
1363             } else {
1364                 return name;
1365             }
1366         }
1367     }
1368 
1369     // Return a Microsoft LCID from the given Locale.
1370     // Used when getting localized font data.
1371 
1372     private static void addLCIDMapEntry(Map<String, Short> map,
1373                                         String key, short value) {
1374         map.put(key, Short.valueOf(value));
1375     }
1376 
1377     private static synchronized void createLCIDMap() {
1378         if (lcidMap != null) {
1379             return;
1380         }
1381 
1382         Map<String, Short> map = new HashMap<>(200);
1383 
1384         // the following statements are derived from the langIDMap
1385         // in src/windows/native/java/lang/java_props_md.c using the following
1386         // awk script:
1387         //    $1~/\/\*/   { next}
1388         //    $3~/\?\?/   { next }
1389         //    $3!~/_/     { next }
1390         //    $1~/0x0409/ { next }
1391         //    $1~/0x0c0a/ { next }
1392         //    $1~/0x042c/ { next }
1393         //    $1~/0x0443/ { next }
1394         //    $1~/0x0812/ { next }
1395         //    $1~/0x04/   { print "        addLCIDMapEntry(map, " substr($3, 0, 3) "\", (short) " substr($1, 0, 6) ");" ; next }
1396         //    $3~/,/      { print "        addLCIDMapEntry(map, " $3  " (short) " substr($1, 0, 6) ");" ; next }
1397         //                { print "        addLCIDMapEntry(map, " $3 ", (short) " substr($1, 0, 6) ");" ; next }
1398         // The lines of this script:
1399         // - eliminate comments
1400         // - eliminate questionable locales
1401         // - eliminate language-only locales
1402         // - eliminate the default LCID value
1403         // - eliminate a few other unneeded LCID values
1404         // - print language-only locale entries for x04* LCID values
1405         //   (apparently Microsoft doesn't use language-only LCID values -
1406         //   see http://www.microsoft.com/OpenType/otspec/name.htm
1407         // - print complete entries for all other LCID values
1408         // Run
1409         //     awk -f awk-script langIDMap > statements
1410         addLCIDMapEntry(map, "ar", (short) 0x0401);
1411         addLCIDMapEntry(map, "bg", (short) 0x0402);
1412         addLCIDMapEntry(map, "ca", (short) 0x0403);
1413         addLCIDMapEntry(map, "zh", (short) 0x0404);
1414         addLCIDMapEntry(map, "cs", (short) 0x0405);
1415         addLCIDMapEntry(map, "da", (short) 0x0406);
1416         addLCIDMapEntry(map, "de", (short) 0x0407);
1417         addLCIDMapEntry(map, "el", (short) 0x0408);
1418         addLCIDMapEntry(map, "es", (short) 0x040a);
1419         addLCIDMapEntry(map, "fi", (short) 0x040b);
1420         addLCIDMapEntry(map, "fr", (short) 0x040c);
1421         addLCIDMapEntry(map, "iw", (short) 0x040d);
1422         addLCIDMapEntry(map, "hu", (short) 0x040e);
1423         addLCIDMapEntry(map, "is", (short) 0x040f);
1424         addLCIDMapEntry(map, "it", (short) 0x0410);
1425         addLCIDMapEntry(map, "ja", (short) 0x0411);
1426         addLCIDMapEntry(map, "ko", (short) 0x0412);
1427         addLCIDMapEntry(map, "nl", (short) 0x0413);
1428         addLCIDMapEntry(map, "no", (short) 0x0414);
1429         addLCIDMapEntry(map, "pl", (short) 0x0415);
1430         addLCIDMapEntry(map, "pt", (short) 0x0416);
1431         addLCIDMapEntry(map, "rm", (short) 0x0417);
1432         addLCIDMapEntry(map, "ro", (short) 0x0418);
1433         addLCIDMapEntry(map, "ru", (short) 0x0419);
1434         addLCIDMapEntry(map, "hr", (short) 0x041a);
1435         addLCIDMapEntry(map, "sk", (short) 0x041b);
1436         addLCIDMapEntry(map, "sq", (short) 0x041c);
1437         addLCIDMapEntry(map, "sv", (short) 0x041d);
1438         addLCIDMapEntry(map, "th", (short) 0x041e);
1439         addLCIDMapEntry(map, "tr", (short) 0x041f);
1440         addLCIDMapEntry(map, "ur", (short) 0x0420);
1441         addLCIDMapEntry(map, "in", (short) 0x0421);
1442         addLCIDMapEntry(map, "uk", (short) 0x0422);
1443         addLCIDMapEntry(map, "be", (short) 0x0423);
1444         addLCIDMapEntry(map, "sl", (short) 0x0424);
1445         addLCIDMapEntry(map, "et", (short) 0x0425);
1446         addLCIDMapEntry(map, "lv", (short) 0x0426);
1447         addLCIDMapEntry(map, "lt", (short) 0x0427);
1448         addLCIDMapEntry(map, "fa", (short) 0x0429);
1449         addLCIDMapEntry(map, "vi", (short) 0x042a);
1450         addLCIDMapEntry(map, "hy", (short) 0x042b);
1451         addLCIDMapEntry(map, "eu", (short) 0x042d);
1452         addLCIDMapEntry(map, "mk", (short) 0x042f);
1453         addLCIDMapEntry(map, "tn", (short) 0x0432);
1454         addLCIDMapEntry(map, "xh", (short) 0x0434);
1455         addLCIDMapEntry(map, "zu", (short) 0x0435);
1456         addLCIDMapEntry(map, "af", (short) 0x0436);
1457         addLCIDMapEntry(map, "ka", (short) 0x0437);
1458         addLCIDMapEntry(map, "fo", (short) 0x0438);
1459         addLCIDMapEntry(map, "hi", (short) 0x0439);
1460         addLCIDMapEntry(map, "mt", (short) 0x043a);
1461         addLCIDMapEntry(map, "se", (short) 0x043b);
1462         addLCIDMapEntry(map, "gd", (short) 0x043c);
1463         addLCIDMapEntry(map, "ms", (short) 0x043e);
1464         addLCIDMapEntry(map, "kk", (short) 0x043f);
1465         addLCIDMapEntry(map, "ky", (short) 0x0440);
1466         addLCIDMapEntry(map, "sw", (short) 0x0441);
1467         addLCIDMapEntry(map, "tt", (short) 0x0444);
1468         addLCIDMapEntry(map, "bn", (short) 0x0445);
1469         addLCIDMapEntry(map, "pa", (short) 0x0446);
1470         addLCIDMapEntry(map, "gu", (short) 0x0447);
1471         addLCIDMapEntry(map, "ta", (short) 0x0449);
1472         addLCIDMapEntry(map, "te", (short) 0x044a);
1473         addLCIDMapEntry(map, "kn", (short) 0x044b);
1474         addLCIDMapEntry(map, "ml", (short) 0x044c);
1475         addLCIDMapEntry(map, "mr", (short) 0x044e);
1476         addLCIDMapEntry(map, "sa", (short) 0x044f);
1477         addLCIDMapEntry(map, "mn", (short) 0x0450);
1478         addLCIDMapEntry(map, "cy", (short) 0x0452);
1479         addLCIDMapEntry(map, "gl", (short) 0x0456);
1480         addLCIDMapEntry(map, "dv", (short) 0x0465);
1481         addLCIDMapEntry(map, "qu", (short) 0x046b);
1482         addLCIDMapEntry(map, "mi", (short) 0x0481);
1483         addLCIDMapEntry(map, "ar_IQ", (short) 0x0801);
1484         addLCIDMapEntry(map, "zh_CN", (short) 0x0804);
1485         addLCIDMapEntry(map, "de_CH", (short) 0x0807);
1486         addLCIDMapEntry(map, "en_GB", (short) 0x0809);
1487         addLCIDMapEntry(map, "es_MX", (short) 0x080a);
1488         addLCIDMapEntry(map, "fr_BE", (short) 0x080c);
1489         addLCIDMapEntry(map, "it_CH", (short) 0x0810);
1490         addLCIDMapEntry(map, "nl_BE", (short) 0x0813);
1491         addLCIDMapEntry(map, "no_NO_NY", (short) 0x0814);
1492         addLCIDMapEntry(map, "pt_PT", (short) 0x0816);
1493         addLCIDMapEntry(map, "ro_MD", (short) 0x0818);
1494         addLCIDMapEntry(map, "ru_MD", (short) 0x0819);
1495         addLCIDMapEntry(map, "sr_CS", (short) 0x081a);
1496         addLCIDMapEntry(map, "sv_FI", (short) 0x081d);
1497         addLCIDMapEntry(map, "az_AZ", (short) 0x082c);
1498         addLCIDMapEntry(map, "se_SE", (short) 0x083b);
1499         addLCIDMapEntry(map, "ga_IE", (short) 0x083c);
1500         addLCIDMapEntry(map, "ms_BN", (short) 0x083e);
1501         addLCIDMapEntry(map, "uz_UZ", (short) 0x0843);
1502         addLCIDMapEntry(map, "qu_EC", (short) 0x086b);
1503         addLCIDMapEntry(map, "ar_EG", (short) 0x0c01);
1504         addLCIDMapEntry(map, "zh_HK", (short) 0x0c04);
1505         addLCIDMapEntry(map, "de_AT", (short) 0x0c07);
1506         addLCIDMapEntry(map, "en_AU", (short) 0x0c09);
1507         addLCIDMapEntry(map, "fr_CA", (short) 0x0c0c);
1508         addLCIDMapEntry(map, "sr_CS", (short) 0x0c1a);
1509         addLCIDMapEntry(map, "se_FI", (short) 0x0c3b);
1510         addLCIDMapEntry(map, "qu_PE", (short) 0x0c6b);
1511         addLCIDMapEntry(map, "ar_LY", (short) 0x1001);
1512         addLCIDMapEntry(map, "zh_SG", (short) 0x1004);
1513         addLCIDMapEntry(map, "de_LU", (short) 0x1007);
1514         addLCIDMapEntry(map, "en_CA", (short) 0x1009);
1515         addLCIDMapEntry(map, "es_GT", (short) 0x100a);
1516         addLCIDMapEntry(map, "fr_CH", (short) 0x100c);
1517         addLCIDMapEntry(map, "hr_BA", (short) 0x101a);
1518         addLCIDMapEntry(map, "ar_DZ", (short) 0x1401);
1519         addLCIDMapEntry(map, "zh_MO", (short) 0x1404);
1520         addLCIDMapEntry(map, "de_LI", (short) 0x1407);
1521         addLCIDMapEntry(map, "en_NZ", (short) 0x1409);
1522         addLCIDMapEntry(map, "es_CR", (short) 0x140a);
1523         addLCIDMapEntry(map, "fr_LU", (short) 0x140c);
1524         addLCIDMapEntry(map, "bs_BA", (short) 0x141a);
1525         addLCIDMapEntry(map, "ar_MA", (short) 0x1801);
1526         addLCIDMapEntry(map, "en_IE", (short) 0x1809);
1527         addLCIDMapEntry(map, "es_PA", (short) 0x180a);
1528         addLCIDMapEntry(map, "fr_MC", (short) 0x180c);
1529         addLCIDMapEntry(map, "sr_BA", (short) 0x181a);
1530         addLCIDMapEntry(map, "ar_TN", (short) 0x1c01);
1531         addLCIDMapEntry(map, "en_ZA", (short) 0x1c09);
1532         addLCIDMapEntry(map, "es_DO", (short) 0x1c0a);
1533         addLCIDMapEntry(map, "sr_BA", (short) 0x1c1a);
1534         addLCIDMapEntry(map, "ar_OM", (short) 0x2001);
1535         addLCIDMapEntry(map, "en_JM", (short) 0x2009);
1536         addLCIDMapEntry(map, "es_VE", (short) 0x200a);
1537         addLCIDMapEntry(map, "ar_YE", (short) 0x2401);
1538         addLCIDMapEntry(map, "es_CO", (short) 0x240a);
1539         addLCIDMapEntry(map, "ar_SY", (short) 0x2801);
1540         addLCIDMapEntry(map, "en_BZ", (short) 0x2809);
1541         addLCIDMapEntry(map, "es_PE", (short) 0x280a);
1542         addLCIDMapEntry(map, "ar_JO", (short) 0x2c01);
1543         addLCIDMapEntry(map, "en_TT", (short) 0x2c09);
1544         addLCIDMapEntry(map, "es_AR", (short) 0x2c0a);
1545         addLCIDMapEntry(map, "ar_LB", (short) 0x3001);
1546         addLCIDMapEntry(map, "en_ZW", (short) 0x3009);
1547         addLCIDMapEntry(map, "es_EC", (short) 0x300a);
1548         addLCIDMapEntry(map, "ar_KW", (short) 0x3401);
1549         addLCIDMapEntry(map, "en_PH", (short) 0x3409);
1550         addLCIDMapEntry(map, "es_CL", (short) 0x340a);
1551         addLCIDMapEntry(map, "ar_AE", (short) 0x3801);
1552         addLCIDMapEntry(map, "es_UY", (short) 0x380a);
1553         addLCIDMapEntry(map, "ar_BH", (short) 0x3c01);
1554         addLCIDMapEntry(map, "es_PY", (short) 0x3c0a);
1555         addLCIDMapEntry(map, "ar_QA", (short) 0x4001);
1556         addLCIDMapEntry(map, "es_BO", (short) 0x400a);
1557         addLCIDMapEntry(map, "es_SV", (short) 0x440a);
1558         addLCIDMapEntry(map, "es_HN", (short) 0x480a);
1559         addLCIDMapEntry(map, "es_NI", (short) 0x4c0a);
1560         addLCIDMapEntry(map, "es_PR", (short) 0x500a);
1561 
1562         lcidMap = map;
1563     }
1564 
1565     private static short getLCIDFromLocale(Locale locale) {
1566         // optimize for common case
1567         if (locale.equals(Locale.US)) {
1568             return US_LCID;
1569         }
1570 
1571         if (lcidMap == null) {
1572             createLCIDMap();
1573         }
1574 
1575         String key = locale.toString();
1576         while (!"".equals(key)) {
1577             Short lcidObject = lcidMap.get(key);
1578             if (lcidObject != null) {
1579                 return lcidObject.shortValue();
1580             }
1581             int pos = key.lastIndexOf('_');
1582             if (pos < 1) {
1583                 return US_LCID;
1584             }
1585             key = key.substring(0, pos);
1586         }
1587 
1588         return US_LCID;
1589     }
1590 
1591     @Override
1592     public String getFamilyName(Locale locale) {
1593         if (locale == null) {
1594             return familyName;
1595         } else if (locale.equals(nameLocale) && localeFamilyName != null) {
1596             return localeFamilyName;
1597         } else {
1598             short localeID = getLCIDFromLocale(locale);
1599             String name = lookupName(localeID, FAMILY_NAME_ID);
1600             if (name == null) {
1601                 return familyName;
1602             } else {
1603                 return name;
1604             }
1605         }
1606     }
1607 
1608     public CharToGlyphMapper getMapper() {
1609         if (mapper == null) {
1610             mapper = new TrueTypeGlyphMapper(this);
1611         }
1612         return mapper;
1613     }
1614 
1615     /* This duplicates initNames() but that has to run fast as its used
1616      * during typical start-up and the information here is likely never
1617      * needed.
1618      */
1619     protected void initAllNames(int requestedID, HashSet<String> names) {
1620         byte[] name = new byte[256];
1621         ByteBuffer buffer = getTableBuffer(nameTag);
1622 
1623         if (buffer != null) {
1624             ShortBuffer sbuffer = buffer.asShortBuffer();
1625             sbuffer.get(); // format - not needed.
1626             short numRecords = sbuffer.get();
1627 
1628             /* The name table uses unsigned shorts. Many of these
1629              * are known small values that fit in a short.
1630              * The values that are sizes or offsets into the table could be
1631              * greater than 32767, so read and store those as ints
1632              */
1633             int stringPtr = ((int) sbuffer.get()) & 0xffff;
1634             for (int i=0; i<numRecords; i++) {
1635                 short platformID = sbuffer.get();
1636                 if (platformID != MS_PLATFORM_ID) {
1637                     sbuffer.position(sbuffer.position()+5);
1638                     continue; // skip over this record.
1639                 }
1640                 short encodingID = sbuffer.get();
1641                 /* short langID = */ sbuffer.get();
1642                 short nameID     = sbuffer.get();
1643                 int   nameLen    = ((int) sbuffer.get()) & 0xffff;
1644                 int   namePtr    = (((int) sbuffer.get()) & 0xffff) + stringPtr;
1645 
1646                 if (nameID == requestedID) {
1647                     buffer.position(namePtr);
1648                     buffer.get(name, 0, nameLen);
1649                     names.add(makeString(name, nameLen, platformID, encodingID));
1650                 }
1651             }
1652         }
1653     }
1654 
1655     String[] getAllFamilyNames() {
1656         HashSet<String> aSet = new HashSet<>();
1657         try {
1658             initAllNames(FAMILY_NAME_ID, aSet);
1659         } catch (Exception e) {
1660             /* In case of malformed font */
1661         }
1662         return aSet.toArray(new String[0]);
1663     }
1664 
1665     String[] getAllFullNames() {
1666         HashSet<String> aSet = new HashSet<>();
1667         try {
1668             initAllNames(FULL_NAME_ID, aSet);
1669         } catch (Exception e) {
1670             /* In case of malformed font */
1671         }
1672         return aSet.toArray(new String[0]);
1673     }
1674 
1675     /*  Used by the OpenType engine for mark positioning.
1676      */
1677     @Override
1678     Point2D.Float getGlyphPoint(long pScalerContext,
1679                                 int glyphCode, int ptNumber) {
1680         try {
1681             return getScaler().getGlyphPoint(pScalerContext,
1682                                              glyphCode, ptNumber);
1683         } catch(FontScalerException fe) {
1684             return null;
1685         }
1686     }
1687 
1688     private char[] gaspTable;
1689 
1690     private char[] getGaspTable() {
1691 
1692         if (gaspTable != null) {
1693             return gaspTable;
1694         }
1695 
1696         ByteBuffer buffer = getTableBuffer(gaspTag);
1697         if (buffer == null) {
1698             return gaspTable = new char[0];
1699         }
1700 
1701         CharBuffer cbuffer = buffer.asCharBuffer();
1702         char format = cbuffer.get();
1703         /* format "1" has appeared for some Windows Vista fonts.
1704          * Its presently undocumented but the existing values
1705          * seem to be still valid so we can use it.
1706          */
1707         if (format > 1) { // unrecognised format
1708             return gaspTable = new char[0];
1709         }
1710 
1711         char numRanges = cbuffer.get();
1712         if (4+numRanges*4 > getTableSize(gaspTag)) { // sanity check
1713             return gaspTable = new char[0];
1714         }
1715         gaspTable = new char[2*numRanges];
1716         cbuffer.get(gaspTable);
1717         return gaspTable;
1718     }
1719 
1720     /* This is to obtain info from the TT 'gasp' (grid-fitting and
1721      * scan-conversion procedure) table which specifies three combinations:
1722      * Hint, Smooth (greyscale), Hint and Smooth.
1723      * In this simplified scheme we don't distinguish the latter two. We
1724      * hint even at small sizes, so as to preserve metrics consistency.
1725      * If the information isn't available default values are substituted.
1726      * The more precise defaults we'd do if we distinguished the cases are:
1727      * Bold (no other style) fonts :
1728      * 0-8 : Smooth ( do grey)
1729      * 9+  : Hint + smooth (gridfit + grey)
1730      * Plain, Italic and Bold-Italic fonts :
1731      * 0-8 : Smooth ( do grey)
1732      * 9-17 : Hint (gridfit)
1733      * 18+  : Hint + smooth (gridfit + grey)
1734      * The defaults should rarely come into play as most TT fonts provide
1735      * better defaults.
1736      * REMIND: consider unpacking the table into an array of booleans
1737      * for faster use.
1738      */
1739     @Override
1740     public boolean useAAForPtSize(int ptsize) {
1741 
1742         char[] gasp = getGaspTable();
1743         if (gasp.length > 0) {
1744             for (int i=0;i<gasp.length;i+=2) {
1745                 if (ptsize <= gasp[i]) {
1746                     return ((gasp[i+1] & 0x2) != 0); // bit 2 means DO_GRAY;
1747                 }
1748             }
1749             return true;
1750         }
1751 
1752         if (style == Font.BOLD) {
1753             return true;
1754         } else {
1755             return ptsize <= 8 || ptsize >= 18;
1756         }
1757     }
1758 
1759     @Override
1760     public boolean hasSupplementaryChars() {
1761         return ((TrueTypeGlyphMapper)getMapper()).hasSupplementaryChars();
1762     }
1763 
1764     @Override
1765     public String toString() {
1766         return "** TrueType Font: Family="+familyName+ " Name="+fullName+
1767             " style="+style+" fileName="+getPublicFileName();
1768     }
1769 
1770 
1771     private static Map<String, short[]> lcidLanguageCompatibilityMap;
1772     private static final short[] EMPTY_COMPATIBLE_LCIDS = new short[0];
1773 
1774     // the language compatible LCIDs for this font's nameLocale
1775     private short[] languageCompatibleLCIDs;
1776 
1777     /*
1778      * Returns true if the given lcid's language is compatible
1779      * to the language of the startup Locale. I.e. if
1780      * startupLocale.getLanguage().equals(lcidLocale.getLanguage()) would
1781      * return true.
1782      */
1783     private boolean isLanguageCompatible(short lcid){
1784         for (short s : languageCompatibleLCIDs) {
1785             if (s == lcid) {
1786                 return true;
1787             }
1788         }
1789         return false;
1790     }
1791 
1792     /*
1793      * Returns an array of all the language compatible LCIDs for the
1794      * given Locale. This array is later used to find compatible
1795      * locales.
1796      */
1797     private static short[] getLanguageCompatibleLCIDsFromLocale(Locale locale) {
1798         if (lcidLanguageCompatibilityMap == null) {
1799             createLCIDMap();
1800             createLCIDLanguageCompatibilityMap();
1801         }
1802         String language = locale.getLanguage();
1803         short[] result = lcidLanguageCompatibilityMap.get(language);
1804         return result == null ? EMPTY_COMPATIBLE_LCIDS : result;
1805     }
1806 
1807 //     private static void prtLine(String s) {
1808 //        System.out.println(s);
1809 //     }
1810 
1811 //     /*
1812 //      * Initializes the map from Locale keys (e.g. "en_BZ" or "de")
1813 //      * to language compatible LCIDs.
1814 //      * This map could be statically created based on the fixed known set
1815 //      * added to lcidMap.
1816 //      */
1817 //     private static void createLCIDLanguageCompatibilityMap() {
1818 //         if (lcidLanguageCompatibilityMap != null) {
1819 //             return;
1820 //         }
1821 //         HashMap<String, List<Short>> result = new HashMap<>();
1822 //         for (Entry<String, Short> e : lcidMap.entrySet()) {
1823 //             String language = e.getKey();
1824 //             int index = language.indexOf('_');
1825 //             if (index != -1) {
1826 //                 language = language.substring(0, index);
1827 //             }
1828 //             List<Short> list = result.get(language);
1829 //             if (list == null) {
1830 //                 list = new ArrayList<>();
1831 //                 result.put(language, list);
1832 //             }
1833 //             if (index == -1) {
1834 //                 list.add(0, e.getValue());
1835 //             } else{
1836 //                 list.add(e.getValue());
1837 //             }
1838 //         }
1839 //         Map<String, short[]> compMap = new HashMap<>();
1840 //         for (Entry<String, List<Short>> e : result.entrySet()) {
1841 //             if (e.getValue().size() > 1) {
1842 //                 List<Short> list = e.getValue();
1843 //                 short[] shorts = new short[list.size()];
1844 //                 for (int i = 0; i < shorts.length; i++) {
1845 //                     shorts[i] = list.get(i);
1846 //                 }
1847 //                 compMap.put(e.getKey(), shorts);
1848 //             }
1849 //         }
1850 
1851 //         /* Now dump code to init the map to System.out */
1852 //         prtLine("    private static void createLCIDLanguageCompatibilityMap() {");
1853 //         prtLine("");
1854 
1855 //         prtLine("        Map<String, short[]> map = new HashMap<>();");
1856 //         prtLine("");
1857 //         prtLine("        short[] sarr;");
1858 //         for (Entry<String, short[]> e : compMap.entrySet()) {
1859 //             String lang = e.getKey();
1860 //             short[] ids = e.getValue();
1861 //             StringBuilder sb = new StringBuilder("sarr = new short[] { ");
1862 //             for (int i = 0; i < ids.length; i++) {
1863 //                 sb.append(ids[i]+", ");
1864 //             }
1865 //             sb.append("}");
1866 //             prtLine("        " + sb + ";");
1867 //             prtLine("        map.put(\"" + lang + "\", sarr);");
1868 //         }
1869 //         prtLine("");
1870 //         prtLine("        lcidLanguageCompatibilityMap = map;");
1871 //         prtLine("    }");
1872 //         /* done dumping map */
1873 
1874 //         lcidLanguageCompatibilityMap = compMap;
1875 //     }
1876 
1877     private static void createLCIDLanguageCompatibilityMap() {
1878 
1879         Map<String, short[]> map = new HashMap<>();
1880 
1881         short[] sarr;
1882         sarr = new short[] { 1031, 3079, 5127, 2055, 4103, };
1883         map.put("de", sarr);
1884         sarr = new short[] { 1044, 2068, };
1885         map.put("no", sarr);
1886         sarr = new short[] { 1049, 2073, };
1887         map.put("ru", sarr);
1888         sarr = new short[] { 1053, 2077, };
1889         map.put("sv", sarr);
1890         sarr = new short[] { 1046, 2070, };
1891         map.put("pt", sarr);
1892         sarr = new short[] { 1131, 3179, 2155, };
1893         map.put("qu", sarr);
1894         sarr = new short[] { 1086, 2110, };
1895         map.put("ms", sarr);
1896         sarr = new short[] { 11273, 3081, 12297, 8201, 10249, 4105, 13321, 6153, 7177, 5129, 2057, };
1897         map.put("en", sarr);
1898         sarr = new short[] { 1050, 4122, };
1899         map.put("hr", sarr);
1900         sarr = new short[] { 1040, 2064, };
1901         map.put("it", sarr);
1902         sarr = new short[] { 1036, 5132, 6156, 2060, 3084, 4108, };
1903         map.put("fr", sarr);
1904         sarr = new short[] { 1034, 12298, 14346, 2058, 8202, 19466, 17418, 9226, 13322, 5130, 7178, 11274, 16394, 4106, 10250, 6154, 18442, 20490, 15370, };
1905         map.put("es", sarr);
1906         sarr = new short[] { 1028, 3076, 5124, 4100, 2052, };
1907         map.put("zh", sarr);
1908         sarr = new short[] { 1025, 8193, 16385, 9217, 2049, 14337, 15361, 11265, 13313, 10241, 7169, 12289, 4097, 5121, 6145, 3073, };
1909         map.put("ar", sarr);
1910         sarr = new short[] { 1083, 3131, 2107, };
1911         map.put("se", sarr);
1912         sarr = new short[] { 1048, 2072, };
1913         map.put("ro", sarr);
1914         sarr = new short[] { 1043, 2067, };
1915         map.put("nl", sarr);
1916         sarr = new short[] { 7194, 3098, };
1917         map.put("sr", sarr);
1918 
1919         lcidLanguageCompatibilityMap = map;
1920     }
1921 }