xref: /haiku/src/servers/app/font/FontCacheEntry.cpp (revision 52f7c9389475e19fc21487b38064b4390eeb6fea)
1 /*
2  * Copyright 2007-2009, Haiku. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Maxim Shemanarev <mcseemagg@yahoo.com>
7  *		Stephan Aßmus <superstippi@gmx.de>
8  *		Andrej Spielmann, <andrej.spielmann@seh.ox.ac.uk>
9  */
10 
11 //----------------------------------------------------------------------------
12 // Anti-Grain Geometry - Version 2.4
13 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
14 //
15 // Permission to copy, use, modify, sell and distribute this software
16 // is granted provided this copyright notice appears in all copies.
17 // This software is provided "as is" without express or implied
18 // warranty, and with no claim as to its suitability for any purpose.
19 //
20 //----------------------------------------------------------------------------
21 // Contact: mcseem@antigrain.com
22 //			mcseemagg@yahoo.com
23 //			http://www.antigrain.com
24 //----------------------------------------------------------------------------
25 
26 
27 #include "FontCacheEntry.h"
28 
29 #include <string.h>
30 
31 #include <new>
32 
33 #include <Autolock.h>
34 
35 #include <agg_array.h>
36 #include <utf8_functions.h>
37 #include <util/OpenHashTable.h>
38 
39 #include "GlobalSubpixelSettings.h"
40 
41 
42 BLocker FontCacheEntry::sUsageUpdateLock("FontCacheEntry usage lock");
43 
44 
45 class FontCacheEntry::GlyphCachePool {
46 	// This class needs to be defined before any inline functions, as otherwise
47 	// gcc2 will barf in debug mode.
48 	struct GlyphHashTableDefinition {
49 		typedef uint32		KeyType;
50 		typedef	GlyphCache	ValueType;
51 
52 		size_t HashKey(uint32 key) const
53 		{
54 			return key;
55 		}
56 
57 		size_t Hash(GlyphCache* value) const
58 		{
59 			return value->glyph_index;
60 		}
61 
62 		bool Compare(uint32 key, GlyphCache* value) const
63 		{
64 			return value->glyph_index == key;
65 		}
66 
67 		GlyphCache*& GetLink(GlyphCache* value) const
68 		{
69 			return value->hash_link;
70 		}
71 	};
72 public:
73 	GlyphCachePool()
74 	{
75 	}
76 
77 	~GlyphCachePool()
78 	{
79 		GlyphCache* glyph = fGlyphTable.Clear(true);
80 		while (glyph != NULL) {
81 			GlyphCache* next = glyph->hash_link;
82 			delete glyph;
83 			glyph = next;
84 		}
85 	}
86 
87 	status_t Init()
88 	{
89 		return fGlyphTable.Init();
90 	}
91 
92 	const GlyphCache* FindGlyph(uint32 glyphIndex) const
93 	{
94 		return fGlyphTable.Lookup(glyphIndex);
95 	}
96 
97 	GlyphCache* CacheGlyph(uint32 glyphIndex,
98 		uint32 dataSize, glyph_data_type dataType, const agg::rect_i& bounds,
99 		float advanceX, float advanceY, float preciseAdvanceX,
100 		float preciseAdvanceY, float insetLeft, float insetRight)
101 	{
102 		GlyphCache* glyph = fGlyphTable.Lookup(glyphIndex);
103 		if (glyph != NULL)
104 			return NULL;
105 
106 		glyph = new(std::nothrow) GlyphCache(glyphIndex, dataSize, dataType,
107 			bounds, advanceX, advanceY, preciseAdvanceX, preciseAdvanceY,
108 			insetLeft, insetRight);
109 		if (glyph == NULL || glyph->data == NULL) {
110 			delete glyph;
111 			return NULL;
112 		}
113 
114 		// TODO: The HashTable grows without bounds. We should cleanup
115 		// older entries from time to time.
116 
117 		fGlyphTable.Insert(glyph);
118 
119 		return glyph;
120 	}
121 
122 private:
123 	typedef BOpenHashTable<GlyphHashTableDefinition> GlyphTable;
124 
125 	GlyphTable	fGlyphTable;
126 };
127 
128 
129 // #pragma mark -
130 
131 
132 FontCacheEntry::FontCacheEntry()
133 	:
134 	MultiLocker("FontCacheEntry lock"),
135 	fGlyphCache(new(std::nothrow) GlyphCachePool()),
136 	fEngine(),
137 	fLastUsedTime(LONGLONG_MIN),
138 	fUseCounter(0)
139 {
140 }
141 
142 
143 FontCacheEntry::~FontCacheEntry()
144 {
145 //printf("~FontCacheEntry()\n");
146 }
147 
148 
149 bool
150 FontCacheEntry::Init(const ServerFont& font, bool forceVector)
151 {
152 	if (!fGlyphCache.IsSet())
153 		return false;
154 
155 	glyph_rendering renderingType = _RenderTypeFor(font, forceVector);
156 
157 	// TODO: encoding from font
158 	FT_Encoding charMap = FT_ENCODING_NONE;
159 	bool hinting = font.Hinting();
160 
161 	if (!fEngine.Init(font.Path(), 0, font.Size(), charMap,
162 			renderingType, hinting)) {
163 		fprintf(stderr, "FontCacheEntry::Init() - some error loading font "
164 			"file %s\n", font.Path());
165 		return false;
166 	}
167 	if (fGlyphCache->Init() != B_OK) {
168 		fprintf(stderr, "FontCacheEntry::Init() - failed to allocate "
169 			"GlyphCache table for font file %s\n", font.Path());
170 		return false;
171 	}
172 
173 	return true;
174 }
175 
176 
177 bool
178 FontCacheEntry::HasGlyphs(const char* utf8String, ssize_t length) const
179 {
180 	uint32 glyphCode;
181 	const char* start = utf8String;
182 	while ((glyphCode = UTF8ToCharCode(&utf8String))) {
183 		if (fGlyphCache->FindGlyph(glyphCode) == NULL)
184 			return false;
185 		if (utf8String - start + 1 > length)
186 			break;
187 	}
188 	return true;
189 }
190 
191 
192 inline bool
193 render_as_space(uint32 glyphCode)
194 {
195 	// whitespace: render as space
196 	// as per Unicode PropList.txt: White_Space
197 	return (glyphCode >= 0x0009 && glyphCode <= 0x000d)
198 			// control characters
199 		|| (glyphCode == 0x0085)
200 			// another control
201 		|| (glyphCode == 0x00a0)
202 			// no-break space
203 		|| (glyphCode == 0x1680)
204 			// ogham space mark
205 		|| (glyphCode >= 0x2000 && glyphCode <= 0x200a)
206 			// en quand, hair space
207 		|| (glyphCode >= 0x2028 && glyphCode <= 0x2029)
208 			// line and paragraph separators
209 		|| (glyphCode == 0x202f)
210 			// narrow no-break space
211 		|| (glyphCode == 0x205f)
212 			// medium math space
213 		|| (glyphCode == 0x3000)
214 			// ideographic space
215 		;
216 }
217 
218 
219 inline bool
220 render_as_zero_width(uint32 glyphCode)
221 {
222 	// ignorable chars: render as invisible
223 	// as per Unicode DerivedCoreProperties.txt: Default_Ignorable_Code_Point.
224 	// We also don't want tofu for noncharacters if we ever get one.
225 	return (glyphCode == 0x00ad)
226 			// soft hyphen
227 		|| (glyphCode == 0x034f)
228 			// combining grapheme joiner
229 		|| (glyphCode == 0x061c)
230 			// arabic letter mark
231 		|| (glyphCode >= 0x115f && glyphCode <= 0x1160)
232 			// hangul fillers
233 		|| (glyphCode >= 0x17b4 && glyphCode <= 0x17b5)
234 			// ignorable khmer vowels
235 		|| (glyphCode >= 0x180b && glyphCode <= 0x180f)
236 			// mongolian variation selectors and vowel separator
237 		|| (glyphCode >= 0x200b && glyphCode <= 0x200f)
238 			// zero width space, cursive joiners, ltr marks
239 		|| (glyphCode >= 0x202a && glyphCode <= 0x202e)
240 			// left to right embed, override
241 		|| (glyphCode >= 0x2060 && glyphCode <= 0x206f)
242 			// word joiner, invisible math operators, reserved
243 		|| (glyphCode == 0x3164)
244 			// hangul filler
245 		|| (glyphCode >= 0xfe00 && glyphCode <= 0xfe0f)
246 			// variation selectors
247 		|| (glyphCode == 0xfeff)
248 			// zero width no-break space
249 		|| (glyphCode == 0xffa0)
250 			// halfwidth hangul filler
251 		|| (glyphCode >= 0xfff0 && glyphCode <= 0xfff8)
252 			// reserved
253 		|| (glyphCode >= 0x1bca0 && glyphCode <= 0x1bca3)
254 			// shorthand format controls
255 		|| (glyphCode >= 0x1d173 && glyphCode <= 0x1d17a)
256 			// musical symbols
257 		|| (glyphCode >= 0xe0000 && glyphCode <= 0xe01ef)
258 			// variation selectors, tag space, reserved
259 		|| (glyphCode >= 0xe01f0 && glyphCode <= 0xe0fff)
260 			// reserved
261 		|| ((glyphCode & 0xffff) >= 0xfffe)
262 			// noncharacters
263 		|| ((glyphCode >= 0xfdd0 && glyphCode <= 0xfdef)
264 			&& glyphCode != 0xfdd1)
265 			// noncharacters; 0xfdd1 is used internally to force .notdef glyph
266 		;
267 }
268 
269 
270 const GlyphCache*
271 FontCacheEntry::CachedGlyph(uint32 glyphCode)
272 {
273 	// Only requires a read lock.
274 	return fGlyphCache->FindGlyph(glyphCode);
275 }
276 
277 
278 bool
279 FontCacheEntry::CanCreateGlyph(uint32 glyphCode)
280 {
281 	// Note that this bypass any fallback or caching because it is used in
282 	// the fallback code itself.
283 	uint32 glyphIndex = fEngine.GlyphIndexForGlyphCode(glyphCode);
284 	return glyphIndex != 0;
285 }
286 
287 
288 const GlyphCache*
289 FontCacheEntry::CreateGlyph(uint32 glyphCode, FontCacheEntry* fallbackEntry)
290 {
291 	// We cache the glyph by the requested glyphCode. The FontEngine of this
292 	// FontCacheEntry may not contain a glyph for the given code, in which case
293 	// we ask the fallbackEntry for the code to index translation and let it
294 	// generate the glyph data. We will still use our own cache for storing the
295 	// glyph. The next time it will be found (by glyphCode).
296 
297 	// NOTE: Both this and the fallback FontCacheEntry are expected to be
298 	// write-locked!
299 
300 	const GlyphCache* glyph = fGlyphCache->FindGlyph(glyphCode);
301 	if (glyph != NULL)
302 		return glyph;
303 
304 	FontEngine* engine = &fEngine;
305 	uint32 glyphIndex = engine->GlyphIndexForGlyphCode(glyphCode);
306 	if (glyphIndex == 0 && fallbackEntry != NULL) {
307 		// Our FontEngine does not contain this glyph, but we can retry with
308 		// the fallbackEntry.
309 		engine = &fallbackEntry->fEngine;
310 		glyphIndex = engine->GlyphIndexForGlyphCode(glyphCode);
311 	}
312 
313 	if (glyphIndex == 0) {
314 		if (render_as_zero_width(glyphCode)) {
315 			// cache and return a zero width glyph
316 			return fGlyphCache->CacheGlyph(glyphCode, 0, glyph_data_invalid,
317 				agg::rect_i(0, 0, -1, -1), 0, 0, 0, 0, 0, 0);
318 		}
319 
320 		// reset to our engine
321 		engine = &fEngine;
322 		if (render_as_space(glyphCode)) {
323 			// get the normal space glyph
324 			glyphIndex = engine->GlyphIndexForGlyphCode(0x20 /* space */);
325 		}
326 	}
327 
328 	if (engine->PrepareGlyph(glyphIndex)) {
329 		glyph = fGlyphCache->CacheGlyph(glyphCode,
330 			engine->DataSize(), engine->DataType(), engine->Bounds(),
331 			engine->AdvanceX(), engine->AdvanceY(),
332 			engine->PreciseAdvanceX(), engine->PreciseAdvanceY(),
333 			engine->InsetLeft(), engine->InsetRight());
334 
335 		if (glyph != NULL)
336 			engine->WriteGlyphTo(glyph->data);
337 	}
338 
339 	return glyph;
340 }
341 
342 
343 void
344 FontCacheEntry::InitAdaptors(const GlyphCache* glyph,
345 	double x, double y, GlyphMonoAdapter& monoAdapter,
346 	GlyphGray8Adapter& gray8Adapter, GlyphPathAdapter& pathAdapter,
347 	double scale)
348 {
349 	if (glyph == NULL)
350 		return;
351 
352 	switch(glyph->data_type) {
353 		case glyph_data_mono:
354 			monoAdapter.init(glyph->data, glyph->data_size, x, y);
355 			break;
356 
357 		case glyph_data_gray8:
358 			gray8Adapter.init(glyph->data, glyph->data_size, x, y);
359 			break;
360 
361 		case glyph_data_subpix:
362 			gray8Adapter.init(glyph->data, glyph->data_size, x, y);
363 			break;
364 
365 		case glyph_data_outline:
366 			pathAdapter.init(glyph->data, glyph->data_size, x, y, scale);
367 			break;
368 
369 		default:
370 			break;
371 	}
372 }
373 
374 
375 bool
376 FontCacheEntry::GetKerning(uint32 glyphCode1, uint32 glyphCode2,
377 	double* x, double* y)
378 {
379 	return fEngine.GetKerning(glyphCode1, glyphCode2, x, y);
380 }
381 
382 
383 /*static*/ void
384 FontCacheEntry::GenerateSignature(char* signature, size_t signatureSize,
385 	const ServerFont& font, bool forceVector)
386 {
387 	glyph_rendering renderingType = _RenderTypeFor(font, forceVector);
388 
389 	// TODO: read more of these from the font
390 	FT_Encoding charMap = FT_ENCODING_NONE;
391 	bool hinting = font.Hinting();
392 	uint8 averageWeight = gSubpixelAverageWeight;
393 
394 	snprintf(signature, signatureSize, "%" B_PRId32 ",%u,%d,%d,%.1f,%d,%d",
395 		font.GetFamilyAndStyle(), charMap,
396 		font.Face(), int(renderingType), font.Size(), hinting, averageWeight);
397 }
398 
399 
400 void
401 FontCacheEntry::UpdateUsage()
402 {
403 	// this is a static lock to prevent usage of too many semaphores,
404 	// but on the other hand, it is not so nice to be using a lock
405 	// here at all
406 	// the hope is that the time is so short to hold this lock, that
407 	// there is not much contention
408 	BAutolock _(sUsageUpdateLock);
409 
410 	fLastUsedTime = system_time();
411 	fUseCounter++;
412 }
413 
414 
415 /*static*/ glyph_rendering
416 FontCacheEntry::_RenderTypeFor(const ServerFont& font, bool forceVector)
417 {
418 	glyph_rendering renderingType = gSubpixelAntialiasing ?
419 		glyph_ren_subpix : glyph_ren_native_gray8;
420 
421 	if (forceVector || font.Rotation() != 0.0 || font.Shear() != 90.0
422 		|| font.FalseBoldWidth() != 0.0
423 		|| (font.Flags() & B_DISABLE_ANTIALIASING) != 0
424 		|| font.Size() > 30
425 		|| !font.Hinting()) {
426 		renderingType = glyph_ren_outline;
427 	}
428 
429 	return renderingType;
430 }
431