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 //----------------------------------------------------------------------
101 HINSTANCE hinstDLL
, // handle to DLL module
102 DWORD fdwReason
, // reason for calling function
103 LPVOID lpvReserved
// reserved
106 // If wxPython is embedded in another wxWidgets app then
107 // the instance has already been set.
108 if (! wxGetInstance())
109 wxSetInstance(hinstDLL
);
114 //----------------------------------------------------------------------
115 // Classes for implementing the wxp main application shell.
116 //----------------------------------------------------------------------
118 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
122 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
123 m_startupComplete
= false;
127 wxPyApp::~wxPyApp() {
131 // This one isn't acutally called... We fake it with _BootstrapApp
132 bool wxPyApp::OnInit() {
137 int wxPyApp::MainLoop() {
140 DeletePendingObjects();
141 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
143 if ( m_exitOnFrameDelete
== Later
) {
144 m_exitOnFrameDelete
= Yes
;
147 retval
= wxApp::MainLoop();
154 bool wxPyApp::OnInitGui() {
156 wxApp::OnInitGui(); // in this case always call the base class version
157 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
158 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
159 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
160 wxPyEndBlockThreads(blocked
);
165 int wxPyApp::OnExit() {
167 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
168 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
169 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
170 wxPyEndBlockThreads(blocked
);
171 wxApp::OnExit(); // in this case always call the base class version
177 void wxPyApp::OnAssert(const wxChar
*file
,
182 // if we're not fully initialized then just log the error
183 if (! m_startupComplete
) {
186 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
196 // If the OnAssert is overloaded in the Python class then call it...
198 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
199 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
200 PyObject
* fso
= wx2PyString(file
);
201 PyObject
* cso
= wx2PyString(file
);
204 mso
= wx2PyString(file
);
206 mso
= Py_None
; Py_INCREF(Py_None
);
208 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
213 wxPyEndBlockThreads(blocked
);
215 // ...otherwise do our own thing with it
218 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
221 // turn it into a Python exception?
222 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
225 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
232 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
233 PyObject
* s
= wx2PyString(buf
);
234 PyErr_SetObject(wxPyAssertionError
, s
);
236 wxPyEndBlockThreads(blocked
);
238 // Now when control returns to whatever API wrapper was called from
239 // Python it should detect that an exception is set and will return
240 // NULL, signalling the exception to Python.
243 // Send it to the normal log destination, but only if
244 // not _DIALOG because it will call this too
245 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
248 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
257 // do the normal wx assert dialog?
258 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
259 wxApp::OnAssert(file
, line
, cond
, msg
);
264 // For catching Apple Events
265 void wxPyApp::MacOpenFile(const wxString
&fileName
)
267 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
268 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
269 PyObject
* s
= wx2PyString(fileName
);
270 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
273 wxPyEndBlockThreads(blocked
);
276 void wxPyApp::MacPrintFile(const wxString
&fileName
)
278 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
279 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
280 PyObject
* s
= wx2PyString(fileName
);
281 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
284 wxPyEndBlockThreads(blocked
);
287 void wxPyApp::MacNewFile()
289 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
290 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
291 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
292 wxPyEndBlockThreads(blocked
);
295 void wxPyApp::MacReopenApp()
297 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
298 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
299 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
300 wxPyEndBlockThreads(blocked
);
305 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
307 return s_macSupportPCMenuShortcuts
;
314 long wxPyApp::GetMacAboutMenuItemId() {
316 return s_macAboutMenuItemId
;
323 long wxPyApp::GetMacPreferencesMenuItemId() {
325 return s_macPreferencesMenuItemId
;
332 long wxPyApp::GetMacExitMenuItemId() {
334 return s_macExitMenuItemId
;
341 wxString
wxPyApp::GetMacHelpMenuTitleName() {
343 return s_macHelpMenuTitleName
;
345 return wxEmptyString
;
350 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
352 s_macSupportPCMenuShortcuts
= val
;
357 void wxPyApp::SetMacAboutMenuItemId(long val
) {
359 s_macAboutMenuItemId
= val
;
364 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
366 s_macPreferencesMenuItemId
= val
;
371 void wxPyApp::SetMacExitMenuItemId(long val
) {
373 s_macExitMenuItemId
= val
;
378 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
380 s_macHelpMenuTitleName
= val
;
385 // This finishes the initialization of wxWindows and then calls the OnInit
386 // that should be present in the derived (Python) class.
387 void wxPyApp::_BootstrapApp()
389 static bool haveInitialized
= false;
392 PyObject
* retval
= NULL
;
393 PyObject
* pyint
= NULL
;
396 // Only initialize wxWidgets once
397 if (! haveInitialized
) {
399 // Get any command-line args passed to this program from the sys module
402 blocked
= wxPyBeginBlockThreads();
404 PyObject
* sysargv
= PySys_GetObject("argv");
405 PyObject
* executable
= PySys_GetObject("executable");
407 if (sysargv
!= NULL
&& executable
!= NULL
) {
408 argc
= PyList_Size(sysargv
) + 1;
409 argv
= new char*[argc
+1];
410 argv
[0] = PyString_AsString(executable
);
412 for(x
=1; x
<argc
; x
++) {
413 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
414 argv
[x
] = PyString_AsString(pyArg
);
418 wxPyEndBlockThreads(blocked
);
420 // Initialize wxWidgets
421 result
= wxEntryStart(argc
, argv
);
424 blocked
= wxPyBeginBlockThreads();
426 PyErr_SetString(PyExc_SystemError
,
427 "wxEntryStart failed, unable to initialize wxWidgets!"
429 " (Is DISPLAY set properly?)"
435 // On wxGTK the locale will be changed to match the system settings,
436 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
437 // for the floating point conversions and such to work right.
438 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
439 setlocale(LC_NUMERIC
, "C");
442 wxSystemOptions::SetOptionInt(wxT("mac.textcontrol-use-mlte"), 1);
444 // The stock objects were all NULL when they were loaded into
445 // SWIG generated proxies, so re-init those now...
446 wxPy_ReinitStockObjects(3);
448 wxPyEndBlockThreads(blocked
);
449 haveInitialized
= true;
452 // It's now ok to generate exceptions for assertion errors.
453 wxPythonApp
->SetStartupComplete(true);
455 // Call the Python wxApp's OnInit function
456 blocked
= wxPyBeginBlockThreads();
457 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
459 PyObject
* method
= m_myInst
.GetLastFound();
460 PyObject
* argTuple
= PyTuple_New(0);
461 retval
= PyEval_CallObject(method
, argTuple
);
467 pyint
= PyNumber_Int(retval
);
469 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
472 result
= PyInt_AS_LONG(pyint
);
475 // Is it okay if there is no OnInit? Probably so...
480 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
487 wxPyEndBlockThreads(blocked
);
490 //---------------------------------------------------------------------
491 //----------------------------------------------------------------------
495 static char* wxPyCopyCString(const wxChar
* src
)
497 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
498 size_t len
= strlen(buff
);
499 char* dest
= new char[len
+1];
505 static char* wxPyCopyCString(const char* src
) // we need a char version too
507 size_t len
= strlen(src
);
508 char* dest
= new char[len
+1];
514 static wxChar
* wxPyCopyWString(const char *src
)
516 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
517 wxString
str(src
, *wxConvCurrent
);
518 return copystring(str
);
522 static wxChar
* wxPyCopyWString(const wxChar
*src
)
524 return copystring(src
);
530 inline const char* dropwx(const char* name
) {
531 if (name
[0] == 'w' && name
[1] == 'x')
537 //----------------------------------------------------------------------
539 // This function is called when the wx._core_ module is imported to do some
540 // initial setup. (Before there is a wxApp object.) The rest happens in
541 // wxPyApp::_BootstrapApp
542 void __wxPyPreStart(PyObject
* moduleDict
)
546 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
547 // | _CRTDBG_CHECK_ALWAYS_DF
548 // | _CRTDBG_DELAY_FREE_MEM_DF
552 #ifdef WXP_WITH_THREAD
553 #if wxPyUSE_GIL_STATE
554 PyEval_InitThreads();
556 PyEval_InitThreads();
557 wxPyTStates
= new wxPyThreadStateArray
;
558 wxPyTMutex
= new wxMutex
;
560 // Save the current (main) thread state in our array
561 PyThreadState
* tstate
= wxPyBeginAllowThreads();
562 wxPyEndAllowThreads(tstate
);
566 // Ensure that the build options in the DLL (or whatever) match this build
567 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
569 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
570 wxPy_ReinitStockObjects(1);
572 wxInitAllImageHandlers();
577 void __wxPyCleanup() {
578 wxPyDoingCleanup
= true;
580 wxPyDoCleanup
= false;
583 #ifdef WXP_WITH_THREAD
584 #if !wxPyUSE_GIL_STATE
587 wxPyTStates
->Empty();
595 // Save a reference to the dictionary of the wx._core module, and inject
596 // a few more things into it.
597 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
600 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
603 if (!PyDict_Check(wxPython_dict
)) {
604 PyErr_SetString(PyExc_TypeError
,
605 "_wxPySetDictionary must have dictionary object!");
609 if (! wxPyPtrTypeMap
)
610 wxPyPtrTypeMap
= PyDict_New();
611 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
613 // Create an exception object to use for wxASSERTions
614 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
615 PyExc_AssertionError
, NULL
);
616 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
618 // Create an exception object to use when the app object hasn't been created yet
619 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
620 PyExc_RuntimeError
, NULL
);
621 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
626 #define wxPlatform "__WXMOTIF__"
627 #define wxPlatName "wxMotif"
630 #define wxPlatform "__WXX11__"
631 #define wxPlatName "wxX11"
634 #define wxPlatform "__WXGTK__"
635 #define wxPlatName "wxGTK"
638 #define wxPlatform "__WXMSW__"
639 #define wxPlatName "wxMSW"
642 #define wxPlatform "__WXMAC__"
643 #define wxPlatName "wxMac"
652 // These should be deprecated in favor of the PlatformInfo tuple built below...
653 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
654 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
655 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
657 // Make a tuple of strings that gives more info about the platform.
658 PyObject
* PlatInfo
= PyList_New(0);
661 #define _AddInfoString(st) \
662 obj = PyString_FromString(st); \
663 PyList_Append(PlatInfo, obj); \
666 _AddInfoString(wxPlatform
);
667 _AddInfoString(wxPlatName
);
669 _AddInfoString("unicode");
671 _AddInfoString("ansi");
675 _AddInfoString("gtk2");
677 _AddInfoString("gtk1");
681 _AddInfoString("wx-assertions-on");
683 _AddInfoString("wx-assertions-off");
686 #undef _AddInfoString
688 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
690 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
696 //---------------------------------------------------------------------------
698 // Python's PyInstance_Check does not return True for instances of new-style
699 // classes. This should get close enough for both new and old classes but I
700 // should re-evaluate the need for doing instance checks...
701 bool wxPyInstance_Check(PyObject
* obj
) {
702 return PyObject_HasAttrString(obj
, "__class__") != 0;
706 // This one checks if the object is an instance of a SWIG proxy class (it has
707 // a .this attribute)
708 bool wxPySwigInstance_Check(PyObject
* obj
) {
709 return PyObject_HasAttrString(obj
, "this") != 0;
712 //---------------------------------------------------------------------------
714 // The stock objects are no longer created when the wx._core_ module is
715 // imported, but only after the app object has been created. The
716 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
717 // objects though various stages of evolution:
719 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
720 // object will be created (otherwise SWIG will just use None.)
722 // pass 2: After the module has been imported and the python proxys have
723 // been created, then set the __class__ to be _wxPyUnbornObject so
724 // it will catch any access to the object and will raise an exception.
726 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
730 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
732 wxPy_ReinitStockObjects(2);
737 static void rsoPass2(const char* name
)
739 static PyObject
* unbornObjectClass
= NULL
;
742 if (unbornObjectClass
== NULL
) {
743 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
744 Py_INCREF(unbornObjectClass
);
747 // Find the object instance
748 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
749 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
750 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
753 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
757 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
763 // Find the object instance
764 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
765 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
766 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
768 // Find the class object and put it back in the instance
769 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
770 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
771 PyObject_SetAttrString(obj
, "__class__", classobj
);
773 // Rebuild the .this swigified pointer with the new value of the C++ pointer
774 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
775 PyObject_SetAttrString(obj
, "this", ptrobj
);
781 void wxPy_ReinitStockObjects(int pass
)
784 // If there is already an App object then wxPython is probably embedded in
785 // a wx C++ application, so there is no need to do all this.
786 static bool embedded
= false;
787 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
791 if (pass
== 3 && embedded
)
795 #define REINITOBJ(name, classname) \
796 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
797 else if (pass == 2) { rsoPass2(#name); } \
798 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
801 #define REINITOBJ2(name, classname) \
803 else if (pass == 2) { rsoPass2(#name); } \
804 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
807 REINITOBJ(wxNORMAL_FONT
, wxFont
);
808 REINITOBJ(wxSMALL_FONT
, wxFont
);
809 REINITOBJ(wxITALIC_FONT
, wxFont
);
810 REINITOBJ(wxSWISS_FONT
, wxFont
);
812 REINITOBJ(wxRED_PEN
, wxPen
);
813 REINITOBJ(wxCYAN_PEN
, wxPen
);
814 REINITOBJ(wxGREEN_PEN
, wxPen
);
815 REINITOBJ(wxBLACK_PEN
, wxPen
);
816 REINITOBJ(wxWHITE_PEN
, wxPen
);
817 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
818 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
819 REINITOBJ(wxGREY_PEN
, wxPen
);
820 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
821 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
823 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
824 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
825 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
826 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
827 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
828 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
829 REINITOBJ(wxRED_BRUSH
, wxBrush
);
830 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
831 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
832 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
834 REINITOBJ(wxBLACK
, wxColour
);
835 REINITOBJ(wxWHITE
, wxColour
);
836 REINITOBJ(wxRED
, wxColour
);
837 REINITOBJ(wxBLUE
, wxColour
);
838 REINITOBJ(wxGREEN
, wxColour
);
839 REINITOBJ(wxCYAN
, wxColour
);
840 REINITOBJ(wxLIGHT_GREY
, wxColour
);
842 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
843 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
844 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
846 REINITOBJ2(wxNullBitmap
, wxBitmap
);
847 REINITOBJ2(wxNullIcon
, wxIcon
);
848 REINITOBJ2(wxNullCursor
, wxCursor
);
849 REINITOBJ2(wxNullPen
, wxPen
);
850 REINITOBJ2(wxNullBrush
, wxBrush
);
851 REINITOBJ2(wxNullPalette
, wxPalette
);
852 REINITOBJ2(wxNullFont
, wxFont
);
853 REINITOBJ2(wxNullColour
, wxColour
);
855 REINITOBJ(wxTheFontList
, wxFontList
);
856 REINITOBJ(wxThePenList
, wxPenList
);
857 REINITOBJ(wxTheBrushList
, wxBrushList
);
858 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
861 REINITOBJ2(wxDefaultValidator
, wxValidator
);
862 REINITOBJ2(wxNullImage
, wxImage
);
863 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
869 //---------------------------------------------------------------------------
871 // Check for existence of a wxApp, setting an exception if there isn't one.
872 // This doesn't need to aquire the GIL because it should only be called from
873 // an %exception before the lock is released.
875 bool wxPyCheckForApp() {
876 if (wxTheApp
!= NULL
)
879 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
884 //---------------------------------------------------------------------------
886 void wxPyUserData_dtor(wxPyUserData
* self
) {
887 if (! wxPyDoingCleanup
) {
888 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
889 Py_DECREF(self
->m_obj
);
891 wxPyEndBlockThreads(blocked
);
896 void wxPyClientData_dtor(wxPyClientData
* self
) {
897 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
898 // may have already garbage collected the object...
899 if (self
->m_incRef
) {
900 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
901 Py_DECREF(self
->m_obj
);
902 wxPyEndBlockThreads(blocked
);
910 // This is called when an OOR controled object is being destroyed. Although
911 // the C++ object is going away there is no way to force the Python object
912 // (and all references to it) to die too. This causes problems (crashes) in
913 // wxPython when a python shadow object attempts to call a C++ method using
914 // the now bogus pointer... So to try and prevent this we'll do a little black
915 // magic and change the class of the python instance to a class that will
916 // raise an exception for any attempt to call methods with it. See
917 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
918 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
920 static PyObject
* deadObjectClass
= NULL
;
922 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
923 if (deadObjectClass
== NULL
) {
924 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
925 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
926 // will lead to a deadlock when it tries to aquire the GIL again.
927 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
928 Py_INCREF(deadObjectClass
);
932 // Only if there is more than one reference to the object and we are
933 // holding the OOR reference:
934 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
935 // bool isInstance = wxPyInstance_Check(self->m_obj);
937 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
939 // Call __del__, if there is one.
940 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
942 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
946 if (PyErr_Occurred())
947 PyErr_Clear(); // just ignore it for now
950 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
952 // Clear the instance's dictionary
955 // put the name of the old class into the instance, and then reset the
956 // class to be the dead class.
957 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
958 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
959 PyDict_SetItemString(dict
, "_name", name
);
960 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
961 //Py_INCREF(deadObjectClass);
967 // m_obj is DECREF'd in the base class dtor...
968 wxPyEndBlockThreads(blocked
);
972 //---------------------------------------------------------------------------
973 // Stuff used by OOR to find the right wxPython class type to return and to
977 // The pointer type map is used when the "pointer" type name generated by SWIG
978 // is not the same as the shadow class name, for example wxPyTreeCtrl
979 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
980 // so we'll just make it a Python dictionary in the wx module's namespace.
981 // (See __wxSetDictionary)
982 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
983 if (! wxPyPtrTypeMap
)
984 wxPyPtrTypeMap
= PyDict_New();
985 PyDict_SetItemString(wxPyPtrTypeMap
,
987 PyString_FromString((char*)ptrName
));
993 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
994 PyObject
* target
= NULL
;
995 bool isEvtHandler
= false;
998 // If it's derived from wxEvtHandler then there may
999 // already be a pointer to a Python object that we can use
1001 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
1002 isEvtHandler
= true;
1003 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
1004 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
1006 target
= data
->m_obj
;
1013 // Otherwise make it the old fashioned way by making a new shadow
1014 // object and putting this pointer in it. Look up the class
1015 // heirarchy until we find a class name that is located in the
1017 const wxClassInfo
* info
= source
->GetClassInfo();
1018 wxString name
= info
->GetClassName();
1019 bool exists
= wxPyCheckSwigType(name
);
1020 while (info
&& !exists
) {
1021 info
= info
->GetBaseClass1();
1022 name
= info
->GetClassName();
1023 exists
= wxPyCheckSwigType(name
);
1026 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1027 if (target
&& isEvtHandler
)
1028 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1030 wxString
msg(wxT("wxPython class not found for "));
1031 msg
+= source
->GetClassInfo()->GetClassName();
1032 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1036 } else { // source was NULL so return None.
1037 Py_INCREF(Py_None
); target
= Py_None
;
1043 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1044 PyObject
* target
= NULL
;
1046 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1047 // If it's derived from wxSizer then there may already be a pointer to
1048 // a Python object that we can use in the OOR data.
1049 wxSizer
* sz
= (wxSizer
*)source
;
1050 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1052 target
= data
->m_obj
;
1058 target
= wxPyMake_wxObject(source
, setThisOwn
, false);
1059 if (target
!= Py_None
)
1060 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1066 //---------------------------------------------------------------------------
1069 #ifdef WXP_WITH_THREAD
1070 #if !wxPyUSE_GIL_STATE
1073 unsigned long wxPyGetCurrentThreadId() {
1074 return wxThread::GetCurrentId();
1077 static wxPyThreadState gs_shutdownTState
;
1080 wxPyThreadState
* wxPyGetThreadState() {
1081 if (wxPyTMutex
== NULL
) // Python is shutting down...
1082 return &gs_shutdownTState
;
1084 unsigned long ctid
= wxPyGetCurrentThreadId();
1085 wxPyThreadState
* tstate
= NULL
;
1088 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1089 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1090 if (info
.tid
== ctid
) {
1095 wxPyTMutex
->Unlock();
1096 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1102 void wxPySaveThreadState(PyThreadState
* tstate
) {
1103 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1104 gs_shutdownTState
.tstate
= tstate
;
1107 unsigned long ctid
= wxPyGetCurrentThreadId();
1109 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1110 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1111 if (info
.tid
== ctid
) {
1113 if (info
.tstate
!= tstate
)
1114 wxLogMessage("*** tstate mismatch!???");
1116 info
.tstate
= tstate
; // allow for transient tstates
1117 // Normally it will never change, but apparently COM callbacks
1118 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1119 // tstate which will then be garbage the next time we try to use
1122 wxPyTMutex
->Unlock();
1126 // not found, so add it...
1127 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1128 wxPyTMutex
->Unlock();
1136 // Calls from Python to wxWindows code are wrapped in calls to these
1139 PyThreadState
* wxPyBeginAllowThreads() {
1140 #ifdef WXP_WITH_THREAD
1141 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1142 #if !wxPyUSE_GIL_STATE
1143 wxPySaveThreadState(saved
);
1151 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1152 #ifdef WXP_WITH_THREAD
1153 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1159 // Calls from wxWindows back to Python code, or even any PyObject
1160 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1162 wxPyBlock_t
wxPyBeginBlockThreads() {
1163 #ifdef WXP_WITH_THREAD
1164 #if wxPyUSE_GIL_STATE
1165 PyGILState_STATE state
= PyGILState_Ensure();
1168 PyThreadState
*current
= _PyThreadState_Current
;
1170 // Only block if there wasn't already a tstate, or if the current one is
1171 // not the one we are wanting to change to. This should prevent deadlock
1172 // if there are nested calls to wxPyBeginBlockThreads
1173 wxPyBlock_t blocked
= false;
1174 wxPyThreadState
* tstate
= wxPyGetThreadState();
1175 if (current
!= tstate
->tstate
) {
1176 PyEval_RestoreThread(tstate
->tstate
);
1187 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1188 #ifdef WXP_WITH_THREAD
1189 #if wxPyUSE_GIL_STATE
1190 PyGILState_Release(blocked
);
1192 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1193 // The value of blocked passed in needs to be the same as that returned
1194 // from wxPyBeginBlockThreads at the same nesting level.
1196 PyEval_SaveThread();
1203 //---------------------------------------------------------------------------
1204 // wxPyInputStream and wxPyCBInputStream methods
1207 void wxPyInputStream::close() {
1208 /* do nothing for now */
1211 void wxPyInputStream::flush() {
1212 /* do nothing for now */
1215 bool wxPyInputStream::eof() {
1217 return m_wxis
->Eof();
1222 wxPyInputStream::~wxPyInputStream() {
1230 PyObject
* wxPyInputStream::read(int size
) {
1231 PyObject
* obj
= NULL
;
1233 const int BUFSIZE
= 1024;
1235 // check if we have a real wxInputStream to work with
1237 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1238 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1239 wxPyEndBlockThreads(blocked
);
1244 // read while bytes are available on the stream
1245 while ( m_wxis
->CanRead() ) {
1246 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1247 buf
.UngetAppendBuf(m_wxis
->LastRead());
1250 } else { // Read only size number of characters
1251 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1252 buf
.UngetWriteBuf(m_wxis
->LastRead());
1256 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1257 wxStreamError err
= m_wxis
->GetLastError();
1258 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1259 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1262 // We use only strings for the streams, not unicode
1263 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1265 wxPyEndBlockThreads(blocked
);
1270 PyObject
* wxPyInputStream::readline(int size
) {
1271 PyObject
* obj
= NULL
;
1276 // check if we have a real wxInputStream to work with
1278 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1279 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1280 wxPyEndBlockThreads(blocked
);
1284 // read until \n or byte limit reached
1285 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1286 ch
= m_wxis
->GetC();
1291 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1292 wxStreamError err
= m_wxis
->GetLastError();
1293 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1294 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1297 // We use only strings for the streams, not unicode
1298 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1300 wxPyEndBlockThreads(blocked
);
1305 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1308 // check if we have a real wxInputStream to work with
1310 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1311 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1312 wxPyEndBlockThreads(blocked
);
1317 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1318 pylist
= PyList_New(0);
1319 wxPyEndBlockThreads(blocked
);
1322 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1324 wxPyEndBlockThreads(blocked
);
1328 // read sizehint bytes or until EOF
1330 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1331 PyObject
* s
= this->readline();
1333 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1335 wxPyEndBlockThreads(blocked
);
1338 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1339 PyList_Append(pylist
, s
);
1340 i
+= PyString_Size(s
);
1341 wxPyEndBlockThreads(blocked
);
1345 wxStreamError err
= m_wxis
->GetLastError();
1346 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1347 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1349 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1350 wxPyEndBlockThreads(blocked
);
1358 void wxPyInputStream::seek(int offset
, int whence
) {
1360 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1363 int wxPyInputStream::tell(){
1365 return m_wxis
->TellI();
1372 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1373 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1376 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1378 m_read
= other
.m_read
;
1379 m_seek
= other
.m_seek
;
1380 m_tell
= other
.m_tell
;
1381 m_block
= other
.m_block
;
1388 wxPyCBInputStream::~wxPyCBInputStream() {
1389 wxPyBlock_t blocked
;
1390 if (m_block
) blocked
= wxPyBeginBlockThreads();
1394 if (m_block
) wxPyEndBlockThreads(blocked
);
1398 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1399 wxPyBlock_t blocked
;
1400 if (block
) blocked
= wxPyBeginBlockThreads();
1402 PyObject
* read
= getMethod(py
, "read");
1403 PyObject
* seek
= getMethod(py
, "seek");
1404 PyObject
* tell
= getMethod(py
, "tell");
1407 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1411 if (block
) wxPyEndBlockThreads(blocked
);
1415 if (block
) wxPyEndBlockThreads(blocked
);
1416 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1420 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1421 return wxPyCBInputStream::create(py
, block
);
1424 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1425 return new wxPyCBInputStream(*other
);
1428 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1429 if (!PyObject_HasAttrString(py
, name
))
1431 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1432 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1440 wxFileOffset
wxPyCBInputStream::GetLength() const {
1441 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1442 if (m_seek
&& m_tell
) {
1443 wxFileOffset temp
= self
->OnSysTell();
1444 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1445 self
->OnSysSeek(temp
, wxFromStart
);
1449 return wxInvalidOffset
;
1453 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1457 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1458 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1459 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1463 if ((result
!= NULL
) && PyString_Check(result
)) {
1464 o
= PyString_Size(result
);
1466 m_lasterror
= wxSTREAM_EOF
;
1469 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1474 m_lasterror
= wxSTREAM_READ_ERROR
;
1475 wxPyEndBlockThreads(blocked
);
1479 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1480 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1485 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1486 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1487 PyObject
* arglist
= PyTuple_New(2);
1489 if (sizeof(wxFileOffset
) > sizeof(long))
1490 // wxFileOffset is a 64-bit value...
1491 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1493 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1495 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1498 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1501 wxPyEndBlockThreads(blocked
);
1506 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1507 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1508 PyObject
* arglist
= Py_BuildValue("()");
1509 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1512 if (result
!= NULL
) {
1513 if (PyLong_Check(result
))
1514 o
= PyLong_AsLongLong(result
);
1516 o
= PyInt_AsLong(result
);
1519 wxPyEndBlockThreads(blocked
);
1523 //----------------------------------------------------------------------
1525 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1527 wxPyCallback::wxPyCallback(PyObject
* func
) {
1532 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1533 m_func
= other
.m_func
;
1537 wxPyCallback::~wxPyCallback() {
1538 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1540 wxPyEndBlockThreads(blocked
);
1544 #define wxPy_PRECALLINIT "_preCallInit"
1545 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1547 // This function is used for all events destined for Python event handlers.
1548 void wxPyCallback::EventThunker(wxEvent
& event
) {
1549 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1550 PyObject
* func
= cb
->m_func
;
1554 bool checkSkip
= false;
1556 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1557 wxString className
= event
.GetClassInfo()->GetClassName();
1559 // If the event is one of these types then pass the original
1560 // event object instead of the one passed to us.
1561 if ( className
== wxT("wxPyEvent") ) {
1562 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1563 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1565 else if ( className
== wxT("wxPyCommandEvent") ) {
1566 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1567 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1570 arg
= wxPyConstructObject((void*)&event
, className
);
1576 // "intern" the pre/post method names to speed up the HasAttr
1577 static PyObject
* s_preName
= NULL
;
1578 static PyObject
* s_postName
= NULL
;
1579 if (s_preName
== NULL
) {
1580 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1581 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1584 // Check if the event object needs some preinitialization
1585 if (PyObject_HasAttr(arg
, s_preName
)) {
1586 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1588 Py_DECREF(result
); // result is ignored, but we still need to decref it
1589 PyErr_Clear(); // Just in case...
1595 // Call the event handler, passing the event object
1596 tuple
= PyTuple_New(1);
1597 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1598 result
= PyEval_CallObject(func
, tuple
);
1600 Py_DECREF(result
); // result is ignored, but we still need to decref it
1601 PyErr_Clear(); // Just in case...
1606 // Check if the event object needs some post cleanup
1607 if (PyObject_HasAttr(arg
, s_postName
)) {
1608 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1610 Py_DECREF(result
); // result is ignored, but we still need to decref it
1611 PyErr_Clear(); // Just in case...
1618 // if the event object was one of our special types and
1619 // it had been cloned, then we need to extract the Skipped
1620 // value from the original and set it in the clone.
1621 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1623 event
.Skip(PyInt_AsLong(result
));
1631 wxPyEndBlockThreads(blocked
);
1635 //----------------------------------------------------------------------
1637 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1639 m_self
= other
.m_self
;
1640 m_class
= other
.m_class
;
1648 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1659 #if PYTHON_API_VERSION >= 1011
1661 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1662 // in which the method was defined. Starting with 2.2 it returns
1663 // "class that asked for the method" which seems totally bogus to me
1664 // but apprently it fixes some obscure problem waiting to happen in
1665 // Python. Since the API was not documented Guido and the gang felt
1666 // safe in changing it. Needless to say that totally screwed up the
1667 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1668 // code to find the class where the method is actually defined...
1671 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1675 if (PyType_Check(klass
)) { // new style classes
1676 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1677 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1678 PyObject
*mro
, *res
, *base
, *dict
;
1679 /* Look in tp_dict of types in MRO */
1681 assert(PyTuple_Check(mro
));
1682 n
= PyTuple_GET_SIZE(mro
);
1683 for (i
= 0; i
< n
; i
++) {
1684 base
= PyTuple_GET_ITEM(mro
, i
);
1685 if (PyClass_Check(base
))
1686 dict
= ((PyClassObject
*)base
)->cl_dict
;
1688 assert(PyType_Check(base
));
1689 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1691 assert(dict
&& PyDict_Check(dict
));
1692 res
= PyDict_GetItem(dict
, name
);
1699 else if (PyClass_Check(klass
)) { // old style classes
1700 // This code is borrowed/adapted from class_lookup in classobject.c
1701 PyClassObject
* cp
= (PyClassObject
*)klass
;
1702 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1703 if (value
!= NULL
) {
1704 return (PyObject
*)cp
;
1706 n
= PyTuple_Size(cp
->cl_bases
);
1707 for (i
= 0; i
< n
; i
++) {
1708 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1709 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1721 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1723 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1725 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1727 #else // 2.2 and after, the hard way...
1729 PyObject
* nameo
= PyString_FromString(name
);
1730 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1738 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1739 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1740 self
->m_lastFound
= NULL
;
1742 // If the object (m_self) has an attibute of the given name...
1743 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1744 PyObject
*method
, *klass
;
1745 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1747 // ...and if that attribute is a method, and if that method's class is
1748 // not from a base class...
1749 if (PyMethod_Check(method
) &&
1750 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1751 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1753 // ...then we'll save a pointer to the method so callCallback can call it.
1754 self
->m_lastFound
= method
;
1760 return m_lastFound
!= NULL
;
1764 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1768 result
= callCallbackObj(argTuple
);
1769 if (result
) { // Assumes an integer return type...
1770 retval
= PyInt_AsLong(result
);
1772 PyErr_Clear(); // forget about it if it's not...
1777 // Invoke the Python callable object, returning the raw PyObject return
1778 // value. Caller should DECREF the return value and also manage the GIL.
1779 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1782 // Save a copy of the pointer in case the callback generates another
1783 // callback. In that case m_lastFound will have a different value when
1784 // it gets back here...
1785 PyObject
* method
= m_lastFound
;
1787 result
= PyEval_CallObject(method
, argTuple
);
1788 Py_DECREF(argTuple
);
1797 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1798 cbh
.setSelf(self
, klass
, incref
);
1801 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1802 return cbh
.findCallback(name
);
1805 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1806 return cbh
.callCallback(argTuple
);
1809 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1810 return cbh
.callCallbackObj(argTuple
);
1814 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1815 if (cbh
->m_incRef
) {
1816 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1817 Py_XDECREF(cbh
->m_self
);
1818 Py_XDECREF(cbh
->m_class
);
1819 wxPyEndBlockThreads(blocked
);
1823 //---------------------------------------------------------------------------
1824 //---------------------------------------------------------------------------
1825 // These event classes can be derived from in Python and passed through the event
1826 // system without losing anything. They do this by keeping a reference to
1827 // themselves and some special case handling in wxPyCallback::EventThunker.
1830 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1831 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1832 //Py_INCREF(m_self); // circular loops...
1836 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1837 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1840 wxPyEndBlockThreads(blocked
);
1843 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1844 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1852 wxPyEndBlockThreads(blocked
);
1855 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1861 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1862 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1865 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1866 : wxEvent(winid
, commandType
) {
1870 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1873 SetSelf(evt
.m_self
, true);
1877 wxPyEvent::~wxPyEvent() {
1881 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1882 : wxCommandEvent(commandType
, id
) {
1886 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1887 : wxCommandEvent(evt
)
1889 SetSelf(evt
.m_self
, true);
1893 wxPyCommandEvent::~wxPyCommandEvent() {
1900 //---------------------------------------------------------------------------
1901 //---------------------------------------------------------------------------
1902 // Convert a wxList to a Python List, only works for lists of wxObjects
1904 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1905 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1909 wxNode
* node
= list
->GetFirst();
1911 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1912 pyList
= PyList_New(0);
1914 wxObj
= node
->GetData();
1915 pyObj
= wxPyMake_wxObject(wxObj
,false);
1916 PyList_Append(pyList
, pyObj
);
1917 node
= node
->GetNext();
1919 wxPyEndBlockThreads(blocked
);
1923 //----------------------------------------------------------------------
1925 long wxPyGetWinHandle(wxWindow
* win
) {
1928 return (long)win
->GetHandle();
1931 #if defined(__WXGTK__) || defined(__WXX11)
1932 return (long)GetXWindow(win
);
1936 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1937 return (long)win
->GetHandle();
1943 //----------------------------------------------------------------------
1944 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1945 // included in every file over and over again...
1947 wxString
* wxString_in_helper(PyObject
* source
) {
1948 wxString
* target
= NULL
;
1950 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1951 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1955 PyObject
* uni
= source
;
1956 if (PyString_Check(source
)) {
1957 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1958 if (PyErr_Occurred()) return NULL
;
1960 target
= new wxString();
1961 size_t len
= PyUnicode_GET_SIZE(uni
);
1963 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1964 target
->UngetWriteBuf(len
);
1967 if (PyString_Check(source
))
1970 // Convert to a string object if it isn't already, then to wxString
1971 PyObject
* str
= source
;
1972 if (PyUnicode_Check(source
)) {
1973 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1974 if (PyErr_Occurred()) return NULL
;
1976 else if (!PyString_Check(source
)) {
1977 str
= PyObject_Str(source
);
1978 if (PyErr_Occurred()) return NULL
;
1980 char* tmpPtr
; int tmpSize
;
1981 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1982 target
= new wxString(tmpPtr
, tmpSize
);
1984 if (!PyString_Check(source
))
1986 #endif // wxUSE_UNICODE
1992 // Similar to above except doesn't use "new" and doesn't set an exception
1993 wxString
Py2wxString(PyObject
* source
)
1998 // Convert to a unicode object, if not already, then to a wxString
1999 PyObject
* uni
= source
;
2000 if (!PyUnicode_Check(source
)) {
2001 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
2002 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2004 size_t len
= PyUnicode_GET_SIZE(uni
);
2006 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
2007 target
.UngetWriteBuf();
2010 if (!PyUnicode_Check(source
))
2013 // Convert to a string object if it isn't already, then to wxString
2014 PyObject
* str
= source
;
2015 if (PyUnicode_Check(source
)) {
2016 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
2017 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2019 else if (!PyString_Check(source
)) {
2020 str
= PyObject_Str(source
);
2021 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2023 char* tmpPtr
; int tmpSize
;
2024 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
2025 target
= wxString(tmpPtr
, tmpSize
);
2027 if (!PyString_Check(source
))
2029 #endif // wxUSE_UNICODE
2035 // Make either a Python String or Unicode object, depending on build mode
2036 PyObject
* wx2PyString(const wxString
& src
)
2040 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
2042 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
2049 void wxSetDefaultPyEncoding(const char* encoding
)
2051 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
2054 const char* wxGetDefaultPyEncoding()
2056 return wxPyDefaultEncoding
;
2059 //----------------------------------------------------------------------
2062 byte
* byte_LIST_helper(PyObject
* source
) {
2063 if (!PyList_Check(source
)) {
2064 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2067 int count
= PyList_Size(source
);
2068 byte
* temp
= new byte
[count
];
2070 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2073 for (int x
=0; x
<count
; x
++) {
2074 PyObject
* o
= PyList_GetItem(source
, x
);
2075 if (! PyInt_Check(o
)) {
2076 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2079 temp
[x
] = (byte
)PyInt_AsLong(o
);
2085 int* int_LIST_helper(PyObject
* source
) {
2086 if (!PyList_Check(source
)) {
2087 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2090 int count
= PyList_Size(source
);
2091 int* temp
= new int[count
];
2093 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2096 for (int x
=0; x
<count
; x
++) {
2097 PyObject
* o
= PyList_GetItem(source
, x
);
2098 if (! PyInt_Check(o
)) {
2099 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2102 temp
[x
] = PyInt_AsLong(o
);
2108 long* long_LIST_helper(PyObject
* source
) {
2109 if (!PyList_Check(source
)) {
2110 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2113 int count
= PyList_Size(source
);
2114 long* temp
= new long[count
];
2116 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2119 for (int x
=0; x
<count
; x
++) {
2120 PyObject
* o
= PyList_GetItem(source
, x
);
2121 if (! PyInt_Check(o
)) {
2122 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2125 temp
[x
] = PyInt_AsLong(o
);
2131 char** string_LIST_helper(PyObject
* source
) {
2132 if (!PyList_Check(source
)) {
2133 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2136 int count
= PyList_Size(source
);
2137 char** temp
= new char*[count
];
2139 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2142 for (int x
=0; x
<count
; x
++) {
2143 PyObject
* o
= PyList_GetItem(source
, x
);
2144 if (! PyString_Check(o
)) {
2145 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2148 temp
[x
] = PyString_AsString(o
);
2153 //--------------------------------
2154 // Part of patch from Tim Hochberg
2155 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2156 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2157 point
->x
= PyInt_AS_LONG(o1
);
2158 point
->y
= PyInt_AS_LONG(o2
);
2161 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2162 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2163 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2166 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2167 // Disallow instances because they can cause havok
2170 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2171 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2172 point
->x
= PyInt_AsLong(o1
);
2173 point
->y
= PyInt_AsLong(o2
);
2180 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2181 // Putting all of the declarations here allows
2182 // us to put the error handling all in one place.
2185 PyObject
*o
, *o1
, *o2
;
2186 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2188 if (!PySequence_Check(source
)) {
2192 // The length of the sequence is returned in count.
2193 *count
= PySequence_Length(source
);
2198 temp
= new wxPoint
[*count
];
2200 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2203 for (x
=0; x
<*count
; x
++) {
2204 // Get an item: try fast way first.
2206 o
= PySequence_Fast_GET_ITEM(source
, x
);
2209 o
= PySequence_GetItem(source
, x
);
2215 // Convert o to wxPoint.
2216 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2217 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2218 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2219 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2220 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2224 else if (wxPySwigInstance_Check(o
)) {
2226 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2231 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2232 o1
= PySequence_GetItem(o
, 0);
2233 o2
= PySequence_GetItem(o
, 1);
2234 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2258 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2262 //------------------------------
2265 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2266 if (!PyList_Check(source
)) {
2267 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2270 int count
= PyList_Size(source
);
2271 wxBitmap
** temp
= new wxBitmap
*[count
];
2273 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2276 for (int x
=0; x
<count
; x
++) {
2277 PyObject
* o
= PyList_GetItem(source
, x
);
2278 if (wxPySwigInstance_Check(o
)) {
2280 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2281 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2287 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2296 wxString
* wxString_LIST_helper(PyObject
* source
) {
2297 if (!PyList_Check(source
)) {
2298 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2301 int count
= PyList_Size(source
);
2302 wxString
* temp
= new wxString
[count
];
2304 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2307 for (int x
=0; x
<count
; x
++) {
2308 PyObject
* o
= PyList_GetItem(source
, x
);
2309 #if PYTHON_API_VERSION >= 1009
2310 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2311 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2315 if (! PyString_Check(o
)) {
2316 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2321 wxString
* pStr
= wxString_in_helper(o
);
2329 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2330 if (!PyList_Check(source
)) {
2331 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2334 int count
= PyList_Size(source
);
2335 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2337 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2340 for (int x
=0; x
<count
; x
++) {
2341 PyObject
* o
= PyList_GetItem(source
, x
);
2342 if (wxPySwigInstance_Check(o
)) {
2343 wxAcceleratorEntry
* ae
;
2344 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2345 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2350 else if (PyTuple_Check(o
)) {
2351 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2352 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2353 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2354 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2357 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2365 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2366 if (!PyList_Check(source
)) {
2367 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2370 int count
= PyList_Size(source
);
2371 wxPen
** temp
= new wxPen
*[count
];
2373 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2376 for (int x
=0; x
<count
; x
++) {
2377 PyObject
* o
= PyList_GetItem(source
, x
);
2378 if (wxPySwigInstance_Check(o
)) {
2380 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2382 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2389 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2397 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2398 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2401 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2405 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2406 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2409 o1
= PySequence_GetItem(source
, 0);
2410 o2
= PySequence_GetItem(source
, 1);
2413 *i1
= PyInt_AsLong(o1
);
2414 *i2
= PyInt_AsLong(o2
);
2424 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2425 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2426 PyObject
*o1
, *o2
, *o3
, *o4
;
2428 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2432 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2433 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2434 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2435 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2438 o1
= PySequence_GetItem(source
, 0);
2439 o2
= PySequence_GetItem(source
, 1);
2440 o3
= PySequence_GetItem(source
, 2);
2441 o4
= PySequence_GetItem(source
, 3);
2444 *i1
= PyInt_AsLong(o1
);
2445 *i2
= PyInt_AsLong(o2
);
2446 *i3
= PyInt_AsLong(o3
);
2447 *i4
= PyInt_AsLong(o4
);
2459 //----------------------------------------------------------------------
2461 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2465 if (wxPySwigInstance_Check(source
) &&
2466 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2470 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2476 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2478 if (source
== Py_None
) {
2479 **obj
= wxSize(-1,-1);
2482 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2486 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2488 if (source
== Py_None
) {
2489 **obj
= wxPoint(-1,-1);
2492 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2497 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2499 if (source
== Py_None
) {
2500 **obj
= wxRealPoint(-1,-1);
2504 // If source is an object instance then it may already be the right type
2505 if (wxPySwigInstance_Check(source
)) {
2507 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2512 // otherwise a 2-tuple of floats is expected
2513 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2514 PyObject
* o1
= PySequence_GetItem(source
, 0);
2515 PyObject
* o2
= PySequence_GetItem(source
, 1);
2516 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2521 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2528 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2534 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2536 if (source
== Py_None
) {
2537 **obj
= wxRect(-1,-1,-1,-1);
2541 // If source is an object instance then it may already be the right type
2542 if (wxPySwigInstance_Check(source
)) {
2544 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2549 // otherwise a 4-tuple of integers is expected
2550 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2551 PyObject
* o1
= PySequence_GetItem(source
, 0);
2552 PyObject
* o2
= PySequence_GetItem(source
, 1);
2553 PyObject
* o3
= PySequence_GetItem(source
, 2);
2554 PyObject
* o4
= PySequence_GetItem(source
, 3);
2555 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2556 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2563 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2564 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2573 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2579 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2581 if (source
== Py_None
) {
2582 **obj
= wxNullColour
;
2586 // If source is an object instance then it may already be the right type
2587 if (wxPySwigInstance_Check(source
)) {
2589 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2594 // otherwise check for a string
2595 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2596 wxString spec
= Py2wxString(source
);
2597 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2598 long red
, green
, blue
;
2599 red
= green
= blue
= 0;
2600 spec
.Mid(1,2).ToLong(&red
, 16);
2601 spec
.Mid(3,2).ToLong(&green
, 16);
2602 spec
.Mid(5,2).ToLong(&blue
, 16);
2604 **obj
= wxColour(red
, green
, blue
);
2607 else { // it's a colour name
2608 **obj
= wxColour(spec
);
2612 // last chance: 3-tuple of integers is expected
2613 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2614 PyObject
* o1
= PySequence_GetItem(source
, 0);
2615 PyObject
* o2
= PySequence_GetItem(source
, 1);
2616 PyObject
* o3
= PySequence_GetItem(source
, 2);
2617 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2623 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2631 PyErr_SetString(PyExc_TypeError
,
2632 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2637 bool wxColour_typecheck(PyObject
* source
) {
2639 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2642 if (PyString_Check(source
) || PyUnicode_Check(source
))
2650 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2652 if (source
== Py_None
) {
2653 **obj
= wxPoint2D(-1,-1);
2657 // If source is an object instance then it may already be the right type
2658 if (wxPySwigInstance_Check(source
)) {
2660 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2665 // otherwise a length-2 sequence of floats is expected
2666 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2667 PyObject
* o1
= PySequence_GetItem(source
, 0);
2668 PyObject
* o2
= PySequence_GetItem(source
, 1);
2669 // This should really check for floats, not numbers -- but that would break code.
2670 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2675 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2681 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2686 //----------------------------------------------------------------------
2688 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2690 PyObject
* list
= PyList_New(0);
2691 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2693 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2695 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2697 PyList_Append(list
, str
);
2704 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2706 PyObject
* list
= PyList_New(0);
2707 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2708 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2709 PyList_Append(list
, number
);
2716 //----------------------------------------------------------------------
2717 //----------------------------------------------------------------------