1#************************************************************** 2# 3# Licensed to the Apache Software Foundation (ASF) under one 4# or more contributor license agreements. See the NOTICE file 5# distributed with this work for additional information 6# regarding copyright ownership. The ASF licenses this file 7# to you under the Apache License, Version 2.0 (the 8# "License"); you may not use this file except in compliance 9# with the License. You may obtain a copy of the License at 10# 11# http://www.apache.org/licenses/LICENSE-2.0 12# 13# Unless required by applicable law or agreed to in writing, 14# software distributed under the License is distributed on an 15# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16# KIND, either express or implied. See the License for the 17# specific language governing permissions and limitations 18# under the License. 19# 20#************************************************************** 21import sys 22 23import pyuno 24 25try: 26 import __builtin__ as builtin 27except ImportError: 28 import builtins 29 30try: 31 unicode 32except NameError: 33 unicode = str 34 35import socket # since on Windows sal3.dll no longer calls WSAStartup 36 37# all functions and variables starting with a underscore (_) must be considered private 38# and can be changed at any time. Don't use them 39_g_ctx = pyuno.getComponentContext( ) 40_g_delegatee = builtin.__dict__["__import__"] 41 42def getComponentContext(): 43 """ returns the UNO component context, that was used to initialize the python runtime. 44 """ 45 return _g_ctx 46 47def getConstantByName( constant ): 48 "Looks up the value of a idl constant by giving its explicit name" 49 return pyuno.getConstantByName( constant ) 50 51def getTypeByName( typeName): 52 """ returns a uno.Type instance of the type given by typeName. In case the 53 type does not exist, a com.sun.star.uno.RuntimeException is raised. 54 """ 55 return pyuno.getTypeByName( typeName ) 56 57def createUnoStruct( typeName, *args ): 58 """creates a uno struct or exception given by typeName. The parameter args may 59 1) be empty. In this case, you get a default constructed uno structure. 60 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) ) 61 2) be a sequence with exactly one element, that contains an instance of typeName. 62 In this case, a copy constructed instance of typeName is returned 63 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) ) 64 3) be a sequence, where the length of the sequence must match the number of 65 elements within typeName (e.g. 66 createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The 67 elements with in the sequence must match the type of each struct element, 68 otherwise an exception is thrown. 69 """ 70 return getClass(typeName)( *args ) 71 72def getClass( typeName ): 73 """returns the class of a concrete uno exception, struct or interface 74 """ 75 return pyuno.getClass(typeName) 76 77def isInterface( obj ): 78 """returns true, when obj is a class of a uno interface""" 79 return pyuno.isInterface( obj ) 80 81def generateUuid(): 82 "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h " 83 return pyuno.generateUuid() 84 85def systemPathToFileUrl( systemPath ): 86 "returns a file-url for the given system path" 87 return pyuno.systemPathToFileUrl( systemPath ) 88 89def fileUrlToSystemPath( url ): 90 "returns a system path (determined by the system, the python interpreter is running on)" 91 return pyuno.fileUrlToSystemPath( url ) 92 93def absolutize( path, relativeUrl ): 94 "returns an absolute file url from the given urls" 95 return pyuno.absolutize( path, relativeUrl ) 96 97def getCurrentContext(): 98 """Returns the currently valid current context. 99 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context 100 for an explanation on the current context concept 101 """ 102 return pyuno.getCurrentContext() 103 104def setCurrentContext( newContext ): 105 """Sets newContext as new uno current context. The newContext must 106 implement the XCurrentContext interface. The implemenation should 107 handle the desired properties and delegate unknown properties to the 108 old context. Ensure to reset the old one when you leave your stack ... 109 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context 110 """ 111 return pyuno.setCurrentContext( newContext ) 112 113 114class Enum: 115 "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" 116 #typeName the name of the enum as a string 117 #value the actual value of this enum as a string 118 def __init__(self,typeName, value): 119 self.typeName = typeName 120 self.value = value 121 pyuno.checkEnum( self ) 122 123 def __repr__(self): 124 return "<uno.Enum %s (%r)>" % (self.typeName, self.value) 125 126 def __eq__(self, that): 127 if not isinstance(that, Enum): 128 return False 129 return (self.typeName == that.typeName) and (self.value == that.value) 130 131class Type: 132 "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO" 133# typeName # Name of the UNO type 134# typeClass # python Enum of TypeClass, see com/sun/star/uno/TypeClass.idl 135 def __init__(self, typeName, typeClass): 136 self.typeName = typeName 137 self.typeClass = typeClass 138 pyuno.checkType(self) 139 def __repr__(self): 140 return "<Type instance %s (%r)>" % (self.typeName, self.typeClass) 141 142 def __eq__(self, that): 143 if not isinstance(that, Type): 144 return False 145 return self.typeClass == that.typeClass and self.typeName == that.typeName 146 147 def __hash__(self): 148 return self.typeName.__hash__() 149 150class Bool(object): 151 """Represents a UNO boolean, use an instance of this class to explicitly 152 pass a boolean to UNO. 153 Note: This class is deprecated. Use python's True and False directly instead 154 """ 155 def __new__(cls, value): 156 if isinstance(value, (str, unicode)) and value == "true": 157 return True 158 if isinstance(value, (str, unicode)) and value == "false": 159 return False 160 if value: 161 return True 162 return False 163 164class Char: 165 "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO" 166 # @param value pass a Unicode string with length 1 167 def __init__(self,value): 168 assert isinstance(value, unicode) 169 assert len(value) == 1 170 self.value=value 171 172 def __repr__(self): 173 return "<Char instance %s>" % (self.value, ) 174 175 def __eq__(self, that): 176 if isinstance(that, (str, unicode)): 177 if len(that) > 1: 178 return False 179 return self.value == that[0] 180 if isinstance(that, Char): 181 return self.value == that.value 182 return False 183 184class ByteSequence: 185 def __init__(self, value): 186 if isinstance(value, str): 187 self.value = value 188 elif isinstance(value, ByteSequence): 189 self.value = value.value 190 else: 191 raise TypeError("expected string or bytesequence") 192 193 def __repr__(self): 194 return "<ByteSequence instance '%s'>" % (self.value, ) 195 196 def __eq__(self, that): 197 if isinstance( that, ByteSequence): 198 return self.value == that.value 199 if isinstance(that, str): 200 return self.value == that 201 return False 202 203 def __len__(self): 204 return len(self.value) 205 206 def __getitem__(self, index): 207 return self.value[index] 208 209 def __iter__( self ): 210 return self.value.__iter__() 211 212 def __add__( self , b ): 213 if isinstance( b, str ): 214 return ByteSequence( self.value + b ) 215 elif isinstance( b, ByteSequence ): 216 return ByteSequence( self.value + b.value ) 217 raise TypeError( "expected string or ByteSequence as operand" ) 218 219 def __hash__( self ): 220 return self.value.hash() 221 222 223class Any: 224 "use only in connection with uno.invoke() to pass an explicit typed any" 225 def __init__(self, type, value ): 226 if isinstance( type, Type ): 227 self.type = type 228 else: 229 self.type = getTypeByName( type ) 230 self.value = value 231 232def invoke( object, methodname, argTuple ): 233 "use this function to pass exactly typed anys to the callee (using uno.Any)" 234 return pyuno.invoke( object, methodname, argTuple ) 235 236#--------------------------------------------------------------------------------------- 237# don't use any functions beyond this point, private section, likely to change 238#--------------------------------------------------------------------------------------- 239#def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ): 240def _uno_import( name, *optargs, **kwargs ): 241 try: 242# print "optargs = " + repr(optargs) 243 return _g_delegatee( name, *optargs, **kwargs ) 244 except ImportError: 245 # process optargs 246 globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):] 247 if not fromlist: 248 raise 249 modnames = name.split( "." ) 250 mod = None 251 d = sys.modules 252 for x in modnames: 253 if x in d: 254 mod = d[x] 255 else: 256 mod = pyuno.__class__(x) # How to create a module ?? 257 d = mod.__dict__ 258 259 RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" ) 260 for x in fromlist: 261 if x not in d: 262 if x.startswith( "typeOf" ): 263 try: 264 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) 265 except RuntimeException as e: 266 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) 267 else: 268 try: 269 # check for structs, exceptions or interfaces 270 d[x] = pyuno.getClass( name + "." + x ) 271 except RuntimeException as e: 272 # check for enums 273 try: 274 d[x] = Enum( name , x ) 275 except RuntimeException as e2: 276 # check for constants 277 try: 278 d[x] = getConstantByName( name + "." + x ) 279 except RuntimeException as e3: 280 # no known uno type ! 281 raise ImportError( "type "+ name + "." +x + " is unknown" ) 282 return mod 283 284# hook into the __import__ chain 285builtin.__dict__["__import__"] = _uno_import 286 287# private, referenced from the pyuno shared library 288def _uno_struct__init__(self,*args): 289 if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ : 290 self.__dict__["value"] = args[0] 291 else: 292 self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args) 293 294# private, referenced from the pyuno shared library 295def _uno_struct__getattr__(self,name): 296 return builtin.getattr(self.__dict__["value"],name) 297 298# private, referenced from the pyuno shared library 299def _uno_struct__setattr__(self,name,value): 300 return builtin.setattr(self.__dict__["value"],name,value) 301 302# private, referenced from the pyuno shared library 303def _uno_struct__repr__(self): 304 return repr(self.__dict__["value"]) 305 306def _uno_struct__str__(self): 307 return str(self.__dict__["value"]) 308 309# private, referenced from the pyuno shared library 310def _uno_struct__eq__(self,cmp): 311 if hasattr(cmp,"value"): 312 return self.__dict__["value"] == cmp.__dict__["value"] 313 return False 314 315# referenced from pyuno shared lib and pythonscript.py 316def _uno_extract_printable_stacktrace( trace ): 317 mod = None 318 try: 319 mod = __import__("traceback") 320 except ImportError as e: 321 pass 322 ret = "" 323 if mod: 324 lst = mod.extract_tb( trace ) 325 max = len(lst) 326 for j in range(max): 327 i = lst[max-j-1] 328 ret = ret + " " + str(i[0]) + ":" + \ 329 str(i[1]) + " in function " + \ 330 str(i[2]) + "() [" + str(i[3]) + "]\n" 331 else: 332 ret = "Couldn't import traceback module" 333 return ret 334