This file is indexed.

/usr/bin/font-sampler is in font-manager 0.5.7-4.

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

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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
#!/usr/bin/python
"""
If called directly this script generates a pdf sample page from a directory
of fonts. It supports Truetype and Type 1 fonts.
"""
# Font Manager, a font management application for the GNOME desktop
#
# Copyright (C) 2009, 2010 Jerry Casiano
#
# 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, write to:
#
# Free Software Foundation, Inc.
# 51 Franklin Street, Fifth Floor
# Boston, MA  02110-1301, USA.

# Disable warnings related to gettext
# pylint: disable-msg=E0602
# Disable warnings related to missing docstrings, for now...
# pylint: disable-msg=C0111

import os
import gtk
import gobject
import cPickle
import shelve
import sys
import time
import UserDict

from os.path import abspath, dirname, basename, exists, join, splitext, \
                        join, isdir, realpath

# Allow running without installation
if os.path.exists(os.path.join(os.path.dirname(__file__), 'font-manager.in')):
    PACKAGE_DIR = dirname(abspath(__file__))
    LIB_DIR = dirname(abspath(__file__))
else:
    PACKAGE_DIR = '/usr/share/font-manager'
    LIB_DIR = '/usr/lib/font-manager'

for directory in PACKAGE_DIR, LIB_DIR:
    if not directory in sys.path:
        sys.path.insert(0, directory)

from core import Preferences
from constants import CACHE_DIR, HOME, PACKAGE_DATA_DIR
from utils.common import display_warning, run_dialog, \
                            natural_sort, natural_sort_pathlist


def _exit_with_error(msg, sec_msg = None):
    dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING,
                                    gtk.BUTTONS_CLOSE, None)
    dialog.set_markup('<b>{0}</b>'.format(msg))
    if sec_msg:
        dialog.format_secondary_text(sec_msg)
    run_dialog(None, dialog, True)
    sys.exit(1)

try:
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.pdfmetrics import FontError, FontNotFoundError
    from reportlab.pdfbase.ttfonts import TTFont, TTFontFile, TTFError
    from reportlab.lib.units import inch
    from reportlab.lib.fonts import addMapping
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
    from reportlab.platypus.flowables import KeepTogether
except ImportError:
    _exit_with_error(_('This program requires the ReportLab Toolit'),
    _('On most distributions this is available as python-reportlab.'))

CACHE_FILE  =   join(CACHE_DIR, 'sampler.cache')

# letter == (612.0, 792.0)
PAGE_WIDTH = letter[0]
PAGE_HEIGHT = letter[1]
# file extensions to include
TYPE1_EXTS = ('.pfb', '.PFB')
TRUETYPE_EXTS = ('.ttf', '.ttc', '.otf', '.TTF', '.TTC', '.OTF')
# A place for rejected files
SKIP_LS = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
# Typical font preview
LINE1 = "The quick brown fox jumps over the lazy dog."
LINE2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LINE3 = "abcdefghijklmnopqrstuvwxyz"
LINE4 = "1234567890.:,;(*!?')"
LINE = { 1 : LINE1, 2 : LINE2, 3 : LINE3, 4 : LINE4 }


