File: fonts.py

package info (click to toggle)
python-enaml 0.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,284 kB
  • sloc: python: 31,443; cpp: 4,499; makefile: 140; javascript: 68; lisp: 53; sh: 20
file content (237 lines) | stat: -rw-r--r-- 6,546 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
#------------------------------------------------------------------------------
# Copyright (c) 2013-2025, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
""" A utility module for dealing with CSS3 font strings.

"""

from atom.api import Coerced

from .fontext import Font, FontStyle, FontCaps, FontStretch


#: A mapping from CSS font style keyword to style enum
_STYLES = {
    'normal': FontStyle.Normal,
    'italic': FontStyle.Italic,
    'oblique': FontStyle.Oblique,
}


#: A mapping from CSS font strecth keyword to style enum
_STRETCH = {
    'ultra-condensed': FontStretch.UltraCondensed,
    'extra-condensed': FontStretch.ExtraCondensed,
    'condensed': FontStretch.Condensed,
    'semi-condensed': FontStretch.SemiCondensed,
    'normal': FontStretch.Unstretched,
    'semi-expanded': FontStretch.SemiExpanded,
    'expanded': FontStretch.Expanded,
    'extra-expanded': FontStretch.ExtraExpanded,
    'ultra-expanded': FontStretch.UltraExpanded,
}


#: A mapping from CSS font variant keyword to caps enum
_VARIANTS = {
    'normal': FontCaps.MixedCase,
    'small-caps':  FontCaps.SmallCaps,
}


#: A mapping from CSS font weight to integer weight. These values are
#: pulled from the Qt stylesheet implementation of font parsing. Enaml
#: does not support the 'bolder' and 'lighter' keywords.
_WEIGHTS = {
    '100': 12,
    '200': 25,
    '300': 37,
    '400': 50,
    '500': 62,
    '600': 75,
    '700': 87,
    '800': 99,
    '900': 99,
    'normal': 50,
    'bold': 75,
}


#: A mapping from CSS font size keywords to font point sizes. These are
#: based on a standard 12 point font size.
_SIZES = {
    'xx-small': 7,
    'x-small': 8,
    'small': 9,
    'medium': 12,
    'large': 14,
    'x-large': 18,
    'xx-large': 24,
}


#: A mapping from CSS font units to functions which convert to points.
_UNITS = {
    'in': lambda size: int(size * 72.0),
    'cm': lambda size: int(size * 72.0 / 2.54),
    'mm': lambda size: int(size * 72.0 / 254.0),
    'pt': lambda size: int(size),
    'pc': lambda size: int(size * 12.0),
    'px': lambda size: int(size * 0.75),
}


def parse_font(font):
    """ Parse a CSS3 shorthand font string into an Enaml Font object.

    Returns
    -------
    result : Font or None
        A font object representing the parsed font. If the string is
        invalid, None will be returned.

    """
    token = []
    tokens = []
    quotechar = None
    for char in font:
        if quotechar is not None:
            if char == quotechar:
                tokens.append(''.join(token))
                token = []
                quotechar = None
            else:
                token.append(char)
        elif char == '"' or char == "'":
            quotechar = char
        elif char in ' \t':
            if token:
                tokens.append(''.join(token))
                token = []
        else:
            token.append(char)

    # Failed to close quoted string.
    if quotechar is not None:
        return

    if token:
        tokens.append(''.join(token))

    sizes = []
    families = []
    optionals = []
    for token in tokens:
        if (token in _STYLES or token in _VARIANTS or
                token in _WEIGHTS or token in _STRETCH):
            optionals.append(token)
        elif token in _SIZES or token[-2:] in _UNITS:
            sizes.append(token)
        else:
            families.append(token)

    if len(optionals) > 4:
        return None
    if len(sizes) != 1:
        return None
    if len(families) != 1:
        return None

    style = None
    variant = None
    weight = None
    stretch = None

    for opt in optionals:
        if opt == 'normal':
            continue
        elif opt in _STYLES:
            if style is not None:
                return None
            style = opt
        elif opt in _VARIANTS:
            if variant is not None:
                return None
            variant = opt
        elif opt in _WEIGHTS:
            if weight is not None:
                return None
            weight = opt
        elif opt in _STRETCH:
            if stretch is not None:
                return None
            stretch = opt
        else:
            return None

    size = sizes[0]
    if size in _SIZES:
        size = _SIZES[size]
    else:
        sizenum, units = size[:-2], size[-2:]
        try:
            sizenum = float(sizenum)
        except ValueError:
            return None
        size = _UNITS[units](sizenum)

    family = str(families[0])
    weight = _WEIGHTS[weight] if weight else _WEIGHTS['normal']
    style = _STYLES[style] if style else _STYLES['normal']
    variant = _VARIANTS[variant] if variant else _VARIANTS['normal']
    stretch = _STRETCH[stretch] if stretch else _STRETCH['normal']

    return Font(family, size, weight, style, variant, stretch)


def coerce_font(font):
    """ The coercing function for the FontMember.

    """
    if isinstance(font, str):
        return parse_font(font)


class FontMember(Coerced):
    """ An Atom member class which coerces a value to a font.

    A font member can be set to a Font, a string, or None. A string
    font will be parsed into a Font object. If the parsing fails,
    the font will be None.  Font strings must be given in CSS grammar,
    e.g. 'bold 12pt arial', which is order dependant.

    The order is the following:

    style variant weight stretch size family

    """
    __slots__ = ()

    def __init__(self, default=None, factory=None):
        """ Initialize a FontMember.

        default : Font, string, or None, optional
            The default font to use for the member.

        factory : callable, optional
            An optional callable which takes no arguments and returns
            the default value for the member. If this is provided, it
            will override any value passed as 'default'.

        Notes
        -----
        When providing a default font value, prefer using a Font object
        directly as this object will be shared among all instances of
        the class. Using a font string will result in a new Font object
        being created for each class instance.

        """
        if factory is None:
            factory = lambda: default
        kind = (Font, type(None))
        sup = super(FontMember, self)
        sup.__init__(kind, factory=factory, coercer=coerce_font)