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) (wxwin)->m_wxwindow ? \
32 GDK_WINDOW_XWINDOW(GTK_PIZZA((wxwin)->m_wxwindow)->bin_window) : \
33 GDK_WINDOW_XWINDOW((wxwin)->m_widget->window)
38 #include "wx/x11/privx.h"
39 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
43 #include <wx/mac/private.h>
46 #include <wx/clipbrd.h>
47 #include <wx/mimetype.h>
50 //----------------------------------------------------------------------
52 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
53 #error Python must support Unicode to use wxWindows Unicode
56 //----------------------------------------------------------------------
58 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
59 bool wxPyDoCleanup
= false;
60 bool wxPyDoingCleanup
= false;
63 #ifdef WXP_WITH_THREAD
64 struct wxPyThreadState
{
66 PyThreadState
* tstate
;
68 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
69 : tid(_tid
), tstate(_tstate
) {}
72 #include <wx/dynarray.h>
73 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
74 #include <wx/arrimpl.cpp>
75 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
77 wxPyThreadStateArray
* wxPyTStates
= NULL
;
78 wxMutex
* wxPyTMutex
= NULL
;
82 static PyObject
* wxPython_dict
= NULL
;
83 static PyObject
* wxPyAssertionError
= NULL
;
84 static PyObject
* wxPyNoAppError
= NULL
;
86 PyObject
* wxPyPtrTypeMap
= NULL
;
89 #ifdef __WXMSW__ // If building for win32...
90 //----------------------------------------------------------------------
91 // This gets run when the DLL is loaded. We just need to save a handle.
92 //----------------------------------------------------------------------
95 HINSTANCE hinstDLL
, // handle to DLL module
96 DWORD fdwReason
, // reason for calling function
97 LPVOID lpvReserved
// reserved
100 // If wxPython is embedded in another wxWindows app then
101 // the inatance has already been set.
102 if (! wxGetInstance())
103 wxSetInstance(hinstDLL
);
108 //----------------------------------------------------------------------
109 // Classes for implementing the wxp main application shell.
110 //----------------------------------------------------------------------
112 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
116 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
117 m_startupComplete
= false;
121 wxPyApp::~wxPyApp() {
125 // This one isn't acutally called... We fake it with _BootstrapApp
126 bool wxPyApp::OnInit() {
131 int wxPyApp::MainLoop() {
134 DeletePendingObjects();
135 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
137 if ( m_exitOnFrameDelete
== Later
) {
138 m_exitOnFrameDelete
= Yes
;
141 retval
= wxApp::MainLoop();
148 bool wxPyApp::OnInitGui() {
150 wxApp::OnInitGui(); // in this case always call the base class version
151 bool blocked
= wxPyBeginBlockThreads();
152 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
153 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
154 wxPyEndBlockThreads(blocked
);
159 int wxPyApp::OnExit() {
161 bool blocked
= wxPyBeginBlockThreads();
162 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
163 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
164 wxPyEndBlockThreads(blocked
);
165 wxApp::OnExit(); // in this case always call the base class version
171 void wxPyApp::OnAssert(const wxChar
*file
,
176 // if we're not fully initialized then just log the error
177 if (! m_startupComplete
) {
180 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
190 // If the OnAssert is overloaded in the Python class then call it...
192 bool blocked
= wxPyBeginBlockThreads();
193 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
194 PyObject
* fso
= wx2PyString(file
);
195 PyObject
* cso
= wx2PyString(file
);
198 mso
= wx2PyString(file
);
200 mso
= Py_None
; Py_INCREF(Py_None
);
202 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
207 wxPyEndBlockThreads(blocked
);
209 // ...otherwise do our own thing with it
212 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
215 // turn it into a Python exception?
216 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
219 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
226 bool blocked
= wxPyBeginBlockThreads();
227 PyObject
* s
= wx2PyString(buf
);
228 PyErr_SetObject(wxPyAssertionError
, s
);
230 wxPyEndBlockThreads(blocked
);
232 // Now when control returns to whatever API wrapper was called from
233 // Python it should detect that an exception is set and will return
234 // NULL, signalling the exception to Python.
237 // Send it to the normal log destination, but only if
238 // not _DIALOG because it will call this too
239 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
242 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
251 // do the normal wx assert dialog?
252 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
253 wxApp::OnAssert(file
, line
, cond
, msg
);
258 // For catching Apple Events
259 void wxPyApp::MacOpenFile(const wxString
&fileName
)
261 bool blocked
= wxPyBeginBlockThreads();
262 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
263 PyObject
* s
= wx2PyString(fileName
);
264 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
267 wxPyEndBlockThreads(blocked
);
270 void wxPyApp::MacPrintFile(const wxString
&fileName
)
272 bool blocked
= wxPyBeginBlockThreads();
273 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
274 PyObject
* s
= wx2PyString(fileName
);
275 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
278 wxPyEndBlockThreads(blocked
);
281 void wxPyApp::MacNewFile()
283 bool blocked
= wxPyBeginBlockThreads();
284 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
285 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
286 wxPyEndBlockThreads(blocked
);
289 void wxPyApp::MacReopenApp()
291 bool blocked
= wxPyBeginBlockThreads();
292 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
293 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
294 wxPyEndBlockThreads(blocked
);
299 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
301 return s_macSupportPCMenuShortcuts
;
308 long wxPyApp::GetMacAboutMenuItemId() {
310 return s_macAboutMenuItemId
;
317 long wxPyApp::GetMacPreferencesMenuItemId() {
319 return s_macPreferencesMenuItemId
;
326 long wxPyApp::GetMacExitMenuItemId() {
328 return s_macExitMenuItemId
;
335 wxString
wxPyApp::GetMacHelpMenuTitleName() {
337 return s_macHelpMenuTitleName
;
339 return wxEmptyString
;
344 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
346 s_macSupportPCMenuShortcuts
= val
;
351 void wxPyApp::SetMacAboutMenuItemId(long val
) {
353 s_macAboutMenuItemId
= val
;
358 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
360 s_macPreferencesMenuItemId
= val
;
365 void wxPyApp::SetMacExitMenuItemId(long val
) {
367 s_macExitMenuItemId
= val
;
372 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
374 s_macHelpMenuTitleName
= val
;
379 // This finishes the initialization of wxWindows and then calls the OnInit
380 // that should be present in the derived (Python) class.
381 void wxPyApp::_BootstrapApp()
383 static bool haveInitialized
= false;
384 bool result
, blocked
;
385 PyObject
* retval
= NULL
;
386 PyObject
* pyint
= NULL
;
389 // Only initialize wxWidgets once
390 if (! haveInitialized
) {
392 // Get any command-line args passed to this program from the sys module
395 blocked
= wxPyBeginBlockThreads();
396 PyObject
* sysargv
= PySys_GetObject("argv");
397 if (sysargv
!= NULL
) {
398 argc
= PyList_Size(sysargv
);
399 argv
= new char*[argc
+1];
401 for(x
=0; x
<argc
; x
++) {
402 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
403 argv
[x
] = PyString_AsString(pyArg
);
407 wxPyEndBlockThreads(blocked
);
409 // Initialize wxWidgets
410 result
= wxEntryStart(argc
, argv
);
413 blocked
= wxPyBeginBlockThreads();
415 PyErr_SetString(PyExc_SystemError
,
416 "wxEntryStart failed, unable to initialize wxWidgets!"
418 " (Is DISPLAY set properly?)"
424 // On wxGTK the locale will be changed to match the system settings, but
425 // Python needs to have LC_NUMERIC set to "C" in order for the floating
426 // point conversions and such to work right.
427 #if defined(__WXGTK__) && PYTHON_API_VERSION <= 1012
428 setlocale(LC_NUMERIC
, "C");
431 // The stock objects were all NULL when they were loaded into
432 // SWIG generated proxies, so re-init those now...
433 wxPy_ReinitStockObjects(3);
435 wxPyEndBlockThreads(blocked
);
436 haveInitialized
= true;
439 // It's now ok to generate exceptions for assertion errors.
440 wxPythonApp
->SetStartupComplete(true);
442 // Call the Python wxApp's OnInit function
443 blocked
= wxPyBeginBlockThreads();
444 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
446 PyObject
* method
= m_myInst
.GetLastFound();
447 PyObject
* argTuple
= PyTuple_New(0);
448 retval
= PyEval_CallObject(method
, argTuple
);
454 pyint
= PyNumber_Int(retval
);
456 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
459 result
= PyInt_AS_LONG(pyint
);
462 // Is it okay if there is no OnInit? Probably so...
467 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
474 wxPyEndBlockThreads(blocked
);
477 //---------------------------------------------------------------------
478 //----------------------------------------------------------------------
482 static char* wxPyCopyCString(const wxChar
* src
)
484 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
485 size_t len
= strlen(buff
);
486 char* dest
= new char[len
+1];
492 static char* wxPyCopyCString(const char* src
) // we need a char version too
494 size_t len
= strlen(src
);
495 char* dest
= new char[len
+1];
501 static wxChar
* wxPyCopyWString(const char *src
)
503 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
504 wxString
str(src
, *wxConvCurrent
);
505 return copystring(str
);
509 static wxChar
* wxPyCopyWString(const wxChar
*src
)
511 return copystring(src
);
517 inline const char* dropwx(const char* name
) {
518 if (name
[0] == 'w' && name
[1] == 'x')
524 //----------------------------------------------------------------------
526 // This function is called when the wx._core_ module is imported to do some
527 // initial setup. (Before there is a wxApp object.) The rest happens in
528 // wxPyApp::_BootstrapApp
529 void __wxPyPreStart(PyObject
* moduleDict
)
533 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
534 // | _CRTDBG_CHECK_ALWAYS_DF
535 // | _CRTDBG_DELAY_FREE_MEM_DF
539 #ifdef WXP_WITH_THREAD
540 PyEval_InitThreads();
541 wxPyTStates
= new wxPyThreadStateArray
;
542 wxPyTMutex
= new wxMutex
;
544 // Save the current (main) thread state in our array
545 PyThreadState
* tstate
= wxPyBeginAllowThreads();
546 wxPyEndAllowThreads(tstate
);
549 // Ensure that the build options in the DLL (or whatever) match this build
550 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
552 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
553 wxPy_ReinitStockObjects(1);
555 wxInitAllImageHandlers();
560 void __wxPyCleanup() {
561 wxPyDoingCleanup
= true;
563 wxPyDoCleanup
= false;
566 #ifdef WXP_WITH_THREAD
569 wxPyTStates
->Empty();
576 // Save a reference to the dictionary of the wx._core module, and inject
577 // a few more things into it.
578 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
581 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
584 if (!PyDict_Check(wxPython_dict
)) {
585 PyErr_SetString(PyExc_TypeError
,
586 "_wxPySetDictionary must have dictionary object!");
590 if (! wxPyPtrTypeMap
)
591 wxPyPtrTypeMap
= PyDict_New();
592 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
594 // Create an exception object to use for wxASSERTions
595 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
596 PyExc_AssertionError
, NULL
);
597 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
599 // Create an exception object to use when the app object hasn't been created yet
600 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
601 PyExc_RuntimeError
, NULL
);
602 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
607 #define wxPlatform "__WXMOTIF__"
608 #define wxPlatName "wxMotif"
611 #define wxPlatform "__WXX11__"
612 #define wxPlatName "wxX11"
615 #define wxPlatform "__WXGTK__"
616 #define wxPlatName "wxGTK"
619 #define wxPlatform "__WXMSW__"
620 #define wxPlatName "wxMSW"
623 #define wxPlatform "__WXMAC__"
624 #define wxPlatName "wxMac"
633 // These should be deprecated in favor of the PlatformInfo tuple built below...
634 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
635 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
636 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
638 // Make a tuple of strings that gives more info about the platform.
639 PyObject
* PlatInfo
= PyList_New(0);
642 #define _AddInfoString(st) \
643 obj = PyString_FromString(st); \
644 PyList_Append(PlatInfo, obj); \
647 _AddInfoString(wxPlatform
);
648 _AddInfoString(wxPlatName
);
650 _AddInfoString("unicode");
652 _AddInfoString("ansi");
656 _AddInfoString("gtk2");
658 _AddInfoString("gtk1");
662 _AddInfoString("wx-assertions-on");
664 _AddInfoString("wx-assertions-off");
667 #undef _AddInfoString
669 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
671 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
677 //---------------------------------------------------------------------------
679 // Python's PyInstance_Check does not return True for instances of new-style
680 // classes. This should get close enough for both new and old classes but I
681 // should re-evaluate the need for doing instance checks...
682 bool wxPyInstance_Check(PyObject
* obj
) {
683 return PyObject_HasAttrString(obj
, "__class__") != 0;
687 // This one checks if the object is an instance of a SWIG proxy class (it has
688 // a .this attribute)
689 bool wxPySwigInstance_Check(PyObject
* obj
) {
690 return PyObject_HasAttrString(obj
, "this") != 0;
693 //---------------------------------------------------------------------------
695 // The stock objects are no longer created when the wx._core_ module is
696 // imported, but only after the app object has been created. The
697 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
698 // objects though various stages of evolution:
700 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
701 // object will be created (otherwise SWIG will just use None.)
703 // pass 2: After the module has been imported and the python proxys have
704 // been created, then set the __class__ to be _wxPyUnbornObject so
705 // it will catch any access to the object and will raise an exception.
707 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
711 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
713 wxPy_ReinitStockObjects(2);
718 static void rsoPass2(const char* name
)
720 static PyObject
* unbornObjectClass
= NULL
;
723 if (unbornObjectClass
== NULL
) {
724 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
725 Py_INCREF(unbornObjectClass
);
728 // Find the object instance
729 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
730 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
731 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
734 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
738 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
744 // Find the object instance
745 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
746 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
747 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
749 // Find the class object and put it back in the instance
750 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
751 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
752 PyObject_SetAttrString(obj
, "__class__", classobj
);
754 // Rebuild the .this swigified pointer with the new value of the C++ pointer
755 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
756 PyObject_SetAttrString(obj
, "this", ptrobj
);
762 void wxPy_ReinitStockObjects(int pass
)
765 // If there is already an App object then wxPython is probably embedded in
766 // a wx C++ application, so there is no need to do all this.
767 static bool embedded
= false;
768 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
772 if (pass
== 3 && embedded
)
776 #define REINITOBJ(name, classname) \
777 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
778 else if (pass == 2) { rsoPass2(#name); } \
779 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
782 #define REINITOBJ2(name, classname) \
784 else if (pass == 2) { rsoPass2(#name); } \
785 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
788 REINITOBJ(wxNORMAL_FONT
, wxFont
);
789 REINITOBJ(wxSMALL_FONT
, wxFont
);
790 REINITOBJ(wxITALIC_FONT
, wxFont
);
791 REINITOBJ(wxSWISS_FONT
, wxFont
);
793 REINITOBJ(wxRED_PEN
, wxPen
);
794 REINITOBJ(wxCYAN_PEN
, wxPen
);
795 REINITOBJ(wxGREEN_PEN
, wxPen
);
796 REINITOBJ(wxBLACK_PEN
, wxPen
);
797 REINITOBJ(wxWHITE_PEN
, wxPen
);
798 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
799 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
800 REINITOBJ(wxGREY_PEN
, wxPen
);
801 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
802 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
804 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
805 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
806 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
807 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
808 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
809 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
810 REINITOBJ(wxRED_BRUSH
, wxBrush
);
811 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
812 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
813 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
815 REINITOBJ(wxBLACK
, wxColour
);
816 REINITOBJ(wxWHITE
, wxColour
);
817 REINITOBJ(wxRED
, wxColour
);
818 REINITOBJ(wxBLUE
, wxColour
);
819 REINITOBJ(wxGREEN
, wxColour
);
820 REINITOBJ(wxCYAN
, wxColour
);
821 REINITOBJ(wxLIGHT_GREY
, wxColour
);
823 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
824 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
825 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
827 REINITOBJ2(wxNullBitmap
, wxBitmap
);
828 REINITOBJ2(wxNullIcon
, wxIcon
);
829 REINITOBJ2(wxNullCursor
, wxCursor
);
830 REINITOBJ2(wxNullPen
, wxPen
);
831 REINITOBJ2(wxNullBrush
, wxBrush
);
832 REINITOBJ2(wxNullPalette
, wxPalette
);
833 REINITOBJ2(wxNullFont
, wxFont
);
834 REINITOBJ2(wxNullColour
, wxColour
);
836 REINITOBJ(wxTheFontList
, wxFontList
);
837 REINITOBJ(wxThePenList
, wxPenList
);
838 REINITOBJ(wxTheBrushList
, wxBrushList
);
839 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
842 REINITOBJ2(wxDefaultValidator
, wxValidator
);
843 REINITOBJ2(wxNullImage
, wxImage
);
844 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
850 //---------------------------------------------------------------------------
852 // Check for existence of a wxApp, setting an exception if there isn't one.
853 // This doesn't need to aquire the GIL because it should only be called from
854 // an %exception before the lock is released.
856 bool wxPyCheckForApp() {
857 if (wxTheApp
!= NULL
)
860 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
865 //---------------------------------------------------------------------------
868 void wxPyClientData_dtor(wxPyClientData
* self
) {
869 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
870 // may have already garbage collected the object...
871 bool blocked
= wxPyBeginBlockThreads();
872 Py_DECREF(self
->m_obj
);
874 wxPyEndBlockThreads(blocked
);
878 void wxPyUserData_dtor(wxPyUserData
* self
) {
879 if (! wxPyDoingCleanup
) {
880 bool blocked
= wxPyBeginBlockThreads();
881 Py_DECREF(self
->m_obj
);
883 wxPyEndBlockThreads(blocked
);
888 // This is called when an OOR controled object is being destroyed. Although
889 // the C++ object is going away there is no way to force the Python object
890 // (and all references to it) to die too. This causes problems (crashes) in
891 // wxPython when a python shadow object attempts to call a C++ method using
892 // the now bogus pointer... So to try and prevent this we'll do a little black
893 // magic and change the class of the python instance to a class that will
894 // raise an exception for any attempt to call methods with it. See
895 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
896 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
898 static PyObject
* deadObjectClass
= NULL
;
900 bool blocked
= wxPyBeginBlockThreads();
901 if (deadObjectClass
== NULL
) {
902 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
903 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
904 // will lead to a deadlock when it tries to aquire the GIL again.
905 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
906 Py_INCREF(deadObjectClass
);
910 // Only if there is more than one reference to the object
911 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
912 // bool isInstance = wxPyInstance_Check(self->m_obj);
914 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
916 // Call __del__, if there is one.
917 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
919 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
923 if (PyErr_Occurred())
924 PyErr_Clear(); // just ignore it for now
927 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
929 // Clear the instance's dictionary
932 // put the name of the old class into the instance, and then reset the
933 // class to be the dead class.
934 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
935 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
936 PyDict_SetItemString(dict
, "_name", name
);
937 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
938 //Py_INCREF(deadObjectClass);
944 // m_obj is DECREF'd in the base class dtor...
945 wxPyEndBlockThreads(blocked
);
949 //---------------------------------------------------------------------------
950 // Stuff used by OOR to find the right wxPython class type to return and to
954 // The pointer type map is used when the "pointer" type name generated by SWIG
955 // is not the same as the shadow class name, for example wxPyTreeCtrl
956 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
957 // so we'll just make it a Python dictionary in the wx module's namespace.
958 // (See __wxSetDictionary)
959 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
960 if (! wxPyPtrTypeMap
)
961 wxPyPtrTypeMap
= PyDict_New();
962 PyDict_SetItemString(wxPyPtrTypeMap
,
964 PyString_FromString((char*)ptrName
));
970 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
971 PyObject
* target
= NULL
;
972 bool isEvtHandler
= false;
975 // If it's derived from wxEvtHandler then there may
976 // already be a pointer to a Python object that we can use
978 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
980 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
981 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
983 target
= data
->m_obj
;
990 // Otherwise make it the old fashioned way by making a new shadow
991 // object and putting this pointer in it. Look up the class
992 // heirarchy until we find a class name that is located in the
994 const wxClassInfo
* info
= source
->GetClassInfo();
995 wxString name
= info
->GetClassName();
996 bool exists
= wxPyCheckSwigType(name
);
997 while (info
&& !exists
) {
998 info
= info
->GetBaseClass1();
999 name
= info
->GetClassName();
1000 exists
= wxPyCheckSwigType(name
);
1003 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1004 if (target
&& isEvtHandler
)
1005 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1007 wxString
msg(wxT("wxPython class not found for "));
1008 msg
+= source
->GetClassInfo()->GetClassName();
1009 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1013 } else { // source was NULL so return None.
1014 Py_INCREF(Py_None
); target
= Py_None
;
1020 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1021 PyObject
* target
= NULL
;
1023 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1024 // If it's derived from wxSizer then there may already be a pointer to
1025 // a Python object that we can use in the OOR data.
1026 wxSizer
* sz
= (wxSizer
*)source
;
1027 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1029 target
= data
->m_obj
;
1035 target
= wxPyMake_wxObject(source
, setThisOwn
, false);
1036 if (target
!= Py_None
)
1037 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1043 //---------------------------------------------------------------------------
1046 #ifdef WXP_WITH_THREAD
1048 unsigned long wxPyGetCurrentThreadId() {
1049 return wxThread::GetCurrentId();
1052 static wxPyThreadState gs_shutdownTState
;
1055 wxPyThreadState
* wxPyGetThreadState() {
1056 if (wxPyTMutex
== NULL
) // Python is shutting down...
1057 return &gs_shutdownTState
;
1059 unsigned long ctid
= wxPyGetCurrentThreadId();
1060 wxPyThreadState
* tstate
= NULL
;
1063 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1064 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1065 if (info
.tid
== ctid
) {
1070 wxPyTMutex
->Unlock();
1071 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1077 void wxPySaveThreadState(PyThreadState
* tstate
) {
1078 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1079 gs_shutdownTState
.tstate
= tstate
;
1082 unsigned long ctid
= wxPyGetCurrentThreadId();
1084 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1085 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1086 if (info
.tid
== ctid
) {
1088 if (info
.tstate
!= tstate
)
1089 wxLogMessage("*** tstate mismatch!???");
1091 info
.tstate
= tstate
; // allow for transient tstates
1092 // Normally it will never change, but apparently COM callbacks
1093 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1094 // tstate which will then be garbage the next time we try to use
1097 wxPyTMutex
->Unlock();
1101 // not found, so add it...
1102 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1103 wxPyTMutex
->Unlock();
1110 // Calls from Python to wxWindows code are wrapped in calls to these
1113 PyThreadState
* wxPyBeginAllowThreads() {
1114 #ifdef WXP_WITH_THREAD
1115 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1116 wxPySaveThreadState(saved
);
1123 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1124 #ifdef WXP_WITH_THREAD
1125 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1131 // Calls from wxWindows back to Python code, or even any PyObject
1132 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1134 bool wxPyBeginBlockThreads() {
1135 #ifdef WXP_WITH_THREAD
1136 // This works in for 2.3, maybe a good alternative to find the needed tstate?
1137 // PyThreadState *check = PyGILState_GetThisThreadState();
1139 PyThreadState
*current
= _PyThreadState_Current
;
1141 // Only block if there wasn't already a tstate, or if the current one is
1142 // not the one we are wanting to change to. This should prevent deadlock
1143 // if there are nested calls to wxPyBeginBlockThreads
1144 bool blocked
= false;
1145 wxPyThreadState
* tstate
= wxPyGetThreadState();
1146 if (current
!= tstate
->tstate
) {
1147 PyEval_RestoreThread(tstate
->tstate
);
1155 void wxPyEndBlockThreads(bool blocked
) {
1156 #ifdef WXP_WITH_THREAD
1157 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1158 // The value of blocked passed in needs to be the same as that returned
1159 // from wxPyBeginBlockThreads at the same nesting level.
1161 PyEval_SaveThread();
1167 //---------------------------------------------------------------------------
1168 // wxPyInputStream and wxPyCBInputStream methods
1171 void wxPyInputStream::close() {
1172 /* do nothing for now */
1175 void wxPyInputStream::flush() {
1176 /* do nothing for now */
1179 bool wxPyInputStream::eof() {
1181 return m_wxis
->Eof();
1186 wxPyInputStream::~wxPyInputStream() {
1193 PyObject
* wxPyInputStream::read(int size
) {
1194 PyObject
* obj
= NULL
;
1196 const int BUFSIZE
= 1024;
1198 // check if we have a real wxInputStream to work with
1200 bool blocked
= wxPyBeginBlockThreads();
1201 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1202 wxPyEndBlockThreads(blocked
);
1207 // read while bytes are available on the stream
1208 while ( m_wxis
->CanRead() ) {
1209 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1210 buf
.UngetAppendBuf(m_wxis
->LastRead());
1213 } else { // Read only size number of characters
1214 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1215 buf
.UngetWriteBuf(m_wxis
->LastRead());
1219 bool blocked
= wxPyBeginBlockThreads();
1220 wxStreamError err
= m_wxis
->GetLastError();
1221 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1222 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1225 // We use only strings for the streams, not unicode
1226 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1228 wxPyEndBlockThreads(blocked
);
1233 PyObject
* wxPyInputStream::readline(int size
) {
1234 PyObject
* obj
= NULL
;
1239 // check if we have a real wxInputStream to work with
1241 bool blocked
= wxPyBeginBlockThreads();
1242 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1243 wxPyEndBlockThreads(blocked
);
1247 // read until \n or byte limit reached
1248 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1249 ch
= m_wxis
->GetC();
1254 bool blocked
= wxPyBeginBlockThreads();
1255 wxStreamError err
= m_wxis
->GetLastError();
1256 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1257 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1260 // We use only strings for the streams, not unicode
1261 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1263 wxPyEndBlockThreads(blocked
);
1268 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1271 // check if we have a real wxInputStream to work with
1273 bool blocked
= wxPyBeginBlockThreads();
1274 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1275 wxPyEndBlockThreads(blocked
);
1280 bool blocked
= wxPyBeginBlockThreads();
1281 pylist
= PyList_New(0);
1282 wxPyEndBlockThreads(blocked
);
1285 bool blocked
= wxPyBeginBlockThreads();
1287 wxPyEndBlockThreads(blocked
);
1291 // read sizehint bytes or until EOF
1293 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1294 PyObject
* s
= this->readline();
1296 bool blocked
= wxPyBeginBlockThreads();
1298 wxPyEndBlockThreads(blocked
);
1301 bool blocked
= wxPyBeginBlockThreads();
1302 PyList_Append(pylist
, s
);
1303 i
+= PyString_Size(s
);
1304 wxPyEndBlockThreads(blocked
);
1308 wxStreamError err
= m_wxis
->GetLastError();
1309 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1310 bool blocked
= wxPyBeginBlockThreads();
1312 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1313 wxPyEndBlockThreads(blocked
);
1321 void wxPyInputStream::seek(int offset
, int whence
) {
1323 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1326 int wxPyInputStream::tell(){
1328 return m_wxis
->TellI();
1335 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1336 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1340 wxPyCBInputStream::~wxPyCBInputStream() {
1342 if (m_block
) blocked
= wxPyBeginBlockThreads();
1346 if (m_block
) wxPyEndBlockThreads(blocked
);
1350 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1352 if (block
) blocked
= wxPyBeginBlockThreads();
1354 PyObject
* read
= getMethod(py
, "read");
1355 PyObject
* seek
= getMethod(py
, "seek");
1356 PyObject
* tell
= getMethod(py
, "tell");
1359 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1363 if (block
) wxPyEndBlockThreads(blocked
);
1367 if (block
) wxPyEndBlockThreads(blocked
);
1368 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1372 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1373 return wxPyCBInputStream::create(py
, block
);
1376 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1377 if (!PyObject_HasAttrString(py
, name
))
1379 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1380 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1388 wxFileOffset
wxPyCBInputStream::GetLength() const {
1389 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1390 if (m_seek
&& m_tell
) {
1391 wxFileOffset temp
= self
->OnSysTell();
1392 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1393 self
->OnSysSeek(temp
, wxFromStart
);
1397 return wxInvalidOffset
;
1401 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1405 bool blocked
= wxPyBeginBlockThreads();
1406 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1407 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1411 if ((result
!= NULL
) && PyString_Check(result
)) {
1412 o
= PyString_Size(result
);
1414 m_lasterror
= wxSTREAM_EOF
;
1417 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1422 m_lasterror
= wxSTREAM_READ_ERROR
;
1423 wxPyEndBlockThreads(blocked
);
1427 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1428 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1432 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1433 bool blocked
= wxPyBeginBlockThreads();
1434 #if defined( __WINCE__) || defined(_LARGE_FILES) || wxHAS_HUGE_FILES
1435 // wxFileOffset is a 64-bit value...
1436 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1438 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1440 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1443 wxPyEndBlockThreads(blocked
);
1448 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1449 bool blocked
= wxPyBeginBlockThreads();
1450 PyObject
* arglist
= Py_BuildValue("()");
1451 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1454 if (result
!= NULL
) {
1455 #if defined( __WINCE__) || defined(_LARGE_FILES) || wxHAS_HUGE_FILES
1456 if (PyLong_Check(result
))
1457 o
= PyLong_AsLongLong(result
);
1460 o
= PyInt_AsLong(result
);
1463 wxPyEndBlockThreads(blocked
);
1467 //----------------------------------------------------------------------
1469 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1471 wxPyCallback::wxPyCallback(PyObject
* func
) {
1476 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1477 m_func
= other
.m_func
;
1481 wxPyCallback::~wxPyCallback() {
1482 bool blocked
= wxPyBeginBlockThreads();
1484 wxPyEndBlockThreads(blocked
);
1488 #define wxPy_PRECALLINIT "_preCallInit"
1489 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1491 // This function is used for all events destined for Python event handlers.
1492 void wxPyCallback::EventThunker(wxEvent
& event
) {
1493 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1494 PyObject
* func
= cb
->m_func
;
1498 bool checkSkip
= false;
1500 bool blocked
= wxPyBeginBlockThreads();
1501 wxString className
= event
.GetClassInfo()->GetClassName();
1503 // If the event is one of these types then pass the original
1504 // event object instead of the one passed to us.
1505 if ( className
== wxT("wxPyEvent") ) {
1506 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1507 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1509 else if ( className
== wxT("wxPyCommandEvent") ) {
1510 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1511 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1514 arg
= wxPyConstructObject((void*)&event
, className
);
1520 // "intern" the pre/post method names to speed up the HasAttr
1521 static PyObject
* s_preName
= NULL
;
1522 static PyObject
* s_postName
= NULL
;
1523 if (s_preName
== NULL
) {
1524 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1525 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1528 // Check if the event object needs some preinitialization
1529 if (PyObject_HasAttr(arg
, s_preName
)) {
1530 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1532 Py_DECREF(result
); // result is ignored, but we still need to decref it
1533 PyErr_Clear(); // Just in case...
1539 // Call the event handler, passing the event object
1540 tuple
= PyTuple_New(1);
1541 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1542 result
= PyEval_CallObject(func
, tuple
);
1544 Py_DECREF(result
); // result is ignored, but we still need to decref it
1545 PyErr_Clear(); // Just in case...
1550 // Check if the event object needs some post cleanup
1551 if (PyObject_HasAttr(arg
, s_postName
)) {
1552 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1554 Py_DECREF(result
); // result is ignored, but we still need to decref it
1555 PyErr_Clear(); // Just in case...
1562 // if the event object was one of our special types and
1563 // it had been cloned, then we need to extract the Skipped
1564 // value from the original and set it in the clone.
1565 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1567 event
.Skip(PyInt_AsLong(result
));
1575 wxPyEndBlockThreads(blocked
);
1579 //----------------------------------------------------------------------
1581 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1583 m_self
= other
.m_self
;
1584 m_class
= other
.m_class
;
1592 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1603 #if PYTHON_API_VERSION >= 1011
1605 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1606 // in which the method was defined. Starting with 2.2 it returns
1607 // "class that asked for the method" which seems totally bogus to me
1608 // but apprently it fixes some obscure problem waiting to happen in
1609 // Python. Since the API was not documented Guido and the gang felt
1610 // safe in changing it. Needless to say that totally screwed up the
1611 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1612 // code to find the class where the method is actually defined...
1615 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1619 if (PyType_Check(klass
)) { // new style classes
1620 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1621 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1622 PyObject
*mro
, *res
, *base
, *dict
;
1623 /* Look in tp_dict of types in MRO */
1625 assert(PyTuple_Check(mro
));
1626 n
= PyTuple_GET_SIZE(mro
);
1627 for (i
= 0; i
< n
; i
++) {
1628 base
= PyTuple_GET_ITEM(mro
, i
);
1629 if (PyClass_Check(base
))
1630 dict
= ((PyClassObject
*)base
)->cl_dict
;
1632 assert(PyType_Check(base
));
1633 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1635 assert(dict
&& PyDict_Check(dict
));
1636 res
= PyDict_GetItem(dict
, name
);
1643 else if (PyClass_Check(klass
)) { // old style classes
1644 // This code is borrowed/adapted from class_lookup in classobject.c
1645 PyClassObject
* cp
= (PyClassObject
*)klass
;
1646 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1647 if (value
!= NULL
) {
1648 return (PyObject
*)cp
;
1650 n
= PyTuple_Size(cp
->cl_bases
);
1651 for (i
= 0; i
< n
; i
++) {
1652 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1653 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1665 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1667 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1669 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1671 #else // 2.2 and after, the hard way...
1673 PyObject
* nameo
= PyString_FromString(name
);
1674 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1682 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1683 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1684 self
->m_lastFound
= NULL
;
1686 // If the object (m_self) has an attibute of the given name...
1687 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1688 PyObject
*method
, *klass
;
1689 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1691 // ...and if that attribute is a method, and if that method's class is
1692 // not from a base class...
1693 if (PyMethod_Check(method
) &&
1694 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1695 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1697 // ...then we'll save a pointer to the method so callCallback can call it.
1698 self
->m_lastFound
= method
;
1704 return m_lastFound
!= NULL
;
1708 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1712 result
= callCallbackObj(argTuple
);
1713 if (result
) { // Assumes an integer return type...
1714 retval
= PyInt_AsLong(result
);
1716 PyErr_Clear(); // forget about it if it's not...
1721 // Invoke the Python callable object, returning the raw PyObject return
1722 // value. Caller should DECREF the return value and also manage the GIL.
1723 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1726 // Save a copy of the pointer in case the callback generates another
1727 // callback. In that case m_lastFound will have a different value when
1728 // it gets back here...
1729 PyObject
* method
= m_lastFound
;
1731 result
= PyEval_CallObject(method
, argTuple
);
1732 Py_DECREF(argTuple
);
1741 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1742 cbh
.setSelf(self
, klass
, incref
);
1745 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1746 return cbh
.findCallback(name
);
1749 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1750 return cbh
.callCallback(argTuple
);
1753 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1754 return cbh
.callCallbackObj(argTuple
);
1758 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1759 if (cbh
->m_incRef
) {
1760 bool blocked
= wxPyBeginBlockThreads();
1761 Py_XDECREF(cbh
->m_self
);
1762 Py_XDECREF(cbh
->m_class
);
1763 wxPyEndBlockThreads(blocked
);
1767 //---------------------------------------------------------------------------
1768 //---------------------------------------------------------------------------
1769 // These event classes can be derived from in Python and passed through the event
1770 // system without losing anything. They do this by keeping a reference to
1771 // themselves and some special case handling in wxPyCallback::EventThunker.
1774 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1775 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1776 //Py_INCREF(m_self); // circular loops...
1780 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1781 bool blocked
= wxPyBeginBlockThreads();
1784 wxPyEndBlockThreads(blocked
);
1787 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1788 bool blocked
= wxPyBeginBlockThreads();
1796 wxPyEndBlockThreads(blocked
);
1799 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1805 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1806 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1809 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1810 : wxEvent(winid
, commandType
) {
1814 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1817 SetSelf(evt
.m_self
, true);
1821 wxPyEvent::~wxPyEvent() {
1825 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1826 : wxCommandEvent(commandType
, id
) {
1830 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1831 : wxCommandEvent(evt
)
1833 SetSelf(evt
.m_self
, true);
1837 wxPyCommandEvent::~wxPyCommandEvent() {
1844 //---------------------------------------------------------------------------
1845 //---------------------------------------------------------------------------
1846 // Convert a wxList to a Python List, only works for lists of wxObjects
1848 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1849 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1853 wxNode
* node
= list
->GetFirst();
1855 bool blocked
= wxPyBeginBlockThreads();
1856 pyList
= PyList_New(0);
1858 wxObj
= node
->GetData();
1859 pyObj
= wxPyMake_wxObject(wxObj
,false);
1860 PyList_Append(pyList
, pyObj
);
1861 node
= node
->GetNext();
1863 wxPyEndBlockThreads(blocked
);
1867 //----------------------------------------------------------------------
1869 long wxPyGetWinHandle(wxWindow
* win
) {
1872 return (long)win
->GetHandle();
1875 #if defined(__WXGTK__) || defined(__WXX11)
1876 return (long)GetXWindow(win
);
1880 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1881 return (long)win
->GetHandle();
1887 //----------------------------------------------------------------------
1888 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1889 // included in every file over and over again...
1891 wxString
* wxString_in_helper(PyObject
* source
) {
1892 wxString
* target
= NULL
;
1894 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1895 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1899 PyObject
* uni
= source
;
1900 if (PyString_Check(source
)) {
1901 uni
= PyUnicode_FromObject(source
);
1902 if (PyErr_Occurred()) return NULL
;
1904 target
= new wxString();
1905 size_t len
= PyUnicode_GET_SIZE(uni
);
1907 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1908 target
->UngetWriteBuf(len
);
1911 if (PyString_Check(source
))
1914 // Convert to a string object if it isn't already, then to wxString
1915 PyObject
* str
= source
;
1916 if (!PyString_Check(source
)) {
1917 str
= PyObject_Str(source
);
1918 if (PyErr_Occurred()) return NULL
;
1920 char* tmpPtr
; int tmpSize
;
1921 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1922 target
= new wxString(tmpPtr
, tmpSize
);
1924 if (!PyString_Check(source
))
1926 #endif // wxUSE_UNICODE
1932 // Similar to above except doesn't use "new" and doesn't set an exception
1933 wxString
Py2wxString(PyObject
* source
)
1938 // Convert to a unicode object, if not already, then to a wxString
1939 PyObject
* uni
= source
;
1940 if (!PyUnicode_Check(source
)) {
1941 uni
= PyUnicode_FromObject(source
);
1942 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1944 size_t len
= PyUnicode_GET_SIZE(uni
);
1946 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1947 target
.UngetWriteBuf();
1950 if (!PyUnicode_Check(source
))
1953 // Convert to a string object if it isn't already, then to wxString
1954 PyObject
* str
= source
;
1955 if (!PyString_Check(source
)) {
1956 str
= PyObject_Str(source
);
1957 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1959 char* tmpPtr
; int tmpSize
;
1960 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1961 target
= wxString(tmpPtr
, tmpSize
);
1963 if (!PyString_Check(source
))
1965 #endif // wxUSE_UNICODE
1971 // Make either a Python String or Unicode object, depending on build mode
1972 PyObject
* wx2PyString(const wxString
& src
)
1976 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1978 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1984 //----------------------------------------------------------------------
1987 byte
* byte_LIST_helper(PyObject
* source
) {
1988 if (!PyList_Check(source
)) {
1989 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1992 int count
= PyList_Size(source
);
1993 byte
* temp
= new byte
[count
];
1995 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1998 for (int x
=0; x
<count
; x
++) {
1999 PyObject
* o
= PyList_GetItem(source
, x
);
2000 if (! PyInt_Check(o
)) {
2001 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2004 temp
[x
] = (byte
)PyInt_AsLong(o
);
2010 int* int_LIST_helper(PyObject
* source
) {
2011 if (!PyList_Check(source
)) {
2012 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2015 int count
= PyList_Size(source
);
2016 int* temp
= new int[count
];
2018 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2021 for (int x
=0; x
<count
; x
++) {
2022 PyObject
* o
= PyList_GetItem(source
, x
);
2023 if (! PyInt_Check(o
)) {
2024 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2027 temp
[x
] = PyInt_AsLong(o
);
2033 long* long_LIST_helper(PyObject
* source
) {
2034 if (!PyList_Check(source
)) {
2035 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2038 int count
= PyList_Size(source
);
2039 long* temp
= new long[count
];
2041 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2044 for (int x
=0; x
<count
; x
++) {
2045 PyObject
* o
= PyList_GetItem(source
, x
);
2046 if (! PyInt_Check(o
)) {
2047 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2050 temp
[x
] = PyInt_AsLong(o
);
2056 char** string_LIST_helper(PyObject
* source
) {
2057 if (!PyList_Check(source
)) {
2058 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2061 int count
= PyList_Size(source
);
2062 char** temp
= new char*[count
];
2064 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2067 for (int x
=0; x
<count
; x
++) {
2068 PyObject
* o
= PyList_GetItem(source
, x
);
2069 if (! PyString_Check(o
)) {
2070 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2073 temp
[x
] = PyString_AsString(o
);
2078 //--------------------------------
2079 // Part of patch from Tim Hochberg
2080 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2081 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2082 point
->x
= PyInt_AS_LONG(o1
);
2083 point
->y
= PyInt_AS_LONG(o2
);
2086 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2087 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2088 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2091 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2092 // Disallow instances because they can cause havok
2095 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2096 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2097 point
->x
= PyInt_AsLong(o1
);
2098 point
->y
= PyInt_AsLong(o2
);
2105 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2106 // Putting all of the declarations here allows
2107 // us to put the error handling all in one place.
2110 PyObject
*o
, *o1
, *o2
;
2111 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2113 if (!PySequence_Check(source
)) {
2117 // The length of the sequence is returned in count.
2118 *count
= PySequence_Length(source
);
2123 temp
= new wxPoint
[*count
];
2125 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2128 for (x
=0; x
<*count
; x
++) {
2129 // Get an item: try fast way first.
2131 o
= PySequence_Fast_GET_ITEM(source
, x
);
2134 o
= PySequence_GetItem(source
, x
);
2140 // Convert o to wxPoint.
2141 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2142 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2143 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2144 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2145 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2149 else if (wxPySwigInstance_Check(o
)) {
2151 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2156 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2157 o1
= PySequence_GetItem(o
, 0);
2158 o2
= PySequence_GetItem(o
, 1);
2159 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2183 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2187 //------------------------------
2190 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2191 if (!PyList_Check(source
)) {
2192 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2195 int count
= PyList_Size(source
);
2196 wxBitmap
** temp
= new wxBitmap
*[count
];
2198 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2201 for (int x
=0; x
<count
; x
++) {
2202 PyObject
* o
= PyList_GetItem(source
, x
);
2203 if (wxPySwigInstance_Check(o
)) {
2205 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2206 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2212 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2221 wxString
* wxString_LIST_helper(PyObject
* source
) {
2222 if (!PyList_Check(source
)) {
2223 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2226 int count
= PyList_Size(source
);
2227 wxString
* temp
= new wxString
[count
];
2229 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2232 for (int x
=0; x
<count
; x
++) {
2233 PyObject
* o
= PyList_GetItem(source
, x
);
2234 #if PYTHON_API_VERSION >= 1009
2235 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2236 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2240 if (! PyString_Check(o
)) {
2241 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2246 wxString
* pStr
= wxString_in_helper(o
);
2254 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2255 if (!PyList_Check(source
)) {
2256 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2259 int count
= PyList_Size(source
);
2260 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2262 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2265 for (int x
=0; x
<count
; x
++) {
2266 PyObject
* o
= PyList_GetItem(source
, x
);
2267 if (wxPySwigInstance_Check(o
)) {
2268 wxAcceleratorEntry
* ae
;
2269 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2270 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2275 else if (PyTuple_Check(o
)) {
2276 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2277 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2278 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2279 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2282 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2290 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2291 if (!PyList_Check(source
)) {
2292 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2295 int count
= PyList_Size(source
);
2296 wxPen
** temp
= new wxPen
*[count
];
2298 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2301 for (int x
=0; x
<count
; x
++) {
2302 PyObject
* o
= PyList_GetItem(source
, x
);
2303 if (wxPySwigInstance_Check(o
)) {
2305 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2307 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2314 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2322 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2323 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2326 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2330 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2331 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2334 o1
= PySequence_GetItem(source
, 0);
2335 o2
= PySequence_GetItem(source
, 1);
2338 *i1
= PyInt_AsLong(o1
);
2339 *i2
= PyInt_AsLong(o2
);
2349 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2350 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2351 PyObject
*o1
, *o2
, *o3
, *o4
;
2353 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2357 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2358 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2359 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2360 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2363 o1
= PySequence_GetItem(source
, 0);
2364 o2
= PySequence_GetItem(source
, 1);
2365 o3
= PySequence_GetItem(source
, 2);
2366 o4
= PySequence_GetItem(source
, 3);
2369 *i1
= PyInt_AsLong(o1
);
2370 *i2
= PyInt_AsLong(o2
);
2371 *i3
= PyInt_AsLong(o3
);
2372 *i4
= PyInt_AsLong(o4
);
2384 //----------------------------------------------------------------------
2386 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2390 if (wxPySwigInstance_Check(source
) &&
2391 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2395 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2401 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2403 if (source
== Py_None
) {
2404 **obj
= wxSize(-1,-1);
2407 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2411 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2413 if (source
== Py_None
) {
2414 **obj
= wxPoint(-1,-1);
2417 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2422 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2424 if (source
== Py_None
) {
2425 **obj
= wxRealPoint(-1,-1);
2429 // If source is an object instance then it may already be the right type
2430 if (wxPySwigInstance_Check(source
)) {
2432 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2437 // otherwise a 2-tuple of floats is expected
2438 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2439 PyObject
* o1
= PySequence_GetItem(source
, 0);
2440 PyObject
* o2
= PySequence_GetItem(source
, 1);
2441 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2446 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2453 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2459 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2461 if (source
== Py_None
) {
2462 **obj
= wxRect(-1,-1,-1,-1);
2466 // If source is an object instance then it may already be the right type
2467 if (wxPySwigInstance_Check(source
)) {
2469 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2474 // otherwise a 4-tuple of integers is expected
2475 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2476 PyObject
* o1
= PySequence_GetItem(source
, 0);
2477 PyObject
* o2
= PySequence_GetItem(source
, 1);
2478 PyObject
* o3
= PySequence_GetItem(source
, 2);
2479 PyObject
* o4
= PySequence_GetItem(source
, 3);
2480 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2481 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2488 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2489 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2498 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2504 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2506 if (source
== Py_None
) {
2507 **obj
= wxNullColour
;
2511 // If source is an object instance then it may already be the right type
2512 if (wxPySwigInstance_Check(source
)) {
2514 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2519 // otherwise check for a string
2520 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2521 wxString spec
= Py2wxString(source
);
2522 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2523 long red
, green
, blue
;
2524 red
= green
= blue
= 0;
2525 spec
.Mid(1,2).ToLong(&red
, 16);
2526 spec
.Mid(3,2).ToLong(&green
, 16);
2527 spec
.Mid(5,2).ToLong(&blue
, 16);
2529 **obj
= wxColour(red
, green
, blue
);
2532 else { // it's a colour name
2533 **obj
= wxColour(spec
);
2537 // last chance: 3-tuple of integers is expected
2538 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2539 PyObject
* o1
= PySequence_GetItem(source
, 0);
2540 PyObject
* o2
= PySequence_GetItem(source
, 1);
2541 PyObject
* o3
= PySequence_GetItem(source
, 2);
2542 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2548 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2556 PyErr_SetString(PyExc_TypeError
,
2557 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2562 bool wxColour_typecheck(PyObject
* source
) {
2564 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2567 if (PyString_Check(source
) || PyUnicode_Check(source
))
2575 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2577 if (source
== Py_None
) {
2578 **obj
= wxPoint2D(-1,-1);
2582 // If source is an object instance then it may already be the right type
2583 if (wxPySwigInstance_Check(source
)) {
2585 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2590 // otherwise a length-2 sequence of floats is expected
2591 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2592 PyObject
* o1
= PySequence_GetItem(source
, 0);
2593 PyObject
* o2
= PySequence_GetItem(source
, 1);
2594 // This should really check for floats, not numbers -- but that would break code.
2595 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2600 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2606 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2611 //----------------------------------------------------------------------
2613 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2615 PyObject
* list
= PyList_New(0);
2616 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2618 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2620 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2622 PyList_Append(list
, str
);
2629 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2631 PyObject
* list
= PyList_New(0);
2632 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2633 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2634 PyList_Append(list
, number
);
2641 //----------------------------------------------------------------------
2642 //----------------------------------------------------------------------