~richardjones/withgui/trunk

« back to all changes in this revision

Viewing changes to withgui.py

  • Committer: Richard Jones
  • Date: 2009-08-27 05:57:06 UTC
  • Revision ID: richard@l-rjones.off.ekorp.com-20090827055706-rm3nnqy4sonkot95
reorg

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import re
2
 
import os
3
 
import sys
4
 
import inspect
5
 
import functools
6
 
 
7
 
# a whole lotta constants
8
 
center = 'center'
9
 
left = 'left'
10
 
right = 'right'
11
 
x = 'x'
12
 
y = 'y'
13
 
both = 'both'
14
 
n = 'n'
15
 
e = 'e'
16
 
s = 's'
17
 
w = 'w'
18
 
nw = 'nw'
19
 
ne = 'ne'
20
 
sw = 'sw'
21
 
se = 'se'
22
 
 
23
 
# color code below originally from pyglet contrib/layout (with extensions)
24
 
class Color(tuple):
25
 
    def __new__(cls, r, g, b, a=1):
26
 
        return tuple.__new__(cls, (r, g, b, a))
27
 
 
28
 
    def to_hex(self, a=False):
29
 
        if a:
30
 
            return '%02x%02x%02x%02x'%(self[0]*255, self[1]*255,
31
 
                self[2]*255, self[3]*255)
32
 
        else:
33
 
            return '%02x%02x%02x'%(self[0]*255, self[1]*255, self[2]*255)
34
 
 
35
 
    @classmethod
36
 
    def from_hex(cls, hex):
37
 
        if len(hex) == 3:
38
 
            return Color(int(hex[0], 16) / 15., 
39
 
                         int(hex[1], 16) / 15.,
40
 
                         int(hex[2], 16) / 15.)
41
 
        elif len(hex) == 4:
42
 
            return Color(int(hex[0], 16) / 15., 
43
 
                         int(hex[1], 16) / 15.,
44
 
                         int(hex[2], 16) / 15.,
45
 
                         int(hex[3], 16) / 15.)
46
 
        elif len(hex) == 6:
47
 
            return Color(int(hex[0:2], 16) / 255.,
48
 
                         int(hex[2:4], 16) / 255.,
49
 
                         int(hex[4:6], 16) / 255.)
50
 
        else:
51
 
            return Color(int(hex[0:2], 16) / 255.,
52
 
                         int(hex[2:4], 16) / 255.,
53
 
                         int(hex[4:6], 16) / 255.,
54
 
                         int(hex[6:8], 16) / 255.)
55
 
 
56
 
# common color names
57
 
Color.names = {
58
 
    'maroon':   Color.from_hex('800000'),
59
 
    'red':      Color.from_hex('ff0000'),
60
 
    'orange':   Color.from_hex('ffa500'),
61
 
    'yellow':   Color.from_hex('ffff00'),
62
 
    'olive':    Color.from_hex('808000'),
63
 
    'purple':   Color.from_hex('800080'),
64
 
    'fuschia':  Color.from_hex('ff00ff'),
65
 
    'white':    Color.from_hex('ffffff'),
66
 
    'lime':     Color.from_hex('00ff00'),
67
 
    'green':    Color.from_hex('008000'),
68
 
    'navy':     Color.from_hex('000080'),
69
 
    'blue':     Color.from_hex('0000ff'),
70
 
    'aqua':     Color.from_hex('00ffff'),
71
 
    'teal':     Color.from_hex('008080'),
72
 
    'black':    Color.from_hex('000000'),
73
 
    'silver':   Color.from_hex('c0c0c0'),
74
 
    'gray':     Color.from_hex('808080'),
75
 
}
76
 
 
77
 
# convenience
78
 
maroon = Color.names['maroon']
79
 
red = Color.names['red']
80
 
orange = Color.names['orange']
81
 
yellow = Color.names['yellow']
82
 
olive = Color.names['olive']
83
 
