Author: pfg Date: Fri Jul 27 18:30:00 2012 New Revision: 1366479 URL: http://svn.apache.org/viewvc?rev=1366479&view=rev Log: Improve portability of pyuno python scripts.
Proper indentation is critical in Python: the reindent.py script made some cleanups. Running the 2to3 script with specific options to disabling the next, unicode, and imports fixers further enhance portability. pyuno is not yet Python 3 ready but these semiautomatic changes make things much easier. Modified: incubator/ooo/trunk/main/pyuno/demo/biblioaccess.py incubator/ooo/trunk/main/pyuno/demo/hello_world_comp.py incubator/ooo/trunk/main/pyuno/demo/ooextract.py incubator/ooo/trunk/main/pyuno/demo/swritercomp.py incubator/ooo/trunk/main/pyuno/demo/swritercompclient.py incubator/ooo/trunk/main/pyuno/source/loader/pythonloader.py incubator/ooo/trunk/main/pyuno/source/module/uno.py incubator/ooo/trunk/main/pyuno/source/module/unohelper.py Modified: incubator/ooo/trunk/main/pyuno/demo/biblioaccess.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/demo/biblioaccess.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/demo/biblioaccess.py (original) +++ incubator/ooo/trunk/main/pyuno/demo/biblioaccess.py Fri Jul 27 18:30:00 2012 @@ -26,9 +26,9 @@ from com.sun.star.sdb.CommandType import def main(): connectionString = "socket,host=localhost,port=2002" - + url = "uno:"+connectionString + ";urp;StarOffice.ComponentContext" - + localCtx = uno.getComponentContext() localSmgr = localCtx.ServiceManager resolver = localSmgr.createInstanceWithContext( @@ -43,12 +43,12 @@ def main(): rowset.execute(); - print "Identifier\tAuthor" + print("Identifier\tAuthor") id = rowset.findColumn( "IDENTIFIER" ) author = rowset.findColumn( "AUTHOR" ) while rowset.next(): - print rowset.getString( id ) + "\t" + repr( rowset.getString( author ) ) + print(rowset.getString( id ) + "\t" + repr( rowset.getString( author ) )) rowset.dispose(); Modified: incubator/ooo/trunk/main/pyuno/demo/hello_world_comp.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/demo/hello_world_comp.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/demo/hello_world_comp.py (original) +++ incubator/ooo/trunk/main/pyuno/demo/hello_world_comp.py Fri Jul 27 18:30:00 2012 @@ -30,32 +30,32 @@ class HelloWorldJob( unohelper.Base, XJo def __init__( self, ctx ): # store the component context for later use self.ctx = ctx - + def trigger( self, args ): # note: args[0] == "HelloWorld", see below config settings - + # retrieve the desktop object desktop = self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", self.ctx ) - + # get current document model model = desktop.getCurrentComponent() - # access the document's text property - text = model.Text + # access the document's text property + text = model.Text - # create a cursor - cursor = text.createTextCursor() + # create a cursor + cursor = text.createTextCursor() - # insert the text into the document - text.insertString( cursor, "Hello World", 0 ) + # insert the text into the document + text.insertString( cursor, "Hello World", 0 ) # pythonloader looks for a static g_ImplementationHelper variable g_ImplementationHelper = unohelper.ImplementationHelper() -# +# g_ImplementationHelper.addImplementation( \ - HelloWorldJob, # UNO object class - "org.openoffice.comp.pyuno.demo.HelloWorld", # implemenation name - ("com.sun.star.task.Job",),) # list of implemented services - # (the only service) + HelloWorldJob, # UNO object class + "org.openoffice.comp.pyuno.demo.HelloWorld", # implemenation name + ("com.sun.star.task.Job",),) # list of implemented services + # (the only service) Modified: incubator/ooo/trunk/main/pyuno/demo/ooextract.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/demo/ooextract.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/demo/ooextract.py (original) +++ incubator/ooo/trunk/main/pyuno/demo/ooextract.py Fri Jul 27 18:30:00 2012 @@ -30,18 +30,18 @@ from com.sun.star.uno import Exception a from com.sun.star.io import IOException,XInputStream, XOutputStream class OutputStream( Base, XOutputStream ): - def __init__( self ): - self.closed = 0 - - def closeOutput(self): - self.closed = 1 - - def writeBytes( self, seq ): - sys.stdout.write( seq.value ) - - def flush( self ): - pass - + def __init__( self ): + self.closed = 0 + + def closeOutput(self): + self.closed = 1 + + def writeBytes( self, seq ): + sys.stdout.write( seq.value ) + + def flush( self ): + pass + def main(): retVal = 0 @@ -60,12 +60,12 @@ def main(): url = "uno:" + a + ";urp;StarOffice.ComponentContext" if o == "--html": filterName = "HTML (StarWriter)" - - print filterName + + print(filterName) if not len( args ): - usage() - sys.exit() - + usage() + sys.exit() + ctxLocal = uno.getComponentContext() smgrLocal = ctxLocal.ServiceManager @@ -90,25 +90,25 @@ def main(): raise UnoException( "Couldn't open stream for unknown reason", None ) doc.storeToURL("private:stream",outProps) - except IOException, e: + except IOException as e: sys.stderr.write( "Error during conversion: " + e.Message + "\n" ) retVal = 1 - except UnoException, e: + except UnoException as e: sys.stderr.write( "Error ("+repr(e.__class__)+") during conversion:" + e.Message + "\n" ) retVal = 1 if doc: doc.dispose() - except UnoException, e: + except UnoException as e: sys.stderr.write( "Error ("+repr(e.__class__)+") :" + e.Message + "\n" ) retVal = 1 - except getopt.GetoptError,e: + except getopt.GetoptError as e: sys.stderr.write( str(e) + "\n" ) usage() retVal = 1 sys.exit(retVal) - + def usage(): sys.stderr.write( "usage: ooextract.py --help |\n"+ " [-c <connection-string> | --connection-string=<connection-string>\n"+ @@ -127,4 +127,4 @@ def usage(): " Instead of the text filter, the writer html filter is used\n" ) -main() +main() Modified: incubator/ooo/trunk/main/pyuno/demo/swritercomp.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/demo/swritercomp.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/demo/swritercomp.py (original) +++ incubator/ooo/trunk/main/pyuno/demo/swritercomp.py Fri Jul 27 18:30:00 2012 @@ -42,92 +42,92 @@ def insertTextIntoCell( table, cellName, # implementing the interface com.sun.star.lang.XMain # unohelper.Base implements the XTypeProvider interface class SWriterComp(XMain,unohelper.Base): - def __init__( self, ctx ): - self.ctx = ctx + def __init__( self, ctx ): + self.ctx = ctx - # implementation for XMain.run( [in] sequence< any > ) - def run( self,args ): + # implementation for XMain.run( [in] sequence< any > ) + def run( self,args ): - ctx = self.ctx - smgr = ctx.ServiceManager - desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) + ctx = self.ctx + smgr = ctx.ServiceManager + desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) - # open a writer document - doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () ) + # open a writer document + doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () ) - text = doc.Text - cursor = text.createTextCursor() - text.insertString( cursor, "The first line in the newly created text document.\n", 0 ) - text.insertString( cursor, "Now we are in the second line\n" , 0 ) + text = doc.Text + cursor = text.createTextCursor() + text.insertString( cursor, "The first line in the newly created text document.\n", 0 ) + text.insertString( cursor, "Now we are in the second line\n" , 0 ) - # create a text table - table = doc.createInstance( "com.sun.star.text.TextTable" ) + # create a text table + table = doc.createInstance( "com.sun.star.text.TextTable" ) - # with 4 rows and 4 columns - table.initialize( 4,4) + # with 4 rows and 4 columns + table.initialize( 4,4) - text.insertTextContent( cursor, table, 0 ) - rows = table.Rows + text.insertTextContent( cursor, table, 0 ) + rows = table.Rows - table.setPropertyValue( "BackTransparent", uno.Bool(0) ) - table.setPropertyValue( "BackColor", 13421823 ) - row = rows.getByIndex(0) - row.setPropertyValue( "BackTransparent", uno.Bool(0) ) - row.setPropertyValue( "BackColor", 6710932 ) + table.setPropertyValue( "BackTransparent", uno.Bool(0) ) + table.setPropertyValue( "BackColor", 13421823 ) + row = rows.getByIndex(0) + row.setPropertyValue( "BackTransparent", uno.Bool(0) ) + row.setPropertyValue( "BackColor", 6710932 ) - textColor = 16777215 + textColor = 16777215 - insertTextIntoCell( table, "A1", "FirstColumn", textColor ) - insertTextIntoCell( table, "B1", "SecondColumn", textColor ) - insertTextIntoCell( table, "C1", "ThirdColumn", textColor ) - insertTextIntoCell( table, "D1", "SUM", textColor ) + insertTextIntoCell( table, "A1", "FirstColumn", textColor ) + insertTextIntoCell( table, "B1", "SecondColumn", textColor ) + insertTextIntoCell( table, "C1", "ThirdColumn", textColor ) + insertTextIntoCell( table, "D1", "SUM", textColor ) - values = ( (22.5,21.5,121.5), - (5615.3,615.3,-615.3), - (-2315.7,315.7,415.7) ) - table.getCellByName("A2").setValue(22.5) - table.getCellByName("B2").setValue(5615.3) - table.getCellByName("C2").setValue(-2315.7) - table.getCellByName("D2").setFormula("sum <A2:C2>") + values = ( (22.5,21.5,121.5), + (5615.3,615.3,-615.3), + (-2315.7,315.7,415.7) ) + table.getCellByName("A2").setValue(22.5) + table.getCellByName("B2").setValue(5615.3) + table.getCellByName("C2").setValue(-2315.7) + table.getCellByName("D2").setFormula("sum <A2:C2>") - table.getCellByName("A3").setValue(21.5) - table.getCellByName("B3").setValue(615.3) - table.getCellByName("C3").setValue(-315.7) - table.getCellByName("D3").setFormula("sum <A3:C3>") + table.getCellByName("A3").setValue(21.5) + table.getCellByName("B3").setValue(615.3) + table.getCellByName("C3").setValue(-315.7) + table.getCellByName("D3").setFormula("sum <A3:C3>") - table.getCellByName("A4").setValue(121.5) - table.getCellByName("B4").setValue(-615.3) - table.getCellByName("C4").setValue(415.7) - table.getCellByName("D4").setFormula("sum <A4:C4>") + table.getCellByName("A4").setValue(121.5) + table.getCellByName("B4").setValue(-615.3) + table.getCellByName("C4").setValue(415.7) + table.getCellByName("D4").setFormula("sum <A4:C4>") - cursor.setPropertyValue( "CharColor", 255 ) - cursor.setPropertyValue( "CharShadowed", uno.Bool(1) ) + cursor.setPropertyValue( "CharColor", 255 ) + cursor.setPropertyValue( "CharShadowed", uno.Bool(1) ) - text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) - text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 ) - text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 ) + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) - textFrame = doc.createInstance( "com.sun.star.text.TextFrame" ) - textFrame.setSize( Size(15000,400)) - textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER ) + textFrame = doc.createInstance( "com.sun.star.text.TextFrame" ) + textFrame.setSize( Size(15000,400)) + textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER ) - text.insertTextContent( cursor, textFrame, 0 ) + text.insertTextContent( cursor, textFrame, 0 ) - textInTextFrame = textFrame.getText() - cursorInTextFrame = textInTextFrame.createTextCursor() - textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 ) - textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0) - text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + textInTextFrame = textFrame.getText() + cursorInTextFrame = textInTextFrame.createTextCursor() + textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 ) + textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0) + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) - cursor.setPropertyValue( "CharColor", 65536 ) - cursor.setPropertyValue( "CharShadowed", uno.Bool(0) ) + cursor.setPropertyValue( "CharColor", 65536 ) + cursor.setPropertyValue( "CharShadowed", uno.Bool(0) ) - text.insertString( cursor, " That's all for now !!" , 0 ) - return 0 + text.insertString( cursor, " That's all for now !!" , 0 ) + return 0 # pythonloader looks for a static g_ImplementationHelper variable g_ImplementationHelper = unohelper.ImplementationHelper() g_ImplementationHelper.addImplementation( \ - SWriterComp,"org.openoffice.comp.pyuno.swriter",("org.openoffice.demo.SWriter",),) + SWriterComp,"org.openoffice.comp.pyuno.swriter",("org.openoffice.demo.SWriter",),) Modified: incubator/ooo/trunk/main/pyuno/demo/swritercompclient.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/demo/swritercompclient.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/demo/swritercompclient.py (original) +++ incubator/ooo/trunk/main/pyuno/demo/swritercompclient.py Fri Jul 27 18:30:00 2012 @@ -24,11 +24,10 @@ import uno localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext( - "com.sun.star.bridge.UnoUrlResolver", localContext ) + "com.sun.star.bridge.UnoUrlResolver", localContext ) remoteContext = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" ) remoteSmgr = remoteContext.ServiceManager pyComp = remoteSmgr.createInstanceWithContext( "org.openoffice.demo.SWriter" , remoteContext ) pyComp.run( (), ) - Modified: incubator/ooo/trunk/main/pyuno/source/loader/pythonloader.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/source/loader/pythonloader.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/source/loader/pythonloader.py (original) +++ incubator/ooo/trunk/main/pyuno/source/loader/pythonloader.py Fri Jul 27 18:30:00 2012 @@ -34,112 +34,110 @@ g_supportedServices = "com.sun.star.loa g_implementationName = "org.openoffice.comp.pyuno.Loader" # referenced by the native C++ loader ! def splitUrl( url ): - nColon = url.find( ":" ) - if -1 == nColon: - raise RuntimeException( "PythonLoader: No protocol in url " + url, None ) - return url[0:nColon], url[nColon+1:len(url)] + nColon = url.find( ":" ) + if -1 == nColon: + raise RuntimeException( "PythonLoader: No protocol in url " + url, None ) + return url[0:nColon], url[nColon+1:len(url)] g_loadedComponents = {} def checkForPythonPathBesideComponent( url ): - path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); - if DEBUG == 1: - print "checking for existence of " + encfile( path ) - if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: - if DEBUG == 1: - print "adding " + encfile( path ) + " to sys.path" - sys.path.append( path ) - - path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); - if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: - if DEBUG == 1: - print "adding " + encfile( path ) + " to sys.path" - sys.path.append( path ) + path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); + if DEBUG == 1: + print("checking for existence of " + encfile( path )) + if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: + if DEBUG == 1: + print("adding " + encfile( path ) + " to sys.path") + sys.path.append( path ) + + path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); + if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: + if DEBUG == 1: + print("adding " + encfile( path ) + " to sys.path") + sys.path.append( path ) def encfile(uni): return uni.encode( sys.getfilesystemencoding()) class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): - def __init__(self, ctx ): - if DEBUG: - print "pythonloader.Loader ctor" - self.ctx = ctx - - def getModuleFromUrl( self, url ): - if DEBUG: - print "pythonloader: interpreting url " +url - protocol, dependent = splitUrl( url ) - if "vnd.sun.star.expand" == protocol: - exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) - url = exp.expandMacros(dependent) - protocol,dependent = splitUrl( url ) - - if DEBUG: - print "pythonloader: after expansion " +protocol +":" + dependent - - try: - if "file" == protocol: - # remove \..\ sequence, which may be useful e.g. in the build env - url = unohelper.absolutize( url, url ) - - # did we load the module already ? - mod = g_loadedComponents.get( url ) - if not mod: - mod = imp.new_module("uno_component") - - # check for pythonpath.zip beside .py files - checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) - - # read the file - filename = unohelper.fileUrlToSystemPath( url ) - fileHandle = file( filename ) - src = fileHandle.read().replace("\r","") - if not src.endswith( "\n" ): - src = src + "\n" - - # compile and execute the module - codeobject = compile( src, encfile(filename), "exec" ) - exec codeobject in mod.__dict__ - mod.__file__ = encfile(filename) - g_loadedComponents[url] = mod - return mod - elif "vnd.openoffice.pymodule" == protocol: - return __import__( dependent ) - else: - raise RuntimeException( "PythonLoader: Unknown protocol " + - protocol + " in url " +url, self ) - except ImportError, e: - raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) - return None - - def activate( self, implementationName, dummy, locationUrl, regKey ): - if DEBUG: - print "pythonloader.Loader.activate" - - mod = self.getModuleFromUrl( locationUrl ) - implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) - if implHelper == None: - return mod.getComponentFactory( implementationName, self.ctx.ServiceManager, regKey ) - else: - return implHelper.getComponentFactory( implementationName,regKey,self.ctx.ServiceManager) - - def writeRegistryInfo( self, regKey, dummy, locationUrl ): - if DEBUG: - print "pythonloader.Loader.writeRegistryInfo" - - mod = self.getModuleFromUrl( locationUrl ) - implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) - if implHelper == None: - return mod.writeRegistryInfo( self.ctx.ServiceManager, regKey ) - else: - return implHelper.writeRegistryInfo( regKey, self.ctx.ServiceManager ) + def __init__(self, ctx ): + if DEBUG: + print("pythonloader.Loader ctor") + self.ctx = ctx + + def getModuleFromUrl( self, url ): + if DEBUG: + print("pythonloader: interpreting url " +url) + protocol, dependent = splitUrl( url ) + if "vnd.sun.star.expand" == protocol: + exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) + url = exp.expandMacros(dependent) + protocol,dependent = splitUrl( url ) + + if DEBUG: + print("pythonloader: after expansion " +protocol +":" + dependent) + + try: + if "file" == protocol: + # remove \..\ sequence, which may be useful e.g. in the build env + url = unohelper.absolutize( url, url ) + + # did we load the module already ? + mod = g_loadedComponents.get( url ) + if not mod: + mod = imp.new_module("uno_component") + + # check for pythonpath.zip beside .py files + checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) + + # read the file + filename = unohelper.fileUrlToSystemPath( url ) + fileHandle = file( filename ) + src = fileHandle.read().replace("\r","") + if not src.endswith( "\n" ): + src = src + "\n" + + # compile and execute the module + codeobject = compile( src, encfile(filename), "exec" ) + exec(codeobject, mod.__dict__) + mod.__file__ = encfile(filename) + g_loadedComponents[url] = mod + return mod + elif "vnd.openoffice.pymodule" == protocol: + return __import__( dependent ) + else: + raise RuntimeException( "PythonLoader: Unknown protocol " + + protocol + " in url " +url, self ) + except ImportError as e: + raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) + return None + + def activate( self, implementationName, dummy, locationUrl, regKey ): + if DEBUG: + print("pythonloader.Loader.activate") + + mod = self.getModuleFromUrl( locationUrl ) + implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) + if implHelper == None: + return mod.getComponentFactory( implementationName, self.ctx.ServiceManager, regKey ) + else: + return implHelper.getComponentFactory( implementationName,regKey,self.ctx.ServiceManager) + + def writeRegistryInfo( self, regKey, dummy, locationUrl ): + if DEBUG: + print("pythonloader.Loader.writeRegistryInfo") + + mod = self.getModuleFromUrl( locationUrl ) + implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) + if implHelper == None: + return mod.writeRegistryInfo( self.ctx.ServiceManager, regKey ) + else: + return implHelper.writeRegistryInfo( regKey, self.ctx.ServiceManager ) - def getImplementationName( self ): - return g_implementationName - - def supportsService( self, ServiceName ): - return ServiceName in self.serviceNames - - def getSupportedServiceNames( self ): - return g_supportedServices + def getImplementationName( self ): + return g_implementationName + def supportsService( self, ServiceName ): + return ServiceName in self.serviceNames + def getSupportedServiceNames( self ): + return g_supportedServices Modified: incubator/ooo/trunk/main/pyuno/source/module/uno.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/source/module/uno.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/source/module/uno.py (original) +++ incubator/ooo/trunk/main/pyuno/source/module/uno.py Fri Jul 27 18:30:00 2012 @@ -31,8 +31,8 @@ _g_delegatee = __builtin__.__dict__["__i def getComponentContext(): """ returns the UNO component context, that was used to initialize the python runtime. - """ - return _g_ctx + """ + return _g_ctx def getConstantByName( constant ): "Looks up the value of a idl constant by giving its explicit name" @@ -41,7 +41,7 @@ def getConstantByName( constant ): def getTypeByName( typeName): """ returns a uno.Type instance of the type given by typeName. In case the type does not exist, a com.sun.star.uno.RuntimeException is raised. - """ + """ return pyuno.getTypeByName( typeName ) def createUnoStruct( typeName, *args ): @@ -70,7 +70,7 @@ def isInterface( obj ): def generateUuid(): "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h " - return pyuno.generateUuid() + return pyuno.generateUuid() def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" @@ -100,9 +100,9 @@ def setCurrentContext( newContext ): """ return pyuno.setCurrentContext( newContext ) - + class Enum: - "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" + "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" #typeName the name of the enum as a string #value the actual value of this enum as a string def __init__(self,typeName, value): @@ -138,7 +138,7 @@ class Type: return self.typeName.__hash__() class Bool(object): - """Represents a UNO boolean, use an instance of this class to explicitly + """Represents a UNO boolean, use an instance of this class to explicitly pass a boolean to UNO. Note: This class is deprecated. Use python's True and False directly instead """ @@ -161,13 +161,13 @@ class Char: def __repr__(self): return "<Char instance %s>" % (self.value, ) - + def __eq__(self, that): if isinstance(that, (str, unicode)): if len(that) > 1: return False return self.value == that[0] - if isinstance(that, Char): + if isinstance(that, Char): return self.value == that.value return False @@ -178,12 +178,12 @@ class Char: # def __repr__(self): # return "<ByteSequence instance %s>" % str.__repr__(self) - # for a little bit compatitbility; setting value is not possible as + # for a little bit compatibility; setting value is not possible as # strings are immutable # def _get_value(self): # return self # -# value = property(_get_value) +# value = property(_get_value) class ByteSequence: def __init__(self, value): @@ -236,7 +236,7 @@ class Any: def invoke( object, methodname, argTuple ): "use this function to pass exactly typed anys to the callee (using uno.Any)" return pyuno.invoke( object, methodname, argTuple ) - + #--------------------------------------------------------------------------------------- # don't use any functions beyond this point, private section, likely to change #--------------------------------------------------------------------------------------- @@ -254,56 +254,56 @@ def _uno_import( name, *optargs, **kwarg mod = None d = sys.modules for x in modnames: - if d.has_key(x): - mod = d[x] + if x in d: + mod = d[x] else: - mod = pyuno.__class__(x) # How to create a module ?? + mod = pyuno.__class__(x) # How to create a module ?? d = mod.__dict__ RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" ) for x in fromlist: - if not d.has_key(x): - if x.startswith( "typeOf" ): - try: - d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) - except RuntimeException,e: - raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) - else: - try: - # check for structs, exceptions or interfaces - d[x] = pyuno.getClass( name + "." + x ) - except RuntimeException,e: - # check for enums + if x not in d: + if x.startswith( "typeOf" ): try: - d[x] = Enum( name , x ) - except RuntimeException,e2: - # check for constants - try: - d[x] = getConstantByName( name + "." + x ) - except RuntimeException,e3: - # no known uno type ! - raise ImportError( "type "+ name + "." +x + " is unknown" ) + d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) + except RuntimeException as e: + raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) + else: + try: + # check for structs, exceptions or interfaces + d[x] = pyuno.getClass( name + "." + x ) + except RuntimeException as e: + # check for enums + try: + d[x] = Enum( name , x ) + except RuntimeException as e2: + # check for constants + try: + d[x] = getConstantByName( name + "." + x ) + except RuntimeException as e3: + # no known uno type ! + raise ImportError( "type "+ name + "." +x + " is unknown" ) return mod -# hook into the __import__ chain +# hook into the __import__ chain __builtin__.__dict__["__import__"] = _uno_import - + # private function, don't use def _impl_extractName(name): - r = range (len(name)-1,0,-1) + r = list(range(len(name)-1,0,-1)) for i in r: if name[i] == ".": - name = name[i+1:len(name)] - break - return name + name = name[i+1:len(name)] + break + return name # private, referenced from the pyuno shared library def _uno_struct__init__(self,*args): if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ : - self.__dict__["value"] = args[0] + self.__dict__["value"] = args[0] else: - self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args) - + self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args) + # private, referenced from the pyuno shared library def _uno_struct__getattr__(self,name): return __builtin__.getattr(self.__dict__["value"],name) @@ -315,14 +315,14 @@ def _uno_struct__setattr__(self,name,val # private, referenced from the pyuno shared library def _uno_struct__repr__(self): return repr(self.__dict__["value"]) - + def _uno_struct__str__(self): return str(self.__dict__["value"]) # private, referenced from the pyuno shared library def _uno_struct__eq__(self,cmp): if hasattr(cmp,"value"): - return self.__dict__["value"] == cmp.__dict__["value"] + return self.__dict__["value"] == cmp.__dict__["value"] return False # referenced from pyuno shared lib and pythonscript.py @@ -330,7 +330,7 @@ def _uno_extract_printable_stacktrace( t mod = None try: mod = __import__("traceback") - except ImportError,e: + except ImportError as e: pass ret = "" if mod: Modified: incubator/ooo/trunk/main/pyuno/source/module/unohelper.py URL: http://svn.apache.org/viewvc/incubator/ooo/trunk/main/pyuno/source/module/unohelper.py?rev=1366479&r1=1366478&r2=1366479&view=diff ============================================================================== --- incubator/ooo/trunk/main/pyuno/source/module/unohelper.py (original) +++ incubator/ooo/trunk/main/pyuno/source/module/unohelper.py Fri Jul 27 18:30:00 2012 @@ -72,7 +72,7 @@ def _propertymode_to_str( mode ): if PROP_ATTR_MAYBEVOID & mode: ret = ret + "maybevoid " return ret.rstrip() - + def inspect( obj , out ): if isinstance( obj, uno.Type ) or \ isinstance( obj, uno.Char ) or \ @@ -102,7 +102,7 @@ def inspect( obj , out ): out.write( " " + ii.typeName + "\n" ) else: out.write( " unknown\n" ) - + access = introspection.inspect( obj ) methods = access.getMethods( METHOD_CONCEPT_ALL ) out.write( "Methods:\n" ) @@ -126,56 +126,56 @@ def createSingleServiceFactory( clazz, i return _FactoryHelper_( clazz, implementationName, serviceNames ) class _ImplementationHelperEntry: - def __init__(self, ctor,serviceNames): - self.ctor = ctor - self.serviceNames = serviceNames - + def __init__(self, ctor,serviceNames): + self.ctor = ctor + self.serviceNames = serviceNames + class ImplementationHelper: - def __init__(self): - self.impls = {} - - def addImplementation( self, ctor, implementationName, serviceNames ): - self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) - - def writeRegistryInfo( self, regKey, smgr ): - for i in self.impls.items(): - keyName = "/"+ i[0] + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in i[1].serviceNames: - key.createKey( serviceName ) - return 1 - - def getComponentFactory( self, implementationName , regKey, smgr ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) - - def getSupportedServiceNames( self, implementationName ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return entry.serviceNames - - def supportsService( self, implementationName, serviceName ): - entry = self.impls.get( implementationName,None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown", None ) - return serviceName in entry.serviceNames + def __init__(self): + self.impls = {} + + def addImplementation( self, ctor, implementationName, serviceNames ): + self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) + + def writeRegistryInfo( self, regKey, smgr ): + for i in list(self.impls.items()): + keyName = "/"+ i[0] + "/UNO/SERVICES" + key = regKey.createKey( keyName ) + for serviceName in i[1].serviceNames: + key.createKey( serviceName ) + return 1 + + def getComponentFactory( self, implementationName , regKey, smgr ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) + + def getSupportedServiceNames( self, implementationName ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return entry.serviceNames + + def supportsService( self, implementationName, serviceName ): + entry = self.impls.get( implementationName,None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown", None ) + return serviceName in entry.serviceNames + - class ImplementationEntry: - def __init__(self, implName, supportedServices, clazz ): - self.implName = implName - self.supportedServices = supportedServices - self.clazz = clazz + def __init__(self, implName, supportedServices, clazz ): + self.implName = implName + self.supportedServices = supportedServices + self.clazz = clazz def writeRegistryInfoHelper( smgr, regKey, seqEntries ): for entry in seqEntries: keyName = "/"+ entry.implName + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in entry.supportedServices: - key.createKey( serviceName ) + key = regKey.createKey( keyName ) + for serviceName in entry.supportedServices: + key.createKey( serviceName ) def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" @@ -188,11 +188,11 @@ def fileUrlToSystemPath( url ): def absolutize( path, relativeUrl ): "returns an absolute file url from the given urls" return pyuno.absolutize( path, relativeUrl ) - + def getComponentFactoryHelper( implementationName, smgr, regKey, seqEntries ): for x in seqEntries: - if x.implName == implementationName: - return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) + if x.implName == implementationName: + return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ): smgr = contextRuntime.ServiceManager @@ -204,56 +204,56 @@ def addComponentsToContext( toBeExtended # create a temporary registry for componentUrl in componentUrls: reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime ) - reg.open( "", 0, 1 ) + reg.open( "", 0, 1 ) if not isWin and componentUrl.endswith( ".uno" ): # still allow platform independent naming if isMac: - componentUrl = componentUrl + ".dylib" + componentUrl = componentUrl + ".dylib" else: - componentUrl = componentUrl + ".so" + componentUrl = componentUrl + ".so" + + implReg.registerImplementation( loaderName,componentUrl, reg ) + rootKey = reg.getRootKey() + implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) + implNames = implementationKey.getKeyNames() + extSMGR = toBeExtendedContext.ServiceManager + for x in implNames: + fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) + extSMGR.insert( fac ) + reg.close() - implReg.registerImplementation( loaderName,componentUrl, reg ) - rootKey = reg.getRootKey() - implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) - implNames = implementationKey.getKeyNames() - extSMGR = toBeExtendedContext.ServiceManager - for x in implNames: - fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) - extSMGR.insert( fac ) - reg.close() - # never shrinks ! _g_typeTable = {} def _unohelper_getHandle( self): - ret = None - if _g_typeTable.has_key( self.__class__ ): - ret = _g_typeTable[self.__class__] - else: - names = {} - traverse = list(self.__class__.__bases__) - while len( traverse ) > 0: - item = traverse.pop() - bases = item.__bases__ - if uno.isInterface( item ): - names[item.__pyunointerface__] = None - elif len(bases) > 0: - # the "else if", because we only need the most derived interface - traverse = traverse + list(bases)# - - lst = names.keys() - types = [] - for x in lst: - t = uno.getTypeByName( x ) - types.append( t ) - - ret = tuple(types) , uno.generateUuid() - _g_typeTable[self.__class__] = ret - return ret - + ret = None + if self.__class__ in _g_typeTable: + ret = _g_typeTable[self.__class__] + else: + names = {} + traverse = list(self.__class__.__bases__) + while len( traverse ) > 0: + item = traverse.pop() + bases = item.__bases__ + if uno.isInterface( item ): + names[item.__pyunointerface__] = None + elif len(bases) > 0: + # the "else if", because we only need the most derived interface + traverse = traverse + list(bases)# + + lst = list(names.keys()) + types = [] + for x in lst: + t = uno.getTypeByName( x ) + types.append( t ) + + ret = tuple(types) , uno.generateUuid() + _g_typeTable[self.__class__] = ret + return ret + class Base(XTypeProvider): - def getTypes( self ): - return _unohelper_getHandle( self )[0] - def getImplementationId(self): - return _unohelper_getHandle( self )[1] + def getTypes( self ): + return _unohelper_getHandle( self )[0] + def getImplementationId(self): + return _unohelper_getHandle( self )[1] class CurrentContext(XCurrentContext, Base ): """a current context implementation, which first does a lookup in the given @@ -271,28 +271,27 @@ class CurrentContext(XCurrentContext, Ba return self.oldContext.getValueByName( name ) else: return None - + # ------------------------------------------------- # implementation details # ------------------------------------------------- class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ): - def __init__( self, clazz, implementationName, serviceNames ): - self.clazz = clazz - self.implementationName = implementationName - self.serviceNames = serviceNames - - def getImplementationName( self ): - return self.implementationName - - def supportsService( self, ServiceName ): - return ServiceName in self.serviceNames - - def getSupportedServiceNames( self ): - return self.serviceNames - - def createInstanceWithContext( self, context ): - return self.clazz( context ) - - def createInstanceWithArgumentsAndContext( self, args, context ): - return self.clazz( context, *args ) - + def __init__( self, clazz, implementationName, serviceNames ): + self.clazz = clazz + self.implementationName = implementationName + self.serviceNames = serviceNames + + def getImplementationName( self ): + return self.implementationName + + def supportsService( self, ServiceName ): + return ServiceName in self.serviceNames + + def getSupportedServiceNames( self ): + return self.serviceNames + + def createInstanceWithContext( self, context ): + return self.clazz( context ) + + def createInstanceWithArgumentsAndContext( self, args, context ): + return self.clazz( context, *args )