File: text_editor.py

package info (click to toggle)
python-envisage 7.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,880 kB
  • sloc: python: 8,696; makefile: 76; sh: 5
file content (226 lines) | stat: -rw-r--r-- 6,678 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
# (C) Copyright 2007-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in 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!
""" A text editor. """


# Standard library imports.
from os.path import basename

from pyface.api import CANCEL, FileDialog

# Enthought library imports.
from pyface.workbench.api import TraitsUIEditor
from traits.api import Code, Instance, observe
from traitsui.api import CodeEditor, Group, Item, View
from traitsui.key_bindings import KeyBinding, KeyBindings
from traitsui.menu import NoButtons

# Local imports.
from .text_editor_handler import TextEditorHandler


def _id_generator():
    """A generator that returns the next number for untitled files."""

    i = 1
    while True:
        yield (i)
        i += 1


_id_generator = _id_generator()


class TextEditor(TraitsUIEditor):
    """A text editor."""

    #### 'TextEditor' interface ###############################################

    # The key bindings used by the editor.
    key_bindings = Instance(KeyBindings)

    # The text being edited.
    text = Code

    ###########################################################################
    # 'IEditor' interface.
    ###########################################################################

    def save(self):
        """Saves the text to disk."""

        # If the file has not yet been saved then prompt for the file name.
        if len(self.obj.path) == 0:
            self.save_as()

        else:
            with open(self.obj.path, "w", encoding="utf-8") as f:
                f.write(self.text)

            # We have just saved the file so we ain't dirty no more!
            self.dirty = False

    def save_as(self):
        """Saves the text to disk after prompting for the file name."""

        dialog = FileDialog(
            parent=self.window.control,
            action="save as",
            default_filename=self.name,
            wildcard=FileDialog.WILDCARD_PY,
        )
        if dialog.open() != CANCEL:
            # Update the editor.
            self.id = dialog.path
            self.name = basename(dialog.path)

            # Update the resource.
            self.obj.path = dialog.path

            # Save it!
            self.save()

    ###########################################################################
    # 'TraitsUIEditor' interface.
    ###########################################################################

    def create_ui(self, parent):
        """Creates the traits UI that represents the editor."""

        ui = self.edit_traits(
            parent=parent, view=self._create_traits_ui_view(), kind="subpanel"
        )

        return ui

    ###########################################################################
    # 'TextEditor' interface.
    ###########################################################################

    def run(self):
        """Runs the file as Python."""

        # The file must be saved first!
        self.save()

        # Execute the code.
        if len(self.obj.path) > 0:
            view = self.window.get_view_by_id(
                "envisage.plugins.python_shell_view"
            )

            if view is not None:
                view.execute_command(
                    'exec(open(r"%s").read())' % self.obj.path, hidden=False
                )

    def select_line(self, lineno):
        """Selects the specified line."""

        self.ui.info.text.selected_line = lineno

    ###########################################################################
    # Private interface.
    ###########################################################################

    #### Trait initializers ###################################################

    def _key_bindings_default(self):
        """Trait initializer."""

        key_bindings = KeyBindings(
            KeyBinding(
                binding1="Ctrl-s",
                description="Save the file",
                method_name="save",
            ),
            KeyBinding(
                binding1="Ctrl-r",
                description="Run the file",
                method_name="run",
            ),
        )

        return key_bindings

    #### Trait change handlers ################################################

    @observe("obj")
    def _handle_update_to_object(self, event):
        """Static trait change handler."""
        new = event.new
        # The path will be the empty string if we are editing a file that has
        # not yet been saved.
        if len(new.path) == 0:
            self.id = self._get_unique_id()
            self.name = self.id

        else:
            self.id = new.path
            self.name = basename(new.path)

            with open(new.path, "r", encoding="utf-8") as f:
                self.text = f.read()

    @observe("text")
    def _update_dirty(self, event):
        """Static trait change handler."""

        if self.traits_inited():
            self.dirty = True

    @observe("dirty")
    def _update_name(self, event):
        """Static trait change handler."""
        dirty = event.new
        if len(self.obj.path) > 0:
            if dirty:
                self.name = basename(self.obj.path) + "*"

            else:
                self.name = basename(self.obj.path)

    #### Methods ##############################################################

    def _create_traits_ui_view(self):
        """Create the traits UI view used by the editor.

        fixme: We create the view dynamically to allow the key bindings to be
        created dynamically (we don't use this just yet, but obviously plugins
        need to be able to contribute new bindings).

        """

        view = View(
            Group(
                Item(
                    "text", editor=CodeEditor(key_bindings=self.key_bindings)
                ),
                show_labels=False,
            ),
            id="envisage.editor.text_editor",
            handler=TextEditorHandler(),
            kind="live",
            resizable=True,
            width=1.0,
            height=1.0,
            buttons=NoButtons,
        )

        return view

    def _get_unique_id(self, prefix="Untitled "):
        """Return a unique id for a new file."""

        id = prefix + str(next(_id_generator))
        while self.window.get_editor_by_id(id) is not None:
            id = prefix + str(next(_id_generator))

        return id