Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/pyshell.py
blob: d7c3243473460f9f617d5aadae92393c22428be9 (plain)
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#
#       Py_Shell.py : inserts the python prompt in a gtk interface
#

import sys, code, os
import __builtin__

from gi.repository import GObject, Pango, Gdk, GObject
from gi.repository import Gtk as gtk
import Queue

PS1=">>> "
PS2="... "
TAB_WIDTH=4
SPACEBAR = 32

BANNER="Python "+sys.version+"\n"



class Completer:
  """
  Taken from rlcompleter, with readline references stripped, and a local dictionary to use.
  """
  def __init__(self,locals):
    self.locals = locals

  def complete(self, text, state):
    """Return the next possible completion for 'text'.
    This is called successively with state == 0, 1, 2, ... until it
    returns None.  The completion should begin with 'text'.

    """
    if state == 0:
      if "." in text:
        self.matches = self.attr_matches(text)
      else:
        self.matches = self.global_matches(text)
    try:
      return self.matches[state]
    except IndexError:
      return None

  def global_matches(self, text):
    """Compute matches when text is a simple name.

    Return a list of all keywords, built-in functions and names
    currently defines in __main__ that match.

    """
    import keyword
    matches = []
    n = len(text)
    for list in [keyword.kwlist, __builtin__.__dict__.keys(), self.locals.keys()]:
      for word in list:
        if word[:n] == text and word != "__builtins__":
          matches.append(word)
    return matches

  def attr_matches(self, text):
    """Compute matches when text contains a dot.

    Assuming the text is of the form NAME.NAME....[NAME], and is
    evaluatable in the globals of __main__, it will be evaluated
    and its attributes (as revealed by dir()) are used as possible
    completions.  (For class instances, class members are are also
    considered.)

    WARNING: this can still invoke arbitrary C code, if an object
    with a __getattr__ hook is evaluated.

    """
    import re
    m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
    if not m:
      return
    expr, attr = m.group(1, 3)
    object = eval(expr, self.locals, self.locals)
    words = dir(object)
    if hasattr(object,'__class__'):
      words.append('__class__')
      words = words + get_class_members(object.__class__)
    matches = []
    n = len(attr)
    for word in words:
      if word[:n] == attr and word != "__builtins__":
        matches.append("%s.%s" % (expr, word))
    return matches

def get_class_members(klass):
  ret = dir(klass)
  if hasattr(klass,'__bases__'):
     for base in klass.__bases__:
       ret = ret + get_class_members(base)
  return ret







class Dummy_File:

    def __init__(self, buffer, tag):
        """Implements a file-like object for redirect the stream to the buffer"""
        
        self.buffer = buffer
        self.tag = tag

    def write(self, text):
        """Write text into the buffer and apply self.tag"""
        iter=self.buffer.get_end_iter()
        self.buffer.insert_with_tags(iter,text,self.tag)

    def writelines(self, l):
        map(self.write, l)

    def flush(self):
        pass

    def isatty(self):
        return 1



