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 REINITOBJ2(wxDefaultValidator
, wxValidator
);
829 REINITOBJ2(wxNullImage
, wxImage
);
830 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
836 //---------------------------------------------------------------------------
838 // Check for existence of a wxApp, setting an exception if there isn't one.
839 // This doesn't need to aquire the GIL because it should only be called from
840 // an %exception before the lock is released.
842 bool wxPyCheckForApp() {
843 if (wxTheApp
!= NULL
)
846 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
851 //---------------------------------------------------------------------------
854 void wxPyClientData_dtor(wxPyClientData
* self
) {
855 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
856 // may have already garbage collected the object...
857 bool blocked
= wxPyBeginBlockThreads();
858 Py_DECREF(self
->m_obj
);
860 wxPyEndBlockThreads(blocked
);
864 void wxPyUserData_dtor(wxPyUserData
* self
) {
865 if (! wxPyDoingCleanup
) {
866 bool blocked
= wxPyBeginBlockThreads();
867 Py_DECREF(self
->m_obj
);
869 wxPyEndBlockThreads(blocked
);
874 // This is called when an OOR controled object is being destroyed. Although
875 // the C++ object is going away there is no way to force the Python object
876 // (and all references to it) to die too. This causes problems (crashes) in
877 // wxPython when a python shadow object attempts to call a C++ method using
878 // the now bogus pointer... So to try and prevent this we'll do a little black
879 // magic and change the class of the python instance to a class that will
880 // raise an exception for any attempt to call methods with it. See
881 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
882 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
884 static PyObject
* deadObjectClass
= NULL
;
886 bool blocked
= wxPyBeginBlockThreads();
887 if (deadObjectClass
== NULL
) {
888 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
889 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
890 // will lead to a deadlock when it tries to aquire the GIL again.
891 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
892 Py_INCREF(deadObjectClass
);
896 // Only if there is more than one reference to the object
897 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
898 // bool isInstance = wxPyInstance_Check(self->m_obj);
900 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
902 // Call __del__, if there is one.
903 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
905 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
909 if (PyErr_Occurred())
910 PyErr_Clear(); // just ignore it for now
913 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
915 // Clear the instance's dictionary
918 // put the name of the old class into the instance, and then reset the
919 // class to be the dead class.
920 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
921 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
922 PyDict_SetItemString(dict
, "_name", name
);
923 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
924 //Py_INCREF(deadObjectClass);
930 // m_obj is DECREF'd in the base class dtor...
931 wxPyEndBlockThreads(blocked
);
935 //---------------------------------------------------------------------------
936 // Stuff used by OOR to find the right wxPython class type to return and to
940 // The pointer type map is used when the "pointer" type name generated by SWIG
941 // is not the same as the shadow class name, for example wxPyTreeCtrl
942 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
943 // so we'll just make it a Python dictionary in the wx module's namespace.
944 // (See __wxSetDictionary)
945 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
946 if (! wxPyPtrTypeMap
)
947 wxPyPtrTypeMap
= PyDict_New();
948 PyDict_SetItemString(wxPyPtrTypeMap
,
950 PyString_FromString((char*)ptrName
));
956 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
957 PyObject
* target
= NULL
;
958 bool isEvtHandler
= False
;
961 // If it's derived from wxEvtHandler then there may
962 // already be a pointer to a Python object that we can use
964 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
966 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
967 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
969 target
= data
->m_obj
;
976 // Otherwise make it the old fashioned way by making a new shadow
977 // object and putting this pointer in it. Look up the class
978 // heirarchy until we find a class name that is located in the
980 const wxClassInfo
* info
= source
->GetClassInfo();
981 wxString name
= info
->GetClassName();
982 bool exists
= wxPyCheckSwigType(name
);
983 while (info
&& !exists
) {
984 info
= info
->GetBaseClass1();
985 name
= info
->GetClassName();
986 exists
= wxPyCheckSwigType(name
);
989 target
= wxPyConstructObject((void*)source
, name
, False
);
990 if (target
&& isEvtHandler
)
991 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
993 wxString
msg(wxT("wxPython class not found for "));
994 msg
+= source
->GetClassInfo()->GetClassName();
995 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
999 } else { // source was NULL so return None.
1000 Py_INCREF(Py_None
); target
= Py_None
;
1006 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
1007 PyObject
* target
= NULL
;
1009 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1010 // If it's derived from wxSizer then there may already be a pointer to
1011 // a Python object that we can use in the OOR data.
1012 wxSizer
* sz
= (wxSizer
*)source
;
1013 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1015 target
= data
->m_obj
;
1021 target
= wxPyMake_wxObject(source
, False
);
1022 if (target
!= Py_None
)
1023 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1029 //---------------------------------------------------------------------------
1032 #ifdef WXP_WITH_THREAD
1034 unsigned long wxPyGetCurrentThreadId() {
1035 return wxThread::GetCurrentId();
1038 static wxPyThreadState gs_shutdownTState
;
1041 wxPyThreadState
* wxPyGetThreadState() {
1042 if (wxPyTMutex
== NULL
) // Python is shutting down...
1043 return &gs_shutdownTState
;
1045 unsigned long ctid
= wxPyGetCurrentThreadId();
1046 wxPyThreadState
* tstate
= NULL
;
1049 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1050 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1051 if (info
.tid
== ctid
) {
1056 wxPyTMutex
->Unlock();
1057 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1063 void wxPySaveThreadState(PyThreadState
* tstate
) {
1064 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1065 gs_shutdownTState
.tstate
= tstate
;
1068 unsigned long ctid
= wxPyGetCurrentThreadId();
1070 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1071 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1072 if (info
.tid
== ctid
) {
1074 if (info
.tstate
!= tstate
)
1075 wxLogMessage("*** tstate mismatch!???");
1077 // info.tstate = tstate; *** DO NOT update existing ones???
1078 // Normally it will never change, but apparently COM callbacks
1079 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1080 // tstate which will then be garbage the next time we try to use
1082 wxPyTMutex
->Unlock();
1086 // not found, so add it...
1087 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1088 wxPyTMutex
->Unlock();
1095 // Calls from Python to wxWindows code are wrapped in calls to these
1098 PyThreadState
* wxPyBeginAllowThreads() {
1099 #ifdef WXP_WITH_THREAD
1100 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1101 wxPySaveThreadState(saved
);
1108 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1109 #ifdef WXP_WITH_THREAD
1110 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1116 // Calls from wxWindows back to Python code, or even any PyObject
1117 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1119 bool wxPyBeginBlockThreads() {
1120 #ifdef WXP_WITH_THREAD
1121 // This works in for 2.3, maybe a good alternative to find the needed tstate?
1122 // PyThreadState *check = PyGILState_GetThisThreadState();
1124 PyThreadState
*current
= _PyThreadState_Current
;
1126 // Only block if there wasn't already a tstate, or if the current one is
1127 // not the one we are wanting to change to. This should prevent deadlock
1128 // if there are nested calls to wxPyBeginBlockThreads
1129 bool blocked
= false;
1130 wxPyThreadState
* tstate
= wxPyGetThreadState();
1131 if (current
!= tstate
->tstate
) {
1132 PyEval_RestoreThread(tstate
->tstate
);
1140 void wxPyEndBlockThreads(bool blocked
) {
1141 #ifdef WXP_WITH_THREAD
1142 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1143 // The value of blocked passed in needs to be the same as that returned
1144 // from wxPyBeginBlockThreads at the same nesting level.
1146 PyEval_SaveThread();
1152 //---------------------------------------------------------------------------
1153 // wxPyInputStream and wxPyCBInputStream methods
1156 void wxPyInputStream::close() {
1157 /* do nothing for now */
1160 void wxPyInputStream::flush() {
1161 /* do nothing for now */
1164 bool wxPyInputStream::eof() {
1166 return m_wxis
->Eof();
1171 wxPyInputStream::~wxPyInputStream() {
1178 PyObject
* wxPyInputStream::read(int size
) {
1179 PyObject
* obj
= NULL
;
1181 const int BUFSIZE
= 1024;
1183 // check if we have a real wxInputStream to work with
1185 bool blocked
= wxPyBeginBlockThreads();
1186 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1187 wxPyEndBlockThreads(blocked
);
1192 // read while bytes are available on the stream
1193 while ( m_wxis
->CanRead() ) {
1194 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1195 buf
.UngetAppendBuf(m_wxis
->LastRead());
1198 } else { // Read only size number of characters
1199 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1200 buf
.UngetWriteBuf(m_wxis
->LastRead());
1204 bool blocked
= wxPyBeginBlockThreads();
1205 wxStreamError err
= m_wxis
->GetLastError();
1206 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1207 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1210 // We use only strings for the streams, not unicode
1211 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1213 wxPyEndBlockThreads(blocked
);
1218 PyObject
* wxPyInputStream::readline(int size
) {
1219 PyObject
* obj
= NULL
;
1224 // check if we have a real wxInputStream to work with
1226 bool blocked
= wxPyBeginBlockThreads();
1227 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1228 wxPyEndBlockThreads(blocked
);
1232 // read until \n or byte limit reached
1233 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1234 ch
= m_wxis
->GetC();
1239 bool blocked
= wxPyBeginBlockThreads();
1240 wxStreamError err
= m_wxis
->GetLastError();
1241 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1242 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1245 // We use only strings for the streams, not unicode
1246 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1248 wxPyEndBlockThreads(blocked
);
1253 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1256 // check if we have a real wxInputStream to work with
1258 bool blocked
= wxPyBeginBlockThreads();
1259 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1260 wxPyEndBlockThreads(blocked
);
1265 bool blocked
= wxPyBeginBlockThreads();
1266 pylist
= PyList_New(0);
1267 wxPyEndBlockThreads(blocked
);
1270 bool blocked
= wxPyBeginBlockThreads();
1272 wxPyEndBlockThreads(blocked
);
1276 // read sizehint bytes or until EOF
1278 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1279 PyObject
* s
= this->readline();
1281 bool blocked
= wxPyBeginBlockThreads();
1283 wxPyEndBlockThreads(blocked
);
1286 bool blocked
= wxPyBeginBlockThreads();
1287 PyList_Append(pylist
, s
);
1288 i
+= PyString_Size(s
);
1289 wxPyEndBlockThreads(blocked
);
1293 wxStreamError err
= m_wxis
->GetLastError();
1294 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1295 bool blocked
= wxPyBeginBlockThreads();
1297 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1298 wxPyEndBlockThreads(blocked
);
1306 void wxPyInputStream::seek(int offset
, int whence
) {
1308 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1311 int wxPyInputStream::tell(){
1313 return m_wxis
->TellI();
1320 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1321 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1325 wxPyCBInputStream::~wxPyCBInputStream() {
1327 if (m_block
) blocked
= wxPyBeginBlockThreads();
1331 if (m_block
) wxPyEndBlockThreads(blocked
);
1335 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1337 if (block
) blocked
= wxPyBeginBlockThreads();
1339 PyObject
* read
= getMethod(py
, "read");
1340 PyObject
* seek
= getMethod(py
, "seek");
1341 PyObject
* tell
= getMethod(py
, "tell");
1344 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1348 if (block
) wxPyEndBlockThreads(blocked
);
1352 if (block
) wxPyEndBlockThreads(blocked
);
1353 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1357 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1358 return wxPyCBInputStream::create(py
, block
);
1361 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1362 if (!PyObject_HasAttrString(py
, name
))
1364 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1365 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1373 size_t wxPyCBInputStream::GetSize() const {
1374 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1375 if (m_seek
&& m_tell
) {
1376 off_t temp
= self
->OnSysTell();
1377 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1378 self
->OnSysSeek(temp
, wxFromStart
);
1386 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1390 bool blocked
= wxPyBeginBlockThreads();
1391 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1392 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1396 if ((result
!= NULL
) && PyString_Check(result
)) {
1397 o
= PyString_Size(result
);
1399 m_lasterror
= wxSTREAM_EOF
;
1402 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1407 m_lasterror
= wxSTREAM_READ_ERROR
;
1408 wxPyEndBlockThreads(blocked
);
1412 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1413 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1417 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1418 bool blocked
= wxPyBeginBlockThreads();
1420 // off_t is a 64-bit value...
1421 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1423 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1425 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1428 wxPyEndBlockThreads(blocked
);
1433 off_t
wxPyCBInputStream::OnSysTell() const {
1434 bool blocked
= wxPyBeginBlockThreads();
1435 PyObject
* arglist
= Py_BuildValue("()");
1436 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1439 if (result
!= NULL
) {
1441 if (PyLong_Check(result
))
1442 o
= PyLong_AsLongLong(result
);
1445 o
= PyInt_AsLong(result
);
1448 wxPyEndBlockThreads(blocked
);
1452 //----------------------------------------------------------------------
1454 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1456 wxPyCallback::wxPyCallback(PyObject
* func
) {
1461 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1462 m_func
= other
.m_func
;
1466 wxPyCallback::~wxPyCallback() {
1467 bool blocked
= wxPyBeginBlockThreads();
1469 wxPyEndBlockThreads(blocked
);
1473 #define wxPy_PRECALLINIT "_preCallInit"
1474 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1476 // This function is used for all events destined for Python event handlers.
1477 void wxPyCallback::EventThunker(wxEvent
& event
) {
1478 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1479 PyObject
* func
= cb
->m_func
;
1483 bool checkSkip
= False
;
1485 bool blocked
= wxPyBeginBlockThreads();
1486 wxString className
= event
.GetClassInfo()->GetClassName();
1488 // If the event is one of these types then pass the original
1489 // event object instead of the one passed to us.
1490 if ( className
== wxT("wxPyEvent") ) {
1491 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1492 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1494 else if ( className
== wxT("wxPyCommandEvent") ) {
1495 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1496 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1499 arg
= wxPyConstructObject((void*)&event
, className
);
1505 // "intern" the pre/post method names to speed up the HasAttr
1506 static PyObject
* s_preName
= NULL
;
1507 static PyObject
* s_postName
= NULL
;
1508 if (s_preName
== NULL
) {
1509 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1510 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1513 // Check if the event object needs some preinitialization
1514 if (PyObject_HasAttr(arg
, s_preName
)) {
1515 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1517 Py_DECREF(result
); // result is ignored, but we still need to decref it
1518 PyErr_Clear(); // Just in case...
1524 // Call the event handler, passing the event object
1525 tuple
= PyTuple_New(1);
1526 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1527 result
= PyEval_CallObject(func
, tuple
);
1529 Py_DECREF(result
); // result is ignored, but we still need to decref it
1530 PyErr_Clear(); // Just in case...
1535 // Check if the event object needs some post cleanup
1536 if (PyObject_HasAttr(arg
, s_postName
)) {
1537 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1539 Py_DECREF(result
); // result is ignored, but we still need to decref it
1540 PyErr_Clear(); // Just in case...
1547 // if the event object was one of our special types and
1548 // it had been cloned, then we need to extract the Skipped
1549 // value from the original and set it in the clone.
1550 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1552 event
.Skip(PyInt_AsLong(result
));
1560 wxPyEndBlockThreads(blocked
);
1564 //----------------------------------------------------------------------
1566 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1568 m_self
= other
.m_self
;
1569 m_class
= other
.m_class
;
1577 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1588 #if PYTHON_API_VERSION >= 1011
1590 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1591 // in which the method was defined. Starting with 2.2 it returns
1592 // "class that asked for the method" which seems totally bogus to me
1593 // but apprently it fixes some obscure problem waiting to happen in
1594 // Python. Since the API was not documented Guido and the gang felt
1595 // safe in changing it. Needless to say that totally screwed up the
1596 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1597 // code to find the class where the method is actually defined...
1600 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1604 if (PyType_Check(klass
)) { // new style classes
1605 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1606 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1607 PyObject
*mro
, *res
, *base
, *dict
;
1608 /* Look in tp_dict of types in MRO */
1610 assert(PyTuple_Check(mro
));
1611 n
= PyTuple_GET_SIZE(mro
);
1612 for (i
= 0; i
< n
; i
++) {
1613 base
= PyTuple_GET_ITEM(mro
, i
);
1614 if (PyClass_Check(base
))
1615 dict
= ((PyClassObject
*)base
)->cl_dict
;
1617 assert(PyType_Check(base
));
1618 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1620 assert(dict
&& PyDict_Check(dict
));
1621 res
= PyDict_GetItem(dict
, name
);
1628 else if (PyClass_Check(klass
)) { // old style classes
1629 // This code is borrowed/adapted from class_lookup in classobject.c
1630 PyClassObject
* cp
= (PyClassObject
*)klass
;
1631 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1632 if (value
!= NULL
) {
1633 return (PyObject
*)cp
;
1635 n
= PyTuple_Size(cp
->cl_bases
);
1636 for (i
= 0; i
< n
; i
++) {
1637 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1638 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1650 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1652 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1654 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1656 #else // 2.2 and after, the hard way...
1658 PyObject
* nameo
= PyString_FromString(name
);
1659 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1667 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1668 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1669 self
->m_lastFound
= NULL
;
1671 // If the object (m_self) has an attibute of the given name...
1672 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1673 PyObject
*method
, *klass
;
1674 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1676 // ...and if that attribute is a method, and if that method's class is
1677 // not from a base class...
1678 if (PyMethod_Check(method
) &&
1679 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1680 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1682 // ...then we'll save a pointer to the method so callCallback can call it.
1683 self
->m_lastFound
= method
;
1689 return m_lastFound
!= NULL
;
1693 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1697 result
= callCallbackObj(argTuple
);
1698 if (result
) { // Assumes an integer return type...
1699 retval
= PyInt_AsLong(result
);
1701 PyErr_Clear(); // forget about it if it's not...
1706 // Invoke the Python callable object, returning the raw PyObject return
1707 // value. Caller should DECREF the return value and also manage the GIL.
1708 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1711 // Save a copy of the pointer in case the callback generates another
1712 // callback. In that case m_lastFound will have a different value when
1713 // it gets back here...
1714 PyObject
* method
= m_lastFound
;
1716 result
= PyEval_CallObject(method
, argTuple
);
1717 Py_DECREF(argTuple
);
1726 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1727 cbh
.setSelf(self
, klass
, incref
);
1730 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1731 return cbh
.findCallback(name
);
1734 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1735 return cbh
.callCallback(argTuple
);
1738 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1739 return cbh
.callCallbackObj(argTuple
);
1743 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1744 if (cbh
->m_incRef
) {
1745 bool blocked
= wxPyBeginBlockThreads();
1746 Py_XDECREF(cbh
->m_self
);
1747 Py_XDECREF(cbh
->m_class
);
1748 wxPyEndBlockThreads(blocked
);
1752 //---------------------------------------------------------------------------
1753 //---------------------------------------------------------------------------
1754 // These event classes can be derived from in Python and passed through the event
1755 // system without losing anything. They do this by keeping a reference to
1756 // themselves and some special case handling in wxPyCallback::EventThunker.
1759 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1760 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1761 //Py_INCREF(m_self); // circular loops...
1765 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1766 bool blocked
= wxPyBeginBlockThreads();
1769 wxPyEndBlockThreads(blocked
);
1772 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1773 bool blocked
= wxPyBeginBlockThreads();
1781 wxPyEndBlockThreads(blocked
);
1784 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1790 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1791 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1794 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1795 : wxEvent(winid
, commandType
) {
1799 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1802 SetSelf(evt
.m_self
, True
);
1806 wxPyEvent::~wxPyEvent() {
1810 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1811 : wxCommandEvent(commandType
, id
) {
1815 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1816 : wxCommandEvent(evt
)
1818 SetSelf(evt
.m_self
, True
);
1822 wxPyCommandEvent::~wxPyCommandEvent() {
1829 //---------------------------------------------------------------------------
1830 //---------------------------------------------------------------------------
1831 // Convert a wxList to a Python List, only works for lists of wxObjects
1833 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1834 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1838 wxNode
* node
= list
->GetFirst();
1840 bool blocked
= wxPyBeginBlockThreads();
1841 pyList
= PyList_New(0);
1843 wxObj
= node
->GetData();
1844 pyObj
= wxPyMake_wxObject(wxObj
);
1845 PyList_Append(pyList
, pyObj
);
1846 node
= node
->GetNext();
1848 wxPyEndBlockThreads(blocked
);
1852 //----------------------------------------------------------------------
1854 long wxPyGetWinHandle(wxWindow
* win
) {
1857 return (long)win
->GetHandle();
1860 #if defined(__WXGTK__) || defined(__WXX11)
1861 return (long)GetXWindow(win
);
1865 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1866 return (long)win
->GetHandle();
1872 //----------------------------------------------------------------------
1873 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1874 // included in every file over and over again...
1876 wxString
* wxString_in_helper(PyObject
* source
) {
1877 wxString
* target
= NULL
;
1879 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1880 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1884 PyObject
* uni
= source
;
1885 if (PyString_Check(source
)) {
1886 uni
= PyUnicode_FromObject(source
);
1887 if (PyErr_Occurred()) return NULL
;
1889 target
= new wxString();
1890 size_t len
= PyUnicode_GET_SIZE(uni
);
1892 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1893 target
->UngetWriteBuf();
1896 if (PyString_Check(source
))
1899 char* tmpPtr
; int tmpSize
;
1900 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1901 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1904 target
= new wxString(tmpPtr
, tmpSize
);
1905 #endif // wxUSE_UNICODE
1911 // Similar to above except doesn't use "new" and doesn't set an exception
1912 wxString
Py2wxString(PyObject
* source
)
1917 // Convert to a unicode object, if not already, then to a wxString
1918 PyObject
* uni
= source
;
1919 if (!PyUnicode_Check(source
)) {
1920 uni
= PyUnicode_FromObject(source
);
1921 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1923 size_t len
= PyUnicode_GET_SIZE(uni
);
1925 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1926 target
.UngetWriteBuf();
1929 if (!PyUnicode_Check(source
))
1932 // Convert to a string object if it isn't already, then to wxString
1933 PyObject
* str
= source
;
1934 if (!PyString_Check(source
)) {
1935 str
= PyObject_Str(source
);
1936 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1938 char* tmpPtr
; int tmpSize
;
1939 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1940 target
= wxString(tmpPtr
, tmpSize
);
1942 if (!PyString_Check(source
))
1944 #endif // wxUSE_UNICODE
1950 // Make either a Python String or Unicode object, depending on build mode
1951 PyObject
* wx2PyString(const wxString
& src
)
1955 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1957 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1963 //----------------------------------------------------------------------
1966 byte
* byte_LIST_helper(PyObject
* source
) {
1967 if (!PyList_Check(source
)) {
1968 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1971 int count
= PyList_Size(source
);
1972 byte
* temp
= new byte
[count
];
1974 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1977 for (int x
=0; x
<count
; x
++) {
1978 PyObject
* o
= PyList_GetItem(source
, x
);
1979 if (! PyInt_Check(o
)) {
1980 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1983 temp
[x
] = (byte
)PyInt_AsLong(o
);
1989 int* int_LIST_helper(PyObject
* source
) {
1990 if (!PyList_Check(source
)) {
1991 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1994 int count
= PyList_Size(source
);
1995 int* temp
= new int[count
];
1997 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2000 for (int x
=0; x
<count
; x
++) {
2001 PyObject
* o
= PyList_GetItem(source
, x
);
2002 if (! PyInt_Check(o
)) {
2003 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2006 temp
[x
] = PyInt_AsLong(o
);
2012 long* long_LIST_helper(PyObject
* source
) {
2013 if (!PyList_Check(source
)) {
2014 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2017 int count
= PyList_Size(source
);
2018 long* temp
= new long[count
];
2020 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2023 for (int x
=0; x
<count
; x
++) {
2024 PyObject
* o
= PyList_GetItem(source
, x
);
2025 if (! PyInt_Check(o
)) {
2026 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2029 temp
[x
] = PyInt_AsLong(o
);
2035 char** string_LIST_helper(PyObject
* source
) {
2036 if (!PyList_Check(source
)) {
2037 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2040 int count
= PyList_Size(source
);
2041 char** temp
= new char*[count
];
2043 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2046 for (int x
=0; x
<count
; x
++) {
2047 PyObject
* o
= PyList_GetItem(source
, x
);
2048 if (! PyString_Check(o
)) {
2049 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2052 temp
[x
] = PyString_AsString(o
);
2057 //--------------------------------
2058 // Part of patch from Tim Hochberg
2059 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2060 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2061 point
->x
= PyInt_AS_LONG(o1
);
2062 point
->y
= PyInt_AS_LONG(o2
);
2065 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2066 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2067 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2070 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2071 // Disallow instances because they can cause havok
2074 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2075 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2076 point
->x
= PyInt_AsLong(o1
);
2077 point
->y
= PyInt_AsLong(o2
);
2084 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2085 // Putting all of the declarations here allows
2086 // us to put the error handling all in one place.
2089 PyObject
*o
, *o1
, *o2
;
2090 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2092 if (!PySequence_Check(source
)) {
2096 // The length of the sequence is returned in count.
2097 *count
= PySequence_Length(source
);
2102 temp
= new wxPoint
[*count
];
2104 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2107 for (x
=0; x
<*count
; x
++) {
2108 // Get an item: try fast way first.
2110 o
= PySequence_Fast_GET_ITEM(source
, x
);
2113 o
= PySequence_GetItem(source
, x
);
2119 // Convert o to wxPoint.
2120 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2121 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2122 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2123 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2124 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2128 else if (wxPySwigInstance_Check(o
)) {
2130 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2135 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2136 o1
= PySequence_GetItem(o
, 0);
2137 o2
= PySequence_GetItem(o
, 1);
2138 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2162 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2166 //------------------------------
2169 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2170 if (!PyList_Check(source
)) {
2171 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2174 int count
= PyList_Size(source
);
2175 wxBitmap
** temp
= new wxBitmap
*[count
];
2177 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2180 for (int x
=0; x
<count
; x
++) {
2181 PyObject
* o
= PyList_GetItem(source
, x
);
2182 if (wxPySwigInstance_Check(o
)) {
2184 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2185 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2191 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2200 wxString
* wxString_LIST_helper(PyObject
* source
) {
2201 if (!PyList_Check(source
)) {
2202 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2205 int count
= PyList_Size(source
);
2206 wxString
* temp
= new wxString
[count
];
2208 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2211 for (int x
=0; x
<count
; x
++) {
2212 PyObject
* o
= PyList_GetItem(source
, x
);
2213 #if PYTHON_API_VERSION >= 1009
2214 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2215 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2219 if (! PyString_Check(o
)) {
2220 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2225 wxString
* pStr
= wxString_in_helper(o
);
2233 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2234 if (!PyList_Check(source
)) {
2235 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2238 int count
= PyList_Size(source
);
2239 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2241 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2244 for (int x
=0; x
<count
; x
++) {
2245 PyObject
* o
= PyList_GetItem(source
, x
);
2246 if (wxPySwigInstance_Check(o
)) {
2247 wxAcceleratorEntry
* ae
;
2248 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2249 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2254 else if (PyTuple_Check(o
)) {
2255 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2256 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2257 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2258 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2261 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2269 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2270 if (!PyList_Check(source
)) {
2271 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2274 int count
= PyList_Size(source
);
2275 wxPen
** temp
= new wxPen
*[count
];
2277 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2280 for (int x
=0; x
<count
; x
++) {
2281 PyObject
* o
= PyList_GetItem(source
, x
);
2282 if (wxPySwigInstance_Check(o
)) {
2284 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2286 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2293 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2301 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2302 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2305 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2309 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2310 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2313 o1
= PySequence_GetItem(source
, 0);
2314 o2
= PySequence_GetItem(source
, 1);
2317 *i1
= PyInt_AsLong(o1
);
2318 *i2
= PyInt_AsLong(o2
);
2328 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2329 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2330 PyObject
*o1
, *o2
, *o3
, *o4
;
2332 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2336 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2337 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2338 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2339 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2342 o1
= PySequence_GetItem(source
, 0);
2343 o2
= PySequence_GetItem(source
, 1);
2344 o3
= PySequence_GetItem(source
, 2);
2345 o4
= PySequence_GetItem(source
, 3);
2348 *i1
= PyInt_AsLong(o1
);
2349 *i2
= PyInt_AsLong(o2
);
2350 *i3
= PyInt_AsLong(o3
);
2351 *i4
= PyInt_AsLong(o4
);
2363 //----------------------------------------------------------------------
2365 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2369 if (wxPySwigInstance_Check(source
) &&
2370 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2374 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2380 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2382 if (source
== Py_None
) {
2383 **obj
= wxSize(-1,-1);
2386 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2390 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2392 if (source
== Py_None
) {
2393 **obj
= wxPoint(-1,-1);
2396 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2401 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2403 if (source
== Py_None
) {
2404 **obj
= wxRealPoint(-1,-1);
2408 // If source is an object instance then it may already be the right type
2409 if (wxPySwigInstance_Check(source
)) {
2411 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2416 // otherwise a 2-tuple of floats is expected
2417 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2418 PyObject
* o1
= PySequence_GetItem(source
, 0);
2419 PyObject
* o2
= PySequence_GetItem(source
, 1);
2420 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2425 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2432 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2438 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2440 if (source
== Py_None
) {
2441 **obj
= wxRect(-1,-1,-1,-1);
2445 // If source is an object instance then it may already be the right type
2446 if (wxPySwigInstance_Check(source
)) {
2448 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2453 // otherwise a 4-tuple of integers is expected
2454 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2455 PyObject
* o1
= PySequence_GetItem(source
, 0);
2456 PyObject
* o2
= PySequence_GetItem(source
, 1);
2457 PyObject
* o3
= PySequence_GetItem(source
, 2);
2458 PyObject
* o4
= PySequence_GetItem(source
, 3);
2459 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2460 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2467 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2468 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2477 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2483 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2485 if (source
== Py_None
) {
2486 **obj
= wxNullColour
;
2490 // If source is an object instance then it may already be the right type
2491 if (wxPySwigInstance_Check(source
)) {
2493 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2498 // otherwise check for a string
2499 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2500 wxString spec
= Py2wxString(source
);
2501 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2502 long red
, green
, blue
;
2503 red
= green
= blue
= 0;
2504 spec
.Mid(1,2).ToLong(&red
, 16);
2505 spec
.Mid(3,2).ToLong(&green
, 16);
2506 spec
.Mid(5,2).ToLong(&blue
, 16);
2508 **obj
= wxColour(red
, green
, blue
);
2511 else { // it's a colour name
2512 **obj
= wxColour(spec
);
2516 // last chance: 3-tuple of integers is expected
2517 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2518 PyObject
* o1
= PySequence_GetItem(source
, 0);
2519 PyObject
* o2
= PySequence_GetItem(source
, 1);
2520 PyObject
* o3
= PySequence_GetItem(source
, 2);
2521 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2527 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2535 PyErr_SetString(PyExc_TypeError
,
2536 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2541 bool wxColour_typecheck(PyObject
* source
) {
2543 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2546 if (PyString_Check(source
) || PyUnicode_Check(source
))
2554 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2556 if (source
== Py_None
) {
2557 **obj
= wxPoint2D(-1,-1);
2561 // If source is an object instance then it may already be the right type
2562 if (wxPySwigInstance_Check(source
)) {
2564 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2569 // otherwise a length-2 sequence of floats is expected
2570 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2571 PyObject
* o1
= PySequence_GetItem(source
, 0);
2572 PyObject
* o2
= PySequence_GetItem(source
, 1);
2573 // This should really check for floats, not numbers -- but that would break code.
2574 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2579 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2585 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2590 //----------------------------------------------------------------------
2592 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2594 PyObject
* list
= PyList_New(0);
2595 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2597 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2599 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2601 PyList_Append(list
, str
);
2608 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2610 PyObject
* list
= PyList_New(0);
2611 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2612 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2613 PyList_Append(list
, number
);
2620 //----------------------------------------------------------------------
2621 //----------------------------------------------------------------------