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() {
130 wxApp::SetInstance(NULL
);
134 // This one isn't acutally called... We fake it with _BootstrapApp
135 bool wxPyApp::OnInit() {
140 int wxPyApp::MainLoop() {
143 DeletePendingObjects();
144 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
146 if ( m_exitOnFrameDelete
== Later
) {
147 m_exitOnFrameDelete
= Yes
;
150 retval
= wxApp::MainLoop();
157 bool wxPyApp::OnInitGui() {
159 wxApp::OnInitGui(); // in this case always call the base class version
160 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
161 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
162 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
163 wxPyEndBlockThreads(blocked
);
168 int wxPyApp::OnExit() {
170 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
171 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
172 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
173 wxPyEndBlockThreads(blocked
);
174 wxApp::OnExit(); // in this case always call the base class version
180 void wxPyApp::OnAssert(const wxChar
*file
,
185 // if we're not fully initialized then just log the error
186 if (! m_startupComplete
) {
189 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
199 // If the OnAssert is overloaded in the Python class then call it...
201 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
202 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
203 PyObject
* fso
= wx2PyString(file
);
204 PyObject
* cso
= wx2PyString(file
);
207 mso
= wx2PyString(file
);
209 mso
= Py_None
; Py_INCREF(Py_None
);
211 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
216 wxPyEndBlockThreads(blocked
);
218 // ...otherwise do our own thing with it
221 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
224 // turn it into a Python exception?
225 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
228 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
235 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
236 PyObject
* s
= wx2PyString(buf
);
237 PyErr_SetObject(wxPyAssertionError
, s
);
239 wxPyEndBlockThreads(blocked
);
241 // Now when control returns to whatever API wrapper was called from
242 // Python it should detect that an exception is set and will return
243 // NULL, signalling the exception to Python.
246 // Send it to the normal log destination, but only if
247 // not _DIALOG because it will call this too
248 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
251 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
260 // do the normal wx assert dialog?
261 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
262 wxApp::OnAssert(file
, line
, cond
, msg
);
267 // For catching Apple Events
268 void wxPyApp::MacOpenFile(const wxString
&fileName
)
270 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
271 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
272 PyObject
* s
= wx2PyString(fileName
);
273 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
276 wxPyEndBlockThreads(blocked
);
279 void wxPyApp::MacPrintFile(const wxString
&fileName
)
281 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
282 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
283 PyObject
* s
= wx2PyString(fileName
);
284 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
287 wxPyEndBlockThreads(blocked
);
290 void wxPyApp::MacNewFile()
292 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
293 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
294 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
295 wxPyEndBlockThreads(blocked
);
298 void wxPyApp::MacReopenApp()
300 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
301 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
302 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
303 wxPyEndBlockThreads(blocked
);
308 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
310 return s_macSupportPCMenuShortcuts
;
317 long wxPyApp::GetMacAboutMenuItemId() {
319 return s_macAboutMenuItemId
;
326 long wxPyApp::GetMacPreferencesMenuItemId() {
328 return s_macPreferencesMenuItemId
;
335 long wxPyApp::GetMacExitMenuItemId() {
337 return s_macExitMenuItemId
;
344 wxString
wxPyApp::GetMacHelpMenuTitleName() {
346 return s_macHelpMenuTitleName
;
348 return wxEmptyString
;
353 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
355 s_macSupportPCMenuShortcuts
= val
;
360 void wxPyApp::SetMacAboutMenuItemId(long val
) {
362 s_macAboutMenuItemId
= val
;
367 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
369 s_macPreferencesMenuItemId
= val
;
374 void wxPyApp::SetMacExitMenuItemId(long val
) {
376 s_macExitMenuItemId
= val
;
381 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
383 s_macHelpMenuTitleName
= val
;
388 // This finishes the initialization of wxWindows and then calls the OnInit
389 // that should be present in the derived (Python) class.
390 void wxPyApp::_BootstrapApp()
392 static bool haveInitialized
= false;
395 PyObject
* retval
= NULL
;
396 PyObject
* pyint
= NULL
;
399 // Only initialize wxWidgets once
400 if (! haveInitialized
) {
402 // Get any command-line args passed to this program from the sys module
405 blocked
= wxPyBeginBlockThreads();
407 PyObject
* sysargv
= PySys_GetObject("argv");
408 PyObject
* executable
= PySys_GetObject("executable");
410 if (sysargv
!= NULL
&& executable
!= NULL
) {
411 argc
= PyList_Size(sysargv
) + 1;
412 argv
= new char*[argc
+1];
413 argv
[0] = strdup(PyString_AsString(executable
));
415 for(x
=1; x
<argc
; x
++) {
416 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
417 argv
[x
] = strdup(PyString_AsString(pyArg
));
421 wxPyEndBlockThreads(blocked
);
423 // Initialize wxWidgets
424 result
= wxEntryStart(argc
, argv
);
425 // wxApp takes ownership of the argv array, don't delete it here
427 blocked
= wxPyBeginBlockThreads();
429 PyErr_SetString(PyExc_SystemError
,
430 "wxEntryStart failed, unable to initialize wxWidgets!"
432 " (Is DISPLAY set properly?)"
438 // On wxGTK the locale will be changed to match the system settings,
439 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
440 // for the floating point conversions and such to work right.
441 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
442 setlocale(LC_NUMERIC
, "C");
445 wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
447 // The stock objects were all NULL when they were loaded into
448 // SWIG generated proxies, so re-init those now...
449 wxPy_ReinitStockObjects(3);
451 wxPyEndBlockThreads(blocked
);
452 haveInitialized
= true;
460 // It's now ok to generate exceptions for assertion errors.
461 wxPythonApp
->SetStartupComplete(true);
463 // Call the Python wxApp's OnInit function
464 blocked
= wxPyBeginBlockThreads();
465 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
467 PyObject
* method
= m_myInst
.GetLastFound();
468 PyObject
* argTuple
= PyTuple_New(0);
469 retval
= PyEval_CallObject(method
, argTuple
);
475 pyint
= PyNumber_Int(retval
);
477 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
480 result
= PyInt_AS_LONG(pyint
);
483 // Is it okay if there is no OnInit? Probably so...
488 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
495 wxPyEndBlockThreads(blocked
);
498 //---------------------------------------------------------------------
499 //----------------------------------------------------------------------
503 static char* wxPyCopyCString(const wxChar
* src
)
505 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
506 size_t len
= strlen(buff
);
507 char* dest
= new char[len
+1];
513 static char* wxPyCopyCString(const char* src
) // we need a char version too
515 size_t len
= strlen(src
);
516 char* dest
= new char[len
+1];
522 static wxChar
* wxPyCopyWString(const char *src
)
524 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
525 wxString
str(src
, *wxConvCurrent
);
526 return copystring(str
);
530 static wxChar
* wxPyCopyWString(const wxChar
*src
)
532 return copystring(src
);
538 inline const char* dropwx(const char* name
) {
539 if (name
[0] == 'w' && name
[1] == 'x')
545 //----------------------------------------------------------------------
547 // This function is called when the wx._core_ module is imported to do some
548 // initial setup. (Before there is a wxApp object.) The rest happens in
549 // wxPyApp::_BootstrapApp
550 void __wxPyPreStart(PyObject
* moduleDict
)
554 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
555 // | _CRTDBG_CHECK_ALWAYS_DF
556 // | _CRTDBG_DELAY_FREE_MEM_DF
560 #ifdef WXP_WITH_THREAD
561 #if wxPyUSE_GIL_STATE
562 PyEval_InitThreads();
564 PyEval_InitThreads();
565 wxPyTStates
= new wxPyThreadStateArray
;
566 wxPyTMutex
= new wxMutex
;
568 // Save the current (main) thread state in our array
569 PyThreadState
* tstate
= wxPyBeginAllowThreads();
570 wxPyEndAllowThreads(tstate
);
574 // Ensure that the build options in the DLL (or whatever) match this build
575 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
577 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
578 wxPy_ReinitStockObjects(1);
580 wxInitAllImageHandlers();
585 void __wxPyCleanup() {
586 wxPyDoingCleanup
= true;
588 wxPyDoCleanup
= false;
591 #ifdef WXP_WITH_THREAD
592 #if !wxPyUSE_GIL_STATE
595 wxPyTStates
->Empty();
603 // Save a reference to the dictionary of the wx._core module, and inject
604 // a few more things into it.
605 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
608 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
611 if (!PyDict_Check(wxPython_dict
)) {
612 PyErr_SetString(PyExc_TypeError
,
613 "_wxPySetDictionary must have dictionary object!");
617 if (! wxPyPtrTypeMap
)
618 wxPyPtrTypeMap
= PyDict_New();
619 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
621 // Create an exception object to use for wxASSERTions
622 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
623 PyExc_AssertionError
, NULL
);
624 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
626 // Create an exception object to use when the app object hasn't been created yet
627 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
628 PyExc_RuntimeError
, NULL
);
629 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
634 #define wxPlatform "__WXMOTIF__"
635 #define wxPlatName "wxMotif"
638 #define wxPlatform "__WXX11__"
639 #define wxPlatName "wxX11"
642 #define wxPlatform "__WXGTK__"
643 #define wxPlatName "wxGTK"
646 #define wxPlatform "__WXMSW__"
647 #define wxPlatName "wxMSW"
650 #define wxPlatform "__WXMAC__"
651 #define wxPlatName "wxMac"
660 // These should be deprecated in favor of the PlatformInfo tuple built below...
661 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
662 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
663 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
665 // Make a tuple of strings that gives more info about the platform.
666 PyObject
* PlatInfo
= PyList_New(0);
669 #define _AddInfoString(st) \
670 obj = PyString_FromString(st); \
671 PyList_Append(PlatInfo, obj); \
674 _AddInfoString(wxPlatform
);
675 _AddInfoString(wxPlatName
);
677 _AddInfoString("unicode");
679 _AddInfoString("ansi");
683 _AddInfoString("gtk2");
685 _AddInfoString("gtk1");
689 _AddInfoString("wx-assertions-on");
691 _AddInfoString("wx-assertions-off");
694 #undef _AddInfoString
696 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
698 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
704 //---------------------------------------------------------------------------
706 // Python's PyInstance_Check does not return True for instances of new-style
707 // classes. This should get close enough for both new and old classes but I
708 // should re-evaluate the need for doing instance checks...
709 bool wxPyInstance_Check(PyObject
* obj
) {
710 return PyObject_HasAttrString(obj
, "__class__") != 0;
714 // This one checks if the object is an instance of a SWIG proxy class (it has
715 // a .this attribute)
716 bool wxPySwigInstance_Check(PyObject
* obj
) {
717 return PyObject_HasAttrString(obj
, "this") != 0;
720 //---------------------------------------------------------------------------
722 // The stock objects are no longer created when the wx._core_ module is
723 // imported, but only after the app object has been created. The
724 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
725 // objects though various stages of evolution:
727 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
728 // object will be created (otherwise SWIG will just use None.)
730 // pass 2: After the module has been imported and the python proxys have
731 // been created, then set the __class__ to be _wxPyUnbornObject so
732 // it will catch any access to the object and will raise an exception.
734 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
738 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
740 wxPy_ReinitStockObjects(2);
745 static void rsoPass2(const char* name
)
747 static PyObject
* unbornObjectClass
= NULL
;
750 if (unbornObjectClass
== NULL
) {
751 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
752 Py_INCREF(unbornObjectClass
);
755 // Find the object instance
756 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
757 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
758 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
761 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
765 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
771 // Find the object instance
772 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
773 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
774 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
776 // Find the class object and put it back in the instance
777 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
778 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
779 PyObject_SetAttrString(obj
, "__class__", classobj
);
781 // Rebuild the .this swigified pointer with the new value of the C++ pointer
782 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
783 PyObject_SetAttrString(obj
, "this", ptrobj
);
789 void wxPy_ReinitStockObjects(int pass
)
792 // If there is already an App object then wxPython is probably embedded in
793 // a wx C++ application, so there is no need to do all this.
794 static bool embedded
= false;
795 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
799 if (pass
== 3 && embedded
)
803 #define REINITOBJ(name, classname) \
804 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
805 else if (pass == 2) { rsoPass2(#name); } \
806 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
809 #define REINITOBJ2(name, classname) \
811 else if (pass == 2) { rsoPass2(#name); } \
812 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
815 REINITOBJ(wxNORMAL_FONT
, wxFont
);
816 REINITOBJ(wxSMALL_FONT
, wxFont
);
817 REINITOBJ(wxITALIC_FONT
, wxFont
);
818 REINITOBJ(wxSWISS_FONT
, wxFont
);
820 REINITOBJ(wxRED_PEN
, wxPen
);
821 REINITOBJ(wxCYAN_PEN
, wxPen
);
822 REINITOBJ(wxGREEN_PEN
, wxPen
);
823 REINITOBJ(wxBLACK_PEN
, wxPen
);
824 REINITOBJ(wxWHITE_PEN
, wxPen
);
825 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
826 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
827 REINITOBJ(wxGREY_PEN
, wxPen
);
828 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
829 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
831 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
832 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
833 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
834 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
835 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
836 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
837 REINITOBJ(wxRED_BRUSH
, wxBrush
);
838 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
839 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
840 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
842 REINITOBJ(wxBLACK
, wxColour
);
843 REINITOBJ(wxWHITE
, wxColour
);
844 REINITOBJ(wxRED
, wxColour
);
845 REINITOBJ(wxBLUE
, wxColour
);
846 REINITOBJ(wxGREEN
, wxColour
);
847 REINITOBJ(wxCYAN
, wxColour
);
848 REINITOBJ(wxLIGHT_GREY
, wxColour
);
850 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
851 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
852 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
854 REINITOBJ2(wxNullBitmap
, wxBitmap
);
855 REINITOBJ2(wxNullIcon
, wxIcon
);
856 REINITOBJ2(wxNullCursor
, wxCursor
);
857 REINITOBJ2(wxNullPen
, wxPen
);
858 REINITOBJ2(wxNullBrush
, wxBrush
);
859 REINITOBJ2(wxNullPalette
, wxPalette
);
860 REINITOBJ2(wxNullFont
, wxFont
);
861 REINITOBJ2(wxNullColour
, wxColour
);
863 REINITOBJ(wxTheFontList
, wxFontList
);
864 REINITOBJ(wxThePenList
, wxPenList
);
865 REINITOBJ(wxTheBrushList
, wxBrushList
);
866 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
869 REINITOBJ2(wxDefaultValidator
, wxValidator
);
870 REINITOBJ2(wxNullImage
, wxImage
);
871 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
877 //---------------------------------------------------------------------------
879 // Check for existence of a wxApp, setting an exception if there isn't one.
880 // This doesn't need to aquire the GIL because it should only be called from
881 // an %exception before the lock is released.
883 bool wxPyCheckForApp() {
884 if (wxTheApp
!= NULL
)
887 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
892 //---------------------------------------------------------------------------
894 void wxPyUserData_dtor(wxPyUserData
* self
) {
895 if (! wxPyDoingCleanup
) {
896 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
897 Py_DECREF(self
->m_obj
);
899 wxPyEndBlockThreads(blocked
);
904 void wxPyClientData_dtor(wxPyClientData
* self
) {
905 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
906 // may have already garbage collected the object...
907 if (self
->m_incRef
) {
908 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
909 Py_DECREF(self
->m_obj
);
910 wxPyEndBlockThreads(blocked
);
918 // This is called when an OOR controled object is being destroyed. Although
919 // the C++ object is going away there is no way to force the Python object
920 // (and all references to it) to die too. This causes problems (crashes) in
921 // wxPython when a python shadow object attempts to call a C++ method using
922 // the now bogus pointer... So to try and prevent this we'll do a little black
923 // magic and change the class of the python instance to a class that will
924 // raise an exception for any attempt to call methods with it. See
925 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
926 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
928 static PyObject
* deadObjectClass
= NULL
;
930 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
931 if (deadObjectClass
== NULL
) {
932 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
933 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
934 // will lead to a deadlock when it tries to aquire the GIL again.
935 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
936 Py_INCREF(deadObjectClass
);
940 // Only if there is more than one reference to the object and we are
941 // holding the OOR reference:
942 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
943 // bool isInstance = wxPyInstance_Check(self->m_obj);
945 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
947 // Call __del__, if there is one.
948 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
950 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
954 if (PyErr_Occurred())
955 PyErr_Clear(); // just ignore it for now
958 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
960 // Clear the instance's dictionary
963 // put the name of the old class into the instance, and then reset the
964 // class to be the dead class.
965 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
966 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
967 PyDict_SetItemString(dict
, "_name", name
);
968 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
969 //Py_INCREF(deadObjectClass);
975 // m_obj is DECREF'd in the base class dtor...
976 wxPyEndBlockThreads(blocked
);
980 //---------------------------------------------------------------------------
981 // Stuff used by OOR to find the right wxPython class type to return and to
985 // The pointer type map is used when the "pointer" type name generated by SWIG
986 // is not the same as the shadow class name, for example wxPyTreeCtrl
987 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
988 // so we'll just make it a Python dictionary in the wx module's namespace.
989 // (See __wxSetDictionary)
990 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
991 if (! wxPyPtrTypeMap
)
992 wxPyPtrTypeMap
= PyDict_New();
993 PyDict_SetItemString(wxPyPtrTypeMap
,
995 PyString_FromString((char*)ptrName
));
1001 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
1002 PyObject
* target
= NULL
;
1003 bool isEvtHandler
= false;
1004 bool isSizer
= false;
1007 // If it's derived from wxEvtHandler then there may
1008 // already be a pointer to a Python object that we can use
1010 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
1011 isEvtHandler
= true;
1012 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
1013 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
1015 target
= data
->m_obj
;
1021 // Also check for wxSizer
1022 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
1024 wxSizer
* sz
= (wxSizer
*)source
;
1025 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1027 target
= data
->m_obj
;
1034 // Otherwise make it the old fashioned way by making a new shadow
1035 // object and putting this pointer in it. Look up the class
1036 // heirarchy until we find a class name that is located in the
1038 const wxClassInfo
* info
= source
->GetClassInfo();
1039 wxString name
= info
->GetClassName();
1040 bool exists
= wxPyCheckSwigType(name
);
1041 while (info
&& !exists
) {
1042 info
= info
->GetBaseClass1();
1043 name
= info
->GetClassName();
1044 exists
= wxPyCheckSwigType(name
);
1047 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1048 if (target
&& isEvtHandler
)
1049 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1050 if (target
&& isSizer
)
1051 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1053 wxString
msg(wxT("wxPython class not found for "));
1054 msg
+= source
->GetClassInfo()->GetClassName();
1055 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1059 } else { // source was NULL so return None.
1060 Py_INCREF(Py_None
); target
= Py_None
;
1066 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1068 return wxPyMake_wxObject(source
, setThisOwn
);
1072 //---------------------------------------------------------------------------
1075 #ifdef WXP_WITH_THREAD
1076 #if !wxPyUSE_GIL_STATE
1079 unsigned long wxPyGetCurrentThreadId() {
1080 return wxThread::GetCurrentId();
1083 static wxPyThreadState gs_shutdownTState
;
1086 wxPyThreadState
* wxPyGetThreadState() {
1087 if (wxPyTMutex
== NULL
) // Python is shutting down...
1088 return &gs_shutdownTState
;
1090 unsigned long ctid
= wxPyGetCurrentThreadId();
1091 wxPyThreadState
* tstate
= NULL
;
1094 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1095 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1096 if (info
.tid
== ctid
) {
1101 wxPyTMutex
->Unlock();
1102 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1108 void wxPySaveThreadState(PyThreadState
* tstate
) {
1109 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1110 gs_shutdownTState
.tstate
= tstate
;
1113 unsigned long ctid
= wxPyGetCurrentThreadId();
1115 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1116 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1117 if (info
.tid
== ctid
) {
1119 if (info
.tstate
!= tstate
)
1120 wxLogMessage("*** tstate mismatch!???");
1122 info
.tstate
= tstate
; // allow for transient tstates
1123 // Normally it will never change, but apparently COM callbacks
1124 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1125 // tstate which will then be garbage the next time we try to use
1128 wxPyTMutex
->Unlock();
1132 // not found, so add it...
1133 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1134 wxPyTMutex
->Unlock();
1142 // Calls from Python to wxWindows code are wrapped in calls to these
1145 PyThreadState
* wxPyBeginAllowThreads() {
1146 #ifdef WXP_WITH_THREAD
1147 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1148 #if !wxPyUSE_GIL_STATE
1149 wxPySaveThreadState(saved
);
1157 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1158 #ifdef WXP_WITH_THREAD
1159 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1165 // Calls from wxWindows back to Python code, or even any PyObject
1166 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1168 wxPyBlock_t
wxPyBeginBlockThreads() {
1169 #ifdef WXP_WITH_THREAD
1170 if (! Py_IsInitialized()) {
1171 return (wxPyBlock_t
)0;
1173 #if wxPyUSE_GIL_STATE
1174 PyGILState_STATE state
= PyGILState_Ensure();
1177 PyThreadState
*current
= _PyThreadState_Current
;
1179 // Only block if there wasn't already a tstate, or if the current one is
1180 // not the one we are wanting to change to. This should prevent deadlock
1181 // if there are nested calls to wxPyBeginBlockThreads
1182 wxPyBlock_t blocked
= false;
1183 wxPyThreadState
* tstate
= wxPyGetThreadState();
1184 if (current
!= tstate
->tstate
) {
1185 PyEval_RestoreThread(tstate
->tstate
);
1191 return (wxPyBlock_t
)0;
1196 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1197 #ifdef WXP_WITH_THREAD
1198 if (! Py_IsInitialized()) {
1201 #if wxPyUSE_GIL_STATE
1202 PyGILState_Release(blocked
);
1204 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1205 // The value of blocked passed in needs to be the same as that returned
1206 // from wxPyBeginBlockThreads at the same nesting level.
1208 PyEval_SaveThread();
1215 //---------------------------------------------------------------------------
1216 // wxPyInputStream and wxPyCBInputStream methods
1219 void wxPyInputStream::close() {
1220 /* do nothing for now */
1223 void wxPyInputStream::flush() {
1224 /* do nothing for now */
1227 bool wxPyInputStream::eof() {
1229 return m_wxis
->Eof();
1234 wxPyInputStream::~wxPyInputStream() {
1242 PyObject
* wxPyInputStream::read(int size
) {
1243 PyObject
* obj
= NULL
;
1245 const int BUFSIZE
= 1024;
1247 // check if we have a real wxInputStream to work with
1249 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1250 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1251 wxPyEndBlockThreads(blocked
);
1256 // read while bytes are available on the stream
1257 while ( m_wxis
->CanRead() ) {
1258 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1259 buf
.UngetAppendBuf(m_wxis
->LastRead());
1262 } else { // Read only size number of characters
1263 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1264 buf
.UngetWriteBuf(m_wxis
->LastRead());
1268 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1269 wxStreamError err
= m_wxis
->GetLastError();
1270 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1271 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1274 // We use only strings for the streams, not unicode
1275 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1277 wxPyEndBlockThreads(blocked
);
1282 PyObject
* wxPyInputStream::readline(int size
) {
1283 PyObject
* obj
= NULL
;
1288 // check if we have a real wxInputStream to work with
1290 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1291 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1292 wxPyEndBlockThreads(blocked
);
1296 // read until \n or byte limit reached
1297 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1298 ch
= m_wxis
->GetC();
1303 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1304 wxStreamError err
= m_wxis
->GetLastError();
1305 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1306 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1309 // We use only strings for the streams, not unicode
1310 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1312 wxPyEndBlockThreads(blocked
);
1317 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1320 // check if we have a real wxInputStream to work with
1322 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1323 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1324 wxPyEndBlockThreads(blocked
);
1329 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1330 pylist
= PyList_New(0);
1331 wxPyEndBlockThreads(blocked
);
1334 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1336 wxPyEndBlockThreads(blocked
);
1340 // read sizehint bytes or until EOF
1342 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1343 PyObject
* s
= this->readline();
1345 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1347 wxPyEndBlockThreads(blocked
);
1350 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1351 PyList_Append(pylist
, s
);
1352 i
+= PyString_Size(s
);
1353 wxPyEndBlockThreads(blocked
);
1357 wxStreamError err
= m_wxis
->GetLastError();
1358 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1359 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1361 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1362 wxPyEndBlockThreads(blocked
);
1370 void wxPyInputStream::seek(int offset
, int whence
) {
1372 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1375 int wxPyInputStream::tell(){
1377 return m_wxis
->TellI();
1384 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1385 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1388 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1390 m_read
= other
.m_read
;
1391 m_seek
= other
.m_seek
;
1392 m_tell
= other
.m_tell
;
1393 m_block
= other
.m_block
;
1400 wxPyCBInputStream::~wxPyCBInputStream() {
1401 wxPyBlock_t blocked
;
1402 if (m_block
) blocked
= wxPyBeginBlockThreads();
1406 if (m_block
) wxPyEndBlockThreads(blocked
);
1410 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1411 wxPyBlock_t blocked
;
1412 if (block
) blocked
= wxPyBeginBlockThreads();
1414 PyObject
* read
= getMethod(py
, "read");
1415 PyObject
* seek
= getMethod(py
, "seek");
1416 PyObject
* tell
= getMethod(py
, "tell");
1419 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1423 if (block
) wxPyEndBlockThreads(blocked
);
1427 if (block
) wxPyEndBlockThreads(blocked
);
1428 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1432 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1433 return wxPyCBInputStream::create(py
, block
);
1436 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1437 return new wxPyCBInputStream(*other
);
1440 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1441 if (!PyObject_HasAttrString(py
, name
))
1443 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1444 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1452 wxFileOffset
wxPyCBInputStream::GetLength() const {
1453 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1454 if (m_seek
&& m_tell
) {
1455 wxFileOffset temp
= self
->OnSysTell();
1456 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1457 self
->OnSysSeek(temp
, wxFromStart
);
1461 return wxInvalidOffset
;
1465 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1469 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1470 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1471 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1475 if ((result
!= NULL
) && PyString_Check(result
)) {
1476 o
= PyString_Size(result
);
1478 m_lasterror
= wxSTREAM_EOF
;
1481 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1486 m_lasterror
= wxSTREAM_READ_ERROR
;
1487 wxPyEndBlockThreads(blocked
);
1491 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1492 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1497 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1498 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1499 PyObject
* arglist
= PyTuple_New(2);
1501 if (sizeof(wxFileOffset
) > sizeof(long))
1502 // wxFileOffset is a 64-bit value...
1503 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1505 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1507 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1510 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1513 wxPyEndBlockThreads(blocked
);
1518 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1519 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1520 PyObject
* arglist
= Py_BuildValue("()");
1521 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1524 if (result
!= NULL
) {
1525 if (PyLong_Check(result
))
1526 o
= PyLong_AsLongLong(result
);
1528 o
= PyInt_AsLong(result
);
1531 wxPyEndBlockThreads(blocked
);
1535 //----------------------------------------------------------------------
1537 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1539 wxPyCallback::wxPyCallback(PyObject
* func
) {
1544 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1545 m_func
= other
.m_func
;
1549 wxPyCallback::~wxPyCallback() {
1550 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1552 wxPyEndBlockThreads(blocked
);
1556 #define wxPy_PRECALLINIT "_preCallInit"
1557 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1559 // This function is used for all events destined for Python event handlers.
1560 void wxPyCallback::EventThunker(wxEvent
& event
) {
1561 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1562 PyObject
* func
= cb
->m_func
;
1566 bool checkSkip
= false;
1568 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1569 wxString className
= event
.GetClassInfo()->GetClassName();
1571 // If the event is one of these types then pass the original
1572 // event object instead of the one passed to us.
1573 if ( className
== wxT("wxPyEvent") ) {
1574 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1575 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1577 else if ( className
== wxT("wxPyCommandEvent") ) {
1578 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1579 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1582 arg
= wxPyConstructObject((void*)&event
, className
);
1588 // "intern" the pre/post method names to speed up the HasAttr
1589 static PyObject
* s_preName
= NULL
;
1590 static PyObject
* s_postName
= NULL
;
1591 if (s_preName
== NULL
) {
1592 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1593 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1596 // Check if the event object needs some preinitialization
1597 if (PyObject_HasAttr(arg
, s_preName
)) {
1598 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1600 Py_DECREF(result
); // result is ignored, but we still need to decref it
1601 PyErr_Clear(); // Just in case...
1607 // Call the event handler, passing the event object
1608 tuple
= PyTuple_New(1);
1609 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1610 result
= PyEval_CallObject(func
, tuple
);
1612 Py_DECREF(result
); // result is ignored, but we still need to decref it
1613 PyErr_Clear(); // Just in case...
1618 // Check if the event object needs some post cleanup
1619 if (PyObject_HasAttr(arg
, s_postName
)) {
1620 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1622 Py_DECREF(result
); // result is ignored, but we still need to decref it
1623 PyErr_Clear(); // Just in case...
1630 // if the event object was one of our special types and
1631 // it had been cloned, then we need to extract the Skipped
1632 // value from the original and set it in the clone.
1633 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1635 event
.Skip(PyInt_AsLong(result
));
1643 wxPyEndBlockThreads(blocked
);
1647 //----------------------------------------------------------------------
1649 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1651 m_self
= other
.m_self
;
1652 m_class
= other
.m_class
;
1660 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1671 #if PYTHON_API_VERSION >= 1011
1673 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1674 // in which the method was defined. Starting with 2.2 it returns
1675 // "class that asked for the method" which seems totally bogus to me
1676 // but apprently it fixes some obscure problem waiting to happen in
1677 // Python. Since the API was not documented Guido and the gang felt
1678 // safe in changing it. Needless to say that totally screwed up the
1679 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1680 // code to find the class where the method is actually defined...
1683 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1687 if (PyType_Check(klass
)) { // new style classes
1688 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1689 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1690 PyObject
*mro
, *res
, *base
, *dict
;
1691 /* Look in tp_dict of types in MRO */
1693 assert(PyTuple_Check(mro
));
1694 n
= PyTuple_GET_SIZE(mro
);
1695 for (i
= 0; i
< n
; i
++) {
1696 base
= PyTuple_GET_ITEM(mro
, i
);
1697 if (PyClass_Check(base
))
1698 dict
= ((PyClassObject
*)base
)->cl_dict
;
1700 assert(PyType_Check(base
));
1701 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1703 assert(dict
&& PyDict_Check(dict
));
1704 res
= PyDict_GetItem(dict
, name
);
1711 else if (PyClass_Check(klass
)) { // old style classes
1712 // This code is borrowed/adapted from class_lookup in classobject.c
1713 PyClassObject
* cp
= (PyClassObject
*)klass
;
1714 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1715 if (value
!= NULL
) {
1716 return (PyObject
*)cp
;
1718 n
= PyTuple_Size(cp
->cl_bases
);
1719 for (i
= 0; i
< n
; i
++) {
1720 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1721 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1733 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1735 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1737 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1739 #else // 2.2 and after, the hard way...
1741 PyObject
* nameo
= PyString_FromString(name
);
1742 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1750 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1751 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1752 self
->m_lastFound
= NULL
;
1754 // If the object (m_self) has an attibute of the given name...
1755 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1756 PyObject
*method
, *klass
;
1757 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1759 // ...and if that attribute is a method, and if that method's class is
1760 // not from a base class...
1761 if (PyMethod_Check(method
) &&
1762 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1763 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1765 // ...then we'll save a pointer to the method so callCallback can call it.
1766 self
->m_lastFound
= method
;
1772 return m_lastFound
!= NULL
;
1776 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1780 result
= callCallbackObj(argTuple
);
1781 if (result
) { // Assumes an integer return type...
1782 retval
= PyInt_AsLong(result
);
1784 PyErr_Clear(); // forget about it if it's not...
1789 // Invoke the Python callable object, returning the raw PyObject return
1790 // value. Caller should DECREF the return value and also manage the GIL.
1791 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1794 // Save a copy of the pointer in case the callback generates another
1795 // callback. In that case m_lastFound will have a different value when
1796 // it gets back here...
1797 PyObject
* method
= m_lastFound
;
1799 result
= PyEval_CallObject(method
, argTuple
);
1800 Py_DECREF(argTuple
);
1809 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1810 cbh
.setSelf(self
, klass
, incref
);
1813 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1814 return cbh
.findCallback(name
);
1817 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1818 return cbh
.callCallback(argTuple
);
1821 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1822 return cbh
.callCallbackObj(argTuple
);
1826 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1827 if (cbh
->m_incRef
) {
1828 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1829 Py_XDECREF(cbh
->m_self
);
1830 Py_XDECREF(cbh
->m_class
);
1831 wxPyEndBlockThreads(blocked
);
1835 //---------------------------------------------------------------------------
1836 //---------------------------------------------------------------------------
1837 // These event classes can be derived from in Python and passed through the event
1838 // system without losing anything. They do this by keeping a reference to
1839 // themselves and some special case handling in wxPyCallback::EventThunker.
1842 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1843 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1844 //Py_INCREF(m_self); // circular loops...
1848 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1849 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1852 wxPyEndBlockThreads(blocked
);
1855 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1856 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1864 wxPyEndBlockThreads(blocked
);
1867 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1873 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1874 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1877 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1878 : wxEvent(winid
, commandType
) {
1882 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1885 SetSelf(evt
.m_self
, true);
1889 wxPyEvent::~wxPyEvent() {
1893 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1894 : wxCommandEvent(commandType
, id
) {
1898 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1899 : wxCommandEvent(evt
)
1901 SetSelf(evt
.m_self
, true);
1905 wxPyCommandEvent::~wxPyCommandEvent() {
1912 //---------------------------------------------------------------------------
1913 //---------------------------------------------------------------------------
1914 // Convert a wxList to a Python List, only works for lists of wxObjects
1916 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1917 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1921 wxNode
* node
= list
->GetFirst();
1923 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1924 pyList
= PyList_New(0);
1926 wxObj
= node
->GetData();
1927 pyObj
= wxPyMake_wxObject(wxObj
,false);
1928 PyList_Append(pyList
, pyObj
);
1929 node
= node
->GetNext();
1931 wxPyEndBlockThreads(blocked
);
1935 //----------------------------------------------------------------------
1937 long wxPyGetWinHandle(wxWindow
* win
) {
1940 return (long)win
->GetHandle();
1943 #if defined(__WXGTK__) || defined(__WXX11)
1944 return (long)GetXWindow(win
);
1948 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1949 return (long)win
->GetHandle();
1955 //----------------------------------------------------------------------
1956 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1957 // included in every file over and over again...
1959 wxString
* wxString_in_helper(PyObject
* source
) {
1960 wxString
* target
= NULL
;
1962 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1963 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1967 PyObject
* uni
= source
;
1968 if (PyString_Check(source
)) {
1969 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1970 if (PyErr_Occurred()) return NULL
;
1972 target
= new wxString();
1973 size_t len
= PyUnicode_GET_SIZE(uni
);
1975 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1976 target
->UngetWriteBuf(len
);
1979 if (PyString_Check(source
))
1982 // Convert to a string object if it isn't already, then to wxString
1983 PyObject
* str
= source
;
1984 if (PyUnicode_Check(source
)) {
1985 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1986 if (PyErr_Occurred()) return NULL
;
1988 else if (!PyString_Check(source
)) {
1989 str
= PyObject_Str(source
);
1990 if (PyErr_Occurred()) return NULL
;
1992 char* tmpPtr
; int tmpSize
;
1993 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1994 target
= new wxString(tmpPtr
, tmpSize
);
1996 if (!PyString_Check(source
))
1998 #endif // wxUSE_UNICODE
2004 // Similar to above except doesn't use "new" and doesn't set an exception
2005 wxString
Py2wxString(PyObject
* source
)
2010 // Convert to a unicode object, if not already, then to a wxString
2011 PyObject
* uni
= source
;
2012 if (!PyUnicode_Check(source
)) {
2013 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
2014 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2016 size_t len
= PyUnicode_GET_SIZE(uni
);
2018 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
2019 target
.UngetWriteBuf();
2022 if (!PyUnicode_Check(source
))
2025 // Convert to a string object if it isn't already, then to wxString
2026 PyObject
* str
= source
;
2027 if (PyUnicode_Check(source
)) {
2028 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
2029 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2031 else if (!PyString_Check(source
)) {
2032 str
= PyObject_Str(source
);
2033 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2035 char* tmpPtr
; int tmpSize
;
2036 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
2037 target
= wxString(tmpPtr
, tmpSize
);
2039 if (!PyString_Check(source
))
2041 #endif // wxUSE_UNICODE
2047 // Make either a Python String or Unicode object, depending on build mode
2048 PyObject
* wx2PyString(const wxString
& src
)
2052 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
2054 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
2061 void wxSetDefaultPyEncoding(const char* encoding
)
2063 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
2066 const char* wxGetDefaultPyEncoding()
2068 return wxPyDefaultEncoding
;
2071 //----------------------------------------------------------------------
2074 byte
* byte_LIST_helper(PyObject
* source
) {
2075 if (!PyList_Check(source
)) {
2076 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2079 int count
= PyList_Size(source
);
2080 byte
* temp
= new byte
[count
];
2082 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2085 for (int x
=0; x
<count
; x
++) {
2086 PyObject
* o
= PyList_GetItem(source
, x
);
2087 if (! PyInt_Check(o
)) {
2088 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2091 temp
[x
] = (byte
)PyInt_AsLong(o
);
2097 int* int_LIST_helper(PyObject
* source
) {
2098 if (!PyList_Check(source
)) {
2099 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2102 int count
= PyList_Size(source
);
2103 int* temp
= new int[count
];
2105 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2108 for (int x
=0; x
<count
; x
++) {
2109 PyObject
* o
= PyList_GetItem(source
, x
);
2110 if (! PyInt_Check(o
)) {
2111 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2114 temp
[x
] = PyInt_AsLong(o
);
2120 long* long_LIST_helper(PyObject
* source
) {
2121 if (!PyList_Check(source
)) {
2122 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2125 int count
= PyList_Size(source
);
2126 long* temp
= new long[count
];
2128 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2131 for (int x
=0; x
<count
; x
++) {
2132 PyObject
* o
= PyList_GetItem(source
, x
);
2133 if (! PyInt_Check(o
)) {
2134 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2137 temp
[x
] = PyInt_AsLong(o
);
2143 char** string_LIST_helper(PyObject
* source
) {
2144 if (!PyList_Check(source
)) {
2145 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2148 int count
= PyList_Size(source
);
2149 char** temp
= new char*[count
];
2151 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2154 for (int x
=0; x
<count
; x
++) {
2155 PyObject
* o
= PyList_GetItem(source
, x
);
2156 if (! PyString_Check(o
)) {
2157 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2160 temp
[x
] = PyString_AsString(o
);
2165 //--------------------------------
2166 // Part of patch from Tim Hochberg
2167 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2168 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2169 point
->x
= PyInt_AS_LONG(o1
);
2170 point
->y
= PyInt_AS_LONG(o2
);
2173 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2174 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2175 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2178 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2179 // Disallow instances because they can cause havok
2182 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2183 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2184 point
->x
= PyInt_AsLong(o1
);
2185 point
->y
= PyInt_AsLong(o2
);
2192 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2193 // Putting all of the declarations here allows
2194 // us to put the error handling all in one place.
2197 PyObject
*o
, *o1
, *o2
;
2198 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2200 if (!PySequence_Check(source
)) {
2204 // The length of the sequence is returned in count.
2205 *count
= PySequence_Length(source
);
2210 temp
= new wxPoint
[*count
];
2212 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2215 for (x
=0; x
<*count
; x
++) {
2216 // Get an item: try fast way first.
2218 o
= PySequence_Fast_GET_ITEM(source
, x
);
2221 o
= PySequence_GetItem(source
, x
);
2227 // Convert o to wxPoint.
2228 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2229 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2230 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2231 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2232 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2236 else if (wxPySwigInstance_Check(o
)) {
2238 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2243 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2244 o1
= PySequence_GetItem(o
, 0);
2245 o2
= PySequence_GetItem(o
, 1);
2246 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2270 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2274 //------------------------------
2277 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2278 if (!PyList_Check(source
)) {
2279 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2282 int count
= PyList_Size(source
);
2283 wxBitmap
** temp
= new wxBitmap
*[count
];
2285 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2288 for (int x
=0; x
<count
; x
++) {
2289 PyObject
* o
= PyList_GetItem(source
, x
);
2290 if (wxPySwigInstance_Check(o
)) {
2292 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2293 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2299 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2308 wxString
* wxString_LIST_helper(PyObject
* source
) {
2309 if (!PyList_Check(source
)) {
2310 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2313 int count
= PyList_Size(source
);
2314 wxString
* temp
= new wxString
[count
];
2316 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2319 for (int x
=0; x
<count
; x
++) {
2320 PyObject
* o
= PyList_GetItem(source
, x
);
2321 #if PYTHON_API_VERSION >= 1009
2322 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2323 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2327 if (! PyString_Check(o
)) {
2328 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2333 wxString
* pStr
= wxString_in_helper(o
);
2341 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2342 if (!PyList_Check(source
)) {
2343 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2346 int count
= PyList_Size(source
);
2347 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2349 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2352 for (int x
=0; x
<count
; x
++) {
2353 PyObject
* o
= PyList_GetItem(source
, x
);
2354 if (wxPySwigInstance_Check(o
)) {
2355 wxAcceleratorEntry
* ae
;
2356 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2357 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2362 else if (PyTuple_Check(o
)) {
2363 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2364 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2365 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2366 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2369 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2377 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2378 if (!PyList_Check(source
)) {
2379 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2382 int count
= PyList_Size(source
);
2383 wxPen
** temp
= new wxPen
*[count
];
2385 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2388 for (int x
=0; x
<count
; x
++) {
2389 PyObject
* o
= PyList_GetItem(source
, x
);
2390 if (wxPySwigInstance_Check(o
)) {
2392 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2394 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2401 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2409 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2410 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2413 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2417 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2418 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2421 o1
= PySequence_GetItem(source
, 0);
2422 o2
= PySequence_GetItem(source
, 1);
2425 *i1
= PyInt_AsLong(o1
);
2426 *i2
= PyInt_AsLong(o2
);
2436 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2437 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2438 PyObject
*o1
, *o2
, *o3
, *o4
;
2440 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2444 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2445 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2446 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2447 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2450 o1
= PySequence_GetItem(source
, 0);
2451 o2
= PySequence_GetItem(source
, 1);
2452 o3
= PySequence_GetItem(source
, 2);
2453 o4
= PySequence_GetItem(source
, 3);
2456 *i1
= PyInt_AsLong(o1
);
2457 *i2
= PyInt_AsLong(o2
);
2458 *i3
= PyInt_AsLong(o3
);
2459 *i4
= PyInt_AsLong(o4
);
2471 //----------------------------------------------------------------------
2473 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2477 if (wxPySwigInstance_Check(source
) &&
2478 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2482 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2488 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2490 if (source
== Py_None
) {
2491 **obj
= wxSize(-1,-1);
2494 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2498 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2500 if (source
== Py_None
) {
2501 **obj
= wxPoint(-1,-1);
2504 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2509 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2511 if (source
== Py_None
) {
2512 **obj
= wxRealPoint(-1,-1);
2516 // If source is an object instance then it may already be the right type
2517 if (wxPySwigInstance_Check(source
)) {
2519 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2524 // otherwise a 2-tuple of floats is expected
2525 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2526 PyObject
* o1
= PySequence_GetItem(source
, 0);
2527 PyObject
* o2
= PySequence_GetItem(source
, 1);
2528 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2533 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2540 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2546 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2548 if (source
== Py_None
) {
2549 **obj
= wxRect(-1,-1,-1,-1);
2553 // If source is an object instance then it may already be the right type
2554 if (wxPySwigInstance_Check(source
)) {
2556 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2561 // otherwise a 4-tuple of integers is expected
2562 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2563 PyObject
* o1
= PySequence_GetItem(source
, 0);
2564 PyObject
* o2
= PySequence_GetItem(source
, 1);
2565 PyObject
* o3
= PySequence_GetItem(source
, 2);
2566 PyObject
* o4
= PySequence_GetItem(source
, 3);
2567 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2568 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2575 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2576 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2585 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2591 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2593 if (source
== Py_None
) {
2594 **obj
= wxNullColour
;
2598 // If source is an object instance then it may already be the right type
2599 if (wxPySwigInstance_Check(source
)) {
2601 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2606 // otherwise check for a string
2607 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2608 wxString spec
= Py2wxString(source
);
2609 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2610 long red
, green
, blue
;
2611 red
= green
= blue
= 0;
2612 spec
.Mid(1,2).ToLong(&red
, 16);
2613 spec
.Mid(3,2).ToLong(&green
, 16);
2614 spec
.Mid(5,2).ToLong(&blue
, 16);
2616 **obj
= wxColour(red
, green
, blue
);
2619 else { // it's a colour name
2620 **obj
= wxColour(spec
);
2624 // last chance: 3-tuple of integers is expected
2625 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2626 PyObject
* o1
= PySequence_GetItem(source
, 0);
2627 PyObject
* o2
= PySequence_GetItem(source
, 1);
2628 PyObject
* o3
= PySequence_GetItem(source
, 2);
2629 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2635 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2643 PyErr_SetString(PyExc_TypeError
,
2644 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2649 bool wxColour_typecheck(PyObject
* source
) {
2651 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2654 if (PyString_Check(source
) || PyUnicode_Check(source
))
2662 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2664 if (source
== Py_None
) {
2665 **obj
= wxPoint2D(-1,-1);
2669 // If source is an object instance then it may already be the right type
2670 if (wxPySwigInstance_Check(source
)) {
2672 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2677 // otherwise a length-2 sequence of floats is expected
2678 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2679 PyObject
* o1
= PySequence_GetItem(source
, 0);
2680 PyObject
* o2
= PySequence_GetItem(source
, 1);
2681 // This should really check for floats, not numbers -- but that would break code.
2682 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2687 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2693 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2698 //----------------------------------------------------------------------
2700 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2702 PyObject
* list
= PyList_New(0);
2703 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2705 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2707 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2709 PyList_Append(list
, str
);
2716 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2718 PyObject
* list
= PyList_New(0);
2719 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2720 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2721 PyList_Append(list
, number
);
2728 //----------------------------------------------------------------------
2729 //----------------------------------------------------------------------