console.py 14.5 KB
Newer Older
1 2
# -*- coding: utf-8 -*-

Steve Frécinaux's avatar
Steve Frécinaux committed
3 4 5 6 7 8 9 10
# pythonconsole.py -- Console widget
#
# Copyright (C) 2006 - Steve Frécinaux
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
11
#
Steve Frécinaux's avatar
Steve Frécinaux committed
12 13 14 15 16 17
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
18
# along with this program; if not, see <http://www.gnu.org/licenses/>.
Steve Frécinaux's avatar
Steve Frécinaux committed
19 20 21 22 23 24 25 26 27 28 29 30

# Parts from "Interactive Python-GTK Console" (stolen from epiphany's console.py)
#     Copyright (C), 1998 James Henstridge <james@daa.com.au>
#     Copyright (C), 2005 Adam Hooper <adamh@densi.com>
# Bits from gedit Python Console Plugin
#     Copyrignt (C), 2005 Raphaël Slinckx

import string
import sys
import re
import traceback

31
from gi.repository import GLib, Gio, Gtk, Gdk, Pango
32

Steve Frécinaux's avatar
Steve Frécinaux committed
33 34
__all__ = ('PythonConsole', 'OutFile')

35
class PythonConsole(Gtk.ScrolledWindow):
36 37 38 39 40

    __gsignals__ = {
        'grab-focus' : 'override',
    }

41 42
    DEFAULT_FONT = "Monospace 10"

43
    CONSOLE_KEY_BASE = 'org.gnome.gedit.plugins.pythonconsole'
44
    SETTINGS_INTERFACE_DIR = "org.gnome.desktop.interface"
45 46 47 48
    SETTINGS_PROFILE_DIR = "org.gnome.GnomeTerminal.profiles.Default"

    CONSOLE_KEY_COMMAND_COLOR = 'command-color'
    CONSOLE_KEY_ERROR_COLOR = 'error-color'
49

50
    def __init__(self, namespace = {}):
51 52 53 54
        Gtk.ScrolledWindow.__init__(self)

        self._settings = Gio.Settings.new(self.CONSOLE_KEY_BASE)
        self._settings.connect("changed", self.on_color_settings_changed)
55

56 57
        self._interface_settings = Gio.Settings.new(self.SETTINGS_INTERFACE_DIR)
        self._interface_settings.connect("changed", self.on_settings_changed)
58

59
        self._profile_settings = self.get_profile_settings()
60
        self._profile_settings.connect("changed", self.on_settings_changed)
61

62
        self.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
63
        self.set_shadow_type(Gtk.ShadowType.NONE)
64
        self.view = Gtk.TextView()
65
        self.reconfigure()
66
        self.view.set_editable(True)
67
        self.view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
68 69 70
        self.add(self.view)
        self.view.show()

71 72 73 74
        buf = self.view.get_buffer()
        self.normal = buf.create_tag("normal")
        self.error  = buf.create_tag("error")
        self.command = buf.create_tag("command")
75

76 77
        # Load the default settings
        self.on_color_settings_changed(self._settings, None)
78 79 80 81 82 83 84

        self.__spaces_pattern = re.compile(r'^\s+')
        self.namespace = namespace

        self.block_command = False

        # Init first line
85 86 87
        buf.create_mark("input-line", buf.get_end_iter(), True)
        buf.insert(buf.get_end_iter(), ">>> ")
        buf.create_mark("input", buf.get_end_iter(), True)
88 89 90 91 92 93 94 95 96 97 98 99 100

        # Init history
        self.history = ['']
        self.history_pos = 0
        self.current_command = ''
        self.namespace['__history__'] = self.history

        # Set up hooks for standard output.
        self.stdout = OutFile(self, sys.stdout.fileno(), self.normal)
        self.stderr = OutFile(self, sys.stderr.fileno(), self.error)

        # Signals
        self.view.connect("key-press-event", self.__key_press_event_cb)
101
        buf.connect("mark-set", self.__mark_set_cb)
102

