File: shell_editor.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 (244 lines) | stat: -rw-r--r-- 9,469 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
#-------------------------------------------------------------------------------
#
#  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:   09/27/2005
#
#-------------------------------------------------------------------------------

""" Editor that displays an interactive Python shell.
"""

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

from __future__ import absolute_import

from traits.api import Bool, Str, Event, Property

from ..editor import Editor

from ..basic_editor_factory import BasicEditorFactory

from ..toolkit import toolkit_object


#-------------------------------------------------------------------------------
#  'ShellEditor' class:
#-------------------------------------------------------------------------------

class _ShellEditor ( Editor ):
    """ Base class for an editor that displays an interactive Python shell.
    """

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

    # An event fired to execute a command in the shell.
    command_to_execute = Event()

    # An event fired whenver the user executes a command in the shell:
    command_executed = Event( Bool )

    # Is the shell editor is scrollable? This value overrides the default.
    scrollable = True

    #---------------------------------------------------------------------------
    #  Finishes initializing the editor by creating the underlying toolkit
    #  widget:
    #---------------------------------------------------------------------------

    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        # Moving the import here, since PythonShell is implemented in the
        # Pyface backend packages, and we want to delay loading this toolkit
        # specific class until this editor is actually used.
        from pyface.python_shell import PythonShell

        locals = None
        value  = self.value
        if self.factory.share and isinstance( value, dict ):
            locals = value
        self._shell  = shell = PythonShell( parent, locals = locals )
        self.control = shell.control
        if locals is None:
            object = self.object
            shell.bind( 'self', object )
            shell.on_trait_change( self.update_object, 'command_executed',
                                   dispatch = 'ui' )
            if not isinstance( value, dict ):
                object.on_trait_change( self.update_any, dispatch = 'ui' )
            else:
                self._base_locals = locals = {}
                for name in self._shell.interpreter().locals.keys():
                    locals[ name ] = None

        # Synchronize any editor events:
        self.sync_value( self.factory.command_to_execute,
                         'command_to_execute', 'from' )
        self.sync_value( self.factory.command_executed,
                         'command_executed', 'to' )

        self.set_tooltip()

    #---------------------------------------------------------------------------
    #  Handles the user entering input data in the edit control:
    #---------------------------------------------------------------------------

    def update_object ( self, event ):
        """ Handles the user entering input data in the edit control.
        """
        locals      = self._shell.interpreter().locals
        base_locals = self._base_locals
        if base_locals is None:
            object = self.object
            for name in object.trait_names():
                if name in locals:
                    try:
                        setattr( object, name, locals[ name ] )
                    except:
                        pass
        else:
            dic = self.value
            for name in locals.keys():
                if name not in base_locals:
                    try:
                        dic[ name ] = locals[ name ]
                    except:
                        pass

        self.command_executed = True

    #---------------------------------------------------------------------------
    #  Updates the editor when the object trait changes external to the editor:
    #---------------------------------------------------------------------------

    def update_editor ( self ):
        """ Updates the editor when the object trait changes externally to the
            editor.
        """
        if self.factory.share:
            value = self.value
            if isinstance( value, dict ):
                self._shell.interpreter().locals = value
        else:
            locals      = self._shell.interpreter().locals
            base_locals = self._base_locals
            if base_locals is None:
                object = self.object
                for name in object.trait_names():
                    locals[ name ] = getattr( object, name, None )
            else:
                dic = self.value
                for name, value in dic.items():
                    locals[ name ] = value

    #---------------------------------------------------------------------------
    #  Updates the editor when the object trait changes external to the editor:
    #---------------------------------------------------------------------------

    def update_any ( self, object, name, old, new ):
        """ Updates the editor when the object trait changes externally to the
            editor.
        """
        locals = self._shell.interpreter().locals
        if self._base_locals is None:
            locals[ name ] = new
        else:
            self.value[ name ] = new

    #---------------------------------------------------------------------------
    #  Disposes of the contents of an editor:
    #---------------------------------------------------------------------------

    def dispose ( self ):
        """ Disposes of the contents of an editor.
        """
        self._shell.on_trait_change( self.update_object, 'command_executed',
                                     remove = True )
        if self._base_locals is None:
            self.object.on_trait_change( self.update_any, remove = True )

        super( _ShellEditor, self ).dispose()

    #---------------------------------------------------------------------------
    #  Restores any saved user preference information associated with the
    #  editor:
    #---------------------------------------------------------------------------

    def restore_prefs ( self, prefs ):
        """ Restores any saved user preference information associated with the
            editor.
        """
        control = self._shell.control
        try:
            control.history      = prefs.get( 'history', [] )
            control.historyIndex = prefs.get( 'historyIndex', -1 )
        except:
            pass

    #---------------------------------------------------------------------------
    #  Returns any user preference information associated with the editor:
    #---------------------------------------------------------------------------

    def save_prefs ( self ):
        """ Returns any user preference information associated with the editor.
        """
        control = self._shell.control
        return { 'history':      control.history,
                 'historyIndex': control.historyIndex }

    #---------------------------------------------------------------------------
    #  Handles the 'command_to_execute' trait being fired:
    #---------------------------------------------------------------------------

    def _command_to_execute_fired ( self, command ):
        """ Handles the 'command_to_execute' trait being fired.
        """
        # Show the command. A 'hidden' command should be executed directly on
        # the namespace trait!
        self._shell.execute_command(command, hidden=False)

#-------------------------------------------------------------------------------
#  Create the editor factory object:
#-------------------------------------------------------------------------------

# Editor factory for shell editors.
class ToolkitEditorFactory ( BasicEditorFactory ):

    # The editor class to be instantiated.
    klass = Property

    # Should the shell interpreter use the object value's dictionary?
    share = Bool( False )

    # Extended trait name of the object event trait which triggers a command
    # execution in the shell when fired.
    command_to_execute = Str

    # Extended trait name of the object event trait which is fired when a
    # command is executed.
    command_executed = Str

    def _get_klass(self):
        """ Returns the toolkit-specific editor class to be used in the UI.
        """
        return toolkit_object('shell_editor:_ShellEditor')

# Define the ShellEditor
ShellEditor = ToolkitEditorFactory

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