File: font_manager.py

package info (click to toggle)
python-enable 3.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 10,392 kB
  • ctags: 17,135
  • sloc: cpp: 79,151; python: 29,601; makefile: 2,926; sh: 43
file content (1068 lines) | stat: -rw-r--r-- 34,819 bytes parent folder | download
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
"""
A module for finding, managing, and using fonts across-platforms.

This module provides a single FontManager that can be shared across
backends and platforms.  The findfont() method returns the best
TrueType (TTF) font file in the local or system font path that matches
the specified FontProperties.  The FontManager also handles Adobe Font
Metrics (AFM) font files for use by the PostScript backend.

The design is based on the W3C Cascading Style Sheet, Level 1 (CSS1)
font specification (http://www.w3.org/TR/1998/REC-CSS2-19980512/ ).
Future versions may implement the Level 2 or 2.1 specifications.


KNOWN ISSUES

  - documentation
  - font variant is untested
  - font stretch is incomplete
  - font size is incomplete
  - font size_adjust is incomplete
  - default font algorithm needs improvement and testing
  - setWeights function needs improvement
  - 'light' is an invalid weight value, remove it.
  - update_fonts not implemented


:Author: John Hunter <jdhunter@ace.bsd.uchicago.edu>
            Paul Barrett <Barrett@STScI.Edu>
:Copyright: John Hunter (2004,2005), Paul Barrett (2004,2005)
:License: matplotlib license (PSF compatible)
            The font directory code is from ttfquery,
            see license/LICENSE_TTFQUERY.

Portions Copyright (c) Enthought, Inc.
All rights reserved

This software is provided without warranty under the terms of the BSD
license included in enthought/LICENSE.txt and may be redistributed only
under the conditions described in the aforementioned license.  The license
is also available online at http://www.enthought.com/licenses/BSD.txt
Thanks for using Enthought open source!

"""

import os, sys, glob, warnings, shutil, stat, time
import tempfile

import afm
#from matplotlib import ft2font
from enthought.etsconfig.api import ETSConfig
from enthought.kiva.fonttools.fontTools.ttLib import TTFont, TTLibError

#verbose = matplotlib.verbose

font_scalings = {'xx-small': 0.579, 'x-small': 0.694, 'small': 0.833,
                 'medium': 1.0, 'large': 1.200, 'x-large': 1.440,
                 'xx-large': 1.728}

weight_dict = {'light': 200, 'normal': 400, 'regular': 400, 'book': 400,
              'medium': 500, 'roman': 500, 'semibold': 600, 'demibold': 600,
              'demi': 600, 'bold': 700, 'heavy': 800, 'extra bold': 800,
               'black': 900}

#  OS Font paths
MSFolders = \
    r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'

MSFontDirectories   = [
    r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
    r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']

X11FontDirectories  = [
    # what seems to be the standard installation point
    "/usr/X11R6/lib/X11/fonts/TTF/",
    # Solaris doesn't abbreviate TrueType
    "/usr/X11R6/lib/X11/fonts/TrueType/",
    # documented as a good place to install new fonts...
    "/usr/share/fonts/",
    # common application, not really useful
    "/usr/lib/openoffice/share/fonts/truetype/",
    ]

OSXFontDirectories = [
    "/Library/Fonts/",
    "/Network/Library/Fonts/",
    "/System/Library/Fonts/"
]

home = os.environ.get('HOME')
if home is not None:
    # user fonts on OSX
    path = os.path.join(home, 'Library', 'Fonts')
    OSXFontDirectories.append(path)

def win32FontDirectory():
    """Return the user-specified font directory for Win32."""

    try:
        import _winreg
    except ImportError:
        return os.path.join(os.environ['WINDIR'], 'Fonts')
    else:
        user = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, MSFolders)
        try:
            return _winreg.QueryValueEx(user, 'Fonts')[0]
        finally:
            _winreg.CloseKey(user)
    return None