purple = Color.names['purple']
84
 
fuschia = Color.names['fuschia']
85
 
white = Color.names['white']
86
 
lime = Color.names['lime']
87
 
green = Color.names['green']
88
 
navy = Color.names['navy']
89
 
blue = Color.names['blue']
90
 
aqua = Color.names['aqua']
91
 
teal = Color.names['teal']
92
 
black = Color.names['black']
93
 
silver = Color.names['silver']
94
 
gray = Color.names['gray']
95
 
 
96
 
def prop_color(value):
97
 
    '''Parse a color value which is one of:
98
 
 
99
 
    name    a color name (CSS 2.1 standard colors)
100
 
    RGB     a three-value hex color
101
 
    RRGGBB  a three-value hex color
102
 
    '''
103
 
    if not isinstance(value, str):
104
 
        return value
105
 
    if value in Color.names:
106
 
        return Color.names[value]
107
 
    return Color.from_hex(value)
108
 
def prop_color_or_image(value):
109
 
    if not isinstance(value, str):
110
 
        return value
111
 
    if value in Color.names:
112
 
        return Color.names[value]
113
 
    if re.match(r'[0-9a-f]{3-8}', value, re.I):
114
 
        return Color.from_hex(value)
115
 
    # image filename
116
 
    return value
117
 
def prop_image(value):
118
 
    # TODO check?
119
 
    return value
120
 
def prop_direction(value):
121
 
    # TODO check
122
 
    return value
123
 
def prop_justify_options(value):
124
 
    assert value in ('left', 'right', 'center')
125
 
    return value
126
 
def prop_fill(value):
127
 
    assert value in ('x', 'y', 'both')
128
 
    return value
129
 
def prop_boolean(value):
130
 
    return bool(value)
131
 
def prop_number(value):
132
 
    # TODO check
133
 
    return value
134
 
def prop_width(value):
135
 
    # TODO check
136
 
    return value
137
 
def prop_height(value):
138
 
    # TODO check
139
 
    return value
140
 
def prop_passthrough(value): return value
141
 
 
142
 
class PropertiesDict(dict):
143
 
    '''Extension of dict that limits the keys to those in the properties
144
 
    dict and enforces value types (and handles some type conversions).
145
 
    '''
146
 
    def __init__(self, properties, d):
147
 
        self.properties = properties
148
 
        self.update(d)
149
 
    def __setitem__(self, key, value):
150
 
        if key not in self.properties:
151
 
            raise KeyError('%s is not a valid property'%key)
152
 
        value = self.properties[key](value)
153
 
        super(PropertiesDict, self).__setitem__(key, value)
154
 
    def update(self, d):
155
 
        for key in d:
156
 
            if key not in self.properties:
157
 
                raise KeyError('%s is not a valid property'%key)
158
 
            d[key] = self.properties[key](d[key])
159
 
        super(PropertiesDict, self).update(d)
160
 
 
161
 
class WidgetBase(object):
162
 
    # widget registry
163
 
    widget_classes = {}
164
 
    @classmethod
165
 
    def register_class(cls, klass, name=None):
166
 
        if name is None:
167
 
            name = klass.__name__.lower()
168
 
        cls.widget_classes[name] = klass
169
 
 
170
 
    # instance attribute defaults
171
 
    _gui = None
172
 
    implementation = None
173
 
    animate = None
174
 
    name = None         # this will be filled in by the locals() magic
175
 
    parent = None
176
 
 
177
 
    # property specs
178
 
    properties = {}
179
 
    defaults = {}
180
 
    fixed_args = []
181
 
 
182
 
    def __init__(self, *args, **kw):
183
 
        if 'parent' in kw:
184
 
            # I'm a child widget
185
 
            self.parent = kw.pop('parent')
186
 
            self.gui = self.parent.gui
187
 
            self.parent.add_child(self)
188
 
        else:
189
 
            # I'm the top-level widget so act like one
