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 < 1009 && 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 #if !wxPyUSE_GIL_STATE
65 struct wxPyThreadState
{
67 PyThreadState
* tstate
;
69 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
70 : tid(_tid
), tstate(_tstate
) {}
73 #include <wx/dynarray.h>
74 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
75 #include <wx/arrimpl.cpp>
76 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
78 wxPyThreadStateArray
* wxPyTStates
= NULL
;
79 wxMutex
* wxPyTMutex
= NULL
;
85 #define DEFAULTENCODING_SIZE 64
86 static char wxPyDefaultEncoding
[DEFAULTENCODING_SIZE
] = "ascii";
88 static PyObject
* wxPython_dict
= NULL
;
89 static PyObject
* wxPyAssertionError
= NULL
;
90 static PyObject
* wxPyNoAppError
= NULL
;
92 PyObject
* wxPyPtrTypeMap
= NULL
;
95 #ifdef __WXMSW__ // If building for win32...
96 //----------------------------------------------------------------------
97 // This gets run when the DLL is loaded. We just need to save a handle.
98 //----------------------------------------------------------------------
102 HINSTANCE hinstDLL
, // handle to DLL module
103 DWORD fdwReason
, // reason for calling function
104 LPVOID lpvReserved
// reserved
107 // If wxPython is embedded in another wxWidgets app then
108 // the instance has already been set.
109 if (! wxGetInstance())
110 wxSetInstance(hinstDLL
);
115 //----------------------------------------------------------------------
116 // Classes for implementing the wxp main application shell.
117 //----------------------------------------------------------------------
119 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
123 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
124 m_startupComplete
= false;
128 wxPyApp::~wxPyApp() {
132 // This one isn't acutally called... We fake it with _BootstrapApp
133 bool wxPyApp::OnInit() {
138 int wxPyApp::MainLoop() {
141 DeletePendingObjects();
142 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
144 if ( m_exitOnFrameDelete
== Later
) {
145 m_exitOnFrameDelete
= Yes
;
148 retval
= wxApp::MainLoop();
155 bool wxPyApp::OnInitGui() {
157 wxApp::OnInitGui(); // in this case always call the base class version
158 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
159 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
160 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
161 wxPyEndBlockThreads(blocked
);
166 int wxPyApp::OnExit() {
168 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
169 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
170 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
171 wxPyEndBlockThreads(blocked
);
172 wxApp::OnExit(); // in this case always call the base class version
178 void wxPyApp::OnAssert(const wxChar
*file
,
183 // if we're not fully initialized then just log the error
184 if (! m_startupComplete
) {
187 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
197 // If the OnAssert is overloaded in the Python class then call it...
199 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
200 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
201 PyObject
* fso
= wx2PyString(file
);
202 PyObject
* cso
= wx2PyString(file
);
205 mso
= wx2PyString(file
);
207 mso
= Py_None
; Py_INCREF(Py_None
);
209 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
214 wxPyEndBlockThreads(blocked
);
216 // ...otherwise do our own thing with it
219 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
222 // turn it into a Python exception?
223 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
226 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
233 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
234 PyObject
* s
= wx2PyString(buf
);
235 PyErr_SetObject(wxPyAssertionError
, s
);
237 wxPyEndBlockThreads(blocked
);
239 // Now when control returns to whatever API wrapper was called from
240 // Python it should detect that an exception is set and will return
241 // NULL, signalling the exception to Python.
244 // Send it to the normal log destination, but only if
245 // not _DIALOG because it will call this too
246 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
249 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
258 // do the normal wx assert dialog?
259 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
260 wxApp::OnAssert(file
, line
, cond
, msg
);
265 // For catching Apple Events
266 void wxPyApp::MacOpenFile(const wxString
&fileName
)
268 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
269 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
270 PyObject
* s
= wx2PyString(fileName
);
271 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
274 wxPyEndBlockThreads(blocked
);
277 void wxPyApp::MacPrintFile(const wxString
&fileName
)
279 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
280 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
281 PyObject
* s
= wx2PyString(fileName
);
282 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
285 wxPyEndBlockThreads(blocked
);
288 void wxPyApp::MacNewFile()
290 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
291 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
292 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
293 wxPyEndBlockThreads(blocked
);
296 void wxPyApp::MacReopenApp()
298 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
299 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
300 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
301 wxPyEndBlockThreads(blocked
);
306 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
308 return s_macSupportPCMenuShortcuts
;
315 long wxPyApp::GetMacAboutMenuItemId() {
317 return s_macAboutMenuItemId
;
324 long wxPyApp::GetMacPreferencesMenuItemId() {
326 return s_macPreferencesMenuItemId
;
333 long wxPyApp::GetMacExitMenuItemId() {
335 return s_macExitMenuItemId
;
342 wxString
wxPyApp::GetMacHelpMenuTitleName() {
344 return s_macHelpMenuTitleName
;
346 return wxEmptyString
;
351 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
353 s_macSupportPCMenuShortcuts
= val
;
358 void wxPyApp::SetMacAboutMenuItemId(long val
) {
360 s_macAboutMenuItemId
= val
;
365 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
367 s_macPreferencesMenuItemId
= val
;
372 void wxPyApp::SetMacExitMenuItemId(long val
) {
374 s_macExitMenuItemId
= val
;
379 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
381 s_macHelpMenuTitleName
= val
;
386 // This finishes the initialization of wxWindows and then calls the OnInit
387 // that should be present in the derived (Python) class.
388 void wxPyApp::_BootstrapApp()
390 static bool haveInitialized
= false;
393 PyObject
* retval
= NULL
;
394 PyObject
* pyint
= NULL
;
397 // Only initialize wxWidgets once
398 if (! haveInitialized
) {
400 // Get any command-line args passed to this program from the sys module
403 blocked
= wxPyBeginBlockThreads();
405 PyObject
* sysargv
= PySys_GetObject("argv");
406 PyObject
* executable
= PySys_GetObject("executable");
408 if (sysargv
!= NULL
&& executable
!= NULL
) {
409 argc
= PyList_Size(sysargv
) + 1;
410 argv
= new char*[argc
+1];
411 argv
[0] = PyString_AsString(executable
);
413 for(x
=1; x
<argc
; x
++) {
414 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
415 argv
[x
] = PyString_AsString(pyArg
);
419 wxPyEndBlockThreads(blocked
);
421 // Initialize wxWidgets
422 result
= wxEntryStart(argc
, argv
);
425 blocked
= wxPyBeginBlockThreads();
427 PyErr_SetString(PyExc_SystemError
,
428 "wxEntryStart failed, unable to initialize wxWidgets!"
430 " (Is DISPLAY set properly?)"
436 // On wxGTK the locale will be changed to match the system settings,
437 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
438 // for the floating point conversions and such to work right.
439 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
440 setlocale(LC_NUMERIC
, "C");
443 wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
445 // The stock objects were all NULL when they were loaded into
446 // SWIG generated proxies, so re-init those now...
447 wxPy_ReinitStockObjects(3);
449 wxPyEndBlockThreads(blocked
);
450 haveInitialized
= true;
453 // It's now ok to generate exceptions for assertion errors.
454 wxPythonApp
->SetStartupComplete(true);
456 // Call the Python wxApp's OnInit function
457 blocked
= wxPyBeginBlockThreads();
458 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
460 PyObject
* method
= m_myInst
.GetLastFound();
461 PyObject
* argTuple
= PyTuple_New(0);
462 retval
= PyEval_CallObject(method
, argTuple
);
468 pyint
= PyNumber_Int(retval
);
470 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
473 result
= PyInt_AS_LONG(pyint
);
476 // Is it okay if there is no OnInit? Probably so...
481 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
488 wxPyEndBlockThreads(blocked
);
491 //---------------------------------------------------------------------
492 //----------------------------------------------------------------------
496 static char* wxPyCopyCString(const wxChar
* src
)
498 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
499 size_t len
= strlen(buff
);
500 char* dest
= new char[len
+1];
506 static char* wxPyCopyCString(const char* src
) // we need a char version too
508 size_t len
= strlen(src
);
509 char* dest
= new char[len
+1];
515 static wxChar
* wxPyCopyWString(const char *src
)
517 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
518 wxString
str(src
, *wxConvCurrent
);
519 return copystring(str
);
523 static wxChar
* wxPyCopyWString(const wxChar
*src
)
525 return copystring(src
);
531 inline const char* dropwx(const char* name
) {
532 if (name
[0] == 'w' && name
[1] == 'x')
538 //----------------------------------------------------------------------
540 // This function is called when the wx._core_ module is imported to do some
541 // initial setup. (Before there is a wxApp object.) The rest happens in
542 // wxPyApp::_BootstrapApp
543 void __wxPyPreStart(PyObject
* moduleDict
)
547 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
548 // | _CRTDBG_CHECK_ALWAYS_DF
549 // | _CRTDBG_DELAY_FREE_MEM_DF
553 #ifdef WXP_WITH_THREAD
554 #if wxPyUSE_GIL_STATE
555 PyEval_InitThreads();
557 PyEval_InitThreads();
558 wxPyTStates
= new wxPyThreadStateArray
;
559 wxPyTMutex
= new wxMutex
;
561 // Save the current (main) thread state in our array
562 PyThreadState
* tstate
= wxPyBeginAllowThreads();
563 wxPyEndAllowThreads(tstate
);
567 // Ensure that the build options in the DLL (or whatever) match this build
568 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
570 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
571 wxPy_ReinitStockObjects(1);
573 wxInitAllImageHandlers();
578 void __wxPyCleanup() {
579 wxPyDoingCleanup
= true;
581 wxPyDoCleanup
= false;
584 #ifdef WXP_WITH_THREAD
585 #if !wxPyUSE_GIL_STATE
588 wxPyTStates
->Empty();
596 // Save a reference to the dictionary of the wx._core module, and inject
597 // a few more things into it.
598 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
601 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
604 if (!PyDict_Check(wxPython_dict
)) {
605 PyErr_SetString(PyExc_TypeError
,
606 "_wxPySetDictionary must have dictionary object!");
610 if (! wxPyPtrTypeMap
)
611 wxPyPtrTypeMap
= PyDict_New();
612 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
614 // Create an exception object to use for wxASSERTions
615 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
616 PyExc_AssertionError
, NULL
);
617 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
619 // Create an exception object to use when the app object hasn't been created yet
620 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
621 PyExc_RuntimeError
, NULL
);
622 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
627 #define wxPlatform "__WXMOTIF__"
628 #define wxPlatName "wxMotif"
631 #define wxPlatform "__WXX11__"
632 #define wxPlatName "wxX11"
635 #define wxPlatform "__WXGTK__"
636 #define wxPlatName "wxGTK"
639 #define wxPlatform "__WXMSW__"
640 #define wxPlatName "wxMSW"
643 #define wxPlatform "__WXMAC__"
644 #define wxPlatName "wxMac"
653 // These should be deprecated in favor of the PlatformInfo tuple built below...
654 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
655 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
656 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
658 // Make a tuple of strings that gives more info about the platform.
659 PyObject
* PlatInfo
= PyList_New(0);
662 #define _AddInfoString(st) \
663 obj = PyString_FromString(st); \
664 PyList_Append(PlatInfo, obj); \
667 _AddInfoString(wxPlatform
);
668 _AddInfoString(wxPlatName
);
670 _AddInfoString("unicode");
672 _AddInfoString("ansi");
676 _AddInfoString("gtk2");
678 _AddInfoString("gtk1");
682 _AddInfoString("wx-assertions-on");
684 _AddInfoString("wx-assertions-off");
687 #undef _AddInfoString
689 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
691 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
697 //---------------------------------------------------------------------------
699 // Python's PyInstance_Check does not return True for instances of new-style
700 // classes. This should get close enough for both new and old classes but I
701 // should re-evaluate the need for doing instance checks...
702 bool wxPyInstance_Check(PyObject
* obj
) {
703 return PyObject_HasAttrString(obj
, "__class__") != 0;
707 // This one checks if the object is an instance of a SWIG proxy class (it has
708 // a .this attribute)
709 bool wxPySwigInstance_Check(PyObject
* obj
) {
710 return PyObject_HasAttrString(obj
, "this") != 0;
713 //---------------------------------------------------------------------------
715 // The stock objects are no longer created when the wx._core_ module is
716 // imported, but only after the app object has been created. The
717 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
718 // objects though various stages of evolution:
720 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
721 // object will be created (otherwise SWIG will just use None.)
723 // pass 2: After the module has been imported and the python proxys have
724 // been created, then set the __class__ to be _wxPyUnbornObject so
725 // it will catch any access to the object and will raise an exception.
727 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
731 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
733 wxPy_ReinitStockObjects(2);
738 static void rsoPass2(const char* name
)
740 static PyObject
* unbornObjectClass
= NULL
;
743 if (unbornObjectClass
== NULL
) {
744 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
745 Py_INCREF(unbornObjectClass
);
748 // Find the object instance
749 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
750 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
751 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
754 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
758 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
764 // Find the object instance
765 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
766 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
767 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
769 // Find the class object and put it back in the instance
770 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
771 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
772 PyObject_SetAttrString(obj
, "__class__", classobj
);
774 // Rebuild the .this swigified pointer with the new value of the C++ pointer
775 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
776 PyObject_SetAttrString(obj
, "this", ptrobj
);
782 void wxPy_ReinitStockObjects(int pass
)
785 // If there is already an App object then wxPython is probably embedded in
786 // a wx C++ application, so there is no need to do all this.
787 static bool embedded
= false;
788 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
792 if (pass
== 3 && embedded
)
796 #define REINITOBJ(name, classname) \
797 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
798 else if (pass == 2) { rsoPass2(#name); } \
799 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
802 #define REINITOBJ2(name, classname) \
804 else if (pass == 2) { rsoPass2(#name); } \
805 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
808 REINITOBJ(wxNORMAL_FONT
, wxFont
);
809 REINITOBJ(wxSMALL_FONT
, wxFont
);
810 REINITOBJ(wxITALIC_FONT
, wxFont
);
811 REINITOBJ(wxSWISS_FONT
, wxFont
);
813 REINITOBJ(wxRED_PEN
, wxPen
);
814 REINITOBJ(wxCYAN_PEN
, wxPen
);
815 REINITOBJ(wxGREEN_PEN
, wxPen
);
816 REINITOBJ(wxBLACK_PEN
, wxPen
);
817 REINITOBJ(wxWHITE_PEN
, wxPen
);
818 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
819 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
820 REINITOBJ(wxGREY_PEN
, wxPen
);
821 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
822 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
824 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
825 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
826 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
827 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
828 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
829 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
830 REINITOBJ(wxRED_BRUSH
, wxBrush
);
831 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
832 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
833 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
835 REINITOBJ(wxBLACK
, wxColour
);
836 REINITOBJ(wxWHITE
, wxColour
);
837 REINITOBJ(wxRED
, wxColour
);
838 REINITOBJ(wxBLUE
, wxColour
);
839 REINITOBJ(wxGREEN
, wxColour
);
840 REINITOBJ(wxCYAN
, wxColour
);
841 REINITOBJ(wxLIGHT_GREY
, wxColour
);
843 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
844 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
845 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
847 REINITOBJ2(wxNullBitmap
, wxBitmap
);
848 REINITOBJ2(wxNullIcon
, wxIcon
);
849 REINITOBJ2(wxNullCursor
, wxCursor
);
850 REINITOBJ2(wxNullPen
, wxPen
);
851 REINITOBJ2(wxNullBrush
, wxBrush
);
852 REINITOBJ2(wxNullPalette
, wxPalette
);
853 REINITOBJ2(wxNullFont
, wxFont
);
854 REINITOBJ2(wxNullColour
, wxColour
);
856 REINITOBJ(wxTheFontList
, wxFontList
);
857 REINITOBJ(wxThePenList
, wxPenList
);
858 REINITOBJ(wxTheBrushList
, wxBrushList
);
859 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
862 REINITOBJ2(wxDefaultValidator
, wxValidator
);
863 REINITOBJ2(wxNullImage
, wxImage
);
864 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
870 //---------------------------------------------------------------------------
872 // Check for existence of a wxApp, setting an exception if there isn't one.
873 // This doesn't need to aquire the GIL because it should only be called from
874 // an %exception before the lock is released.
876 bool wxPyCheckForApp() {
877 if (wxTheApp
!= NULL
)
880 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
885 //---------------------------------------------------------------------------
887 void wxPyUserData_dtor(wxPyUserData
* self
) {
888 if (! wxPyDoingCleanup
) {
889 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
890 Py_DECREF(self
->m_obj
);
892 wxPyEndBlockThreads(blocked
);
897 void wxPyClientData_dtor(wxPyClientData
* self
) {
898 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
899 // may have already garbage collected the object...
900 if (self
->m_incRef
) {
901 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
902 Py_DECREF(self
->m_obj
);
903 wxPyEndBlockThreads(blocked
);
911 // This is called when an OOR controled object is being destroyed. Although
912 // the C++ object is going away there is no way to force the Python object
913 // (and all references to it) to die too. This causes problems (crashes) in
914 // wxPython when a python shadow object attempts to call a C++ method using
915 // the now bogus pointer... So to try and prevent this we'll do a little black
916 // magic and change the class of the python instance to a class that will
917 // raise an exception for any attempt to call methods with it. See
918 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
919 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
921 static PyObject
* deadObjectClass
= NULL
;
923 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
924 if (deadObjectClass
== NULL
) {
925 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
926 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
927 // will lead to a deadlock when it tries to aquire the GIL again.
928 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
929 Py_INCREF(deadObjectClass
);
933 // Only if there is more than one reference to the object and we are
934 // holding the OOR reference:
935 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
936 // bool isInstance = wxPyInstance_Check(self->m_obj);
938 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
940 // Call __del__, if there is one.
941 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
943 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
947 if (PyErr_Occurred())
948 PyErr_Clear(); // just ignore it for now
951 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
953 // Clear the instance's dictionary
956 // put the name of the old class into the instance, and then reset the
957 // class to be the dead class.
958 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
959 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
960 PyDict_SetItemString(dict
, "_name", name
);
961 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
962 //Py_INCREF(deadObjectClass);
968 // m_obj is DECREF'd in the base class dtor...
969 wxPyEndBlockThreads(blocked
);
973 //---------------------------------------------------------------------------
974 // Stuff used by OOR to find the right wxPython class type to return and to
978 // The pointer type map is used when the "pointer" type name generated by SWIG
979 // is not the same as the shadow class name, for example wxPyTreeCtrl
980 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
981 // so we'll just make it a Python dictionary in the wx module's namespace.
982 // (See __wxSetDictionary)
983 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
984 if (! wxPyPtrTypeMap
)
985 wxPyPtrTypeMap
= PyDict_New();
986 PyDict_SetItemString(wxPyPtrTypeMap
,
988 PyString_FromString((char*)ptrName
));
994 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
995 PyObject
* target
= NULL
;
996 bool isEvtHandler
= false;
999 // If it's derived from wxEvtHandler then there may
1000 // already be a pointer to a Python object that we can use
1002 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
1003 isEvtHandler
= true;
1004 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
1005 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
1007 target
= data
->m_obj
;
1014 // Otherwise make it the old fashioned way by making a new shadow
1015 // object and putting this pointer in it. Look up the class
1016 // heirarchy until we find a class name that is located in the
1018 const wxClassInfo
* info
= source
->GetClassInfo();
1019 wxString name
= info
->GetClassName();
1020 bool exists
= wxPyCheckSwigType(name
);
1021 while (info
&& !exists
) {
1022 info
= info
->GetBaseClass1();
1023 name
= info
->GetClassName();
1024 exists
= wxPyCheckSwigType(name
);
1027 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1028 if (target
&& isEvtHandler
)
1029 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1031 wxString
msg(wxT("wxPython class not found for "));
1032 msg
+= source
->GetClassInfo()->GetClassName();
1033 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1037 } else { // source was NULL so return None.
1038 Py_INCREF(Py_None
); target
= Py_None
;
1044 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1045 PyObject
* target
= NULL
;
1047 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1048 // If it's derived from wxSizer then there may already be a pointer to
1049 // a Python object that we can use in the OOR data.
1050 wxSizer
* sz
= (wxSizer
*)source
;
1051 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1053 target
= data
->m_obj
;
1059 target
= wxPyMake_wxObject(source
, setThisOwn
, false);
1060 if (target
!= Py_None
)
1061 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1067 //---------------------------------------------------------------------------
1070 #ifdef WXP_WITH_THREAD
1071 #if !wxPyUSE_GIL_STATE
1074 unsigned long wxPyGetCurrentThreadId() {
1075 return wxThread::GetCurrentId();
1078 static wxPyThreadState gs_shutdownTState
;
1081 wxPyThreadState
* wxPyGetThreadState() {
1082 if (wxPyTMutex
== NULL
) // Python is shutting down...
1083 return &gs_shutdownTState
;
1085 unsigned long ctid
= wxPyGetCurrentThreadId();
1086 wxPyThreadState
* tstate
= NULL
;
1089 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1090 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1091 if (info
.tid
== ctid
) {
1096 wxPyTMutex
->Unlock();
1097 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1103 void wxPySaveThreadState(PyThreadState
* tstate
) {
1104 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1105 gs_shutdownTState
.tstate
= tstate
;
1108 unsigned long ctid
= wxPyGetCurrentThreadId();
1110 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1111 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1112 if (info
.tid
== ctid
) {
1114 if (info
.tstate
!= tstate
)
1115 wxLogMessage("*** tstate mismatch!???");
1117 info
.tstate
= tstate
; // allow for transient tstates
1118 // Normally it will never change, but apparently COM callbacks
1119 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1120 // tstate which will then be garbage the next time we try to use
1123 wxPyTMutex
->Unlock();
1127 // not found, so add it...
1128 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1129 wxPyTMutex
->Unlock();
1137 // Calls from Python to wxWindows code are wrapped in calls to these
1140 PyThreadState
* wxPyBeginAllowThreads() {
1141 #ifdef WXP_WITH_THREAD
1142 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1143 #if !wxPyUSE_GIL_STATE
1144 wxPySaveThreadState(saved
);
1152 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1153 #ifdef WXP_WITH_THREAD
1154 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1160 // Calls from wxWindows back to Python code, or even any PyObject
1161 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1163 wxPyBlock_t
wxPyBeginBlockThreads() {
1164 #ifdef WXP_WITH_THREAD
1165 #if wxPyUSE_GIL_STATE
1166 PyGILState_STATE state
= PyGILState_Ensure();
1169 PyThreadState
*current
= _PyThreadState_Current
;
1171 // Only block if there wasn't already a tstate, or if the current one is
1172 // not the one we are wanting to change to. This should prevent deadlock
1173 // if there are nested calls to wxPyBeginBlockThreads
1174 wxPyBlock_t blocked
= false;
1175 wxPyThreadState
* tstate
= wxPyGetThreadState();
1176 if (current
!= tstate
->tstate
) {
1177 PyEval_RestoreThread(tstate
->tstate
);
1188 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1189 #ifdef WXP_WITH_THREAD
1190 #if wxPyUSE_GIL_STATE
1191 PyGILState_Release(blocked
);
1193 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1194 // The value of blocked passed in needs to be the same as that returned
1195 // from wxPyBeginBlockThreads at the same nesting level.
1197 PyEval_SaveThread();
1204 //---------------------------------------------------------------------------
1205 // wxPyInputStream and wxPyCBInputStream methods
1208 void wxPyInputStream::close() {
1209 /* do nothing for now */
1212 void wxPyInputStream::flush() {
1213 /* do nothing for now */
1216 bool wxPyInputStream::eof() {
1218 return m_wxis
->Eof();
1223 wxPyInputStream::~wxPyInputStream() {
1231 PyObject
* wxPyInputStream::read(int size
) {
1232 PyObject
* obj
= NULL
;
1234 const int BUFSIZE
= 1024;
1236 // check if we have a real wxInputStream to work with
1238 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1239 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1240 wxPyEndBlockThreads(blocked
);
1245 // read while bytes are available on the stream
1246 while ( m_wxis
->CanRead() ) {
1247 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1248 buf
.UngetAppendBuf(m_wxis
->LastRead());
1251 } else { // Read only size number of characters
1252 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1253 buf
.UngetWriteBuf(m_wxis
->LastRead());
1257 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1258 wxStreamError err
= m_wxis
->GetLastError();
1259 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1260 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1263 // We use only strings for the streams, not unicode
1264 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1266 wxPyEndBlockThreads(blocked
);
1271 PyObject
* wxPyInputStream::readline(int size
) {
1272 PyObject
* obj
= NULL
;
1277 // check if we have a real wxInputStream to work with
1279 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1280 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1281 wxPyEndBlockThreads(blocked
);
1285 // read until \n or byte limit reached
1286 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1287 ch
= m_wxis
->GetC();
1292 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1293 wxStreamError err
= m_wxis
->GetLastError();
1294 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1295 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1298 // We use only strings for the streams, not unicode
1299 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1301 wxPyEndBlockThreads(blocked
);
1306 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1309 // check if we have a real wxInputStream to work with
1311 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1312 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1313 wxPyEndBlockThreads(blocked
);
1318 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1319 pylist
= PyList_New(0);
1320 wxPyEndBlockThreads(blocked
);
1323 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1325 wxPyEndBlockThreads(blocked
);
1329 // read sizehint bytes or until EOF
1331 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1332 PyObject
* s
= this->readline();
1334 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1336 wxPyEndBlockThreads(blocked
);
1339 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1340 PyList_Append(pylist
, s
);
1341 i
+= PyString_Size(s
);
1342 wxPyEndBlockThreads(blocked
);
1346 wxStreamError err
= m_wxis
->GetLastError();
1347 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1348 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1350 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1351 wxPyEndBlockThreads(blocked
);
1359 void wxPyInputStream::seek(int offset
, int whence
) {
1361 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1364 int wxPyInputStream::tell(){
1366 return m_wxis
->TellI();
1373 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1374 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1377 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1379 m_read
= other
.m_read
;
1380 m_seek
= other
.m_seek
;
1381 m_tell
= other
.m_tell
;
1382 m_block
= other
.m_block
;
1389 wxPyCBInputStream::~wxPyCBInputStream() {
1390 wxPyBlock_t blocked
;
1391 if (m_block
) blocked
= wxPyBeginBlockThreads();
1395 if (m_block
) wxPyEndBlockThreads(blocked
);
1399 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1400 wxPyBlock_t blocked
;
1401 if (block
) blocked
= wxPyBeginBlockThreads();
1403 PyObject
* read
= getMethod(py
, "read");
1404 PyObject
* seek
= getMethod(py
, "seek");
1405 PyObject
* tell
= getMethod(py
, "tell");
1408 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1412 if (block
) wxPyEndBlockThreads(blocked
);
1416 if (block
) wxPyEndBlockThreads(blocked
);
1417 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1421 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1422 return wxPyCBInputStream::create(py
, block
);
1425 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1426 return new wxPyCBInputStream(*other
);
1429 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1430 if (!PyObject_HasAttrString(py
, name
))
1432 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1433 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1441 wxFileOffset
wxPyCBInputStream::GetLength() const {
1442 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1443 if (m_seek
&& m_tell
) {
1444 wxFileOffset temp
= self
->OnSysTell();
1445 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1446 self
->OnSysSeek(temp
, wxFromStart
);
1450 return wxInvalidOffset
;
1454 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1458 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1459 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1460 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1464 if ((result
!= NULL
) && PyString_Check(result
)) {
1465 o
= PyString_Size(result
);
1467 m_lasterror
= wxSTREAM_EOF
;
1470 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1475 m_lasterror
= wxSTREAM_READ_ERROR
;
1476 wxPyEndBlockThreads(blocked
);
1480 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1481 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1486 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1487 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1488 PyObject
* arglist
= PyTuple_New(2);
1490 if (sizeof(wxFileOffset
) > sizeof(long))
1491 // wxFileOffset is a 64-bit value...
1492 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1494 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1496 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1499 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1502 wxPyEndBlockThreads(blocked
);
1507 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1508 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1509 PyObject
* arglist
= Py_BuildValue("()");
1510 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1513 if (result
!= NULL
) {
1514 if (PyLong_Check(result
))
1515 o
= PyLong_AsLongLong(result
);
1517 o
= PyInt_AsLong(result
);
1520 wxPyEndBlockThreads(blocked
);
1524 //----------------------------------------------------------------------
1526 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1528 wxPyCallback::wxPyCallback(PyObject
* func
) {
1533 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1534 m_func
= other
.m_func
;
1538 wxPyCallback::~wxPyCallback() {
1539 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1541 wxPyEndBlockThreads(blocked
);
1545 #define wxPy_PRECALLINIT "_preCallInit"
1546 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1548 // This function is used for all events destined for Python event handlers.
1549 void wxPyCallback::EventThunker(wxEvent
& event
) {
1550 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1551 PyObject
* func
= cb
->m_func
;
1555 bool checkSkip
= false;
1557 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1558 wxString className
= event
.GetClassInfo()->GetClassName();
1560 // If the event is one of these types then pass the original
1561 // event object instead of the one passed to us.
1562 if ( className
== wxT("wxPyEvent") ) {
1563 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1564 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1566 else if ( className
== wxT("wxPyCommandEvent") ) {
1567 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1568 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1571 arg
= wxPyConstructObject((void*)&event
, className
);
1577 // "intern" the pre/post method names to speed up the HasAttr
1578 static PyObject
* s_preName
= NULL
;
1579 static PyObject
* s_postName
= NULL
;
1580 if (s_preName
== NULL
) {
1581 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1582 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1585 // Check if the event object needs some preinitialization
1586 if (PyObject_HasAttr(arg
, s_preName
)) {
1587 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1589 Py_DECREF(result
); // result is ignored, but we still need to decref it
1590 PyErr_Clear(); // Just in case...
1596 // Call the event handler, passing the event object
1597 tuple
= PyTuple_New(1);
1598 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1599 result
= PyEval_CallObject(func
, tuple
);
1601 Py_DECREF(result
); // result is ignored, but we still need to decref it
1602 PyErr_Clear(); // Just in case...
1607 // Check if the event object needs some post cleanup
1608 if (PyObject_HasAttr(arg
, s_postName
)) {
1609 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1611 Py_DECREF(result
); // result is ignored, but we still need to decref it
1612 PyErr_Clear(); // Just in case...
1619 // if the event object was one of our special types and
1620 // it had been cloned, then we need to extract the Skipped
1621 // value from the original and set it in the clone.
1622 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1624 event
.Skip(PyInt_AsLong(result
));
1632 wxPyEndBlockThreads(blocked
);
1636 //----------------------------------------------------------------------
1638 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1640 m_self
= other
.m_self
;
1641 m_class
= other
.m_class
;
1649 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1660 #if PYTHON_API_VERSION >= 1011
1662 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1663 // in which the method was defined. Starting with 2.2 it returns
1664 // "class that asked for the method" which seems totally bogus to me
1665 // but apprently it fixes some obscure problem waiting to happen in
1666 // Python. Since the API was not documented Guido and the gang felt
1667 // safe in changing it. Needless to say that totally screwed up the
1668 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1669 // code to find the class where the method is actually defined...
1672 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1676 if (PyType_Check(klass
)) { // new style classes
1677 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1678 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1679 PyObject
*mro
, *res
, *base
, *dict
;
1680 /* Look in tp_dict of types in MRO */
1682 assert(PyTuple_Check(mro
));
1683 n
= PyTuple_GET_SIZE(mro
);
1684 for (i
= 0; i
< n
; i
++) {
1685 base
= PyTuple_GET_ITEM(mro
, i
);
1686 if (PyClass_Check(base
))
1687 dict
= ((PyClassObject
*)base
)->cl_dict
;
1689 assert(PyType_Check(base
));
1690 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1692 assert(dict
&& PyDict_Check(dict
));
1693 res
= PyDict_GetItem(dict
, name
);
1700 else if (PyClass_Check(klass
)) { // old style classes
1701 // This code is borrowed/adapted from class_lookup in classobject.c
1702 PyClassObject
* cp
= (PyClassObject
*)klass
;
1703 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1704 if (value
!= NULL
) {
1705 return (PyObject
*)cp
;
1707 n
= PyTuple_Size(cp
->cl_bases
);
1708 for (i
= 0; i
< n
; i
++) {
1709 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1710 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1722 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1724 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1726 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1728 #else // 2.2 and after, the hard way...
1730 PyObject
* nameo
= PyString_FromString(name
);
1731 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1739 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1740 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1741 self
->m_lastFound
= NULL
;
1743 // If the object (m_self) has an attibute of the given name...
1744 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1745 PyObject
*method
, *klass
;
1746 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1748 // ...and if that attribute is a method, and if that method's class is
1749 // not from a base class...
1750 if (PyMethod_Check(method
) &&
1751 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1752 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1754 // ...then we'll save a pointer to the method so callCallback can call it.
1755 self
->m_lastFound
= method
;
1761 return m_lastFound
!= NULL
;
1765 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1769 result
= callCallbackObj(argTuple
);
1770 if (result
) { // Assumes an integer return type...
1771 retval
= PyInt_AsLong(result
);
1773 PyErr_Clear(); // forget about it if it's not...
1778 // Invoke the Python callable object, returning the raw PyObject return
1779 // value. Caller should DECREF the return value and also manage the GIL.
1780 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1783 // Save a copy of the pointer in case the callback generates another
1784 // callback. In that case m_lastFound will have a different value when
1785 // it gets back here...
1786 PyObject
* method
= m_lastFound
;
1788 result
= PyEval_CallObject(method
, argTuple
);
1789 Py_DECREF(argTuple
);
1798 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1799 cbh
.setSelf(self
, klass
, incref
);
1802 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1803 return cbh
.findCallback(name
);
1806 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1807 return cbh
.callCallback(argTuple
);
1810 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1811 return cbh
.callCallbackObj(argTuple
);
1815 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1816 if (cbh
->m_incRef
) {
1817 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1818 Py_XDECREF(cbh
->m_self
);
1819 Py_XDECREF(cbh
->m_class
);
1820 wxPyEndBlockThreads(blocked
);
1824 //---------------------------------------------------------------------------
1825 //---------------------------------------------------------------------------
1826 // These event classes can be derived from in Python and passed through the event
1827 // system without losing anything. They do this by keeping a reference to
1828 // themselves and some special case handling in wxPyCallback::EventThunker.
1831 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1832 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1833 //Py_INCREF(m_self); // circular loops...
1837 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1838 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1841 wxPyEndBlockThreads(blocked
);
1844 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1845 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1853 wxPyEndBlockThreads(blocked
);
1856 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1862 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1863 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1866 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1867 : wxEvent(winid
, commandType
) {
1871 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1874 SetSelf(evt
.m_self
, true);
1878 wxPyEvent::~wxPyEvent() {
1882 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1883 : wxCommandEvent(commandType
, id
) {
1887 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1888 : wxCommandEvent(evt
)
1890 SetSelf(evt
.m_self
, true);
1894 wxPyCommandEvent::~wxPyCommandEvent() {
1901 //---------------------------------------------------------------------------
1902 //---------------------------------------------------------------------------
1903 // Convert a wxList to a Python List, only works for lists of wxObjects
1905 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1906 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1910 wxNode
* node
= list
->GetFirst();
1912 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1913 pyList
= PyList_New(0);
1915 wxObj
= node
->GetData();
1916 pyObj
= wxPyMake_wxObject(wxObj
,false);
1917 PyList_Append(pyList
, pyObj
);
1918 node
= node
->GetNext();
1920 wxPyEndBlockThreads(blocked
);
1924 //----------------------------------------------------------------------
1926 long wxPyGetWinHandle(wxWindow
* win
) {
1929 return (long)win
->GetHandle();
1932 #if defined(__WXGTK__) || defined(__WXX11)
1933 return (long)GetXWindow(win
);
1937 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1938 return (long)win
->GetHandle();
1944 //----------------------------------------------------------------------
1945 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1946 // included in every file over and over again...
1948 wxString
* wxString_in_helper(PyObject
* source
) {
1949 wxString
* target
= NULL
;
1951 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1952 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1956 PyObject
* uni
= source
;
1957 if (PyString_Check(source
)) {
1958 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1959 if (PyErr_Occurred()) return NULL
;
1961 target
= new wxString();
1962 size_t len
= PyUnicode_GET_SIZE(uni
);
1964 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1965 target
->UngetWriteBuf(len
);
1968 if (PyString_Check(source
))
1971 // Convert to a string object if it isn't already, then to wxString
1972 PyObject
* str
= source
;
1973 if (PyUnicode_Check(source
)) {
1974 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1975 if (PyErr_Occurred()) return NULL
;
1977 else if (!PyString_Check(source
)) {
1978 str
= PyObject_Str(source
);
1979 if (PyErr_Occurred()) return NULL
;
1981 char* tmpPtr
; int tmpSize
;
1982 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1983 target
= new wxString(tmpPtr
, tmpSize
);
1985 if (!PyString_Check(source
))
1987 #endif // wxUSE_UNICODE
1993 // Similar to above except doesn't use "new" and doesn't set an exception
1994 wxString
Py2wxString(PyObject
* source
)
1999 // Convert to a unicode object, if not already, then to a wxString
2000 PyObject
* uni
= source
;
2001 if (!PyUnicode_Check(source
)) {
2002 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
2003 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2005 size_t len
= PyUnicode_GET_SIZE(uni
);
2007 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
2008 target
.UngetWriteBuf();
2011 if (!PyUnicode_Check(source
))
2014 // Convert to a string object if it isn't already, then to wxString
2015 PyObject
* str
= source
;
2016 if (PyUnicode_Check(source
)) {
2017 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
2018 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2020 else if (!PyString_Check(source
)) {
2021 str
= PyObject_Str(source
);
2022 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2024 char* tmpPtr
; int tmpSize
;
2025 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
2026 target
= wxString(tmpPtr
, tmpSize
);
2028 if (!PyString_Check(source
))
2030 #endif // wxUSE_UNICODE
2036 // Make either a Python String or Unicode object, depending on build mode
2037 PyObject
* wx2PyString(const wxString
& src
)
2041 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
2043 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
2050 void wxSetDefaultPyEncoding(const char* encoding
)
2052 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
2055 const char* wxGetDefaultPyEncoding()
2057 return wxPyDefaultEncoding
;
2060 //----------------------------------------------------------------------
2063 byte
* byte_LIST_helper(PyObject
* source
) {
2064 if (!PyList_Check(source
)) {
2065 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2068 int count
= PyList_Size(source
);
2069 byte
* temp
= new byte
[count
];
2071 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2074 for (int x
=0; x
<count
; x
++) {
2075 PyObject
* o
= PyList_GetItem(source
, x
);
2076 if (! PyInt_Check(o
)) {
2077 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2080 temp
[x
] = (byte
)PyInt_AsLong(o
);
2086 int* int_LIST_helper(PyObject
* source
) {
2087 if (!PyList_Check(source
)) {
2088 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2091 int count
= PyList_Size(source
);
2092 int* temp
= new int[count
];
2094 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2097 for (int x
=0; x
<count
; x
++) {
2098 PyObject
* o
= PyList_GetItem(source
, x
);
2099 if (! PyInt_Check(o
)) {
2100 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2103 temp
[x
] = PyInt_AsLong(o
);
2109 long* long_LIST_helper(PyObject
* source
) {
2110 if (!PyList_Check(source
)) {
2111 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2114 int count
= PyList_Size(source
);
2115 long* temp
= new long[count
];
2117 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2120 for (int x
=0; x
<count
; x
++) {
2121 PyObject
* o
= PyList_GetItem(source
, x
);
2122 if (! PyInt_Check(o
)) {
2123 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2126 temp
[x
] = PyInt_AsLong(o
);
2132 char** string_LIST_helper(PyObject
* source
) {
2133 if (!PyList_Check(source
)) {
2134 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2137 int count
= PyList_Size(source
);
2138 char** temp
= new char*[count
];
2140 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2143 for (int x
=0; x
<count
; x
++) {
2144 PyObject
* o
= PyList_GetItem(source
, x
);
2145 if (! PyString_Check(o
)) {
2146 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2149 temp
[x
] = PyString_AsString(o
);
2154 //--------------------------------
2155 // Part of patch from Tim Hochberg
2156 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2157 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2158 point
->x
= PyInt_AS_LONG(o1
);
2159 point
->y
= PyInt_AS_LONG(o2
);
2162 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2163 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2164 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2167 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2168 // Disallow instances because they can cause havok
2171 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2172 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2173 point
->x
= PyInt_AsLong(o1
);
2174 point
->y
= PyInt_AsLong(o2
);
2181 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2182 // Putting all of the declarations here allows
2183 // us to put the error handling all in one place.
2186 PyObject
*o
, *o1
, *o2
;
2187 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2189 if (!PySequence_Check(source
)) {
2193 // The length of the sequence is returned in count.
2194 *count
= PySequence_Length(source
);
2199 temp
= new wxPoint
[*count
];
2201 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2204 for (x
=0; x
<*count
; x
++) {
2205 // Get an item: try fast way first.
2207 o
= PySequence_Fast_GET_ITEM(source
, x
);
2210 o
= PySequence_GetItem(source
, x
);
2216 // Convert o to wxPoint.
2217 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2218 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2219 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2220 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2221 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2225 else if (wxPySwigInstance_Check(o
)) {
2227 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2232 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2233 o1
= PySequence_GetItem(o
, 0);
2234 o2
= PySequence_GetItem(o
, 1);
2235 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2259 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2263 //------------------------------
2266 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2267 if (!PyList_Check(source
)) {
2268 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2271 int count
= PyList_Size(source
);
2272 wxBitmap
** temp
= new wxBitmap
*[count
];
2274 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2277 for (int x
=0; x
<count
; x
++) {
2278 PyObject
* o
= PyList_GetItem(source
, x
);
2279 if (wxPySwigInstance_Check(o
)) {
2281 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2282 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2288 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2297 wxString
* wxString_LIST_helper(PyObject
* source
) {
2298 if (!PyList_Check(source
)) {
2299 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2302 int count
= PyList_Size(source
);
2303 wxString
* temp
= new wxString
[count
];
2305 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2308 for (int x
=0; x
<count
; x
++) {
2309 PyObject
* o
= PyList_GetItem(source
, x
);
2310 #if PYTHON_API_VERSION >= 1009
2311 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2312 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2316 if (! PyString_Check(o
)) {
2317 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2322 wxString
* pStr
= wxString_in_helper(o
);
2330 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2331 if (!PyList_Check(source
)) {
2332 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2335 int count
= PyList_Size(source
);
2336 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2338 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2341 for (int x
=0; x
<count
; x
++) {
2342 PyObject
* o
= PyList_GetItem(source
, x
);
2343 if (wxPySwigInstance_Check(o
)) {
2344 wxAcceleratorEntry
* ae
;
2345 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2346 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2351 else if (PyTuple_Check(o
)) {
2352 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2353 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2354 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2355 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2358 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2366 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2367 if (!PyList_Check(source
)) {
2368 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2371 int count
= PyList_Size(source
);
2372 wxPen
** temp
= new wxPen
*[count
];
2374 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2377 for (int x
=0; x
<count
; x
++) {
2378 PyObject
* o
= PyList_GetItem(source
, x
);
2379 if (wxPySwigInstance_Check(o
)) {
2381 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2383 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2390 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2398 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2399 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2402 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2406 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2407 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2410 o1
= PySequence_GetItem(source
, 0);
2411 o2
= PySequence_GetItem(source
, 1);
2414 *i1
= PyInt_AsLong(o1
);
2415 *i2
= PyInt_AsLong(o2
);
2425 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2426 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2427 PyObject
*o1
, *o2
, *o3
, *o4
;
2429 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2433 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2434 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2435 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2436 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2439 o1
= PySequence_GetItem(source
, 0);
2440 o2
= PySequence_GetItem(source
, 1);
2441 o3
= PySequence_GetItem(source
, 2);
2442 o4
= PySequence_GetItem(source
, 3);
2445 *i1
= PyInt_AsLong(o1
);
2446 *i2
= PyInt_AsLong(o2
);
2447 *i3
= PyInt_AsLong(o3
);
2448 *i4
= PyInt_AsLong(o4
);
2460 //----------------------------------------------------------------------
2462 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2466 if (wxPySwigInstance_Check(source
) &&
2467 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2471 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2477 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2479 if (source
== Py_None
) {
2480 **obj
= wxSize(-1,-1);
2483 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2487 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2489 if (source
== Py_None
) {
2490 **obj
= wxPoint(-1,-1);
2493 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2498 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2500 if (source
== Py_None
) {
2501 **obj
= wxRealPoint(-1,-1);
2505 // If source is an object instance then it may already be the right type
2506 if (wxPySwigInstance_Check(source
)) {
2508 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2513 // otherwise a 2-tuple of floats is expected
2514 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2515 PyObject
* o1
= PySequence_GetItem(source
, 0);
2516 PyObject
* o2
= PySequence_GetItem(source
, 1);
2517 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2522 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2529 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2535 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2537 if (source
== Py_None
) {
2538 **obj
= wxRect(-1,-1,-1,-1);
2542 // If source is an object instance then it may already be the right type
2543 if (wxPySwigInstance_Check(source
)) {
2545 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2550 // otherwise a 4-tuple of integers is expected
2551 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2552 PyObject
* o1
= PySequence_GetItem(source
, 0);
2553 PyObject
* o2
= PySequence_GetItem(source
, 1);
2554 PyObject
* o3
= PySequence_GetItem(source
, 2);
2555 PyObject
* o4
= PySequence_GetItem(source
, 3);
2556 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2557 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2564 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2565 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2574 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2580 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2582 if (source
== Py_None
) {
2583 **obj
= wxNullColour
;
2587 // If source is an object instance then it may already be the right type
2588 if (wxPySwigInstance_Check(source
)) {
2590 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2595 // otherwise check for a string
2596 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2597 wxString spec
= Py2wxString(source
);
2598 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2599 long red
, green
, blue
;
2600 red
= green
= blue
= 0;
2601 spec
.Mid(1,2).ToLong(&red
, 16);
2602 spec
.Mid(3,2).ToLong(&green
, 16);
2603 spec
.Mid(5,2).ToLong(&blue
, 16);
2605 **obj
= wxColour(red
, green
, blue
);
2608 else { // it's a colour name
2609 **obj
= wxColour(spec
);
2613 // last chance: 3-tuple of integers is expected
2614 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2615 PyObject
* o1
= PySequence_GetItem(source
, 0);
2616 PyObject
* o2
= PySequence_GetItem(source
, 1);
2617 PyObject
* o3
= PySequence_GetItem(source
, 2);
2618 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2624 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2632 PyErr_SetString(PyExc_TypeError
,
2633 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2638 bool wxColour_typecheck(PyObject
* source
) {
2640 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2643 if (PyString_Check(source
) || PyUnicode_Check(source
))
2651 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2653 if (source
== Py_None
) {
2654 **obj
= wxPoint2D(-1,-1);
2658 // If source is an object instance then it may already be the right type
2659 if (wxPySwigInstance_Check(source
)) {
2661 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2666 // otherwise a length-2 sequence of floats is expected
2667 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2668 PyObject
* o1
= PySequence_GetItem(source
, 0);
2669 PyObject
* o2
= PySequence_GetItem(source
, 1);
2670 // This should really check for floats, not numbers -- but that would break code.
2671 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2676 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2682 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2687 //----------------------------------------------------------------------
2689 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2691 PyObject
* list
= PyList_New(0);
2692 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2694 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2696 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2698 PyList_Append(list
, str
);
2705 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2707 PyObject
* list
= PyList_New(0);
2708 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2709 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2710 PyList_Append(list
, number
);
2717 //----------------------------------------------------------------------
2718 //----------------------------------------------------------------------