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;
455 // It's now ok to generate exceptions for assertion errors.
456 wxPythonApp
->SetStartupComplete(true);
458 // Call the Python wxApp's OnInit function
459 blocked
= wxPyBeginBlockThreads();
460 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
462 PyObject
* method
= m_myInst
.GetLastFound();
463 PyObject
* argTuple
= PyTuple_New(0);
464 retval
= PyEval_CallObject(method
, argTuple
);
470 pyint
= PyNumber_Int(retval
);
472 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
475 result
= PyInt_AS_LONG(pyint
);
478 // Is it okay if there is no OnInit? Probably so...
483 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
490 wxPyEndBlockThreads(blocked
);
493 //---------------------------------------------------------------------
494 //----------------------------------------------------------------------
498 static char* wxPyCopyCString(const wxChar
* src
)
500 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
501 size_t len
= strlen(buff
);
502 char* dest
= new char[len
+1];
508 static char* wxPyCopyCString(const char* src
) // we need a char version too
510 size_t len
= strlen(src
);
511 char* dest
= new char[len
+1];
517 static wxChar
* wxPyCopyWString(const char *src
)
519 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
520 wxString
str(src
, *wxConvCurrent
);
521 return copystring(str
);
525 static wxChar
* wxPyCopyWString(const wxChar
*src
)
527 return copystring(src
);
533 inline const char* dropwx(const char* name
) {
534 if (name
[0] == 'w' && name
[1] == 'x')
540 //----------------------------------------------------------------------
542 // This function is called when the wx._core_ module is imported to do some
543 // initial setup. (Before there is a wxApp object.) The rest happens in
544 // wxPyApp::_BootstrapApp
545 void __wxPyPreStart(PyObject
* moduleDict
)
549 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
550 // | _CRTDBG_CHECK_ALWAYS_DF
551 // | _CRTDBG_DELAY_FREE_MEM_DF
555 #ifdef WXP_WITH_THREAD
556 #if wxPyUSE_GIL_STATE
557 PyEval_InitThreads();
559 PyEval_InitThreads();
560 wxPyTStates
= new wxPyThreadStateArray
;
561 wxPyTMutex
= new wxMutex
;
563 // Save the current (main) thread state in our array
564 PyThreadState
* tstate
= wxPyBeginAllowThreads();
565 wxPyEndAllowThreads(tstate
);
569 // Ensure that the build options in the DLL (or whatever) match this build
570 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
572 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
573 wxPy_ReinitStockObjects(1);
575 wxInitAllImageHandlers();
580 void __wxPyCleanup() {
581 wxPyDoingCleanup
= true;
583 wxPyDoCleanup
= false;
586 #ifdef WXP_WITH_THREAD
587 #if !wxPyUSE_GIL_STATE
590 wxPyTStates
->Empty();
598 // Save a reference to the dictionary of the wx._core module, and inject
599 // a few more things into it.
600 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
603 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
606 if (!PyDict_Check(wxPython_dict
)) {
607 PyErr_SetString(PyExc_TypeError
,
608 "_wxPySetDictionary must have dictionary object!");
612 if (! wxPyPtrTypeMap
)
613 wxPyPtrTypeMap
= PyDict_New();
614 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
616 // Create an exception object to use for wxASSERTions
617 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
618 PyExc_AssertionError
, NULL
);
619 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
621 // Create an exception object to use when the app object hasn't been created yet
622 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
623 PyExc_RuntimeError
, NULL
);
624 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
629 #define wxPlatform "__WXMOTIF__"
630 #define wxPlatName "wxMotif"
633 #define wxPlatform "__WXX11__"
634 #define wxPlatName "wxX11"
637 #define wxPlatform "__WXGTK__"
638 #define wxPlatName "wxGTK"
641 #define wxPlatform "__WXMSW__"
642 #define wxPlatName "wxMSW"
645 #define wxPlatform "__WXMAC__"
646 #define wxPlatName "wxMac"
655 // These should be deprecated in favor of the PlatformInfo tuple built below...
656 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
657 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
658 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
660 // Make a tuple of strings that gives more info about the platform.
661 PyObject
* PlatInfo
= PyList_New(0);
664 #define _AddInfoString(st) \
665 obj = PyString_FromString(st); \
666 PyList_Append(PlatInfo, obj); \
669 _AddInfoString(wxPlatform
);
670 _AddInfoString(wxPlatName
);
672 _AddInfoString("unicode");
674 _AddInfoString("ansi");
678 _AddInfoString("gtk2");
680 _AddInfoString("gtk1");
684 _AddInfoString("wx-assertions-on");
686 _AddInfoString("wx-assertions-off");
689 #undef _AddInfoString
691 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
693 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
699 //---------------------------------------------------------------------------
701 // Python's PyInstance_Check does not return True for instances of new-style
702 // classes. This should get close enough for both new and old classes but I
703 // should re-evaluate the need for doing instance checks...
704 bool wxPyInstance_Check(PyObject
* obj
) {
705 return PyObject_HasAttrString(obj
, "__class__") != 0;
709 // This one checks if the object is an instance of a SWIG proxy class (it has
710 // a .this attribute)
711 bool wxPySwigInstance_Check(PyObject
* obj
) {
712 return PyObject_HasAttrString(obj
, "this") != 0;
715 //---------------------------------------------------------------------------
717 // The stock objects are no longer created when the wx._core_ module is
718 // imported, but only after the app object has been created. The
719 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
720 // objects though various stages of evolution:
722 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
723 // object will be created (otherwise SWIG will just use None.)
725 // pass 2: After the module has been imported and the python proxys have
726 // been created, then set the __class__ to be _wxPyUnbornObject so
727 // it will catch any access to the object and will raise an exception.
729 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
733 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
735 wxPy_ReinitStockObjects(2);
740 static void rsoPass2(const char* name
)
742 static PyObject
* unbornObjectClass
= NULL
;
745 if (unbornObjectClass
== NULL
) {
746 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
747 Py_INCREF(unbornObjectClass
);
750 // Find the object instance
751 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
752 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
753 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
756 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
760 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
766 // Find the object instance
767 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
768 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
769 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
771 // Find the class object and put it back in the instance
772 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
773 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
774 PyObject_SetAttrString(obj
, "__class__", classobj
);
776 // Rebuild the .this swigified pointer with the new value of the C++ pointer
777 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
778 PyObject_SetAttrString(obj
, "this", ptrobj
);
784 void wxPy_ReinitStockObjects(int pass
)
787 // If there is already an App object then wxPython is probably embedded in
788 // a wx C++ application, so there is no need to do all this.
789 static bool embedded
= false;
790 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
794 if (pass
== 3 && embedded
)
798 #define REINITOBJ(name, classname) \
799 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
800 else if (pass == 2) { rsoPass2(#name); } \
801 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
804 #define REINITOBJ2(name, classname) \
806 else if (pass == 2) { rsoPass2(#name); } \
807 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
810 REINITOBJ(wxNORMAL_FONT
, wxFont
);
811 REINITOBJ(wxSMALL_FONT
, wxFont
);
812 REINITOBJ(wxITALIC_FONT
, wxFont
);
813 REINITOBJ(wxSWISS_FONT
, wxFont
);
815 REINITOBJ(wxRED_PEN
, wxPen
);
816 REINITOBJ(wxCYAN_PEN
, wxPen
);
817 REINITOBJ(wxGREEN_PEN
, wxPen
);
818 REINITOBJ(wxBLACK_PEN
, wxPen
);
819 REINITOBJ(wxWHITE_PEN
, wxPen
);
820 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
821 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
822 REINITOBJ(wxGREY_PEN
, wxPen
);
823 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
824 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
826 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
827 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
828 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
829 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
830 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
831 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
832 REINITOBJ(wxRED_BRUSH
, wxBrush
);
833 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
834 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
835 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
837 REINITOBJ(wxBLACK
, wxColour
);
838 REINITOBJ(wxWHITE
, wxColour
);
839 REINITOBJ(wxRED
, wxColour
);
840 REINITOBJ(wxBLUE
, wxColour
);
841 REINITOBJ(wxGREEN
, wxColour
);
842 REINITOBJ(wxCYAN
, wxColour
);
843 REINITOBJ(wxLIGHT_GREY
, wxColour
);
845 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
846 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
847 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
849 REINITOBJ2(wxNullBitmap
, wxBitmap
);
850 REINITOBJ2(wxNullIcon
, wxIcon
);
851 REINITOBJ2(wxNullCursor
, wxCursor
);
852 REINITOBJ2(wxNullPen
, wxPen
);
853 REINITOBJ2(wxNullBrush
, wxBrush
);
854 REINITOBJ2(wxNullPalette
, wxPalette
);
855 REINITOBJ2(wxNullFont
, wxFont
);
856 REINITOBJ2(wxNullColour
, wxColour
);
858 REINITOBJ(wxTheFontList
, wxFontList
);
859 REINITOBJ(wxThePenList
, wxPenList
);
860 REINITOBJ(wxTheBrushList
, wxBrushList
);
861 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
864 REINITOBJ2(wxDefaultValidator
, wxValidator
);
865 REINITOBJ2(wxNullImage
, wxImage
);
866 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
872 //---------------------------------------------------------------------------
874 // Check for existence of a wxApp, setting an exception if there isn't one.
875 // This doesn't need to aquire the GIL because it should only be called from
876 // an %exception before the lock is released.
878 bool wxPyCheckForApp() {
879 if (wxTheApp
!= NULL
)
882 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
887 //---------------------------------------------------------------------------
889 void wxPyUserData_dtor(wxPyUserData
* self
) {
890 if (! wxPyDoingCleanup
) {
891 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
892 Py_DECREF(self
->m_obj
);
894 wxPyEndBlockThreads(blocked
);
899 void wxPyClientData_dtor(wxPyClientData
* self
) {
900 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
901 // may have already garbage collected the object...
902 if (self
->m_incRef
) {
903 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
904 Py_DECREF(self
->m_obj
);
905 wxPyEndBlockThreads(blocked
);
913 // This is called when an OOR controled object is being destroyed. Although
914 // the C++ object is going away there is no way to force the Python object
915 // (and all references to it) to die too. This causes problems (crashes) in
916 // wxPython when a python shadow object attempts to call a C++ method using
917 // the now bogus pointer... So to try and prevent this we'll do a little black
918 // magic and change the class of the python instance to a class that will
919 // raise an exception for any attempt to call methods with it. See
920 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
921 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
923 static PyObject
* deadObjectClass
= NULL
;
925 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
926 if (deadObjectClass
== NULL
) {
927 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
928 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
929 // will lead to a deadlock when it tries to aquire the GIL again.
930 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
931 Py_INCREF(deadObjectClass
);
935 // Only if there is more than one reference to the object and we are
936 // holding the OOR reference:
937 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
938 // bool isInstance = wxPyInstance_Check(self->m_obj);
940 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
942 // Call __del__, if there is one.
943 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
945 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
949 if (PyErr_Occurred())
950 PyErr_Clear(); // just ignore it for now
953 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
955 // Clear the instance's dictionary
958 // put the name of the old class into the instance, and then reset the
959 // class to be the dead class.
960 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
961 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
962 PyDict_SetItemString(dict
, "_name", name
);
963 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
964 //Py_INCREF(deadObjectClass);
970 // m_obj is DECREF'd in the base class dtor...
971 wxPyEndBlockThreads(blocked
);
975 //---------------------------------------------------------------------------
976 // Stuff used by OOR to find the right wxPython class type to return and to
980 // The pointer type map is used when the "pointer" type name generated by SWIG
981 // is not the same as the shadow class name, for example wxPyTreeCtrl
982 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
983 // so we'll just make it a Python dictionary in the wx module's namespace.
984 // (See __wxSetDictionary)
985 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
986 if (! wxPyPtrTypeMap
)
987 wxPyPtrTypeMap
= PyDict_New();
988 PyDict_SetItemString(wxPyPtrTypeMap
,
990 PyString_FromString((char*)ptrName
));
996 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
997 PyObject
* target
= NULL
;
998 bool isEvtHandler
= false;
1001 // If it's derived from wxEvtHandler then there may
1002 // already be a pointer to a Python object that we can use
1004 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
1005 isEvtHandler
= true;
1006 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
1007 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
1009 target
= data
->m_obj
;
1016 // Otherwise make it the old fashioned way by making a new shadow
1017 // object and putting this pointer in it. Look up the class
1018 // heirarchy until we find a class name that is located in the
1020 const wxClassInfo
* info
= source
->GetClassInfo();
1021 wxString name
= info
->GetClassName();
1022 bool exists
= wxPyCheckSwigType(name
);
1023 while (info
&& !exists
) {
1024 info
= info
->GetBaseClass1();
1025 name
= info
->GetClassName();
1026 exists
= wxPyCheckSwigType(name
);
1029 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1030 if (target
&& isEvtHandler
)
1031 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1033 wxString
msg(wxT("wxPython class not found for "));
1034 msg
+= source
->GetClassInfo()->GetClassName();
1035 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1039 } else { // source was NULL so return None.
1040 Py_INCREF(Py_None
); target
= Py_None
;
1046 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1047 PyObject
* target
= NULL
;
1049 if (source
&& wxIsKindOf(source
, wxSizer
)) {
1050 // If it's derived from wxSizer then there may already be a pointer to
1051 // a Python object that we can use in the OOR data.
1052 wxSizer
* sz
= (wxSizer
*)source
;
1053 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1055 target
= data
->m_obj
;
1061 target
= wxPyMake_wxObject(source
, setThisOwn
, false);
1062 if (target
!= Py_None
)
1063 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1069 //---------------------------------------------------------------------------
1072 #ifdef WXP_WITH_THREAD
1073 #if !wxPyUSE_GIL_STATE
1076 unsigned long wxPyGetCurrentThreadId() {
1077 return wxThread::GetCurrentId();
1080 static wxPyThreadState gs_shutdownTState
;
1083 wxPyThreadState
* wxPyGetThreadState() {
1084 if (wxPyTMutex
== NULL
) // Python is shutting down...
1085 return &gs_shutdownTState
;
1087 unsigned long ctid
= wxPyGetCurrentThreadId();
1088 wxPyThreadState
* tstate
= NULL
;
1091 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1092 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1093 if (info
.tid
== ctid
) {
1098 wxPyTMutex
->Unlock();
1099 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1105 void wxPySaveThreadState(PyThreadState
* tstate
) {
1106 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1107 gs_shutdownTState
.tstate
= tstate
;
1110 unsigned long ctid
= wxPyGetCurrentThreadId();
1112 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1113 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1114 if (info
.tid
== ctid
) {
1116 if (info
.tstate
!= tstate
)
1117 wxLogMessage("*** tstate mismatch!???");
1119 info
.tstate
= tstate
; // allow for transient tstates
1120 // Normally it will never change, but apparently COM callbacks
1121 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1122 // tstate which will then be garbage the next time we try to use
1125 wxPyTMutex
->Unlock();
1129 // not found, so add it...
1130 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1131 wxPyTMutex
->Unlock();
1139 // Calls from Python to wxWindows code are wrapped in calls to these
1142 PyThreadState
* wxPyBeginAllowThreads() {
1143 #ifdef WXP_WITH_THREAD
1144 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1145 #if !wxPyUSE_GIL_STATE
1146 wxPySaveThreadState(saved
);
1154 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1155 #ifdef WXP_WITH_THREAD
1156 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1162 // Calls from wxWindows back to Python code, or even any PyObject
1163 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1165 wxPyBlock_t
wxPyBeginBlockThreads() {
1166 #ifdef WXP_WITH_THREAD
1167 #if wxPyUSE_GIL_STATE
1168 PyGILState_STATE state
= PyGILState_Ensure();
1171 PyThreadState
*current
= _PyThreadState_Current
;
1173 // Only block if there wasn't already a tstate, or if the current one is
1174 // not the one we are wanting to change to. This should prevent deadlock
1175 // if there are nested calls to wxPyBeginBlockThreads
1176 wxPyBlock_t blocked
= false;
1177 wxPyThreadState
* tstate
= wxPyGetThreadState();
1178 if (current
!= tstate
->tstate
) {
1179 PyEval_RestoreThread(tstate
->tstate
);
1190 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1191 #ifdef WXP_WITH_THREAD
1192 #if wxPyUSE_GIL_STATE
1193 PyGILState_Release(blocked
);
1195 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1196 // The value of blocked passed in needs to be the same as that returned
1197 // from wxPyBeginBlockThreads at the same nesting level.
1199 PyEval_SaveThread();
1206 //---------------------------------------------------------------------------
1207 // wxPyInputStream and wxPyCBInputStream methods
1210 void wxPyInputStream::close() {
1211 /* do nothing for now */
1214 void wxPyInputStream::flush() {
1215 /* do nothing for now */
1218 bool wxPyInputStream::eof() {
1220 return m_wxis
->Eof();
1225 wxPyInputStream::~wxPyInputStream() {
1233 PyObject
* wxPyInputStream::read(int size
) {
1234 PyObject
* obj
= NULL
;
1236 const int BUFSIZE
= 1024;
1238 // check if we have a real wxInputStream to work with
1240 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1241 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1242 wxPyEndBlockThreads(blocked
);
1247 // read while bytes are available on the stream
1248 while ( m_wxis
->CanRead() ) {
1249 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1250 buf
.UngetAppendBuf(m_wxis
->LastRead());
1253 } else { // Read only size number of characters
1254 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1255 buf
.UngetWriteBuf(m_wxis
->LastRead());
1259 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1260 wxStreamError err
= m_wxis
->GetLastError();
1261 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1262 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1265 // We use only strings for the streams, not unicode
1266 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1268 wxPyEndBlockThreads(blocked
);
1273 PyObject
* wxPyInputStream::readline(int size
) {
1274 PyObject
* obj
= NULL
;
1279 // check if we have a real wxInputStream to work with
1281 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1282 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1283 wxPyEndBlockThreads(blocked
);
1287 // read until \n or byte limit reached
1288 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1289 ch
= m_wxis
->GetC();
1294 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1295 wxStreamError err
= m_wxis
->GetLastError();
1296 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1297 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1300 // We use only strings for the streams, not unicode
1301 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1303 wxPyEndBlockThreads(blocked
);
1308 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1311 // check if we have a real wxInputStream to work with
1313 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1314 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1315 wxPyEndBlockThreads(blocked
);
1320 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1321 pylist
= PyList_New(0);
1322 wxPyEndBlockThreads(blocked
);
1325 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1327 wxPyEndBlockThreads(blocked
);
1331 // read sizehint bytes or until EOF
1333 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1334 PyObject
* s
= this->readline();
1336 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1338 wxPyEndBlockThreads(blocked
);
1341 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1342 PyList_Append(pylist
, s
);
1343 i
+= PyString_Size(s
);
1344 wxPyEndBlockThreads(blocked
);
1348 wxStreamError err
= m_wxis
->GetLastError();
1349 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1350 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1352 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1353 wxPyEndBlockThreads(blocked
);
1361 void wxPyInputStream::seek(int offset
, int whence
) {
1363 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1366 int wxPyInputStream::tell(){
1368 return m_wxis
->TellI();
1375 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1376 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1379 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1381 m_read
= other
.m_read
;
1382 m_seek
= other
.m_seek
;
1383 m_tell
= other
.m_tell
;
1384 m_block
= other
.m_block
;
1391 wxPyCBInputStream::~wxPyCBInputStream() {
1392 wxPyBlock_t blocked
;
1393 if (m_block
) blocked
= wxPyBeginBlockThreads();
1397 if (m_block
) wxPyEndBlockThreads(blocked
);
1401 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1402 wxPyBlock_t blocked
;
1403 if (block
) blocked
= wxPyBeginBlockThreads();
1405 PyObject
* read
= getMethod(py
, "read");
1406 PyObject
* seek
= getMethod(py
, "seek");
1407 PyObject
* tell
= getMethod(py
, "tell");
1410 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1414 if (block
) wxPyEndBlockThreads(blocked
);
1418 if (block
) wxPyEndBlockThreads(blocked
);
1419 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1423 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1424 return wxPyCBInputStream::create(py
, block
);
1427 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1428 return new wxPyCBInputStream(*other
);
1431 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1432 if (!PyObject_HasAttrString(py
, name
))
1434 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1435 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1443 wxFileOffset
wxPyCBInputStream::GetLength() const {
1444 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1445 if (m_seek
&& m_tell
) {
1446 wxFileOffset temp
= self
->OnSysTell();
1447 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1448 self
->OnSysSeek(temp
, wxFromStart
);
1452 return wxInvalidOffset
;
1456 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1460 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1461 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1462 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1466 if ((result
!= NULL
) && PyString_Check(result
)) {
1467 o
= PyString_Size(result
);
1469 m_lasterror
= wxSTREAM_EOF
;
1472 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1477 m_lasterror
= wxSTREAM_READ_ERROR
;
1478 wxPyEndBlockThreads(blocked
);
1482 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1483 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1488 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1489 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1490 PyObject
* arglist
= PyTuple_New(2);
1492 if (sizeof(wxFileOffset
) > sizeof(long))
1493 // wxFileOffset is a 64-bit value...
1494 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1496 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1498 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1501 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1504 wxPyEndBlockThreads(blocked
);
1509 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1510 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1511 PyObject
* arglist
= Py_BuildValue("()");
1512 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1515 if (result
!= NULL
) {
1516 if (PyLong_Check(result
))
1517 o
= PyLong_AsLongLong(result
);
1519 o
= PyInt_AsLong(result
);
1522 wxPyEndBlockThreads(blocked
);
1526 //----------------------------------------------------------------------
1528 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1530 wxPyCallback::wxPyCallback(PyObject
* func
) {
1535 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1536 m_func
= other
.m_func
;
1540 wxPyCallback::~wxPyCallback() {
1541 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1543 wxPyEndBlockThreads(blocked
);
1547 #define wxPy_PRECALLINIT "_preCallInit"
1548 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1550 // This function is used for all events destined for Python event handlers.
1551 void wxPyCallback::EventThunker(wxEvent
& event
) {
1552 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1553 PyObject
* func
= cb
->m_func
;
1557 bool checkSkip
= false;
1559 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1560 wxString className
= event
.GetClassInfo()->GetClassName();
1562 // If the event is one of these types then pass the original
1563 // event object instead of the one passed to us.
1564 if ( className
== wxT("wxPyEvent") ) {
1565 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1566 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1568 else if ( className
== wxT("wxPyCommandEvent") ) {
1569 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1570 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1573 arg
= wxPyConstructObject((void*)&event
, className
);
1579 // "intern" the pre/post method names to speed up the HasAttr
1580 static PyObject
* s_preName
= NULL
;
1581 static PyObject
* s_postName
= NULL
;
1582 if (s_preName
== NULL
) {
1583 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1584 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1587 // Check if the event object needs some preinitialization
1588 if (PyObject_HasAttr(arg
, s_preName
)) {
1589 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1591 Py_DECREF(result
); // result is ignored, but we still need to decref it
1592 PyErr_Clear(); // Just in case...
1598 // Call the event handler, passing the event object
1599 tuple
= PyTuple_New(1);
1600 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1601 result
= PyEval_CallObject(func
, tuple
);
1603 Py_DECREF(result
); // result is ignored, but we still need to decref it
1604 PyErr_Clear(); // Just in case...
1609 // Check if the event object needs some post cleanup
1610 if (PyObject_HasAttr(arg
, s_postName
)) {
1611 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1613 Py_DECREF(result
); // result is ignored, but we still need to decref it
1614 PyErr_Clear(); // Just in case...
1621 // if the event object was one of our special types and
1622 // it had been cloned, then we need to extract the Skipped
1623 // value from the original and set it in the clone.
1624 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1626 event
.Skip(PyInt_AsLong(result
));
1634 wxPyEndBlockThreads(blocked
);
1638 //----------------------------------------------------------------------
1640 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1642 m_self
= other
.m_self
;
1643 m_class
= other
.m_class
;
1651 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1662 #if PYTHON_API_VERSION >= 1011
1664 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1665 // in which the method was defined. Starting with 2.2 it returns
1666 // "class that asked for the method" which seems totally bogus to me
1667 // but apprently it fixes some obscure problem waiting to happen in
1668 // Python. Since the API was not documented Guido and the gang felt
1669 // safe in changing it. Needless to say that totally screwed up the
1670 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1671 // code to find the class where the method is actually defined...
1674 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1678 if (PyType_Check(klass
)) { // new style classes
1679 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1680 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1681 PyObject
*mro
, *res
, *base
, *dict
;
1682 /* Look in tp_dict of types in MRO */
1684 assert(PyTuple_Check(mro
));
1685 n
= PyTuple_GET_SIZE(mro
);
1686 for (i
= 0; i
< n
; i
++) {
1687 base
= PyTuple_GET_ITEM(mro
, i
);
1688 if (PyClass_Check(base
))
1689 dict
= ((PyClassObject
*)base
)->cl_dict
;
1691 assert(PyType_Check(base
));
1692 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1694 assert(dict
&& PyDict_Check(dict
));
1695 res
= PyDict_GetItem(dict
, name
);
1702 else if (PyClass_Check(klass
)) { // old style classes
1703 // This code is borrowed/adapted from class_lookup in classobject.c
1704 PyClassObject
* cp
= (PyClassObject
*)klass
;
1705 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1706 if (value
!= NULL
) {
1707 return (PyObject
*)cp
;
1709 n
= PyTuple_Size(cp
->cl_bases
);
1710 for (i
= 0; i
< n
; i
++) {
1711 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1712 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1724 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1726 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1728 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1730 #else // 2.2 and after, the hard way...
1732 PyObject
* nameo
= PyString_FromString(name
);
1733 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1741 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1742 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1743 self
->m_lastFound
= NULL
;
1745 // If the object (m_self) has an attibute of the given name...
1746 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1747 PyObject
*method
, *klass
;
1748 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1750 // ...and if that attribute is a method, and if that method's class is
1751 // not from a base class...
1752 if (PyMethod_Check(method
) &&
1753 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1754 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1756 // ...then we'll save a pointer to the method so callCallback can call it.
1757 self
->m_lastFound
= method
;
1763 return m_lastFound
!= NULL
;
1767 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1771 result
= callCallbackObj(argTuple
);
1772 if (result
) { // Assumes an integer return type...
1773 retval
= PyInt_AsLong(result
);
1775 PyErr_Clear(); // forget about it if it's not...
1780 // Invoke the Python callable object, returning the raw PyObject return
1781 // value. Caller should DECREF the return value and also manage the GIL.
1782 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1785 // Save a copy of the pointer in case the callback generates another
1786 // callback. In that case m_lastFound will have a different value when
1787 // it gets back here...
1788 PyObject
* method
= m_lastFound
;
1790 result
= PyEval_CallObject(method
, argTuple
);
1791 Py_DECREF(argTuple
);
1800 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1801 cbh
.setSelf(self
, klass
, incref
);
1804 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1805 return cbh
.findCallback(name
);
1808 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1809 return cbh
.callCallback(argTuple
);
1812 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1813 return cbh
.callCallbackObj(argTuple
);
1817 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1818 if (cbh
->m_incRef
) {
1819 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1820 Py_XDECREF(cbh
->m_self
);
1821 Py_XDECREF(cbh
->m_class
);
1822 wxPyEndBlockThreads(blocked
);
1826 //---------------------------------------------------------------------------
1827 //---------------------------------------------------------------------------
1828 // These event classes can be derived from in Python and passed through the event
1829 // system without losing anything. They do this by keeping a reference to
1830 // themselves and some special case handling in wxPyCallback::EventThunker.
1833 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1834 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1835 //Py_INCREF(m_self); // circular loops...
1839 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1840 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1843 wxPyEndBlockThreads(blocked
);
1846 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1847 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1855 wxPyEndBlockThreads(blocked
);
1858 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1864 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1865 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1868 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1869 : wxEvent(winid
, commandType
) {
1873 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1876 SetSelf(evt
.m_self
, true);
1880 wxPyEvent::~wxPyEvent() {
1884 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1885 : wxCommandEvent(commandType
, id
) {
1889 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1890 : wxCommandEvent(evt
)
1892 SetSelf(evt
.m_self
, true);
1896 wxPyCommandEvent::~wxPyCommandEvent() {
1903 //---------------------------------------------------------------------------
1904 //---------------------------------------------------------------------------
1905 // Convert a wxList to a Python List, only works for lists of wxObjects
1907 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1908 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1912 wxNode
* node
= list
->GetFirst();
1914 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1915 pyList
= PyList_New(0);
1917 wxObj
= node
->GetData();
1918 pyObj
= wxPyMake_wxObject(wxObj
,false);
1919 PyList_Append(pyList
, pyObj
);
1920 node
= node
->GetNext();
1922 wxPyEndBlockThreads(blocked
);
1926 //----------------------------------------------------------------------
1928 long wxPyGetWinHandle(wxWindow
* win
) {
1931 return (long)win
->GetHandle();
1934 #if defined(__WXGTK__) || defined(__WXX11)
1935 return (long)GetXWindow(win
);
1939 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1940 return (long)win
->GetHandle();
1946 //----------------------------------------------------------------------
1947 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1948 // included in every file over and over again...
1950 wxString
* wxString_in_helper(PyObject
* source
) {
1951 wxString
* target
= NULL
;
1953 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1954 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1958 PyObject
* uni
= source
;
1959 if (PyString_Check(source
)) {
1960 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1961 if (PyErr_Occurred()) return NULL
;
1963 target
= new wxString();
1964 size_t len
= PyUnicode_GET_SIZE(uni
);
1966 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1967 target
->UngetWriteBuf(len
);
1970 if (PyString_Check(source
))
1973 // Convert to a string object if it isn't already, then to wxString
1974 PyObject
* str
= source
;
1975 if (PyUnicode_Check(source
)) {
1976 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1977 if (PyErr_Occurred()) return NULL
;
1979 else if (!PyString_Check(source
)) {
1980 str
= PyObject_Str(source
);
1981 if (PyErr_Occurred()) return NULL
;
1983 char* tmpPtr
; int tmpSize
;
1984 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1985 target
= new wxString(tmpPtr
, tmpSize
);
1987 if (!PyString_Check(source
))
1989 #endif // wxUSE_UNICODE
1995 // Similar to above except doesn't use "new" and doesn't set an exception
1996 wxString
Py2wxString(PyObject
* source
)
2001 // Convert to a unicode object, if not already, then to a wxString
2002 PyObject
* uni
= source
;
2003 if (!PyUnicode_Check(source
)) {
2004 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
2005 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2007 size_t len
= PyUnicode_GET_SIZE(uni
);
2009 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
2010 target
.UngetWriteBuf();
2013 if (!PyUnicode_Check(source
))
2016 // Convert to a string object if it isn't already, then to wxString
2017 PyObject
* str
= source
;
2018 if (PyUnicode_Check(source
)) {
2019 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
2020 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2022 else if (!PyString_Check(source
)) {
2023 str
= PyObject_Str(source
);
2024 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2026 char* tmpPtr
; int tmpSize
;
2027 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
2028 target
= wxString(tmpPtr
, tmpSize
);
2030 if (!PyString_Check(source
))
2032 #endif // wxUSE_UNICODE
2038 // Make either a Python String or Unicode object, depending on build mode
2039 PyObject
* wx2PyString(const wxString
& src
)
2043 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
2045 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
2052 void wxSetDefaultPyEncoding(const char* encoding
)
2054 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
2057 const char* wxGetDefaultPyEncoding()
2059 return wxPyDefaultEncoding
;
2062 //----------------------------------------------------------------------
2065 byte
* byte_LIST_helper(PyObject
* source
) {
2066 if (!PyList_Check(source
)) {
2067 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2070 int count
= PyList_Size(source
);
2071 byte
* temp
= new byte
[count
];
2073 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2076 for (int x
=0; x
<count
; x
++) {
2077 PyObject
* o
= PyList_GetItem(source
, x
);
2078 if (! PyInt_Check(o
)) {
2079 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2082 temp
[x
] = (byte
)PyInt_AsLong(o
);
2088 int* int_LIST_helper(PyObject
* source
) {
2089 if (!PyList_Check(source
)) {
2090 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2093 int count
= PyList_Size(source
);
2094 int* temp
= new int[count
];
2096 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2099 for (int x
=0; x
<count
; x
++) {
2100 PyObject
* o
= PyList_GetItem(source
, x
);
2101 if (! PyInt_Check(o
)) {
2102 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2105 temp
[x
] = PyInt_AsLong(o
);
2111 long* long_LIST_helper(PyObject
* source
) {
2112 if (!PyList_Check(source
)) {
2113 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2116 int count
= PyList_Size(source
);
2117 long* temp
= new long[count
];
2119 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2122 for (int x
=0; x
<count
; x
++) {
2123 PyObject
* o
= PyList_GetItem(source
, x
);
2124 if (! PyInt_Check(o
)) {
2125 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2128 temp
[x
] = PyInt_AsLong(o
);
2134 char** string_LIST_helper(PyObject
* source
) {
2135 if (!PyList_Check(source
)) {
2136 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2139 int count
= PyList_Size(source
);
2140 char** temp
= new char*[count
];
2142 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2145 for (int x
=0; x
<count
; x
++) {
2146 PyObject
* o
= PyList_GetItem(source
, x
);
2147 if (! PyString_Check(o
)) {
2148 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2151 temp
[x
] = PyString_AsString(o
);
2156 //--------------------------------
2157 // Part of patch from Tim Hochberg
2158 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2159 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2160 point
->x
= PyInt_AS_LONG(o1
);
2161 point
->y
= PyInt_AS_LONG(o2
);
2164 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2165 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2166 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2169 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2170 // Disallow instances because they can cause havok
2173 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2174 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2175 point
->x
= PyInt_AsLong(o1
);
2176 point
->y
= PyInt_AsLong(o2
);
2183 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2184 // Putting all of the declarations here allows
2185 // us to put the error handling all in one place.
2188 PyObject
*o
, *o1
, *o2
;
2189 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2191 if (!PySequence_Check(source
)) {
2195 // The length of the sequence is returned in count.
2196 *count
= PySequence_Length(source
);
2201 temp
= new wxPoint
[*count
];
2203 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2206 for (x
=0; x
<*count
; x
++) {
2207 // Get an item: try fast way first.
2209 o
= PySequence_Fast_GET_ITEM(source
, x
);
2212 o
= PySequence_GetItem(source
, x
);
2218 // Convert o to wxPoint.
2219 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2220 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2221 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2222 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2223 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2227 else if (wxPySwigInstance_Check(o
)) {
2229 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2234 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2235 o1
= PySequence_GetItem(o
, 0);
2236 o2
= PySequence_GetItem(o
, 1);
2237 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2261 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2265 //------------------------------
2268 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2269 if (!PyList_Check(source
)) {
2270 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2273 int count
= PyList_Size(source
);
2274 wxBitmap
** temp
= new wxBitmap
*[count
];
2276 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2279 for (int x
=0; x
<count
; x
++) {
2280 PyObject
* o
= PyList_GetItem(source
, x
);
2281 if (wxPySwigInstance_Check(o
)) {
2283 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2284 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2290 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2299 wxString
* wxString_LIST_helper(PyObject
* source
) {
2300 if (!PyList_Check(source
)) {
2301 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2304 int count
= PyList_Size(source
);
2305 wxString
* temp
= new wxString
[count
];
2307 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2310 for (int x
=0; x
<count
; x
++) {
2311 PyObject
* o
= PyList_GetItem(source
, x
);
2312 #if PYTHON_API_VERSION >= 1009
2313 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2314 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2318 if (! PyString_Check(o
)) {
2319 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2324 wxString
* pStr
= wxString_in_helper(o
);
2332 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2333 if (!PyList_Check(source
)) {
2334 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2337 int count
= PyList_Size(source
);
2338 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2340 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2343 for (int x
=0; x
<count
; x
++) {
2344 PyObject
* o
= PyList_GetItem(source
, x
);
2345 if (wxPySwigInstance_Check(o
)) {
2346 wxAcceleratorEntry
* ae
;
2347 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2348 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2353 else if (PyTuple_Check(o
)) {
2354 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2355 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2356 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2357 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2360 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2368 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2369 if (!PyList_Check(source
)) {
2370 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2373 int count
= PyList_Size(source
);
2374 wxPen
** temp
= new wxPen
*[count
];
2376 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2379 for (int x
=0; x
<count
; x
++) {
2380 PyObject
* o
= PyList_GetItem(source
, x
);
2381 if (wxPySwigInstance_Check(o
)) {
2383 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2385 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2392 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2400 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2401 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2404 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2408 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2409 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2412 o1
= PySequence_GetItem(source
, 0);
2413 o2
= PySequence_GetItem(source
, 1);
2416 *i1
= PyInt_AsLong(o1
);
2417 *i2
= PyInt_AsLong(o2
);
2427 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2428 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2429 PyObject
*o1
, *o2
, *o3
, *o4
;
2431 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2435 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2436 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2437 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2438 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2441 o1
= PySequence_GetItem(source
, 0);
2442 o2
= PySequence_GetItem(source
, 1);
2443 o3
= PySequence_GetItem(source
, 2);
2444 o4
= PySequence_GetItem(source
, 3);
2447 *i1
= PyInt_AsLong(o1
);
2448 *i2
= PyInt_AsLong(o2
);
2449 *i3
= PyInt_AsLong(o3
);
2450 *i4
= PyInt_AsLong(o4
);
2462 //----------------------------------------------------------------------
2464 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2468 if (wxPySwigInstance_Check(source
) &&
2469 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2473 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2479 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2481 if (source
== Py_None
) {
2482 **obj
= wxSize(-1,-1);
2485 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2489 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2491 if (source
== Py_None
) {
2492 **obj
= wxPoint(-1,-1);
2495 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2500 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2502 if (source
== Py_None
) {
2503 **obj
= wxRealPoint(-1,-1);
2507 // If source is an object instance then it may already be the right type
2508 if (wxPySwigInstance_Check(source
)) {
2510 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2515 // otherwise a 2-tuple of floats is expected
2516 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2517 PyObject
* o1
= PySequence_GetItem(source
, 0);
2518 PyObject
* o2
= PySequence_GetItem(source
, 1);
2519 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2524 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2531 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2537 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2539 if (source
== Py_None
) {
2540 **obj
= wxRect(-1,-1,-1,-1);
2544 // If source is an object instance then it may already be the right type
2545 if (wxPySwigInstance_Check(source
)) {
2547 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2552 // otherwise a 4-tuple of integers is expected
2553 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2554 PyObject
* o1
= PySequence_GetItem(source
, 0);
2555 PyObject
* o2
= PySequence_GetItem(source
, 1);
2556 PyObject
* o3
= PySequence_GetItem(source
, 2);
2557 PyObject
* o4
= PySequence_GetItem(source
, 3);
2558 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2559 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2566 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2567 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2576 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2582 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2584 if (source
== Py_None
) {
2585 **obj
= wxNullColour
;
2589 // If source is an object instance then it may already be the right type
2590 if (wxPySwigInstance_Check(source
)) {
2592 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2597 // otherwise check for a string
2598 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2599 wxString spec
= Py2wxString(source
);
2600 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2601 long red
, green
, blue
;
2602 red
= green
= blue
= 0;
2603 spec
.Mid(1,2).ToLong(&red
, 16);
2604 spec
.Mid(3,2).ToLong(&green
, 16);
2605 spec
.Mid(5,2).ToLong(&blue
, 16);
2607 **obj
= wxColour(red
, green
, blue
);
2610 else { // it's a colour name
2611 **obj
= wxColour(spec
);
2615 // last chance: 3-tuple of integers is expected
2616 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2617 PyObject
* o1
= PySequence_GetItem(source
, 0);
2618 PyObject
* o2
= PySequence_GetItem(source
, 1);
2619 PyObject
* o3
= PySequence_GetItem(source
, 2);
2620 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2626 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2634 PyErr_SetString(PyExc_TypeError
,
2635 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2640 bool wxColour_typecheck(PyObject
* source
) {
2642 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2645 if (PyString_Check(source
) || PyUnicode_Check(source
))
2653 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2655 if (source
== Py_None
) {
2656 **obj
= wxPoint2D(-1,-1);
2660 // If source is an object instance then it may already be the right type
2661 if (wxPySwigInstance_Check(source
)) {
2663 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2668 // otherwise a length-2 sequence of floats is expected
2669 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2670 PyObject
* o1
= PySequence_GetItem(source
, 0);
2671 PyObject
* o2
= PySequence_GetItem(source
, 1);
2672 // This should really check for floats, not numbers -- but that would break code.
2673 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2678 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2684 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2689 //----------------------------------------------------------------------
2691 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2693 PyObject
* list
= PyList_New(0);
2694 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2696 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2698 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2700 PyList_Append(list
, str
);
2707 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2709 PyObject
* list
= PyList_New(0);
2710 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2711 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2712 PyList_Append(list
, number
);
2719 //----------------------------------------------------------------------
2720 //----------------------------------------------------------------------