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