1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Helper functions/classes for the wxPython extension module
7 // Created: 1-July-1997
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
16 #include "wx/wxPython/wxPython_int.h"
17 #include "wx/wxPython/pyistream.h"
20 #include <wx/msw/private.h>
21 #include <wx/msw/winundef.h>
22 #include <wx/msw/msvcrt.h>
27 #include <gdk/gdkprivate.h>
28 #include <wx/gtk/win_gtk.h>
32 #include <wx/mac/private.h>
35 #include <wx/clipbrd.h>
36 #include <wx/mimetype.h>
39 //----------------------------------------------------------------------
41 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
42 #error Python must support Unicode to use wxWindows Unicode
45 //----------------------------------------------------------------------
47 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
48 bool wxPyDoCleanup
= False
;
49 bool wxPyDoingCleanup
= False
;
52 #ifdef WXP_WITH_THREAD
53 struct wxPyThreadState
{
55 PyThreadState
* tstate
;
58 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
59 : tid(_tid
), tstate(_tstate
), blocked(1) {}
62 #include <wx/dynarray.h>
63 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
64 #include <wx/arrimpl.cpp>
65 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
67 wxPyThreadStateArray
* wxPyTStates
= NULL
;
68 wxMutex
* wxPyTMutex
= NULL
;
72 static PyObject
* wxPython_dict
= NULL
;
73 static PyObject
* wxPyAssertionError
= NULL
;
75 PyObject
* wxPyPtrTypeMap
= NULL
;
78 #ifdef __WXMSW__ // If building for win32...
79 //----------------------------------------------------------------------
80 // This gets run when the DLL is loaded. We just need to save a handle.
81 //----------------------------------------------------------------------
84 HINSTANCE hinstDLL
, // handle to DLL module
85 DWORD fdwReason
, // reason for calling function
86 LPVOID lpvReserved
// reserved
89 // If wxPython is embedded in another wxWindows app then
90 // the inatance has already been set.
91 if (! wxGetInstance())
92 wxSetInstance(hinstDLL
);
97 //----------------------------------------------------------------------
98 // Classes for implementing the wxp main application shell.
99 //----------------------------------------------------------------------
101 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
105 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
106 m_startupComplete
= False
;
110 wxPyApp::~wxPyApp() {
114 // This one isn't acutally called... We fake it with _BootstrapApp
115 bool wxPyApp::OnInit() {
120 int wxPyApp::MainLoop() {
123 DeletePendingObjects();
124 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
126 if ( m_exitOnFrameDelete
== Later
) {
127 m_exitOnFrameDelete
= Yes
;
130 retval
= wxApp::MainLoop();
137 bool wxPyApp::OnInitGui() {
139 wxApp::OnInitGui(); // in this case always call the base class version
140 wxPyBeginBlockThreads();
141 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
142 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
143 wxPyEndBlockThreads();
148 int wxPyApp::OnExit() {
150 wxPyBeginBlockThreads();
151 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
152 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
153 wxPyEndBlockThreads();
154 wxApp::OnExit(); // in this case always call the base class version
160 void wxPyApp::OnAssert(const wxChar
*file
,
165 // if we're not fully initialized then just log the error
166 if (! m_startupComplete
) {
169 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
179 // If the OnAssert is overloaded in the Python class then call it...
181 wxPyBeginBlockThreads();
182 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
183 PyObject
* fso
= wx2PyString(file
);
184 PyObject
* cso
= wx2PyString(file
);
187 mso
= wx2PyString(file
);
189 mso
= Py_None
; Py_INCREF(Py_None
);
191 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
196 wxPyEndBlockThreads();
198 // ...otherwise do our own thing with it
201 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
204 // turn it into a Python exception?
205 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
208 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
215 wxPyBeginBlockThreads();
216 PyObject
* s
= wx2PyString(buf
);
217 PyErr_SetObject(wxPyAssertionError
, s
);
219 wxPyEndBlockThreads();
221 // Now when control returns to whatever API wrapper was called from
222 // Python it should detect that an exception is set and will return
223 // NULL, signalling the exception to Python.
226 // Send it to the normal log destination, but only if
227 // not _DIALOG because it will call this too
228 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
231 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
240 // do the normal wx assert dialog?
241 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
242 wxApp::OnAssert(file
, line
, cond
, msg
);
247 // For catching Apple Events
248 void wxPyApp::MacOpenFile(const wxString
&fileName
)
250 wxPyBeginBlockThreads();
251 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
252 PyObject
* s
= wx2PyString(fileName
);
253 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
256 wxPyEndBlockThreads();
259 void wxPyApp::MacPrintFile(const wxString
&fileName
)
261 wxPyBeginBlockThreads();
262 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
263 PyObject
* s
= wx2PyString(fileName
);
264 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
267 wxPyEndBlockThreads();
270 void wxPyApp::MacNewFile()
272 wxPyBeginBlockThreads();
273 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
274 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
275 wxPyEndBlockThreads();
278 void wxPyApp::MacReopenApp()
280 wxPyBeginBlockThreads();
281 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
282 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
283 wxPyEndBlockThreads();
288 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
290 return s_macSupportPCMenuShortcuts
;
297 long wxPyApp::GetMacAboutMenuItemId() {
299 return s_macAboutMenuItemId
;
306 long wxPyApp::GetMacPreferencesMenuItemId() {
308 return s_macPreferencesMenuItemId
;
315 long wxPyApp::GetMacExitMenuItemId() {
317 return s_macExitMenuItemId
;
324 wxString
wxPyApp::GetMacHelpMenuTitleName() {
326 return s_macHelpMenuTitleName
;
328 return wxEmptyString
;
333 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
335 s_macSupportPCMenuShortcuts
= val
;
340 void wxPyApp::SetMacAboutMenuItemId(long val
) {
342 s_macAboutMenuItemId
= val
;
347 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
349 s_macPreferencesMenuItemId
= val
;
354 void wxPyApp::SetMacExitMenuItemId(long val
) {
356 s_macExitMenuItemId
= val
;
361 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
363 s_macHelpMenuTitleName
= val
;
368 // This finishes the initialization of wxWindows and then calls the OnInit
369 // that should be present in the derived (Python) class.
370 void wxPyApp::_BootstrapApp()
373 PyObject
* retval
= NULL
;
374 PyObject
* pyint
= NULL
;
377 // Get any command-line args passed to this program from the sys module
380 wxPyBeginBlockThreads();
381 PyObject
* sysargv
= PySys_GetObject("argv");
382 if (sysargv
!= NULL
) {
383 argc
= PyList_Size(sysargv
);
384 argv
= new char*[argc
+1];
386 for(x
=0; x
<argc
; x
++) {
387 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
388 argv
[x
] = PyString_AsString(pyArg
);
392 wxPyEndBlockThreads();
394 result
= wxEntryStart(argc
, argv
);
397 wxPyBeginBlockThreads();
399 PyErr_SetString(PyExc_SystemError
, "wxEntryStart failed!");
403 // The stock objects were all NULL when they were loaded into
404 // SWIG generated proxies, so re-init those now...
405 wxPy_ReinitStockObjects(3);
407 // It's now ok to generate exceptions for assertion errors.
408 wxPythonApp
->SetStartupComplete(True
);
410 // Call the Python wxApp's OnInit function
411 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
413 PyObject
* method
= m_myInst
.GetLastFound();
414 PyObject
* argTuple
= PyTuple_New(0);
415 retval
= PyEval_CallObject(method
, argTuple
);
421 pyint
= PyNumber_Int(retval
);
423 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
426 result
= PyInt_AS_LONG(pyint
);
429 // Is it okay if there is no OnInit? Probably so...
435 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
442 wxPyEndBlockThreads();
445 //---------------------------------------------------------------------
446 //----------------------------------------------------------------------
450 static char* wxPyCopyCString(const wxChar
* src
)
452 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
453 size_t len
= strlen(buff
);
454 char* dest
= new char[len
+1];
460 static char* wxPyCopyCString(const char* src
) // we need a char version too
462 size_t len
= strlen(src
);
463 char* dest
= new char[len
+1];
469 static wxChar
* wxPyCopyWString(const char *src
)
471 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
472 wxString
str(src
, *wxConvCurrent
);
473 return copystring(str
);
477 static wxChar
* wxPyCopyWString(const wxChar
*src
)
479 return copystring(src
);
485 inline const char* dropwx(const char* name
) {
486 if (name
[0] == 'w' && name
[1] == 'x')
492 //----------------------------------------------------------------------
494 // This function is called when the wxc module is imported to do some initial
495 // setup. (Before there is a wxApp object.) The rest happens in
496 // wxPyApp::_BootstrapApp
497 void __wxPyPreStart(PyObject
* moduleDict
)
501 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
504 #ifdef WXP_WITH_THREAD
505 PyEval_InitThreads();
506 wxPyTStates
= new wxPyThreadStateArray
;
507 wxPyTMutex
= new wxMutex
;
509 // Save the current (main) thread state in our array
510 PyThreadState
* tstate
= wxPyBeginAllowThreads();
511 wxPyEndAllowThreads(tstate
);
514 // Ensure that the build options in the DLL (or whatever) match this build
515 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
517 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
518 wxPy_ReinitStockObjects(1);
523 void __wxPyCleanup() {
524 wxPyDoingCleanup
= True
;
526 wxPyDoCleanup
= False
;
529 #ifdef WXP_WITH_THREAD
532 wxPyTStates
->Empty();
539 // Save a reference to the dictionary of the wx.core module, and inject
540 // a few more things into it.
541 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
544 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
547 if (!PyDict_Check(wxPython_dict
)) {
548 PyErr_SetString(PyExc_TypeError
, "_wxPySetDictionary must have dictionary object!");
552 if (! wxPyPtrTypeMap
)
553 wxPyPtrTypeMap
= PyDict_New();
554 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
556 // Create an exception object to use for wxASSERTions
557 wxPyAssertionError
= PyErr_NewException("wx.core.PyAssertionError",
558 PyExc_AssertionError
, NULL
);
559 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
563 #define wxPlatform "__WXMOTIF__"
564 #define wxPlatName "wxMotif"
567 #define wxPlatform "__WXX11__"
568 #define wxPlatName "wxX11"
571 #define wxPlatform "__WXGTK__"
572 #define wxPlatName "wxGTK"
575 #define wxPlatform "__WXMSW__"
576 #define wxPlatName "wxMSW"
579 #define wxPlatform "__WXMAC__"
580 #define wxPlatName "wxMac"
589 // These should be deprecated in favor of the PlatformInfo tuple built below...
590 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
591 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
592 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
595 PyObject
* PlatInfo
= PyList_New(0);
598 #define _AddInfoString(st) \
599 obj = PyString_FromString(st); \
600 PyList_Append(PlatInfo, obj); \
603 _AddInfoString(wxPlatform
);
604 _AddInfoString(wxPlatName
);
606 _AddInfoString("unicode");
608 _AddInfoString("ascii");
612 _AddInfoString("gtk2");
614 _AddInfoString("gtk1");
618 #undef _AddInfoString
620 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
622 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
628 //---------------------------------------------------------------------------
630 // Python's PyInstance_Check does not return True for instances of new-style
631 // classes. This should get close enough for both new and old classes but I
632 // should re-evaluate the need for doing instance checks...
633 bool wxPyInstance_Check(PyObject
* obj
) {
634 return PyObject_HasAttrString(obj
, "__class__") != 0;
638 // This one checks if the object is an instance of a SWIG proxy class (it has
639 // a .this attribute)
640 bool wxPySwigInstance_Check(PyObject
* obj
) {
641 return PyObject_HasAttrString(obj
, "this") != 0;
644 //---------------------------------------------------------------------------
646 // The stock objects are no longer created when the wxc module is imported,
647 // but only after the app object has been created. The
648 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
649 // objects though various stages of evolution:
651 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
652 // object will be created (otherwise it will just use None.)
654 // pass 2: After the module has been imported and the python proxys have
655 // been created, then set the __class__ to be _wxPyUnbornObject so
656 // it will catch any access to the object and will raise an exception.
658 // pass 3: Finally, from OnInit patch things up so the stock objects can
662 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
664 wxPy_ReinitStockObjects(2);
669 static void rsoPass2(const char* name
)
671 static PyObject
* unbornObjectClass
= NULL
;
674 if (unbornObjectClass
== NULL
) {
675 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
676 Py_INCREF(unbornObjectClass
);
679 // Find the object instance
680 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
681 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
682 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
685 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
689 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
695 // Find the object instance
696 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
697 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
698 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
700 // Find the class object and put it back in the instance
701 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
702 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
703 PyObject_SetAttrString(obj
, "__class__", classobj
);
705 // Rebuild the .this swigified pointer with the new value of the C++ pointer
706 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
707 PyObject_SetAttrString(obj
, "this", ptrobj
);
713 void wxPy_ReinitStockObjects(int pass
)
716 #define REINITOBJ(name, classname) \
717 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
718 else if (pass == 2) { rsoPass2(#name); } \
719 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
722 #define REINITOBJ2(name, classname) \
724 else if (pass == 2) { rsoPass2(#name); } \
725 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
728 REINITOBJ(wxNORMAL_FONT
, wxFont
);
729 REINITOBJ(wxSMALL_FONT
, wxFont
);
730 REINITOBJ(wxITALIC_FONT
, wxFont
);
731 REINITOBJ(wxSWISS_FONT
, wxFont
);
733 REINITOBJ(wxRED_PEN
, wxPen
);
734 REINITOBJ(wxCYAN_PEN
, wxPen
);
735 REINITOBJ(wxGREEN_PEN
, wxPen
);
736 REINITOBJ(wxBLACK_PEN
, wxPen
);
737 REINITOBJ(wxWHITE_PEN
, wxPen
);
738 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
739 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
740 REINITOBJ(wxGREY_PEN
, wxPen
);
741 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
742 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
744 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
745 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
746 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
747 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
748 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
749 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
750 REINITOBJ(wxRED_BRUSH
, wxBrush
);
751 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
752 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
753 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
755 REINITOBJ(wxBLACK
, wxColour
);
756 REINITOBJ(wxWHITE
, wxColour
);
757 REINITOBJ(wxRED
, wxColour
);
758 REINITOBJ(wxBLUE
, wxColour
);
759 REINITOBJ(wxGREEN
, wxColour
);
760 REINITOBJ(wxCYAN
, wxColour
);
761 REINITOBJ(wxLIGHT_GREY
, wxColour
);
763 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
764 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
765 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
767 REINITOBJ2(wxNullBitmap
, wxBitmap
);
768 REINITOBJ2(wxNullIcon
, wxIcon
);
769 REINITOBJ2(wxNullCursor
, wxCursor
);
770 REINITOBJ2(wxNullPen
, wxPen
);
771 REINITOBJ2(wxNullBrush
, wxBrush
);
772 REINITOBJ2(wxNullPalette
, wxPalette
);
773 REINITOBJ2(wxNullFont
, wxFont
);
774 REINITOBJ2(wxNullColour
, wxColour
);
776 REINITOBJ(wxTheFontList
, wxFontList
);
777 REINITOBJ(wxThePenList
, wxPenList
);
778 REINITOBJ(wxTheBrushList
, wxBrushList
);
779 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
782 REINITOBJ(wxTheClipboard
, wxClipboard
);
783 REINITOBJ2(wxDefaultValidator
, wxValidator
);
784 REINITOBJ2(wxNullImage
, wxImage
);
785 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
791 //---------------------------------------------------------------------------
793 void wxPyClientData_dtor(wxPyClientData
* self
) {
794 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
795 // may have already garbage collected the object...
796 wxPyBeginBlockThreads();
797 Py_DECREF(self
->m_obj
);
799 wxPyEndBlockThreads();
803 void wxPyUserData_dtor(wxPyUserData
* self
) {
804 if (! wxPyDoingCleanup
) {
805 wxPyBeginBlockThreads();
806 Py_DECREF(self
->m_obj
);
808 wxPyEndBlockThreads();
813 // This is called when an OOR controled object is being destroyed. Although
814 // the C++ object is going away there is no way to force the Python object
815 // (and all references to it) to die too. This causes problems (crashes) in
816 // wxPython when a python shadow object attempts to call a C++ method using
817 // the now bogus pointer... So to try and prevent this we'll do a little black
818 // magic and change the class of the python instance to a class that will
819 // raise an exception for any attempt to call methods with it. See
820 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
821 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
823 static PyObject
* deadObjectClass
= NULL
;
825 wxPyBeginBlockThreads();
826 if (deadObjectClass
== NULL
) {
827 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
828 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
829 // will lead to a deadlock when it tries to aquire the GIL again.
830 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
831 Py_INCREF(deadObjectClass
);
835 // Only if there is more than one reference to the object
836 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
837 // bool isInstance = wxPyInstance_Check(self->m_obj);
839 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
841 // Call __del__, if there is one.
842 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
844 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
848 if (PyErr_Occurred())
849 PyErr_Clear(); // just ignore it for now
852 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
854 // Clear the instance's dictionary
857 // put the name of the old class into the instance, and then reset the
858 // class to be the dead class.
859 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
860 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
861 PyDict_SetItemString(dict
, "_name", name
);
862 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
863 //Py_INCREF(deadObjectClass);
869 // m_obj is DECREF'd in the base class dtor...
870 wxPyEndBlockThreads();
874 //---------------------------------------------------------------------------
875 // Stuff used by OOR to find the right wxPython class type to return and to
879 // The pointer type map is used when the "pointer" type name generated by SWIG
880 // is not the same as the shadow class name, for example wxPyTreeCtrl
881 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
882 // so we'll just make it a Python dictionary in the wx module's namespace.
883 // (See __wxSetDictionary)
884 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
885 if (! wxPyPtrTypeMap
)
886 wxPyPtrTypeMap
= PyDict_New();
887 PyDict_SetItemString(wxPyPtrTypeMap
,
889 PyString_FromString((char*)ptrName
));
895 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
896 PyObject
* target
= NULL
;
897 bool isEvtHandler
= False
;
900 // If it's derived from wxEvtHandler then there may
901 // already be a pointer to a Python object that we can use
903 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
905 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
906 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
908 target
= data
->m_obj
;
915 // Otherwise make it the old fashioned way by making a new shadow
916 // object and putting this pointer in it. Look up the class
917 // heirarchy until we find a class name that is located in the
919 const wxClassInfo
* info
= source
->GetClassInfo();
920 wxString name
= info
->GetClassName();
921 bool exists
= wxPyCheckSwigType(name
);
922 while (info
&& !exists
) {
923 info
= info
->GetBaseClass1();
924 name
= info
->GetClassName();
925 exists
= wxPyCheckSwigType(name
);
928 target
= wxPyConstructObject((void*)source
, name
, False
);
929 if (target
&& isEvtHandler
)
930 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
932 wxString
msg(wxT("wxPython class not found for "));
933 msg
+= source
->GetClassInfo()->GetClassName();
934 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
938 } else { // source was NULL so return None.
939 Py_INCREF(Py_None
); target
= Py_None
;
945 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
946 PyObject
* target
= NULL
;
948 if (source
&& wxIsKindOf(source
, wxSizer
)) {
949 // If it's derived from wxSizer then there may already be a pointer to
950 // a Python object that we can use in the OOR data.
951 wxSizer
* sz
= (wxSizer
*)source
;
952 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
954 target
= data
->m_obj
;
960 target
= wxPyMake_wxObject(source
, False
);
961 if (target
!= Py_None
)
962 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
968 //---------------------------------------------------------------------------
971 #ifdef WXP_WITH_THREAD
973 unsigned long wxPyGetCurrentThreadId() {
974 return wxThread::GetCurrentId();
977 static wxPyThreadState gs_shutdownTState
;
980 wxPyThreadState
* wxPyGetThreadState() {
981 if (wxPyTMutex
== NULL
) // Python is shutting down...
982 return &gs_shutdownTState
;
984 unsigned long ctid
= wxPyGetCurrentThreadId();
985 wxPyThreadState
* tstate
= NULL
;
988 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
989 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
990 if (info
.tid
== ctid
) {
995 wxPyTMutex
->Unlock();
996 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1002 void wxPySaveThreadState(PyThreadState
* tstate
) {
1003 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1004 gs_shutdownTState
.tstate
= tstate
;
1007 unsigned long ctid
= wxPyGetCurrentThreadId();
1009 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1010 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1011 if (info
.tid
== ctid
) {
1013 if (info
.tstate
!= tstate
)
1014 wxLogMessage("*** tstate mismatch!???");
1016 // info.tstate = tstate; *** DO NOT update existing ones???
1017 // Normally it will never change, but apparently COM callbacks
1018 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1019 // tstate which will then be garbage the next time we try to use
1021 wxPyTMutex
->Unlock();
1025 // not found, so add it...
1026 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1027 wxPyTMutex
->Unlock();
1034 // Calls from Python to wxWindows code are wrapped in calls to these
1037 PyThreadState
* wxPyBeginAllowThreads() {
1038 #ifdef WXP_WITH_THREAD
1039 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1040 wxPySaveThreadState(saved
);
1041 wxPyGetThreadState()->blocked
-= 1;
1048 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1049 #ifdef WXP_WITH_THREAD
1050 wxPyGetThreadState()->blocked
+= 1;
1051 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1057 // Calls from wxWindows back to Python code, or even any PyObject
1058 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1060 void wxPyBeginBlockThreads() {
1061 #ifdef WXP_WITH_THREAD
1062 wxPyThreadState
* tstate
= wxPyGetThreadState();
1063 if (tstate
->blocked
++ == 0) { // if nested calls then do nothing
1064 PyEval_RestoreThread(tstate
->tstate
);
1070 void wxPyEndBlockThreads() {
1071 #ifdef WXP_WITH_THREAD
1072 wxPyThreadState
* tstate
= wxPyGetThreadState();
1073 tstate
->blocked
-= 1;
1074 if ( tstate
->blocked
== 0) { // if nested calls then do nothing
1075 PyEval_SaveThread();
1081 //---------------------------------------------------------------------------
1082 // wxPyInputStream and wxPyCBInputStream methods
1085 void wxPyInputStream::close() {
1086 /* do nothing for now */
1089 void wxPyInputStream::flush() {
1090 /* do nothing for now */
1093 bool wxPyInputStream::eof() {
1095 return m_wxis
->Eof();
1100 wxPyInputStream::~wxPyInputStream() {
1107 PyObject
* wxPyInputStream::read(int size
) {
1108 PyObject
* obj
= NULL
;
1110 const int BUFSIZE
= 1024;
1112 // check if we have a real wxInputStream to work with
1114 wxPyBeginBlockThreads();
1115 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1116 wxPyEndBlockThreads();
1121 // read while bytes are available on the stream
1122 while ( m_wxis
->CanRead() ) {
1123 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1124 buf
.UngetAppendBuf(m_wxis
->LastRead());
1127 } else { // Read only size number of characters
1128 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1129 buf
.UngetWriteBuf(m_wxis
->LastRead());
1133 wxPyBeginBlockThreads();
1134 wxStreamError err
= m_wxis
->GetLastError();
1135 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1136 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1139 // We use only strings for the streams, not unicode
1140 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1142 wxPyEndBlockThreads();
1147 PyObject
* wxPyInputStream::readline(int size
) {
1148 PyObject
* obj
= NULL
;
1153 // check if we have a real wxInputStream to work with
1155 wxPyBeginBlockThreads();
1156 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1157 wxPyEndBlockThreads();
1161 // read until \n or byte limit reached
1162 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1163 ch
= m_wxis
->GetC();
1168 wxPyBeginBlockThreads();
1169 wxStreamError err
= m_wxis
->GetLastError();
1170 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1171 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1174 // We use only strings for the streams, not unicode
1175 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1177 wxPyEndBlockThreads();
1182 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1185 // check if we have a real wxInputStream to work with
1187 wxPyBeginBlockThreads();
1188 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1189 wxPyEndBlockThreads();
1194 wxPyBeginBlockThreads();
1195 pylist
= PyList_New(0);
1197 wxPyBeginBlockThreads();
1199 wxPyEndBlockThreads();
1203 // read sizehint bytes or until EOF
1205 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1206 PyObject
* s
= this->readline();
1208 wxPyBeginBlockThreads();
1210 wxPyEndBlockThreads();
1213 wxPyBeginBlockThreads();
1214 PyList_Append(pylist
, s
);
1215 i
+= PyString_Size(s
);
1216 wxPyEndBlockThreads();
1220 wxStreamError err
= m_wxis
->GetLastError();
1221 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1222 wxPyBeginBlockThreads();
1224 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1225 wxPyEndBlockThreads();
1233 void wxPyInputStream::seek(int offset
, int whence
) {
1235 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1238 int wxPyInputStream::tell(){
1240 return m_wxis
->TellI();
1247 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1248 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1252 wxPyCBInputStream::~wxPyCBInputStream() {
1253 if (m_block
) wxPyBeginBlockThreads();
1257 if (m_block
) wxPyEndBlockThreads();
1261 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1262 if (block
) wxPyBeginBlockThreads();
1264 PyObject
* read
= getMethod(py
, "read");
1265 PyObject
* seek
= getMethod(py
, "seek");
1266 PyObject
* tell
= getMethod(py
, "tell");
1269 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1273 if (block
) wxPyEndBlockThreads();
1277 if (block
) wxPyEndBlockThreads();
1278 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1282 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1283 return wxPyCBInputStream::create(py
, block
);
1286 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1287 if (!PyObject_HasAttrString(py
, name
))
1289 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1290 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1298 size_t wxPyCBInputStream::GetSize() const {
1299 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1300 if (m_seek
&& m_tell
) {
1301 off_t temp
= self
->OnSysTell();
1302 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1303 self
->OnSysSeek(temp
, wxFromStart
);
1311 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1315 wxPyBeginBlockThreads();
1316 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1317 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1321 if ((result
!= NULL
) && PyString_Check(result
)) {
1322 o
= PyString_Size(result
);
1324 m_lasterror
= wxSTREAM_EOF
;
1327 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1332 m_lasterror
= wxSTREAM_READ_ERROR
;
1333 wxPyEndBlockThreads();
1337 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1338 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1342 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1343 wxPyBeginBlockThreads();
1345 // off_t is a 64-bit value...
1346 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1348 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1350 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1353 wxPyEndBlockThreads();
1358 off_t
wxPyCBInputStream::OnSysTell() const {
1359 wxPyBeginBlockThreads();
1360 PyObject
* arglist
= Py_BuildValue("()");
1361 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1364 if (result
!= NULL
) {
1366 if (PyLong_Check(result
))
1367 o
= PyLong_AsLongLong(result
);
1370 o
= PyInt_AsLong(result
);
1373 wxPyEndBlockThreads();
1377 //----------------------------------------------------------------------
1379 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1381 wxPyCallback::wxPyCallback(PyObject
* func
) {
1386 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1387 m_func
= other
.m_func
;
1391 wxPyCallback::~wxPyCallback() {
1392 wxPyBeginBlockThreads();
1394 wxPyEndBlockThreads();
1399 // This function is used for all events destined for Python event handlers.
1400 void wxPyCallback::EventThunker(wxEvent
& event
) {
1401 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1402 PyObject
* func
= cb
->m_func
;
1406 bool checkSkip
= False
;
1408 wxPyBeginBlockThreads();
1409 wxString className
= event
.GetClassInfo()->GetClassName();
1411 // If the event is one of these types then pass the original
1412 // event object instead of the one passed to us.
1413 if ( className
== wxT("wxPyEvent") ) {
1414 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1415 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1417 else if ( className
== wxT("wxPyCommandEvent") ) {
1418 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1419 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1422 arg
= wxPyConstructObject((void*)&event
, className
);
1428 // Check if the event object needs some preinitialization
1429 if (PyObject_HasAttrString(arg
, "_preInit")) {
1430 result
= PyObject_CallMethod(arg
, "_preInit", "O", arg
);
1432 Py_DECREF(result
); // result is ignored, but we still need to decref it
1433 PyErr_Clear(); // Just in case...
1439 // Call the event handler, passing the event object
1440 tuple
= PyTuple_New(1);
1441 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1442 result
= PyEval_CallObject(func
, tuple
);
1444 Py_DECREF(result
); // result is ignored, but we still need to decref it
1445 PyErr_Clear(); // Just in case...
1451 // if the event object was one of our special types and
1452 // it had been cloned, then we need to extract the Skipped
1453 // value from the original and set it in the clone.
1454 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1456 event
.Skip(PyInt_AsLong(result
));
1464 wxPyEndBlockThreads();
1468 //----------------------------------------------------------------------
1470 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1472 m_self
= other
.m_self
;
1473 m_class
= other
.m_class
;
1481 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1492 #if PYTHON_API_VERSION >= 1011
1494 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1495 // in which the method was defined. Starting with 2.2 it returns
1496 // "class that asked for the method" which seems totally bogus to me
1497 // but apprently it fixes some obscure problem waiting to happen in
1498 // Python. Since the API was not documented Guido and the gang felt
1499 // safe in changing it. Needless to say that totally screwed up the
1500 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1501 // code to find the class where the method is actually defined...
1504 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1508 if (PyType_Check(klass
)) { // new style classes
1509 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1510 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1511 PyObject
*mro
, *res
, *base
, *dict
;
1512 /* Look in tp_dict of types in MRO */
1514 assert(PyTuple_Check(mro
));
1515 n
= PyTuple_GET_SIZE(mro
);
1516 for (i
= 0; i
< n
; i
++) {
1517 base
= PyTuple_GET_ITEM(mro
, i
);
1518 if (PyClass_Check(base
))
1519 dict
= ((PyClassObject
*)base
)->cl_dict
;
1521 assert(PyType_Check(base
));
1522 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1524 assert(dict
&& PyDict_Check(dict
));
1525 res
= PyDict_GetItem(dict
, name
);
1532 else if (PyClass_Check(klass
)) { // old style classes
1533 // This code is borrowed/adapted from class_lookup in classobject.c
1534 PyClassObject
* cp
= (PyClassObject
*)klass
;
1535 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1536 if (value
!= NULL
) {
1537 return (PyObject
*)cp
;
1539 n
= PyTuple_Size(cp
->cl_bases
);
1540 for (i
= 0; i
< n
; i
++) {
1541 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1542 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1554 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1556 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1558 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1560 #else // 2.2 and after, the hard way...
1562 PyObject
* nameo
= PyString_FromString(name
);
1563 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1571 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1572 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1573 self
->m_lastFound
= NULL
;
1575 // If the object (m_self) has an attibute of the given name...
1576 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1577 PyObject
*method
, *klass
;
1578 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1580 // ...and if that attribute is a method, and if that method's class is
1581 // not from a base class...
1582 if (PyMethod_Check(method
) &&
1583 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1584 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1586 // ...then we'll save a pointer to the method so callCallback can call it.
1587 self
->m_lastFound
= method
;
1593 return m_lastFound
!= NULL
;
1597 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1601 result
= callCallbackObj(argTuple
);
1602 if (result
) { // Assumes an integer return type...
1603 retval
= PyInt_AsLong(result
);
1605 PyErr_Clear(); // forget about it if it's not...
1610 // Invoke the Python callable object, returning the raw PyObject return
1611 // value. Caller should DECREF the return value and also manage the GIL.
1612 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1615 // Save a copy of the pointer in case the callback generates another
1616 // callback. In that case m_lastFound will have a different value when
1617 // it gets back here...
1618 PyObject
* method
= m_lastFound
;
1620 result
= PyEval_CallObject(method
, argTuple
);
1621 Py_DECREF(argTuple
);
1630 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1631 cbh
.setSelf(self
, klass
, incref
);
1634 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1635 return cbh
.findCallback(name
);
1638 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1639 return cbh
.callCallback(argTuple
);
1642 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1643 return cbh
.callCallbackObj(argTuple
);
1647 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1648 if (cbh
->m_incRef
) {
1649 wxPyBeginBlockThreads();
1650 Py_XDECREF(cbh
->m_self
);
1651 Py_XDECREF(cbh
->m_class
);
1652 wxPyEndBlockThreads();
1656 //---------------------------------------------------------------------------
1657 //---------------------------------------------------------------------------
1658 // These event classes can be derived from in Python and passed through the event
1659 // system without losing anything. They do this by keeping a reference to
1660 // themselves and some special case handling in wxPyCallback::EventThunker.
1663 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1664 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1665 //Py_INCREF(m_self); // circular loops...
1669 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1670 wxPyBeginBlockThreads();
1673 wxPyEndBlockThreads();
1676 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1677 wxPyBeginBlockThreads();
1685 wxPyEndBlockThreads();
1688 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1694 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1695 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1698 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1699 : wxEvent(winid
, commandType
) {
1703 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1706 SetSelf(evt
.m_self
, True
);
1710 wxPyEvent::~wxPyEvent() {
1714 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1715 : wxCommandEvent(commandType
, id
) {
1719 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1720 : wxCommandEvent(evt
)
1722 SetSelf(evt
.m_self
, True
);
1726 wxPyCommandEvent::~wxPyCommandEvent() {
1733 //---------------------------------------------------------------------------
1734 //---------------------------------------------------------------------------
1735 // Convert a wxList to a Python List, only works for lists of wxObjects
1737 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1738 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1742 wxNode
* node
= list
->GetFirst();
1744 wxPyBeginBlockThreads();
1745 pyList
= PyList_New(0);
1747 wxObj
= node
->GetData();
1748 pyObj
= wxPyMake_wxObject(wxObj
);
1749 PyList_Append(pyList
, pyObj
);
1750 node
= node
->GetNext();
1752 wxPyEndBlockThreads();
1756 //----------------------------------------------------------------------
1758 long wxPyGetWinHandle(wxWindow
* win
) {
1761 return (long)win
->GetHandle();
1764 // Find and return the actual X-Window.
1766 if (win
->m_wxwindow
) {
1768 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1770 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1772 return (long)bwin
->xwindow
;
1779 return (long)MAC_WXHWND(win
->MacGetRootWindow());
1785 //----------------------------------------------------------------------
1786 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1787 // included in every file over and over again...
1789 #if PYTHON_API_VERSION >= 1009
1790 static char* wxStringErrorMsg
= "String or Unicode type required";
1792 static char* wxStringErrorMsg
= "String type required";
1796 wxString
* wxString_in_helper(PyObject
* source
) {
1798 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1799 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1800 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1804 if (PyUnicode_Check(source
)) {
1805 target
= new wxString();
1806 size_t len
= PyUnicode_GET_SIZE(source
);
1808 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1809 target
->UngetWriteBuf();
1812 // It is a string, get pointers to it and transform to unicode
1813 char* tmpPtr
; int tmpSize
;
1814 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1815 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1818 char* tmpPtr
; int tmpSize
;
1819 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1820 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1823 target
= new wxString(tmpPtr
, tmpSize
);
1824 #endif // wxUSE_UNICODE
1826 #else // No Python unicode API (1.5.2)
1827 if (!PyString_Check(source
)) {
1828 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1831 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1837 // Similar to above except doesn't use "new" and doesn't set an exception
1838 wxString
Py2wxString(PyObject
* source
)
1841 bool doDecRef
= False
;
1843 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1844 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1845 // Convert to String if not one already... (TODO: Unicode too?)
1846 source
= PyObject_Str(source
);
1851 if (PyUnicode_Check(source
)) {
1852 size_t len
= PyUnicode_GET_SIZE(source
);
1854 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1855 target
.UngetWriteBuf();
1858 // It is a string, get pointers to it and transform to unicode
1859 char* tmpPtr
; int tmpSize
;
1860 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1861 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1864 char* tmpPtr
; int tmpSize
;
1865 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1866 target
= wxString(tmpPtr
, tmpSize
);
1867 #endif // wxUSE_UNICODE
1869 #else // No Python unicode API (1.5.2)
1870 if (!PyString_Check(source
)) {
1871 // Convert to String if not one already...
1872 source
= PyObject_Str(source
);
1875 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1884 // Make either a Python String or Unicode object, depending on build mode
1885 PyObject
* wx2PyString(const wxString
& src
)
1889 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1891 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1897 //----------------------------------------------------------------------
1900 byte
* byte_LIST_helper(PyObject
* source
) {
1901 if (!PyList_Check(source
)) {
1902 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1905 int count
= PyList_Size(source
);
1906 byte
* temp
= new byte
[count
];
1908 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1911 for (int x
=0; x
<count
; x
++) {
1912 PyObject
* o
= PyList_GetItem(source
, x
);
1913 if (! PyInt_Check(o
)) {
1914 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1917 temp
[x
] = (byte
)PyInt_AsLong(o
);
1923 int* int_LIST_helper(PyObject
* source
) {
1924 if (!PyList_Check(source
)) {
1925 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1928 int count
= PyList_Size(source
);
1929 int* temp
= new int[count
];
1931 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1934 for (int x
=0; x
<count
; x
++) {
1935 PyObject
* o
= PyList_GetItem(source
, x
);
1936 if (! PyInt_Check(o
)) {
1937 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1940 temp
[x
] = PyInt_AsLong(o
);
1946 long* long_LIST_helper(PyObject
* source
) {
1947 if (!PyList_Check(source
)) {
1948 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1951 int count
= PyList_Size(source
);
1952 long* temp
= new long[count
];
1954 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1957 for (int x
=0; x
<count
; x
++) {
1958 PyObject
* o
= PyList_GetItem(source
, x
);
1959 if (! PyInt_Check(o
)) {
1960 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1963 temp
[x
] = PyInt_AsLong(o
);
1969 char** string_LIST_helper(PyObject
* source
) {
1970 if (!PyList_Check(source
)) {
1971 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1974 int count
= PyList_Size(source
);
1975 char** temp
= new char*[count
];
1977 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1980 for (int x
=0; x
<count
; x
++) {
1981 PyObject
* o
= PyList_GetItem(source
, x
);
1982 if (! PyString_Check(o
)) {
1983 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1986 temp
[x
] = PyString_AsString(o
);
1991 //--------------------------------
1992 // Part of patch from Tim Hochberg
1993 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1994 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1995 point
->x
= PyInt_AS_LONG(o1
);
1996 point
->y
= PyInt_AS_LONG(o2
);
1999 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2000 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2001 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2004 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2005 // Disallow instances because they can cause havok
2008 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2009 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2010 point
->x
= PyInt_AsLong(o1
);
2011 point
->y
= PyInt_AsLong(o2
);
2018 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2019 // Putting all of the declarations here allows
2020 // us to put the error handling all in one place.
2023 PyObject
*o
, *o1
, *o2
;
2024 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2026 if (!PySequence_Check(source
)) {
2030 // The length of the sequence is returned in count.
2031 *count
= PySequence_Length(source
);
2036 temp
= new wxPoint
[*count
];
2038 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2041 for (x
=0; x
<*count
; x
++) {
2042 // Get an item: try fast way first.
2044 o
= PySequence_Fast_GET_ITEM(source
, x
);
2047 o
= PySequence_GetItem(source
, x
);
2053 // Convert o to wxPoint.
2054 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2055 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2056 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2057 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2058 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2062 else if (wxPySwigInstance_Check(o
)) {
2064 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2069 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2070 o1
= PySequence_GetItem(o
, 0);
2071 o2
= PySequence_GetItem(o
, 1);
2072 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2096 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2100 //------------------------------
2103 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2104 if (!PyList_Check(source
)) {
2105 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2108 int count
= PyList_Size(source
);
2109 wxBitmap
** temp
= new wxBitmap
*[count
];
2111 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2114 for (int x
=0; x
<count
; x
++) {
2115 PyObject
* o
= PyList_GetItem(source
, x
);
2116 if (wxPySwigInstance_Check(o
)) {
2118 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2119 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2125 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2134 wxString
* wxString_LIST_helper(PyObject
* source
) {
2135 if (!PyList_Check(source
)) {
2136 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2139 int count
= PyList_Size(source
);
2140 wxString
* temp
= new wxString
[count
];
2142 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2145 for (int x
=0; x
<count
; x
++) {
2146 PyObject
* o
= PyList_GetItem(source
, x
);
2147 #if PYTHON_API_VERSION >= 1009
2148 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2149 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2153 if (! PyString_Check(o
)) {
2154 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2159 wxString
* pStr
= wxString_in_helper(o
);
2167 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2168 if (!PyList_Check(source
)) {
2169 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2172 int count
= PyList_Size(source
);
2173 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2175 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2178 for (int x
=0; x
<count
; x
++) {
2179 PyObject
* o
= PyList_GetItem(source
, x
);
2180 if (wxPySwigInstance_Check(o
)) {
2181 wxAcceleratorEntry
* ae
;
2182 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2183 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2188 else if (PyTuple_Check(o
)) {
2189 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2190 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2191 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2192 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2195 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2203 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2204 if (!PyList_Check(source
)) {
2205 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2208 int count
= PyList_Size(source
);
2209 wxPen
** temp
= new wxPen
*[count
];
2211 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2214 for (int x
=0; x
<count
; x
++) {
2215 PyObject
* o
= PyList_GetItem(source
, x
);
2216 if (wxPySwigInstance_Check(o
)) {
2218 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2220 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2227 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2235 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2236 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2239 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2243 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2244 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2247 o1
= PySequence_GetItem(source
, 0);
2248 o2
= PySequence_GetItem(source
, 1);
2251 *i1
= PyInt_AsLong(o1
);
2252 *i2
= PyInt_AsLong(o2
);
2262 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2263 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2264 PyObject
*o1
, *o2
, *o3
, *o4
;
2266 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2270 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2271 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2272 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2273 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2276 o1
= PySequence_GetItem(source
, 0);
2277 o2
= PySequence_GetItem(source
, 1);
2278 o3
= PySequence_GetItem(source
, 2);
2279 o4
= PySequence_GetItem(source
, 3);
2282 *i1
= PyInt_AsLong(o1
);
2283 *i2
= PyInt_AsLong(o2
);
2284 *i3
= PyInt_AsLong(o3
);
2285 *i4
= PyInt_AsLong(o4
);
2297 //----------------------------------------------------------------------
2299 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2303 if (wxPySwigInstance_Check(source
) &&
2304 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2308 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2314 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2316 if (source
== Py_None
) {
2317 **obj
= wxSize(-1,-1);
2320 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2324 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2326 if (source
== Py_None
) {
2327 **obj
= wxPoint(-1,-1);
2330 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2335 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2337 if (source
== Py_None
) {
2338 **obj
= wxRealPoint(-1,-1);
2342 // If source is an object instance then it may already be the right type
2343 if (wxPySwigInstance_Check(source
)) {
2345 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2350 // otherwise a 2-tuple of floats is expected
2351 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2352 PyObject
* o1
= PySequence_GetItem(source
, 0);
2353 PyObject
* o2
= PySequence_GetItem(source
, 1);
2354 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2359 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2366 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2372 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2374 if (source
== Py_None
) {
2375 **obj
= wxRect(-1,-1,-1,-1);
2379 // If source is an object instance then it may already be the right type
2380 if (wxPySwigInstance_Check(source
)) {
2382 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2387 // otherwise a 4-tuple of integers is expected
2388 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2389 PyObject
* o1
= PySequence_GetItem(source
, 0);
2390 PyObject
* o2
= PySequence_GetItem(source
, 1);
2391 PyObject
* o3
= PySequence_GetItem(source
, 2);
2392 PyObject
* o4
= PySequence_GetItem(source
, 3);
2393 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2394 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2401 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2402 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2411 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2417 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2419 if (source
== Py_None
) {
2420 **obj
= wxNullColour
;
2424 // If source is an object instance then it may already be the right type
2425 if (wxPySwigInstance_Check(source
)) {
2427 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2432 // otherwise check for a string
2433 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2434 wxString spec
= Py2wxString(source
);
2435 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2436 long red
, green
, blue
;
2437 red
= green
= blue
= 0;
2438 spec
.Mid(1,2).ToLong(&red
, 16);
2439 spec
.Mid(3,2).ToLong(&green
, 16);
2440 spec
.Mid(5,2).ToLong(&blue
, 16);
2442 **obj
= wxColour(red
, green
, blue
);
2445 else { // it's a colour name
2446 **obj
= wxColour(spec
);
2450 // last chance: 3-tuple of integers is expected
2451 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2452 PyObject
* o1
= PySequence_GetItem(source
, 0);
2453 PyObject
* o2
= PySequence_GetItem(source
, 1);
2454 PyObject
* o3
= PySequence_GetItem(source
, 2);
2455 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2461 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2469 PyErr_SetString(PyExc_TypeError
,
2470 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2475 bool wxColour_typecheck(PyObject
* source
) {
2477 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2480 if (PyString_Check(source
) || PyUnicode_Check(source
))
2488 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2490 if (source
== Py_None
) {
2491 **obj
= wxPoint2D(-1,-1);
2495 // If source is an object instance then it may already be the right type
2496 if (wxPySwigInstance_Check(source
)) {
2498 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2503 // otherwise a length-2 sequence of floats is expected
2504 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2505 PyObject
* o1
= PySequence_GetItem(source
, 0);
2506 PyObject
* o2
= PySequence_GetItem(source
, 1);
2507 // This should really check for floats, not numbers -- but that would break code.
2508 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2513 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2519 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2524 //----------------------------------------------------------------------
2526 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2528 PyObject
* list
= PyList_New(0);
2529 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2531 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2533 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2535 PyList_Append(list
, str
);
2542 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2544 PyObject
* list
= PyList_New(0);
2545 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2546 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2547 PyList_Append(list
, number
);
2554 //----------------------------------------------------------------------
2555 //----------------------------------------------------------------------