ipython_view.py 16.2 KB
Newer Older
1 2
#!/usr/bin/python
'''
3
Provides IPython console widget.
4 5 6 7 8 9 10 11 12 13 14

@author: Eitan Isaacson
@organization: IBM Corporation
@copyright: Copyright (c) 2007 IBM Corporation
@license: BSD

All rights reserved. This program and the accompanying materials are made 
available under the terms of the BSD which accompanies this distribution, and 
is available at U{http://www.opensource.org/licenses/bsd-license.php}
'''

15
import gtk, gobject
16 17 18
import re
import sys
import os
19
import pango
20 21 22 23 24 25 26 27
from StringIO import StringIO

try:
  import IPython
except ImportError:
  IPython = None

class IterableIPShell:
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  '''
  Create an IPython instance. Does not start a blocking event loop,
  instead allow single iterations. This allows embedding in GTK+ 
  without blockage.

  @ivar IP: IPython instance.
  @type IP: IPython.iplib.InteractiveShell
  @ivar iter_more: Indicates if the line executed was a complete command,
  or we should wait for more.
  @type iter_more: integer
  @ivar history_level: The place in history where we currently are 
  when pressing up/down.
  @type history_level: integer
  @ivar complete_sep: Seperation delimeters for completion function.
  @type complete_sep: _sre.SRE_Pattern
  '''
44
  def __init__(self,argv=[],user_ns=None,user_global_ns=None, 
45
               cin=None, cout=None,cerr=None, input_func=None):
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    '''
    
    
    @param argv: Command line options for IPython
    @type argv: list
    @param user_ns: User namespace.
    @type user_ns: dictionary
    @param user_global_ns: User global namespace.
    @type user_global_ns: dictionary.
    @param cin: Console standard input.
    @type cin: IO stream
    @param cout: Console standard output.
    @type cout: IO stream 
    @param cerr: Console standard error.
    @type cerr: IO stream
    @param input_func: Replacement for builtin raw_input()
    @type input_func: function
    '''
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    if input_func:
      IPython.iplib.raw_input_original = input_func
    if cin:
      IPython.Shell.Term.cin = cin
    if cout:
      IPython.Shell.Term.cout = cout
    if cerr:
      IPython.Shell.Term.cerr = cerr

    # This is to get rid of the blockage that accurs during 
    # IPython.Shell.InteractiveShell.user_setup()
    IPython.iplib.raw_input = lambda x: None

    self.term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr)
    os.environ['TERM'] = 'dumb'
    excepthook = sys.excepthook 
80 81 82 83 84
    self.IP = IPython.Shell.make_IPython(
      argv,user_ns=user_ns,
      user_global_ns=user_global_ns,
      embedded=True,
      shell_class=IPython.Shell.InteractiveShell)
85 86 87 88 89 90 91
    self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd),
                                            header='IPython system call: ',
                                            verbose=self.IP.rc.system_verbose)
    sys.excepthook = excepthook
    self.iter_more = 0
    self.history_level = 0
    self.complete_sep =  re.compile('[\s\{\}\[\]\(\)]')
92 93
    self.updateNamespace({'exit':lambda:None})
    self.updateNamespace({'quit':lambda:None})
94 95

  def execute(self):
96 97 98
    '''
    Executes the current line provided by the shell object.
    '''
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
    self.history_level = 0
    orig_stdout = sys.stdout
    sys.stdout = IPython.Shell.Term.cout
    try:
      line = self.IP.raw_input(None, self.iter_more)
      if self.IP.autoindent:
        self.IP.readline_startup_hook(None)
    except KeyboardInterrupt:
      self.IP.write('\nKeyboardInterrupt\n')
      self.IP.resetbuffer()
      # keep cache in sync with the prompt counter:
      self.IP.outputcache.prompt_count -= 1
        
      if self.IP.autoindent:
        self.IP.indent_current_nsp = 0
      self.iter_more = 0
    except:
      self.IP.showtraceback()
    else:
      self.iter_more = self.IP.push(line)
      if (self.IP.SyntaxTB.last_syntax_error and
          self.IP.rc.autoedit_syntax):
        self.IP.edit_syntax_error()
    if self.iter_more:
      self.prompt = str(self.IP.outputcache.prompt2).strip()
      if self.IP.autoindent:
        self.IP.readline_startup_hook(self.IP.pre_readline)
    else:
      self.prompt = str(self.IP.outputcache.prompt1).strip()
    sys.stdout = orig_stdout

  def historyBack(self):
131 132 133 134 135 136
    '''
    Provides one history command back.
    
    @return: The command string.
    @rtype: string
    '''