103 104 105 106
    def get_profile_settings(self):
        #FIXME return either the gnome-terminal settings or the gedit one
        return Gio.Settings.new(self.CONSOLE_KEY_BASE)

107 108 109
    def do_grab_focus(self):
        self.view.grab_focus()

110 111 112
    def reconfigure(self):
        # Font
        font_desc = None
113
        system_font = self._interface_settings.get_string("monospace-font-name")
114

115
        if self._profile_settings.get_boolean("use-system-font"):
116 117
            font_name = system_font
        else:
118
            font_name = self._profile_settings.get_string("font")
119 120

        try:
121
            font_desc = Pango.FontDescription(font_name)
122 123 124 125
        except:
            if font_name != self.DEFAULT_FONT:
                if font_name != system_font:
                    try:
126
                        font_desc = Pango.FontDescription(system_font)
127 128 129 130 131
                    except:
                        pass

                if font_desc == None:
                    try:
132
                        font_desc = Pango.FontDescription(self.DEFAULT_FONT)
133 134 135 136 137 138
                    except:
                        pass

        if font_desc != None:
            self.view.modify_font(font_desc)

139
    def on_settings_changed(self, settings, key):
140 141
        self.reconfigure()

142 143 144
    def on_color_settings_changed(self, settings, key):
        self.error.set_property("foreground", settings.get_string(self.CONSOLE_KEY_ERROR_COLOR))
        self.command.set_property("foreground", settings.get_string(self.CONSOLE_KEY_COMMAND_COLOR))
145 146 147 148 149

    def stop(self):
        self.namespace = None

    def __key_press_event_cb(self, view, event):
150
        modifier_mask = Gtk.accelerator_get_default_mod_mask()
151
        event_state = event.state & modifier_mask
152

153
        if event.keyval == Gdk.KEY_D and event_state == Gdk.ModifierType.CONTROL_MASK:
154 155
            self.destroy()

156
        elif event.keyval == Gdk.KEY_Return and event_state == Gdk.ModifierType.CONTROL_MASK:
157
            # Get the command
158 159
            buf = view.get_buffer()
            inp_mark = buf.get_mark("input")
160
            inp = buf.get_iter_at_mark(inp_mark)
161
            cur = buf.get_end_iter()
162
            line = buf.get_text(inp, cur, False)
163 164 165 166
            self.current_command = self.current_command + line + "\n"
            self.history_add(line)

            # Prepare the new line
167 168 169 170
            cur = buf.get_end_iter()
            buf.insert(cur, "\n... ")
            cur = buf.get_end_iter()
            buf.move_mark(inp_mark, cur)
171 172 173 174

            # Keep indentation of precendent line
            spaces = re.match(self.__spaces_pattern, line)
            if spaces is not None:
175 176
                buf.insert(cur, line[spaces.start() : spaces.end()])
                cur = buf.get_end_iter()
177

178
            buf.place_cursor(cur)
179
            GLib.idle_add(self.scroll_to_end)
180 181
            return True

182
        elif event.keyval == Gdk.KEY_Return:
183
            # Get the marks
184 185 186
            buf = view.get_buffer()
            lin_mark = buf.get_mark("input-line")
            inp_mark = buf.get_mark("input")
187 188

            # Get the command line
189 190 191
            inp = buf.get_iter_at_mark(inp_mark)
            cur = buf.get_end_iter()
            line = buf.get_text(inp, cur, False)
192 193 194 195
            self.current_command = self.current_command + line + "\n"
            self.history_add(line)

            # Make the line blue
196 197 198
            lin = buf.get_iter_at_mark(lin_mark)
            buf.apply_tag(self.command, lin, cur)
            buf.insert(cur, "\n")
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

            cur_strip = self.current_command.rstrip()

            if cur_strip.endswith(":") \
            or (self.current_command[-2:] != "\n\n" and self.block_command):
                # Unfinished block command
                self.block_command = True
                com_mark = "... "
            elif cur_strip.endswith("\\"):
                com_mark = "... "
            else:
                # Eval the command
                self.__run(self.current_command)
                self.current_command = ''
                self.block_command = False
                com_mark = ">>> "

            # Prepare the new line