def win32InstalledFonts(directory=None, fontext='ttf'):

    """Search for fonts in the specified font directory, or use the
system directories if none given.  A list of TrueType fonts are
returned by default with AFM fonts as an option.
"""

    import _winreg
    if directory is None:
        directory = win32FontDirectory()

    key, items = None, {}
    for fontdir in MSFontDirectories:
        try:
            local = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, fontdir)
        except OSError:
            continue

        if not local:
            return glob.glob(os.path.join(directory, '*.'+fontext))
        try:
            for j in range(_winreg.QueryInfoKey(local)[1]):
                try:
                    key, direc, any = _winreg.EnumValue( local, j)
                    if not os.path.dirname(direc):
                        direc = os.path.join(directory, direc)
                    direc = os.path.abspath(direc).lower()
                    if direc[-4:] == '.'+fontext:
                        items[direc] = 1
                except EnvironmentError:
                    continue
                except WindowsError:
                    continue

            return items.keys()
        finally:
            _winreg.CloseKey(local)
    return None

def OSXFontDirectory():
    """Return the system font directories for OS X."""

    fontpaths = []
    def add(arg,directory,files):
        fontpaths.append(directory)
    for fontdir in OSXFontDirectories:
        try:
            if os.path.isdir(fontdir):
                os.path.walk(fontdir, add, None)
        except (IOError, OSError, TypeError, ValueError):
            pass
    return fontpaths

def OSXInstalledFonts(directory=None, fontext=None):
    """Get list of font files on OS X - ignores font suffix by default"""
    if directory is None:
        directory = OSXFontDirectory()

    files = []
    for path in directory:
        if fontext is None:
            files.extend(glob.glob(os.path.join(path,'*')))
        else:
            files.extend(glob.glob(os.path.join(path, '*.'+fontext)))
            files.extend(glob.glob(os.path.join(path, '*.'+fontext.upper())))
    return files


def x11FontDirectory():
    """Return the system font directories for X11."""
    fontpaths = []
    def add(arg,directory,files):
        fontpaths.append(directory)

    for fontdir in X11FontDirectories:
        try:
            if os.path.isdir(fontdir):
                os.path.walk(fontdir, add, None)
        except (IOError, OSError, TypeError, ValueError):
            pass
    return fontpaths

def findSystemFonts(fontpaths=None, fontext='ttf'):

    """Search for fonts in the specified font paths, or use the system
paths if none given.  A list of TrueType fonts are returned by default
with AFM fonts as an option.
"""

    fontfiles = {}

    if fontpaths is None:

        if sys.platform == 'win32':
            fontdir = win32FontDirectory()

            fontpaths = [fontdir]
            # now get all installed fonts directly...
            for f in win32InstalledFonts(fontdir):
                base, ext = os.path.splitext(f)
                if len(ext)>1 and ext[1:].lower()==fontext:
                    fontfiles[f] = 1
        else:
            fontpaths = x11FontDirectory()
            # check for OS X & load its fonts if present
            if sys.platform == 'darwin':
                for f in OSXInstalledFonts():
                    fontfiles[f] = 1

    elif isinstance(fontpaths, (str, unicode)):
        fontpaths = [fontpaths]

    for path in fontpaths:
        files = glob.glob(os.path.join(path, '*.'+fontext))
        files.extend(glob.glob(os.path.join(path, '*.'+fontext.upper())))
        for fname in files:
            fontfiles[os.path.abspath(fname)] = 1

    return [fname for fname in fontfiles.keys() if os.path.exists(fname)]

def weight_as_number(weight):
    """Return the weight property as a numeric value.  String values
are converted to their corresponding numeric value.
"""

    if isinstance(weight, str):
        try:
            weight = weight_dict[weight.lower()]
        except KeyError:
            weight = 400
    elif weight in range(100, 1000, 100):
        pass
    else:
        raise ValueError, 'weight not a valid integer'
    return weight


