Version 4.2.0.1, tag libreoffice-4.2.0.1
[LibreOffice.git] / pyuno / source / module / pyuno_module.cxx
blob5513f0e051cea86a680999e3ded75a6011b7299d
1 /* -*- Mode: C++; eval:(c-set-style "bsd"); tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <config_features.h>
21 #include <config_folders.h>
23 #include "pyuno_impl.hxx"
25 #include <boost/unordered_map.hpp>
26 #include <utility>
28 #include <osl/module.hxx>
29 #include <osl/thread.h>
30 #include <osl/process.h>
31 #include <osl/file.hxx>
33 #include <typelib/typedescription.hxx>
35 #include <rtl/ustring.hxx>
36 #include <rtl/strbuf.hxx>
37 #include <rtl/ustrbuf.hxx>
38 #include <rtl/uuid.h>
39 #include <rtl/bootstrap.hxx>
41 #include <uno/current_context.hxx>
42 #include <cppuhelper/bootstrap.hxx>
44 #include <com/sun/star/reflection/XConstantTypeDescription.hpp>
45 #include <com/sun/star/reflection/XIdlReflection.hpp>
46 #include <com/sun/star/reflection/XIdlClass.hpp>
47 #include <com/sun/star/registry/InvalidRegistryException.hpp>
49 using osl::Module;
52 using com::sun::star::uno::Sequence;
53 using com::sun::star::uno::Reference;
54 using com::sun::star::uno::XInterface;
55 using com::sun::star::uno::Any;
56 using com::sun::star::uno::makeAny;
57 using com::sun::star::uno::UNO_QUERY;
58 using com::sun::star::uno::RuntimeException;
59 using com::sun::star::uno::TypeDescription;
60 using com::sun::star::uno::XComponentContext;
61 using com::sun::star::container::NoSuchElementException;
62 using com::sun::star::reflection::XIdlReflection;
63 using com::sun::star::reflection::XIdlClass;
64 using com::sun::star::script::XInvocation2;
66 using namespace pyuno;
68 namespace {
70 /**
71 @ index of the next to be used member in the initializer list !
73 // LEM TODO: export member names as keyword arguments in initialiser?
74 // Python supports very flexible variadic functions. By marking
75 // variables with one asterisk (e.g. *var) the given variable is
76 // defined to be a tuple of all the extra arguments. By marking
77 // variables with two asterisks (e.g. **var) the given variable is a
78 // dictionary of all extra keyword arguments; the keys are strings,
79 // which are the names that were used to identify the arguments. If
80 // they exist, these arguments must be the last one in the list.
82 class fillStructState
84 // Keyword arguments used
85 PyObject *used;
86 // Which structure members are initialised
87 boost::unordered_map <const OUString, bool, OUStringHash> initialised;
88 // How many positional arguments are consumed
89 // This is always the so-many first ones
90 sal_Int32 nPosConsumed;
92 public:
93 fillStructState()
94 : used (PyDict_New())
95 , initialised ()
96 , nPosConsumed (0)
98 if ( ! used )
99 throw RuntimeException("pyuno._createUnoStructHelper failed to create new dictionary", Reference< XInterface > ());
101 ~fillStructState()
103 Py_DECREF(used);
105 void setUsed(PyObject *key)
107 PyDict_SetItem(used, key, Py_True);
109 void setInitialised(OUString key, sal_Int32 pos = -1)
111 if (initialised[key])
113 OUStringBuffer buf;
114 buf.appendAscii( "pyuno._createUnoStructHelper: member '");
115 buf.append(key);
116 buf.appendAscii( "'");
117 if ( pos >= 0 )
119 buf.appendAscii( " at position ");
120 buf.append(pos);
122 buf.appendAscii( " initialised multiple times.");
123 throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface > ());
125 initialised[key] = true;
126 if ( pos >= 0 )
127 ++nPosConsumed;
129 bool isInitialised(OUString key)
131 return initialised[key];
133 PyObject *getUsed() const
135 return used;
137 sal_Int32 getCntConsumed() const
139 return nPosConsumed;
143 static void fillStruct(
144 const Reference< XInvocation2 > &inv,
145 typelib_CompoundTypeDescription *pCompType,
146 PyObject *initializer,
147 PyObject *kwinitializer,
148 fillStructState &state,
149 const Runtime &runtime) throw ( RuntimeException )
151 if( pCompType->pBaseTypeDescription )
152 fillStruct( inv, pCompType->pBaseTypeDescription, initializer, kwinitializer, state, runtime );
154 const sal_Int32 nMembers = pCompType->nMembers;
156 for( int i = 0 ; i < nMembers ; i ++ )
158 const OUString OUMemberName (pCompType->ppMemberNames[i]);
159 PyObject *pyMemberName =
160 PyStr_FromString(OUStringToOString(OUMemberName,
161 RTL_TEXTENCODING_UTF8).getStr());
162 if ( PyObject *element = PyDict_GetItem(kwinitializer, pyMemberName ) )
164 state.setInitialised(OUMemberName);
165 state.setUsed(pyMemberName);
166 Any a = runtime.pyObject2Any( element, ACCEPT_UNO_ANY );
167 inv->setValue( OUMemberName, a );
172 const int remainingPosInitialisers = PyTuple_Size(initializer) - state.getCntConsumed();
173 for( int i = 0 ; i < remainingPosInitialisers && i < nMembers ; i ++ )
175 const int tupleIndex = state.getCntConsumed();
176 const OUString pMemberName (pCompType->ppMemberNames[i]);
177 state.setInitialised(pMemberName, tupleIndex);
178 PyObject *element = PyTuple_GetItem( initializer, tupleIndex );
179 Any a = runtime.pyObject2Any( element, ACCEPT_UNO_ANY );
180 inv->setValue( pMemberName, a );
183 for ( int i = 0; i < nMembers ; ++i)
185 const OUString memberName (pCompType->ppMemberNames[i]);
186 if ( ! state.isInitialised( memberName ) )
188 OUStringBuffer buf;
189 buf.appendAscii( "pyuno._createUnoStructHelper: member '");
190 buf.append(memberName);
191 buf.appendAscii( "' of struct type '");
192 buf.append(pCompType->aBase.pTypeName);
193 buf.appendAscii( "' not given a value.");
194 throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface > ());
199 OUString getLibDir()
201 static OUString *pLibDir;
202 if( !pLibDir )
204 osl::MutexGuard guard( osl::Mutex::getGlobalMutex() );
205 if( ! pLibDir )
207 static OUString libDir;
209 // workarounds the $(ORIGIN) until it is available
210 if( Module::getUrlFromAddress(
211 reinterpret_cast< oslGenericFunction >(getLibDir), libDir ) )
213 libDir = OUString( libDir.getStr(), libDir.lastIndexOf('/' ) );
214 OUString name ( "PYUNOLIBDIR" );
215 rtl_bootstrap_set( name.pData, libDir.pData );
217 pLibDir = &libDir;
220 return *pLibDir;
223 void raisePySystemException( const char * exceptionType, const OUString & message )
225 OStringBuffer buf;
226 buf.append( "Error during bootstrapping uno (");
227 buf.append( exceptionType );
228 buf.append( "):" );
229 buf.append( OUStringToOString( message, osl_getThreadTextEncoding() ) );
230 PyErr_SetString( PyExc_SystemError, buf.makeStringAndClear().getStr() );
233 extern "C" {
235 static PyObject* getComponentContext(
236 SAL_UNUSED_PARAMETER PyObject*, SAL_UNUSED_PARAMETER PyObject*)
238 PyRef ret;
241 Reference<XComponentContext> ctx;
243 // getLibDir() must be called in order to set bootstrap variables correctly !
244 OUString path( getLibDir());
245 if( Runtime::isInitialized() )
247 Runtime runtime;
248 ctx = runtime.getImpl()->cargo->xContext;
250 else
252 // cppu::defaultBootstrap_InitialComponentContext expects
253 // command line arguments to be present
254 osl_setCommandArgs(0, 0); // fake it
256 OUString iniFile;
257 if( path.isEmpty() )
259 PyErr_SetString(
260 PyExc_RuntimeError, "osl_getUrlFromAddress fails, that's why I cannot find ini "
261 "file for bootstrapping python uno bridge\n" );
262 return NULL;
265 OUStringBuffer iniFileName;
266 iniFileName.append( path );
267 #if HAVE_FEATURE_MACOSX_MACLIKE_APP_STRUCTURE
268 iniFileName.appendAscii( "/../" LIBO_ETC_FOLDER );
269 #endif
270 iniFileName.appendAscii( "/" );
271 iniFileName.appendAscii( SAL_CONFIGFILE( "pyuno" ) );
272 iniFile = iniFileName.makeStringAndClear();
273 osl::DirectoryItem item;
274 if( osl::DirectoryItem::get( iniFile, item ) == item.E_None )
276 // in case pyuno.ini exists, use this file for bootstrapping
277 PyThreadDetach antiguard;
278 ctx = cppu::defaultBootstrap_InitialComponentContext (iniFile);
280 else
282 // defaulting to the standard bootstrapping
283 PyThreadDetach antiguard;
284 ctx = cppu::defaultBootstrap_InitialComponentContext ();
289 if( ! Runtime::isInitialized() )
291 Runtime::initialize( ctx );
293 Runtime runtime;
294 ret = runtime.any2PyObject( makeAny( ctx ) );
296 catch (const com::sun::star::registry::InvalidRegistryException &e)
298 // can't use raisePyExceptionWithAny() here, because the function
299 // does any conversions, which will not work with a
300 // wrongly bootstrapped pyuno!
301 raisePySystemException( "InvalidRegistryException", e.Message );
303 catch(const com::sun::star::lang::IllegalArgumentException & e)
305 raisePySystemException( "IllegalArgumentException", e.Message );
307 catch(const com::sun::star::script::CannotConvertException & e)
309 raisePySystemException( "CannotConvertException", e.Message );
311 catch (const com::sun::star::uno::RuntimeException & e)
313 raisePySystemException( "RuntimeException", e.Message );
315 catch (const com::sun::star::uno::Exception & e)
317 raisePySystemException( "uno::Exception", e.Message );
319 return ret.getAcquired();
322 static PyObject* initPoniesMode(
323 SAL_UNUSED_PARAMETER PyObject*, SAL_UNUSED_PARAMETER PyObject*)
325 // this tries to bootstrap enough of the soffice from python to run
326 // unit tests, which is only possible indirectly because pyuno is URE
327 // so load "test" library and invoke a function there to do the work
330 PyObject *const ctx(getComponentContext(0, 0));
331 if (!ctx) { abort(); }
332 Runtime const runtime;
333 Any const a(runtime.pyObject2Any(ctx));
334 Reference<XComponentContext> xContext;
335 a >>= xContext;
336 if (!xContext.is()) { abort(); }
337 using com::sun::star::lang::XMultiServiceFactory;
338 Reference<XMultiServiceFactory> const xMSF(
339 xContext->getServiceManager(),
340 com::sun::star::uno::UNO_QUERY_THROW);
341 if (!xMSF.is()) { abort(); }
342 char *const testlib = getenv("TEST_LIB");
343 if (!testlib) { abort(); }
344 OString const libname = OString(testlib, strlen(testlib))
345 #ifdef _WIN32
346 .replaceAll(OString('/'), OString('\\'))
347 #endif
349 oslModule const mod( osl_loadModuleAscii(libname.getStr(),
350 SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL) );
351 if (!mod) { abort(); }
352 oslGenericFunction const pFunc(
353 osl_getAsciiFunctionSymbol(mod, "test_init"));
354 if (!pFunc) { abort(); }
355 // guess casting pFunc is undefined behavior but don't see a better way
356 ((void (SAL_CALL *)(XMultiServiceFactory*)) pFunc) (xMSF.get());
358 catch (const com::sun::star::uno::Exception &)
360 abort();
362 return Py_None;
365 PyObject * extractOneStringArg( PyObject *args, char const *funcName )
367 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
369 OStringBuffer buf;
370 buf.append( funcName ).append( ": expecting one string argument" );
371 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
372 return NULL;
374 PyObject *obj = PyTuple_GetItem( args, 0 );
375 if (!PyStr_Check(obj) && !PyUnicode_Check(obj))
377 OStringBuffer buf;
378 buf.append( funcName ).append( ": expecting one string argument" );
379 PyErr_SetString( PyExc_TypeError, buf.getStr());
380 return NULL;
382 return obj;
385 static PyObject *createUnoStructHelper(
386 SAL_UNUSED_PARAMETER PyObject *, PyObject* args, PyObject* keywordArgs)
388 Any IdlStruct;
389 PyRef ret;
392 Runtime runtime;
393 if( PyTuple_Size( args ) == 2 )
395 PyObject *structName = PyTuple_GetItem(args, 0);
396 PyObject *initializer = PyTuple_GetItem(args, 1);
398 if (PyStr_Check(structName))
400 if( PyTuple_Check( initializer ) && PyDict_Check ( keywordArgs ) )
402 OUString typeName( OUString::createFromAscii(PyStr_AsString(structName)));
403 RuntimeCargo *c = runtime.getImpl()->cargo;
404 Reference<XIdlClass> idl_class ( c->xCoreReflection->forName (typeName),UNO_QUERY);
405 if (idl_class.is ())
407 idl_class->createObject (IdlStruct);
408 PyUNO *me = (PyUNO*)PyUNO_new_UNCHECKED( IdlStruct, c->xInvocation );
409 PyRef returnCandidate( (PyObject*)me, SAL_NO_ACQUIRE );
410 TypeDescription desc( typeName );
411 OSL_ASSERT( desc.is() ); // could already instantiate an XInvocation2 !
413 typelib_CompoundTypeDescription *pCompType =
414 ( typelib_CompoundTypeDescription * ) desc.get();
415 fillStructState state;
416 if ( PyTuple_Size( initializer ) > 0 || PyDict_Size( keywordArgs ) > 0 )
417 fillStruct( me->members->xInvocation, pCompType, initializer, keywordArgs, state, runtime );
418 if( state.getCntConsumed() != PyTuple_Size(initializer) )
420 OUStringBuffer buf;
421 buf.appendAscii( "pyuno._createUnoStructHelper: too many ");
422 buf.appendAscii( "elements in the initializer list, expected " );
423 buf.append( state.getCntConsumed() );
424 buf.appendAscii( ", got " );
425 buf.append( (sal_Int32) PyTuple_Size(initializer) );
426 throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface > ());
428 ret = PyRef( PyTuple_Pack(2, returnCandidate.get(), state.getUsed()), SAL_NO_ACQUIRE);
430 else
432 OStringBuffer buf;
433 buf.append( "UNO struct " );
434 buf.append( PyStr_AsString(structName) );
435 buf.append( " is unknown" );
436 PyErr_SetString (PyExc_RuntimeError, buf.getStr());
439 else
441 PyErr_SetString(
442 PyExc_RuntimeError,
443 "pyuno._createUnoStructHelper: 2nd argument (initializer sequence) is no tuple" );
446 else
448 PyErr_SetString (PyExc_AttributeError, "createUnoStruct: first argument wasn't a string");
451 else
453 PyErr_SetString (PyExc_AttributeError, "pyuno._createUnoStructHelper: expects exactly two non-keyword arguments:\n\tStructure Name\n\tinitialiser tuple; may be the empty tuple");
456 catch( const com::sun::star::uno::RuntimeException & e )
458 raisePyExceptionWithAny( makeAny( e ) );
460 catch( const com::sun::star::script::CannotConvertException & e )
462 raisePyExceptionWithAny( makeAny( e ) );
464 catch( const com::sun::star::uno::Exception & e )
466 raisePyExceptionWithAny( makeAny( e ) );
468 return ret.getAcquired();
471 static PyObject *getTypeByName(
472 SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
474 PyObject * ret = NULL;
478 char *name;
480 if (PyArg_ParseTuple (args, "s", &name))
482 OUString typeName ( OUString::createFromAscii( name ) );
483 TypeDescription typeDesc( typeName );
484 if( typeDesc.is() )
486 Runtime runtime;
487 ret = PyUNO_Type_new(
488 name, (com::sun::star::uno::TypeClass)typeDesc.get()->eTypeClass, runtime );
490 else
492 OStringBuffer buf;
493 buf.append( "Type " ).append(name).append( " is unknown" );
494 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
498 catch ( const RuntimeException & e )
500 raisePyExceptionWithAny( makeAny( e ) );
502 return ret;
505 static PyObject *getConstantByName(
506 SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
508 PyObject *ret = 0;
511 char *name;
513 if (PyArg_ParseTuple (args, "s", &name))
515 OUString typeName ( OUString::createFromAscii( name ) );
516 Runtime runtime;
517 css::uno::Reference< css::reflection::XConstantTypeDescription > td;
518 if (!(runtime.getImpl()->cargo->xTdMgr->getByHierarchicalName(
519 typeName)
520 >>= td))
522 OUStringBuffer buf;
523 buf.appendAscii( "pyuno.getConstantByName: " ).append( typeName );
524 buf.appendAscii( "is not a constant" );
525 throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface > () );
527 PyRef constant = runtime.any2PyObject( td->getConstantValue() );
528 ret = constant.getAcquired();
531 catch( const NoSuchElementException & e )
533 // to the python programmer, this is a runtime exception,
534 // do not support tweakings with the type system
535 RuntimeException runExc( e.Message, Reference< XInterface > () );
536 raisePyExceptionWithAny( makeAny( runExc ) );
538 catch(const com::sun::star::script::CannotConvertException & e)
540 raisePyExceptionWithAny( makeAny( e ) );
542 catch(const com::sun::star::lang::IllegalArgumentException & e)
544 raisePyExceptionWithAny( makeAny( e ) );
546 catch( const RuntimeException & e )
548 raisePyExceptionWithAny( makeAny(e) );
550 return ret;
553 static PyObject *checkType( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
555 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
557 OStringBuffer buf;
558 buf.append( "pyuno.checkType : expecting one uno.Type argument" );
559 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
560 return NULL;
562 PyObject *obj = PyTuple_GetItem( args, 0 );
566 PyType2Type( obj );
568 catch(const RuntimeException & e)
570 raisePyExceptionWithAny( makeAny( e ) );
571 return NULL;
573 Py_INCREF( Py_None );
574 return Py_None;
577 static PyObject *checkEnum( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
579 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
581 OStringBuffer buf;
582 buf.append( "pyuno.checkType : expecting one uno.Type argument" );
583 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
584 return NULL;
586 PyObject *obj = PyTuple_GetItem( args, 0 );
590 PyEnum2Enum( obj );
592 catch(const RuntimeException & e)
594 raisePyExceptionWithAny( makeAny( e) );
595 return NULL;
597 Py_INCREF( Py_None );
598 return Py_None;
601 static PyObject *getClass( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
603 PyObject *obj = extractOneStringArg( args, "pyuno.getClass");
604 if( ! obj )
605 return NULL;
609 Runtime runtime;
610 PyRef ret = getClass(pyString2ustring(obj), runtime);
611 Py_XINCREF( ret.get() );
612 return ret.get();
614 catch(const RuntimeException & e)
616 // NOOPT !!!
617 // gcc 3.2.3 crashes here in the regcomp test scenario
618 // only since migration to python 2.3.4 ???? strange thing
619 // optimization switched off for this module !
620 raisePyExceptionWithAny( makeAny(e) );
622 return NULL;
625 static PyObject *isInterface( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
628 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 1 )
630 PyObject *obj = PyTuple_GetItem( args, 0 );
631 Runtime r;
632 return PyLong_FromLong( isInterfaceClass( r, obj ) );
634 return PyLong_FromLong( 0 );
637 static PyObject * generateUuid(
638 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * )
640 Sequence< sal_Int8 > seq( 16 );
641 rtl_createUuid( (sal_uInt8*)seq.getArray() , 0 , sal_False );
642 PyRef ret;
645 Runtime runtime;
646 ret = runtime.any2PyObject( makeAny( seq ) );
648 catch( const RuntimeException & e )
650 raisePyExceptionWithAny( makeAny(e) );
652 return ret.getAcquired();
655 static PyObject *systemPathToFileUrl(
656 SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
658 PyObject *obj = extractOneStringArg( args, "pyuno.systemPathToFileUrl" );
659 if( ! obj )
660 return NULL;
662 OUString sysPath = pyString2ustring( obj );
663 OUString url;
664 osl::FileBase::RC e = osl::FileBase::getFileURLFromSystemPath( sysPath, url );
666 if( e != osl::FileBase::E_None )
668 OUStringBuffer buf;
669 buf.appendAscii( "Couldn't convert " );
670 buf.append( sysPath );
671 buf.appendAscii( " to a file url for reason (" );
672 buf.append( (sal_Int32) e );
673 buf.appendAscii( ")" );
674 raisePyExceptionWithAny(
675 makeAny( RuntimeException( buf.makeStringAndClear(), Reference< XInterface > () )));
676 return NULL;
678 return ustring2PyUnicode( url ).getAcquired();
681 static PyObject * fileUrlToSystemPath(
682 SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
684 PyObject *obj = extractOneStringArg( args, "pyuno.fileUrlToSystemPath" );
685 if( ! obj )
686 return NULL;
688 OUString url = pyString2ustring( obj );
689 OUString sysPath;
690 osl::FileBase::RC e = osl::FileBase::getSystemPathFromFileURL( url, sysPath );
692 if( e != osl::FileBase::E_None )
694 OUStringBuffer buf;
695 buf.appendAscii( "Couldn't convert file url " );
696 buf.append( sysPath );
697 buf.appendAscii( " to a system path for reason (" );
698 buf.append( (sal_Int32) e );
699 buf.appendAscii( ")" );
700 raisePyExceptionWithAny(
701 makeAny( RuntimeException( buf.makeStringAndClear(), Reference< XInterface > () )));
702 return NULL;
704 return ustring2PyUnicode( sysPath ).getAcquired();
707 static PyObject * absolutize( SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
709 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 2 )
711 OUString ouPath = pyString2ustring( PyTuple_GetItem( args , 0 ) );
712 OUString ouRel = pyString2ustring( PyTuple_GetItem( args, 1 ) );
713 OUString ret;
714 oslFileError e = osl_getAbsoluteFileURL( ouPath.pData, ouRel.pData, &(ret.pData) );
715 if( e != osl_File_E_None )
717 OUStringBuffer buf;
718 buf.appendAscii( "Couldn't absolutize " );
719 buf.append( ouRel );
720 buf.appendAscii( " using root " );
721 buf.append( ouPath );
722 buf.appendAscii( " for reason (" );
723 buf.append( (sal_Int32) e );
724 buf.appendAscii( ")" );
726 PyErr_SetString(
727 PyExc_OSError,
728 OUStringToOString(buf.makeStringAndClear(),osl_getThreadTextEncoding()).getStr());
729 return 0;
731 return ustring2PyUnicode( ret ).getAcquired();
733 return 0;
736 static PyObject * invoke(SAL_UNUSED_PARAMETER PyObject *, PyObject *args)
738 PyObject *ret = 0;
739 if(PyTuple_Check(args) && PyTuple_Size(args) == 3)
741 PyObject *object = PyTuple_GetItem(args, 0);
742 PyObject *item1 = PyTuple_GetItem(args, 1);
743 if (PyStr_Check(item1))
745 const char *name = PyStr_AsString(item1);
746 PyObject *item2 = PyTuple_GetItem(args, 2);
747 if(PyTuple_Check(item2))
749 ret = PyUNO_invoke(object, name, item2);
751 else
753 OStringBuffer buf;
754 buf.append("uno.invoke expects a tuple as 3rd argument, got ");
755 buf.append(PyStr_AsString(PyObject_Str(item2)));
756 PyErr_SetString(
757 PyExc_RuntimeError, buf.makeStringAndClear().getStr());
760 else
762 OStringBuffer buf;
763 buf.append("uno.invoke expected a string as 2nd argument, got ");
764 buf.append(PyStr_AsString(PyObject_Str(item1)));
765 PyErr_SetString(
766 PyExc_RuntimeError, buf.makeStringAndClear().getStr());
769 else
771 OStringBuffer buf;
772 buf.append("uno.invoke expects object, name, (arg1, arg2, ... )\n");
773 PyErr_SetString(PyExc_RuntimeError, buf.makeStringAndClear().getStr());
775 return ret;
778 static PyObject *getCurrentContext(
779 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * )
781 PyRef ret;
784 Runtime runtime;
785 ret = runtime.any2PyObject(
786 makeAny( com::sun::star::uno::getCurrentContext() ) );
788 catch( const com::sun::star::uno::Exception & e )
790 raisePyExceptionWithAny( makeAny( e ) );
792 return ret.getAcquired();
795 static PyObject *setCurrentContext(
796 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * args )
798 PyRef ret;
801 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 1 )
804 Runtime runtime;
805 Any a = runtime.pyObject2Any( PyTuple_GetItem( args, 0 ) );
807 Reference< com::sun::star::uno::XCurrentContext > context;
809 if( (a.hasValue() && (a >>= context)) || ! a.hasValue() )
811 ret = com::sun::star::uno::setCurrentContext( context ) ? Py_True : Py_False;
813 else
815 OStringBuffer buf;
816 buf.append( "uno.setCurrentContext expects an XComponentContext implementation, got " );
817 buf.append(
818 PyStr_AsString(PyObject_Str(PyTuple_GetItem(args, 0))));
819 PyErr_SetString(
820 PyExc_RuntimeError, buf.makeStringAndClear().getStr() );
823 else
825 OStringBuffer buf;
826 buf.append( "uno.setCurrentContext expects exactly one argument (the current Context)\n" );
827 PyErr_SetString(
828 PyExc_RuntimeError, buf.makeStringAndClear().getStr() );
831 catch( const com::sun::star::uno::Exception & e )
833 raisePyExceptionWithAny( makeAny( e ) );
835 return ret.getAcquired();
840 struct PyMethodDef PyUNOModule_methods [] =
842 {"experimentalExtraMagic", initPoniesMode, METH_VARARGS, NULL},
843 {"getComponentContext", getComponentContext, METH_VARARGS, NULL},
844 {"_createUnoStructHelper", reinterpret_cast<PyCFunction>(createUnoStructHelper), METH_VARARGS | METH_KEYWORDS, NULL},
845 {"getTypeByName", getTypeByName, METH_VARARGS, NULL},
846 {"getConstantByName", getConstantByName, METH_VARARGS, NULL},
847 {"getClass", getClass, METH_VARARGS, NULL},
848 {"checkEnum", checkEnum, METH_VARARGS, NULL},
849 {"checkType", checkType, METH_VARARGS, NULL},
850 {"generateUuid", generateUuid, METH_VARARGS, NULL},
851 {"systemPathToFileUrl", systemPathToFileUrl, METH_VARARGS, NULL},
852 {"fileUrlToSystemPath", fileUrlToSystemPath, METH_VARARGS, NULL},
853 {"absolutize", absolutize, METH_VARARGS | METH_KEYWORDS, NULL},
854 {"isInterface", isInterface, METH_VARARGS, NULL},
855 {"invoke", invoke, METH_VARARGS | METH_KEYWORDS, NULL},
856 {"setCurrentContext", setCurrentContext, METH_VARARGS, NULL},
857 {"getCurrentContext", getCurrentContext, METH_VARARGS, NULL},
858 {NULL, NULL, 0, NULL}
863 extern "C"
864 #if PY_MAJOR_VERSION >= 3
865 PyObject* PyInit_pyuno()
867 PyUNO_initType();
868 // noop when called already, otherwise needed to allow multiple threads
869 PyEval_InitThreads();
870 static struct PyModuleDef moduledef =
872 PyModuleDef_HEAD_INIT,
873 "pyuno", // module name
874 0, // module documentation
875 -1, // module keeps state in global variables,
876 PyUNOModule_methods, // modules methods
877 0, // m_reload (must be 0)
878 0, // m_traverse
879 0, // m_clear
880 0, // m_free
882 return PyModule_Create(&moduledef);
884 #else
885 void initpyuno()
887 PyUNO_initType();
888 PyEval_InitThreads();
889 Py_InitModule ("pyuno", PyUNOModule_methods);
891 #endif /* PY_MAJOR_VERSION >= 3 */
893 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */