File: live_editor_model.py

package info (click to toggle)
python-enaml 0.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,284 kB
  • sloc: python: 31,443; cpp: 4,499; makefile: 140; javascript: 68; lisp: 53; sh: 20
file content (281 lines) | stat: -rw-r--r-- 9,462 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
#------------------------------------------------------------------------------
# Copyright (c) 2013-2025, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
import linecache
import traceback
from types import ModuleType

from atom.api import Atom, Str, Typed, observe

import enaml
from enaml.core.object import Object
from enaml.core.enaml_compiler import EnamlCompiler
from enaml.core.parser import parse
from enaml.widgets.widget import Widget

try:
    import jedi
    COMPLETION_AVAILABLE = True
except ImportError:
    COMPLETION_AVAILABLE = False


ENAML_KEYWORDS = ['enamldef', 'attr', 'alias', 'func', 'template', 'class',
                  'with', 'else', 'while']


def _fake_linecache(text, filename):
    """ Inject text into the linecache for traceback purposes.

    Parameters
    ----------
    text : str
        The text of the file.

    filename : str
        The name of the file.

    """
    size = len(text)
    mtime = int(1343290295)
    lines = text.splitlines()
    lines = [l + '\n' for l in lines]
    linecache.cache[filename] = size, mtime, lines, filename


class LiveEditorModel(Atom):
    """ A model which works in concert with the live editor panels.

    This model manages the compiling and instantiation of the model
    and view objects defined by the user.

    The model has six inputs:

        'model_text'
            The full text of the Python module which defines the model.

        'view_text'
            The full text of the Enaml module which defines the view.

        'model_item'
            The name of the target model class in the model module.

        'view_item'
            The name of the target enamldef in the view module.

        'model_filename'
            An optional filename to associate with the model module.

        'view_filename'
            An optional filename to associate with the view module.

    The model has three outputs:

        'compiled_model'
            The instance of the user defined model, or None if no model
            could be created.

        'compiled_view'
            The instance of the user defined view, or None if no view
            could be created.

        'traceback'
            A string holding the traceback for any compilation and
            instantiation errors.

    If the 'compiled_view' object has a 'model' attribute, then the
    'compiled_model' object will be assigned to that attribute.

    """
    #: The current live model object bound to the main view.
    compiled_model = Typed(Atom)

    #: The current live view object to include in the main view.
    compiled_view = Typed(Object)

    #: The Python module input text for the model module.
    model_text = Str()

    #: The Enaml module input text for the view module.
    view_text = Str()

    #: The string name of the Atom class to use as the model.
    model_item = Str()

    #: The string name of the enamldef to use as the view.
    view_item = Str()

    #: An optional filename to use when compiling the python code.
    model_filename = Str('__live_model__.py')

    #: An optional filename to use when compiling the enaml code.
    view_filename = Str('__live_view__.enaml')

    #: A string which holds the most recent traceback.
    traceback = Str()

    #: The module created from the model text.
    _model_module = Typed(ModuleType)

    #: The module created from the view text.
    _view_module = Typed(ModuleType)

    #--------------------------------------------------------------------------
    # Post Validators
    #--------------------------------------------------------------------------
    def _post_validate_model_text(self, old, new):
        """ Post validate the model text.

        This validator replaces CRLF with LF characters.

        """
        return new.replace('\r\n', '\n').replace('\r', '\n')

    def _post_validate_view_text(self, old, new):
        """ Post validate the view text.

        This validator replaces CRLF with LF characters.

        """
        return new.replace('\r\n', '\n').replace('\r', '\n')

    #--------------------------------------------------------------------------
    # Observers
    #--------------------------------------------------------------------------
    @observe('model_text', 'model_item')
    def _refresh_model_trigger(self, change):
        """ An observer which triggers a compiled model refresh.

        """
        if change['type'] == 'update':
            self.refresh_model()

    @observe('view_text', 'view_item')
    def _refresh_view_trigger(self, change):
        """ An observer which triggers a compiled view refresh.

        """
        if change['type'] == 'update':
            self.refresh_view()

    #--------------------------------------------------------------------------
    # Public API
    #--------------------------------------------------------------------------
    def refresh_model(self):
        """ Refresh the compiled model object.

        This method will (re)compile the model for the given model text
        and update the 'compiled_model' attribute. If a compiled view is
        available and has a member named 'model', the model will be
        applied to the view.

        """
        text = self.model_text
        filename = self.model_filename
        _fake_linecache(text, filename)
        try:
            if not text:
                self.compiled_model = None
                self._model_module = None
            else:
                code = compile(text, filename, 'exec')
                module = ModuleType(filename.rsplit('.', 1)[0])
                module.__file__ = filename
                namespace = module.__dict__
                exec(code, namespace)
                model = namespace.get(self.model_item, lambda: None)()
                self.compiled_model = model
                self._model_module = module
            self.relink_view()
        except Exception:
            self.traceback = traceback.format_exc()
        else:
            self.traceback = ''

    def refresh_view(self):
        """ Refresh the compiled view object.

        This method will (re)compile the view for the given view text
        and update the 'compiled_view' attribute. If a compiled model
        is available and the view has a member named 'model', the model
        will be applied to the view.

        """
        text = self.view_text
        filename = self.view_filename
        _fake_linecache(text, filename)
        try:
            if not text:
                self.compiled_view = None
                self._view_module = None
            else:
                ast = parse(text, filename=filename)
                code = EnamlCompiler.compile(ast, filename)
                module = ModuleType('__main__')
                module.__file__ = filename
                namespace = module.__dict__
                with enaml.imports():
                    exec(code, namespace)
                view = namespace.get(self.view_item, lambda: None)()
                if isinstance(view, Object) and 'model' in view.members():
                    view.model = self.compiled_model
                # trap any initialization errors and roll back the view
                old = self.compiled_view
                try:
                    self.compiled_view = view
                except Exception:
                    self.compiled_view = old
                    if isinstance(old, Widget):
                        old.show()
                    raise
                self._view_module = module
                if old is not None and not old.is_destroyed:
                    old.destroy()
        except Exception:
            self.traceback = traceback.format_exc()
        else:
            self.traceback = ''

    def autocomplete(self, source, position):
        """ Obtain autocompletion suggestions for the source text using jedi .
        if available.

        """
        if not COMPLETION_AVAILABLE or not source:
            return ENAML_KEYWORDS
        try:
            # Use jedi to get suggestions
            line, column = position
            script = jedi.Script(source, line+1, column)

            # Get suggestions
            results = []
            for c in script.completions():
                results.append(c.name)

                # Try to get a signature if the docstring matches
                # something Scintilla will use (ex "func(..." or "Class(...")
                # Scintilla ignores docstrings without a comma in the args
                if c.type in ['function', 'class', 'instance']:
                    docstring = c.docstring()
                    if docstring.startswith("{}(".format(c.name)):
                        results.append(docstring)
                        continue

            return results + ENAML_KEYWORDS
        except Exception:
            # Autocompletion may fail for random reasons so catch all errors
            # as we don't want the editor to quit because of this
            return ENAML_KEYWORDS

    def relink_view(self):
        """ Relink the compiled view with the compiled model.

        """
        view = self.compiled_view
        if view is not None and 'model' in view.members():
            view.model = self.compiled_model