class FontKey(object):
    """A class for storing Font properties.  It is used when populating
the font dictionary.
"""

    def __init__(self,
                 name   ='',
                 style  ='normal',
                 variant='normal',
                 weight ='normal',
                 stretch='normal',
                 size   ='medium'
                 ):
        self.name    = name
        self.style   = style
        self.variant = variant
        self.weight  = weight
        self.stretch = stretch
        try:
            self.size = str(float(size))
        except ValueError:
            self.size = size

def getPropDict(font):
    n = font['name']
    propdict = {}
    for prop in n.names:
        propdict[(prop.platformID, prop.platEncID, prop.langID, prop.nameID )] = prop.string
    return propdict



def ttfFontProperty(font):
    """A function for populating the FontKey by extracting information
    from the TrueType font file.
    """
    props = getPropDict(font)
    name = props[(1,0,0,1)]

    #  Styles are: italic, oblique, and normal (default)

    try: sfnt2 = props[(1,0,0,2)]
    except: sfnt2 = None
    try: sfnt4 = props[(1,0,0,4)]
    except: sfnt4 = None

    if sfnt2:
        sfnt2 = sfnt2.lower()
    else:
        sfnt2 = ''
    if sfnt4:
        sfnt4 = sfnt4.lower()
    else:
        sfnt4 = ''
    if   sfnt4.find('oblique') >= 0:
        style = 'oblique'
    elif sfnt4.find('italic') >= 0:
        style = 'italic'
    elif sfnt2.find('regular') >= 0:
        style = 'normal'
    else:
        style = 'normal'


    #  Variants are: small-caps and normal (default)

    #  !!!!  Untested
    if name.lower() in ['capitals', 'small-caps']:
        variant = 'small-caps'
    else:
        variant = 'normal'

    #  Weights are: 100, 200, 300, 400 (normal: default), 500 (medium),
    #    600 (semibold, demibold), 700 (bold), 800 (heavy), 900 (black)
    #    lighter and bolder are also allowed.

    weight = None
    for w in weight_dict.keys():
        if sfnt4.find(w) >= 0:
            weight = w
            break
    if not weight:
        weight = 400
    weight = weight_as_number(weight)

    #  Stretch can be absolute and relative
    #  Absolute stretches are: ultra-condensed, extra-condensed, condensed,
    #    semi-condensed, normal, semi-expanded, expanded, extra-expanded,
    #    and ultra-expanded.
    #  Relative stretches are: wider, narrower
    #  Child value is: inherit

    #  !!!!  Incomplete
    if   sfnt4.find('narrow') >= 0 or sfnt4.find('condensed') >= 0 or \
           sfnt4.find('cond') >= 0:
        stretch = 'condensed'
    elif sfnt4.find('demi cond') >= 0:
        stretch = 'semi-condensed'
    elif sfnt4.find('wide') >= 0 or sfnt4.find('expanded') >= 0:
        stretch = 'expanded'
    else:
        stretch = 'normal'

    #  Sizes can be absolute and relative.
    #  Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
    #    and xx-large.
    #  Relative sizes are: larger, smaller
    #  Length value is an absolute font size, e.g. 12pt
    #  Percentage values are in 'em's.  Most robust specification.

    #  !!!!  Incomplete
    size = 'scalable'

    #  !!!!  Incomplete
    size_adjust = None

    return FontKey(name, style, variant, weight, stretch, size)


