File: editor_factory.py

package info (click to toggle)
python-traitsui 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 13,292 kB
  • sloc: python: 39,867; makefile: 120; sh: 5
file content (294 lines) | stat: -rw-r--r-- 11,908 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
#------------------------------------------------------------------------------
#
#  Copyright (c) 2005, 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:   10/07/2004
#
#------------------------------------------------------------------------------

""" Defines the abstract EditorFactory class, which represents a factory for
    creating the Editor objects used in a Traits-based user interface.
"""

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

from __future__ import absolute_import

import sys, os

from traits.api import HasPrivateTraits, Callable, Str, Bool, Event, Any, Property

from .helper import enum_values_changed

from .toolkit import toolkit_object

#-------------------------------------------------------------------------------
#  'EditorFactory' abstract base class:
#-------------------------------------------------------------------------------

class EditorFactory ( HasPrivateTraits ):
    """ Represents a factory for creating the Editor objects in a Traits-based
        user interface.
    """

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Function to use for string formatting
    format_func = Callable

    # Format string to use for formatting (used if **format_func** is not set).
    format_str = Str

    # Is the editor being used to create table grid cells?
    is_grid_cell = Bool( False )

    # Are created editors initially enabled?
    enabled = Bool( True )

    # The extended trait name of the trait containing editor invalid state
    # status:
    invalid = Str

    # Text aligment to use in most readonly editors
    # Possible values: left, right, top, bottom, just, vcenter, hcenter, center
    # Example: left,vcenter
    text_alignment = Str

    # The editor class to use for 'simple' style views.
    simple_editor_class = Property

    # The editor class to use for 'custom' style views.
    custom_editor_class = Property

    # The editor class to use for 'text' style views.
    text_editor_class   = Property

    # The editor class to use for 'readonly' style views.
    readonly_editor_class = Property

    #---------------------------------------------------------------------------
    #  Initializes the object:
    #---------------------------------------------------------------------------

    def __init__ ( self, *args, **traits ):
        """ Initializes the factory object.
        """
        HasPrivateTraits.__init__( self, **traits )
        self.init( *args )

    #---------------------------------------------------------------------------
    #  Performs any initialization needed after all constructor traits have
    #  been set:
    #---------------------------------------------------------------------------

    def init ( self ):
        """ Performs any initialization needed after all constructor traits
            have been set.
        """
        pass

    #---------------------------------------------------------------------------
    #  Returns the value of a specified extended name of the form: name or
    #  context_object_name.name[.name...]:
    #---------------------------------------------------------------------------

    def named_value ( self, name, ui ):
        """ Returns the value of a specified extended name of the form: name or
            context_object_name.name[.name...]:
        """
        names = name.split( '.' )

        if len( names ) == 1:
            # fixme: This will produce incorrect values if the actual Item the
            # factory is being used with does not use the default object='name'
            # value, and the specified 'name' does not contain a '.'. The
            # solution will probably involve providing the Item as an argument,
            # but it is currently not available at the time this method needs to
            # be called...
            names.insert( 0, 'object' )

        value = ui.context[ names[0] ]
        for name in names[1:]:
            value = getattr( value, name )

        return value
    #---------------------------------------------------------------------------
    #  Methods that generate backend toolkit-specific editors.
    #---------------------------------------------------------------------------

    def simple_editor ( self, ui, object, name, description, parent ):
        """ Generates an editor using the "simple" style.
        """
        return self.simple_editor_class( parent,
                                         factory     = self,
                                         ui          = ui,
                                         object      = object,
                                         name        = name,
                                         description = description )

    def custom_editor ( self, ui, object, name, description, parent ):
        """ Generates an editor using the "custom" style.
        """
        return self.custom_editor_class( parent,
                                         factory     = self,
                                         ui          = ui,
                                         object      = object,
                                         name        = name,
                                         description = description )

    def text_editor ( self, ui, object, name, description, parent ):
        """ Generates an editor using the "text" style.
        """
        return self.text_editor_class( parent,
                                       factory     = self,
                                       ui          = ui,
                                       object      = object,
                                       name        = name,
                                       description = description )

    def readonly_editor ( self, ui, object, name, description, parent ):
        """ Generates an "editor" that is read-only.
        """
        return self.readonly_editor_class( parent,
                                           factory     = self,
                                           ui          = ui,
                                           object      = object,
                                           name        = name,
                                           description = description )

    #---------------------------------------------------------------------------
    #  Private methods
    #---------------------------------------------------------------------------
    @classmethod
    def _get_toolkit_editor(cls, class_name):
        """
        Returns the editor by name class_name in the backend package.
        """
        editor_factory_classes = [factory_class for factory_class in cls.mro()
                                  if issubclass(factory_class, EditorFactory)]
        for index in range(len( editor_factory_classes )):
            try:
                factory_class = editor_factory_classes[index]
                editor_file_name = os.path.basename(
                                sys.modules[factory_class.__module__].__file__)
                return toolkit_object(':'.join([editor_file_name.split('.')[0],
                                             class_name]), True)
            except Exception, e:
                if index == len(editor_factory_classes)-1:
                    raise e
        return None

    #---------------------------------------------------------------------------
    #  Property getters
    #---------------------------------------------------------------------------

    def _get_simple_editor_class(self):
        """ Returns the editor class to use for "simple" style views.
        The default implementation tries to import the SimpleEditor class in the
        editor file in the backend package, and if such a class is not to found
        it returns the SimpleEditor class defined in editor_factory module in
        the backend package.

        """
        try:
            SimpleEditor = self._get_toolkit_editor('SimpleEditor')
        except:
            SimpleEditor = toolkit_object('editor_factory:SimpleEditor')
        return SimpleEditor


    def _get_custom_editor_class(self):
        """ Returns the editor class to use for "custom" style views.
        The default implementation tries to import the CustomEditor class in the
        editor file in the backend package, and if such a class is not to found
        it returns simple_editor_class.

        """
        try:
            CustomEditor = self._get_toolkit_editor('CustomEditor')
        except:
            CustomEditor = self.simple_editor_class
        return CustomEditor


    def _get_text_editor_class(self):
        """ Returns the editor class to use for "text" style views.
        The default implementation tries to import the TextEditor class in the
        editor file in the backend package, and if such a class is not found
        it returns the TextEditor class declared in the editor_factory module in
        the backend package.

        """
        try:
            TextEditor = self._get_toolkit_editor('TextEditor')
        except:
            TextEditor = toolkit_object('editor_factory:TextEditor')
        return TextEditor


    def _get_readonly_editor_class(self):
        """ Returns the editor class to use for "readonly" style views.
        The default implementation tries to import the ReadonlyEditor class in
        the editor file in the backend package, and if such a class is not found
        it returns the ReadonlyEditor class declared in the editor_factory
        module in the backend package.

        """
        try:
            ReadonlyEditor = self._get_toolkit_editor('ReadonlyEditor')
        except:
            ReadonlyEditor = toolkit_object('editor_factory:ReadonlyEditor')
        return ReadonlyEditor


#-------------------------------------------------------------------------------
#  'EditorWithListFactory' abstract base class:
#-------------------------------------------------------------------------------

class EditorWithListFactory ( EditorFactory ):
    """ Base class for factories of editors for objects that contain lists.
    """

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Values to enumerate (can be a list, tuple, dict, or a CTrait or
    # TraitHandler that is "mapped"):
    values = Any

    # Extended name of the trait on **object** containing the enumeration data:
    object = Str( 'object' )

    # Name of the trait on 'object' containing the enumeration data
    name = Str

    # Fired when the **values** trait has been updated:
    values_modified = Event

    #---------------------------------------------------------------------------
    #  Recomputes the mappings whenever the 'values' trait is changed:
    #---------------------------------------------------------------------------

    def _values_changed ( self ):
        """ Recomputes the mappings whenever the **values** trait is changed.
        """
        self._names, self._mapping, self._inverse_mapping = \
            enum_values_changed( self.values )

        self.values_modified = True

## EOF ########################################################################