Kaydet (Commit) 2f2c34da authored tarafından Pedro Giffuni's avatar Pedro Giffuni

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