update emoji autocorrect entries from po-files
[LibreOffice.git] / pyuno / source / module / pyuno_module.cxx
blobc2187afcccd8ede5701d27a654c850d0632e7ffa
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 <unordered_map>
26 #include <utility>
28 #include <osl/module.hxx>
29 #include <osl/thread.h>
30 #include <osl/file.hxx>
32 #include <typelib/typedescription.hxx>
34 #include <rtl/ustring.hxx>
35 #include <rtl/strbuf.hxx>
36 #include <rtl/ustrbuf.hxx>
37 #include <rtl/uuid.h>
38 #include <rtl/bootstrap.hxx>
40 #include <uno/current_context.hxx>
41 #include <cppuhelper/bootstrap.hxx>
43 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
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 std::unordered_map <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");
101 ~fillStructState()
103 Py_DECREF(used);
105 int setUsed(PyObject *key)
107 return PyDict_SetItem(used, key, Py_True);
109 void setInitialised(const 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());
125 initialised[key] = true;
126 if ( pos >= 0 )
127 ++nPosConsumed;
129 bool isInitialised(const 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());
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 OUString iniFile;
253 if( path.isEmpty() )
255 PyErr_SetString(
256 PyExc_RuntimeError, "osl_getUrlFromAddress fails, that's why I cannot find ini "
257 "file for bootstrapping python uno bridge\n" );
258 return NULL;
261 OUStringBuffer iniFileName;
262 iniFileName.append( path );
263 #ifdef MACOSX
264 iniFileName.appendAscii( "/../" LIBO_ETC_FOLDER );
265 #endif
266 iniFileName.appendAscii( "/" );
267 iniFileName.appendAscii( SAL_CONFIGFILE( "pyuno" ) );
268 iniFile = iniFileName.makeStringAndClear();
269 osl::DirectoryItem item;
270 if( osl::DirectoryItem::get( iniFile, item ) == item.E_None )
272 // in case pyuno.ini exists, use this file for bootstrapping
273 PyThreadDetach antiguard;
274 ctx = cppu::defaultBootstrap_InitialComponentContext (iniFile);
276 else
278 // defaulting to the standard bootstrapping
279 PyThreadDetach antiguard;
280 ctx = cppu::defaultBootstrap_InitialComponentContext ();
285 if( ! Runtime::isInitialized() )
287 Runtime::initialize( ctx );
289 Runtime runtime;
290 ret = runtime.any2PyObject( makeAny( ctx ) );
292 catch (const com::sun::star::registry::InvalidRegistryException &e)
294 // can't use raisePyExceptionWithAny() here, because the function
295 // does any conversions, which will not work with a
296 // wrongly bootstrapped pyuno!
297 raisePySystemException( "InvalidRegistryException", e.Message );
299 catch(const com::sun::star::lang::IllegalArgumentException & e)
301 raisePySystemException( "IllegalArgumentException", e.Message );
303 catch(const com::sun::star::script::CannotConvertException & e)
305 raisePySystemException( "CannotConvertException", e.Message );
307 catch (const com::sun::star::uno::RuntimeException & e)
309 raisePySystemException( "RuntimeException", e.Message );
311 catch (const com::sun::star::uno::Exception & e)
313 raisePySystemException( "uno::Exception", e.Message );
315 return ret.getAcquired();
318 static PyObject* initTestEnvironment(
319 SAL_UNUSED_PARAMETER PyObject*, SAL_UNUSED_PARAMETER PyObject*)
321 // this tries to bootstrap enough of the soffice from python to run
322 // unit tests, which is only possible indirectly because pyuno is URE
323 // so load "test" library and invoke a function there to do the work
326 PyObject *const ctx(getComponentContext(0, 0));
327 if (!ctx) { abort(); }
328 Runtime const runtime;
329 Any const a(runtime.pyObject2Any(ctx));
330 Reference<XComponentContext> xContext;
331 a >>= xContext;
332 if (!xContext.is()) { abort(); }
333 using com::sun::star::lang::XMultiServiceFactory;
334 Reference<XMultiServiceFactory> const xMSF(
335 xContext->getServiceManager(),
336 com::sun::star::uno::UNO_QUERY_THROW);
337 if (!xMSF.is()) { abort(); }
338 char *const testlib = getenv("TEST_LIB");
339 if (!testlib) { abort(); }
340 OString const libname = OString(testlib, strlen(testlib))
341 #ifdef _WIN32
342 .replaceAll(OString('/'), OString('\\'))
343 #endif
346 osl::Module &mod = runtime.getImpl()->cargo->testModule;
347 mod.load(OStringToOUString(libname, osl_getThreadTextEncoding()),
348 SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL);
349 if (!mod.is()) { abort(); }
350 oslGenericFunction const pFunc(
351 mod.getFunctionSymbol("test_init"));
352 if (!pFunc) { abort(); }
353 reinterpret_cast<void (SAL_CALL *)(XMultiServiceFactory*)>(pFunc)(xMSF.get());
355 catch (const com::sun::star::uno::Exception &)
357 abort();
359 return Py_None;
362 PyObject * extractOneStringArg( PyObject *args, char const *funcName )
364 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
366 OStringBuffer buf;
367 buf.append( funcName ).append( ": expecting one string argument" );
368 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
369 return NULL;
371 PyObject *obj = PyTuple_GetItem( args, 0 );
372 if (!PyStr_Check(obj) && !PyUnicode_Check(obj))
374 OStringBuffer buf;
375 buf.append( funcName ).append( ": expecting one string argument" );
376 PyErr_SetString( PyExc_TypeError, buf.getStr());
377 return NULL;
379 return obj;
382 static PyObject *createUnoStructHelper(
383 SAL_UNUSED_PARAMETER PyObject *, PyObject* args, PyObject* keywordArgs)
385 Any IdlStruct;
386 PyRef ret;
389 Runtime runtime;
390 if( PyTuple_Size( args ) == 2 )
392 PyObject *structName = PyTuple_GetItem(args, 0);
393 PyObject *initializer = PyTuple_GetItem(args, 1);
395 if (PyStr_Check(structName))
397 if( PyTuple_Check( initializer ) && PyDict_Check ( keywordArgs ) )
399 OUString typeName( OUString::createFromAscii(PyStr_AsString(structName)));
400 RuntimeCargo *c = runtime.getImpl()->cargo;
401 Reference<XIdlClass> idl_class ( c->xCoreReflection->forName (typeName),UNO_QUERY);
402 if (idl_class.is ())
404 idl_class->createObject (IdlStruct);
405 PyUNO *me = reinterpret_cast<PyUNO*>(PyUNO_new_UNCHECKED( IdlStruct, c->xInvocation ));
406 PyRef returnCandidate( reinterpret_cast<PyObject*>(me), SAL_NO_ACQUIRE );
407 TypeDescription desc( typeName );
408 OSL_ASSERT( desc.is() ); // could already instantiate an XInvocation2 !
410 typelib_CompoundTypeDescription *pCompType =
411 reinterpret_cast<typelib_CompoundTypeDescription *>(desc.get());
412 fillStructState state;
413 if ( PyTuple_Size( initializer ) > 0 || PyDict_Size( keywordArgs ) > 0 )
414 fillStruct( me->members->xInvocation, pCompType, initializer, keywordArgs, state, runtime );
415 if( state.getCntConsumed() != PyTuple_Size(initializer) )
417 OUStringBuffer buf;
418 buf.appendAscii( "pyuno._createUnoStructHelper: too many ");
419 buf.appendAscii( "elements in the initializer list, expected " );
420 buf.append( state.getCntConsumed() );
421 buf.appendAscii( ", got " );
422 buf.append( (sal_Int32) PyTuple_Size(initializer) );
423 throw RuntimeException( buf.makeStringAndClear());
425 ret = PyRef( PyTuple_Pack(2, returnCandidate.get(), state.getUsed()), SAL_NO_ACQUIRE);
427 else
429 OStringBuffer buf;
430 buf.append( "UNO struct " );
431 buf.append( PyStr_AsString(structName) );
432 buf.append( " is unknown" );
433 PyErr_SetString (PyExc_RuntimeError, buf.getStr());
436 else
438 PyErr_SetString(
439 PyExc_RuntimeError,
440 "pyuno._createUnoStructHelper: 2nd argument (initializer sequence) is no tuple" );
443 else
445 PyErr_SetString (PyExc_AttributeError, "createUnoStruct: first argument wasn't a string");
448 else
450 PyErr_SetString (PyExc_AttributeError, "pyuno._createUnoStructHelper: expects exactly two non-keyword arguments:\n\tStructure Name\n\tinitialiser tuple; may be the empty tuple");
453 catch( const com::sun::star::uno::RuntimeException & e )
455 raisePyExceptionWithAny( makeAny( e ) );
457 catch( const com::sun::star::script::CannotConvertException & e )
459 raisePyExceptionWithAny( makeAny( e ) );
461 catch( const com::sun::star::uno::Exception & e )
463 raisePyExceptionWithAny( makeAny( e ) );
465 return ret.getAcquired();
468 static PyObject *getTypeByName(
469 SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
471 PyObject * ret = NULL;
475 char *name;
477 if (PyArg_ParseTuple (args, "s", &name))
479 OUString typeName ( OUString::createFromAscii( name ) );
480 TypeDescription typeDesc( typeName );
481 if( typeDesc.is() )
483 Runtime runtime;
484 ret = PyUNO_Type_new(
485 name, (com::sun::star::uno::TypeClass)typeDesc.get()->eTypeClass, runtime );
487 else
489 OStringBuffer buf;
490 buf.append( "Type " ).append(name).append( " is unknown" );
491 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
495 catch ( const RuntimeException & e )
497 raisePyExceptionWithAny( makeAny( e ) );
499 return ret;
502 static PyObject *getConstantByName(
503 SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
505 PyObject *ret = 0;
508 char *name;
510 if (PyArg_ParseTuple (args, "s", &name))
512 OUString typeName ( OUString::createFromAscii( name ) );
513 Runtime runtime;
514 css::uno::Reference< css::reflection::XConstantTypeDescription > td;
515 if (!(runtime.getImpl()->cargo->xTdMgr->getByHierarchicalName(
516 typeName)
517 >>= td))
519 OUStringBuffer buf;
520 buf.appendAscii( "pyuno.getConstantByName: " ).append( typeName );
521 buf.appendAscii( "is not a constant" );
522 throw RuntimeException(buf.makeStringAndClear() );
524 PyRef constant = runtime.any2PyObject( td->getConstantValue() );
525 ret = constant.getAcquired();
528 catch( const NoSuchElementException & e )
530 // to the python programmer, this is a runtime exception,
531 // do not support tweakings with the type system
532 RuntimeException runExc( e.Message );
533 raisePyExceptionWithAny( makeAny( runExc ) );
535 catch(const com::sun::star::script::CannotConvertException & e)
537 raisePyExceptionWithAny( makeAny( e ) );
539 catch(const com::sun::star::lang::IllegalArgumentException & e)
541 raisePyExceptionWithAny( makeAny( e ) );
543 catch( const RuntimeException & e )
545 raisePyExceptionWithAny( makeAny(e) );
547 return ret;
550 static PyObject *checkType( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
552 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
554 OStringBuffer buf;
555 buf.append( "pyuno.checkType : expecting one uno.Type argument" );
556 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
557 return NULL;
559 PyObject *obj = PyTuple_GetItem( args, 0 );
563 PyType2Type( obj );
565 catch(const RuntimeException & e)
567 raisePyExceptionWithAny( makeAny( e ) );
568 return NULL;
570 Py_INCREF( Py_None );
571 return Py_None;
574 static PyObject *checkEnum( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
576 if( !PyTuple_Check( args ) || PyTuple_Size( args) != 1 )
578 OStringBuffer buf;
579 buf.append( "pyuno.checkType : expecting one uno.Type argument" );
580 PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
581 return NULL;
583 PyObject *obj = PyTuple_GetItem( args, 0 );
587 PyEnum2Enum( obj );
589 catch(const RuntimeException & e)
591 raisePyExceptionWithAny( makeAny( e) );
592 return NULL;
594 Py_INCREF( Py_None );
595 return Py_None;
598 static PyObject *getClass( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
600 PyObject *obj = extractOneStringArg( args, "pyuno.getClass");
601 if( ! obj )
602 return NULL;
606 Runtime runtime;
607 PyRef ret = getClass(pyString2ustring(obj), runtime);
608 Py_XINCREF( ret.get() );
609 return ret.get();
611 catch(const RuntimeException & e)
613 raisePyExceptionWithAny( makeAny(e) );
615 return NULL;
618 static PyObject *isInterface( SAL_UNUSED_PARAMETER PyObject *, PyObject *args )
621 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 1 )
623 PyObject *obj = PyTuple_GetItem( args, 0 );
624 Runtime r;
625 return PyLong_FromLong( isInterfaceClass( r, obj ) );
627 return PyLong_FromLong( 0 );
630 static PyObject * generateUuid(
631 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * )
633 Sequence< sal_Int8 > seq( 16 );
634 rtl_createUuid( reinterpret_cast<sal_uInt8*>(seq.getArray()) , 0 , sal_False );
635 PyRef ret;
638 Runtime runtime;
639 ret = runtime.any2PyObject( makeAny( seq ) );
641 catch( const RuntimeException & e )
643 raisePyExceptionWithAny( makeAny(e) );
645 return ret.getAcquired();
648 static PyObject *systemPathToFileUrl(
649 SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
651 PyObject *obj = extractOneStringArg( args, "pyuno.systemPathToFileUrl" );
652 if( ! obj )
653 return NULL;
655 OUString sysPath = pyString2ustring( obj );
656 OUString url;
657 osl::FileBase::RC e = osl::FileBase::getFileURLFromSystemPath( sysPath, url );
659 if( e != osl::FileBase::E_None )
661 OUStringBuffer buf;
662 buf.appendAscii( "Couldn't convert " );
663 buf.append( sysPath );
664 buf.appendAscii( " to a file url for reason (" );
665 buf.append( (sal_Int32) e );
666 buf.appendAscii( ")" );
667 raisePyExceptionWithAny(
668 makeAny( RuntimeException( buf.makeStringAndClear() )));
669 return NULL;
671 return ustring2PyUnicode( url ).getAcquired();
674 static PyObject * fileUrlToSystemPath(
675 SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
677 PyObject *obj = extractOneStringArg( args, "pyuno.fileUrlToSystemPath" );
678 if( ! obj )
679 return NULL;
681 OUString url = pyString2ustring( obj );
682 OUString sysPath;
683 osl::FileBase::RC e = osl::FileBase::getSystemPathFromFileURL( url, sysPath );
685 if( e != osl::FileBase::E_None )
687 OUStringBuffer buf;
688 buf.appendAscii( "Couldn't convert file url " );
689 buf.append( sysPath );
690 buf.appendAscii( " to a system path for reason (" );
691 buf.append( (sal_Int32) e );
692 buf.appendAscii( ")" );
693 raisePyExceptionWithAny(
694 makeAny( RuntimeException( buf.makeStringAndClear() )));
695 return NULL;
697 return ustring2PyUnicode( sysPath ).getAcquired();
700 static PyObject * absolutize( SAL_UNUSED_PARAMETER PyObject *, PyObject * args )
702 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 2 )
704 OUString ouPath = pyString2ustring( PyTuple_GetItem( args , 0 ) );
705 OUString ouRel = pyString2ustring( PyTuple_GetItem( args, 1 ) );
706 OUString ret;
707 oslFileError e = osl_getAbsoluteFileURL( ouPath.pData, ouRel.pData, &(ret.pData) );
708 if( e != osl_File_E_None )
710 OUStringBuffer buf;
711 buf.appendAscii( "Couldn't absolutize " );
712 buf.append( ouRel );
713 buf.appendAscii( " using root " );
714 buf.append( ouPath );
715 buf.appendAscii( " for reason (" );
716 buf.append( (sal_Int32) e );
717 buf.appendAscii( ")" );
719 PyErr_SetString(
720 PyExc_OSError,
721 OUStringToOString(buf.makeStringAndClear(),osl_getThreadTextEncoding()).getStr());
722 return 0;
724 return ustring2PyUnicode( ret ).getAcquired();
726 return 0;
729 static PyObject * invoke(SAL_UNUSED_PARAMETER PyObject *, PyObject *args)
731 PyObject *ret = 0;
732 if(PyTuple_Check(args) && PyTuple_Size(args) == 3)
734 PyObject *object = PyTuple_GetItem(args, 0);
735 PyObject *item1 = PyTuple_GetItem(args, 1);
736 if (PyStr_Check(item1))
738 const char *name = PyStr_AsString(item1);
739 PyObject *item2 = PyTuple_GetItem(args, 2);
740 if(PyTuple_Check(item2))
742 ret = PyUNO_invoke(object, name, item2);
744 else
746 OStringBuffer buf;
747 buf.append("uno.invoke expects a tuple as 3rd argument, got ");
748 buf.append(PyStr_AsString(PyObject_Str(item2)));
749 PyErr_SetString(
750 PyExc_RuntimeError, buf.makeStringAndClear().getStr());
753 else
755 OStringBuffer buf;
756 buf.append("uno.invoke expected a string as 2nd argument, got ");
757 buf.append(PyStr_AsString(PyObject_Str(item1)));
758 PyErr_SetString(
759 PyExc_RuntimeError, buf.makeStringAndClear().getStr());
762 else
764 OStringBuffer buf;
765 buf.append("uno.invoke expects object, name, (arg1, arg2, ... )\n");
766 PyErr_SetString(PyExc_RuntimeError, buf.makeStringAndClear().getStr());
768 return ret;
771 static PyObject *getCurrentContext(
772 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * )
774 PyRef ret;
777 Runtime runtime;
778 ret = runtime.any2PyObject(
779 makeAny( com::sun::star::uno::getCurrentContext() ) );
781 catch( const com::sun::star::uno::Exception & e )
783 raisePyExceptionWithAny( makeAny( e ) );
785 return ret.getAcquired();
788 static PyObject *setCurrentContext(
789 SAL_UNUSED_PARAMETER PyObject *, SAL_UNUSED_PARAMETER PyObject * args )
791 PyRef ret;
794 if( PyTuple_Check( args ) && PyTuple_Size( args ) == 1 )
797 Runtime runtime;
798 Any a = runtime.pyObject2Any( PyTuple_GetItem( args, 0 ) );
800 Reference< com::sun::star::uno::XCurrentContext > context;
802 if( (a.hasValue() && (a >>= context)) || ! a.hasValue() )
804 ret = com::sun::star::uno::setCurrentContext( context ) ? Py_True : Py_False;
806 else
808 OStringBuffer buf;
809 buf.append( "uno.setCurrentContext expects an XComponentContext implementation, got " );
810 buf.append(
811 PyStr_AsString(PyObject_Str(PyTuple_GetItem(args, 0))));
812 PyErr_SetString(
813 PyExc_RuntimeError, buf.makeStringAndClear().getStr() );
816 else
818 OStringBuffer buf;
819 buf.append( "uno.setCurrentContext expects exactly one argument (the current Context)\n" );
820 PyErr_SetString(
821 PyExc_RuntimeError, buf.makeStringAndClear().getStr() );
824 catch( const com::sun::star::uno::Exception & e )
826 raisePyExceptionWithAny( makeAny( e ) );
828 return ret.getAcquired();
833 struct PyMethodDef PyUNOModule_methods [] =
835 {"private_initTestEnvironment", initTestEnvironment, METH_VARARGS, NULL},
836 {"getComponentContext", getComponentContext, METH_VARARGS, NULL},
837 {"_createUnoStructHelper", reinterpret_cast<PyCFunction>(createUnoStructHelper), METH_VARARGS | METH_KEYWORDS, NULL},
838 {"getTypeByName", getTypeByName, METH_VARARGS, NULL},
839 {"getConstantByName", getConstantByName, METH_VARARGS, NULL},
840 {"getClass", getClass, METH_VARARGS, NULL},
841 {"checkEnum", checkEnum, METH_VARARGS, NULL},
842 {"checkType", checkType, METH_VARARGS, NULL},
843 {"generateUuid", generateUuid, METH_VARARGS, NULL},
844 {"systemPathToFileUrl", systemPathToFileUrl, METH_VARARGS, NULL},
845 {"fileUrlToSystemPath", fileUrlToSystemPath, METH_VARARGS, NULL},
846 {"absolutize", absolutize, METH_VARARGS | METH_KEYWORDS, NULL},
847 {"isInterface", isInterface, METH_VARARGS, NULL},
848 {"invoke", invoke, METH_VARARGS | METH_KEYWORDS, NULL},
849 {"setCurrentContext", setCurrentContext, METH_VARARGS, NULL},
850 {"getCurrentContext", getCurrentContext, METH_VARARGS, NULL},
851 {NULL, NULL, 0, NULL}
856 extern "C"
857 #if PY_MAJOR_VERSION >= 3
858 PyObject* PyInit_pyuno()
860 PyUNO_initType();
861 // noop when called already, otherwise needed to allow multiple threads
862 PyEval_InitThreads();
863 static struct PyModuleDef moduledef =
865 PyModuleDef_HEAD_INIT,
866 "pyuno", // module name
867 0, // module documentation
868 -1, // module keeps state in global variables,
869 PyUNOModule_methods, // modules methods
870 0, // m_reload (must be 0)
871 0, // m_traverse
872 0, // m_clear
873 0, // m_free
875 return PyModule_Create(&moduledef);
877 #else
878 void initpyuno()
880 PyUNO_initType();
881 PyEval_InitThreads();
882 Py_InitModule ("pyuno", PyUNOModule_methods);
884 #endif /* PY_MAJOR_VERSION >= 3 */
886 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */