summaryrefslogtreecommitdiff
path: root/Build/source/texk/dvisvgm/dvisvgm-1.2.2/src/Font.cpp
blob: f9ec0737a2d8e24662e1c1eff1a51e4a24ccd354 (plain)
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
/*************************************************************************
** Font.cpp                                                             **
**                                                                      **
** This file is part of dvisvgm -- the DVI to SVG converter             **
** Copyright (C) 2005-2013 Martin Gieseking <martin.gieseking@uos.de>   **
**                                                                      **
** This program is free software; you can redistribute it and/or        **
** modify it under the terms of the GNU General Public License as       **
** published by the Free Software Foundation; either version 3 of       **
** the License, or (at your option) any later version.                  **
**                                                                      **
** This program 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 for more details.                         **
**                                                                      **
** You should have received a copy of the GNU General Public License    **
** along with this program; if not, see <http://www.gnu.org/licenses/>. **
*************************************************************************/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include "FileSystem.h"
#include "Font.h"
#include "FontEngine.h"
#include "FileFinder.h"
#include "GFGlyphTracer.h"
#include "Glyph.h"
#include "Message.h"
#include "MetafontWrapper.h"
#include "TFM.h"
#include "VFReader.h"
#include "macros.h"
#include "FileSystem.h"
#include "SignalHandler.h"
#include "Subfont.h"
#include "SVGTree.h"
#include "FontMap.h"

using namespace std;


/** Returns true if 'unicode' is a valid unicode value in XML documents.
 *  XML version 1.0 doesn't allow various unicode character references
 *  (&#1; for example).  */
static bool valid_unicode (UInt32 unicode) {
	UInt32 ranges[] = {
		0x0000, 0x0020,
		0x007f, 0x0084,
		0x0086, 0x009f,
		0xfdd0, 0xfddf
	};
	for (int i=0; i < 4; i++)
		if (unicode >= ranges[2*i] && unicode <= ranges[2*i+1])
			return false;
	return true;
}


UInt32 Font::unicode (UInt32 c) const {
	// @@ this should be optimized :-)
	return valid_unicode(c) ? c : 0x3400+c;
}


///////////////////////////////////////////////////////////////////////////////////////


TFMFont::TFMFont (string name, UInt32 cs, double ds, double ss)
	: tfm(0), fontname(name), checksum(cs), dsize(ds), ssize(ss)
{
}


TFMFont::~TFMFont () {
	delete tfm;
}


/** Returns a font metrics object for the current font.
 *  @throw FontException if TFM file can't be found */
const TFM* TFMFont::getTFM () const {
	if (!tfm) {
		tfm = TFM::createFromFile(fontname.c_str());
		if (!tfm)
			throw FontException("can't find "+fontname+".tfm");
	}
	return tfm;
}


double TFMFont::charWidth (int c) const {
	double w = getTFM()->getCharWidth(c);
	if (style())
		w *= style()->extend;
	return w;
}


double TFMFont::italicCorr (int c) const {
	double w = getTFM()->getItalicCorr(c);
	if (style())
		w *= style()->extend;
	return w;
}


double TFMFont::charDepth (int c) const  {return getTFM()->getCharDepth(c);}
double TFMFont::charHeight (int c) const {return getTFM()->getCharHeight(c);}


bool TFMFont::verifyChecksums () const   {
	if (checksum != 0 && getTFM()->getChecksum() != 0)
		return checksum == getTFM()->getChecksum();
	return true;
}

//////////////////////////////////////////////////////////////////////////////

// static class variables
bool PhysicalFont::KEEP_TEMP_FILES = false;
const char *PhysicalFont::CACHE_PATH = 0;
double PhysicalFont::METAFONT_MAG = 4;
FontCache PhysicalFont::_cache;


Font* PhysicalFont::create (string name, UInt32 checksum, double dsize, double ssize, PhysicalFont::Type type) {
	return new PhysicalFontImpl(name, 0, checksum, dsize, ssize, type);
}


Font* PhysicalFont::create (string name, int fontindex, UInt32 checksum, double dsize, double ssize) {
	return new PhysicalFontImpl(name, fontindex, checksum, dsize, ssize, PhysicalFont::TTC);
}


const char* PhysicalFont::path () const {
	string ext;
	switch (type()) {
		case PFB: ext = "pfb"; break;
		case TTC: ext = "ttc"; break;
		case TTF: ext = "ttf"; break;
		case MF : ext = "mf";  break;
	}
	return FileFinder::lookup(name()+"."+ext);
}


/** Returns the number of units per EM. The EM square is the virtual area a glyph is designed on.
 *  All coordinates used to specify portions of the glyph are relative to the origin (0,0) at the
 *  lower left corner of this square, while the upper right corner is located at (m,m), where m
 *  is an integer value defined with the font, and returned by this function. */
