blob: 561b7df234543deae4c889801a5a790368977faa [file] [log] [blame]
reed@android.com8a1c16f2008-12-17 15:59:43 +00001/* libs/graphics/ports/SkFontHost_android.cpp
2 **
3 ** Copyright 2006, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18#include "SkFontHost.h"
19#include "SkDescriptor.h"
20#include "SkMMapStream.h"
21#include "SkOSFile.h"
22#include "SkPaint.h"
23#include "SkString.h"
24#include "SkStream.h"
25#include "SkThread.h"
26#include "SkTSearch.h"
27#include <stdio.h>
28
29#define FONT_CACHE_MEMORY_BUDGET (1 * 1024 * 1024)
30
31#ifndef SK_FONT_FILE_PREFIX
32 #define SK_FONT_FILE_PREFIX "/usr/share/fonts/truetype/msttcorefonts/"
33#endif
34
35SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);
36
37static void GetFullPathForSysFonts(SkString* full, const char name[])
38{
39 full->append(SK_FONT_FILE_PREFIX);
40 full->append(name);
41}
42
43///////////////////////////////////////////////////////////////////////////////
44
45struct FamilyRec;
46
47/* This guy holds a mapping of a name -> family, used for looking up fonts.
48 Since it is stored in a stretchy array that doesn't preserve object
49 semantics, we don't use constructor/destructors, but just have explicit
50 helpers to manage our internal bookkeeping.
51 */
52struct NameFamilyPair {
53 const char* fName; // we own this
54 FamilyRec* fFamily; // we don't own this, we just reference it
55
56 void construct(const char name[], FamilyRec* family)
57 {
58 fName = strdup(name);
59 fFamily = family; // we don't own this, so just record the referene
60 }
61 void destruct()
62 {
63 free((char*)fName);
64 // we don't own family, so just ignore our reference
65 }
66};
67
68// we use atomic_inc to grow this for each typeface we create
69static int32_t gUniqueFontID;
70
71// this is the mutex that protects these globals
72static SkMutex gFamilyMutex;
73static FamilyRec* gFamilyHead;
74static SkTDArray<NameFamilyPair> gNameList;
75
76struct FamilyRec {
77 FamilyRec* fNext;
78 SkTypeface* fFaces[4];
79
80 FamilyRec()
81 {
82 fNext = gFamilyHead;
83 memset(fFaces, 0, sizeof(fFaces));
84 gFamilyHead = this;
85 }
86};
87
88static SkTypeface* find_best_face(const FamilyRec* family,
reed@android.com1bfd0ca2009-02-20 14:22:36 +000089 SkTypeface::Style style) {
reed@android.com8a1c16f2008-12-17 15:59:43 +000090 SkTypeface* const* faces = family->fFaces;
91
92 if (faces[style] != NULL) { // exact match
93 return faces[style];
94 }
95 // look for a matching bold
96 style = (SkTypeface::Style)(style ^ SkTypeface::kItalic);
97 if (faces[style] != NULL) {
98 return faces[style];
99 }
100 // look for the plain
101 if (faces[SkTypeface::kNormal] != NULL) {
102 return faces[SkTypeface::kNormal];
103 }
104 // look for anything
105 for (int i = 0; i < 4; i++) {
106 if (faces[i] != NULL) {
107 return faces[i];
108 }
109 }
110 // should never get here, since the faces list should not be empty
111 SkASSERT(!"faces list is empty");
112 return NULL;
113}
114
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000115static FamilyRec* find_family(const SkTypeface* member) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000116 FamilyRec* curr = gFamilyHead;
117 while (curr != NULL) {
118 for (int i = 0; i < 4; i++) {
119 if (curr->fFaces[i] == member) {
120 return curr;
121 }
122 }
123 curr = curr->fNext;
124 }
125 return NULL;
126}
127
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000128static SkTypeface* resolve_uniqueID(uint32_t uniqueID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000129 FamilyRec* curr = gFamilyHead;
130 while (curr != NULL) {
131 for (int i = 0; i < 4; i++) {
132 SkTypeface* face = curr->fFaces[i];
133 if (face != NULL && face->uniqueID() == uniqueID) {
134 return face;
135 }
136 }
137 curr = curr->fNext;
138 }
139 return NULL;
140}
141
142/* Remove reference to this face from its family. If the resulting family
143 is empty (has no faces), return that family, otherwise return NULL
144 */
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000145static FamilyRec* remove_from_family(const SkTypeface* face) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000146 FamilyRec* family = find_family(face);
147 SkASSERT(family->fFaces[face->style()] == face);
148 family->fFaces[face->style()] = NULL;
149
150 for (int i = 0; i < 4; i++) {
151 if (family->fFaces[i] != NULL) { // family is non-empty
152 return NULL;
153 }
154 }
155 return family; // return the empty family
156}
157
158// maybe we should make FamilyRec be doubly-linked
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000159static void detach_and_delete_family(FamilyRec* family) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000160 FamilyRec* curr = gFamilyHead;
161 FamilyRec* prev = NULL;
162
163 while (curr != NULL) {
164 FamilyRec* next = curr->fNext;
165 if (curr == family) {
166 if (prev == NULL) {
167 gFamilyHead = next;
168 } else {
169 prev->fNext = next;
170 }
171 SkDELETE(family);
172 return;
173 }
174 prev = curr;
175 curr = next;
176 }
177 SkASSERT(!"Yikes, couldn't find family in our list to remove/delete");
178}
179
180static FamilyRec* find_familyrec(const char name[]) {
181 const NameFamilyPair* list = gNameList.begin();
182 int index = SkStrLCSearch(&list[0].fName, gNameList.count(), name,
183 sizeof(list[0]));
184 return index >= 0 ? list[index].fFamily : NULL;
185}
186
187static SkTypeface* find_typeface(const char name[], SkTypeface::Style style) {
188 FamilyRec* rec = find_familyrec(name);
189 return rec ? find_best_face(rec, style) : NULL;
190}
191
192static SkTypeface* find_typeface(const SkTypeface* familyMember,
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000193 SkTypeface::Style style) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000194 const FamilyRec* family = find_family(familyMember);
195 return family ? find_best_face(family, style) : NULL;
196}
197
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000198static void add_name(const char name[], FamilyRec* family) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000199 SkAutoAsciiToLC tolc(name);
200 name = tolc.lc();
201
202 NameFamilyPair* list = gNameList.begin();
203 int count = gNameList.count();
204
205 int index = SkStrLCSearch(&list[0].fName, count, name, sizeof(list[0]));
206
207 if (index < 0) {
208 list = gNameList.insert(~index);
209 list->construct(name, family);
210 }
211}
212
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000213static void remove_from_names(FamilyRec* emptyFamily) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000214#ifdef SK_DEBUG
215 for (int i = 0; i < 4; i++) {
216 SkASSERT(emptyFamily->fFaces[i] == NULL);
217 }
218#endif
219
220 SkTDArray<NameFamilyPair>& list = gNameList;
221
222 // must go backwards when removing
223 for (int i = list.count() - 1; i >= 0; --i) {
224 NameFamilyPair* pair = &list[i];
225 if (pair->fFamily == emptyFamily) {
226 pair->destruct();
227 list.remove(i);
228 }
229 }
230}
231
232///////////////////////////////////////////////////////////////////////////////
233
234class FamilyTypeface : public SkTypeface {
235public:
236 FamilyTypeface(Style style, bool sysFont, FamilyRec* family)
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000237 : SkTypeface(style, sk_atomic_inc(&gUniqueFontID) + 1) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000238 fIsSysFont = sysFont;
239
240 SkAutoMutexAcquire ac(gFamilyMutex);
241
242 if (NULL == family) {
243 family = SkNEW(FamilyRec);
244 }
245 family->fFaces[style] = this;
246 fFamilyRec = family; // just record it so we can return it if asked
247 }
248
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000249 virtual ~FamilyTypeface() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000250 SkAutoMutexAcquire ac(gFamilyMutex);
251
252 // remove us from our family. If the family is now empty, we return
253 // that and then remove that family from the name list
254 FamilyRec* family = remove_from_family(this);
255 if (NULL != family) {
256 remove_from_names(family);
257 detach_and_delete_family(family);
258 }
259 }
260
261 bool isSysFont() const { return fIsSysFont; }
262 FamilyRec* getFamily() const { return fFamilyRec; }
263
264 virtual SkStream* openStream() = 0;
265 virtual void closeStream(SkStream*) = 0;
266 virtual const char* getUniqueString() const = 0;
267
268private:
269 FamilyRec* fFamilyRec; // we don't own this, just point to it
270 bool fIsSysFont;
271
272 typedef SkTypeface INHERITED;
273};
274
275///////////////////////////////////////////////////////////////////////////////
276
277class StreamTypeface : public FamilyTypeface {
278public:
279 StreamTypeface(Style style, bool sysFont, FamilyRec* family,
280 SkStream* stream)
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000281 : INHERITED(style, sysFont, family) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000282 fStream = stream;
283 }
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000284 virtual ~StreamTypeface() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000285 SkDELETE(fStream);
286 }
287
288 // overrides
289 virtual SkStream* openStream() { return fStream; }
290 virtual void closeStream(SkStream*) {}
291 virtual const char* getUniqueString() const { return NULL; }
292
293private:
294 SkStream* fStream;
295
296 typedef FamilyTypeface INHERITED;
297};
298
299class FileTypeface : public FamilyTypeface {
300public:
301 FileTypeface(Style style, bool sysFont, FamilyRec* family,
302 const char path[])
303 : INHERITED(style, sysFont, family) {
304 fPath.set(path);
305 }
306
307 // overrides
308 virtual SkStream* openStream()
309 {
310 SkStream* stream = SkNEW_ARGS(SkMMAPStream, (fPath.c_str()));
311
312 // check for failure
313 if (stream->getLength() <= 0) {
314 SkDELETE(stream);
315 // maybe MMAP isn't supported. try FILE
316 stream = SkNEW_ARGS(SkFILEStream, (fPath.c_str()));
317 if (stream->getLength() <= 0) {
318 SkDELETE(stream);
319 stream = NULL;
320 }
321 }
322 return stream;
323 }
324 virtual void closeStream(SkStream* stream)
325 {
326 SkDELETE(stream);
327 }
328 virtual const char* getUniqueString() const {
329 const char* str = strrchr(fPath.c_str(), '/');
330 if (str) {
331 str += 1; // skip the '/'
332 }
333 return str;
334 }
335
336private:
337 SkString fPath;
338
339 typedef FamilyTypeface INHERITED;
340};
341
342///////////////////////////////////////////////////////////////////////////////
343///////////////////////////////////////////////////////////////////////////////
344
345static bool get_name_and_style(const char path[], SkString* name,
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000346 SkTypeface::Style* style) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000347 SkMMAPStream stream(path);
348 if (stream.getLength() > 0) {
349 *style = find_name_and_style(&stream, name);
350 return true;
351 }
352 else {
353 SkFILEStream stream(path);
354 if (stream.getLength() > 0) {
355 *style = find_name_and_style(&stream, name);
356 return true;
357 }
358 }
359
360 SkDebugf("---- failed to open <%s> as a font\n", path);
361 return false;
362}
363
364// these globals are assigned (once) by load_system_fonts()
365static SkTypeface* gFallBackTypeface;
366static FamilyRec* gDefaultFamily;
367static SkTypeface* gDefaultNormal;
368
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000369static void load_system_fonts() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000370 // check if we've already be called
371 if (NULL != gDefaultNormal) {
372 return;
373 }
374
375 SkOSFile::Iter iter(SK_FONT_FILE_PREFIX, ".ttf");
376 SkString name;
377
378 while (iter.next(&name, false)) {
379 SkString filename;
380 GetFullPathForSysFonts(&filename, name.c_str());
381// while (filename.size() == 0) { filename.set("/usr/share/fonts/truetype/msttcorefonts/Arial.ttf");
382
383 SkString realname;
384 SkTypeface::Style style;
385
386 if (!get_name_and_style(filename.c_str(), &realname, &style)) {
387 SkDebugf("------ can't load <%s> as a font\n", filename.c_str());
388 continue;
389 }
390
391// SkDebugf("font: <%s> %d <%s>\n", realname.c_str(), style, filename.c_str());
392
393 FamilyRec* family = find_familyrec(realname.c_str());
394 // this constructor puts us into the global gFamilyHead llist
395 FamilyTypeface* tf = SkNEW_ARGS(FileTypeface,
396 (style,
397 true, // system-font (cannot delete)
398 family, // what family to join
399 filename.c_str()) // filename
400 );
401
402 if (NULL == family) {
403 add_name(realname.c_str(), tf->getFamily());
404 }
405 }
406
407 // do this after all fonts are loaded. This is our default font, and it
408 // acts as a sentinel so we only execute load_system_fonts() once
409 static const char* gDefaultNames[] = {
410 "Arial", "Verdana", "Times New Roman", NULL
411 };
412 const char** names = gDefaultNames;
413 while (*names) {
414 SkTypeface* tf = find_typeface(*names++, SkTypeface::kNormal);
415 if (tf) {
416 gDefaultNormal = tf;
417 break;
418 }
419 }
420 // check if we found *something*
421 if (NULL == gDefaultNormal) {
422 if (NULL == gFamilyHead) {
423 sk_throw();
424 }
425 for (int i = 0; i < 4; i++) {
426 if ((gDefaultNormal = gFamilyHead->fFaces[i]) != NULL) {
427 break;
428 }
429 }
430 }
431 if (NULL == gDefaultNormal) {
432 sk_throw();
433 }
434 gFallBackTypeface = gDefaultNormal;
435 gDefaultFamily = find_family(gDefaultNormal);
436
437// SkDebugf("---- default %p head %p family %p\n", gDefaultNormal, gFamilyHead, gDefaultFamily);
438}
439
440///////////////////////////////////////////////////////////////////////////////
441
442void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
443#if 0
444 const char* name = ((FamilyTypeface*)face)->getUniqueString();
445
446 stream->write8((uint8_t)face->getStyle());
447
448 if (NULL == name || 0 == *name) {
449 stream->writePackedUInt(0);
450 // SkDebugf("--- fonthost serialize null\n");
451 } else {
452 uint32_t len = strlen(name);
453 stream->writePackedUInt(len);
454 stream->write(name, len);
455 // SkDebugf("--- fonthost serialize <%s> %d\n", name, face->getStyle());
456 }
457#endif
458 sk_throw();
459}
460
461SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
462#if 0
463 load_system_fonts();
464
465 int style = stream->readU8();
466
467 int len = stream->readPackedUInt();
468 if (len > 0) {
469 SkString str;
470 str.resize(len);
471 stream->read(str.writable_str(), len);
472
473 const FontInitRec* rec = gSystemFonts;
474 for (size_t i = 0; i < SK_ARRAY_COUNT(gSystemFonts); i++) {
475 if (strcmp(rec[i].fFileName, str.c_str()) == 0) {
476 // backup until we hit the fNames
477 for (int j = i; j >= 0; --j) {
478 if (rec[j].fNames != NULL) {
479 return SkFontHost::FindTypeface(NULL, rec[j].fNames[0],
480 (SkTypeface::Style)style);
481 }
482 }
483 }
484 }
485 }
486 return SkFontHost::FindTypeface(NULL, NULL, (SkTypeface::Style)style);
487#endif
488 sk_throw();
reed@android.com6f252972009-01-14 16:46:16 +0000489 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000490}
491
492///////////////////////////////////////////////////////////////////////////////
493
494SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace,
495 const char familyName[],
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000496 SkTypeface::Style style) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000497 load_system_fonts();
498
499 SkAutoMutexAcquire ac(gFamilyMutex);
500
501 // clip to legal style bits
502 style = (SkTypeface::Style)(style & SkTypeface::kBoldItalic);
503
504 SkTypeface* tf = NULL;
505
506 if (NULL != familyFace) {
507 tf = find_typeface(familyFace, style);
508 } else if (NULL != familyName) {
509 // SkDebugf("======= familyName <%s>\n", familyName);
510 tf = find_typeface(familyName, style);
511 }
512
513 if (NULL == tf) {
514 tf = find_best_face(gDefaultFamily, style);
515 }
516
517 return tf;
518}
519
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000520SkTypeface* SkFontHost::ResolveTypeface(uint32_t fontID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000521 SkAutoMutexAcquire ac(gFamilyMutex);
522
523 return resolve_uniqueID(fontID);
524}
525
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000526SkStream* SkFontHost::OpenStream(uint32_t fontID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000527 FamilyTypeface* tf = (FamilyTypeface*)SkFontHost::ResolveTypeface(fontID);
528 SkStream* stream = tf ? tf->openStream() : NULL;
529
530 if (NULL == stream || stream->getLength() == 0) {
531 delete stream;
532 stream = NULL;
533 }
534 return stream;
535}
536
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000537void SkFontHost::CloseStream(uint32_t fontID, SkStream* stream) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000538 FamilyTypeface* tf = (FamilyTypeface*)SkFontHost::ResolveTypeface(fontID);
539 if (NULL != tf) {
540 tf->closeStream(stream);
541 }
542}
543
544SkScalerContext* SkFontHost::CreateFallbackScalerContext(
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000545 const SkScalerContext::Rec& rec) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000546 load_system_fonts();
547
548 SkAutoDescriptor ad(sizeof(rec) + SkDescriptor::ComputeOverhead(1));
549 SkDescriptor* desc = ad.getDesc();
550
551 desc->init();
552 SkScalerContext::Rec* newRec =
553 (SkScalerContext::Rec*)desc->addEntry(kRec_SkDescriptorTag,
554 sizeof(rec), &rec);
555 newRec->fFontID = gFallBackTypeface->uniqueID();
556 desc->computeChecksum();
557
558 return SkFontHost::CreateScalerContext(desc);
559}
560
561///////////////////////////////////////////////////////////////////////////////
562
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000563SkTypeface* SkFontHost::CreateTypeface(SkStream* stream) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000564 if (NULL == stream || stream->getLength() <= 0) {
565 SkDELETE(stream);
566 return NULL;
567 }
568
569 SkString name;
570 SkTypeface::Style style = find_name_and_style(stream, &name);
571
572 return SkNEW_ARGS(StreamTypeface, (style, false, NULL, stream));
573}
574
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000575SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) {
576 SkTypeface* face = NULL;
577 SkFILEStream* stream = SkNEW_ARGS(SkFILEStream, (path));
578
579 if (stream->isValid()) {
580 face = CreateTypeface(stream);
581 }
582 stream->unref();
583 return face;
reed@android.com0becfc5b2009-01-13 13:26:44 +0000584}
585
reed@android.com8a1c16f2008-12-17 15:59:43 +0000586///////////////////////////////////////////////////////////////////////////////
587
reed@android.com1bfd0ca2009-02-20 14:22:36 +0000588size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000589 if (sizeAllocatedSoFar > FONT_CACHE_MEMORY_BUDGET)
590 return sizeAllocatedSoFar - FONT_CACHE_MEMORY_BUDGET;
591 else
592 return 0; // nothing to do
593}
594