File: themed_vertical_notebook.py

package info (click to toggle)
python-traitsui 4.4.0-1.3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,680 kB
  • ctags: 6,394
  • sloc: python: 32,786; makefile: 16; sh: 5
file content (508 lines) | stat: -rw-r--r-- 16,752 bytes parent folder | download | duplicates (3)
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#-------------------------------------------------------------------------------
#
#  Copyright (c) 2007, Enthought, Inc.
#  All rights reserved.
#
#  This software is provided without warranty under the terms of the BSD
#  license included in enthought/LICENSE.txt and may be redistributed only
#  under the conditions described in the aforementioned license.  The license
#  is also available online at http://www.enthought.com/licenses/BSD.txt
#
#  Thanks for using Enthought open source!
#
#  Author: David C. Morrill
#  Date:   07/05/2007
#
#-------------------------------------------------------------------------------

""" Defines a ThemedVerticalNotebook class for displaying a series of pages
    organized vertically, as opposed to horizontally like a standard notebook.
"""

#-------------------------------------------------------------------------------
#  Imports:
#-------------------------------------------------------------------------------

import wx

from traits.api \
    import HasTraits, HasPrivateTraits, Instance, List, Str, Bool, Property, \
           Event, Any, on_trait_change, cached_property

from traitsui.api \
    import UI, Theme

from traitsui.ui_traits \
    import ATheme

from traitsui.editor \
    import Editor

from constants \
    import WindowColor, screen_dy

from image_slice \
    import paint_parent

from image_panel \
    import ImagePanel

from themed_control \
    import ThemedControl

from helper \
    import TraitsUIPanel, TraitsUIScrolledPanel

#-------------------------------------------------------------------------------
#  'ThemedPage' class:
#-------------------------------------------------------------------------------