class PopUp:

    def __init__(self, text_view, list, position):
        self.text_view=text_view
        
        #avoid duplicate items in list
        tmp={}
        n_chars=0
        for item in list:
            dim=len(item)
            if dim>n_chars:
                n_chars=dim
            tmp[item]=None 
        list=tmp.keys()
        list.sort()
        
        self.list=list
        self.position=position
        self.popup=gtk.Window(gtk.WINDOW_POPUP)
        frame=gtk.Frame()
        sw=gtk.ScrolledWindow()
        sw.set_policy(gtk.GTK_POLICY_AUTOMATIC, gtk.GTK_POLICY_AUTOMATIC)
        model=gtk.ListStore(GObject.TYPE_STRING)
        for item in self.list:
            iter=model.append()
            model.set(iter, 0, item)
        self.list_view=gtk.TreeView(model)
        self.list_view.connect("row-activated", self.hide)
        self.list_view.set_property("headers-visible", False)
        selection=self.list_view.get_selection()
        selection.connect("changed",self.select_row)
        selection.select_path((0,))
        renderer=gtk.CellRendererText()
        column=gtk.TreeViewColumn("",renderer,text=0)
        self.list_view.append_column(column)
        sw.add(self.list_view)
        frame.add(sw)
        self.popup.add(frame)
        
        #set the width of the popup according with the length of the strings
        contest=self.popup.get_pango_context()
        desc=contest.get_font_description()
        lang=contest.get_language()
        metrics= contest.get_metrics(desc, lang)
        width= Pango.PIXELS(metrics.get_approximate_char_width()* n_chars)
        if width>80:
            self.popup.set_size_request(width,90)
        else:
            self.popup.set_size_request(80,90)
        self.show_popup()

 
    def hide(self, *arg):
        self.popup.hide()
         
    def show_popup(self):
        buffer=self.text_view.get_buffer()
        iter=buffer.get_iter_at_mark(buffer.get_insert())
        
        rectangle=self.text_view.get_iter_location(iter)
        absX, absY=self.text_view.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, 
                                   rectangle.x+rectangle.width+20 ,
                                   rectangle.y+rectangle.height+50)
        parent=self.text_view.get_parent()
        self.popup.move(self.position[0]+absX, self.position[1]+absY)
        self.popup.show_all()

             

    def prev(self):
        sel=self.list_view.get_selection()
        model, iter=sel.get_selected()
        newIter=model.get_path(iter)
        if newIter!=None and newIter[0]>0:
            path=(newIter[0]-1,)
            self.list_view.set_cursor(path)
            

    def next(self):
        sel=self.list_view.get_selection()
        model, iter=sel.get_selected()
        newIter=model.iter_next(iter)
        if newIter!=None:
            path=model.get_path(newIter)
            self.list_view.set_cursor(path)


    def sel_confirmed(self):
        sel=self.list_view.get_selection()
        self.select_row(sel)
        self.hide()

                                                                                                                                                
    def select_row(self, selection):
        model, iter= selection.get_selected()
        name=model.get_value(iter,0)
        buffer=self.text_view.get_buffer()
        end=buffer.get_iter_at_mark(buffer.get_insert())
        start=end.copy()
        start.backward_char()
        while start.get_char() not in " ,()[]":
            start.backward_char()
        start.forward_char()
        buffer.delete(start,end)
        iter=buffer.get_iter_at_mark(buffer.get_insert())
        buffer.insert(iter,name)