190
 
            self.stack = [self]                 # CIRCULAR REF here
191
 
            self.gui = self                     # CIRCULAR REF here
192
 
            self.after_actions = []
193
 
            self.window_settings = dict(title='withgui')
194
 
            self.resource = Resource()
195
 
 
196
 
        self.children = []
197
 
        self.event_handlers = {}
198
 
        self.named_widgets = {}
199
 
 
200
 
        # TODO allow layouts to accept a list of child widgets
201
 
        # TODO rename "parent" to "container" or "box" or something
202
 
 
203
 
        settings = dict(self.defaults)
204
 
 
205
 
        if args:
206
 
            kw.update(dict(zip(self.fixed_args, args)))
207
 
 
208
 
        # callbacks / animate
209
 
        for k in dict(kw):
210
 
            if k == 'animate' or k.startswith('on_'):
211
 
                self.add_handler(k, kw.pop(k))
212
 
 
213
 
        settings.update(kw)
214
 
        self.settings = PropertiesDict(self.properties, settings)
215
 
 
216
 
        # if we're already physical then add the widget to the actual gui
217
 
        if self.parent and self.parent.implementation:
218
 
            # TODO handle no parent - create new top-level window
219
 
            self.parent.implementation.add_child(self)
220
 
 
221
 
    def __getattr__(self, name):
222
 
        if name in self.widget_classes:
223
 
            if self is self.gui:
224
 
                parent = self.gui.stack[-1]
225
 
            else:
226
 
                parent = self
227
 
            return functools.partial(self.widget_classes[name],
228
 
                parent=parent)
229
 
 
230
 
        if self.implementation is not None:
231
 
            return self.implementation.get_property(name)
232
 
        elif name in self.properties:
233
 
            return self.settings[name]
234
 
        try:
235
 
            return self.__dict__[name]
236
 
        except KeyError:
237
 
            raise AttributeError('%r has no attribute %s'%(self, name))
238
 
 
239
 
    def __setattr__(self, name, value):
240
 
        if name in ('parent', 'implementation', 'gui', 'extra'):
241
 
            self.__dict__[name] = value
242
 
        elif self.implementation is not None:
243
 
            self.implementation.set_property(name, value)
244
 
        elif name in self.properties:
245
 
            self.settings[name] = self.properties[name](value)
246
 
        else:
247
 
            self.__dict__[name] = value
248
 
 
249
 
 
250
 
    def __call__(self, func):
251
 
        '''Decorate some function - or rather schlurp it into this widget
252
 
        spec as some event handler or animator.
253
 
        '''
254
 
        # TODO refactor so this isn't duplicated in __exit__
255
 
        # are we invoked as a function decorator?
256
 
        if not hasattr(func, '__call__'):
257
 
            raise ValueError('only callable as a decorator')
258
 
        name = func.func_name
259
 
        self.add_handler(name, func)
260
 
        # this for the locals() hax
261
 
        func.name = name
262
 
 
263
 
    def add_handler(self, name, callable):
264
 
        if name == 'animate':
265
 
            # hi, I'm a generator, so generate me
266
 
            self.animate = callable(self)
267
 
            self.animate.send(None)
268
 
        elif name.startswith('on_'):
269
 
            # TODO validate name
270
 
            self.event_handlers[name] = callable
271
 
        else:
272
 
            # not a name I recognise - ignore it
273
 
            return
274
 
 
275
 
 
276
 
    # overridable child adder (for example see Form.add_child)
277
 
    def add_child(self, child):
278
 
        self.children.append(child)
279
 
        child.parent = self
280
 
 
281
 
    def remove_child(self, child):
282
 
        self.children.remove(child)
283
 
        child.parent = None
284
 
 
285
 
    def __getitem__(self, item):
286
 
        if isinstance(item, str):
287
 
            if item[0] == '.':
288
 
                name = item[1:].lower()
289
 
                return [child for child in self.children
290
 
                    if child.__class__.__name__.lower() == name]
