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