~ubuntu-branches/ubuntu/utopic/python-traitsui/utopic

« back to all changes in this revision

Viewing changes to traitsui/wx/font_trait.py

  • Committer: Bazaar Package Importer
  • Author(s): Varun Hiremath
  • Date: 2011-07-09 13:57:39 UTC
  • Revision ID: james.westby@ubuntu.com-20110709135739-x5u20q86huissmn1
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#------------------------------------------------------------------------------
 
2
#
 
3
#  Copyright (c) 2005, Enthought, Inc.
 
4
#  All rights reserved.
 
5
#
 
6
#  This software is provided without warranty under the terms of the BSD
 
7
#  license included in enthought/LICENSE.txt and may be redistributed only
 
8
#  under the conditions described in the aforementioned license.  The license
 
9
#  is also available online at http://www.enthought.com/licenses/BSD.txt
 
10
#
 
11
#  Thanks for using Enthought open source!
 
12
#
 
13
#  Author: David C. Morrill
 
14
#  Date:   12/22/2004
 
15
#
 
16
#------------------------------------------------------------------------------
 
17
 
 
18
""" Trait definition for a wxPython-based font.
 
19
"""
 
20
 
 
21
#-------------------------------------------------------------------------------
 
22
#  Imports:
 
23
#-------------------------------------------------------------------------------
 
24
 
 
25
import wx
 
26
 
 
27
from traits.api \
 
28
    import Trait, TraitHandler, TraitError
 
29
 
 
30
#-------------------------------------------------------------------------------
 
31
#  Convert a string into a valid 'wxFont' object (if possible):
 
32
#-------------------------------------------------------------------------------
 
33
 
 
34
# Mapping of strings to valid wxFont families
 
35
font_families = {
 
36
    'default':    wx.DEFAULT,
 
37
    'decorative': wx.DECORATIVE,
 
38
    'roman':      wx.ROMAN,
 
39
    'script':     wx.SCRIPT,
 
40
    'swiss':      wx.SWISS,
 
41
    'modern':     wx.MODERN
 
42
}
 
43
 
 
44
# Mapping of strings to wxFont styles
 
45
font_styles = {
 
46
    'slant':  wx.SLANT,
 
47
    'italic': wx.ITALIC
 
48
}
 
49
 
 
50
# Mapping of strings wxFont weights
 
51
font_weights = {
 
52
    'light': wx.LIGHT,
 
53
    'bold':  wx.BOLD
 
54
}
 
55
 
 
56
# Strings to ignore in text representations of fonts
 
57
font_noise = [ 'pt', 'point', 'family' ]
 
58
 
 
59
#-------------------------------------------------------------------------------
 
60
#  Converts a wx.Font into a string description of itself:
 
61
#-------------------------------------------------------------------------------
 
62
 
 
63
def font_to_str ( font ):
 
64
    """ Converts a wx.Font into a string description of itself.
 
65
    """
 
66
    weight = { wx.LIGHT:  ' Light',
 
67
               wx.BOLD:   ' Bold'   }.get( font.GetWeight(), '' )
 
68
    style  = { wx.SLANT:  ' Slant',
 
69
               wx.ITALIC: ' Italic' }.get( font.GetStyle(), '' )
 
70
    underline = ''
 
71
    if font.GetUnderlined():
 
72
        underline = ' underline'
 
73
    return '%s point %s%s%s%s' % (
 
74
           font.GetPointSize(), font.GetFaceName(), style, weight, underline )
 
75
 
 
76
#-------------------------------------------------------------------------------
 
77
#  Create a TraitFont object from a string description:
 
78
#-------------------------------------------------------------------------------
 
79
 
 
80
def create_traitsfont ( value ):
 
81
    """ Create a TraitFont object from a string description.
 
82
    """
 
83
    if isinstance( value, wx.Font ):
 
84
        value = font_to_str( value )
 
85
 
 
86
    point_size = None
 
87
    family     = wx.DEFAULT
 
88
    style      = wx.NORMAL
 
89
    weight     = wx.NORMAL
 
90
    underline  = 0
 
91
    facename   = []
 