int PhysicalFont::unitsPerEm() const {
	if (type() == MF)
		return 1000;
	FontEngine::instance().setFont(*this);
	return FontEngine::instance().getUnitsPerEM();
}


int PhysicalFont::hAdvance () const {
	if (type() == MF)
		return 0;
	FontEngine::instance().setFont(*this);
	return FontEngine::instance().getHAdvance();
}


double PhysicalFont::hAdvance (int c) const {
	if (type() == MF)
		return unitsPerEm()*charWidth(c)/designSize();
	FontEngine::instance().setFont(*this);
	if (FontEncoding *enc = encoding())
		return FontEngine::instance().getHAdvance(enc->getEntry(c));
	if (const FontMap::Entry *map_entry = FontMap::instance().lookup(name()))
		if (Subfont *sf = map_entry->subfont)
			c = sf->decode(c);
	return FontEngine::instance().getHAdvance(c);
}


string PhysicalFont::glyphName (int c) const {
	if (type() == MF)
		return "";
	FontEngine::instance().setFont(*this);
	if (FontEncoding *enc = encoding()) {
		const char *name = enc->getEntry(c);
		return name ? name : "";
	}
	if (const FontMap::Entry *map_entry = FontMap::instance().lookup(name()))
		if (Subfont *sf = map_entry->subfont)
			c = sf->decode(c);
	return FontEngine::instance().getGlyphName(c);
}


int PhysicalFont::ascent () const {
	if (type() == MF)
		return 0;
	FontEngine::instance().setFont(*this);
	return FontEngine::instance().getAscender();
}


int PhysicalFont::descent () const {
	if (type() == MF)
		return 0;
	FontEngine::instance().setFont(*this);
	return FontEngine::instance().getDescender();
}


/** Extracts the glyph outlines of a given character.
 *  @param[in]  c character code of requested glyph
 *  @param[out] glyph path segments of the glyph outline
 *  @param[in]  cb optional callback object for tracer class
 *  @return true if outline could be computed */
bool PhysicalFont::getGlyph (int c, GraphicPath<Int32> &glyph, GFGlyphTracer::Callback *cb) const {
	if (type() == MF) {
		const Glyph *cached_glyph=0;
		if (CACHE_PATH) {
			_cache.write(CACHE_PATH);
			_cache.read(name().c_str(), CACHE_PATH);
			cached_glyph = _cache.getGlyph(c);
		}
		if (cached_glyph) {
			glyph = *cached_glyph;
			return true;
		}
		else {
			string gfname;
			if (createGF(gfname)) {
				try {
					GFGlyphTracer tracer(gfname, unitsPerEm()/getTFM()->getDesignSize(), cb);
					tracer.setGlyph(glyph);
					tracer.executeChar(c);
					glyph.closeOpenSubPaths();
					if (CACHE_PATH)
						_cache.setGlyph(c, glyph);
					return true;
				}
				catch (GFException &e) {
					// @@ print error message
				}
			}
			else {
				Message::wstream(true) << "failed creating " << name() << ".gf\n";
			}
		}
	}
	else { // PFB or TTF
		bool ok=true;
		FontEngine::instance().setFont(*this);
		if (FontEncoding *enc = encoding()) {
			if (const char *encname = enc->getEntry(c))
				ok = FontEngine::instance().traceOutline(encname, glyph, false);
		}
		else {
			if (const FontMap::Entry *map_entry = FontMap::instance().lookup(name()))
				if (Subfont *sf = map_entry->subfont)
					c = sf->decode(c);
			ok = FontEngine::instance().traceOutline(c, glyph, false);
		}
		glyph.closeOpenSubPaths();
		return ok;
	}
	return false;
}


/** Creates a GF file for this font object.
 *  @param[out] gfname name of GF font file
 *  @return true on success */
bool PhysicalFont::createGF (string &gfname) const {
	SignalHandler::instance().check();
	gfname = name()+".gf";
	MetafontWrapper mf(name());
	bool ok = mf.make("ljfour", METAFONT_MAG); // call Metafont if necessary
	return ok && mf.success() && getTFM();
}


/** Traces all glyphs of the current font and stores them in the cache. If caching is disabled, nothing happens.
 *  @param[in] includeCached if true, glyphs already cached are traced again
 *  @param[in] cb optional callback methods called by the tracer
 *  @return number of glyphs traced */