class ThemedPage ( HasPrivateTraits ):
    """ A class representing a themed page within a notebook.
    """

    #-- Public Traits ----------------------------------------------------------

    # The name of the page (displayed on its 'tab') [Set by client]:
    name = Str

    # The optional Traits UI associated with this page [Set by client]:
    ui = Instance( UI )

    # The wxPython window the page represents [Set by client]:
    control = Instance( wx.Window )

    # Optional client data associated with the page [Set/Get by client]:
    data = Any

    # The optional object defining the page name [Set by client]:
    object = Instance( HasTraits )

    # The name of the object trait that signals a page name change [Set by
    # client]:
    trait_name = Str

    # The parent window for the client page [Get by client]:
    parent = Property

    #-- Traits for use by the Notebook/Sizer -----------------------------------

    # The current open status of the notebook page:
    is_open = Bool( False )

    # The minimum size for the page:
    min_size = Property

    # The open size property for the page:
    open_size = Property

    # The closed size property for the page:
    closed_size = Property

    #-- Private Traits ---------------------------------------------------------

    # The notebook this page is associated with:
    notebook = Instance( 'ThemedVerticalNotebook' )

    # The theme used to display a closed page:
    closed_theme = ATheme

    # The theme use to display an open page:
    open_theme = ATheme

    # The control representing the closed page:
    closed_page = Property( depends_on = 'closed_theme' )

    # The control representing the open page:
    open_page = Property( depends_on = 'open_theme' )

    #-- Public Methods ---------------------------------------------------------

    def close ( self ):
        """ Closes the notebook page.
        """
        if self.object is not None:
            self.object.on_trait_change( self._name_updated, self.trait_name,
                                         remove = True )
            self.object = None

        if self.ui is not None:
            self.ui.dispose()
            self.ui = None

        if self.closed_page is not None:
            self.closed_page.control.Destroy()
            self.open_page.control.Destroy()
            self.control = None

    def set_size ( self, x, y, dx, dy ):
        """ Sets the size of the current active page.
        """
        if self.is_open:
            self.open_page.control.SetDimensions( x, y, dx, dy )
        else:
            self.closed_page.control.SetDimensions( x, y, dx, dy )

    def register_name_listener ( self, object, trait_name ):
        """ Registers a listener on the specified object trait for a page name
            change.
        """
        # Save the information, so we can unregister it later:
        self.object, self.trait_name = object, trait_name

        # Register the listener:
        object.on_trait_change( self._name_updated, trait_name )

        # Make sure the name gets initialized:
        self._name_updated()

    #-- Property Implementations -----------------------------------------------

    def _get_min_size ( self ):
        """ Returns the minimum size for the page.
        """
        dxo, dyo = self.open_page.best_size
        dxc, dyc = self.closed_page.best_size
        if self.is_open:
            return wx.Size( max( dxo, dxc ), dyo )

        return wx.Size( max( dxo, dxc ), dyc )

    def _get_open_size ( self ):
        """ Returns the open size for the page.
        """
        return self.open_page.best_size

    def _get_closed_size ( self ):
        """ Returns the closed size for the page.
        """
        return self.closed_page.best_size

    @cached_property
    def _get_closed_page ( self ):
        """ Returns the 'closed' form of the notebook page.
        """
        result = ThemedControl( theme             = self.closed_theme,
                                text              = self.name,
                                controller        = self,
                                default_alignment = 'center',
                                state             = 'closed' )
        result.create_control( self.notebook.control )

        return result

    @cached_property
    def _get_open_page ( self ):
        """ Returns the 'open' form of the notebook page.
        """
        result = ImagePanel( theme             = self.open_theme,
                             text              = self.name,
                             controller        = self,
                             default_alignment = 'center',
                             state             = 'open' )
        result.create_control( self.notebook.control )

        return result

    def _get_parent ( self ):
        """ Returns the parent window for the client's window.
        """
        return self.open_page.control

    #-- Trait Event Handlers ---------------------------------------------------

    def _ui_changed ( self, ui ):
        """ Handles the ui trait being changed.
        """
        if ui is not None:
            self.control = ui.control

    def _control_changed ( self, control ):
        """ Handles the control for the page being changed.
        """
        if control is not None:
            self.open_page.control.GetSizer().Add( control, 1, wx.EXPAND )
            self._is_open_changed( self.is_open )

    def _is_open_changed ( self, is_open ):
        """ Handles the 'is_open' state of the page being changed.
        """
        self.closed_page.control.Show( not is_open )
        self.open_page.control.Show( is_open )

        if is_open:
            self.closed_page.control.SetSize( wx.Size( 0, 0 ) )
        else:
            self.open_page.control.SetSize( wx.Size( 0, 0 ) )

    def _name_changed ( self, name ):
        """ Handles the name trait being changed.
        """
        self.closed_page.text = self.open_page.text = name

    def _name_updated ( self ):
        """ Handles a signal that the associated object's page name has changed.
        """
        nb           = self.notebook
        handler_name = None

        method = None
        editor = nb.editor
        if editor is not None:
            method = getattr( editor.ui.handler,
                 '%s_%s_page_name' % ( editor.object_name, editor.name ), None )
        if method is not None:
            handler_name = method( editor.ui.info, self.object )

        if handler_name is not None:
            self.name = handler_name
        else:
            self.name = getattr( self.object, self.trait_name ) or '???'

    #-- ThemedControl Mouse Event Handlers -------------------------------------

    def open_left_down ( self, x, y, event ):
        """ Handles the user clicking on an open notebook page to close it.
        """
        if not self.notebook.double_click:
            self.notebook.close( self )

    def open_left_dclick ( self, x, y, event ):
        """ Handles the user double clicking on an open notebook page to close
            it.
        """
        if self.notebook.double_click:
            self.notebook.close( self )

    def closed_left_down ( self, x, y, event ):
        """ Handles the user clicking on a closed notebook page to open it.
        """
        if not self.notebook.double_click:
            self.notebook.open( self )

    def closed_left_dclick ( self, x, y, event ):
        """ Handles the user double clicking on a closed notebook page to open
            it.
        """
        if self.notebook.double_click:
            self.notebook.open( self )

#-------------------------------------------------------------------------------
#  'ThemedVerticalNotebook' class:
#-------------------------------------------------------------------------------