217 218 219 220 221 222
            cur = buf.get_end_iter()
            buf.move_mark(lin_mark, cur)
            buf.insert(cur, com_mark)
            cur = buf.get_end_iter()
            buf.move_mark(inp_mark, cur)
            buf.place_cursor(cur)
223
            GLib.idle_add(self.scroll_to_end)
224 225
            return True

226
        elif event.keyval == Gdk.KEY_KP_Down or event.keyval == Gdk.KEY_Down:
227
            # Next entry from history
228
            view.stop_emission_by_name("key_press_event")
229
            self.history_down()
230
            GLib.idle_add(self.scroll_to_end)
231 232
            return True

233
        elif event.keyval == Gdk.KEY_KP_Up or event.keyval == Gdk.KEY_Up:
234
            # Previous entry from history
235
            view.stop_emission_by_name("key_press_event")
236
            self.history_up()
237
            GLib.idle_add(self.scroll_to_end)
238 239
            return True

240 241
        elif event.keyval == Gdk.KEY_KP_Left or event.keyval == Gdk.KEY_Left or \
             event.keyval == Gdk.KEY_BackSpace:
242 243 244
            buf = view.get_buffer()
            inp = buf.get_iter_at_mark(buf.get_mark("input"))
            cur = buf.get_iter_at_mark(buf.get_insert())
245 246
            if inp.compare(cur) == 0:
                if not event_state:
247
                    buf.place_cursor(inp)
248 249 250
                return True
            return False

251 252 253
        # For the console we enable smart/home end behavior incoditionally
        # since it is useful when editing python

254
        elif (event.keyval == Gdk.KEY_KP_Home or event.keyval == Gdk.KEY_Home) and \
255
             event_state == event_state & (Gdk.ModifierType.SHIFT_MASK|Gdk.ModifierType.CONTROL_MASK):
256
            # Go to the begin of the command instead of the begin of the line
257 258 259
            buf = view.get_buffer()
            it = buf.get_iter_at_mark(buf.get_mark("input"))
            ins = buf.get_iter_at_mark(buf.get_insert())
260

261 262
            while it.get_char().isspace():
                it.forward_char()
263

264 265
            if it.equal(ins):
                it = buf.get_iter_at_mark(buf.get_mark("input"))
266

267 268
            if event_state & Gdk.ModifierType.SHIFT_MASK:
                buf.move_mark_by_name("insert", it)
269
            else:
270
                buf.place_cursor(it)
271 272
            return True

273
        elif (event.keyval == Gdk.KEY_KP_End or event.keyval == Gdk.KEY_End) and \
274
             event_state == event_state & (Gdk.ModifierType.SHIFT_MASK|Gdk.ModifierType.CONTROL_MASK):
275

276 277 278
            buf = view.get_buffer()
            it = buf.get_end_iter()
            ins = buf.get_iter_at_mark(buf.get_insert())
279

280
            it.backward_char()
281

282 283
            while it.get_char().isspace():
                it.backward_char()
284

285
            it.forward_char()
286

287 288
            if it.equal(ins):
                it = buf.get_end_iter()
289

290 291
            if event_state & Gdk.ModifierType.SHIFT_MASK:
                buf.move_mark_by_name("insert", it)
292
            else:
293
                buf.place_cursor(it)
294 295
            return True

296 297 298
    def __mark_set_cb(self, buf, it, name):
        input = buf.get_iter_at_mark(buf.get_mark("input"))
        pos   = buf.get_iter_at_mark(buf.get_insert())
299 300 301
        self.view.set_editable(pos.compare(input) != -1)

    def get_command_line(self):
302 303 304
        buf = self.view.get_buffer()
        inp = buf.get_iter_at_mark(buf.get_mark("input"))
        cur = buf.get_end_iter()
305
        return buf.get_text(inp, cur, False)
306 307

    def set_command_line(self, command):