291
 
            return self.named_widgets[item]
292
 
        else:
293
 
            return self.children[item]
294
 
 
295
 
    def __enter__(self):
296
 
        # save off the current set of names in the locals()
297
 
        f = sys._getframe(1)
298
 
        locals = inspect.getargvalues(f)[3]
299
 
        self._names = set((k, id(v)) for k, v in locals.items())
300
 
        self.gui.stack.append(self)
301
 
        return self
302
 
 
303
 
    def __exit__(self, exc_type, exc_val, exc_tb):
304
 
        # determine whether any new local variables were created during the
305
 
        # context manager's lifespan and if so (and they're not already
306
 
        # claimed) then add to this object's named objects / event handlers
307
 
        f = sys._getframe(1)
308
 
        locals = inspect.getargvalues(f)[3]
309
 
 
310
 
        # TODO don't store locals names on the object, be smarter about
311
 
        # with "scopes" and store a new stack or something
312
 
        # TODO this is currently buggy - see the second on_click in
313
 
        # form_simple.py
314
 
 
315
 
        for name in locals:
316
 
            o = locals[name]
317
 
            key = (name, id(o))
318
 
 
319
 
            if key in self._names:
320
 
                continue
321
 
 
322
 
            if getattr(o, 'name', None) is not None:
323
 
                continue
324
 
 
325
 
            if o is self:
326
 
                # this is my with statement, don't name me!
327
 
                continue
328
 
 
329
 
            if isinstance(o, WidgetBase):
330
 
                self.named_widgets[name] = o
331
 
 
332
 
            elif hasattr(o, '__call__'):
333
 
                if name == 'animate':
334
 
                    # TODO check signature for dt?
335
 
                    # hi, I'm a generator, so generate and kick me off
336
 
                    self.animate = o(self)
337
 
                    self.animate.send(None)
338
 
                elif name.startswith('on_'):
339
 
                    self.event_handlers[name] = o
340
 
                else:
341
 
                    # not a name I recognise - ignore ir
342
 
                    continue
343
 
 
344
 
            else:
345
 
                # not a widget or callable, ignore it
346
 
                continue
347
 
 
348
 
            o.name = name
349
 
        self.gui.stack.pop()
350
 
 
351
 
    def dump(self, level=''):
352
 
        print '%s%s %r'%(level, self.__class__.__name__.lower(),
353
 
            self.settings)
354
 
        for c in self.children:
355
 
            c.dump(level + '  ')
356
 
 
357
 
    def after(self, delay, action=None):
358
 
        '''Schedule some delayed action.
359
 
 
360
 
        For example::
361
 
 
362
 
            @gui.after(2)
363
 
            def action():
364
 
                ... do something
365
 
 
366
 
        is equivalent to::
367
 
 
368
 
            gui.after(2, action)
369
 
        '''
370
 
        if action is not None:
371
 
            self.gui.after_actions.append((delay, action))
372
 
            return action
373
 
        def f(action):
374
 
            self.gui.after_actions.append((delay, action))
375
 
            return action
376
 
        return f
377
 
 
378
 
    def run(self):
379
 
        #from withsimplui import GUI
380
 
        #from withqt4 import GUI
381
 
        #from withtk import GUI
382
 
        from withkytten import GUI
383
 
 
384
 
        # the assignment here isn't strictly necessary
385
 
        self.gui = GUI(self)
386
 
        self.gui.run()
387
 
 
388
 
    def stop(self, data=None):
389
 
        return self.gui.stop(data)
390
 
 
391
 
    def window(self, **kw):
392
 
        # TODO validate the keywords / values
393
 
        self.gui.window_settings.update(kw)
394
 
 
395
 
    def destroy(self):
396
 
        # remove me from my parent and if I'm implemented then destroy that
397
 
        # too
398
 
        self.parent.remove_child(self)
399
 
        if self.implementation:
400
 
            self.implementation.destroy()
401
 
 
402
 
# TODO Slider
403
 
# TODO Checkbox
404
 
# TODO Color
405
 
# TODO Marked-up text
406
 
class Frame(WidgetBase):
407
 
    # TODO other properties
408
 
    properties = dict(
409
 
        padding=prop_number,
410
 
        background=prop_color_or_image,
411
 
        width=prop_width,
412
 
        height=prop_height,
413
 
    )
414
 
WidgetBase.register_class(Frame)
415
 
 
416
 
class Label(WidgetBase):
417
 
    fixed_args = ('value',)
418
 
    defaults = dict(value='', anchor=nw)
419
 
    properties = dict(
420
 
        foreground=prop_color,
421
 
        background=prop_color,
422
 
        anchor=prop_direction,
423
 
        expand=prop_boolean,
424
 
        justify=prop_justify_options,
425
 
        margin=prop_number,
426
 
        fill=prop_fill,
427
 
        x=prop_number,
428
 
        y=prop_number,
429
 
        value=prop_passthrough,
430
 
    )
431
 
WidgetBase.register_class(Label)
432
 
 
433
 
class Image(WidgetBase):
434
 
    fixed_args = ('value',)
435
 
    defaults = dict(value=None, anchor=nw)
436
 
    properties = dict(
437
 
        anchor=prop_direction,
438
 
        justify=prop_justify_options,
439
 
        margin=prop_number,
440
 
        x=prop_number,
441
 
        y=prop_number,
442
 
        value=prop_image,
443
 
    )
444
 
WidgetBase.register_class(Image)
445
 
 
446
 
class Canvas(WidgetBase):
447
 
    # TODO other properties?
448
 
    properties = dict(
449
 
        padding=prop_number,
450
 
        width=prop_width,
451
 
        height=prop_height,
452
 
        background=prop_color_or_image,
453
 
    )
454
 
    widget_classes = dict(
455
 
        label = Label,
456
 
        image = Image,
457
 
    )
458
 
WidgetBase.register_class(Canvas)
459
 
 
460
 
class Column(Frame):
461
 
    pass
462
 
WidgetBase.register_class(Column)
463
 
 
464
 
class Row(Frame):
465
 
    pass
466
 
WidgetBase.register_class(Row)
467
 
 
468
 
class FormRow(object):
469
 
    '''This encapsulates a label, widget and help text for a single row
470
 
    (value) in a Form.
471
 
    '''
472
 
    label = None
473
 
    widget = None
474
 
    help = None
475
 
    def __init__(self, gui=None):
476
 
        self.gui = gui
477
 
    def needs(self, widget):
478
 
        if isinstance(widget, Label):
479
 
            return self.label is None
480
 
        elif isinstance(widget, Help):
481
 
            return self.help is None
482
 
        return self.widget is None
483
 
    def add(self, widget):
484
 
        if isinstance(widget, Label):
485
 
            self.label = widget
486
 
        elif isinstance(widget, Help):
487
 
            self.help = widget
488
 
        else:
489
 
            self.widget = widget
490
 
 
491
 
class Form(WidgetBase):
492
 
    def __init__(self, *args, **kw):
493
 
        super(Form, self).__init__(*args, **kw)
494
 
        self.rows = [FormRow(self.gui)]
495
 
        self.buttons = []
496
 
 
497
 
    def add_child(self, child):
498
 
        if isinstance(child, FormRow):
499
 
            self.rows.append(child)
500
 
        elif isinstance(child, FormButton):
501
 
            self.buttons.append(child)
502
 
        else:
503
 
            self.children.append(child)
504
 
            child.parent = self
505
 
            if not self.rows[-1].needs(child):
506
 
                self.rows.append(FormRow())
507
 
            self.rows[-1].add(child)
508
 
 
509
 
    def row(self, label=None, widget=None, help=None):
