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
523 // | _CRTDBG_CHECK_ALWAYS_DF
524 // | _CRTDBG_DELAY_FREE_MEM_DF
528 #ifdef WXP_WITH_THREAD
529 PyEval_InitThreads();
530 wxPyTStates
= new wxPyThreadStateArray
;
531 wxPyTMutex
= new wxMutex
;
533 // Save the current (main) thread state in our array
534 PyThreadState
* tstate
= wxPyBeginAllowThreads();
535 wxPyEndAllowThreads(tstate
);
538 // Ensure that the build options in the DLL (or whatever) match this build
539 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
541 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
542 wxPy_ReinitStockObjects(1);
544 wxInitAllImageHandlers();
549 void __wxPyCleanup() {
550 wxPyDoingCleanup
= True
;
552 wxPyDoCleanup
= False
;
555 #ifdef WXP_WITH_THREAD
558 wxPyTStates
->Empty();
565 // Save a reference to the dictionary of the wx._core module, and inject
566 // a few more things into it.
567 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
570 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
573 if (!PyDict_Check(wxPython_dict
)) {
574 PyErr_SetString(PyExc_TypeError
,
575 "_wxPySetDictionary must have dictionary object!");
579 if (! wxPyPtrTypeMap
)
580 wxPyPtrTypeMap
= PyDict_New();
581 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
583 // Create an exception object to use for wxASSERTions
584 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
585 PyExc_AssertionError
, NULL
);
586 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
588 // Create an exception object to use when the app object hasn't been created yet
589 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
590 PyExc_RuntimeError
, NULL
);
591 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
596 #define wxPlatform "__WXMOTIF__"
597 #define wxPlatName "wxMotif"
600 #define wxPlatform "__WXX11__"
601 #define wxPlatName "wxX11"
604 #define wxPlatform "__WXGTK__"
605 #define wxPlatName "wxGTK"
608 #define wxPlatform "__WXMSW__"
609 #define wxPlatName "wxMSW"
612 #define wxPlatform "__WXMAC__"
613 #define wxPlatName "wxMac"
622 // These should be deprecated in favor of the PlatformInfo tuple built below...
623 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
624 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
625 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
628 PyObject
* PlatInfo
= PyList_New(0);
631 #define _AddInfoString(st) \
632 obj = PyString_FromString(st); \
633 PyList_Append(PlatInfo, obj); \
636 _AddInfoString(wxPlatform
);
637 _AddInfoString(wxPlatName
);
639 _AddInfoString("unicode");
641 _AddInfoString("ascii");
645 _AddInfoString("gtk2");
647 _AddInfoString("gtk1");
651 _AddInfoString("wx-assertions-on");
653 _AddInfoString("wx-assertions-off");
656 #undef _AddInfoString
658 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
660 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
666 //---------------------------------------------------------------------------
668 // Python's PyInstance_Check does not return True for instances of new-style
669 // classes. This should get close enough for both new and old classes but I
670 // should re-evaluate the need for doing instance checks...
671 bool wxPyInstance_Check(PyObject
* obj
) {
672 return PyObject_HasAttrString(obj
, "__class__") != 0;
676 // This one checks if the object is an instance of a SWIG proxy class (it has
677 // a .this attribute)
678 bool wxPySwigInstance_Check(PyObject
* obj
) {
679 return PyObject_HasAttrString(obj
, "this") != 0;
682 //---------------------------------------------------------------------------
684 // The stock objects are no longer created when the wx._core_ module is
685 // imported, but only after the app object has been created. The
686 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
687 // objects though various stages of evolution:
689 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
690 // object will be created (otherwise SWIG will just use None.)
692 // pass 2: After the module has been imported and the python proxys have
693 // been created, then set the __class__ to be _wxPyUnbornObject so
694 // it will catch any access to the object and will raise an exception.
696 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
700 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
702 wxPy_ReinitStockObjects(2);
707 static void rsoPass2(const char* name
)
709 static PyObject
* unbornObjectClass
= NULL
;
712 if (unbornObjectClass
== NULL
) {
713 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
714 Py_INCREF(unbornObjectClass
);
717 // Find the object instance
718 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
719 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
720 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
723 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
727 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
733 // Find the object instance
734 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
735 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
736 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
738 // Find the class object and put it back in the instance
739 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
740 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
741 PyObject_SetAttrString(obj
, "__class__", classobj
);
743 // Rebuild the .this swigified pointer with the new value of the C++ pointer
744 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
745 PyObject_SetAttrString(obj
, "this", ptrobj
);
751 void wxPy_ReinitStockObjects(int pass
)
754 // If there is already an App object then wxPython is probably embedded in
755 // a wx C++ application, so there is no need to do all this.
756 static bool embedded
= false;
757 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
761 if (pass
== 3 && embedded
)
765 #define REINITOBJ(name, classname) \
766 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
767 else if (pass == 2) { rsoPass2(#name); } \
768 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
771 #define REINITOBJ2(name, classname) \
773 else if (pass == 2) { rsoPass2(#name); } \
774 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
777 REINITOBJ(wxNORMAL_FONT
, wxFont
);
778 REINITOBJ(wxSMALL_FONT
, wxFont
);
779 REINITOBJ(wxITALIC_FONT
, wxFont
);
780 REINITOBJ(wxSWISS_FONT
, wxFont
);
782 REINITOBJ(wxRED_PEN
, wxPen
);
783 REINITOBJ(wxCYAN_PEN
, wxPen
);
784 REINITOBJ(wxGREEN_PEN
, wxPen
);
785 REINITOBJ(wxBLACK_PEN
, wxPen
);
786 REINITOBJ(wxWHITE_PEN
, wxPen
);
787 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
788 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
789 REINITOBJ(wxGREY_PEN
, wxPen
);
790 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
791 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
793 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
794 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
795 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
796 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
797 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
798 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
799 REINITOBJ(wxRED_BRUSH
, wxBrush
);
800 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
801 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
802 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
804 REINITOBJ(wxBLACK
, wxColour
);
805 REINITOBJ(wxWHITE
, wxColour
);
806 REINITOBJ(wxRED
, wxColour
);
807 REINITOBJ(wxBLUE
, wxColour
);
808 REINITOBJ(wxGREEN
, wxColour
);
809 REINITOBJ(wxCYAN
, wxColour
);
810 REINITOBJ(wxLIGHT_GREY
, wxColour
);
812 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
813 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
814 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
816 REINITOBJ2(wxNullBitmap
, wxBitmap
);
817 REINITOBJ2(wxNullIcon
, wxIcon
);
818 REINITOBJ2(wxNullCursor
, wxCursor
);
819 REINITOBJ2(wxNullPen
, wxPen
);
820 REINITOBJ2(wxNullBrush
, wxBrush
);
821 REINITOBJ2(wxNullPalette
, wxPalette
);
822 REINITOBJ2(wxNullFont
, wxFont
);
823 REINITOBJ2(wxNullColour
, wxColour
);
825 REINITOBJ(wxTheFontList
, wxFontList
);
826 REINITOBJ(wxThePenList
, wxPenList
);
827 REINITOBJ(wxTheBrushList
, wxBrushList
);
828 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
831 REINITOBJ2(wxDefaultValidator
, wxValidator
);
832 REINITOBJ2(wxNullImage
, wxImage
);
833 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
839 //---------------------------------------------------------------------------
841 // Check for existence of a wxApp, setting an exception if there isn't one.
842 // This doesn't need to aquire the GIL because it should only be called from
843 // an %exception before the lock is released.
845 bool wxPyCheckForApp() {
846 if (wxTheApp
!= NULL
)
849 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
854 //---------------------------------------------------------------------------
857 void wxPyClientData_dtor(wxPyClientData
* self
) {
858 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
859 // may have already garbage collected the object...
860 bool blocked
= wxPyBeginBlockThreads();
861 Py_DECREF(self
->m_obj
);
863 wxPyEndBlockThreads(blocked
);
867 void wxPyUserData_dtor(wxPyUserData
* self
) {
868 if (! wxPyDoingCleanup
) {
869 bool blocked
= wxPyBeginBlockThreads();
870 Py_DECREF(self
->m_obj
);
872 wxPyEndBlockThreads(blocked
);
877 // This is called when an OOR controled object is being destroyed. Although
878 // the C++ object is going away there is no way to force the Python object
879 // (and all references to it) to die too. This causes problems (crashes) in
880 // wxPython when a python shadow object attempts to call a C++ method using
881 // the now bogus pointer... So to try and prevent this we'll do a little black
882 // magic and change the class of the python instance to a class that will
883 // raise an exception for any attempt to call methods with it. See
884 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
885 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
887 static PyObject
* deadObjectClass
= NULL
;
889 bool blocked
= wxPyBeginBlockThreads();
890 if (deadObjectClass
== NULL
) {
891 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
892 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
893 // will lead to a deadlock when it tries to aquire the GIL again.
894 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
895 Py_INCREF(deadObjectClass
);
899 // Only if there is more than one reference to the object
900 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
901 // bool isInstance = wxPyInstance_Check(self->m_obj);
903 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
905 // Call __del__, if there is one.
906 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
908 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
912 if (PyErr_Occurred())
913 PyErr_Clear(); // just ignore it for now
916 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
918 // Clear the instance's dictionary
921 // put the name of the old class into the instance, and then reset the
922 // class to be the dead class.
923 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
924 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
925 PyDict_SetItemString(dict
, "_name", name
);
926 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
927 //Py_INCREF(deadObjectClass);
933 // m_obj is DECREF'd in the base class dtor...
934 wxPyEndBlockThreads(blocked
);
938 //---------------------------------------------------------------------------
939 // Stuff used by OOR to find the right wxPython class type to return and to
943 // The pointer type map is used when the "pointer" type name generated by SWIG
944 // is not the same as the shadow class name, for example wxPyTreeCtrl
945 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
946 // so we'll just make it a Python dictionary in the wx module's namespace.
947 // (See __wxSetDictionary)
948 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
949 if (! wxPyPtrTypeMap
)
950 wxPyPtrTypeMap
= PyDict_New();
951 PyDict_SetItemString(wxPyPtrTypeMap
,
953 PyString_FromString((char*)ptrName
));
959 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
960 PyObject
* target
= NULL
;
961 bool isEvtHandler
= False
;
964 // If it's derived from wxEvtHandler then there may
965 // already be a pointer to a Python object that we can use
967 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
969 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
970 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
972 target
= data
->m_obj
;
979 // Otherwise make it the old fashioned way by making a new shadow
980 // object and putting this pointer in it. Look up the class
981 // heirarchy until we find a class name that is located in the
983 const wxClassInfo
* info
= source
->GetClassInfo();
984 wxString name
= info
->GetClassName();
985 bool exists
= wxPyCheckSwigType(name
);
986 while (info
&& !exists
) {
987 info
= info
->GetBaseClass1();
988 name
= info
->GetClassName();
989 exists
= wxPyCheckSwigType(name
);
992 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
993 if (target
&& isEvtHandler
)
994 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
996 wxString
msg(wxT("wxPython class not found for "));
997 msg
+= source
->GetClassInfo()->GetClassName();
998 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1002 } else { // source was NULL so return None.
1003 Py_INCREF(Py_None
); target
= Py_None
;
1009 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1010 PyObject
* target
= NULL
;
1012 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1013 // If it's derived from wxSizer then there may already be a pointer to
1014 // a Python object that we can use in the OOR data.
1015 wxSizer
* sz
= (wxSizer
*)source
;
1016 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1018 target
= data
->m_obj
;
1024 target
= wxPyMake_wxObject(source
, setThisOwn
, False
);
1025 if (target
!= Py_None
)
1026 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1032 //---------------------------------------------------------------------------
1035 #ifdef WXP_WITH_THREAD
1037 unsigned long wxPyGetCurrentThreadId() {
1038 return wxThread::GetCurrentId();
1041 static wxPyThreadState gs_shutdownTState
;
1044 wxPyThreadState
* wxPyGetThreadState() {
1045 if (wxPyTMutex
== NULL
) // Python is shutting down...
1046 return &gs_shutdownTState
;
1048 unsigned long ctid
= wxPyGetCurrentThreadId();
1049 wxPyThreadState
* tstate
= NULL
;
1052 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1053 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1054 if (info
.tid
== ctid
) {
1059 wxPyTMutex
->Unlock();
1060 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1066 void wxPySaveThreadState(PyThreadState
* tstate
) {
1067 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1068 gs_shutdownTState
.tstate
= tstate
;
1071 unsigned long ctid
= wxPyGetCurrentThreadId();
1073 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1074 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1075 if (info
.tid
== ctid
) {
1077 if (info
.tstate
!= tstate
)
1078 wxLogMessage("*** tstate mismatch!???");
1080 // info.tstate = tstate; *** DO NOT update existing ones???
1081 // Normally it will never change, but apparently COM callbacks
1082 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1083 // tstate which will then be garbage the next time we try to use
1085 wxPyTMutex
->Unlock();
1089 // not found, so add it...
1090 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1091 wxPyTMutex
->Unlock();
1098 // Calls from Python to wxWindows code are wrapped in calls to these
1101 PyThreadState
* wxPyBeginAllowThreads() {
1102 #ifdef WXP_WITH_THREAD
1103 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1104 wxPySaveThreadState(saved
);
1111 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1112 #ifdef WXP_WITH_THREAD
1113 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1119 // Calls from wxWindows back to Python code, or even any PyObject
1120 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1122 bool wxPyBeginBlockThreads() {
1123 #ifdef WXP_WITH_THREAD
1124 // This works in for 2.3, maybe a good alternative to find the needed tstate?
1125 // PyThreadState *check = PyGILState_GetThisThreadState();
1127 PyThreadState
*current
= _PyThreadState_Current
;
1129 // Only block if there wasn't already a tstate, or if the current one is
1130 // not the one we are wanting to change to. This should prevent deadlock
1131 // if there are nested calls to wxPyBeginBlockThreads
1132 bool blocked
= false;
1133 wxPyThreadState
* tstate
= wxPyGetThreadState();
1134 if (current
!= tstate
->tstate
) {
1135 PyEval_RestoreThread(tstate
->tstate
);
1143 void wxPyEndBlockThreads(bool blocked
) {
1144 #ifdef WXP_WITH_THREAD
1145 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1146 // The value of blocked passed in needs to be the same as that returned
1147 // from wxPyBeginBlockThreads at the same nesting level.
1149 PyEval_SaveThread();
1155 //---------------------------------------------------------------------------
1156 // wxPyInputStream and wxPyCBInputStream methods
1159 void wxPyInputStream::close() {
1160 /* do nothing for now */
1163 void wxPyInputStream::flush() {
1164 /* do nothing for now */
1167 bool wxPyInputStream::eof() {
1169 return m_wxis
->Eof();
1174 wxPyInputStream::~wxPyInputStream() {
1181 PyObject
* wxPyInputStream::read(int size
) {
1182 PyObject
* obj
= NULL
;
1184 const int BUFSIZE
= 1024;
1186 // check if we have a real wxInputStream to work with
1188 bool blocked
= wxPyBeginBlockThreads();
1189 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1190 wxPyEndBlockThreads(blocked
);
1195 // read while bytes are available on the stream
1196 while ( m_wxis
->CanRead() ) {
1197 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1198 buf
.UngetAppendBuf(m_wxis
->LastRead());
1201 } else { // Read only size number of characters
1202 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1203 buf
.UngetWriteBuf(m_wxis
->LastRead());
1207 bool blocked
= wxPyBeginBlockThreads();
1208 wxStreamError err
= m_wxis
->GetLastError();
1209 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1210 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1213 // We use only strings for the streams, not unicode
1214 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1216 wxPyEndBlockThreads(blocked
);
1221 PyObject
* wxPyInputStream::readline(int size
) {
1222 PyObject
* obj
= NULL
;
1227 // check if we have a real wxInputStream to work with
1229 bool blocked
= wxPyBeginBlockThreads();
1230 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1231 wxPyEndBlockThreads(blocked
);
1235 // read until \n or byte limit reached
1236 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1237 ch
= m_wxis
->GetC();
1242 bool blocked
= wxPyBeginBlockThreads();
1243 wxStreamError err
= m_wxis
->GetLastError();
1244 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1245 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1248 // We use only strings for the streams, not unicode
1249 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1251 wxPyEndBlockThreads(blocked
);
1256 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1259 // check if we have a real wxInputStream to work with
1261 bool blocked
= wxPyBeginBlockThreads();
1262 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1263 wxPyEndBlockThreads(blocked
);
1268 bool blocked
= wxPyBeginBlockThreads();
1269 pylist
= PyList_New(0);
1270 wxPyEndBlockThreads(blocked
);
1273 bool blocked
= wxPyBeginBlockThreads();
1275 wxPyEndBlockThreads(blocked
);
1279 // read sizehint bytes or until EOF
1281 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1282 PyObject
* s
= this->readline();
1284 bool blocked
= wxPyBeginBlockThreads();
1286 wxPyEndBlockThreads(blocked
);
1289 bool blocked
= wxPyBeginBlockThreads();
1290 PyList_Append(pylist
, s
);
1291 i
+= PyString_Size(s
);
1292 wxPyEndBlockThreads(blocked
);
1296 wxStreamError err
= m_wxis
->GetLastError();
1297 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1298 bool blocked
= wxPyBeginBlockThreads();
1300 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1301 wxPyEndBlockThreads(blocked
);
1309 void wxPyInputStream::seek(int offset
, int whence
) {
1311 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1314 int wxPyInputStream::tell(){
1316 return m_wxis
->TellI();
1323 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1324 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1328 wxPyCBInputStream::~wxPyCBInputStream() {
1330 if (m_block
) blocked
= wxPyBeginBlockThreads();
1334 if (m_block
) wxPyEndBlockThreads(blocked
);
1338 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1340 if (block
) blocked
= wxPyBeginBlockThreads();
1342 PyObject
* read
= getMethod(py
, "read");
1343 PyObject
* seek
= getMethod(py
, "seek");
1344 PyObject
* tell
= getMethod(py
, "tell");
1347 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1351 if (block
) wxPyEndBlockThreads(blocked
);
1355 if (block
) wxPyEndBlockThreads(blocked
);
1356 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1360 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1361 return wxPyCBInputStream::create(py
, block
);
1364 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1365 if (!PyObject_HasAttrString(py
, name
))
1367 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1368 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1376 size_t wxPyCBInputStream::GetSize() const {
1377 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1378 if (m_seek
&& m_tell
) {
1379 off_t temp
= self
->OnSysTell();
1380 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1381 self
->OnSysSeek(temp
, wxFromStart
);
1389 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1393 bool blocked
= wxPyBeginBlockThreads();
1394 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1395 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1399 if ((result
!= NULL
) && PyString_Check(result
)) {
1400 o
= PyString_Size(result
);
1402 m_lasterror
= wxSTREAM_EOF
;
1405 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1410 m_lasterror
= wxSTREAM_READ_ERROR
;
1411 wxPyEndBlockThreads(blocked
);
1415 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1416 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1420 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1421 bool blocked
= wxPyBeginBlockThreads();
1423 // off_t is a 64-bit value...
1424 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1426 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1428 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1431 wxPyEndBlockThreads(blocked
);
1436 off_t
wxPyCBInputStream::OnSysTell() const {
1437 bool blocked
= wxPyBeginBlockThreads();
1438 PyObject
* arglist
= Py_BuildValue("()");
1439 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1442 if (result
!= NULL
) {
1444 if (PyLong_Check(result
))
1445 o
= PyLong_AsLongLong(result
);
1448 o
= PyInt_AsLong(result
);
1451 wxPyEndBlockThreads(blocked
);
1455 //----------------------------------------------------------------------
1457 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1459 wxPyCallback::wxPyCallback(PyObject
* func
) {
1464 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1465 m_func
= other
.m_func
;
1469 wxPyCallback::~wxPyCallback() {
1470 bool blocked
= wxPyBeginBlockThreads();
1472 wxPyEndBlockThreads(blocked
);
1476 #define wxPy_PRECALLINIT "_preCallInit"
1477 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1479 // This function is used for all events destined for Python event handlers.
1480 void wxPyCallback::EventThunker(wxEvent
& event
) {
1481 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1482 PyObject
* func
= cb
->m_func
;
1486 bool checkSkip
= False
;
1488 bool blocked
= wxPyBeginBlockThreads();
1489 wxString className
= event
.GetClassInfo()->GetClassName();
1491 // If the event is one of these types then pass the original
1492 // event object instead of the one passed to us.
1493 if ( className
== wxT("wxPyEvent") ) {
1494 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1495 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1497 else if ( className
== wxT("wxPyCommandEvent") ) {
1498 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1499 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1502 arg
= wxPyConstructObject((void*)&event
, className
);
1508 // "intern" the pre/post method names to speed up the HasAttr
1509 static PyObject
* s_preName
= NULL
;
1510 static PyObject
* s_postName
= NULL
;
1511 if (s_preName
== NULL
) {
1512 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1513 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1516 // Check if the event object needs some preinitialization
1517 if (PyObject_HasAttr(arg
, s_preName
)) {
1518 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1520 Py_DECREF(result
); // result is ignored, but we still need to decref it
1521 PyErr_Clear(); // Just in case...
1527 // Call the event handler, passing the event object
1528 tuple
= PyTuple_New(1);
1529 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1530 result
= PyEval_CallObject(func
, tuple
);
1532 Py_DECREF(result
); // result is ignored, but we still need to decref it
1533 PyErr_Clear(); // Just in case...
1538 // Check if the event object needs some post cleanup
1539 if (PyObject_HasAttr(arg
, s_postName
)) {
1540 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1542 Py_DECREF(result
); // result is ignored, but we still need to decref it
1543 PyErr_Clear(); // Just in case...
1550 // if the event object was one of our special types and
1551 // it had been cloned, then we need to extract the Skipped
1552 // value from the original and set it in the clone.
1553 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1555 event
.Skip(PyInt_AsLong(result
));
1563 wxPyEndBlockThreads(blocked
);
1567 //----------------------------------------------------------------------
1569 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1571 m_self
= other
.m_self
;
1572 m_class
= other
.m_class
;
1580 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1591 #if PYTHON_API_VERSION >= 1011
1593 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1594 // in which the method was defined. Starting with 2.2 it returns
1595 // "class that asked for the method" which seems totally bogus to me
1596 // but apprently it fixes some obscure problem waiting to happen in
1597 // Python. Since the API was not documented Guido and the gang felt
1598 // safe in changing it. Needless to say that totally screwed up the
1599 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1600 // code to find the class where the method is actually defined...
1603 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1607 if (PyType_Check(klass
)) { // new style classes
1608 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1609 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1610 PyObject
*mro
, *res
, *base
, *dict
;
1611 /* Look in tp_dict of types in MRO */
1613 assert(PyTuple_Check(mro
));
1614 n
= PyTuple_GET_SIZE(mro
);
1615 for (i
= 0; i
< n
; i
++) {
1616 base
= PyTuple_GET_ITEM(mro
, i
);
1617 if (PyClass_Check(base
))
1618 dict
= ((PyClassObject
*)base
)->cl_dict
;
1620 assert(PyType_Check(base
));
1621 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1623 assert(dict
&& PyDict_Check(dict
));
1624 res
= PyDict_GetItem(dict
, name
);
1631 else if (PyClass_Check(klass
)) { // old style classes
1632 // This code is borrowed/adapted from class_lookup in classobject.c
1633 PyClassObject
* cp
= (PyClassObject
*)klass
;
1634 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1635 if (value
!= NULL
) {
1636 return (PyObject
*)cp
;
1638 n
= PyTuple_Size(cp
->cl_bases
);
1639 for (i
= 0; i
< n
; i
++) {
1640 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1641 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1653 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1655 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1657 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1659 #else // 2.2 and after, the hard way...
1661 PyObject
* nameo
= PyString_FromString(name
);
1662 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1670 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1671 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1672 self
->m_lastFound
= NULL
;
1674 // If the object (m_self) has an attibute of the given name...
1675 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1676 PyObject
*method
, *klass
;
1677 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1679 // ...and if that attribute is a method, and if that method's class is
1680 // not from a base class...
1681 if (PyMethod_Check(method
) &&
1682 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1683 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1685 // ...then we'll save a pointer to the method so callCallback can call it.
1686 self
->m_lastFound
= method
;
1692 return m_lastFound
!= NULL
;
1696 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1700 result
= callCallbackObj(argTuple
);
1701 if (result
) { // Assumes an integer return type...
1702 retval
= PyInt_AsLong(result
);
1704 PyErr_Clear(); // forget about it if it's not...
1709 // Invoke the Python callable object, returning the raw PyObject return
1710 // value. Caller should DECREF the return value and also manage the GIL.
1711 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1714 // Save a copy of the pointer in case the callback generates another
1715 // callback. In that case m_lastFound will have a different value when
1716 // it gets back here...
1717 PyObject
* method
= m_lastFound
;
1719 result
= PyEval_CallObject(method
, argTuple
);
1720 Py_DECREF(argTuple
);
1729 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1730 cbh
.setSelf(self
, klass
, incref
);
1733 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1734 return cbh
.findCallback(name
);
1737 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1738 return cbh
.callCallback(argTuple
);
1741 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1742 return cbh
.callCallbackObj(argTuple
);
1746 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1747 if (cbh
->m_incRef
) {
1748 bool blocked
= wxPyBeginBlockThreads();
1749 Py_XDECREF(cbh
->m_self
);
1750 Py_XDECREF(cbh
->m_class
);
1751 wxPyEndBlockThreads(blocked
);
1755 //---------------------------------------------------------------------------
1756 //---------------------------------------------------------------------------
1757 // These event classes can be derived from in Python and passed through the event
1758 // system without losing anything. They do this by keeping a reference to
1759 // themselves and some special case handling in wxPyCallback::EventThunker.
1762 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1763 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1764 //Py_INCREF(m_self); // circular loops...
1768 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1769 bool blocked
= wxPyBeginBlockThreads();
1772 wxPyEndBlockThreads(blocked
);
1775 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1776 bool blocked
= wxPyBeginBlockThreads();
1784 wxPyEndBlockThreads(blocked
);
1787 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1793 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1794 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1797 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1798 : wxEvent(winid
, commandType
) {
1802 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1805 SetSelf(evt
.m_self
, True
);
1809 wxPyEvent::~wxPyEvent() {
1813 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1814 : wxCommandEvent(commandType
, id
) {
1818 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1819 : wxCommandEvent(evt
)
1821 SetSelf(evt
.m_self
, True
);
1825 wxPyCommandEvent::~wxPyCommandEvent() {
1832 //---------------------------------------------------------------------------
1833 //---------------------------------------------------------------------------
1834 // Convert a wxList to a Python List, only works for lists of wxObjects
1836 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1837 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1841 wxNode
* node
= list
->GetFirst();
1843 bool blocked
= wxPyBeginBlockThreads();
1844 pyList
= PyList_New(0);
1846 wxObj
= node
->GetData();
1847 pyObj
= wxPyMake_wxObject(wxObj
,false);
1848 PyList_Append(pyList
, pyObj
);
1849 node
= node
->GetNext();
1851 wxPyEndBlockThreads(blocked
);
1855 //----------------------------------------------------------------------
1857 long wxPyGetWinHandle(wxWindow
* win
) {
1860 return (long)win
->GetHandle();
1863 #if defined(__WXGTK__) || defined(__WXX11)
1864 return (long)GetXWindow(win
);
1868 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1869 return (long)win
->GetHandle();
1875 //----------------------------------------------------------------------
1876 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1877 // included in every file over and over again...
1879 wxString
* wxString_in_helper(PyObject
* source
) {
1880 wxString
* target
= NULL
;
1882 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1883 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1887 PyObject
* uni
= source
;
1888 if (PyString_Check(source
)) {
1889 uni
= PyUnicode_FromObject(source
);
1890 if (PyErr_Occurred()) return NULL
;
1892 target
= new wxString();
1893 size_t len
= PyUnicode_GET_SIZE(uni
);
1895 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1896 target
->UngetWriteBuf();
1899 if (PyString_Check(source
))
1902 char* tmpPtr
; int tmpSize
;
1903 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1904 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1907 target
= new wxString(tmpPtr
, tmpSize
);
1908 #endif // wxUSE_UNICODE
1914 // Similar to above except doesn't use "new" and doesn't set an exception
1915 wxString
Py2wxString(PyObject
* source
)
1920 // Convert to a unicode object, if not already, then to a wxString
1921 PyObject
* uni
= source
;
1922 if (!PyUnicode_Check(source
)) {
1923 uni
= PyUnicode_FromObject(source
);
1924 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1926 size_t len
= PyUnicode_GET_SIZE(uni
);
1928 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1929 target
.UngetWriteBuf();
1932 if (!PyUnicode_Check(source
))
1935 // Convert to a string object if it isn't already, then to wxString
1936 PyObject
* str
= source
;
1937 if (!PyString_Check(source
)) {
1938 str
= PyObject_Str(source
);
1939 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1941 char* tmpPtr
; int tmpSize
;
1942 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1943 target
= wxString(tmpPtr
, tmpSize
);
1945 if (!PyString_Check(source
))
1947 #endif // wxUSE_UNICODE
1953 // Make either a Python String or Unicode object, depending on build mode
1954 PyObject
* wx2PyString(const wxString
& src
)
1958 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1960 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1966 //----------------------------------------------------------------------
1969 byte
* byte_LIST_helper(PyObject
* source
) {
1970 if (!PyList_Check(source
)) {
1971 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1974 int count
= PyList_Size(source
);
1975 byte
* temp
= new byte
[count
];
1977 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1980 for (int x
=0; x
<count
; x
++) {
1981 PyObject
* o
= PyList_GetItem(source
, x
);
1982 if (! PyInt_Check(o
)) {
1983 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1986 temp
[x
] = (byte
)PyInt_AsLong(o
);
1992 int* int_LIST_helper(PyObject
* source
) {
1993 if (!PyList_Check(source
)) {
1994 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1997 int count
= PyList_Size(source
);
1998 int* temp
= new int[count
];
2000 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2003 for (int x
=0; x
<count
; x
++) {
2004 PyObject
* o
= PyList_GetItem(source
, x
);
2005 if (! PyInt_Check(o
)) {
2006 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2009 temp
[x
] = PyInt_AsLong(o
);
2015 long* long_LIST_helper(PyObject
* source
) {
2016 if (!PyList_Check(source
)) {
2017 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2020 int count
= PyList_Size(source
);
2021 long* temp
= new long[count
];
2023 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2026 for (int x
=0; x
<count
; x
++) {
2027 PyObject
* o
= PyList_GetItem(source
, x
);
2028 if (! PyInt_Check(o
)) {
2029 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2032 temp
[x
] = PyInt_AsLong(o
);
2038 char** string_LIST_helper(PyObject
* source
) {
2039 if (!PyList_Check(source
)) {
2040 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2043 int count
= PyList_Size(source
);
2044 char** temp
= new char*[count
];
2046 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2049 for (int x
=0; x
<count
; x
++) {
2050 PyObject
* o
= PyList_GetItem(source
, x
);
2051 if (! PyString_Check(o
)) {
2052 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2055 temp
[x
] = PyString_AsString(o
);
2060 //--------------------------------
2061 // Part of patch from Tim Hochberg
2062 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2063 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2064 point
->x
= PyInt_AS_LONG(o1
);
2065 point
->y
= PyInt_AS_LONG(o2
);
2068 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2069 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2070 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2073 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2074 // Disallow instances because they can cause havok
2077 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2078 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2079 point
->x
= PyInt_AsLong(o1
);
2080 point
->y
= PyInt_AsLong(o2
);
2087 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2088 // Putting all of the declarations here allows
2089 // us to put the error handling all in one place.
2092 PyObject
*o
, *o1
, *o2
;
2093 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2095 if (!PySequence_Check(source
)) {
2099 // The length of the sequence is returned in count.
2100 *count
= PySequence_Length(source
);
2105 temp
= new wxPoint
[*count
];
2107 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2110 for (x
=0; x
<*count
; x
++) {
2111 // Get an item: try fast way first.
2113 o
= PySequence_Fast_GET_ITEM(source
, x
);
2116 o
= PySequence_GetItem(source
, x
);
2122 // Convert o to wxPoint.
2123 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2124 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2125 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2126 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2127 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2131 else if (wxPySwigInstance_Check(o
)) {
2133 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2138 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2139 o1
= PySequence_GetItem(o
, 0);
2140 o2
= PySequence_GetItem(o
, 1);
2141 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2165 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2169 //------------------------------
2172 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2173 if (!PyList_Check(source
)) {
2174 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2177 int count
= PyList_Size(source
);
2178 wxBitmap
** temp
= new wxBitmap
*[count
];
2180 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2183 for (int x
=0; x
<count
; x
++) {
2184 PyObject
* o
= PyList_GetItem(source
, x
);
2185 if (wxPySwigInstance_Check(o
)) {
2187 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2188 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2194 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2203 wxString
* wxString_LIST_helper(PyObject
* source
) {
2204 if (!PyList_Check(source
)) {
2205 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2208 int count
= PyList_Size(source
);
2209 wxString
* temp
= new wxString
[count
];
2211 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2214 for (int x
=0; x
<count
; x
++) {
2215 PyObject
* o
= PyList_GetItem(source
, x
);
2216 #if PYTHON_API_VERSION >= 1009
2217 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2218 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2222 if (! PyString_Check(o
)) {
2223 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2228 wxString
* pStr
= wxString_in_helper(o
);
2236 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2237 if (!PyList_Check(source
)) {
2238 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2241 int count
= PyList_Size(source
);
2242 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2244 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2247 for (int x
=0; x
<count
; x
++) {
2248 PyObject
* o
= PyList_GetItem(source
, x
);
2249 if (wxPySwigInstance_Check(o
)) {
2250 wxAcceleratorEntry
* ae
;
2251 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2252 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2257 else if (PyTuple_Check(o
)) {
2258 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2259 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2260 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2261 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2264 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2272 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2273 if (!PyList_Check(source
)) {
2274 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2277 int count
= PyList_Size(source
);
2278 wxPen
** temp
= new wxPen
*[count
];
2280 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2283 for (int x
=0; x
<count
; x
++) {
2284 PyObject
* o
= PyList_GetItem(source
, x
);
2285 if (wxPySwigInstance_Check(o
)) {
2287 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2289 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2296 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2304 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2305 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2308 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2312 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2313 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2316 o1
= PySequence_GetItem(source
, 0);
2317 o2
= PySequence_GetItem(source
, 1);
2320 *i1
= PyInt_AsLong(o1
);
2321 *i2
= PyInt_AsLong(o2
);
2331 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2332 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2333 PyObject
*o1
, *o2
, *o3
, *o4
;
2335 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2339 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2340 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2341 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2342 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2345 o1
= PySequence_GetItem(source
, 0);
2346 o2
= PySequence_GetItem(source
, 1);
2347 o3
= PySequence_GetItem(source
, 2);
2348 o4
= PySequence_GetItem(source
, 3);
2351 *i1
= PyInt_AsLong(o1
);
2352 *i2
= PyInt_AsLong(o2
);
2353 *i3
= PyInt_AsLong(o3
);
2354 *i4
= PyInt_AsLong(o4
);
2366 //----------------------------------------------------------------------
2368 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2372 if (wxPySwigInstance_Check(source
) &&
2373 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2377 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2383 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2385 if (source
== Py_None
) {
2386 **obj
= wxSize(-1,-1);
2389 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2393 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2395 if (source
== Py_None
) {
2396 **obj
= wxPoint(-1,-1);
2399 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2404 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2406 if (source
== Py_None
) {
2407 **obj
= wxRealPoint(-1,-1);
2411 // If source is an object instance then it may already be the right type
2412 if (wxPySwigInstance_Check(source
)) {
2414 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2419 // otherwise a 2-tuple of floats is expected
2420 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2421 PyObject
* o1
= PySequence_GetItem(source
, 0);
2422 PyObject
* o2
= PySequence_GetItem(source
, 1);
2423 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2428 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2435 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2441 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2443 if (source
== Py_None
) {
2444 **obj
= wxRect(-1,-1,-1,-1);
2448 // If source is an object instance then it may already be the right type
2449 if (wxPySwigInstance_Check(source
)) {
2451 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2456 // otherwise a 4-tuple of integers is expected
2457 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2458 PyObject
* o1
= PySequence_GetItem(source
, 0);
2459 PyObject
* o2
= PySequence_GetItem(source
, 1);
2460 PyObject
* o3
= PySequence_GetItem(source
, 2);
2461 PyObject
* o4
= PySequence_GetItem(source
, 3);
2462 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2463 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2470 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2471 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2480 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2486 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2488 if (source
== Py_None
) {
2489 **obj
= wxNullColour
;
2493 // If source is an object instance then it may already be the right type
2494 if (wxPySwigInstance_Check(source
)) {
2496 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2501 // otherwise check for a string
2502 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2503 wxString spec
= Py2wxString(source
);
2504 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2505 long red
, green
, blue
;
2506 red
= green
= blue
= 0;
2507 spec
.Mid(1,2).ToLong(&red
, 16);
2508 spec
.Mid(3,2).ToLong(&green
, 16);
2509 spec
.Mid(5,2).ToLong(&blue
, 16);
2511 **obj
= wxColour(red
, green
, blue
);
2514 else { // it's a colour name
2515 **obj
= wxColour(spec
);
2519 // last chance: 3-tuple of integers is expected
2520 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2521 PyObject
* o1
= PySequence_GetItem(source
, 0);
2522 PyObject
* o2
= PySequence_GetItem(source
, 1);
2523 PyObject
* o3
= PySequence_GetItem(source
, 2);
2524 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2530 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2538 PyErr_SetString(PyExc_TypeError
,
2539 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2544 bool wxColour_typecheck(PyObject
* source
) {
2546 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2549 if (PyString_Check(source
) || PyUnicode_Check(source
))
2557 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2559 if (source
== Py_None
) {
2560 **obj
= wxPoint2D(-1,-1);
2564 // If source is an object instance then it may already be the right type
2565 if (wxPySwigInstance_Check(source
)) {
2567 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2572 // otherwise a length-2 sequence of floats is expected
2573 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2574 PyObject
* o1
= PySequence_GetItem(source
, 0);
2575 PyObject
* o2
= PySequence_GetItem(source
, 1);
2576 // This should really check for floats, not numbers -- but that would break code.
2577 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2582 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2588 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2593 //----------------------------------------------------------------------
2595 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2597 PyObject
* list
= PyList_New(0);
2598 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2600 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2602 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2604 PyList_Append(list
, str
);
2611 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2613 PyObject
* list
= PyList_New(0);
2614 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2615 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2616 PyList_Append(list
, number
);
2623 //----------------------------------------------------------------------
2624 //----------------------------------------------------------------------