def afmFontProperty(font):
    """A function for populating the FontKey by extracting information
from the AFM font file.
"""

    name = font.get_familyname()

    #  Styles are: italic, oblique, and normal (default)

    if font.get_angle() != 0 or name.lower().find('italic') >= 0:
        style = 'italic'
    elif name.lower().find('oblique') >= 0:
        style = 'oblique'
    else:
        style = 'normal'

    #  Variants are: small-caps and normal (default)

    # !!!!  Untested
    if name.lower() in ['capitals', 'small-caps']:
        variant = 'small-caps'
    else:
        variant = 'normal'

    #  Weights are: 100, 200, 300, 400 (normal: default), 500 (medium),
    #    600 (semibold, demibold), 700 (bold), 800 (heavy), 900 (black)
    #    lighter and bolder are also allowed.

    weight = weight_as_number(font.get_weight().lower())

    #  Stretch can be absolute and relative
    #  Absolute stretches are: ultra-condensed, extra-condensed, condensed,
    #    semi-condensed, normal, semi-expanded, expanded, extra-expanded,
    #    and ultra-expanded.
    #  Relative stretches are: wider, narrower
    #  Child value is: inherit

    # !!!!  Incomplete
    stretch = 'normal'

    #  Sizes can be absolute and relative.
    #  Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
    #    and xx-large.
    #  Relative sizes are: larger, smaller
    #  Length value is an absolute font size, e.g. 12pt
    #  Percentage values are in 'em's.  Most robust specification.

    #  All AFM fonts are apparently scalable.

    size = 'scalable'

    # !!!!  Incomplete
    size_adjust = None

    return FontKey(name, style, variant, weight, stretch, size)


def add_filename(fontdict, prop, fname):
    """A function to add a font file name to the font dictionary using
the FontKey properties.  If a font property has no dictionary, then
create it.
"""

    try:
        size = str(float(prop.size))
    except ValueError:
        size = prop.size

    d = fontdict.                    \
        setdefault(prop.name,    {}).\
        setdefault(prop.style,   {}).\
        setdefault(prop.variant, {}).\
        setdefault(prop.weight,  {}).\
        setdefault(prop.stretch, {})
    d[size] = fname


def createFontDict(fontfiles, fontext='ttf'):
    """A function to create a dictionary of font file paths.  The
default is to create a dictionary for TrueType fonts.  An AFM font
dictionary can optionally be created.
"""
    fontdict = {}
    #  Add fonts from list of known font files.
    seen = {}
    for fpath in fontfiles:
#        verbose.report('createFontDict: %s' % (fpath), 'debug')
        fname = fpath.split('/')[-1]
        if seen.has_key(fname):  continue
        else: seen[fname] = 1
        if fontext == 'afm':
            try:
                font = afm.AFM(file(fpath))
            except RuntimeError:
                continue
            prop = afmFontProperty(font)
        else:
            try:
                font = TTFont(str(fpath))
            except (IOError, RuntimeError, TTLibError):
                continue
            except UnicodeError:
                continue
            try:
                prop = ttfFontProperty(font)
            except:
                continue

        add_filename(fontdict, prop, fpath)

        #  !!!!  Default font algorithm needs improvement
        if   prop.name.lower() in ['bitstream vera serif', 'luxi serif', 'times', 'times new roman']:
            prop.name = 'serif'
            add_filename(fontdict, prop, fpath)
        elif prop.name.lower() in ['bitstream vera sans', 'helvetica', 'luxi sans', 'arial']:
            prop.name = 'sans-serif'
            add_filename(fontdict, prop, fpath)
        elif prop.name.lower() in ['zapf chancery', 'itc zapf chancery']:
            prop.name = 'cursive'
            add_filename(fontdict, prop, fpath)
        elif prop.name.lower() in ['western', 'itc avant garde gothic', 'impact']:
            prop.name = 'fantasy'
            add_filename(fontdict, prop, fpath)
        elif prop.name.lower() in ['bitstream vera sans mono', 'luxi mono', 'courier', 'courier new']:
            prop.name = 'monospace'
            add_filename(fontdict, prop, fpath)

    return fontdict

