#!/bin/env python
# A simple Python interpreter in Python which runs inside a Tk app.
# Ka-Ping Yee, 18 March 1997

import _tkinter, Tkinter, sys, string, traceback

root = Tkinter.Tk()                               # create the Tk object
root.title('pywish')                              # label the window
root.iconname('pywish')                           # label the icon
sys.ps1, sys.ps2 = '>>> ', '... '                 # set up prompts
gdict = {'Tkinter': Tkinter, 'root': root}        # set up namespace

def promptstart():                                # show starting prompt
    sys.stdout.write(sys.ps1)
    sys.stdout.flush()

def promptcont():                                 # show continuation prompt
    sys.stdout.write(sys.ps2)
    sys.stdout.flush()

line, source, multi = '', '', 0                   # state information

def getinput(file, num):                          # input event handler
    global line, source, multi

    chunk = file.readline()
    if not chunk: sys.exit(0)                     # got EOF, so quit
    line = line + chunk
    if line[-1] != '\n': return                   # collect text until \n

    line = string.rstrip(line)
    if multi:
        if line:
            source = source + line + '\n'         # append line to block
            promptcont()
        else:
            interpret(source)                     # blank line ends block
            source, multi = '', 0
    else:
        if not line: promptstart()                # no input, prompt again
        elif line and line[-1] == ':':
            source, multi = line + '\n', 1        # start multi-line block
            promptcont()
        else: interpret(line)                     # just do this line

    line = ''

def interpret(source):
    try:
        code = compile(source + '\n\n\n', '<stdin>', 'single')
        exec(code, gdict)

    except SyntaxError:                           # emulate Python
        (value, info) = sys.exc_value
        (filename, linenum, position, source) = info
        if filename is None: filename = '<stdin>'
        print '  File "' + filename + '", line', linenum
        print '    ' + source, ' '*position + '   ^'
        print 'SyntaxError:', value

    except:                                       # discard first entry
        print "Traceback (innermost last):"       # to hide my stack frame
        for entry in traceback.extract_tb(sys.exc_traceback)[1:]:
            (file, linenum, func, source) = entry
            print '  File "' + file + '", line', linenum, 'in', func
            if source: print '    ' + string.lstrip(source)
        print str(sys.exc_type) + ': ' + str(sys.exc_value)

    promptstart()

print 'Python', sys.version, '(pywish)'           # official-looking header
print sys.copyright
promptstart()
_tkinter.createfilehandler(sys.stdin, Tkinter.READABLE, getinput)
_tkinter.mainloop()                               # we're all set; go!
