enthought / traitsui
1
# ------------------------------------------------------------------------------
2
#
3
#  Copyright (c) 2005, Enthought, Inc.
4
#  All rights reserved.
5
#
6
#  This software is provided without warranty under the terms of the BSD
7
#  license included in LICENSE.txt and may be redistributed only
8
#  under the conditions described in the aforementioned license.  The license
9
#  is also available online at http://www.enthought.com/licenses/BSD.txt
10
#
11
#  Thanks for using Enthought open source!
12
#
13
#  Author: David C. Morrill
14
#  Date:   10/18/2004
15
#
16
# ------------------------------------------------------------------------------
17

18 4
""" Defines the abstract ViewElement class that all trait view template items
19
    (i.e., View, Group, Item, Include) derive from.
20
"""
21

22 4
import re
23

24 4
from traits.api import HasPrivateTraits, Instance, Bool
25

26 4
from .ui_traits import (
27
    AnObject,
28
    DockStyle,
29
    EditorStyle,
30
    ExportType,
31
    HelpId,
32
    Image,
33
)
34

35
# Is the AbstractViewElement ABC available in traits.api?
36

37 4
try:
38 4
    from traits.api import AbstractViewElement
39 0
except ImportError:
40 0
    AbstractViewElement = None
41

42

43 4
label_pat = re.compile(r"^(.*)\[(.*)\](.*)$", re.MULTILINE | re.DOTALL)
44 4
label_pat2 = re.compile(r"^(.*){(.*)}(.*)$", re.MULTILINE | re.DOTALL)
45

46
# -------------------------------------------------------------------------
47
#  'ViewElement' class (abstract):
48
# -------------------------------------------------------------------------
49

50

51 4
class ViewElement(HasPrivateTraits):
52
    """ An element of a view.
53
    """
54

55 4
    def replace_include(self, view_elements):
56
        """ Searches the current object's **content** attribute for objects that
57
        have an **id** attribute, and replaces each one with an Include object
58
        with the same **id** value, and puts the replaced object into the
59
        specified ViewElements object.
60

61
        Parameters
62
        ----------
63
        view_elements : ViewElements object
64
            Object containing Group, Item, and Include objects
65
        """
66 4
        pass  # Normally overridden in a subclass
67

68 4
    def is_includable(self):
69
        """ Returns whether the object is replacable by an Include object.
70
        """
71 4
        return False  # Normally overridden in a subclass
72

73

74 4
class DefaultViewElement(ViewElement):
75
    """ A view element that can be used as a default value for traits whose
76
        value is a view element.
77
    """
78

79
    # -------------------------------------------------------------------------
80
    #  Trait definitions:
81
    # -------------------------------------------------------------------------
82

83
    #: The default context object to edit:
84 4
    object = AnObject
85

86
    #: The default editor style to use:
87 4
    style = EditorStyle
88

89
    #: The default dock style to use:
90 4
    dock = DockStyle
91

92
    #: The default notebook tab image to use:
93 4
    image = Image
94

95
    #: The category of elements dragged out of the view:
96 4
    export = ExportType
97

98
    #: Should labels be added to items in a group?
99 4
    show_labels = Bool(True)
100

101

102
# -------------------------------------------------------------------------
103
#  Trait definitions:
104
# -------------------------------------------------------------------------
105

106
# The container trait used by ViewSubElements:
107 4
Container = Instance(ViewElement, factory=DefaultViewElement)
108

109
# -------------------------------------------------------------------------
110
#  'ViewSubElement' class (abstract):
111
# -------------------------------------------------------------------------
112

113

114 4
class ViewSubElement(ViewElement):
115
    """ Abstract class representing elements that can be contained in a view.
116
    """
117

118
    # -------------------------------------------------------------------------
119
    #  Trait definitions:
120
    # -------------------------------------------------------------------------
121

122
    #: The object this ViewSubElement is contained in; must be a ViewElement.
123 4
    container = Container
124

125
    #: External help context identifier:
126 4
    help_id = HelpId
127

128 4
    def _split(self, name, value, char, finder, assign, result):
129
        """ Splits a string at a specified character.
130
        """
131 4
        col = finder(value, char)
132 4
        if col < 0:
133 4
            return value
134

135 4
        items = (value[:col].strip(), value[col + 1:].strip())
136 4
        if items[assign] != "":
137 4
            setattr(self, name, items[assign])
138

139 4
        return items[result]
140

141 4
    def _option(self, string, option, name, value):
142
        """ Sets a object trait if a specified option string is found.
143
        """
144 4
        col = string.find(option)
145 4
        if col >= 0:
146 4
            string = string[:col] + string[col + len(option):]
147 4
            setattr(self, name, value)
148

149 4
        return string
150

151 4
    def _parse_style(self, value):
152
        """ Parses any of the one-character forms of the **style** trait.
153
        """
154 4
        value = self._option(value, "$", "style", "simple")
155 4
        value = self._option(value, "@", "style", "custom")
156 4
        value = self._option(value, "*", "style", "text")
157 4
        value = self._option(value, "~", "style", "readonly")
158 4
        value = self._split("style", value, ";", str.rfind, 1, 0)
159

160 4
        return value
161

162 4
    def _parse_label(self, value):
163
        """ Parses a '[label]' value from the string definition.
164
        """
165 4
        match = label_pat.match(value)
166 4
        if match is not None:
167 4
            self._parsed_label()
168
        else:
169 4
            match = label_pat2.match(value)
170

171 4
        empty = False
172 4
        if match is not None:
173 4
            self.label = match.group(2).strip()
174 4
            empty = self.label == ""
175 4
            value = match.group(1) + match.group(3)
176

177 4
        return (value, empty)
178

179 4
    def _parsed_label(self):
180
        """ Handles a label being found in the string definition.
181
        """
182 0
        pass
183

184 4
    def _repr_value(self, value, prefix="", suffix="", ignore=""):
185
        """ Returns a "pretty print" version of a specified Item trait value.
186
        """
187 4
        if value == ignore:
188 0
            return ""
189

190 0
        return "%s%s%s" % (prefix, value, suffix)
191

192 4
    def _repr_options(self, *names):
193
        """ Returns a 'pretty print' version of a list of traits.
194
        """
195 4
        result = []
196 4
        for name in names:
197 4
            value = getattr(self, name)
198 4
            if value != self.trait(name).default_value_for(self, name):
199 4
                result.append((name, repr(value)))
200

201 4
        if len(result) > 0:
202 4
            n = max([len(name) for name, value in result])
203 4
            return ",\n".join(
204
                ["%s = %s" % (name.ljust(n), value) for name, value in result]
205
            )
206

207 0
        return None
208

209 4
    def _indent(self, string, indent="    "):
210
        """ Indents each line in a specified string by 4 spaces.
211
        """
212 4
        return "\n".join([indent + s for s in string.split("\n")])
213

214

215
# Register ViewElement as implementing AbstractViewElement
216
# TODO: eventually have ViewElement inherit directly
217 4
if AbstractViewElement is not None:
218 4
    AbstractViewElement.register(ViewElement)

Read our documentation on viewing source code .

Loading