137
    self.history_level -= 1
138 139
    if not self._getHistory():
      self.history_level +=1
140 141 142
    return self._getHistory()
  
  def historyForward(self):
143 144 145 146 147 148
    '''
    Provides one history command forward.
    
    @return: The command string.
    @rtype: string
    '''
149 150
    if self.history_level < 0:
      self.history_level += 1
151 152 153
    return self._getHistory()
  
  def _getHistory(self):
154 155 156 157 158 159
    '''
    Get's the command string of the current history level.
    
    @return: Historic command string.
    @rtype: string
    '''
160 161 162 163 164 165 166
    try:
      rv = self.IP.user_ns['In'][self.history_level].strip('\n')
    except IndexError:
      rv = ''
    return rv

  def updateNamespace(self, ns_dict):
167 168 169 170 171 172
    '''
    Add the current dictionary to the shell namespace.
    
    @param ns_dict: A dictionary of symbol-values.
    @type ns_dict: dictionary
    '''
173 174 175
    self.IP.user_ns.update(ns_dict)

  def complete(self, line):
176 177 178 179 180 181 182 183 184 185
    '''
    Returns an auto completed line and/or posibilities for completion.
    
    @param line: Given line so far.
    @type line: string
    
    @return: Line completed as for as possible, 
    and possible further completions.
    @rtype: tuple
    '''
186 187 188
    split_line = self.complete_sep.split(line)
    possibilities = self.IP.complete(split_line[-1])
    if possibilities:
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
      def _commonPrefix(str1, str2):
        '''
        Reduction function. returns common prefix of two given strings.
        
        @param str1: First string.
        @type str1: string
        @param str2: Second string
        @type str2: string
        
        @return: Common prefix to both strings.
        @rtype: string
        '''
        for i in range(len(str1)):
          if not str2.startswith(str1[:i+1]):
            return str1[:i]
        return str1
      common_prefix = reduce(_commonPrefix, possibilities)
206 207 208 209 210 211 212
      completed = line[:-len(split_line[-1])]+common_prefix
    else:
      completed = line
    return completed, possibilities
  

  def shell(self, cmd,verbose=0,debug=0,header=''):
213 214 215 216 217 218 219 220 221 222 223 224
    '''
    Replacement method to allow shell commands without them blocking.
    
    @param cmd: Shell command to execute.
    @type cmd: string
    @param verbose: Verbosity
    @type verbose: integer
    @param debug: Debug level
    @type debug: integer
    @param header: Header to be printed before output
    @type header: string
    '''
225 226 227 228 229 230 231 232 233 234
    stat = 0
    if verbose or debug: print header+cmd
    # flush stdout so we don't mangle python's buffering
    if not debug:
      input, output = os.popen4(cmd)
      print output.read()
      output.close()
      input.close()

class ConsoleView(gtk.TextView):
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  '''
  Specialized text view for console-like workflow.

  @cvar ANSI_COLORS: Mapping of terminal colors to X11 names.
  @type ANSI_COLORS: dictionary

  @ivar text_buffer: Widget's text buffer.
  @type text_buffer: gtk.TextBuffer
  @ivar color_pat: Regex of terminal color pattern
  @type color_pat: _sre.SRE_Pattern
  @ivar mark: Scroll mark for automatic scrolling on input.
  @type mark: gtk.TextMark
  @ivar line_start: Start of command line mark.
  @type line_start: gtk.TextMark
  '''
  ANSI_COLORS =  {'0;30': 'Black',     '0;31': 'Red',
                  '0;32': 'Green',     '0;33': 'Brown',
                  '0;34': 'Blue',      '0;35': 'Purple',
                  '0;36': 'Cyan',      '0;37': 'LightGray',
                  '1;30': 'DarkGray',  '1;31': 'DarkRed',
                  '1;32': 'SeaGreen',  '1;33': 'Yellow',
                  '1;34': 'LightBlue', '1;35': 'MediumPurple',
                  '1;36': 'LightCyan', '1;37': 'White'}

259
  def __init__(self):
260 261 262
    '''
    Initialize console view.
    '''
263
    gtk.TextView.__init__(self)
264
    self.modify_font(pango.FontDescription('Mono'))
265 266 267 268 269
    self.set_cursor_visible(True)
    self.text_buffer = self.get_buffer()
    self.mark = self.text_buffer.create_mark('scroll_mark', 
                                             self.text_buffer.get_end_iter(),
                                             False)
270
    for code in self.ANSI_COLORS:
271
      self.text_buffer.create_tag(code, 
272
                                  foreground=self.ANSI_COLORS[code], 
273 274 275 276
                                  weight=700)
    self.text_buffer.create_tag('0')
    self.text_buffer.create_tag('notouch', editable=False)
    self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?')
277 278 279
    self.line_start = \
        self.text_buffer.create_mark('line_start', 
                                     self.text_buffer.get_end_iter(), True)
280
    self.connect('key-press-event', self.onKeyPress)
281 282
    
  def write(self, text, editable=False):
283 284 285
    gobject.idle_add(self._write, text, editable)

  def _write(self, text, editable=False):
286 287 288 289 290 291 292 293
    '''
    Write given text to buffer.
    
    @param text: Text to append.
    @type text: string
    @param editable: If true, added text is editable.
    @type editable: boolean
    '''
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    segments = self.color_pat.split(text)
    segment = segments.pop(0)
    start_mark = self.text_buffer.create_mark(None, 
                                              self.text_buffer.get_end_iter(), 
                                              True)
    self.text_buffer.insert(self.text_buffer.get_end_iter(), segment)

    if segments:
      ansi_tags = self.color_pat.findall(text)
      for tag in ansi_tags:
        i = segments.index(tag)
        self.text_buffer.insert_with_tags_by_name(self.text_buffer.get_end_iter(),
                                             segments[i+1], tag)
        segments.pop(i)
    if not editable:
      self.text_buffer.apply_tag_by_name('notouch',
                                         self.text_buffer.get_iter_at_mark(start_mark),
                                         self.text_buffer.get_end_iter())
    self.text_buffer.delete_mark(start_mark)
    self.scroll_mark_onscreen(self.mark)

315

316
  def showPrompt(self, prompt):
317 318 319
    gobject.idle_add(self._showPrompt, prompt)

  def _showPrompt(self, prompt):
320 321 322 323 324 325
    '''
    Prints prompt at start of line.
    
    @param prompt: Prompt to print.
    @type prompt: string
    '''
326 327 328
    self._write(prompt)
    self.text_buffer.move_mark(self.line_start,
                               self.text_buffer.get_end_iter())
329 330

  def changeLine(self, text):
331 332 333
    gobject.idle_add(self._changeLine, text)

  def _changeLine(self, text):
334 335 336 337 338 339
    '''
    Replace currently entered command line with given text.
    
    @param text: Text to use as replacement.
    @type text: string
    '''
340 341 342
    iter = self.text_buffer.get_iter_at_mark(self.line_start)
    iter.forward_to_line_end()
    self.text_buffer.delete(self.text_buffer.get_iter_at_mark(self.line_start), iter)
343
    self._write(text, True)
344 345

  def getCurrentLine(self):
346 347 348 349 350 351 352 353 354
    '''
    Get text in current command line.
    
    @return: Text of current command line.
    @rtype: string
    '''
    rv = self.text_buffer.get_slice(
      self.text_buffer.get_iter_at_mark(self.line_start),
      self.text_buffer.get_end_iter(), False)
355 356 357
    return rv

  def showReturned(self, text):
358 359 360
    gobject.idle_add(self._showReturned, text)

  def _showReturned(self, text):
361 362 363 364 365 366
    '''
    Show returned text from last command and print new prompt.
    
    @param text: Text to show.
    @type text: string
    '''
367 368
    iter = self.text_buffer.get_iter_at_mark(self.line_start)
    iter.forward_to_line_end()
369 370 371 372
    self.text_buffer.apply_tag_by_name(
      'notouch', 
      self.text_buffer.get_iter_at_mark(self.line_start),
      iter)
373
    self._write('\n'+text)
374
    if text:
375 376
      self._write('\n')
    self._showPrompt(self.prompt)
377 378 379
    self.text_buffer.move_mark(self.line_start,self.text_buffer.get_end_iter())
    self.text_buffer.place_cursor(self.text_buffer.get_end_iter())

380
  def onKeyPress(self, widget, event):
381 382 383 384 385 386 387 388 389 390 391 392 393
    '''
    Key press callback used for correcting behavior for console-like 
    interfaces. For example 'home' should go to prompt, not to begining of
    line.
    
    @param widget: Widget that key press accored in.
    @type widget: gtk.Widget
    @param event: Event object
    @type event: gtk.gdk.Event
    
    @return: Return True if event should not trickle.
    @rtype: boolean
    '''
394 395 396 397
    insert_mark = self.text_buffer.get_insert()
    insert_iter = self.text_buffer.get_iter_at_mark(insert_mark)
    selection_mark = self.text_buffer.get_selection_bound()
    selection_iter = self.text_buffer.get_iter_at_mark(selection_mark)