308 309 310 311 312 313
        buf = self.view.get_buffer()
        mark = buf.get_mark("input")
        inp = buf.get_iter_at_mark(mark)
        cur = buf.get_end_iter()
        buf.delete(inp, cur)
        buf.insert(inp, command)
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        self.view.grab_focus()

    def history_add(self, line):
        if line.strip() != '':
            self.history_pos = len(self.history)
            self.history[self.history_pos - 1] = line
            self.history.append('')

    def history_up(self):
        if self.history_pos > 0:
            self.history[self.history_pos] = self.get_command_line()
            self.history_pos = self.history_pos - 1
            self.set_command_line(self.history[self.history_pos])

    def history_down(self):
        if self.history_pos < len(self.history) - 1:
            self.history[self.history_pos] = self.get_command_line()
            self.history_pos = self.history_pos + 1
            self.set_command_line(self.history[self.history_pos])

    def scroll_to_end(self):
335 336
        i = self.view.get_buffer().get_end_iter()
        self.view.scroll_to_iter(i, 0.0, False, 0.5, 0.5)
337 338 339
        return False

    def write(self, text, tag = None):
340
        buf = self.view.get_buffer()
341 342 343 344 345
        if tag is None:
            buf.insert(buf.get_end_iter(), text)
        else:
            buf.insert_with_tags(buf.get_end_iter(), text, tag)

346
        GLib.idle_add(self.scroll_to_end)
347 348

    def eval(self, command, display_command = False):
349 350 351 352
        buf = self.view.get_buffer()
        lin = buf.get_mark("input-line")
        buf.delete(buf.get_iter_at_mark(lin),
                   buf.get_end_iter())
353 354 355 356 357 358 359 360 361 362 363

        if isinstance(command, list) or isinstance(command, tuple):
            for c in command:
                if display_command:
                    self.write(">>> " + c + "\n", self.command)
                self.__run(c)
        else:
            if display_command:
                self.write(">>> " + c + "\n", self.command)
            self.__run(command)

364 365 366 367 368 369
        cur = buf.get_end_iter()
        buf.move_mark_by_name("input-line", cur)
        buf.insert(cur, ">>> ")
        cur = buf.get_end_iter()
        buf.move_mark_by_name("input", cur)
        self.view.scroll_to_iter(buf.get_end_iter(), 0.0, False, 0.5, 0.5)
370 371 372 373 374 375 376 377 378

    def __run(self, command):
        sys.stdout, self.stdout = self.stdout, sys.stdout
        sys.stderr, self.stderr = self.stderr, sys.stderr

        try:
            try:
                r = eval(command, self.namespace, self.namespace)
                if r is not None:
379
                    print(r)
380
            except SyntaxError:
381
                exec(command, self.namespace)
382 383 384 385 386 387 388 389 390 391 392 393 394
        except:
            if hasattr(sys, 'last_type') and sys.last_type == SystemExit:
                self.destroy()
            else:
                traceback.print_exc()

        sys.stdout, self.stdout = self.stdout, sys.stdout
        sys.stderr, self.stderr = self.stderr, sys.stderr

    def destroy(self):
        pass
        #gtk.ScrolledWindow.destroy(self)

Steve Frécinaux's avatar
Steve Frécinaux committed
395
class OutFile:
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    """A fake output file object. It sends output to a TK test widget,
    and if asked for a file number, returns one set on instance creation"""
    def __init__(self, console, fn, tag):
        self.fn = fn
        self.console = console
        self.tag = tag
    def close(self):         pass
    def flush(self):         pass
    def fileno(self):        return self.fn
    def isatty(self):        return 0
    def read(self, a):       return ''
    def readline(self):      return ''
    def readlines(self):     return []
    def write(self, s):      self.console.write(s, self.tag)
    def writelines(self, l): self.console.write(l, self.tag)
411 412
    def seek(self, a):       raise IOError((29, 'Illegal seek'))
    def tell(self):          raise IOError((29, 'Illegal seek'))
413 414 415
    truncate = tell

# ex:et:ts=4: