-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
FontConfiguration.java
2263 lines (2074 loc) · 91.6 KB
/
FontConfiguration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt;
import java.awt.Font;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import sun.font.CompositeFontDescriptor;
import sun.font.SunFontManager;
import sun.font.FontUtilities;
import sun.util.logging.PlatformLogger;
/**
* Provides the definitions of the five logical fonts: Serif, SansSerif,
* Monospaced, Dialog, and DialogInput. The necessary information
* is obtained from fontconfig files.
*/
public abstract class FontConfiguration {
//static global runtime env
protected static String osVersion;
protected static String osName;
protected static String encoding; // canonical name of default nio charset
protected static Locale startupLocale = null;
protected static Hashtable<String, String> localeMap = null;
private static FontConfiguration fontConfig;
private static PlatformLogger logger;
protected static boolean isProperties = true;
protected SunFontManager fontManager;
protected boolean preferLocaleFonts;
protected boolean preferPropFonts;
private File fontConfigFile;
private boolean foundOsSpecificFile;
private boolean inited;
private String javaLib;
/* A default FontConfiguration must be created before an alternate
* one to ensure proper static initialisation takes place.
*/
public FontConfiguration(SunFontManager fm) {
if (FontUtilities.debugFonts()) {
FontUtilities.logInfo("Creating standard Font Configuration");
}
if (FontUtilities.debugFonts() && logger == null) {
logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
}
fontManager = fm;
setOsNameAndVersion(); /* static initialization */
setEncoding(); /* static initialization */
/* Separating out the file location from the rest of the
* initialisation, so the caller has the option of doing
* something else if a suitable file isn't found.
*/
findFontConfigFile();
}
public synchronized boolean init() {
if (!inited) {
this.preferLocaleFonts = false;
this.preferPropFonts = false;
setFontConfiguration();
readFontConfigFile(fontConfigFile);
initFontConfig();
inited = true;
}
return true;
}
public FontConfiguration(SunFontManager fm,
boolean preferLocaleFonts,
boolean preferPropFonts) {
fontManager = fm;
if (FontUtilities.debugFonts()) {
FontUtilities.logInfo("Creating alternate Font Configuration");
}
this.preferLocaleFonts = preferLocaleFonts;
this.preferPropFonts = preferPropFonts;
/* fontConfig should be initialised by default constructor, and
* its data tables can be shared, since readFontConfigFile doesn't
* update any other state. Also avoid a doPrivileged block.
*/
initFontConfig();
}
/**
* Fills in this instance's osVersion and osName members. By
* default uses the system properties os.name and os.version;
* subclasses may override.
*/
protected void setOsNameAndVersion() {
osName = System.getProperty("os.name");
osVersion = System.getProperty("os.version");
}
private void setEncoding() {
encoding = Charset.defaultCharset().name();
startupLocale = SunToolkit.getStartupLocale();
}
/////////////////////////////////////////////////////////////////////
// methods for loading the FontConfig file //
/////////////////////////////////////////////////////////////////////
public boolean foundOsSpecificFile() {
return foundOsSpecificFile;
}
/* Smoke test to see if we can trust this configuration by testing if
* the first slot of a composite font maps to an installed file.
*/
public boolean fontFilesArePresent() {
init();
short fontNameID = compFontNameIDs[0][0][0];
short fileNameID = getComponentFileID(fontNameID);
final String fileName = mapFileName(getComponentFileName(fileNameID));
@SuppressWarnings("removal")
Boolean exists = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Boolean>() {
public Boolean run() {
try {
File f = new File(fileName);
return Boolean.valueOf(f.exists());
}
catch (Exception e) {
return Boolean.FALSE;
}
}
});
return exists.booleanValue();
}
private void findFontConfigFile() {
foundOsSpecificFile = true; // default assumption.
String javaHome = System.getProperty("java.home");
if (javaHome == null) {
throw new Error("java.home property not set");
}
javaLib = javaHome + File.separator + "lib";
String javaConfFonts = javaHome +
File.separator + "conf" +
File.separator + "fonts";
String userConfigFile = System.getProperty("sun.awt.fontconfig");
if (userConfigFile != null) {
fontConfigFile = new File(userConfigFile);
} else {
fontConfigFile = findFontConfigFile(javaConfFonts);
if (fontConfigFile == null) {
fontConfigFile = findFontConfigFile(javaLib);
}
}
}
private void readFontConfigFile(File f) {
/* This is invoked here as readFontConfigFile is only invoked
* once per VM, and always in a privileged context, thus the
* directory containing installed fall back fonts is accessed
* from this context
*/
getInstalledFallbackFonts(javaLib);
if (f != null) {
try (FileInputStream in = new FileInputStream(f.getPath())) {
if (isProperties) {
loadProperties(in);
} else {
loadBinary(in);
}
if (FontUtilities.debugFonts()) {
logger.config("Read logical font configuration from " + f);
}
} catch (IOException e) {
if (FontUtilities.debugFonts()) {
logger.config("Failed to read logical font configuration from " + f);
}
}
}
String version = getVersion();
if (!"1".equals(version) && FontUtilities.debugFonts()) {
logger.config("Unsupported fontconfig version: " + version);
}
}
protected void getInstalledFallbackFonts(String javaLib) {
String fallbackDirName = javaLib + File.separator +
"fonts" + File.separator + "fallback";
File fallbackDir = new File(fallbackDirName);
if (fallbackDir.exists() && fallbackDir.isDirectory()) {
String[] ttfs = fallbackDir.list(fontManager.getTrueTypeFilter());
String[] t1s = fallbackDir.list(fontManager.getType1Filter());
int numTTFs = (ttfs == null) ? 0 : ttfs.length;
int numT1s = (t1s == null) ? 0 : t1s.length;
int len = numTTFs + numT1s;
if (numTTFs + numT1s == 0) {
return;
}
installedFallbackFontFiles = new String[len];
for (int i=0; i<numTTFs; i++) {
installedFallbackFontFiles[i] =
fallbackDir + File.separator + ttfs[i];
}
for (int i=0; i<numT1s; i++) {
installedFallbackFontFiles[i+numTTFs] =
fallbackDir + File.separator + t1s[i];
}
fontManager.registerFontsInDir(fallbackDirName);
}
}
private File findImpl(String fname) {
File f = new File(fname + ".properties");
if (FontUtilities.debugFonts()) {
logger.info("Looking for text fontconfig file : " + f);
}
if (f.canRead()) {
if (FontUtilities.debugFonts()) {
logger.info("Found file : " + f);
}
isProperties = true;
return f;
}
f = new File(fname + ".bfc");
if (FontUtilities.debugFonts()) {
logger.info("Looking for binary fontconfig file : " + f);
}
if (f.canRead()) {
if (FontUtilities.debugFonts()) {
logger.info("Found file : " + f);
}
isProperties = false;
return f;
}
return null;
}
private File findFontConfigFile(String dir) {
if (!(new File(dir)).exists()) {
return null;
}
String baseName = dir + File.separator + "fontconfig";
File configFile;
String osMajorVersion = null;
if (osVersion != null && osName != null) {
configFile = findImpl(baseName + "." + osName + "." + osVersion);
if (configFile != null) {
return configFile;
}
int decimalPointIndex = osVersion.indexOf('.');
if (decimalPointIndex != -1) {
osMajorVersion = osVersion.substring(0, osVersion.indexOf('.'));
configFile = findImpl(baseName + "." + osName + "." + osMajorVersion);
if (configFile != null) {
return configFile;
}
}
}
if (osName != null) {
configFile = findImpl(baseName + "." + osName);
if (configFile != null) {
return configFile;
}
}
if (osVersion != null) {
configFile = findImpl(baseName + "." + osVersion);
if (configFile != null) {
return configFile;
}
if (osMajorVersion != null) {
configFile = findImpl(baseName + "." + osMajorVersion);
if (configFile != null) {
return configFile;
}
}
}
foundOsSpecificFile = false;
configFile = findImpl(baseName);
if (configFile != null) {
return configFile;
}
if (FontUtilities.debugFonts()) {
logger.info("Did not find a fontconfig file.");
}
return null;
}
/* Initialize the internal data tables from binary format font
* configuration file.
*/
public static void loadBinary(InputStream inStream) throws IOException {
DataInputStream in = new DataInputStream(inStream);
head = readShortTable(in, HEAD_LENGTH);
int[] tableSizes = new int[INDEX_TABLEEND];
for (int i = 0; i < INDEX_TABLEEND; i++) {
tableSizes[i] = head[i + 1] - head[i];
}
table_scriptIDs = readShortTable(in, tableSizes[INDEX_scriptIDs]);
table_scriptFonts = readShortTable(in, tableSizes[INDEX_scriptFonts]);
table_elcIDs = readShortTable(in, tableSizes[INDEX_elcIDs]);
table_sequences = readShortTable(in, tableSizes[INDEX_sequences]);
table_fontfileNameIDs = readShortTable(in, tableSizes[INDEX_fontfileNameIDs]);
table_componentFontNameIDs = readShortTable(in, tableSizes[INDEX_componentFontNameIDs]);
table_filenames = readShortTable(in, tableSizes[INDEX_filenames]);
table_awtfontpaths = readShortTable(in, tableSizes[INDEX_awtfontpaths]);
table_exclusions = readShortTable(in, tableSizes[INDEX_exclusions]);
table_proportionals = readShortTable(in, tableSizes[INDEX_proportionals]);
table_scriptFontsMotif = readShortTable(in, tableSizes[INDEX_scriptFontsMotif]);
table_alphabeticSuffix = readShortTable(in, tableSizes[INDEX_alphabeticSuffix]);
table_stringIDs = readShortTable(in, tableSizes[INDEX_stringIDs]);
//StringTable cache
stringCache = new String[table_stringIDs.length + 1];
int len = tableSizes[INDEX_stringTable];
byte[] bb = new byte[len * 2];
table_stringTable = new char[len];
in.read(bb);
int i = 0, j = 0;
while (i < len) {
table_stringTable[i++] = (char)(bb[j++] << 8 | (bb[j++] & 0xff));
}
if (verbose) {
dump();
}
}
/* Generate a binary format font configuration from internal data
* tables.
*/
public static void saveBinary(OutputStream out) throws IOException {
sanityCheck();
DataOutputStream dataOut = new DataOutputStream(out);
writeShortTable(dataOut, head);
writeShortTable(dataOut, table_scriptIDs);
writeShortTable(dataOut, table_scriptFonts);
writeShortTable(dataOut, table_elcIDs);
writeShortTable(dataOut, table_sequences);
writeShortTable(dataOut, table_fontfileNameIDs);
writeShortTable(dataOut, table_componentFontNameIDs);
writeShortTable(dataOut, table_filenames);
writeShortTable(dataOut, table_awtfontpaths);
writeShortTable(dataOut, table_exclusions);
writeShortTable(dataOut, table_proportionals);
writeShortTable(dataOut, table_scriptFontsMotif);
writeShortTable(dataOut, table_alphabeticSuffix);
writeShortTable(dataOut, table_stringIDs);
//stringTable
dataOut.writeChars(new String(table_stringTable));
out.close();
if (verbose) {
dump();
}
}
//private static boolean loadingProperties;
private static short stringIDNum;
private static short[] stringIDs;
private static StringBuilder stringTable;
public static void loadProperties(InputStream in) throws IOException {
//loadingProperties = true;
//StringID starts from "1", "0" is reserved for "not defined"
stringIDNum = 1;
stringIDs = new short[1000];
stringTable = new StringBuilder(4096);
if (verbose && logger == null) {
logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
}
new PropertiesHandler().load(in);
//loadingProperties = false;
stringIDs = null;
stringTable = null;
}
/////////////////////////////////////////////////////////////////////
// methods for initializing the FontConfig //
/////////////////////////////////////////////////////////////////////
/**
* set initLocale, initEncoding and initELC for this FontConfig object
* currently we just simply use the startup locale and encoding
*/
private void initFontConfig() {
initLocale = startupLocale;
initEncoding = encoding;
if (preferLocaleFonts && !willReorderForStartupLocale()) {
preferLocaleFonts = false;
}
initELC = getInitELC();
initAllComponentFonts();
}
//"ELC" stands for "Encoding.Language.Country". This method returns
//the ID of the matched elc setting of "initLocale" in elcIDs table.
//If no match is found, it returns the default ID, which is
//"NULL.NULL.NULL" in elcIDs table.
private short getInitELC() {
if (initELC != -1) {
return initELC;
}
HashMap <String, Integer> elcIDs = new HashMap<String, Integer>();
for (int i = 0; i < table_elcIDs.length; i++) {
elcIDs.put(getString(table_elcIDs[i]), i);
}
String language = initLocale.getLanguage();
String country = initLocale.getCountry();
String elc;
if (elcIDs.containsKey(elc=initEncoding + "." + language + "." + country)
|| elcIDs.containsKey(elc=initEncoding + "." + language)
|| elcIDs.containsKey(elc=initEncoding)) {
initELC = elcIDs.get(elc).shortValue();
} else {
initELC = elcIDs.get("NULL.NULL.NULL").shortValue();
}
int i = 0;
while (i < table_alphabeticSuffix.length) {
if (initELC == table_alphabeticSuffix[i]) {
alphabeticSuffix = getString(table_alphabeticSuffix[i + 1]);
return initELC;
}
i += 2;
}
return initELC;
}
public static boolean verbose;
private short initELC = -1;
private Locale initLocale;
private String initEncoding;
private String alphabeticSuffix;
private short[][][] compFontNameIDs = new short[NUM_FONTS][NUM_STYLES][];
private int[][][] compExclusions = new int[NUM_FONTS][][];
private int[] compCoreNum = new int[NUM_FONTS];
private Set<Short> coreFontNameIDs = new HashSet<Short>();
private Set<Short> fallbackFontNameIDs = new HashSet<Short>();
private void initAllComponentFonts() {
short[] fallbackScripts = getFallbackScripts();
for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
short[] coreScripts = getCoreScripts(fontIndex);
compCoreNum[fontIndex] = coreScripts.length;
/*
System.out.println("coreScriptID=" + table_sequences[initELC * 5 + fontIndex]);
for (int i = 0; i < coreScripts.length; i++) {
System.out.println(" " + i + " :" + getString(table_scriptIDs[coreScripts[i]]));
}
*/
//init exclusionRanges
int[][] exclusions = new int[coreScripts.length][];
for (int i = 0; i < coreScripts.length; i++) {
exclusions[i] = getExclusionRanges(coreScripts[i]);
}
compExclusions[fontIndex] = exclusions;
//init componentFontNames
for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
int index;
short[] nameIDs = new short[coreScripts.length + fallbackScripts.length];
//core
for (index = 0; index < coreScripts.length; index++) {
nameIDs[index] = getComponentFontID(coreScripts[index],
fontIndex, styleIndex);
if (preferLocaleFonts && localeMap != null &&
fontManager.usingAlternateFontforJALocales()) {
nameIDs[index] = remapLocaleMap(fontIndex, styleIndex,
coreScripts[index], nameIDs[index]);
}
if (preferPropFonts) {
nameIDs[index] = remapProportional(fontIndex, nameIDs[index]);
}
//System.out.println("nameid=" + nameIDs[index]);
coreFontNameIDs.add(nameIDs[index]);
}
//fallback
for (int i = 0; i < fallbackScripts.length; i++) {
short id = getComponentFontID(fallbackScripts[i],
fontIndex, styleIndex);
if (preferLocaleFonts && localeMap != null &&
fontManager.usingAlternateFontforJALocales()) {
id = remapLocaleMap(fontIndex, styleIndex, fallbackScripts[i], id);
}
if (preferPropFonts) {
id = remapProportional(fontIndex, id);
}
if (contains(nameIDs, id, index)) {
continue;
}
/*
System.out.println("fontIndex=" + fontIndex + ", styleIndex=" + styleIndex
+ ", fbIndex=" + i + ",fbS=" + fallbackScripts[i] + ", id=" + id);
*/
fallbackFontNameIDs.add(id);
nameIDs[index++] = id;
}
if (index < nameIDs.length) {
short[] newNameIDs = new short[index];
System.arraycopy(nameIDs, 0, newNameIDs, 0, index);
nameIDs = newNameIDs;
}
compFontNameIDs[fontIndex][styleIndex] = nameIDs;
}
}
}
private short remapLocaleMap(int fontIndex, int styleIndex, short scriptID, short fontID) {
String scriptName = getString(table_scriptIDs[scriptID]);
String value = localeMap.get(scriptName);
if (value == null) {
String fontName = fontNames[fontIndex];
String styleName = styleNames[styleIndex];
value = localeMap.get(fontName + "." + styleName + "." + scriptName);
}
if (value == null) {
return fontID;
}
for (int i = 0; i < table_componentFontNameIDs.length; i++) {
String name = getString(table_componentFontNameIDs[i]);
if (value.equalsIgnoreCase(name)) {
fontID = (short)i;
break;
}
}
return fontID;
}
public static boolean hasMonoToPropMap() {
return table_proportionals != null && table_proportionals.length != 0;
}
private short remapProportional(int fontIndex, short id) {
if (preferPropFonts &&
table_proportionals.length != 0 &&
fontIndex != 2 && //"monospaced"
fontIndex != 4) { //"dialoginput"
int i = 0;
while (i < table_proportionals.length) {
if (table_proportionals[i] == id) {
return table_proportionals[i + 1];
}
i += 2;
}
}
return id;
}
/////////////////////////////////////////////////////////////////////
// Methods for handling font and style names //
/////////////////////////////////////////////////////////////////////
protected static final int NUM_FONTS = 5;
protected static final int NUM_STYLES = 4;
protected static final String[] fontNames
= {"serif", "sansserif", "monospaced", "dialog", "dialoginput"};
protected static final String[] publicFontNames
= {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG,
Font.DIALOG_INPUT};
protected static final String[] styleNames
= {"plain", "bold", "italic", "bolditalic"};
/**
* Checks whether the given font family name is a valid logical font name.
* The check is case insensitive.
*/
public static boolean isLogicalFontFamilyName(String fontName) {
return isLogicalFontFamilyNameLC(fontName.toLowerCase(Locale.ENGLISH));
}
/**
* Checks whether the given font family name is a valid logical font name.
* The check is case sensitive.
*/
public static boolean isLogicalFontFamilyNameLC(String fontName) {
for (int i = 0; i < fontNames.length; i++) {
if (fontName.equals(fontNames[i])) {
return true;
}
}
return false;
}
/**
* Checks whether the given style name is a valid logical font style name.
*/
private static boolean isLogicalFontStyleName(String styleName) {
for (int i = 0; i < styleNames.length; i++) {
if (styleName.equals(styleNames[i])) {
return true;
}
}
return false;
}
/**
* Checks whether the given font face name is a valid logical font name.
* The check is case insensitive.
*/
public static boolean isLogicalFontFaceName(String fontName) {
return isLogicalFontFaceNameLC(fontName.toLowerCase(Locale.ENGLISH));
}
/**
* Checks whether the given font face name is a valid logical font name.
* The check is case sensitive.
*/
public static boolean isLogicalFontFaceNameLC(String fontName) {
int period = fontName.indexOf('.');
if (period >= 0) {
String familyName = fontName.substring(0, period);
String styleName = fontName.substring(period + 1);
return isLogicalFontFamilyName(familyName) &&
isLogicalFontStyleName(styleName);
} else {
return isLogicalFontFamilyName(fontName);
}
}
protected static int getFontIndex(String fontName) {
return getArrayIndex(fontNames, fontName);
}
protected static int getStyleIndex(String styleName) {
return getArrayIndex(styleNames, styleName);
}
private static int getArrayIndex(String[] names, String name) {
for (int i = 0; i < names.length; i++) {
if (name.equals(names[i])) {
return i;
}
}
assert false;
return 0;
}
protected static int getStyleIndex(int style) {
switch (style) {
case Font.PLAIN:
return 0;
case Font.BOLD:
return 1;
case Font.ITALIC:
return 2;
case Font.BOLD | Font.ITALIC:
return 3;
default:
return 0;
}
}
protected static String getFontName(int fontIndex) {
return fontNames[fontIndex];
}
protected static String getStyleName(int styleIndex) {
return styleNames[styleIndex];
}
/**
* Returns the font face name for the given logical font
* family name and style.
* The style argument is interpreted as in java.awt.Font.Font.
*/
public static String getLogicalFontFaceName(String familyName, int style) {
assert isLogicalFontFamilyName(familyName);
return familyName.toLowerCase(Locale.ENGLISH) + "." + getStyleString(style);
}
/**
* Returns the string typically used in properties files
* for the given style.
* The style argument is interpreted as in java.awt.Font.Font.
*/
public static String getStyleString(int style) {
return getStyleName(getStyleIndex(style));
}
/**
* Returns a fallback name for the given font name. For a few known
* font names, matching logical font names are returned. For all
* other font names, defaultFallback is returned.
* defaultFallback differs between AWT and 2D.
*/
public abstract String getFallbackFamilyName(String fontName, String defaultFallback);
/**
* Returns the 1.1 equivalent for some old 1.0 font family names for
* which we need to maintain compatibility in some configurations.
* Returns null for other font names.
*/
protected String getCompatibilityFamilyName(String fontName) {
fontName = fontName.toLowerCase(Locale.ENGLISH);
if (fontName.equals("timesroman")) {
return "serif";
} else if (fontName.equals("helvetica")) {
return "sansserif";
} else if (fontName.equals("courier")) {
return "monospaced";
}
return null;
}
protected static String[] installedFallbackFontFiles = null;
/**
* Maps a file name given in the font configuration file
* to a format appropriate for the platform.
*/
protected String mapFileName(String fileName) {
return fileName;
}
//////////////////////////////////////////////////////////////////////
// reordering //
//////////////////////////////////////////////////////////////////////
/* Mappings from file encoding to font config name for font supporting
* the corresponding language. This is filled in by initReorderMap()
*/
protected HashMap<String, Object> reorderMap = null;
/* Platform-specific mappings */
protected abstract void initReorderMap();
/* Move item at index "src" to "dst", shuffling all values in
* between down
*/
private void shuffle(String[] seq, int src, int dst) {
if (dst >= src) {
return;
}
String tmp = seq[src];
for (int i=src; i>dst; i--) {
seq[i] = seq[i-1];
}
seq[dst] = tmp;
}
/* Called to determine if there's a re-order sequence for this locale/
* encoding. If there's none then the caller can "bail" and avoid
* unnecessary work
*/
public static boolean willReorderForStartupLocale() {
return getReorderSequence() != null;
}
private static Object getReorderSequence() {
if (fontConfig.reorderMap == null) {
fontConfig.initReorderMap();
}
HashMap<String, Object> reorderMap = fontConfig.reorderMap;
/* Find the most specific mapping */
String language = startupLocale.getLanguage();
String country = startupLocale.getCountry();
Object val = reorderMap.get(encoding + "." + language + "." + country);
if (val == null) {
val = reorderMap.get(encoding + "." + language);
}
if (val == null) {
val = reorderMap.get(encoding);
}
return val;
}
/* This method reorders the sequence such that the matches for the
* file encoding are moved ahead of other elements.
* If an encoding uses more than one font, they are all moved up.
*/
private void reorderSequenceForLocale(String[] seq) {
Object val = getReorderSequence();
if (val instanceof String) {
for (int i=0; i< seq.length; i++) {
if (seq[i].equals(val)) {
shuffle(seq, i, 0);
return;
}
}
} else if (val instanceof String[]) {
String[] fontLangs = (String[])val;
for (int l=0; l<fontLangs.length;l++) {
for (int i=0; i<seq.length;i++) {
if (seq[i].equals(fontLangs[l])) {
shuffle(seq, i, l);
}
}
}
}
}
private static Vector<String> splitSequence(String sequence) {
//String.split would be more convenient, but incurs big performance penalty
Vector<String> parts = new Vector<>();
int start = 0;
int end;
while ((end = sequence.indexOf(',', start)) >= 0) {
parts.add(sequence.substring(start, end));
start = end + 1;
}
if (sequence.length() > start) {
parts.add(sequence.substring(start));
}
return parts;
}
////////////////////////////////////////////////////////////////////////
// Methods for extracting information from the fontconfig data for AWT//
////////////////////////////////////////////////////////////////////////
private Hashtable<String, Charset> charsetRegistry = new Hashtable<>(5);
/**
* Returns FontDescriptors describing the physical fonts used for the
* given logical font name and style. The font name is interpreted
* in a case insensitive way.
* The style argument is interpreted as in java.awt.Font.Font.
*/
public FontDescriptor[] getFontDescriptors(String fontName, int style) {
assert isLogicalFontFamilyName(fontName);
fontName = fontName.toLowerCase(Locale.ENGLISH);
int fontIndex = getFontIndex(fontName);
int styleIndex = getStyleIndex(style);
return getFontDescriptors(fontIndex, styleIndex);
}
private FontDescriptor[][][] fontDescriptors =
new FontDescriptor[NUM_FONTS][NUM_STYLES][];
private FontDescriptor[] getFontDescriptors(int fontIndex, int styleIndex) {
FontDescriptor[] descriptors = fontDescriptors[fontIndex][styleIndex];
if (descriptors == null) {
descriptors = buildFontDescriptors(fontIndex, styleIndex);
fontDescriptors[fontIndex][styleIndex] = descriptors;
}
return descriptors;
}
protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
String fontName = fontNames[fontIndex];
String styleName = styleNames[styleIndex];
short[] scriptIDs = getCoreScripts(fontIndex);
short[] nameIDs = compFontNameIDs[fontIndex][styleIndex];
String[] sequence = new String[scriptIDs.length];
String[] names = new String[scriptIDs.length];
for (int i = 0; i < sequence.length; i++) {
names[i] = getComponentFontName(nameIDs[i]);
sequence[i] = getScriptName(scriptIDs[i]);
if (alphabeticSuffix != null && "alphabetic".equals(sequence[i])) {
sequence[i] = sequence[i] + "/" + alphabeticSuffix;
}
}
int[][] fontExclusionRanges = compExclusions[fontIndex];
FontDescriptor[] descriptors = new FontDescriptor[names.length];
for (int i = 0; i < names.length; i++) {
String awtFontName;
String encoding;
awtFontName = makeAWTFontName(names[i], sequence[i]);
// look up character encoding
encoding = getEncoding(names[i], sequence[i]);
if (encoding == null) {
encoding = "default";
}
CharsetEncoder enc
= getFontCharsetEncoder(encoding.trim(), awtFontName);
// we already have the exclusion ranges
int[] exclusionRanges = fontExclusionRanges[i];
// create descriptor
descriptors[i] = new FontDescriptor(awtFontName, enc, exclusionRanges);
}
return descriptors;
}
/**
* Returns the AWT font name for the given platform font name and
* character subset.
*/
protected String makeAWTFontName(String platformFontName,
String characterSubsetName) {
return platformFontName;
}
/**
* Returns the java.io name of the platform character encoding for the
* given AWT font name and character subset. May return "default"
* to indicate that getDefaultFontCharset should be called to obtain
* a charset encoder.
*/
protected abstract String getEncoding(String awtFontName,
String characterSubsetName);
private CharsetEncoder getFontCharsetEncoder(final String charsetName,
String fontName) {
Charset fc = null;
if (charsetName.equals("default")) {
fc = charsetRegistry.get(fontName);
} else {
fc = charsetRegistry.get(charsetName);
}
if (fc != null) {
return fc.newEncoder();
}
if (!charsetName.startsWith("sun.awt.") &&
!charsetName.equals("default") &&
!charsetName.startsWith("sun.font.")) {
fc = Charset.forName(charsetName);
} else {
@SuppressWarnings("removal")
Class<?> fcc = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
public Class<?> run() {
try {
return Class.forName(charsetName, true,
ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e) {
}
return null;
}
});
if (fcc != null) {
try {
fc = (Charset) fcc.getDeclaredConstructor().newInstance();
} catch (Exception e) {
}
}
}
if (fc == null) {
fc = getDefaultFontCharset(fontName);
}
if (charsetName.equals("default")){
charsetRegistry.put(fontName, fc);
} else {
charsetRegistry.put(charsetName, fc);
}
return fc.newEncoder();
}
protected abstract Charset getDefaultFontCharset(
String fontName);
/* This retrieves the platform font directories (path) calculated
* by setAWTFontPathSequence(String[]). The default implementation
* returns null, its expected that X11 platforms may return
* non-null.