Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Remote PyPyGTK v0.1
- Brett Hartshorn 2010 - License BSD
- '''
- ## Reserved Characters, can not be passed from rpython to Cpython by function call in a string
- ## you can change them if you need ##
- FUNCTION_FAST = '|'
- FUNCTION_SLOW = '$'
- FUNC_ARG_SEP = '^'
- ARGUMENT_SEP = '~'
- import os, sys, time, inspect, types, select, subprocess
- sys.path.append('pypy')
- import pypy.tool.error
- import gtk as _gtk
- import glib
- def loop():
- rlist,wlist,xlist = select.select( [read], [write], [], 0.01 )
- if rlist and wlist: # must wait for both read and write, because read can be selected by itself, but we must also respond
- a = read.readline().strip()
- if a: print a
- if a.startswith('>'):
- if FUNC_ARG_SEP in a:
- cname, args = a.split('>')[-1].strip().split( FUNC_ARG_SEP )
- nargs = string2args( args )
- cls = getattr( _gtk, cname )
- o = cls( *nargs )
- else:
- cname = a.split('>')[-1].strip()
- cls = getattr( _gtk, cname )
- o = cls()
- ID = id( o )
- INSTANCES[ ID ] = o
- print '$new instance', o
- print '$instance ID', ID
- write.write( '%s\n' %ID )
- write.flush()
- elif a.startswith('@'):
- ID, b = a.split( FUNCTION_SLOW )
- ID = int(ID[1:]) # strip the @
- o = INSTANCES[ID]
- print '$got instance', o
- fname,args = b.split(FUNC_ARG_SEP)
- func = getattr( o, fname )
- nargs = string2args( args )
- func( *nargs )
- return True
- def pipe( *args ): # the types of *args can not change in pypy, convert to strings first
- a = ''
- #b = list(args) # pypy does not like iteration over a tuple
- for arg in args: a += '%s' %arg
- stdout.write( '%s\n' %a )
- stdout.flush()
- def string2args( string ):
- nargs = []
- for arg in string.split(ARGUMENT_SEP):
- if arg.strip():
- if arg.startswith('@'): nargs.append( INSTANCES[int(arg[1:])] )
- else: nargs.append( eval(arg) )
- return nargs
- def args2string( args ):
- a = ''
- for arg in list(args):
- if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
- elif isinstance( arg, str ): # type(arg) is str # not allowed in pypy
- a += '"%s"%s' %(arg, ARGUMENT_SEP)
- else: a += '%s%s' %(arg, ARGUMENT_SEP)
- return a
- class Proxy(object):
- def __init__(self, *args):
- if args:
- pipe( 'init args: %s' %args )
- #a = args2string( args )
- a = ''
- for arg in list(args):
- if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
- elif isinstance( arg, str ): # type(arg) is str # not allowed in pypy
- a += '"%s"%s' %(arg, ARGUMENT_SEP)
- else: a += '%s%s' %(arg, ARGUMENT_SEP)
- pipe( '>create>%s%s%s' %(self.classname, FUNC_ARG_SEP, a) )
- else: pipe( '>create>%s' %self.classname )
- self._ID = 0
- rl,wl,xl = rpoll.select( [0], [], [], 10.0 ) # wait 10 seconds, subprocess only needs to wait for reading
- if rl:
- ID = stdin.readline().strip('\n').strip(' ')
- pipe( '^got new ID: %s' %ID )
- self._ID = int(ID)
- else:
- pipe( '^^ lost contact with parent process ^^' )
- raise SystemExit
- CLASSES = {} ## TODO geneate classes so __init__ *args can work better
- INSTANCES = {}
- Generated = []
- def genRPC( fname ): ## interesting pypy needs generated functions so that *args can work properly
- index = len( Generated )
- ## TODO handle all special cases for pygtk
- if fname=='connect':
- def rpc( self, name, tag, callback, *args ):
- pipe( '-rpc %s %s' %(self, name) )
- a = '"%s"%s' %(tag, ARGUMENT_SEP)
- a += '%s%s' %(callback, ARGUMENT_SEP) # TODO, can we send the byte codes of lambda? or how to get source?
- for arg in list(args):
- if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
- elif isinstance( arg, str ): # type(arg) is str # not allowed in pypy
- a += '"%s"%s' %(arg, ARGUMENT_SEP)
- else: a += '%s%s' %(arg, ARGUMENT_SEP)
- pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SLOW, name, FUNC_ARG_SEP, a) )
- wrap = eval( 'lambda self,tag,cb,*args: generatedRPC%s(self,"%s",tag,cb,*args)' %(index,fname) )
- else:
- def rpc( self, name, *args ):
- pipe( '-rpc %s %s' %(self, name) )
- a = ''
- for arg in list(args):
- if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
- elif isinstance( arg, str ): # type(arg) is str # not allowed in pypy
- a += '"%s"%s' %(arg, ARGUMENT_SEP)
- else: a += '%s%s' %(arg, ARGUMENT_SEP)
- pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SLOW, name, FUNC_ARG_SEP, a) )
- wrap = eval( 'lambda self,*args: generatedRPC%s(self,"%s",*args)' %(index,fname) ) # trick to pass function name
- Generated.append( rpc )
- globals().update( {'generatedRPC%s'%index: rpc} )
- return wrap, index
- def wrap_class( cls ):
- name = cls.__name__
- funcs = {}
- fnames = ''
- d = {'classname':name}
- for n in dir(cls):
- a = getattr( cls, n )
- if inspect.isroutine( a ) and not n.startswith('_'):
- genfunc, index = genRPC(n)
- #d[n] = eval( 'lambda self,*args: generatedRPC%s(self,"%s",*args)' %(index,n) )
- d[n] = genfunc
- mclass = types.ClassType(name, bases=(Proxy,), dict=d)
- return mclass
- def wrap( module, name ):
- class RemoteGTK: pass
- wmodule = RemoteGTK()
- for name in dir( module ):
- if not name.startswith('_'):
- o = getattr( module, name )
- if inspect.isclass( o ):
- wc = wrap_class( o )
- setattr( wmodule, name, wc)
- return wmodule
- if '--pypy' in sys.argv:
- gtk = wrap( _gtk, 'gtk' )
- print gtk
- def entry_point():
- w = gtk.Window()
- w.set_size_request( 320,200 )
- w.set_title('PyPyGTK v0.1')
- root = gtk.VBox(); w.add( root )
- root.set_border_width(50)
- lab = gtk.Label()
- lab.set_text( 'hello world' )
- root.pack_start( lab )
- b = gtk.Button( 'click me' )
- b.connect('clicked', "lambda b,l: l.set_text('clicked')", lab )
- root.pack_start( b )
- w.show_all()
- if '--pypy' in sys.argv:
- from pypy.rlib import streamio
- from pypy.rlib import rpoll
- stdin = streamio.fdopen_as_stream(0, 'r', 0) # fd, mode, buffering
- stdout = streamio.fdopen_as_stream(1, 'w', 0)
- from pypy.translator.interactive import Translation
- t = Translation( entry_point )
- t.annotate(); t.rtype()
- f = t.compile_c()
- f()
- print( 'subprocess exit' )
- else:
- process = subprocess.Popen( 'python %s --pypy' %sys.argv[0], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0, shell=True )
- write = process.stdin
- read = process.stdout
- print( 'read pipe', read )
- print( 'read write', write )
- glib.timeout_add( 33, loop )
- _gtk.main()
- print( 'toplevel exit' )
Advertisement
Add Comment
Please, Sign In to add comment