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>
29 #include <gdk/gdkprivate.h>
30 #include <wx/gtk/win_gtk.h>
31 #define GetXWindow(wxwin) GDK_WINDOW_XWINDOW((wxwin)->m_widget->window)
36 #include "wx/x11/privx.h"
37 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
41 #include <wx/mac/private.h>
44 #include <wx/clipbrd.h>
45 #include <wx/mimetype.h>
48 //----------------------------------------------------------------------
50 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
51 #error Python must support Unicode to use wxWindows Unicode
54 //----------------------------------------------------------------------
56 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
57 bool wxPyDoCleanup
= False
;
58 bool wxPyDoingCleanup
= False
;
61 #ifdef WXP_WITH_THREAD
62 struct wxPyThreadState
{
64 PyThreadState
* tstate
;
66 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
67 : tid(_tid
), tstate(_tstate
) {}
70 #include <wx/dynarray.h>
71 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
72 #include <wx/arrimpl.cpp>
73 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
75 wxPyThreadStateArray
* wxPyTStates
= NULL
;
76 wxMutex
* wxPyTMutex
= NULL
;
80 static PyObject
* wxPython_dict
= NULL
;
81 static PyObject
* wxPyAssertionError
= NULL
;
82 static PyObject
* wxPyNoAppError
= NULL
;
84 PyObject
* wxPyPtrTypeMap
= NULL
;
87 #ifdef __WXMSW__ // If building for win32...
88 //----------------------------------------------------------------------
89 // This gets run when the DLL is loaded. We just need to save a handle.
90 //----------------------------------------------------------------------
93 HINSTANCE hinstDLL
, // handle to DLL module
94 DWORD fdwReason
, // reason for calling function
95 LPVOID lpvReserved
// reserved
98 // If wxPython is embedded in another wxWindows app then
99 // the inatance has already been set.
100 if (! wxGetInstance())
101 wxSetInstance(hinstDLL
);
106 //----------------------------------------------------------------------
107 // Classes for implementing the wxp main application shell.
108 //----------------------------------------------------------------------
110 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
114 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
115 m_startupComplete
= False
;
119 wxPyApp::~wxPyApp() {
123 // This one isn't acutally called... We fake it with _BootstrapApp
124 bool wxPyApp::OnInit() {
129 int wxPyApp::MainLoop() {
132 DeletePendingObjects();
133 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
135 if ( m_exitOnFrameDelete
== Later
) {
136 m_exitOnFrameDelete
= Yes
;
139 retval
= wxApp::MainLoop();
146 bool wxPyApp::OnInitGui() {
148 wxApp::OnInitGui(); // in this case always call the base class version
149 bool blocked
= wxPyBeginBlockThreads();
150 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
151 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
152 wxPyEndBlockThreads(blocked
);
157 int wxPyApp::OnExit() {
159 bool blocked
= wxPyBeginBlockThreads();
160 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
161 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
162 wxPyEndBlockThreads(blocked
);
163 wxApp::OnExit(); // in this case always call the base class version
169 void wxPyApp::OnAssert(const wxChar
*file
,
174 // if we're not fully initialized then just log the error
175 if (! m_startupComplete
) {
178 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
188 // If the OnAssert is overloaded in the Python class then call it...
190 bool blocked
= wxPyBeginBlockThreads();
191 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
192 PyObject
* fso
= wx2PyString(file
);
193 PyObject
* cso
= wx2PyString(file
);
196 mso
= wx2PyString(file
);
198 mso
= Py_None
; Py_INCREF(Py_None
);
200 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
205 wxPyEndBlockThreads(blocked
);
207 // ...otherwise do our own thing with it
210 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
213 // turn it into a Python exception?
214 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
217 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
224 bool blocked
= wxPyBeginBlockThreads();
225 PyObject
* s
= wx2PyString(buf
);
226 PyErr_SetObject(wxPyAssertionError
, s
);
228 wxPyEndBlockThreads(blocked
);
230 // Now when control returns to whatever API wrapper was called from
231 // Python it should detect that an exception is set and will return
232 // NULL, signalling the exception to Python.
235 // Send it to the normal log destination, but only if
236 // not _DIALOG because it will call this too
237 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
240 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
249 // do the normal wx assert dialog?
250 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
251 wxApp::OnAssert(file
, line
, cond
, msg
);
256 // For catching Apple Events
257 void wxPyApp::MacOpenFile(const wxString
&fileName
)
259 bool blocked
= wxPyBeginBlockThreads();
260 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
261 PyObject
* s
= wx2PyString(fileName
);
262 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
265 wxPyEndBlockThreads(blocked
);
268 void wxPyApp::MacPrintFile(const wxString
&fileName
)
270 bool blocked
= wxPyBeginBlockThreads();
271 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
272 PyObject
* s
= wx2PyString(fileName
);
273 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
276 wxPyEndBlockThreads(blocked
);
279 void wxPyApp::MacNewFile()
281 bool blocked
= wxPyBeginBlockThreads();
282 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
283 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
284 wxPyEndBlockThreads(blocked
);
287 void wxPyApp::MacReopenApp()
289 bool blocked
= wxPyBeginBlockThreads();
290 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
291 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
292 wxPyEndBlockThreads(blocked
);
297 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
299 return s_macSupportPCMenuShortcuts
;
306 long wxPyApp::GetMacAboutMenuItemId() {
308 return s_macAboutMenuItemId
;
315 long wxPyApp::GetMacPreferencesMenuItemId() {
317 return s_macPreferencesMenuItemId
;
324 long wxPyApp::GetMacExitMenuItemId() {
326 return s_macExitMenuItemId
;
333 wxString
wxPyApp::GetMacHelpMenuTitleName() {
335 return s_macHelpMenuTitleName
;
337 return wxEmptyString
;
342 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
344 s_macSupportPCMenuShortcuts
= val
;
349 void wxPyApp::SetMacAboutMenuItemId(long val
) {
351 s_macAboutMenuItemId
= val
;
356 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
358 s_macPreferencesMenuItemId
= val
;
363 void wxPyApp::SetMacExitMenuItemId(long val
) {
365 s_macExitMenuItemId
= val
;
370 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
372 s_macHelpMenuTitleName
= val
;
377 // This finishes the initialization of wxWindows and then calls the OnInit
378 // that should be present in the derived (Python) class.
379 void wxPyApp::_BootstrapApp()
382 PyObject
* retval
= NULL
;
383 PyObject
* pyint
= NULL
;
386 // Get any command-line args passed to this program from the sys module
389 bool blocked
= wxPyBeginBlockThreads();
390 PyObject
* sysargv
= PySys_GetObject("argv");
391 if (sysargv
!= NULL
) {
392 argc
= PyList_Size(sysargv
);
393 argv
= new char*[argc
+1];
395 for(x
=0; x
<argc
; x
++) {
396 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
397 argv
[x
] = PyString_AsString(pyArg
);
401 wxPyEndBlockThreads(blocked
);
403 // Initialize wxWidgets
404 result
= wxEntryStart(argc
, argv
);
407 blocked
= wxPyBeginBlockThreads();
409 PyErr_SetString(PyExc_SystemError
,
410 "wxEntryStart failed, unable to initialize wxWidgets!"
412 " (Is DISPLAY set properly?)"
418 // On wxGTK the locale will be changed to match the system settings, but
419 // Python needs to have LC_NUMERIC set to "C" in order for the floating
420 // point conversions and such to work right.
422 setlocale(LC_NUMERIC
, "C");
425 // The stock objects were all NULL when they were loaded into
426 // SWIG generated proxies, so re-init those now...
427 wxPy_ReinitStockObjects(3);
429 // It's now ok to generate exceptions for assertion errors.
430 wxPythonApp
->SetStartupComplete(True
);
432 // Call the Python wxApp's OnInit function
433 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
435 PyObject
* method
= m_myInst
.GetLastFound();
436 PyObject
* argTuple
= PyTuple_New(0);
437 retval
= PyEval_CallObject(method
, argTuple
);
443 pyint
= PyNumber_Int(retval
);
445 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
448 result
= PyInt_AS_LONG(pyint
);
451 // Is it okay if there is no OnInit? Probably so...
456 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
463 wxPyEndBlockThreads(blocked
);
466 //---------------------------------------------------------------------
467 //----------------------------------------------------------------------
471 static char* wxPyCopyCString(const wxChar
* src
)
473 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
474 size_t len
= strlen(buff
);
475 char* dest
= new char[len
+1];
481 static char* wxPyCopyCString(const char* src
) // we need a char version too
483 size_t len
= strlen(src
);
484 char* dest
= new char[len
+1];
490 static wxChar
* wxPyCopyWString(const char *src
)
492 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
493 wxString
str(src
, *wxConvCurrent
);
494 return copystring(str
);
498 static wxChar
* wxPyCopyWString(const wxChar
*src
)
500 return copystring(src
);
506 inline const char* dropwx(const char* name
) {
507 if (name
[0] == 'w' && name
[1] == 'x')
513 //----------------------------------------------------------------------
515 // This function is called when the wx._core_ module is imported to do some
516 // initial setup. (Before there is a wxApp object.) The rest happens in
517 // wxPyApp::_BootstrapApp
518 void __wxPyPreStart(PyObject
* moduleDict
)
522 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
525 #ifdef WXP_WITH_THREAD
526 PyEval_InitThreads();
527 wxPyTStates
= new wxPyThreadStateArray
;
528 wxPyTMutex
= new wxMutex
;
530 // Save the current (main) thread state in our array
531 PyThreadState
* tstate
= wxPyBeginAllowThreads();
532 wxPyEndAllowThreads(tstate
);
535 // Ensure that the build options in the DLL (or whatever) match this build
536 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
538 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
539 wxPy_ReinitStockObjects(1);
541 wxInitAllImageHandlers();
546 void __wxPyCleanup() {
547 wxPyDoingCleanup
= True
;
549 wxPyDoCleanup
= False
;
552 #ifdef WXP_WITH_THREAD
555 wxPyTStates
->Empty();
562 // Save a reference to the dictionary of the wx._core module, and inject
563 // a few more things into it.
564 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
567 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
570 if (!PyDict_Check(wxPython_dict
)) {
571 PyErr_SetString(PyExc_TypeError
,
572 "_wxPySetDictionary must have dictionary object!");
576 if (! wxPyPtrTypeMap
)
577 wxPyPtrTypeMap
= PyDict_New();
578 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
580 // Create an exception object to use for wxASSERTions
581 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
582 PyExc_AssertionError
, NULL
);
583 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
585 // Create an exception object to use when the app object hasn't been created yet
586 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
587 PyExc_RuntimeError
, NULL
);
588 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
593 #define wxPlatform "__WXMOTIF__"
594 #define wxPlatName "wxMotif"
597 #define wxPlatform "__WXX11__"
598 #define wxPlatName "wxX11"
601 #define wxPlatform "__WXGTK__"
602 #define wxPlatName "wxGTK"
605 #define wxPlatform "__WXMSW__"
606 #define wxPlatName "wxMSW"
609 #define wxPlatform "__WXMAC__"
610 #define wxPlatName "wxMac"
619 // These should be deprecated in favor of the PlatformInfo tuple built below...
620 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
621 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
622 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
625 PyObject
* PlatInfo
= PyList_New(0);
628 #define _AddInfoString(st) \
629 obj = PyString_FromString(st); \
630 PyList_Append(PlatInfo, obj); \
633 _AddInfoString(wxPlatform
);
634 _AddInfoString(wxPlatName
);
636 _AddInfoString("unicode");
638 _AddInfoString("ascii");
642 _AddInfoString("gtk2");
644 _AddInfoString("gtk1");
648 _AddInfoString("wx-assertions-on");
650 _AddInfoString("wx-assertions-off");
653 #undef _AddInfoString
655 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
657 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
663 //---------------------------------------------------------------------------
665 // Python's PyInstance_Check does not return True for instances of new-style
666 // classes. This should get close enough for both new and old classes but I
667 // should re-evaluate the need for doing instance checks...
668 bool wxPyInstance_Check(PyObject
* obj
) {
669 return PyObject_HasAttrString(obj
, "__class__") != 0;
673 // This one checks if the object is an instance of a SWIG proxy class (it has
674 // a .this attribute)
675 bool wxPySwigInstance_Check(PyObject
* obj
) {
676 return PyObject_HasAttrString(obj
, "this") != 0;
679 //---------------------------------------------------------------------------
681 // The stock objects are no longer created when the wx._core_ module is
682 // imported, but only after the app object has been created. The
683 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
684 // objects though various stages of evolution:
686 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
687 // object will be created (otherwise SWIG will just use None.)
689 // pass 2: After the module has been imported and the python proxys have
690 // been created, then set the __class__ to be _wxPyUnbornObject so
691 // it will catch any access to the object and will raise an exception.
693 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
697 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
699 wxPy_ReinitStockObjects(2);
704 static void rsoPass2(const char* name
)
706 static PyObject
* unbornObjectClass
= NULL
;
709 if (unbornObjectClass
== NULL
) {
710 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
711 Py_INCREF(unbornObjectClass
);
714 // Find the object instance
715 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
716 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
717 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
720 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
724 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
730 // Find the object instance
731 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
732 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
733 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
735 // Find the class object and put it back in the instance
736 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
737 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
738 PyObject_SetAttrString(obj
, "__class__", classobj
);
740 // Rebuild the .this swigified pointer with the new value of the C++ pointer
741 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
742 PyObject_SetAttrString(obj
, "this", ptrobj
);
748 void wxPy_ReinitStockObjects(int pass
)
751 // If there is already an App object then wxPython is probably embedded in
752 // a wx C++ application, so there is no need to do all this.
753 static bool embedded
= false;
754 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
758 if (pass
== 3 && embedded
)
762 #define REINITOBJ(name, classname) \
763 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
764 else if (pass == 2) { rsoPass2(#name); } \
765 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
768 #define REINITOBJ2(name, classname) \
770 else if (pass == 2) { rsoPass2(#name); } \
771 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
774 REINITOBJ(wxNORMAL_FONT
, wxFont
);
775 REINITOBJ(wxSMALL_FONT
, wxFont
);
776 REINITOBJ(wxITALIC_FONT
, wxFont
);
777 REINITOBJ(wxSWISS_FONT
, wxFont
);
779 REINITOBJ(wxRED_PEN
, wxPen
);
780 REINITOBJ(wxCYAN_PEN
, wxPen
);
781 REINITOBJ(wxGREEN_PEN
, wxPen
);
782 REINITOBJ(wxBLACK_PEN
, wxPen
);
783 REINITOBJ(wxWHITE_PEN
, wxPen
);
784 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
785 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
786 REINITOBJ(wxGREY_PEN
, wxPen
);
787 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
788 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
790 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
791 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
792 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
793 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
794 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
795 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
796 REINITOBJ(wxRED_BRUSH
, wxBrush
);
797 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
798 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
799 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
801 REINITOBJ(wxBLACK
, wxColour
);
802 REINITOBJ(wxWHITE
, wxColour
);
803 REINITOBJ(wxRED
, wxColour
);
804 REINITOBJ(wxBLUE
, wxColour
);
805 REINITOBJ(wxGREEN
, wxColour
);
806 REINITOBJ(wxCYAN
, wxColour
);
807 REINITOBJ(wxLIGHT_GREY
, wxColour
);
809 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
810 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
811 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
813 REINITOBJ2(wxNullBitmap
, wxBitmap
);
814 REINITOBJ2(wxNullIcon
, wxIcon
);
815 REINITOBJ2(wxNullCursor
, wxCursor
);
816 REINITOBJ2(wxNullPen
, wxPen
);
817 REINITOBJ2(wxNullBrush
, wxBrush
);
818 REINITOBJ2(wxNullPalette
, wxPalette
);
819 REINITOBJ2(wxNullFont
, wxFont
);
820 REINITOBJ2(wxNullColour
, wxColour
);
822 REINITOBJ(wxTheFontList
, wxFontList
);
823 REINITOBJ(wxThePenList
, wxPenList
);
824 REINITOBJ(wxTheBrushList
, wxBrushList
);
825 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
828 REINITOBJ(wxTheClipboard
, wxClipboard
);
829 REINITOBJ2(wxDefaultValidator
, wxValidator
);
830 REINITOBJ2(wxNullImage
, wxImage
);
831 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
837 //---------------------------------------------------------------------------
839 // Check for existence of a wxApp, setting an exception if there isn't one.
840 // This doesn't need to aquire the GIL because it should only be called from
841 // an %exception before the lock is released.
843 bool wxPyCheckForApp() {
844 if (wxTheApp
!= NULL
)
847 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
852 //---------------------------------------------------------------------------
855 void wxPyClientData_dtor(wxPyClientData
* self
) {
856 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
857 // may have already garbage collected the object...
858 bool blocked
= wxPyBeginBlockThreads();
859 Py_DECREF(self
->m_obj
);
861 wxPyEndBlockThreads(blocked
);
865 void wxPyUserData_dtor(wxPyUserData
* self
) {
866 if (! wxPyDoingCleanup
) {
867 bool blocked
= wxPyBeginBlockThreads();
868 Py_DECREF(self
->m_obj
);
870 wxPyEndBlockThreads(blocked
);
875 // This is called when an OOR controled object is being destroyed. Although
876 // the C++ object is going away there is no way to force the Python object
877 // (and all references to it) to die too. This causes problems (crashes) in
878 // wxPython when a python shadow object attempts to call a C++ method using
879 // the now bogus pointer... So to try and prevent this we'll do a little black
880 // magic and change the class of the python instance to a class that will
881 // raise an exception for any attempt to call methods with it. See
882 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
883 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
885 static PyObject
* deadObjectClass
= NULL
;
887 bool blocked
= wxPyBeginBlockThreads();
888 if (deadObjectClass
== NULL
) {
889 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
890 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
891 // will lead to a deadlock when it tries to aquire the GIL again.
892 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
893 Py_INCREF(deadObjectClass
);
897 // Only if there is more than one reference to the object
898 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
899 // bool isInstance = wxPyInstance_Check(self->m_obj);
901 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
903 // Call __del__, if there is one.
904 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
906 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
910 if (PyErr_Occurred())
911 PyErr_Clear(); // just ignore it for now
914 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
916 // Clear the instance's dictionary
919 // put the name of the old class into the instance, and then reset the
920 // class to be the dead class.
921 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
922 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
923 PyDict_SetItemString(dict
, "_name", name
);
924 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
925 //Py_INCREF(deadObjectClass);
931 // m_obj is DECREF'd in the base class dtor...
932 wxPyEndBlockThreads(blocked
);
936 //---------------------------------------------------------------------------
937 // Stuff used by OOR to find the right wxPython class type to return and to
941 // The pointer type map is used when the "pointer" type name generated by SWIG
942 // is not the same as the shadow class name, for example wxPyTreeCtrl
943 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
944 // so we'll just make it a Python dictionary in the wx module's namespace.
945 // (See __wxSetDictionary)
946 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
947 if (! wxPyPtrTypeMap
)
948 wxPyPtrTypeMap
= PyDict_New();
949 PyDict_SetItemString(wxPyPtrTypeMap
,
951 PyString_FromString((char*)ptrName
));
957 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
958 PyObject
* target
= NULL
;
959 bool isEvtHandler
= False
;
962 // If it's derived from wxEvtHandler then there may
963 // already be a pointer to a Python object that we can use
965 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
967 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
968 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
970 target
= data
->m_obj
;
977 // Otherwise make it the old fashioned way by making a new shadow
978 // object and putting this pointer in it. Look up the class
979 // heirarchy until we find a class name that is located in the
981 const wxClassInfo
* info
= source
->GetClassInfo();
982 wxString name
= info
->GetClassName();
983 bool exists
= wxPyCheckSwigType(name
);
984 while (info
&& !exists
) {
985 info
= info
->GetBaseClass1();
986 name
= info
->GetClassName();
987 exists
= wxPyCheckSwigType(name
);
990 target
= wxPyConstructObject((void*)source
, name
, False
);
991 if (target
&& isEvtHandler
)
992 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
994 wxString
msg(wxT("wxPython class not found for "));
995 msg
+= source
->GetClassInfo()->GetClassName();
996 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1000 } else { // source was NULL so return None.
1001 Py_INCREF(Py_None
); target
= Py_None
;
1007 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
1008 PyObject
* target
= NULL
;
1010 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1011 // If it's derived from wxSizer then there may already be a pointer to
1012 // a Python object that we can use in the OOR data.
1013 wxSizer
* sz
= (wxSizer
*)source
;
1014 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1016 target
= data
->m_obj
;
1022 target
= wxPyMake_wxObject(source
, False
);
1023 if (target
!= Py_None
)
1024 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1030 //---------------------------------------------------------------------------
1033 #ifdef WXP_WITH_THREAD
1035 unsigned long wxPyGetCurrentThreadId() {
1036 return wxThread::GetCurrentId();
1039 static wxPyThreadState gs_shutdownTState
;
1042 wxPyThreadState
* wxPyGetThreadState() {
1043 if (wxPyTMutex
== NULL
) // Python is shutting down...
1044 return &gs_shutdownTState
;
1046 unsigned long ctid
= wxPyGetCurrentThreadId();
1047 wxPyThreadState
* tstate
= NULL
;
1050 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1051 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1052 if (info
.tid
== ctid
) {
1057 wxPyTMutex
->Unlock();
1058 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1064 void wxPySaveThreadState(PyThreadState
* tstate
) {
1065 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1066 gs_shutdownTState
.tstate
= tstate
;
1069 unsigned long ctid
= wxPyGetCurrentThreadId();
1071 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1072 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1073 if (info
.tid
== ctid
) {
1075 if (info
.tstate
!= tstate
)
1076 wxLogMessage("*** tstate mismatch!???");
1078 // info.tstate = tstate; *** DO NOT update existing ones???
1079 // Normally it will never change, but apparently COM callbacks
1080 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1081 // tstate which will then be garbage the next time we try to use
1083 wxPyTMutex
->Unlock();
1087 // not found, so add it...
1088 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1089 wxPyTMutex
->Unlock();
1096 // Calls from Python to wxWindows code are wrapped in calls to these
1099 PyThreadState
* wxPyBeginAllowThreads() {
1100 #ifdef WXP_WITH_THREAD
1101 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1102 wxPySaveThreadState(saved
);
1109 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1110 #ifdef WXP_WITH_THREAD
1111 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1117 // Calls from wxWindows back to Python code, or even any PyObject
1118 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1120 bool wxPyBeginBlockThreads() {
1121 #ifdef WXP_WITH_THREAD
1122 // This works in for 2.3, maybe a good alternative to find the needed tstate?
1123 // PyThreadState *check = PyGILState_GetThisThreadState();
1125 PyThreadState
*current
= _PyThreadState_Current
;
1127 // Only block if there wasn't already a tstate, or if the current one is
1128 // not the one we are wanting to change to. This should prevent deadlock
1129 // if there are nested calls to wxPyBeginBlockThreads
1130 bool blocked
= false;
1131 wxPyThreadState
* tstate
= wxPyGetThreadState();
1132 if (current
!= tstate
->tstate
) {
1133 PyEval_RestoreThread(tstate
->tstate
);
1141 void wxPyEndBlockThreads(bool blocked
) {
1142 #ifdef WXP_WITH_THREAD
1143 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1144 // The value of blocked passed in needs to be the same as that returned
1145 // from wxPyBeginBlockThreads at the same nesting level.
1147 PyEval_SaveThread();
1153 //---------------------------------------------------------------------------
1154 // wxPyInputStream and wxPyCBInputStream methods
1157 void wxPyInputStream::close() {
1158 /* do nothing for now */
1161 void wxPyInputStream::flush() {
1162 /* do nothing for now */
1165 bool wxPyInputStream::eof() {
1167 return m_wxis
->Eof();
1172 wxPyInputStream::~wxPyInputStream() {
1179 PyObject
* wxPyInputStream::read(int size
) {
1180 PyObject
* obj
= NULL
;
1182 const int BUFSIZE
= 1024;
1184 // check if we have a real wxInputStream to work with
1186 bool blocked
= wxPyBeginBlockThreads();
1187 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1188 wxPyEndBlockThreads(blocked
);
1193 // read while bytes are available on the stream
1194 while ( m_wxis
->CanRead() ) {
1195 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1196 buf
.UngetAppendBuf(m_wxis
->LastRead());
1199 } else { // Read only size number of characters
1200 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1201 buf
.UngetWriteBuf(m_wxis
->LastRead());
1205 bool blocked
= wxPyBeginBlockThreads();
1206 wxStreamError err
= m_wxis
->GetLastError();
1207 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1208 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1211 // We use only strings for the streams, not unicode
1212 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1214 wxPyEndBlockThreads(blocked
);
1219 PyObject
* wxPyInputStream::readline(int size
) {
1220 PyObject
* obj
= NULL
;
1225 // check if we have a real wxInputStream to work with
1227 bool blocked
= wxPyBeginBlockThreads();
1228 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1229 wxPyEndBlockThreads(blocked
);
1233 // read until \n or byte limit reached
1234 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1235 ch
= m_wxis
->GetC();
1240 bool blocked
= wxPyBeginBlockThreads();
1241 wxStreamError err
= m_wxis
->GetLastError();
1242 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1243 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1246 // We use only strings for the streams, not unicode
1247 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1249 wxPyEndBlockThreads(blocked
);
1254 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1257 // check if we have a real wxInputStream to work with
1259 bool blocked
= wxPyBeginBlockThreads();
1260 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1261 wxPyEndBlockThreads(blocked
);
1266 bool blocked
= wxPyBeginBlockThreads();
1267 pylist
= PyList_New(0);
1268 wxPyEndBlockThreads(blocked
);
1271 bool blocked
= wxPyBeginBlockThreads();
1273 wxPyEndBlockThreads(blocked
);
1277 // read sizehint bytes or until EOF
1279 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1280 PyObject
* s
= this->readline();
1282 bool blocked
= wxPyBeginBlockThreads();
1284 wxPyEndBlockThreads(blocked
);
1287 bool blocked
= wxPyBeginBlockThreads();
1288 PyList_Append(pylist
, s
);
1289 i
+= PyString_Size(s
);
1290 wxPyEndBlockThreads(blocked
);
1294 wxStreamError err
= m_wxis
->GetLastError();
1295 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1296 bool blocked
= wxPyBeginBlockThreads();
1298 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1299 wxPyEndBlockThreads(blocked
);
1307 void wxPyInputStream::seek(int offset
, int whence
) {
1309 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1312 int wxPyInputStream::tell(){
1314 return m_wxis
->TellI();
1321 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1322 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1326 wxPyCBInputStream::~wxPyCBInputStream() {
1328 if (m_block
) blocked
= wxPyBeginBlockThreads();
1332 if (m_block
) wxPyEndBlockThreads(blocked
);
1336 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1338 if (block
) blocked
= wxPyBeginBlockThreads();
1340 PyObject
* read
= getMethod(py
, "read");
1341 PyObject
* seek
= getMethod(py
, "seek");
1342 PyObject
* tell
= getMethod(py
, "tell");
1345 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1349 if (block
) wxPyEndBlockThreads(blocked
);
1353 if (block
) wxPyEndBlockThreads(blocked
);
1354 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1358 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1359 return wxPyCBInputStream::create(py
, block
);
1362 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1363 if (!PyObject_HasAttrString(py
, name
))
1365 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1366 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1374 size_t wxPyCBInputStream::GetSize() const {
1375 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1376 if (m_seek
&& m_tell
) {
1377 off_t temp
= self
->OnSysTell();
1378 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1379 self
->OnSysSeek(temp
, wxFromStart
);
1387 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1391 bool blocked
= wxPyBeginBlockThreads();
1392 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1393 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1397 if ((result
!= NULL
) && PyString_Check(result
)) {
1398 o
= PyString_Size(result
);
1400 m_lasterror
= wxSTREAM_EOF
;
1403 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1408 m_lasterror
= wxSTREAM_READ_ERROR
;
1409 wxPyEndBlockThreads(blocked
);
1413 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1414 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1418 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1419 bool blocked
= wxPyBeginBlockThreads();
1421 // off_t is a 64-bit value...
1422 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1424 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1426 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1429 wxPyEndBlockThreads(blocked
);
1434 off_t
wxPyCBInputStream::OnSysTell() const {
1435 bool blocked
= wxPyBeginBlockThreads();
1436 PyObject
* arglist
= Py_BuildValue("()");
1437 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1440 if (result
!= NULL
) {
1442 if (PyLong_Check(result
))
1443 o
= PyLong_AsLongLong(result
);
1446 o
= PyInt_AsLong(result
);
1449 wxPyEndBlockThreads(blocked
);
1453 //----------------------------------------------------------------------
1455 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1457 wxPyCallback::wxPyCallback(PyObject
* func
) {
1462 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1463 m_func
= other
.m_func
;
1467 wxPyCallback::~wxPyCallback() {
1468 bool blocked
= wxPyBeginBlockThreads();
1470 wxPyEndBlockThreads(blocked
);
1474 #define wxPy_PRECALLINIT "_preCallInit"
1475 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1477 // This function is used for all events destined for Python event handlers.
1478 void wxPyCallback::EventThunker(wxEvent
& event
) {
1479 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1480 PyObject
* func
= cb
->m_func
;
1484 bool checkSkip
= False
;
1486 bool blocked
= wxPyBeginBlockThreads();
1487 wxString className
= event
.GetClassInfo()->GetClassName();
1489 // If the event is one of these types then pass the original
1490 // event object instead of the one passed to us.
1491 if ( className
== wxT("wxPyEvent") ) {
1492 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1493 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1495 else if ( className
== wxT("wxPyCommandEvent") ) {
1496 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1497 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1500 arg
= wxPyConstructObject((void*)&event
, className
);
1506 // "intern" the pre/post method names to speed up the HasAttr
1507 static PyObject
* s_preName
= NULL
;
1508 static PyObject
* s_postName
= NULL
;
1509 if (s_preName
== NULL
) {
1510 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1511 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1514 // Check if the event object needs some preinitialization
1515 if (PyObject_HasAttr(arg
, s_preName
)) {
1516 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1518 Py_DECREF(result
); // result is ignored, but we still need to decref it
1519 PyErr_Clear(); // Just in case...
1525 // Call the event handler, passing the event object
1526 tuple
= PyTuple_New(1);
1527 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1528 result
= PyEval_CallObject(func
, tuple
);
1530 Py_DECREF(result
); // result is ignored, but we still need to decref it
1531 PyErr_Clear(); // Just in case...
1536 // Check if the event object needs some post cleanup
1537 if (PyObject_HasAttr(arg
, s_postName
)) {
1538 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1540 Py_DECREF(result
); // result is ignored, but we still need to decref it
1541 PyErr_Clear(); // Just in case...
1548 // if the event object was one of our special types and
1549 // it had been cloned, then we need to extract the Skipped
1550 // value from the original and set it in the clone.
1551 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1553 event
.Skip(PyInt_AsLong(result
));
1561 wxPyEndBlockThreads(blocked
);
1565 //----------------------------------------------------------------------
1567 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1569 m_self
= other
.m_self
;
1570 m_class
= other
.m_class
;
1578 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1589 #if PYTHON_API_VERSION >= 1011
1591 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1592 // in which the method was defined. Starting with 2.2 it returns
1593 // "class that asked for the method" which seems totally bogus to me
1594 // but apprently it fixes some obscure problem waiting to happen in
1595 // Python. Since the API was not documented Guido and the gang felt
1596 // safe in changing it. Needless to say that totally screwed up the
1597 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1598 // code to find the class where the method is actually defined...
1601 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1605 if (PyType_Check(klass
)) { // new style classes
1606 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1607 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1608 PyObject
*mro
, *res
, *base
, *dict
;
1609 /* Look in tp_dict of types in MRO */
1611 assert(PyTuple_Check(mro
));
1612 n
= PyTuple_GET_SIZE(mro
);
1613 for (i
= 0; i
< n
; i
++) {
1614 base
= PyTuple_GET_ITEM(mro
, i
);
1615 if (PyClass_Check(base
))
1616 dict
= ((PyClassObject
*)base
)->cl_dict
;
1618 assert(PyType_Check(base
));
1619 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1621 assert(dict
&& PyDict_Check(dict
));
1622 res
= PyDict_GetItem(dict
, name
);
1629 else if (PyClass_Check(klass
)) { // old style classes
1630 // This code is borrowed/adapted from class_lookup in classobject.c
1631 PyClassObject
* cp
= (PyClassObject
*)klass
;
1632 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1633 if (value
!= NULL
) {
1634 return (PyObject
*)cp
;
1636 n
= PyTuple_Size(cp
->cl_bases
);
1637 for (i
= 0; i
< n
; i
++) {
1638 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1639 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1651 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1653 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1655 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1657 #else // 2.2 and after, the hard way...
1659 PyObject
* nameo
= PyString_FromString(name
);
1660 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1668 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1669 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1670 self
->m_lastFound
= NULL
;
1672 // If the object (m_self) has an attibute of the given name...
1673 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1674 PyObject
*method
, *klass
;
1675 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1677 // ...and if that attribute is a method, and if that method's class is
1678 // not from a base class...
1679 if (PyMethod_Check(method
) &&
1680 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1681 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1683 // ...then we'll save a pointer to the method so callCallback can call it.
1684 self
->m_lastFound
= method
;
1690 return m_lastFound
!= NULL
;
1694 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1698 result
= callCallbackObj(argTuple
);
1699 if (result
) { // Assumes an integer return type...
1700 retval
= PyInt_AsLong(result
);
1702 PyErr_Clear(); // forget about it if it's not...
1707 // Invoke the Python callable object, returning the raw PyObject return
1708 // value. Caller should DECREF the return value and also manage the GIL.
1709 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1712 // Save a copy of the pointer in case the callback generates another
1713 // callback. In that case m_lastFound will have a different value when
1714 // it gets back here...
1715 PyObject
* method
= m_lastFound
;
1717 result
= PyEval_CallObject(method
, argTuple
);
1718 Py_DECREF(argTuple
);
1727 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1728 cbh
.setSelf(self
, klass
, incref
);
1731 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1732 return cbh
.findCallback(name
);
1735 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1736 return cbh
.callCallback(argTuple
);
1739 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1740 return cbh
.callCallbackObj(argTuple
);
1744 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1745 if (cbh
->m_incRef
) {
1746 bool blocked
= wxPyBeginBlockThreads();
1747 Py_XDECREF(cbh
->m_self
);
1748 Py_XDECREF(cbh
->m_class
);
1749 wxPyEndBlockThreads(blocked
);
1753 //---------------------------------------------------------------------------
1754 //---------------------------------------------------------------------------
1755 // These event classes can be derived from in Python and passed through the event
1756 // system without losing anything. They do this by keeping a reference to
1757 // themselves and some special case handling in wxPyCallback::EventThunker.
1760 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1761 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1762 //Py_INCREF(m_self); // circular loops...
1766 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1767 bool blocked
= wxPyBeginBlockThreads();
1770 wxPyEndBlockThreads(blocked
);
1773 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1774 bool blocked
= wxPyBeginBlockThreads();
1782 wxPyEndBlockThreads(blocked
);
1785 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1791 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1792 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1795 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1796 : wxEvent(winid
, commandType
) {
1800 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1803 SetSelf(evt
.m_self
, True
);
1807 wxPyEvent::~wxPyEvent() {
1811 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1812 : wxCommandEvent(commandType
, id
) {
1816 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1817 : wxCommandEvent(evt
)
1819 SetSelf(evt
.m_self
, True
);
1823 wxPyCommandEvent::~wxPyCommandEvent() {
1830 //---------------------------------------------------------------------------
1831 //---------------------------------------------------------------------------
1832 // Convert a wxList to a Python List, only works for lists of wxObjects
1834 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1835 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1839 wxNode
* node
= list
->GetFirst();
1841 bool blocked
= wxPyBeginBlockThreads();
1842 pyList
= PyList_New(0);
1844 wxObj
= node
->GetData();
1845 pyObj
= wxPyMake_wxObject(wxObj
);
1846 PyList_Append(pyList
, pyObj
);
1847 node
= node
->GetNext();
1849 wxPyEndBlockThreads(blocked
);
1853 //----------------------------------------------------------------------
1855 long wxPyGetWinHandle(wxWindow
* win
) {
1858 return (long)win
->GetHandle();
1861 #if defined(__WXGTK__) || defined(__WXX11)
1862 return (long)GetXWindow(win
);
1866 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1867 return (long)win
->GetHandle();
1873 //----------------------------------------------------------------------
1874 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1875 // included in every file over and over again...
1877 wxString
* wxString_in_helper(PyObject
* source
) {
1878 wxString
* target
= NULL
;
1880 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1881 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1885 PyObject
* uni
= source
;
1886 if (PyString_Check(source
)) {
1887 uni
= PyUnicode_FromObject(source
);
1888 if (PyErr_Occurred()) return NULL
;
1890 target
= new wxString();
1891 size_t len
= PyUnicode_GET_SIZE(uni
);
1893 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1894 target
->UngetWriteBuf();
1897 if (PyString_Check(source
))
1900 char* tmpPtr
; int tmpSize
;
1901 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1902 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1905 target
= new wxString(tmpPtr
, tmpSize
);
1906 #endif // wxUSE_UNICODE
1912 // Similar to above except doesn't use "new" and doesn't set an exception
1913 wxString
Py2wxString(PyObject
* source
)
1918 // Convert to a unicode object, if not already, then to a wxString
1919 PyObject
* uni
= source
;
1920 if (!PyUnicode_Check(source
)) {
1921 uni
= PyUnicode_FromObject(source
);
1922 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1924 size_t len
= PyUnicode_GET_SIZE(uni
);
1926 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1927 target
.UngetWriteBuf();
1930 if (!PyUnicode_Check(source
))
1933 // Convert to a string object if it isn't already, then to wxString
1934 PyObject
* str
= source
;
1935 if (!PyString_Check(source
)) {
1936 str
= PyObject_Str(source
);
1937 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1939 char* tmpPtr
; int tmpSize
;
1940 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1941 target
= wxString(tmpPtr
, tmpSize
);
1943 if (!PyString_Check(source
))
1945 #endif // wxUSE_UNICODE
1951 // Make either a Python String or Unicode object, depending on build mode
1952 PyObject
* wx2PyString(const wxString
& src
)
1956 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1958 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1964 //----------------------------------------------------------------------
1967 byte
* byte_LIST_helper(PyObject
* source
) {
1968 if (!PyList_Check(source
)) {
1969 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1972 int count
= PyList_Size(source
);
1973 byte
* temp
= new byte
[count
];
1975 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1978 for (int x
=0; x
<count
; x
++) {
1979 PyObject
* o
= PyList_GetItem(source
, x
);
1980 if (! PyInt_Check(o
)) {
1981 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1984 temp
[x
] = (byte
)PyInt_AsLong(o
);
1990 int* int_LIST_helper(PyObject
* source
) {
1991 if (!PyList_Check(source
)) {
1992 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1995 int count
= PyList_Size(source
);
1996 int* temp
= new int[count
];
1998 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2001 for (int x
=0; x
<count
; x
++) {
2002 PyObject
* o
= PyList_GetItem(source
, x
);
2003 if (! PyInt_Check(o
)) {
2004 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2007 temp
[x
] = PyInt_AsLong(o
);
2013 long* long_LIST_helper(PyObject
* source
) {
2014 if (!PyList_Check(source
)) {
2015 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2018 int count
= PyList_Size(source
);
2019 long* temp
= new long[count
];
2021 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2024 for (int x
=0; x
<count
; x
++) {
2025 PyObject
* o
= PyList_GetItem(source
, x
);
2026 if (! PyInt_Check(o
)) {
2027 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2030 temp
[x
] = PyInt_AsLong(o
);
2036 char** string_LIST_helper(PyObject
* source
) {
2037 if (!PyList_Check(source
)) {
2038 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2041 int count
= PyList_Size(source
);
2042 char** temp
= new char*[count
];
2044 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2047 for (int x
=0; x
<count
; x
++) {
2048 PyObject
* o
= PyList_GetItem(source
, x
);
2049 if (! PyString_Check(o
)) {
2050 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2053 temp
[x
] = PyString_AsString(o
);
2058 //--------------------------------
2059 // Part of patch from Tim Hochberg
2060 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2061 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2062 point
->x
= PyInt_AS_LONG(o1
);
2063 point
->y
= PyInt_AS_LONG(o2
);
2066 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2067 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2068 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2071 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2072 // Disallow instances because they can cause havok
2075 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2076 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2077 point
->x
= PyInt_AsLong(o1
);
2078 point
->y
= PyInt_AsLong(o2
);
2085 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2086 // Putting all of the declarations here allows
2087 // us to put the error handling all in one place.
2090 PyObject
*o
, *o1
, *o2
;
2091 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2093 if (!PySequence_Check(source
)) {
2097 // The length of the sequence is returned in count.
2098 *count
= PySequence_Length(source
);
2103 temp
= new wxPoint
[*count
];
2105 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2108 for (x
=0; x
<*count
; x
++) {
2109 // Get an item: try fast way first.
2111 o
= PySequence_Fast_GET_ITEM(source
, x
);
2114 o
= PySequence_GetItem(source
, x
);
2120 // Convert o to wxPoint.
2121 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2122 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2123 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2124 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2125 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2129 else if (wxPySwigInstance_Check(o
)) {
2131 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2136 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2137 o1
= PySequence_GetItem(o
, 0);
2138 o2
= PySequence_GetItem(o
, 1);
2139 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2163 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2167 //------------------------------
2170 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2171 if (!PyList_Check(source
)) {
2172 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2175 int count
= PyList_Size(source
);
2176 wxBitmap
** temp
= new wxBitmap
*[count
];
2178 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2181 for (int x
=0; x
<count
; x
++) {
2182 PyObject
* o
= PyList_GetItem(source
, x
);
2183 if (wxPySwigInstance_Check(o
)) {
2185 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2186 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2192 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2201 wxString
* wxString_LIST_helper(PyObject
* source
) {
2202 if (!PyList_Check(source
)) {
2203 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2206 int count
= PyList_Size(source
);
2207 wxString
* temp
= new wxString
[count
];
2209 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2212 for (int x
=0; x
<count
; x
++) {
2213 PyObject
* o
= PyList_GetItem(source
, x
);
2214 #if PYTHON_API_VERSION >= 1009
2215 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2216 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2220 if (! PyString_Check(o
)) {
2221 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2226 wxString
* pStr
= wxString_in_helper(o
);
2234 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2235 if (!PyList_Check(source
)) {
2236 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2239 int count
= PyList_Size(source
);
2240 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2242 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2245 for (int x
=0; x
<count
; x
++) {
2246 PyObject
* o
= PyList_GetItem(source
, x
);
2247 if (wxPySwigInstance_Check(o
)) {
2248 wxAcceleratorEntry
* ae
;
2249 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2250 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2255 else if (PyTuple_Check(o
)) {
2256 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2257 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2258 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2259 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2262 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2270 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2271 if (!PyList_Check(source
)) {
2272 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2275 int count
= PyList_Size(source
);
2276 wxPen
** temp
= new wxPen
*[count
];
2278 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2281 for (int x
=0; x
<count
; x
++) {
2282 PyObject
* o
= PyList_GetItem(source
, x
);
2283 if (wxPySwigInstance_Check(o
)) {
2285 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2287 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2294 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2302 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2303 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2306 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2310 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2311 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2314 o1
= PySequence_GetItem(source
, 0);
2315 o2
= PySequence_GetItem(source
, 1);
2318 *i1
= PyInt_AsLong(o1
);
2319 *i2
= PyInt_AsLong(o2
);
2329 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2330 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2331 PyObject
*o1
, *o2
, *o3
, *o4
;
2333 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2337 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2338 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2339 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2340 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2343 o1
= PySequence_GetItem(source
, 0);
2344 o2
= PySequence_GetItem(source
, 1);
2345 o3
= PySequence_GetItem(source
, 2);
2346 o4
= PySequence_GetItem(source
, 3);
2349 *i1
= PyInt_AsLong(o1
);
2350 *i2
= PyInt_AsLong(o2
);
2351 *i3
= PyInt_AsLong(o3
);
2352 *i4
= PyInt_AsLong(o4
);
2364 //----------------------------------------------------------------------
2366 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2370 if (wxPySwigInstance_Check(source
) &&
2371 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2375 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2381 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2383 if (source
== Py_None
) {
2384 **obj
= wxSize(-1,-1);
2387 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2391 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2393 if (source
== Py_None
) {
2394 **obj
= wxPoint(-1,-1);
2397 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2402 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2404 if (source
== Py_None
) {
2405 **obj
= wxRealPoint(-1,-1);
2409 // If source is an object instance then it may already be the right type
2410 if (wxPySwigInstance_Check(source
)) {
2412 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2417 // otherwise a 2-tuple of floats is expected
2418 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2419 PyObject
* o1
= PySequence_GetItem(source
, 0);
2420 PyObject
* o2
= PySequence_GetItem(source
, 1);
2421 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2426 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2433 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2439 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2441 if (source
== Py_None
) {
2442 **obj
= wxRect(-1,-1,-1,-1);
2446 // If source is an object instance then it may already be the right type
2447 if (wxPySwigInstance_Check(source
)) {
2449 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2454 // otherwise a 4-tuple of integers is expected
2455 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2456 PyObject
* o1
= PySequence_GetItem(source
, 0);
2457 PyObject
* o2
= PySequence_GetItem(source
, 1);
2458 PyObject
* o3
= PySequence_GetItem(source
, 2);
2459 PyObject
* o4
= PySequence_GetItem(source
, 3);
2460 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2461 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2468 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2469 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2478 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2484 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2486 if (source
== Py_None
) {
2487 **obj
= wxNullColour
;
2491 // If source is an object instance then it may already be the right type
2492 if (wxPySwigInstance_Check(source
)) {
2494 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2499 // otherwise check for a string
2500 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2501 wxString spec
= Py2wxString(source
);
2502 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2503 long red
, green
, blue
;
2504 red
= green
= blue
= 0;
2505 spec
.Mid(1,2).ToLong(&red
, 16);
2506 spec
.Mid(3,2).ToLong(&green
, 16);
2507 spec
.Mid(5,2).ToLong(&blue
, 16);
2509 **obj
= wxColour(red
, green
, blue
);
2512 else { // it's a colour name
2513 **obj
= wxColour(spec
);
2517 // last chance: 3-tuple of integers is expected
2518 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2519 PyObject
* o1
= PySequence_GetItem(source
, 0);
2520 PyObject
* o2
= PySequence_GetItem(source
, 1);
2521 PyObject
* o3
= PySequence_GetItem(source
, 2);
2522 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2528 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2536 PyErr_SetString(PyExc_TypeError
,
2537 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2542 bool wxColour_typecheck(PyObject
* source
) {
2544 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2547 if (PyString_Check(source
) || PyUnicode_Check(source
))
2555 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2557 if (source
== Py_None
) {
2558 **obj
= wxPoint2D(-1,-1);
2562 // If source is an object instance then it may already be the right type
2563 if (wxPySwigInstance_Check(source
)) {
2565 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2570 // otherwise a length-2 sequence of floats is expected
2571 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2572 PyObject
* o1
= PySequence_GetItem(source
, 0);
2573 PyObject
* o2
= PySequence_GetItem(source
, 1);
2574 // This should really check for floats, not numbers -- but that would break code.
2575 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2580 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2586 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2591 //----------------------------------------------------------------------
2593 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2595 PyObject
* list
= PyList_New(0);
2596 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2598 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2600 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2602 PyList_Append(list
, str
);
2609 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2611 PyObject
* list
= PyList_New(0);
2612 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2613 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2614 PyList_Append(list
, number
);
2621 //----------------------------------------------------------------------
2622 //----------------------------------------------------------------------