int PhysicalFont::traceAllGlyphs (bool includeCached, GFGlyphTracer::Callback *cb) const {
	int count = 0;
	if (type() == MF && CACHE_PATH) {
		if (const TFM *tfm = getTFM()) {
			int fchar = tfm->firstChar();
			int lchar = tfm->lastChar();
			string gfname;
			Glyph glyph;
			if (createGF(gfname)) {
				_cache.read(name().c_str(), CACHE_PATH);
				GFGlyphTracer tracer(gfname, unitsPerEm()/getTFM()->getDesignSize(), cb);
				tracer.setGlyph(glyph);
				for (int i=fchar; i <= lchar; i++) {
					if (includeCached || !_cache.getGlyph(i)) {
						glyph.newpath();
						tracer.executeChar(i);
						glyph.closeOpenSubPaths();
						_cache.setGlyph(i, glyph);
						++count;
					}
				}
				_cache.write(CACHE_PATH);
			}
		}
	}
	return count;
}


/** Computes the exact bounding box of a glyph.
 *  @param[in]  c character code of the glyph
 *  @param[out] bbox the computed bounding box
 *  @param[in]  optional calback object forwarded to the tracer
 *  @return true if the box could be computed successfully */
bool PhysicalFont::getGlyphBox(int c, BoundingBox& bbox, GFGlyphTracer::Callback* cb) const {
	Glyph glyph;
	if (getGlyph(c, glyph, cb)) {
		glyph.computeBBox(bbox);
		double s = scaledSize()/unitsPerEm();
		bbox.scale(s, s);
		return true;
	}
	return false;
}


Font* VirtualFont::create (string name, UInt32 checksum, double dsize, double ssize) {
	return new VirtualFontImpl(name, checksum, dsize, ssize);
}


//////////////////////////////////////////////////////////////////////////////


PhysicalFontImpl::PhysicalFontImpl (string name, int fontindex, UInt32 cs, double ds, double ss, PhysicalFont::Type type)
	: TFMFont(name, cs, ds, ss), _filetype(type), _fontIndex(fontindex), _style(0), _charmap(0)
{
}


PhysicalFontImpl::~PhysicalFontImpl () {
	if (CACHE_PATH)
		_cache.write(CACHE_PATH);
	if (!KEEP_TEMP_FILES)
		tidy();
	delete _style;
	delete _charmap;
}


UInt32 PhysicalFontImpl::unicode (UInt32 c) const {
	if (type() == MF)
		return Font::unicode(c);

	if (_charmap == 0) {
		FontEngine &fe = FontEngine::instance();
		if (fe.setFont(*this)) {
			_charmap = new map<UInt32,UInt32>;
			fe.buildTranslationMap(*_charmap);
		}
	}
	typedef map<UInt32,UInt32>::const_iterator ConstIterator;
	ConstIterator it = _charmap->find(c);
	if (it != _charmap->end())
		return it->second;

	// No unicode equivalent found in font file.
	// Now we should look for a smart alternative but at the moment
	// it's sufficient to simply choose a valid unused unicode value...
	map<UInt32,UInt32> reverse_map;
	FORALL(*_charmap, ConstIterator, it)
		reverse_map[it->second] = it->first;
	// can we use charcode itself as unicode replacement?
	if (valid_unicode(c) && (reverse_map.empty() || reverse_map.find(c) != reverse_map.end()))
		return c;
	return 0x3400+c;
}


void PhysicalFontImpl::tidy () const {
   if (type() == MF) {
		const char *ext[] = {"gf", "tfm", "log", 0};
		for (const char **p=ext; *p; ++p) {
			if (FileSystem::exists((name()+"."+(*p)).c_str()))
				FileSystem::remove(name()+"."+(*p));
		}
   }
}


void PhysicalFontImpl::setStyle (double bold, double extend, double slant) {
	if (_style) {
		_style->bold = bold;
		_style->extend = extend;
		_style->slant = slant;
	}
	else if (bold != 0 || extend != 1 || slant != 0)
		_style = new Style(bold, extend, slant);
}


//////////////////////////////////////////////////////////////////////////////

VirtualFontImpl::VirtualFontImpl (string name, UInt32 cs, double ds, double ss)
	: TFMFont(name, cs, ds, ss)
{
}


VirtualFontImpl::~VirtualFontImpl () {
	// delete dvi vectors received by VFReaderAction
	for (map<UInt32, DVIVector*>::iterator i=charDefs.begin(); i != charDefs.end(); ++i)
		delete i->second;
}


const char* VirtualFontImpl::path () const {
	return FileFinder::lookup(name()+".vf");
}


void VirtualFontImpl::assignChar (UInt32 c, DVIVector *dvi) {
	if (dvi) {
		if (charDefs.find(c) == charDefs.end())
			charDefs[c] = dvi;
		else
			delete dvi;
	}
}


const vector<UInt8>* VirtualFontImpl::getDVI (int c) const {
	map<UInt32,DVIVector*>::const_iterator it = charDefs.find(c);
	return (it == charDefs.end() ? 0 : it->second);
}