Guest User

PyPyGTK v0.1

a guest
Jul 24th, 2010
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.33 KB | None | 0 0
  1. '''
  2. Remote PyPyGTK v0.1
  3. Brett Hartshorn 2010 - License BSD
  4. '''
  5. ## Reserved Characters, can not be passed from rpython to Cpython by function call in a string
  6. ## you can change them if you need ##
  7. FUNCTION_FAST = '|'
  8. FUNCTION_SLOW = '$'
  9. FUNC_ARG_SEP = '^'
  10. ARGUMENT_SEP = '~'
  11.  
  12. import os, sys, time, inspect, types, select, subprocess
  13. sys.path.append('pypy')
  14. import pypy.tool.error
  15. import gtk as _gtk
  16. import glib
  17.  
  18. def loop():
  19.     rlist,wlist,xlist = select.select( [read], [write], [], 0.01 )     
  20.     if rlist and wlist: # must wait for both read and write, because read can be selected by itself, but we must also respond
  21.         a = read.readline().strip()
  22.         if a: print a
  23.         if a.startswith('>'):
  24.             if FUNC_ARG_SEP in a:
  25.                 cname, args = a.split('>')[-1].strip().split( FUNC_ARG_SEP )
  26.                 nargs = string2args( args )
  27.                 cls = getattr( _gtk, cname )
  28.                 o = cls( *nargs )
  29.             else:
  30.                 cname = a.split('>')[-1].strip()
  31.                 cls = getattr( _gtk, cname )
  32.                 o = cls()
  33.  
  34.             ID = id( o )
  35.             INSTANCES[ ID ] = o
  36.             print '$new instance', o
  37.             print '$instance ID', ID
  38.             write.write( '%s\n' %ID )
  39.             write.flush()
  40.  
  41.         elif a.startswith('@'):
  42.             ID, b = a.split( FUNCTION_SLOW )
  43.             ID = int(ID[1:])        # strip the @
  44.             o = INSTANCES[ID]
  45.             print '$got instance', o
  46.             fname,args = b.split(FUNC_ARG_SEP)
  47.             func = getattr( o, fname )
  48.             nargs = string2args( args )
  49.             func( *nargs )
  50.  
  51.     return True
  52.  
  53. def pipe( *args ):  # the types of *args can not change in pypy, convert to strings first
  54.     a = ''
  55.     #b = list(args) # pypy does not like iteration over a tuple
  56.     for arg in args: a += '%s' %arg
  57.     stdout.write( '%s\n' %a )
  58.     stdout.flush()
  59.  
  60. def string2args( string ):
  61.     nargs = []
  62.     for arg in string.split(ARGUMENT_SEP):
  63.         if arg.strip():
  64.             if arg.startswith('@'): nargs.append( INSTANCES[int(arg[1:])] )
  65.             else: nargs.append( eval(arg) )
  66.     return nargs
  67.  
  68. def args2string( args ):
  69.     a = ''
  70.     for arg in list(args):
  71.         if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  72.         elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  73.             a += '"%s"%s' %(arg, ARGUMENT_SEP)
  74.         else: a += '%s%s' %(arg, ARGUMENT_SEP)
  75.     return a   
  76.  
  77. class Proxy(object):
  78.     def __init__(self, *args):
  79.         if args:
  80.             pipe( 'init args: %s' %args )
  81.             #a = args2string( args )
  82.             a = ''
  83.             for arg in list(args):
  84.                 if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  85.                 elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  86.                     a += '"%s"%s' %(arg, ARGUMENT_SEP)
  87.                 else: a += '%s%s' %(arg, ARGUMENT_SEP)
  88.             pipe( '>create>%s%s%s' %(self.classname, FUNC_ARG_SEP, a) )
  89.         else: pipe( '>create>%s' %self.classname )
  90.         self._ID = 0
  91.         rl,wl,xl = rpoll.select( [0], [], [], 10.0 )    # wait 10 seconds, subprocess only needs to wait for reading
  92.         if rl:
  93.             ID = stdin.readline().strip('\n').strip(' ')
  94.             pipe( '^got new ID: %s' %ID )
  95.             self._ID = int(ID)
  96.         else:
  97.             pipe( '^^ lost contact with parent process ^^' )
  98.             raise SystemExit
  99.            
  100. CLASSES = {}        ## TODO geneate classes so __init__ *args can work better
  101. INSTANCES = {}
  102. Generated = []
  103.  
  104. def genRPC( fname ):        ## interesting pypy needs generated functions so that *args can work properly
  105.     index = len( Generated )
  106.     ## TODO handle all special cases for pygtk
  107.     if fname=='connect':
  108.         def rpc( self, name, tag, callback, *args ):
  109.             pipe( '-rpc %s %s' %(self, name) )
  110.             a = '"%s"%s' %(tag, ARGUMENT_SEP)
  111.             a += '%s%s' %(callback, ARGUMENT_SEP)       # TODO, can we send the byte codes of lambda? or how to get source?
  112.             for arg in list(args):
  113.                 if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  114.                 elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  115.                     a += '"%s"%s' %(arg, ARGUMENT_SEP)
  116.                 else: a += '%s%s' %(arg, ARGUMENT_SEP)
  117.             pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SLOW, name, FUNC_ARG_SEP, a) )
  118.         wrap = eval( 'lambda self,tag,cb,*args: generatedRPC%s(self,"%s",tag,cb,*args)' %(index,fname) )
  119.  
  120.     else:
  121.         def rpc( self, name, *args ):
  122.             pipe( '-rpc %s %s' %(self, name) )
  123.             a = ''
  124.             for arg in list(args):
  125.                 if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  126.                 elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  127.                     a += '"%s"%s' %(arg, ARGUMENT_SEP)
  128.                 else: a += '%s%s' %(arg, ARGUMENT_SEP)
  129.             pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SLOW, name, FUNC_ARG_SEP, a) )
  130.         wrap = eval( 'lambda self,*args: generatedRPC%s(self,"%s",*args)' %(index,fname) )  # trick to pass function name
  131.  
  132.     Generated.append( rpc )
  133.     globals().update( {'generatedRPC%s'%index: rpc} )
  134.     return wrap, index
  135.  
  136. def wrap_class( cls ):
  137.     name = cls.__name__
  138.     funcs = {}
  139.     fnames = ''
  140.     d = {'classname':name}
  141.     for n in dir(cls):
  142.         a = getattr( cls, n )
  143.         if inspect.isroutine( a ) and not n.startswith('_'):
  144.             genfunc, index = genRPC(n)
  145.             #d[n] = eval( 'lambda self,*args: generatedRPC%s(self,"%s",*args)' %(index,n) )
  146.             d[n] = genfunc
  147.     mclass = types.ClassType(name, bases=(Proxy,), dict=d)
  148.     return mclass
  149.  
  150. def wrap( module, name ):
  151.     class RemoteGTK: pass
  152.     wmodule = RemoteGTK()
  153.     for name in dir( module ):
  154.         if not name.startswith('_'):
  155.             o = getattr( module, name )
  156.             if inspect.isclass( o ):
  157.                 wc = wrap_class( o )
  158.                 setattr( wmodule, name, wc)
  159.     return wmodule
  160.  
  161. if '--pypy' in sys.argv:
  162.     gtk = wrap( _gtk, 'gtk' )
  163.     print gtk
  164.  
  165. def entry_point():
  166.     w = gtk.Window()
  167.     w.set_size_request( 320,200 )
  168.     w.set_title('PyPyGTK v0.1')
  169.     root = gtk.VBox(); w.add( root )
  170.     root.set_border_width(50)
  171.     lab = gtk.Label()
  172.     lab.set_text( 'hello world' )
  173.     root.pack_start( lab )
  174.     b = gtk.Button( 'click me' )
  175.     b.connect('clicked', "lambda b,l: l.set_text('clicked')", lab )
  176.     root.pack_start( b )
  177.     w.show_all()
  178.  
  179. if '--pypy' in sys.argv:
  180.     from pypy.rlib import streamio
  181.     from pypy.rlib import rpoll
  182.     stdin = streamio.fdopen_as_stream(0, 'r', 0)        # fd, mode, buffering
  183.     stdout = streamio.fdopen_as_stream(1, 'w', 0)
  184.     from pypy.translator.interactive import Translation
  185.     t = Translation( entry_point )
  186.     t.annotate(); t.rtype()
  187.     f = t.compile_c()
  188.     f()
  189.     print( 'subprocess exit' )
  190.  
  191. else:
  192.     process = subprocess.Popen( 'python %s --pypy' %sys.argv[0], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0, shell=True )
  193.     write = process.stdin
  194.     read = process.stdout
  195.     print( 'read pipe', read )
  196.     print( 'read write', write )
  197.     glib.timeout_add( 33, loop )
  198.     _gtk.main()
  199.     print( 'toplevel exit' )
Advertisement
Add Comment
Please, Sign In to add comment