This file is indexed.

/usr/lib/python2.7/dist-packages/uniconvertor/app/Graphics/font.py is in python-uniconvertor 1.1.5-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# Sketch - A Python-based interactive drawing program
# Copyright (C) 1997, 1998, 1999, 2000 by Bernhard Herzog
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#
#	Font management...
#

import os, re, operator
from string import split, strip, atoi, atof, lower, translate, maketrans


import streamfilter

from app import _, config, Point, TrafoType, Scale, SketchError, \
		SketchInternalError, Subscribe, CreatePath, CreateFontMetric, SKCache
		
from app.conf import const
from app.Lib import encoding

from app.events.warn import warn, INTERNAL, USER, pdebug
from sk1libs.utils.fs import find_in_path, find_files_in_path

minus_tilde = maketrans('-', '~')

def xlfd_matrix(trafo):
	mat = '[%f %f %f %f]' % trafo.matrix()
	return translate(mat, minus_tilde)


def _str(val):
	return strip(val)

def _bb(val):
	return tuple(map(int, map(round, map(atof, split(strip(val))))))

def _number(val):
	return int(round(atof(val)))

converters = {
	'EncodingScheme':	_str,
	'Ascender':		_number,
	'Descender':	_number,
	'ItalicAngle':	atof,
	'FontBBox':		_bb,
	'StartCharMetrics':	None,
	'EndFontMetrics':	None
}

StandardEncoding = 'AdobeStandardEncoding'

def read_char_metrics(afm):
	# read the individual char metrics. Assumes that each line contains
	# the keys C, W, N and B. Of these keys, only C (or CH, but that's
	# not implemented here) is really required by the AFM specification.
	charmetrics = {encoding.notdef: (0, 0,0,0,0)}
	font_encoding = [encoding.notdef] * 256
	while 1:
		line = afm.readline()
		if line == 'EndCharMetrics\n':
			break
		items = filter(None, map(strip, split(line, ';')))
		if not items:
			continue
		code = name = width = bbox = None
		for item in items:
			[key, value] = split(item, None, 1)
			if key == 'C':
				code = atoi(value)
			elif key == 'WX':
				width = int(round(atof(value)))
			elif key == 'N':
				name = value
			elif key == 'B':
				bbox = tuple(map(int,map(round,map(atof,split(value)))))
		charmetrics[name] = (width,) + bbox
		font_encoding[code] = name
	return charmetrics, font_encoding

def read_afm_file(filename):
	afm = streamfilter.LineDecode(open(filename, 'r'))

	attribs = {'ItalicAngle': 0.0}
	charmetrics = None
	font_encoding = [encoding.notdef] * 256

	while 1:
		line = afm.readline()
		if not line:
			break
		try:
			[key, value] = split(line, None, 1)
		except ValueError:
			# this normally means that a line contained only a keyword
			# but no value or that the line was empty
			continue
		try:
			action = converters[key]
		except KeyError:
			continue
		if action:
			attribs[key] = action(value)
		elif key == 'StartCharMetrics':
			charmetrics, font_encoding = read_char_metrics(afm)
			break
		else:
			# EndFontMetrics
			break

	if not charmetrics:
		raise ValueError, \
				'AFM files without individual char metrics not yet supported.'

	if attribs.get('EncodingScheme', StandardEncoding) == StandardEncoding:
		enc = encoding.iso_latin_1
	else:
		enc = font_encoding

	try:
		rescharmetrics = map(operator.getitem, [charmetrics] * len(enc), enc)
	except KeyError:
		# Some iso-latin-1 glyphs are not defined in the font. Try the
		# slower way and report missing glyphs.
		length = len(enc)
		rescharmetrics = [(0, 0,0,0,0)] * length
		for idx in range(length):
			name = enc[idx]
			try:
				rescharmetrics[idx] = charmetrics[name]
			except KeyError:
				# missing character...
				warn(INTERNAL, '%s: missing character %s', filename, name)

	# some fonts don't define ascender and descender (psyr.afm for
	# instance). use the values from the font bounding box instead. This
	# is not really a good idea, but how do we solve this?
	#
	# If psyr.afm is the only afm-file where these values are missing
	# (?) we could use the values from the file s050000l.afm shipped
	# with ghostscript (or replace psyr.afm with that file).
	#
	# This is a more general problem since many of the values Sketch
	# reads from afm files are only optional (including ascender and
	# descender).
	if not attribs.has_key('Ascender'):
		attribs['Ascender'] = attribs['FontBBox'][3]
	if not attribs.has_key('Descender'):
		attribs['Descender'] = attribs['FontBBox'][1]

	return (CreateFontMetric(attribs['Ascender'], attribs['Descender'],
								attribs['FontBBox'], attribs['ItalicAngle'],
								rescharmetrics),
			enc)