92
    for word in value.split():
 
93
        lword = word.lower()
 
94
        if font_families.has_key( lword ):
 
95
            family = font_families[ lword ]
 
96
        elif font_styles.has_key( lword ):
 
97
            style = font_styles[ lword ]
 
98
        elif font_weights.has_key( lword ):
 
99
            weight = font_weights[ lword ]
 
100
        elif lword == 'underline':
 
101
            underline = 1
 
102
        elif lword not in font_noise:
 
103
            if point_size is None:
 
104
                try:
 
105
                    point_size = int( lword )
 
106
                    continue
 
107
                except:
 
108
                    pass
 
109
            facename.append( word )
 
110
    return TraitsFont( point_size or 10, family, style, weight, underline,
 
111
                    ' '.join( facename ) )
 
112
 
 
113
#-------------------------------------------------------------------------------
 
114
#  'TraitsFont' class:
 
115
#-------------------------------------------------------------------------------
 
116
 
 
117
class TraitsFont ( wx.Font ):
 
118
    """ A Traits-specific wx.Font.
 
119
    """
 
120
    #---------------------------------------------------------------------------
 
121
    #  Returns the pickleable form of a TraitsFont object:
 
122
    #---------------------------------------------------------------------------
 
123
 
 
124
    def __reduce_ex__ ( self, protocol ):
 
125
        """ Returns the pickleable form of a TraitsFont object.
 
126
        """
 
127
        return ( create_traitsfont, ( font_to_str( self ), ) )
 
128
 
 
129
    #---------------------------------------------------------------------------
 
130
    #  Returns a printable form of the font:
 
131
    #---------------------------------------------------------------------------
 
132
 
 
133
    def __str__ ( self ):
 
134
        """ Returns a printable form of the font.
 
135
        """
 
136
        return font_to_str( self )
 
137
 
 
138
#-------------------------------------------------------------------------------
 
139
#  'TraitWXFont' class'
 
140
#-------------------------------------------------------------------------------
 
141
 
 
142
class TraitWXFont ( TraitHandler ):
 
143
    """ Ensures that values assigned to a trait attribute are valid font
 
144
    descriptor strings; the value actually assigned is the corresponding
 
145
    TraitsFont.
 
146
    """
 
147
    #---------------------------------------------------------------------------
 
148
    #  Validates that the value is a valid font:
 
149
    #---------------------------------------------------------------------------
 
150
 
 
151
    def validate ( self, object, name, value ):
 
152
        """ Validates that the value is a valid font descriptor string. If so,
 
153
        it returns the corresponding TraitsFont; otherwise, it raises a
 
154
        TraitError.
 
155
        """
 
156
        if value is None:
 
157
            return None
 
158
 
 
159
        try:
 
160
            return create_traitsfont( value )
 
161
        except:
 
162
            pass
 
163
 
 
164
        raise TraitError, ( object, name, 'a font descriptor string',
 
165
                            repr( value ) )
 
166
 
 
167
    def info ( self ):
 
168
        return ( "a string describing a font (e.g. '12 pt bold italic "
 
169
                 "swiss family Arial' or 'default 12')" )
 
170
 
 
171
#-------------------------------------------------------------------------------
 
172
#  Define a wxPython specific font trait:
 
173
#-------------------------------------------------------------------------------
 
174
 
 
175
### Note: Declare the editor to be a function which returns the FontEditor
 
176
# class from traits ui to avoid circular import issues. For backwards
 
177
# compatibility with previous Traits versions, the 'editors' folder in Traits
 
178
# project declares 'from api import *' in its __init__.py. The 'api' in turn
 
179
# can contain classes that have a Font trait which lead to this file getting
 
180
# imported. This leads to a circular import when declaring a Font trait.
 
181
def get_font_editor(*args, **traits):
 
182
    from font_editor import ToolkitEditorFactory
 
183
    return ToolkitEditorFactory(*args, **traits)
 
184
 
 
185
fh     = TraitWXFont()
 
186
WxFont = Trait( wx.SystemSettings_GetFont( wx.SYS_DEFAULT_GUI_FONT ), fh, editor = get_font_editor )