510
 
        '''Create a row in one go. The label and help are passed in as
511
 
        strings. The widget is separately constructed.
512
 
 
513
 
        Returns the widget for convenience (may be bound to a local name
514
 
        for later access or manipulation).
515
 
        '''
516
 
        if label is not None:
517
 
            assert not isinstance(label, Label)
518
 
            Label(label, parent=self)
519
 
        if widget is not None:
520
 
            assert isinstance(widget, WidgetBase)
521
 
        if help is not None:
522
 
            assert not isinstance(help, Help)
523
 
            Help(help, parent=self)
524
 
        # for convenience this will allow local binding of the widget to a
525
 
        # name
526
 
        return widget
527
 
 
528
 
WidgetBase.register_class(Form)
529
 
 
530
 
class Text(WidgetBase):
531
 
    fixed_args = ('value',)
532
 
    properties = dict(
533
 
        value=prop_passthrough,
534
 
    )
535
 
WidgetBase.register_class(Text)
536
 
 
537
 
class Selection(WidgetBase):
538
 
    fixed_args = ('options', 'value')
539
 
    properties = dict(
540
 
        options=prop_passthrough,
541
 
        value=prop_passthrough,
542
 
    )
543
 
WidgetBase.register_class(Selection)
544
 
 
545
 
class Help(WidgetBase):
546
 
    fixed_args = ('value',)
547
 
    properties = dict(
548
 
        value=prop_passthrough,
549
 
    )
550
 
WidgetBase.register_class(Help)
551
 
 
552
 
class Button(WidgetBase):
553
 
    fixed_args = ('value',)
554
 
    properties = dict(
555
 
        foreground=prop_color,
556
 
        background=prop_color,
557
 
        anchor=prop_direction,
558
 
        justify=prop_justify_options,
559
 
        margin=prop_number,
560
 
        fill=prop_fill,
561
 
        x=prop_number,
562
 
        y=prop_number,
563
 
        value=prop_passthrough,
564
 
    )
565
 
    def on_click(self, handler):
566
 
        self.event_handlers['on_click'] = handler
567
 
WidgetBase.register_class(Button)
568
 
 
569
 
class FormButton(Button):
570
 
    # group submit / cancel button classes
571
 
    pass
572
 
class Submit(FormButton):
573
 
    pass
574
 
WidgetBase.register_class(Submit)
575
 
 
576
 
class Cancel(FormButton):
577
 
    pass
578
 
WidgetBase.register_class(Cancel)
579
 
 
580
 
class Resource(object):
581
 
    def __init__(self):
582
 
        self.paths = [os.path.abspath(os.path.dirname(sys.argv[0]))]
583
 
 
584
 
    def add(self, path):
585
 
        # TODO allow ZIP files etc.
586
 
        self.paths.append(path)
587
 
 
588
 
    def lookup(self, name):
589
 
        for path in self.paths:
590
 
            p = os.path.join(path, name)
591
 
            if os.path.isfile(os.path.join(path, name)):
592
 
                return p
593
 
    
594
 
def run_for(seconds):
595
 
    '''Become a generator over the other animation generator f() which
596
 
    expects to be passed values from 0 to 1 over the specified time in
597
 
    seconds.
598
 
    '''
599
 
    def g(f):
600
 
        def animate(w, seconds=seconds, f=f):
601
 
            t = 0.0
602
 
            f = f(w)
603
 
            f.send(None)
604
 
            while t < seconds:
605
 
                dt = yield
606
 
                t += dt
607
 
                if t > seconds:
608
 
                    f.send(1)
609
 
                else:
610
 
                    f.send(t / seconds)
611
 
        return animate
612
 
    return g
613
 
 
614
 
 
615
 
if __name__ == '__main__':
616
 
    with Column() as gui:
617
 
        gui.resource.add(os.path.abspath(os.path.dirname(sys.argv[1])))
618
 
        exec(open(sys.argv[1]).read())
619
 
    sys.exit(gui.run())
620