_warned_about_afm = {}
def read_metric(ps_name):
	for afm in ps_to_filename[ps_name]:
		afm = afm + '.afm'
		filename = find_in_path(config.font_path, afm)
		if filename:
			if __debug__:
				import time
				start = time.clock()
			metric = read_afm_file(filename)
			if __debug__:
				pdebug('timing', 'time to read afm %s: %g', afm,
						time.clock() - start)
			return metric
	else:
		if not _warned_about_afm.get(afm):
			warn(USER,
					_("I cannot find the metrics for the font %(ps_name)s.\n"
					"The file %(afm)s is not in the font_path.\n"
					"I'll use the metrics for %(fallback)s instead."),
					ps_name = ps_name, afm = afm,
					fallback = config.preferences.fallback_font)
			_warned_about_afm[afm] = 1
		if ps_name != config.preferences.fallback_font:
			return read_metric(config.preferences.fallback_font)
		else:
			raise SketchError("Can't load metrics for fallback font %s",
								config.preferences.fallback_font)


def font_file_name(ps_name):
	names = []
	for basename in ps_to_filename[ps_name]:
		names.append(basename + '.pfb')
		names.append(basename + '.pfa')
	filename = find_files_in_path(config.font_path, names)
	return filename

	
def read_outlines(ps_name):
	filename = font_file_name(ps_name)
	if filename:
		if __debug__:
			pdebug('font', 'read_outlines: %s', filename)

		import app.Lib.type1
		return app.Lib.type1.read_outlines(filename)
	else:
		raise SketchInternalError('Cannot find file for font %s' % ps_name)

def convert_outline(outline):
	paths = []
	trafo = Scale(0.001)
	for closed, sub in outline:
		if closed:
			sub.append(sub[0])
		path = CreatePath()
		paths.append(path)
		for item in sub:
			if len(item) == 2:
				apply(path.AppendLine, item)
			else:
				apply(path.AppendBezier, item)
		if closed:
			path.load_close()
	for path in paths:
		path.Transform(trafo)
	return tuple(paths)




fontlist = []
fontmap = {}
ps_to_filename = {}

def _add_ps_filename(ps_name, filename):
	filename = (filename,)
	if ps_to_filename.has_key(ps_name):
		filename = ps_to_filename[ps_name] + filename
	ps_to_filename[ps_name] = filename

def read_font_dirs():
	#print 'read_font_dirs'
	if __debug__:
		import time
		start = time.clock()

	rx_sfd = re.compile(r'^.*\.sfd$')
	for directory in config.font_path:
		#print directory
		try:
			filenames = os.listdir(directory)
		except os.error, exc:
			warn(USER, _("Cannot list directory %s:%s\n"
							"ignoring it in font_path"),
					directory, str(exc))
			continue
		dirfiles = filter(rx_sfd.match, filenames)
		for filename in dirfiles:
			filename = os.path.join(directory, filename)
			#print filename
			try:
				file = open(filename, 'r')
				line_nr = 0
				for line in file.readlines():
					line_nr = line_nr + 1
					line = strip(line)
					if not line or line[0] == '#':
						continue
					info = map(intern, split(line, ','))
					if len(info) == 6:
						psname = info[0]
						fontlist.append(tuple(info[:-1]))
						_add_ps_filename(psname, info[-1])
						fontmap[psname] = tuple(info[1:-1])
					elif len(info) == 2:
						psname, basename = info
						_add_ps_filename(psname, basename)
					else:
						warn(INTERNAL,'%s:%d: line must have exactly 6 fields',
								filename, line_nr)
				file.close()
			except IOError, value:
				warn(USER, _("Cannot load sfd file %(filename)s:%(message)s;"
								"ignoring it"),
						filename = filename, message = value.strerror)
	if __debug__:
		pdebug('timing', 'time to read font dirs: %g', time.clock() - start)

def make_family_to_fonts():
	families = {}
	for item in fontlist:
		family = item[1]
		fontname = item[0]
		if families.has_key(family):
			families[family] = families[family] + (fontname,)
		else:
			families[family] = (fontname,)
	return families



xlfd_template = "%s--%s-*-*-*-*-*-%s"

font_cache = SKCache()