class ThemedVerticalNotebook ( HasPrivateTraits ):
    """ Defines a ThemedVerticalNotebook class for displaying a series of pages
        organized vertically, as opposed to horizontally like a standard
        notebook.
    """

    #-- Public Traits ----------------------------------------------------------

    # The theme to use for 'closed' notebook pages:
    closed_theme = ATheme( Theme( '@std:notebook_close', content = 0 ) )

    # The theme to use for 'open' notebook pages:
    open_theme = ATheme( Theme( '@std:notebook_open', content = 0 ) )

    # Allow multiple open pages at once?
    multiple_open = Bool( False )

    # Should the notebook be scrollable?
    scrollable = Bool( False )

    # Use double clicks (True) or single clicks (False) to open/close pages:
    double_click = Bool( False )

    # The pages contained in the notebook:
    pages = List( ThemedPage )

    # The traits UI editor this notebook is associated with (if any):
    editor = Instance( Editor )

    #-- Private Traits ---------------------------------------------------------

    # The wxPython control used to represent the notebook:
    control = Instance( wx.Window )

    #-- Public Methods ---------------------------------------------------------

    def create_control ( self, parent ):
        """ Creates the underlying wxPython window used for the notebook.
        """
        # Create the correct type of window based on whether or not it should
        # be scrollable:
        if self.scrollable:
            self.control = control = TraitsUIScrolledPanel( parent )
            control.SetScrollRate( 6, 6 )
            control.SetSize( wx.Size( 0, 0 ) )
        else:
            self.control = control = TraitsUIPanel( parent, -1 )

        control._image_slice = getattr( parent, '_image_slice', None )
        control.SetSizer( ThemedVerticalNotebookSizer( self ) )

        # Set up the painting event handlers:
        wx.EVT_ERASE_BACKGROUND( control, self._erase_background )
        wx.EVT_PAINT( control, self._paint )

        return control

    def create_page ( self ):
        """ Creates a new **ThemedPage** object representing a notebook page and
            returns it as the result.
        """
        return ThemedPage( notebook     = self ).set(
                           closed_theme = self.closed_theme,
                           open_theme   = self.open_theme )

    def open ( self, page ):
        """ Handles opening a specified **ThemedPage** notebook page.
        """
        if (page is not None) and (not page.is_open):
            if not self.multiple_open:
                for a_page in self.pages:
                    a_page.is_open = False

            page.is_open = True

            self._refresh()

    def close ( self, page ):
        """ Handles closing a specified **ThemedPage** notebook page.
        """
        if (page is not None) and page.is_open:
            page.is_open = False
            self._refresh()

    #-- Trait Event Handlers ---------------------------------------------------

    def _pages_changed ( self, old, new ):
        """ Handles the notebook's pages being changed.
        """
        for page in old:
            page.close()

        self._refresh()

    def _pages_items_changed ( self, event ):
        """ Handles some of the notebook's pages being changed.
        """
        for page in event.removed:
            page.close()

        self._refresh()

    def _multiple_open_changed ( self, multiple_open ):
        """ Handles the 'multiple_open' flag being changed.
        """
        if not multiple_open:
            first = True
            for page in self.pages:
                if first and page.is_open:
                    first = False
                else:
                    page.is_open = False

        self._refresh()

    #-- wx.Python Event Handlers -----------------------------------------------

    def _erase_background ( self, event ):
        """ Do not erase the background here (do it in the 'on_paint' handler).
        """
        pass

    def _paint ( self, event ):
        """ Paint the background using the associated ImageSlice object.
        """
        paint_parent( wx.PaintDC( self.control ), self.control )

    #-- Private Methods --------------------------------------------------------

    def _refresh ( self ):
        """ Refresh the layout and contents of the notebook.
        """
        control = self.control
        if control is not None:
            # Set the virtual size of the canvas (so scroll bars work right):
            sizer = control.GetSizer()
            if control.GetSize()[0] == 0:
                control.SetSize( sizer.CalcInit() )
            control.SetVirtualSize( sizer.CalcMin() )
            control.Layout()
            control.Refresh()

#-------------------------------------------------------------------------------
#  'ThemedVerticalNotebookSizer' class:
#-------------------------------------------------------------------------------

class ThemedVerticalNotebookSizer ( wx.PySizer ):
    """ Defines a sizer that correctly sizes a themed vertical notebook's
        children to implement the vertical notebook UI model.
    """

    def __init__ ( self, notebook ):
        """ Initializes the object.
        """
        super( ThemedVerticalNotebookSizer, self ).__init__()

        # Save the notebook reference:
        self._notebook = notebook

    def CalcMin ( self ):
        """ Calculates the minimum size of the control by aggregating the
            sizes of the open and closed pages.
        """
        tdx, tdy = 0, 0
        for page in self._notebook.pages:
            dx, dy = page.min_size
            tdx    = max( tdx, dx )
            tdy   += dy

        return wx.Size( tdx, tdy )

    def CalcInit ( self ):
        """ Calculates a reasonable initial size of the control by aggregating
            the sizes of the open and closed pages.
        """
        tdx, tdy = 0, 0
        open_dy  = closed_dy = 0
        for page in self._notebook.pages:
            dxo, dyo = page.open_size
            dxc, dyc = page.closed_size
            tdx      = max( tdx, dxo, dxc )
            if dyo > open_dy:
                tdy += (dyo - open_dy + closed_dy)
                open_dy, closed_dy = dyo, dyc
            else:
                tdy += dyc

        return wx.Size( tdx, min( tdy, screen_dy / 2 ) )

    def RecalcSizes ( self ):
        """ Layout the contents of the sizer based on the sizer's current size
            and position.
        """
        x, y     = self.GetPositionTuple()
        tdx, tdy = self.GetSizeTuple()
        cdy      = ody = 0
        for page in self._notebook.pages:
            dx, dy = page.min_size
            if page.is_open:
                ody += dy
            else:
                cdy += dy

        ady = max( 0, tdy - cdy )

        for page in self._notebook.pages:
            dx, dy = page.min_size
            if page.is_open:
                ndy  = (ady * dy) / ody
                ady -= ndy
                ody -= dy
                dy   = ndy
            page.set_size( x, y, tdx, dy )
            y += dy