def setWeights(font):
    """A function to populate missing values in a font weight
dictionary.  This proceedure is necessary since the font finding
algorithm always matches on the weight property.
"""

    # !!!!  Not completely correct
    temp = font.copy()
    if len(temp) == 1:
        wgt = temp.keys()[0]
        for j in range(100, 1000, 100):
            font[j] = temp[wgt]

    if temp.has_key(400):
        for j in range(100, 1000, 100):
            font[j] = temp[400]
    if temp.has_key(500):
        if temp.has_key(400):
            for j in range(500, 1000, 100):
                font[j] = temp[500]
        else:
            for j in range(100, 1000, 100):
                font[j] = temp[500]

    if temp.has_key(300):
        for j in [100, 200, 300]:
            font[j] = temp[300]
    if temp.has_key(200):
        if temp.has_key(300):
            for j in [100, 200]:
                font[j] = temp[200]
        else:
            for j in [100, 200, 300]:
                font[j] = temp[200]

    if temp.has_key(800):
        for j in [600, 700, 800, 900]:
            font[j] = temp[800]
    if temp.has_key(700):
        if temp.has_key(800):
            for j in [600, 700]:
                font[j] = temp[700]
        else:
            for j in [600, 700, 800, 900]:
                font[j] = temp[700]


class FontProperties:
    """A class for storing and manipulating font properties.

The font properties are those described in the W3C Cascading Style
Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/)
font specification.  The six properties are:

  family 
      A list of font names in decreasing order of priority. The last item is 
      the default font name and is given the name of the font family, one of:
      serif, sans-serif, cursive, fantasy, or monospace.
  style 
      One of: normal, italic or oblique.
  variant
      Either normal or small-caps.
  stretch 
      Either an absolute or relative value. Absolute values are: 
      ultra-condensed, extra-condensed, condensed, semi-condensed, normal, 
      semi-expanded, expanded, extra-expanded or ultra-expanded; relative values
      are: narrower or wider. This property is currently not implemented and is
      set to 'normal'.
  weight 
      A numeric value in the range 100, 200, 300, ..., 900.
  size 
      An absolute or relative value, or an absolute font size, or scalable. 
      Absolute values are: xx-small, x-small, small, medium, large, x-large,
      xx-large; relative values are smaller or larger.

The default font property for TrueType fonts is: sans-serif, normal,
normal, normal, 400, scalable.

The preferred usage of font sizes is to use the absolute values, e.g.
large, instead of absolute font sizes, e.g. 12.  This approach allows
all text sizes to be made larger or smaller based on the font manager's
default font size, i.e. by using the set_default_size() method of the
font manager.


Examples::

  #  Load default font properties
  >>> p = FontProperties()
  >>> p.get_family()
  ['Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucida', 'Arial', 'Helvetica', 'sans-serif']

  #  Change font family to 'fantasy'
  >>> p.set_family('fantasy')
  >>> p.get_family()
  ['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'fantasy']

  #  Make these fonts highest priority in font family
  >>> p.set_name(['foo', 'fantasy', 'bar', 'baz'])
  Font name 'fantasy' is a font family. It is being deleted from the list.
  >>> p.get_family()
  ['foo', 'bar', 'baz', 'Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'fantasy']

"""

    def __init__(self,
                 family = None,
                 style  = None,
                 variant= None,
                 weight = None,
                 stretch= None,
                 size   = None,
                 fname = None, # if this is set, it's a hardcoded filename to use
                 ):


        if family is None: family = 'serif'
        if style is None: style  = 'normal'
        if variant is None: variant= 'normal'
        if weight is None: weight = 'normal'
        if stretch is None: stretch= 'normal'
        if size is None: size   = 'medium'

        if isinstance(family, str):
            family = [family]
        self.__family  = family
        self.__style   = style
        self.__variant = variant
        self.__weight  = weight
        self.__stretch = stretch
        self.__size    = size
        self.__parent_size = fontManager.get_default_size()
        self.fname = fname

    def __hash__(self):
        return hash( (
            tuple(self.__family), self.__style, self.__variant,
            self.__weight, self.__stretch, self.__size,
            self.__parent_size, self.fname))

    def __str__(self):
        return str((self.__family, self.__style, self.__variant,
                    self.__weight, self.__stretch, self.__size))

    def get_family(self):
        """Return a list of font names that comprise the font family.
        """
        return self.__family

    def get_name(self):
        """Return the name of the font that best matches the font
properties.
"""
        filename = str(fontManager.findfont(self))
        if filename[-4:] == ".afm":
            return afm.AFM(file(filename)).get_familyname()
        else:
            return getPropDict(TTFont(str(fontManager.findfont(self))))[(1,0,0,1)]

    def get_style(self):
        """Return the font style.  Values are: normal, italic or oblique.
        """
        return self.__style

    def get_variant(self):
        """Return the font variant.  Values are: normal or small-caps.
        """
        return self.__variant

    def get_weight(self):
        """Return the font weight.  See the FontProperties class for a
a list of possible values.
"""
        return self.__weight

    def get_stretch(self):
        """Return the font stretch or width.  Options are: normal,
narrow, condensed, or wide.
"""
        return self.__stretch

    def get_size(self):
        """Return the font size.
        """
        return self.__size

    def set_family(self, family):
        """Change the font family.  Options are: serif, sans-serif, cursive,
fantasy, or monospace."""

        if family in ('serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'):
            self.__family = [family]
        else:
            raise KeyError, '%s - use serif, sans-serif, cursive, fantasy, or monospace.' % family

    def set_name(self, names):

        """Add one or more font names to the font family list.  If the
font name is already in the list, then the font is given a higher
priority in the font family list.  To change the font family, use the
set_family() method.
"""

        msg = "Font name '%s' is a font family. It is being deleted from the list."
        font_family = ['serif', 'sans-serif', 'cursive', 'fantasy',
                       'monospace']

        if isinstance(names, basestring):
            names = [names]

        #  Remove family names from list of font names.
        for name in names[:]:
            if name.lower() in font_family:
                warnings.warn( msg % name)
                while name in names:
                    names.remove(name.lower())

        #  Remove font names from family list.
        for name in names:
            while name in self.__family:
                self.__family.remove(name)

        self.__family = names + self.__family

    def set_style(self, style):
        """Set the font style.  Values are: normal, italic or oblique.
        """
        self.__style = style

    def set_variant(self, variant):
        """Set the font variant.  Values are: normal or small-caps.
        """
        self.__variant = variant

    def set_weight(self, weight):
        """Set the font weight.  See the FontProperties class for a
a list of possible values.
"""
        self.__weight = weight

    def set_stretch(self, stretch):
        """Set the font stretch or width.  Options are: normal, narrow,
condensed, or wide.
"""
        self.__stretch = stretch

    def set_size(self, size):
        """Set the font size.
        """
        self.__size = size

    def get_size_in_points(self, parent_size=None):
        """Return the size property as a numeric value.  String values
are converted to their corresponding numeric value.
"""
        if self.__size in font_scalings.keys():
            size = fontManager.get_default_size()*font_scalings[self.__size]
        elif self.__size == 'larger':
            size = self.__parent_size*1.2
        elif self.__size == 'smaller':
            size = self.__parent_size/1.2
        else:
            size = self.__size
        return float(size)

    def copy(self):
        """Return a deep copy of self"""
        return FontProperties(self.__family,
                              self.__style,
                              self.__variant,
                              self.__weight,
                              self.__stretch,
                              self.__size)