class Font:

	def __init__(self, name):
		self.name = name
		info = fontmap[name]
		family, font_attrs, xlfd_start, encoding_name = info
		self.family = family
		self.font_attrs = font_attrs
		self.xlfd_start = lower(xlfd_start)
		self.encoding_name = encoding_name
		self.metric, self.encoding = read_metric(self.PostScriptName())
		self.outlines = None

		self.ref_count = 0
		font_cache[self.name] = self

	def __del__(self):
		if font_cache.has_key(self.name):
			del font_cache[self.name]

	def __repr__(self):
		return "<Font %s>" % self.name

	def GetXLFD(self, size_trafo):
		if type(size_trafo) == TrafoType:
			if size_trafo.m11 == size_trafo.m22 > 0\
				and size_trafo.m12 == size_trafo.m21 == 0:
				# a uniform scaling. Special case for better X11R5
				# compatibility
				return xlfd_template % (self.xlfd_start,
										int(round(size_trafo.m11)),
										self.encoding_name)
			return xlfd_template % (self.xlfd_start, xlfd_matrix(size_trafo),
									self.encoding_name)
		return xlfd_template % (self.xlfd_start, int(round(size_trafo)),
								self.encoding_name)

	def PostScriptName(self):
		return self.name

	def TextBoundingBox(self, text, size):
		# Return the bounding rectangle of TEXT when set in this font
		# with a size of SIZE. The coordinates of the rectangle are
		# relative to the origin of the first character.
		llx, lly, urx, ury = self.metric.string_bbox(text)
		size = size / 1000.0
		return (llx * size, lly * size, urx * size, ury * size)

	def TextCoordBox(self, text, size):
		# Return the coord rectangle of TEXT when set in this font with
		# a size of SIZE. The coordinates of the rectangle are relative
		# to the origin of the first character.
		metric = self.metric
		width = metric.string_width(text)
		size = size / 1000.0
		return (0,		metric.descender * size,
				width * size,	metric.ascender * size)

	def TextCaretData(self, text, pos, size):
		from math import tan, pi
		size = size / 1000.0
		x = self.metric.string_width(text, pos) * size
		lly = self.metric.lly * size
		ury = self.metric.ury * size
		t = tan(self.metric.italic_angle * pi / 180.0);
		up = ury - lly
		return Point(x - t * lly, lly), Point(-t * up, up)

	def TypesetText(self, text):
		return self.metric.typeset_string(text)

	def IsPrintable(self, char):
		return self.encoding[ord(char)] != encoding.notdef

	def GetOutline(self, char):
		if self.outlines is None:
			self.char_strings, self.cs_interp \
								= read_outlines(self.PostScriptName())
			self.outlines = {}
		char_name = self.encoding[ord(char)]
		outline = self.outlines.get(char_name)
		if outline is None:
			self.cs_interp.execute(self.char_strings[char_name])
			outline = convert_outline(self.cs_interp.paths)
			self.outlines[char_name] = outline
			self.cs_interp.reset()
		copy = []
		for path in outline:
			path = path.Duplicate()
			copy.append(path)
		return tuple(copy)

	def FontFileName(self):
		return font_file_name(self.PostScriptName())



_warned_about_font = {}
def GetFont(fontname):
	if font_cache.has_key(fontname):
		return font_cache[fontname]
	if not fontmap.has_key(fontname):
		if not _warned_about_font.get(fontname):
			warn(USER, _("I can't find font %(fontname)s. "
							"I'll use %(fallback)s instead"),
					fontname = fontname,
					fallback = config.preferences.fallback_font)
			warn(USER, _("Fontsystem not yet implemented in UniConvertor. "
					"See /usr/share/doc/python-uniconvertor/README.Debian for more info"))
			_warned_about_font[fontname] = 1
		if fontname != config.preferences.fallback_font:
			return GetFont(config.preferences.fallback_font)
		raise ValueError, 'Cannot find font %s.' % fontname
	return Font(fontname)


#
#	Initialisation on import
#

## workaround for a bug that stops uniconvertor from working with svg
## files winth font properties in style attributes, even if they apply
## to no text because all text is empty or transformed to paths
## see http://svn.berlios.de/viewcvs/bulmages/branches/docsMonolitic/bulmages/installbulmages/openreports/ca/

class FakeFont(Font):
    def __init__(self, name):
        self.name = name
        self.family = name
        self.font_attrs = 'Regular Italic'
        self.xlfd_start = '-adobe-Nimbus Roman No9 L-regular-i-normal'
        self.encoding_name = 'iso8859-1'
        self.outlines = None
        self.ref_count = 0
        font_cache[self.name] = self

def ensure_there_is_at_least_a_fake_fallback_font():
   fallback = 'Slim';
   if (not (config is  None)) and (hasattr(config,'preferences'))  and (hasattr(config.preferences,'fallback_font')):
           fallback = config.preferences.fallback_font
   if not font_cache.has_key(fallback):
          return FakeFont(fallback)
   return font_cache[fallback]

fallbackFont = ensure_there_is_at_least_a_fake_fallback_font()

Subscribe(const.INITIALIZE, read_font_dirs)
read_font_dirs()