398
    start_iter = self.text_buffer.get_iter_at_mark(self.line_start)
399
    if event.keyval == gtk.keysyms.Home:
400 401 402
      if event.state & gtk.gdk.CONTROL_MASK or event.state & gtk.gdk.MOD1_MASK:
        pass
      elif event.state & gtk.gdk.SHIFT_MASK:
403 404
        self.text_buffer.move_mark(insert_mark, start_iter)
        return True
405 406 407
      else:
        self.text_buffer.place_cursor(start_iter)
        return True
408 409 410 411 412
    elif event.keyval == gtk.keysyms.Left:
      insert_iter.backward_cursor_position()
      if not insert_iter.editable(True):
        return True
    elif not event.string:
413 414
      pass
    elif start_iter.compare(insert_iter) <= 0 and \
415
          start_iter.compare(selection_iter) <= 0:
416
      pass
417 418 419
    elif start_iter.compare(insert_iter) > 0 and \
          start_iter.compare(selection_iter) > 0:
      self.text_buffer.place_cursor(start_iter)
420
    elif insert_iter.compare(selection_iter) < 0:
421
      self.text_buffer.move_mark(insert_mark, start_iter)
422
    elif insert_iter.compare(selection_iter) > 0:
423
      self.text_buffer.move_mark(selection_mark, start_iter)             
424

425 426 427 428 429 430 431 432
    return self.onKeyPressExtend(event)

  def onKeyPressExtend(self, event):
    '''
    For some reason we can't extend onKeyPress directly (bug #500900).
    '''
    pass

433
class IPythonView(ConsoleView, IterableIPShell):
434 435 436 437
  '''
  Sub-class of both modified IPython shell and L{ConsoleView} this makes
  a GTK+ IPython console.
  '''
438
  def __init__(self):
439 440 441
    '''
    Initialize. Redirect I/O to console.
    '''
442 443 444 445
    ConsoleView.__init__(self)
    self.cout = StringIO()
    IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout, 
                             input_func=self.raw_input)
446
#    self.connect('key_press_event', self.keyPress)
447 448 449 450 451 452
    self.execute()
    self.cout.truncate(0)
    self.showPrompt(self.prompt)
    self.interrupt = False

  def raw_input(self, prompt=''):
453 454 455 456 457 458 459 460 461
    '''
    Custom raw_input() replacement. Get's current line from console buffer.
    
    @param prompt: Prompt to print. Here for compatability as replacement.
    @type prompt: string
    
    @return: The current command line text.
    @rtype: string
    '''
462 463 464 465 466
    if self.interrupt:
      self.interrupt = False
      raise KeyboardInterrupt
    return self.getCurrentLine()

467
  def onKeyPressExtend(self, event):
468 469 470 471 472 473 474 475 476 477 478 479
    '''
    Key press callback with plenty of shell goodness, like history, 
    autocompletions, etc.
    
    @param widget: Widget that key press occured in.
    @type widget: gtk.Widget
    @param event: Event object.
    @type event: gtk.gdk.Event
    
    @return: True if event should not trickle.
    @rtype: boolean
    '''
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    if event.state & gtk.gdk.CONTROL_MASK and event.keyval == 99:
      self.interrupt = True
      self._processLine()
      return True
    elif event.keyval == gtk.keysyms.Return:
      self._processLine()
      return True
    elif event.keyval == gtk.keysyms.Up:
      self.changeLine(self.historyBack())
      return True
    elif event.keyval == gtk.keysyms.Down:
      self.changeLine(self.historyForward())
      return True
    elif event.keyval == gtk.keysyms.Tab:
      if not self.getCurrentLine().strip():
        return False
      completed, possibilities = self.complete(self.getCurrentLine())
      if len(possibilities) > 1:
        slice = self.getCurrentLine()
        self.write('\n')
        for symbol in possibilities:
          self.write(symbol+'\n')
        self.showPrompt(self.prompt)
503
      self.changeLine(completed or slice)
504 505 506
      return True

  def _processLine(self):
507 508 509
    '''
    Process current command line.
    '''
510 511 512 513 514 515 516
    self.history_pos = 0
    self.execute()
    rv = self.cout.getvalue()
    if rv: rv = rv.strip('\n')
    self.showReturned(rv)
    self.cout.truncate(0)
    
517 518 519 520 521 522 523 524
if __name__ == "__main__":
  window = gtk.Window()
  window.set_default_size(640, 320)
  window.connect('delete-event', lambda x, y: gtk.main_quit())
  window.add(IPythonView())
  window.show_all()
  gtk.main()