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
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.fonts.autodetect;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.apps.io.InternalResourceResolver;
import org.apache.fop.fonts.CustomFont;
import org.apache.fop.fonts.EmbedFontInfo;
import org.apache.fop.fonts.EmbeddingMode;
import org.apache.fop.fonts.EncodingMode;
import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontCache;
import org.apache.fop.fonts.FontEventListener;
import org.apache.fop.fonts.FontLoader;
import org.apache.fop.fonts.FontTriplet;
import org.apache.fop.fonts.FontUtil;
import org.apache.fop.fonts.MultiByteFont;
import org.apache.fop.fonts.truetype.FontFileReader;
import org.apache.fop.fonts.truetype.OFFontLoader;
import org.apache.fop.fonts.truetype.TTFFile;
/**
* Attempts to determine correct FontInfo
*/
public class FontInfoFinder {
/** logging instance */
private final Log log = LogFactory.getLog(FontInfoFinder.class);
private FontEventListener eventListener;
/**
* Sets the font event listener that can be used to receive events about particular events
* in this class.
* @param listener the font event listener
*/
public void setEventListener(FontEventListener listener) {
this.eventListener = listener;
}
/**
* Attempts to determine FontTriplets from a given CustomFont.
* It seems to be fairly accurate but will probably require some tweaking over time
*
* @param customFont CustomFont
* @param triplets Collection that will take the generated triplets
*/
private void generateTripletsFromFont(CustomFont customFont, Collection<FontTriplet> triplets) {
if (log.isTraceEnabled()) {
log.trace("Font: " + customFont.getFullName()
+ ", family: " + customFont.getFamilyNames()
+ ", PS: " + customFont.getFontName()
+ ", EmbedName: " + customFont.getEmbedFontName());
}
// default style and weight triplet vales (fallback)
String strippedName = stripQuotes(customFont.getStrippedFontName());
//String subName = customFont.getFontSubName();
String fullName = stripQuotes(customFont.getFullName());
String searchName = fullName.toLowerCase();
String style = guessStyle(customFont, searchName);
int weight; //= customFont.getWeight();
int guessedWeight = FontUtil.guessWeight(searchName);
//We always take the guessed weight for now since it yield much better results.
//OpenType's OS/2 usWeightClass value proves to be unreliable.
weight = guessedWeight;
//Full Name usually includes style/weight info so don't use these traits
//If we still want to use these traits, we have to make FontInfo.fontLookup() smarter
triplets.add(new FontTriplet(fullName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL));
if (!fullName.equals(strippedName)) {
triplets.add(new FontTriplet(strippedName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL));
}
Set<String> familyNames = customFont.getFamilyNames();
for (String familyName : familyNames) {
familyName = stripQuotes(familyName);
if (!fullName.equals(familyName)) {
/* Heuristic:
* The more similar the family name to the full font name,
* the higher the priority of its triplet.
* (Lower values indicate higher priorities.) */
int priority = fullName.startsWith(familyName)
? fullName.length() - familyName.length()
: fullName.length();
triplets.add(new FontTriplet(familyName, style, weight, priority));
}
}
}
private final Pattern quotePattern = Pattern.compile("'");
private String stripQuotes(String name) {
return quotePattern.matcher(name).replaceAll("");
}
private String guessStyle(CustomFont customFont, String fontName) {
// style
String style = Font.STYLE_NORMAL;
if (customFont.getItalicAngle() > 0) {
style = Font.STYLE_ITALIC;
} else {
style = FontUtil.guessStyle(fontName);
}
return style;
}
/**
* Attempts to determine FontInfo from a given custom font
* @param fontUri the font URI
* @param customFont the custom font
* @param fontCache font cache (may be null)
* @return FontInfo from the given custom font
*/
private EmbedFontInfo getFontInfoFromCustomFont(URI fontUri, CustomFont customFont,
FontCache fontCache, InternalResourceResolver resourceResolver) {
List<FontTriplet> fontTripletList = new java.util.ArrayList<FontTriplet>();
generateTripletsFromFont(customFont, fontTripletList);
String subFontName = null;
if (customFont instanceof MultiByteFont) {
subFontName = ((MultiByteFont) customFont).getTTCName();
}
EmbedFontInfo fontInfo = new EmbedFontInfo(null, customFont.isKerningEnabled(),
customFont.isAdvancedEnabled(), fontTripletList, fontUri, subFontName,
EncodingMode.AUTO, EmbeddingMode.AUTO);
fontInfo.setPostScriptName(customFont.getFontName());
if (fontCache != null) {
fontCache.addFont(fontInfo, resourceResolver);
}
return fontInfo;
}
/**
* Attempts to determine EmbedFontInfo from a given font file.
*
* @param fontURI the URI of the font resource
* @param resourceResolver font resolver used to resolve font
* @param fontCache font cache (may be null)
* @return an array of newly created embed font info. Generally, this array
* will have only one entry, unless the fontUrl is a TrueType Collection
*/
public EmbedFontInfo[] find(URI fontURI, InternalResourceResolver resourceResolver, FontCache fontCache) {
URI embedUri = resourceResolver.resolveFromBase(fontURI);
String embedStr = embedUri.toASCIIString();
boolean useKerning = true;
boolean useAdvanced = true;
long fileLastModified = -1;
if (fontCache != null) {
fileLastModified = FontCache.getLastModified(fontURI);
// firstly try and fetch it from cache before loading/parsing the font file
if (fontCache.containsFont(embedStr)) {
EmbedFontInfo[] fontInfos = fontCache.getFontInfos(embedStr, fileLastModified);
if (fontInfos != null) {
return fontInfos;
}
// is this a previously failed parsed font?
} else if (fontCache.isFailedFont(embedStr, fileLastModified)) {
if (log.isDebugEnabled()) {
log.debug("Skipping font file that failed to load previously: " + embedUri);
}
return null;
}
}
// try to determine triplet information from font file
CustomFont customFont = null;
if (fontURI.toASCIIString().toLowerCase().endsWith(".ttc")) {
// Get a list of the TTC Font names
List<String> ttcNames = null;
InputStream in = null;
try {
in = resourceResolver.getResource(fontURI);
TTFFile ttf = new TTFFile(false, false);
FontFileReader reader = new FontFileReader(in);
ttcNames = ttf.getTTCnames(reader);
} catch (Exception e) {
if (this.eventListener != null) {
this.eventListener.fontLoadingErrorAtAutoDetection(this,
fontURI.toASCIIString(), e);
}
return null;
} finally {
IOUtils.closeQuietly(in);
}
List<EmbedFontInfo> embedFontInfoList = new java.util.ArrayList<EmbedFontInfo>();
// For each font name ...
for (String fontName : ttcNames) {
if (log.isDebugEnabled()) {
log.debug("Loading " + fontName);
}
try {
OFFontLoader ttfLoader = new OFFontLoader(fontURI, fontName, true,
EmbeddingMode.AUTO, EncodingMode.AUTO, useKerning, useAdvanced,
resourceResolver);
customFont = ttfLoader.getFont();
if (this.eventListener != null) {
customFont.setEventListener(this.eventListener);
}
} catch (Exception e) {
if (fontCache != null) {
fontCache.registerFailedFont(embedUri.toASCIIString(), fileLastModified);
}
if (this.eventListener != null) {
this.eventListener.fontLoadingErrorAtAutoDetection(this,
embedUri.toASCIIString(), e);
}
continue;
}
EmbedFontInfo fi = getFontInfoFromCustomFont(fontURI, customFont, fontCache,
resourceResolver);
if (fi != null) {
embedFontInfoList.add(fi);
}
}
return embedFontInfoList.toArray(
new EmbedFontInfo[embedFontInfoList.size()]);
} else {
// The normal case
try {
customFont = FontLoader.loadFont(fontURI, null, true, EmbeddingMode.AUTO,
EncodingMode.AUTO, useKerning, useAdvanced, resourceResolver);
if (this.eventListener != null) {
customFont.setEventListener(this.eventListener);
}
} catch (Exception e) {
if (fontCache != null) {
fontCache.registerFailedFont(embedUri.toASCIIString(), fileLastModified);
}
if (this.eventListener != null) {
this.eventListener.fontLoadingErrorAtAutoDetection(this,
embedUri.toASCIIString(), e);
}
return null;
}
EmbedFontInfo fi = getFontInfoFromCustomFont(fontURI, customFont, fontCache, resourceResolver);
if (fi != null) {
return new EmbedFontInfo[] {fi};
} else {
return null;
}
}
}
}
|