File: advanced.enaml

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 (261 lines) | stat: -rw-r--r-- 6,662 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
#------------------------------------------------------------------------------
# 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.
#------------------------------------------------------------------------------
""" An advanced example of Enaml templates.

This example shows how Enaml templates can be used to automatically
generate the body of a form. Template specialization is used to select
the proper control for a model attribute at runtime. Template recursion
is then used to unroll a list of these controls into the body of a form.

<< autodoc-me >>
"""
from __future__ import print_function
from atom.api import Atom, Bool, Enum, Event, Float, Int, Str

from enaml.core.api import DynamicTemplate
from enaml.stdlib.fields import FloatField
from enaml.widgets.api import (
    CheckBox, Container, Field, Form, GroupBox, Label, ObjectCombo, PushButton,
    SpinBox, Window,
)


#------------------------------------------------------------------------------
# "Libaray" Definitions
#------------------------------------------------------------------------------
# The templates and enamldefs defined in this section are ones which can
# be written once and then used as a library. They are more-or-less fully
# generic and will work for a large swath of models.

template FormControl(Attr, MemberType):
    """ A template which generates a control for an AutoForm.

    This default specialization displays read-only text for the value.

    Parameters
    ----------
    Attr : str
        The name of the attribute on 'model' being accessed.

    MemberType : type
        The type of the member being accessed.

    """
    Field:
        read_only = True
        text << str(getattr(model, Attr))


template FormControl(Attr, MemberType: Int):
    """ A form control template specialization for Int members.

    This control uses a spin box to represent the value.

    """
    SpinBox:
        value := getattr(model, Attr)


template FormControl(Attr, MemberType: Str):
    """ A form control template specialization for Str members.

    This control uses a Field to represent the value.

    """
    Field:
        text := getattr(model, Attr)


template FormControl(Attr, MemberType: Float):
    """ A form control template specialization for Float members.

    This control uses a FloatField to represent the value.

    """
    FloatField:
        value := getattr(model, Attr)


template FormControl(Attr, MemberType: Bool):
    """ A form control template specialization for Bool members.

    This control uses a CheckBox to represent the value.

    """
    CheckBox:
        checked := getattr(model, Attr)


template FormControl(Attr, MemberType: Event):
    """ A form control template specialization for Event members.

    This control uses a PushButton to represent the value.

    """
    const ButtonText = Attr[0].upper() + Attr[1:].lower()
    PushButton:
        text = ButtonText
        clicked :: getattr(model, Attr)()


def enum_labels(model, attr):
    """ Return the list of enum labels for the given model and attr.

    """
    items = getattr(type(model), attr).items
    return sorted(items)


template FormControl(Attr, MemberType: Enum):
    """ A form control template specialization for Enum members.

    This control uses an ObjectCombo to represent the value.

    """
    ObjectCombo:
        items = enum_labels(model, Attr)
        selected := getattr(model, Attr)


template FormItem(Attr, MemberType):
    """ A template which generates a pair of items for an AutoForm.

    Parameters
    ----------
    Attr : str
        The name of the attribute on 'model' being accessed.

    MemberType : type
        The type of the member being accessed.

    """
    const LabelText = Attr[0].upper() + Attr[1:].lower()
    Label:
        text = LabelText
    FormControl(Attr, MemberType):
        pass


def form_spec(obtype):
    """ Generate a form specification for an atom type.

    Parameters
    ----------
    obtype : type
        The Atom subclass of interest.

    Returns
    -------
    result : tuple
        A tuple of 2-tuples of (attr, member_type) for all non-private
        members of the class.

    """
    items = []
    for name, member in obtype.members().items():
        if not name.startswith('_'):
            items.append((name, type(member)))
    items.sort()
    return tuple(items)


template ForEach(Spec, Item):
    """ A templated loop which maps a template over a sequence.

    Parameters
    ----------
    Spec : tuple
        A tuple of tuples which are the values to map over the item.

    Item : template
        A template which accepts *values from inner tuples of the spec.

    """
    ForEach(Spec[:-1], Item):
        pass
    Item(*Spec[-1]):
        pass


template ForEach(Spec: (), Item):
    """ The terminating condition for the templated loop.

    """
    pass


template AutoFormBody(ModelType):
    """ A template which builds the body for an AutoForm.

    Parameters
    ----------
    ModelType : type
        The type of the model. This should be an Atom subclass.

    """
    const Spec: tuple = form_spec(ModelType)
    ForEach(Spec, FormItem):
        pass


template AutoFormBody(ModelType: type(None)):
    """ A template specialization for null models.

    """
    pass


enamldef AutoForm(Form):
    """ A Form which automatically generates its body from a model.

    """
    attr model: Atom
    DynamicTemplate:
        base = AutoFormBody
        args = (type(model),)


#------------------------------------------------------------------------------
# Main Models and Views
#------------------------------------------------------------------------------
class FooModel(Atom):
    spam = Int(34)
    ham = Int(42)
    first = Str('first')
    last = Str('last')
    owner = Str('owner')
    time = Float(42.56)
    click = Bool()
    clack = Bool()


class BarModel(Atom):
    name = Str('name')
    trigger = Event()
    choices = Enum('first', 'second', 'third')
    def _observe_trigger(self, change):
        print('I was triggered')


enamldef Main(Window):
    title = 'Advanced Templates'
    attr foo_model = FooModel()
    attr bar_model = BarModel()
    Container:
        GroupBox:
            title = 'Foo Model'
            flat = True
            AutoForm:
                padding = 0
                model = foo_model
        GroupBox:
            title = 'Bar Model'
            flat = True
            AutoForm:
                padding = 0
                model = bar_model