class Shell_Gui:

    def __init__(self,with_window=1,banner=BANNER, label_text="Interactive Python Shell", namespace=None, queue_pack=None):
        
        self.queue_pack = queue_pack
        self.code_lines = []
        self.banner=banner
        box=gtk.HBox()
        box.set_homogeneous(False)
        box.set_border_width(4)
        box.set_spacing(4)
        sw=gtk.ScrolledWindow()

        self.view=gtk.TextView()
        self.buffer = self.view.get_buffer()
        # creates three tags
        tag_err=self.buffer.create_tag("error")
        tag_err.set_property("foreground","red")
        tag_err.set_property("font","monospace 10")
        
        tag_out=self.buffer.create_tag("out_tag")
        tag_out.set_property("foreground","blue")
        tag_out.set_property("font","monospace 10")
        
        tag_in=self.buffer.create_tag("in_tag")
        tag_in.set_property("foreground","black")
        tag_in.set_property("font","monospace 10")

        tag_no_edit=self.buffer.create_tag("no_edit")
        tag_no_edit.set_property("editable",False)
        #add the banner
        self.buffer.set_text(self.banner+PS1)
        start,end=self.buffer.get_bounds()
        self.buffer.apply_tag_by_name("out_tag", start, end)
        self.buffer.apply_tag_by_name("no_edit", start, end)

        self.view.connect("key_press_event", self.key_press)
        self.view.connect("drag_data_received",self.drag_data_received)

        GObject.timeout_add(30, self.on_idle)

        self.view.set_wrap_mode(gtk.WrapMode.WORD_CHAR)
        sw.add(self.view)
        box.pack_start(sw, True, True, 0)

        #creates  two dummy files
        self.dummy_out=Dummy_File(self.buffer,tag_out)
        self.dummy_err=Dummy_File(self.buffer,tag_err)
        
        #creates the console
        if namespace is None: namespace = {}
        self.core=code.InteractiveConsole(namespace)

        #autocompletation capabilities
        self.completer = Completer(self.core.locals)
        self.popup=None
        
        #creates history capabilities
        self.history=[" "]
        self.history_pos=0

        #add buttons
        #b_box=gtk.Toolbar()
        #b_box.set_orientation(gtk.Orientation.VERTICAL)
        #b_box.set_style(gtk.ToolbarStyle.ICONS)

        #button1 = gtk.ToolButton(gtk.STOCK_SAVE)
        #button2 = gtk.ToolButton(gtk.STOCK_CLEAR)
        #button3 = gtk.ToolButton(gtk.STOCK_PREFERENCES)

        #b_box.insert(gtk.STOCK_CLEAR,"Clear the output", None, self.clear_text, None,-1)
        #b_box.insert(gtk.STOCK_SAVE,"Save the output", None, self.save_text, None,-1)
        #b_box.insert(gtk.STOCK_PREFERENCES,"Preferences", None, None, None,-1)
        #b_box.insert(button1, 0)
        #b_box.insert(button2, 0)
        #b_box.insert(button3, 0)

        if with_window:
            q_button = gtk.ToolButton(gtk.STOCK_QUIT)
            #b_box.insert(q_button, 0)
        
        
        #box.pack_start(b_box, False, True, 0)
        frame=gtk.Frame()
        frame.set_label(label_text)
        frame.show_all()
        frame.add(box)
        
        
        if with_window:
            self.gui=gtk.Window()
            self.gui.add(frame)
            self.gui.connect("delete-event",self.quit)
            self.gui.set_default_size(520,200)
            self.gui.show_all()
        else:
            self.gui=frame
        




    def key_press(self, view, event):
        if self.popup!=None:
            
            if event.keyval == Gdk.KEY_Up:
                self.popup.prev()
                return True
            elif event.keyval == Gdk.KEY_Down:
                self.popup.next()
                return True 
            elif event.keyval == Gdk.KEY_Return:
                self.popup.sel_confirmed()
                self.popup=None
                return True 
            else:
                self.popup.hide()
                self.popup=None
        else:
            if event.keyval == Gdk.KEY_Up:
                
                if self.history_pos>0:
                    # remove text into the line...
                    end=self.buffer.get_end_iter()
                    start=self.buffer.get_iter_at_line(end.get_line())
                    start.forward_chars(4)
                    self.buffer.delete(start,end)
                    #inset the new text
                    pos=self.buffer.get_end_iter()
                    self.buffer.insert(pos, self.history[self.history_pos])
                    self.history_pos-=1
                else:
                    Gdk.beep()
                self.view.emit_stop_by_name("key-press-event")
                return True
                
            elif event.keyval == Gdk.KEY_Down:
    
                if self.history_pos<len(self.history)-1:
                    # remove text into the line...
                    end=self.buffer.get_end_iter()
                    start=self.buffer.get_iter_at_line(end.get_line())
                    start.forward_chars(4)
                    self.buffer.delete(start,end)
                    #inset the new text
                    pos=self.buffer.get_end_iter()
                    self.history_pos+=1
                    self.buffer.insert(pos, self.history[self.history_pos])
                    
                else:
                    Gdk.beep()
                self.view.emit_stop_by_name("key-press-event")
                return True
            
            elif event.keyval == Gdk.KEY_Tab:
                iter=self.buffer.get_iter_at_mark(self.buffer.get_insert())
                self.buffer.insert(iter,TAB_WIDTH*" ")
                return True
            
            elif event.keyval == Gdk.KEY_Return:
                command=self.get_line()
                self.exec_code(command)
                start,end=self.buffer.get_bounds()
                self.buffer.apply_tag_by_name("no_edit",start,end)
                self.buffer.place_cursor(end)
                return True
                
            #elif event.keyval == SPACEBAR: #and event.state & gtk.gdk.CONTROL_MASK:
            #    self.complete_text()
            #    return True
            
    

    def clear_text(self,*widget):
        dlg=gtk.Dialog("Clear")
        dlg.add_button("Clear",1)
        dlg.add_button("Reset",2)
        dlg.add_button(gtk.STOCK_CLOSE,gtk.RESPONSE_CLOSE)
        dlg.set_default_size(250,150)
        hbox=gtk.HBox()
        #add an image
        img=gtk.Image()
        img.set_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_DIALOG)
        hbox.pack_start(img, True, True, 0)
        
        #add text
        text="You have two options:\n"
        text+="   -clear only the output window\n"
        text+="   -reset the shell\n"
        text+="\n What do you want to do?"
        label=gtk.Label(text)
        hbox.pack_start(label, True, True, 0)
        
        hbox.show_all()
        dlg.vbox.pack_start(hbox, True, True, 0)
        
        ans=dlg.run()
        dlg.hide()
        if ans==1:
            self.buffer.set_text(self.banner+PS1)
            start,end=self.buffer.get_bounds()
            self.buffer.apply_tag_by_name("out_tag",start,end)

        elif ans==2:
            self.buffer.set_text(self.banner+PS1)
            start,end=self.buffer.get_bounds()
            self.buffer.apply_tag_by_name("out_tag",start,end)
            self.buffer.apply_tag_by_name("no_edit",start,end)

            #creates the console
            self.core=code.InteractiveConsole()
            #reset history
            self.history=[" "]
            self.history_pos=0
        self.view.grab_focus()


    def save_text(self, *widget):
        dlg=gtk.Dialog("Save to file")
        dlg.add_button("Commands",1)
        dlg.add_button("All",2)
        dlg.add_button(gtk.STOCK_CLOSE,gtk.RESPONSE_CLOSE)
        dlg.set_default_size(250,150)
        hbox=gtk.HBox()
        #add an image
        img=gtk.Image()
        img.set_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_DIALOG)
        hbox.pack_start(img)
        
        #add text
        text="You have two options:\n"
        text+="   -save only commands\n"
        text+="   -save all\n"
        text+="\n What do you want to save?"
        label=gtk.Label(text)
        hbox.pack_start(label)
        
        hbox.show_all()
        dlg.vbox.pack_start(hbox)
        
        ans=dlg.run()
        dlg.hide()
        if ans==1 :
            def ok_save(button, data=None):
                win =button.get_toplevel()
                win.hide()
                name=win.get_filename()
                if os.path.isfile(name):
                    box=gtk.MessageDialog(dlg,
                                      gtk.DIALOG_DESTROY_WITH_PARENT,
                                      gtk.MESSAGE_QUESTION,gtk.BUTTONS_YES_NO,
                                    name+" already exists; do you want to overwrite it?"
                                    )
                    ans=box.run()
                    box.hide()
                    if ans==gtk.RESPONSE_NO:
                        return
                try:
                    file=open(name,'w')
                    for i in self.history:
                        file.write(i)
                        file.write("\n")
                    file.close()
                    
                        
                except Exception, x:
                    box=gtk.MessageDialog(dlg,
                                      gtk.DIALOG_DESTROY_WITH_PARENT,
                                      gtk.MESSAGE_ERROR,gtk.BUTTONS_CLOSE,
                                    "Unable to write \n"+
                                    name+"\n on disk \n\n%s"%(x)
                                    )
                    box.run()
                    box.hide()
                    
            def cancel_button(button):
                win.get_toplevel()
                win.hide()
                
            win=gtk.FileSelection("Save Commands...")
            win.ok_button.connect_object("clicked", ok_save,win.ok_button)
            win.cancel_button.connect_object("clicked", cancel_button,win.cancel_button)
            win.show()
        elif ans==2:
            def ok_save(button, data=None):
                win =button.get_toplevel()
                win.hide()
                name=win.get_filename()
                if os.path.isfile(name):
                    box=gtk.MessageDialog(dlg,
                                      gtk.DIALOG_DESTROY_WITH_PARENT,
                                      gtk.MESSAGE_QUESTION,gtk.BUTTONS_YES_NO,
                                    name+" already exists; do you want to overwrite it?"
                                    )
                    ans=box.run()
                    box.hide()
                    if ans==gtk.RESPONSE_NO:
                        return
                try:
                    start,end=self.buffer.get_bounds()
                    text=self.buffer.get_text(start,end,0)
                    file=open(name,'w')
                    file.write(text)
                    file.close()
                    
                except Exception, x:
                    box=gtk.MessageDialog(dlg,
                                      gtk.DIALOG_DESTROY_WITH_PARENT,
                                      gtk.MESSAGE_ERROR,gtk.BUTTONS_CLOSE,
                                    "Unable to write \n"+
                                    name+"\n on disk \n\n%s"%(x)
                                    )
                    box.run()
                    box.hide()
                    
            def cancel_button(button):
                win.get_toplevel()
                win.hide()
                
            win=gtk.FileSelection("Save Log...")
            win.ok_button.connect_object("clicked", ok_save,win.ok_button)
            win.cancel_button.connect_object("clicked", cancel_button,win.cancel_button)
            win.show()
        dlg.destroy()
        self.view.grab_focus()
        

          
    def get_line(self):
        iter=self.buffer.get_iter_at_mark(self.buffer.get_insert())
        line=iter.get_line()
        start=self.buffer.get_iter_at_line(line)
        end=start.copy()
        end.forward_line()
        command=self.buffer.get_text(start,end,0)
        if  (command[:4]==PS1 or command[:4]==PS2):
            command=command[4:]
        return command
        
        
    def complete_text(self):
        end=self.buffer.get_iter_at_mark(self.buffer.get_insert())
        start=end.copy()
        start.backward_char()
        while start.get_char() not in " ,()[]=":
            start.backward_char()
        start.forward_char()
        token=self.buffer.get_text(start,end,0).strip() 
        completions = []
        try:
            p=self.completer.complete(token,len(completions))
            while p != None:
              completions.append(p)
              p=self.completer.complete(token, len(completions))
        except:
            return 
        if len(completions)==1:
            self.buffer.delete(start,end)
            iter=self.buffer.get_iter_at_mark(self.buffer.get_insert())
            self.buffer.insert(iter,completions[0])
        elif len(completions)>1:
            #show a popup 
            if isinstance(self.gui, gtk.Frame):
                rect=self.gui.get_allocation()
                app=self.gui.window.get_position()
                position=(app[0]+rect.x,app[1]+rect.y)
            else:    
                position=self.gui.get_position()

            self.popup=PopUp(self.view, completions, position) 

         
    def replace_line(self, text):
        iter=self.buffer.get_iter_at_mark(self.buffer.get_insert())
        line=iter.get_line()
        start=self.buffer.get_iter_at_line(line)
        start.forward_chars(4)
        end=start.copy()
        end.forward_line()
        self.buffer.delete(start,end)
        iter=self.buffer.get_iter_at_mark(self.buffer.get_insert())
        self.buffer.insert(iter, text)
        
        
                          
    def sdt2files(self):
        """switch stdin stdout stderr to my dummy files"""
        self.std_out_saved=sys.stdout
        self.std_err_saved=sys.stderr
        
        sys.stdout=self.dummy_out
        sys.stderr=self.dummy_err
        
        
        
        
        

    def files2sdt(self):
        """switch my dummy files to stdin stdout stderr  """
        sys.stdout=self.std_out_saved
        sys.stderr=self.std_err_saved
        



    def drag_data_received(self, source, drag_context, n1, n2, selection_data, long1, long2):
        print selection_data.data
        
    def on_idle(self, e=None):
        try:
            result = self.queue_pack[1].get(False)
            self.dummy_out.write(result)
            self.dummy_out.write("%s" % (PS1)) 
            return True
        except Queue.Empty:
            pass
            return True

    def exec_code(self, text):
        """Execute text into the console and display the output into TextView"""
        
        #update history
        self.history.append(text)
        self.history_pos=len(self.history)-1
        
        self.dummy_out.write("\n")
        self.code_lines.append(text)
        cur_code = "\n".join(self.code_lines)
        action = self.core.compile(cur_code)
        if action:
            # the line needs to be executed
            self.code_lines = []
            self.queue_pack[0].put(cur_code)
        else:
            self.dummy_out.write(PS2)

        self.view.scroll_mark_onscreen(self.buffer.get_insert())



    def quit(self,*args):
        if __name__=='__main__':
            gtk.main_quit()
        else:
            if self.popup!=None:
                self.popup.hide()
            self.gui.hide()

if __name__ == "__main__":
    Shell_Gui()
    gtk.main()