File: widget.py

package info (click to toggle)
python-vispy 0.15.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,868 kB
  • sloc: python: 59,799; javascript: 6,800; makefile: 69; sh: 6
file content (489 lines) | stat: -rw-r--r-- 14,124 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
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

from __future__ import division

import numpy as np

from ..visuals import Compound
from ...visuals.mesh import MeshVisual
from ...visuals.transforms import STTransform
from ...visuals.filters import Clipper
from ...util.event import Event
from ...geometry import Rect
from ...color import Color


class Widget(Compound):
    """A widget takes up a rectangular space, intended for use in
    a 2D pixel coordinate frame.

    The widget is positioned using the transform attribute (as any
    node), and its extent (size) is kept as a separate property.

    Parameters
    ----------
    pos : (x, y)
        A 2-element tuple to specify the top left corner of the widget.
    size : (w, h)
        A 2-element tuple to spicify the size of the widget.
    border_color : color
        The color of the border.
    border_width : float
        The width of the border line in pixels.
    bgcolor : color
        The background color.
    padding : int
        The amount of padding in the widget (i.e. the space reserved between
        the contents and the border).
    margin : int
        The margin to keep outside the widget's border.
    """

    def __init__(self, pos=(0, 0), size=(10, 10), border_color=None,
                 border_width=1, bgcolor=None, padding=0, margin=0, **kwargs):
        # For drawing border.
        # A mesh is required because GL lines cannot be drawn with predictable
        # shape across all platforms.
        self._mesh = MeshVisual(color=border_color, mode='triangles')
        self._mesh.set_gl_state('translucent', depth_test=False,
                                cull_face=False)
        self._picking_mesh = MeshVisual(mode='triangle_fan')
        self._picking_mesh.set_gl_state(cull_face=False, depth_test=False)
        self._picking_mesh.visible = False

        # reserved space inside border
        self._padding = padding

        self._border_width = border_width

        # reserved space outside border
        self._margin = margin
        self._size = 100, 100

        # layout interaction
        self._width_limits = [0, None]
        self._height_limits = [0, None]
        self._stretch = [None, None]

        # used by the constraint solver
        # in Grid - these are Cassowary variables
        self._var_w = self._var_h = None
        self._var_x = self._var_y = None

        self._widgets = []
        self._border_color = Color(border_color)
        self._bgcolor = Color(bgcolor)
        self._face_colors = None

        # Flag to allow rect setter to know if pos or size changed.
        self._pos_or_size_changed = False

        Compound.__init__(self, [self._mesh, self._picking_mesh], **kwargs)

        self.transform = STTransform()
        self.events.add(resize=Event)
        self.pos = pos
        self._update_colors()
        self.size = size

    @property
    def pos(self):
        return tuple(self.transform.translate[:2])

    @pos.setter
    def pos(self, p):
        assert isinstance(p, tuple)
        assert len(p) == 2
        # Handle floating point discrepancies
        if abs(p[0] - self.pos[0]) < 1e-4 and \
           abs(p[1] - self.pos[1]) < 1e-4:
            return
        self._pos_or_size_changed = True
        self.transform.translate = p[0], p[1], 0, 0
        self._update_line()

    @property
    def size(self):
        """The size (w, h) of this widget.

        If the widget is a child of another widget, then its size is assigned
        automatically by its parent.
        """
        return self._size

    @size.setter
    def size(self, s):
        assert isinstance(s, tuple)
        assert len(s) == 2
        # Handle floating point discrepancies
        if abs(s[0] - self._size[0]) < 1e-4 and \
           abs(s[1] - self._size[1]) < 1e-4:
            return
        self._pos_or_size_changed = True
        self._size = s
        self._update_line()
        self._update_child_widgets()
        self._update_clipper()
        self.events.resize()

    @property
    def width(self):
        """The actual width of this widget"""
        return self._size[0]

    @property
    def width_min(self):
        """The minimum width the widget can have"""
        return self._width_limits[0]

    @width_min.setter
    def width_min(self, width_min):
        """Set the minimum height of the widget

        Parameters
        ----------
        height_min: float
            the minimum height of the widget
        """
        if width_min is None:
            self._width_limits[0] = 0
            return

        width_min = float(width_min)
        assert(0 <= width_min)

        self._width_limits[0] = width_min
        self._update_layout()

    @property
    def width_max(self):
        """The maximum width the widget can have"""
        return self._width_limits[1]

    @width_max.setter
    def width_max(self, width_max):
        """Set the maximum width of the widget.

        Parameters
        ----------
        width_max: None | float
            the maximum width of the widget. if None, maximum width
            is unbounded
        """
        if width_max is None:
            self._width_limits[1] = None
            return

        width_max = float(width_max)
        assert(self.width_min <= width_max)

        self._width_limits[1] = width_max
        self._update_layout()

    @property
    def height(self):
        """The actual height of the widget"""
        return self._size[1]

    @property
    def height_min(self):
        """The minimum height of the widget"""
        return self._height_limits[0]

    @height_min.setter
    def height_min(self, height_min):
        """Set the minimum height of the widget

        Parameters
        ----------
        height_min: float
            the minimum height of the widget
        """
        if height_min is None:
            self._height_limits[0] = 0
            return

        height_min = float(height_min)
        assert(height_min >= 0)

        self._height_limits[0] = height_min
        self._update_layout()

    @property
    def height_max(self):
        """The maximum height of the widget"""
        return self._height_limits[1]

    @height_max.setter
    def height_max(self, height_max):
        """Set the maximum height of the widget.

        Parameters
        ----------
        height_max: None | float
            the maximum height of the widget. if None, maximum height
            is unbounded
        """
        if height_max is None:
            self._height_limits[1] = None
            return

        height_max = float(height_max)
        assert(0 <= self.height_min <= height_max)
        self._height_limits[1] = height_max
        self._update_layout()

    @property
    def rect(self):
        return Rect((0, 0), self.size)

    @rect.setter
    def rect(self, r):
        self._pos_or_size_changed = False
        with self.events.resize.blocker():
            self.pos = r.pos
            self.size = r.size
        if self._pos_or_size_changed:
            self.update()
            self.events.resize()

    @property
    def inner_rect(self):
        """The rectangular area inside the margin, border, and padding.

        Generally widgets should avoid drawing or placing sub-widgets outside
        this rectangle.
        """
        m = self.margin + self._border_width + self.padding
        if not self.border_color.is_blank:
            m += 1
        return Rect((m, m), (self.size[0]-2*m, self.size[1]-2*m))

    @property
    def stretch(self):
        """Stretch factors (w, h) used when determining how much space to
        allocate to this widget in a layout.

        If either stretch factor is None, then it will be assigned when the
        widget is added to a layout based on the number of columns or rows it
        occupies.
        """
        return self._stretch

    @stretch.setter
    def stretch(self, s):
        self._stretch = [float(s[0]), float(s[1])]

        if self._stretch[0] == 0:
            raise RuntimeError("received 0 as stretch parameter: %s", s)

        if self._stretch[1] == 0:
            raise RuntimeError("received 0 as stretch parameter: %s", s)

        self._update_layout()

    def _update_layout(self):
        if isinstance(self.parent, Widget):
            self.parent._update_child_widgets()

    def _update_clipper(self):
        """Called whenever the clipper for this widget may need to be updated."""
        if self.clip_children and self._clipper is None:
            self._clipper = Clipper()
        elif not self.clip_children:
            self._clipper = None

        if self._clipper is None:
            return
        self._clipper.rect = self.inner_rect
        self._clipper.transform = self.get_transform('framebuffer', 'visual')

    @property
    def border_color(self):
        """The color of the border."""
        return self._border_color

    @border_color.setter
    def border_color(self, b):
        self._border_color = Color(b)
        self._update_colors()
        self._update_line()
        self.update()

    @property
    def border_width(self):
        """The width of the border."""
        return self._border_width

    @border_width.setter
    def border_width(self, b):
        self._border_width = float(b)
        self._update_line()
        self.update()

    @property
    def bgcolor(self):
        """The background color of the Widget."""
        return self._bgcolor

    @bgcolor.setter
    def bgcolor(self, value):
        self._bgcolor = Color(value)
        self._update_colors()
        self._update_line()
        self.update()

    @property
    def margin(self):
        return self._margin

    @margin.setter
    def margin(self, m):
        self._margin = m
        self._update_child_widgets()
        self._update_line()
        self.update()
        self.events.resize()

    @property
    def padding(self):
        return self._padding

    @padding.setter
    def padding(self, p):
        self._padding = p
        self._update_child_widgets()
        self.update()

    def _update_line(self):
        """Update border line to match new shape"""
        w = self._border_width
        m = self.margin
        # border is drawn within the boundaries of the widget:
        #
        #  size = (8, 7)  margin=2
        #  internal rect = (3, 3, 2, 1)
        #  ........
        #  ........
        #  ..BBBB..
        #  ..B  B..
        #  ..BBBB..
        #  ........
        #  ........
        #
        left = bot = m
        right = self.size[0] - m
        top = self.size[1] - m
        pos = np.array([
            [left, bot], [left+w, bot+w],
            [right, bot], [right-w, bot+w],
            [right, top], [right-w, top-w],
            [left, top], [left+w, top-w],
        ], dtype=np.float32)
        faces = np.array([
            [0, 2, 1],
            [1, 2, 3],
            [2, 4, 3],
            [3, 5, 4],
            [4, 5, 6],
            [5, 7, 6],
            [6, 0, 7],
            [7, 0, 1],
            [5, 3, 1],
            [1, 5, 7],
        ], dtype=np.int32)
        start = 8 if self._border_color.is_blank else 0
        stop = 8 if self._bgcolor.is_blank else 10
        face_colors = None
        if self._face_colors is not None:
            face_colors = self._face_colors[start:stop]
        self._mesh.set_data(vertices=pos, faces=faces[start:stop],
                            face_colors=face_colors)

        # picking mesh covers the entire area
        self._picking_mesh.set_data(vertices=pos[::2])

    def _update_colors(self):
        self._face_colors = np.concatenate(
            (np.tile(self.border_color.rgba, (8, 1)),
             np.tile(self.bgcolor.rgba, (2, 1)))).astype(np.float32)
        self._update_visibility()

    @property
    def picking(self):
        return self._picking

    @picking.setter
    def picking(self, p):
        Compound.picking.fset(self, p)
        self._update_visibility()

    def _update_visibility(self):
        blank = self.border_color.is_blank and self.bgcolor.is_blank
        picking = self.picking
        self._picking_mesh.visible = picking and self.interactive
        self._mesh.visible = not picking and not blank

    def _update_child_widgets(self):
        # Set the position and size of child boxes (only those added
        # using add_widget)
        for ch in self._widgets:
            ch.rect = self.rect.padded(self.padding + self.margin)

    def add_widget(self, widget):
        """
        Add a Widget as a managed child of this Widget.

        The child will be
        automatically positioned and sized to fill the entire space inside
        this Widget (unless _update_child_widgets is redefined).

        Parameters
        ----------
        widget : instance of Widget
            The widget to add.

        Returns
        -------
        widget : instance of Widget
            The widget.
        """
        self._widgets.append(widget)
        widget.parent = self
        self._update_child_widgets()
        return widget

    def add_grid(self, *args, **kwargs):
        """
        Create a new Grid and add it as a child widget.

        All arguments are given to Grid().
        """
        from .grid import Grid
        grid = Grid(*args, **kwargs)
        return self.add_widget(grid)

    def add_view(self, *args, **kwargs):
        """
        Create a new ViewBox and add it as a child widget.

        All arguments are given to ViewBox().
        """
        from .viewbox import ViewBox
        view = ViewBox(*args, **kwargs)
        return self.add_widget(view)

    def remove_widget(self, widget):
        """
        Remove a Widget as a managed child of this Widget.

        Parameters
        ----------
        widget : instance of Widget
            The widget to remove.
        """
        self._widgets.remove(widget)
        widget.parent = None
        self._update_child_widgets()