def ttfdict_to_fnames(d):
    'flatten a ttfdict to all the filenames it contains'
    fnames = []
    for named in d.values():
        for styled in named.values():
            for variantd in styled.values():
                for weightd in variantd.values():
                    for stretchd in weightd.values():
                        for fname in stretchd.values():
                            fnames.append(fname)
    return fnames

def _is_writable_dir(p):
    """
    p is a string pointing to a putative writable dir -- return True p
    is such a string, else False
    """
    if not isinstance(p, basestring):
        return False

    try:
        t = tempfile.TemporaryFile(dir=p)
        t.write('kiva.test')
        t.close()
    except OSError:
        return False
    else:
        return True


def get_configdir():
    """
    Return the string representing the configuration dir.  If s is the
    special string _default_, use HOME/.kiva.  s must be writable
    """

    p = os.path.join(ETSConfig.application_data, 'kiva')
    if not os.path.exists(p):
        os.makedirs(p)
    if not _is_writable_dir(p):
        raise IOError('Configuration directory %s must be writable' % p)
    return p


def get_home():
    """Find user's home directory if possible.
    Otherwise raise error.

    :see:  http://mail.python.org/pipermail/python-list/2005-February/263921.html
    """
    path=''
    try:
        path=os.path.expanduser("~")
    except:
        pass
    if not os.path.isdir(path):
        for evar in ('HOME', 'USERPROFILE', 'TMP'):
            try:
                path = os.environ[evar]
                if os.path.isdir(path):
                    break
            except: pass
    if path:
        return path
    else:
        raise RuntimeError('please define environment variable $HOME')


class FontManager:

    """On import, the FontManager creates a dictionary of TrueType
fonts based on the font properties: name, style, variant, weight,
stretch, and size.  The findfont() method searches this dictionary
for a font file name that exactly matches the font properties of the
specified text.  If none is found, a default font is returned.  By
updating the dictionary with the properties of the found font, the
font dictionary can act like a font cache.
"""

    def __init__(self, size=12.0, weight='normal'):

        self.__default_size = size
        self.__default_weight = weight

        paths = []
        #This allows matplotlib to put fonts in its directory.
        #Does kiva need this capability? (probably not)
#        paths = [rcParams['datapath']]


        #  Create list of font paths

        for pathname in ['TTFPATH', 'AFMPATH']:
            if os.environ.has_key(pathname):
                ttfpath = os.environ[pathname]
                if ttfpath.find(';') >= 0: #win32 style
                    paths.extend(ttfpath.split(';'))
                elif ttfpath.find(':') >= 0: # unix style
                    paths.extend(ttfpath.split(':'))
                else:
                    paths.append(ttfpath)

#        verbose.report('font search path %s'%(str(paths)))
        #  Load TrueType fonts and create font dictionary.

        self.ttffiles = findSystemFonts(paths) + findSystemFonts()

        for fname in self.ttffiles:
#            verbose.report('trying fontname %s' % fname, 'debug')
            if fname.lower().find('vera.ttf')>=0:
                self.defaultFont = fname
                break
        else:
            # use anything
            if len(self.ttffiles) > 0:
                self.defaultFont = self.ttffiles[0]
            else:
                self.defaultFont = None

        cache_message = \
"""Saving TTF font cache for non-PS backends to %s.
Delete this file to have kiva rebuild the cache."""

        ttfcache = os.path.join(get_configdir(), 'ttffont.cache')


        try:
            import cPickle as pickle
        except ImportError:
            import pickle


        def rebuild():
            self.ttfdict = createFontDict(self.ttffiles)
            pickle.dump(self.ttfdict, file(ttfcache, 'w'))
#            verbose.report(cache_message % ttfcache)

        try:
            self.ttfdict = pickle.load(file(ttfcache))
        except:
            rebuild()
        else:
            #If cache is more than 12 hours old, rebuild
            if time.time() - os.stat(ttfcache)[stat.ST_MTIME] > 60*60*12:
                rebuild()
            # verify all the cached fnames still exist; if not rebuild
            else:
                for fname in ttfdict_to_fnames(self.ttfdict):
                    if not os.path.exists(fname):
                        rebuild()
                        break