class FontSampler(UserDict.UserDict):
    _widgets = (
                'MainWindow', 'FileChooserButton', 'OutputButton', 'Pangram',
                'CreateButton', 'Expander', 'ProgressWindow', 'ProgressBar',
                'ProgressLabel', 'Table', 'Author', 'Subject', 'FontSize'
                )
    def __init__(self):
        UserDict.UserDict.__init__(self)
        self.data = {}
        self.fontlist = None
        self.outfile = join(HOME, 'Sample Sheet.pdf')
        self.collection = basename(splitext(self.outfile)[0])
        self.builder = gtk.Builder()
        self.builder.set_translation_domain('font-manager')
        self.builder.add_from_file(os.path.join(PACKAGE_DATA_DIR,
                                                        'font-sampler.ui'))
        for widget in self._widgets:
            self.data[widget] = self.builder.get_object(widget)
        self.data['FileSelector'] = None
        self.data['Preferences'] = Preferences()
        self.data['Config'] = Config()
        self.data['ProgressWindow'].connect('delete-event', self._quit)
        self._load_config()

    def build_pdf(self, unused_widget, exit_on_success = False):
        if self.data['MainWindow'].get_property('visible'):
            self.data['MainWindow'].hide()
        self.data['ProgressWindow'].show()
        while gtk.events_pending():
            gtk.main_iteration()
        buildsample = BuildSample(self, self.data['Config'],
                                self.collection, self.fontlist, self.outfile)
        time.sleep(1)
        if buildsample.basic():
            self.data['ProgressWindow'].hide()
            if exit_on_success:
                sys.exit(0)
            else:
                self.data['MainWindow'].show()
        else:
            sys.exit(1)
        return

    def connect_callbacks(self):
        self.data['MainWindow'].connect('delete-event', gtk.main_quit)
        self.data['Author'].connect('changed', self._set_author)
        self.data['Subject'].connect('changed', self._set_subject)
        self.data['FontSize'].connect('value-changed', self._set_fontsize)
        self.data['Pangram'].connect('toggled', self._set_pangram)
        self.data['Expander'].connect('activate', self._set_window_size)
        self.data['Expander'].remove(self.data['Table'])
        self.data['Author'].set_text(self.data['Config'].author)
        self.data['Subject'].set_text(self.data['Config'].subject)
        self.data['FontSize'].set_value(self.data['Preferences'].fontsize)
        self.data['Pangram'].set_active(self.data['Preferences'].pangram)
        self.data['OutputButton'].set_label(self.outfile)
        self.data['FileChooserButton'].connect('selection-changed',
                                                        self._folder_selected)
        self.data['FileChooserButton'].set_current_folder(HOME)
        self.data['OutputButton'].connect('clicked', self._show_file_selector)
        self.data['CreateButton'].connect('clicked', self.build_pdf)
        self.data['FileSelector'] = self._create_file_selector()
        return

    def _create_file_selector(self):
        fileselector = gtk.FileChooserDialog(_('Save as...'),
                                        self.data['MainWindow'],
                                        gtk.FILE_CHOOSER_ACTION_SAVE,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                            gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        fileselector.set_local_only(True)
        fileselector.set_do_overwrite_confirmation(True)
        return fileselector

    def _folder_selected(self, widget):
        self.fontlist = widget.get_filename()
        return

    def _load_config(self):
        config = self.data['Config']
        config.fontsize = self.data['Preferences'].fontsize
        config.pangram = self.data['Preferences'].pangram
        return

    def progress_callback(self, family, total, processed):
        """
        Set progressbar text and percentage.
        """
        if family is not None:
            self.data['ProgressBar'].set_text(family)
        if processed > 0 and processed <= total:
            self.data['ProgressBar'].set_fraction(float(processed)/float(total))
        while gtk.events_pending():
            gtk.main_iteration()
        return

    def _set_author(self, widget):
        self.data['Config'].author = widget.get_text()
        return

    def _set_subject(self, widget):
        self.data['Config'].subject = widget.get_text()
        return

    def _set_fontsize(self, widget):
        self.data['Config'].fontsize = widget.get_value()
        return

    def _set_pangram(self, widget):
        self.data['Config'].pangram = widget.get_active()
        return

    def _set_window_size(self, unused_widget):
        if self.data['Expander'].get_expanded():
            self.data['Expander'].remove(self.data['Table'])
        else:
            self.data['Expander'].add(self.data['Table'])
        self.data['Expander'].resize_children()
        self.data['MainWindow'].resize(1, 1)
        self.data['MainWindow'].queue_draw()
        while gtk.events_pending():
            gtk.main_iteration()
        return

    def _show_file_selector(self, widget):
        fileselector = self.data['FileSelector']
        if self.outfile:
            fileselector.set_current_name(basename(self.outfile))
        fileselector.show()
        response = fileselector.run()
        if response == gtk.RESPONSE_ACCEPT:
            outfile = fileselector.get_filename()
            # Make sure we have write access before we go any further
            new_folder = dirname(outfile)
            if not os.access(new_folder, os.W_OK):
                display_warning(_('Selected folder must be writeable'),
                                    parent = self.data['MainWindow'])
                self._show_file_selector(None)
                return
            if not outfile.endswith('.pdf'):
                outfile = '{0}.pdf'.format(outfile)
            self.outfile = outfile
            self.collection = basename(splitext(outfile)[0])
            self.data['OutputButton'].set_label(self.outfile)
        fileselector.hide()
        while gtk.events_pending():
            gtk.main_iteration()
        return

    @staticmethod
    def _quit(*args):
        gtk.main_quit()
        sys.exit(0)


class Config(object):
    def __init__(self):
        self.styles = getSampleStyleSheet()
        self.fontsize = 20
        author =  os.getenv('USER')
        self.author = author.capitalize()
        self.subject = _('Sample of included fonts')
        self.pangram = False


class BuildSample:
    """
    Build a sample pdf from given directory or list

    objects -- an ObjectContainer instance

    Keyword arguments:
    config -- a Config instance or None to use default values
    collection -- collection name / pdf name
    fontlist -- a python list or the directory to scan for font files
    outfile -- the name of output file - <fullpath>/filename.pdf
    """
    def __init__(self, objects, config, collection, fontlist, outfile):
        #
        if config is None:
            self.config = Config()
        else:
            self.config = config
        self.styles = self.config.styles
        self.font_size = self.config.fontsize
        self.author =  self.config.author
        self.subject = self.config.subject
        #
        self.objects = objects
        self.collection = collection
        self.fontlist = fontlist
        self.outfile = outfile
        filelist = []
        if isinstance(fontlist, (tuple, list)):
            filelist = fontlist
        elif isdir(fontlist):
            for root, unused_dirs, files in os.walk(fontlist):
                for filename in files:
                    filepath = realpath(join(root, filename))
                    if not filepath in filelist:
                        filelist.append(filepath)
        else:
            raise TypeError\
            ('No files given for export, not a valid filepath or python list')
        self.total = len(filelist)
        self.fontlist = filelist
        self.failed = {}
        self.body = None
        self.rltotal = None
        self.rlprogress = None

    def basic(self):
        """
        Constructs a basic pdf listing the filename followed by a sample
        rendering of the font.
        """
        processed = 0
        progressbar = self.objects['ProgressBar']
        progress_label = self.objects['ProgressLabel']
        doc = SimpleDocTemplate(self.outfile, pagesize=letter, author=self.author,
                                subject=self.subject, title=self.collection,
                                leftMargin=0.75*inch, rightMargin=0.75*inch,
                                topMargin=1*inch, bottomMargin=0.75*inch)
        self.body = [Spacer(1, 0.01*inch)]
        style = self.styles[ "Normal" ]
        progress_label.set_text(_('Registering font files...'))
        while gtk.events_pending():
            gtk.main_iteration()
        for filepath in natural_sort_pathlist(self.fontlist):
            filename = filepath.rsplit('/', 1)[1]
            self.sort_and_register(filename, filepath, style)
            processed += 1
            progressbar.set_text(filename)
            self.objects.progress_callback(None, self.total, processed)
        progress_label.set_text('')
        progressbar.set_text('')
        self.objects['ProgressWindow'].hide()
        while gtk.events_pending():
            gtk.main_iteration()
        if not self.prompt_for_failed_fonts():
            return False
        self.objects['ProgressWindow'].show()
        progress_label.set_text(_('Rendering PDF file...'))
        while gtk.events_pending():
            gtk.main_iteration()
        # Render and save pdf
        doc.setProgressCallBack(self._on_render_progress)
        doc.build(self.body)
        #
        return True

    def _on_render_progress(self, typ, val):
        """
        Progress callback function.
        """
        if typ == 'SIZE_EST':
            self.rltotal = val
        elif typ == 'PROGRESS' and self.rltotal is not None:
            if val > self.rlprogress:
                self.objects.progress_callback(None, self.rltotal, val)
                self.rlprogress = val
        elif typ == 'FINISHED':
            self.rltotal = None
            self.rlprogress = None
        return

    def build_basic_paragraph(self, filename, name, style):
        fullsize = self.font_size
        halfsize = fullsize / 2
        quarter = fullsize / 4
        threequarter = halfsize + quarter
        # Build our current sample
        try:
            sample = []
            current_file = Paragraph(
                '<font size="{0}">{1}</font>'.format(halfsize, filename), style)
            sample.append(current_file)
            sample.append(Spacer(1, 0.1*inch))
            current_sample = Paragraph(
                '<font name="{0}" size="{1}">{2}</font>'.format(name, fullsize,
                                                                name), style)
            sample.append(current_sample)
            sample.append(Spacer(1, 0.2*inch))
            if self.config.pangram:
                for linenumber in 1, 2, 3, 4:
                    current_sample = Paragraph\
                    ('<font name="{0}" size="{1}">{2}</font>'.format(name,
                                        threequarter, LINE[linenumber]), style)
                    sample.append(current_sample)
                    sample.append(Spacer(1, 0.1*inch))
            sample.append(Spacer(1, 0.5*inch))
            self.body.append(KeepTogether(sample))
        # Triggered by some font psnames?
        except ValueError, error:
            self.failed[filename] = error
        return

    def sort_and_register(self, filename, filepath, style):
        if filename.endswith(TRUETYPE_EXTS):
            name = self.register_ttf(filename, filepath)
            if not name:
                return False
            self.build_basic_paragraph(filename, name, style)
        elif filename.endswith(TYPE1_EXTS):
            name = self.register_type1(filename, filepath)
            if not name:
                return False
            self.build_basic_paragraph(filename, name, style)
        return True

    def register_ttf(self, filename, filepath):
        try:
            # Prepare the font for use
            tt_file = TTFontFile(filepath)
            # makeSubset is called later on and sometimes raises an
            # IndexError, so we call it here so we can catch it in time.
            # Seems to only happen with shoddy fonts.
            tt_file.makeSubset(range(128))
            name = tt_file.name
            font = TTFont(name, filepath)
            pdfmetrics.registerFont(font)
            return name
        except TTFError, error:
            self.failed[filename] = error
            return False
        except (IndexError, AssertionError), error:
            self.failed[filename] = error
            return False

    def register_type1(self, filename, filepath):
        try:
            # Prepare the font for use
            pfb_file = filepath
            if filepath.endswith('.pfb'):
                afm_file = filepath.replace('.pfb', '.afm')
            elif filepath.endswith('.PFB'):
                afm_file = filepath.replace('.PFB', '.AFM')
            face = pdfmetrics.EmbeddedType1Face(afm_file, pfb_file)
            name = find_type1_name(afm_file)
            pdfmetrics.registerTypeFace(face)
            font = pdfmetrics.Font(name, name, 'WinAnsiEncoding')
            pdfmetrics.registerFont(font)
            return name
        except (FontError, FontNotFoundError), error:
            self.failed[filename] = error
            return False
        except (IndexError, AssertionError), error:
            self.failed[filename] = error
            return False

    def prompt_for_failed_fonts(self):
        SKIP_LS.clear()
        if len(self.failed) > 0:
            if not self.confirm_action(self.failed):
                return False
        return True

    def confirm_action(self, dic):
        """
        For whatever reason not all fonts will be included, show the user
        which, why and confirm that they still wants to continue.
        """
        dialog = gtk.Dialog(_('Skipping the following families'), None,
                        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                                ('Cancel', gtk.RESPONSE_CANCEL,
                                    'Continue', gtk.RESPONSE_OK))
        dialog.set_default_size(625, 225)
        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.set_property('shadow-type', gtk.SHADOW_ETCHED_IN)
        tree = _build_tree(dic)
        sw.add(tree)
        dialog.vbox.pack_start(sw, True, True, 5)
        status = gtk.Label(_('Due to the reasons listed above {0!s} out of \
{1!s} fonts will not be included in the sample sheet').format(len(self.failed),
                                                                    self.total))
        dialog.vbox.pack_start(status, False, True, 5)
        dialog.vbox.show_all()
        result = run_dialog(dialog = dialog)
        return (result == gtk.RESPONSE_OK)


def find_type1_name(path):
    """
    Try to extract a font name from an AFM file.
    """
    noname = _('Face name unavailable')
    try:
        f = open(path)
    except IOError:
        return noname
    found = 0
    while not found:
        line = f.readline()[:-1]
        if not found and line[:16] == 'StartCharMetrics':
            return noname
        if line[:8] == 'FontName':
            fontname = line[9:]
            found = 1
    fontname.strip()
    return fontname

def _build_tree(dic):
    lstore = SKIP_LS
    ordered = natural_sort([e for e in dic.iterkeys()])
    for font in ordered:
        error = str(dic[font])
        if error.find(':'):
            try:
                error = error.split(':')[1]
            except IndexError:
                pass
        error.strip()
        error = unicode(error, errors='replace')
        lstore.append([font, error])
    tree = gtk.TreeView(lstore)
    cell_render = gtk.CellRendererText()
    col1 = gtk.TreeViewColumn(_('Font file'), cell_render, text=0)
    col1.set_min_width(175)
    col1.set_sort_column_id(0)
    col2 = gtk.TreeViewColumn(_('Problem encountered'), cell_render, text=1)
    col2.set_min_width(275)
    tree.append_column(col1)
    tree.append_column(col2)
    return tree


if __name__ == '__main__':
    if exists(CACHE_FILE):
        cache = shelve.open(CACHE_FILE, protocol=cPickle.HIGHEST_PROTOCOL)
        objects = FontSampler()
        objects.collection = cache['collection']
        objects.fontlist = cache['fontlist']
        objects.outfile = cache['outfile']
        cache.close()
        os.unlink(CACHE_FILE)
        objects.build_pdf(None, True)
    else:
        objects = FontSampler()
        objects.connect_callbacks()
        objects['MainWindow'].show()
    try:
        gtk.main()
    except (KeyboardInterrupt):
        sys.exit(0)