#            verbose.report('loaded ttfcache file %s'%ttfcache)




        #  Load AFM fonts for PostScript
        #  Only load file names at this stage, the font dictionary will be
        #  created when needed.

        self.afmfiles = findSystemFonts(paths, fontext='afm') + \
                        findSystemFonts(fontext='afm')
        self.afmdict = {}

    def get_default_weight(self):
        "Return the default font weight."
        return self.__default_weight

    def get_default_size(self):
        "Return the default font size."
        return self.__default_size

    def set_default_weight(self, weight):
        "Set the default font weight.  The initial value is 'normal'."
        self.__default_weight = weight

    def set_default_size(self, size):
        "Set the default font size in points.  The initial value is 12pt."
        self.__default_size = size

    def update_fonts(self, filenames):
        """Update the font dictionary with new font files.
Currently not implemented."""
        #  !!!!  Needs implementing
        raise NotImplementedError


    def findfont(self, prop, fontext='ttf'):

        """Search the font dictionary for a font that exactly or closely
matches the specified font properties.  See the FontProperties class
for a description.

The properties are searched in the following order: name, style,
variant, weight, stretch, and size.  The font weight always matches
returning the closest weight, and the font size always matches for
scalable fonts.  An oblique style font will be used inplace of a
missing italic style font if present.  See the W3C Cascading Style
Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/)
documentation for a description of the font finding algorithm.
"""
        cache_message = \
"""Saving AFM font cache for PS backend to %s.
Delete this file to have kiva rebuild the cache."""

        debug = False
        if prop.fname is not None:
            fname = prop.fname
#            verbose.report('findfont returning %s'%fname, 'debug')
            return fname

        if fontext == 'afm':
            if len(self.afmdict) == 0:
                afmcache = os.path.join(get_configdir(), '.afmfont.cache')
                try:
                    import cPickle as pickle
                except ImportError:
                    import pickle
                try:
                    self.afmdict = pickle.load(file(afmcache))
                except:
                    self.afmdict = createFontDict(self.afmfiles, fontext='afm')
                    pickle.dump(self.afmdict, file(afmcache, 'w'))
#                    verbose.report(cache_message % afmcache)
            fontdict = self.afmdict
        else:
            fontdict = self.ttfdict

        name    = prop.get_family()[0]
        style   = prop.get_style()
        variant = prop.get_variant()
        weight  = weight_as_number(prop.get_weight())
        stretch = prop.get_stretch()
        size    = str(prop.get_size_in_points())


        try:
            fname = fontdict[name][style][variant][weight][stretch][size]
#            verbose.report('\tfindfont cached %(name)s, %(style)s, %(variant)s, %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug')
#            verbose.report('findfont returning %s'%fname, 'debug')
            return fname
        except KeyError:
            pass

        for name in prop.get_family():
            font = fontdict
            if font.has_key(name):
                font = font[name]
            else:
#                verbose.report('\tfindfont failed %(name)s'%locals(), 'debug')
                continue

            if font.has_key(style):
                font = font[style]
            elif style == 'italics' and font.has_key('oblique'):
                font = font['oblique']
            else:
#                verbose.report('\tfindfont failed %(name)s, %(style)s'%locals(), 'debug')
                continue

            if font.has_key(variant):
                font = font[variant]
            else:
#               verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s'%locals(), 'debug')
                continue

            if not font.has_key(weight):
                setWeights(font)
            font = font[weight]

            # !!!!  need improvement
            if font.has_key(stretch):
                font = font[stretch]
            else:
#               verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s'%locals(), 'debug')
                continue

            if font.has_key('scalable'):
                fname = font['scalable']
            elif font.has_key(size):
                fname = font[size]
            else:
#               verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug')
                continue

            fontkey = FontKey(name, style, variant, weight, stretch, size)
            add_filename(fontdict, fontkey, fname)
#           verbose.report('\tfindfont found %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug')
#           verbose.report('findfont returning %s'%fname, 'debug')

            return fname

        fontkey = FontKey(name, style, variant, weight, stretch, size)
        add_filename(fontdict, fontkey, self.defaultFont)
        warnings.warn('Could not match %s, %s, %s.  Returning %s' % (name, style, variant, self.defaultFont))

        return self.defaultFont

fontManager = FontManager()