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"
18 #include "wx/wxPython/swigver.h"
19 #include "wx/wxPython/twoitem.h"
22 #include <wx/msw/private.h>
23 #include <wx/msw/winundef.h>
24 #include <wx/msw/msvcrt.h>
31 #include <gdk/gdkprivate.h>
32 #include <wx/gtk/win_gtk.h>
33 #define GetXWindow(wxwin) (wxwin)->m_wxwindow ? \
34 GDK_WINDOW_XWINDOW(GTK_PIZZA((wxwin)->m_wxwindow)->bin_window) : \
35 GDK_WINDOW_XWINDOW((wxwin)->m_widget->window)
40 #include "wx/x11/privx.h"
41 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
45 #include <wx/mac/private.h>
48 #include <wx/clipbrd.h>
49 #include <wx/mimetype.h>
52 //----------------------------------------------------------------------
54 #if PYTHON_API_VERSION < 1009 && wxUSE_UNICODE
55 #error Python must support Unicode to use wxWindows Unicode
58 //----------------------------------------------------------------------
60 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
61 bool wxPyDoCleanup
= false;
62 bool wxPyDoingCleanup
= false;
65 #ifdef WXP_WITH_THREAD
66 #if !wxPyUSE_GIL_STATE
67 struct wxPyThreadState
{
69 PyThreadState
* tstate
;
71 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
72 : tid(_tid
), tstate(_tstate
) {}
75 #include <wx/dynarray.h>
76 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
77 #include <wx/arrimpl.cpp>
78 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
80 wxPyThreadStateArray
* wxPyTStates
= NULL
;
81 wxMutex
* wxPyTMutex
= NULL
;
87 #define DEFAULTENCODING_SIZE 64
88 static char wxPyDefaultEncoding
[DEFAULTENCODING_SIZE
] = "ascii";
90 static PyObject
* wxPython_dict
= NULL
;
91 static PyObject
* wxPyAssertionError
= NULL
;
92 static PyObject
* wxPyNoAppError
= NULL
;
94 PyObject
* wxPyPtrTypeMap
= NULL
;
97 #ifdef __WXMSW__ // If building for win32...
98 //----------------------------------------------------------------------
99 // This gets run when the DLL is loaded. We just need to save a handle.
100 //----------------------------------------------------------------------
104 HINSTANCE hinstDLL
, // handle to DLL module
105 DWORD fdwReason
, // reason for calling function
106 LPVOID lpvReserved
// reserved
109 // If wxPython is embedded in another wxWidgets app then
110 // the instance has already been set.
111 if (! wxGetInstance())
112 wxSetInstance(hinstDLL
);
117 //----------------------------------------------------------------------
118 // Classes for implementing the wxp main application shell.
119 //----------------------------------------------------------------------
121 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
125 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
126 m_startupComplete
= false;
130 wxPyApp::~wxPyApp() {
132 wxApp::SetInstance(NULL
);
136 // This one isn't acutally called... We fake it with _BootstrapApp
137 bool wxPyApp::OnInit() {
142 int wxPyApp::MainLoop() {
145 DeletePendingObjects();
146 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
148 if ( m_exitOnFrameDelete
== Later
) {
149 m_exitOnFrameDelete
= Yes
;
152 retval
= wxApp::MainLoop();
159 bool wxPyApp::OnInitGui() {
161 wxApp::OnInitGui(); // in this case always call the base class version
162 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
163 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
164 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
165 wxPyEndBlockThreads(blocked
);
170 int wxPyApp::OnExit() {
172 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
173 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
174 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
175 wxPyEndBlockThreads(blocked
);
176 wxApp::OnExit(); // in this case always call the base class version
182 void wxPyApp::ExitMainLoop() {
184 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
185 if ((found
= wxPyCBH_findCallback(m_myInst
, "ExitMainLoop")))
186 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
187 wxPyEndBlockThreads(blocked
);
189 wxApp::ExitMainLoop();
194 void wxPyApp::OnAssertFailure(const wxChar
*file
,
200 // if we're not fully initialized then just log the error
201 if (! m_startupComplete
) {
204 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
207 buf
<< wxT(" in ") << func
<< wxT("()");
209 buf
<< wxT(": ") << msg
;
215 // If the OnAssert is overloaded in the Python class then call it...
217 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
218 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
219 PyObject
* fso
= wx2PyString(file
);
220 PyObject
* cso
= wx2PyString(file
);
223 mso
= wx2PyString(file
);
225 mso
= Py_None
; Py_INCREF(Py_None
);
227 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
232 wxPyEndBlockThreads(blocked
);
234 // ...otherwise do our own thing with it
237 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
240 // turn it into a Python exception?
241 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
244 buf
.Printf(wxT("C++ assertion \"%s\" failed at %s(%d)"), cond
, file
, line
);
246 buf
<< wxT(" in ") << func
<< wxT("()");
248 buf
<< wxT(": ") << msg
;
252 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
253 PyObject
* s
= wx2PyString(buf
);
254 PyErr_SetObject(wxPyAssertionError
, s
);
256 wxPyEndBlockThreads(blocked
);
258 // Now when control returns to whatever API wrapper was called from
259 // Python it should detect that an exception is set and will return
260 // NULL, signalling the exception to Python.
263 // Send it to the normal log destination, but only if
264 // not _DIALOG because it will call this too
265 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
268 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
271 buf
<< wxT(" in ") << func
<< wxT("()");
273 buf
<< wxT(": ") << msg
;
277 // do the normal wx assert dialog?
278 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
279 wxApp::OnAssertFailure(file
, line
, func
, cond
, msg
);
284 // For catching Apple Events
285 void wxPyApp::MacOpenFile(const wxString
&fileName
)
287 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
288 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
289 PyObject
* s
= wx2PyString(fileName
);
290 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
293 wxPyEndBlockThreads(blocked
);
296 void wxPyApp::MacPrintFile(const wxString
&fileName
)
298 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
299 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
300 PyObject
* s
= wx2PyString(fileName
);
301 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
304 wxPyEndBlockThreads(blocked
);
307 void wxPyApp::MacNewFile()
309 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
310 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
311 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
312 wxPyEndBlockThreads(blocked
);
315 void wxPyApp::MacReopenApp()
317 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
318 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
319 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
320 wxPyEndBlockThreads(blocked
);
325 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
327 return s_macSupportPCMenuShortcuts
;
334 long wxPyApp::GetMacAboutMenuItemId() {
336 return s_macAboutMenuItemId
;
343 long wxPyApp::GetMacPreferencesMenuItemId() {
345 return s_macPreferencesMenuItemId
;
352 long wxPyApp::GetMacExitMenuItemId() {
354 return s_macExitMenuItemId
;
361 wxString
wxPyApp::GetMacHelpMenuTitleName() {
363 return s_macHelpMenuTitleName
;
365 return wxEmptyString
;
370 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
372 s_macSupportPCMenuShortcuts
= val
;
377 void wxPyApp::SetMacAboutMenuItemId(long val
) {
379 s_macAboutMenuItemId
= val
;
384 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
386 s_macPreferencesMenuItemId
= val
;
391 void wxPyApp::SetMacExitMenuItemId(long val
) {
393 s_macExitMenuItemId
= val
;
398 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
400 s_macHelpMenuTitleName
= val
;
405 // This finishes the initialization of wxWindows and then calls the OnInit
406 // that should be present in the derived (Python) class.
407 void wxPyApp::_BootstrapApp()
409 static bool haveInitialized
= false;
412 PyObject
* retval
= NULL
;
413 PyObject
* pyint
= NULL
;
416 // Only initialize wxWidgets once
417 if (! haveInitialized
) {
419 // Get any command-line args passed to this program from the sys module
422 blocked
= wxPyBeginBlockThreads();
424 PyObject
* sysargv
= PySys_GetObject("argv");
425 PyObject
* executable
= PySys_GetObject("executable");
427 if (sysargv
!= NULL
&& executable
!= NULL
) {
428 argc
= PyList_Size(sysargv
) + 1;
429 argv
= new char*[argc
+1];
430 argv
[0] = strdup(PyString_AsString(executable
));
432 for(x
=1; x
<argc
; x
++) {
433 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
434 argv
[x
] = strdup(PyString_AsString(pyArg
));
438 wxPyEndBlockThreads(blocked
);
440 // Initialize wxWidgets
441 result
= wxEntryStart(argc
, argv
);
442 // wxApp takes ownership of the argv array, don't delete it here
444 blocked
= wxPyBeginBlockThreads();
446 PyErr_SetString(PyExc_SystemError
,
447 "wxEntryStart failed, unable to initialize wxWidgets!"
449 " (Is DISPLAY set properly?)"
455 // On wxGTK the locale will be changed to match the system settings,
456 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
457 // for the floating point conversions and such to work right.
458 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
459 setlocale(LC_NUMERIC
, "C");
462 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
464 wxPyEndBlockThreads(blocked
);
465 haveInitialized
= true;
473 // It's now ok to generate exceptions for assertion errors.
474 wxPythonApp
->SetStartupComplete(true);
477 // Call the Python wxApp's OnPreInit and OnInit functions
478 blocked
= wxPyBeginBlockThreads();
479 if (wxPyCBH_findCallback(m_myInst
, "OnPreInit")) {
480 PyObject
* method
= m_myInst
.GetLastFound();
481 PyObject
* argTuple
= PyTuple_New(0);
482 retval
= PyEval_CallObject(method
, argTuple
);
483 m_myInst
.clearRecursionGuard(method
);
489 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
491 PyObject
* method
= m_myInst
.GetLastFound();
492 PyObject
* argTuple
= PyTuple_New(0);
493 retval
= PyEval_CallObject(method
, argTuple
);
494 m_myInst
.clearRecursionGuard(method
);
500 pyint
= PyNumber_Int(retval
);
502 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
505 result
= PyInt_AS_LONG(pyint
);
508 // Is it okay if there is no OnInit? Probably so...
513 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
520 wxPyEndBlockThreads(blocked
);
523 //---------------------------------------------------------------------
524 //----------------------------------------------------------------------
528 static char* wxPyCopyCString(const wxChar
* src
)
530 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
531 size_t len
= strlen(buff
);
532 char* dest
= new char[len
+1];
538 static char* wxPyCopyCString(const char* src
) // we need a char version too
540 size_t len
= strlen(src
);
541 char* dest
= new char[len
+1];
547 static wxChar
* wxPyCopyWString(const char *src
)
549 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
550 wxString
str(src
, *wxConvCurrent
);
551 return copystring(str
);
555 static wxChar
* wxPyCopyWString(const wxChar
*src
)
557 return copystring(src
);
563 inline const char* dropwx(const char* name
) {
564 if (name
[0] == 'w' && name
[1] == 'x')
570 //----------------------------------------------------------------------
572 // This function is called when the wx._core_ module is imported to do some
573 // initial setup. (Before there is a wxApp object.) The rest happens in
574 // wxPyApp::_BootstrapApp
575 void __wxPyPreStart(PyObject
* moduleDict
)
579 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
580 // | _CRTDBG_CHECK_ALWAYS_DF
581 // | _CRTDBG_DELAY_FREE_MEM_DF
585 #ifdef WXP_WITH_THREAD
586 #if wxPyUSE_GIL_STATE
587 PyEval_InitThreads();
589 PyEval_InitThreads();
590 wxPyTStates
= new wxPyThreadStateArray
;
591 wxPyTMutex
= new wxMutex
;
593 // Save the current (main) thread state in our array
594 PyThreadState
* tstate
= wxPyBeginAllowThreads();
595 wxPyEndAllowThreads(tstate
);
599 // Ensure that the build options in the DLL (or whatever) match this build
600 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
602 wxInitAllImageHandlers();
607 void __wxPyCleanup() {
608 wxPyDoingCleanup
= true;
610 wxPyDoCleanup
= false;
613 #ifdef WXP_WITH_THREAD
614 #if !wxPyUSE_GIL_STATE
617 wxPyTStates
->Empty();
625 // Save a reference to the dictionary of the wx._core module, and inject
626 // a few more things into it.
627 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
630 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
633 if (!PyDict_Check(wxPython_dict
)) {
634 PyErr_SetString(PyExc_TypeError
,
635 "_wxPySetDictionary must have dictionary object!");
639 if (! wxPyPtrTypeMap
)
640 wxPyPtrTypeMap
= PyDict_New();
641 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
643 // Create an exception object to use for wxASSERTions
644 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
645 PyExc_AssertionError
, NULL
);
646 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
648 // Create an exception object to use when the app object hasn't been created yet
649 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
650 PyExc_RuntimeError
, NULL
);
651 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
656 #define wxPlatform "__WXMOTIF__"
657 #define wxPlatName "wxMotif"
660 #define wxPlatform "__WXX11__"
661 #define wxPlatName "wxX11"
664 #define wxPlatform "__WXGTK__"
665 #define wxPlatName "wxGTK"
668 #define wxPlatform "__WXMSW__"
669 #define wxPlatName "wxMSW"
672 #define wxPlatform "__WXMAC__"
673 #define wxPlatName "wxMac"
682 // These should be deprecated in favor of the PlatformInfo tuple built below...
683 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
684 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
685 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
687 // Make a tuple of strings that gives more info about the platform.
688 PyObject
* PlatInfo
= PyList_New(0);
691 #define _AddInfoString(st) \
692 obj = PyString_FromString(st); \
693 PyList_Append(PlatInfo, obj); \
696 _AddInfoString(wxPlatform
);
697 _AddInfoString(wxPlatName
);
699 _AddInfoString("unicode");
701 _AddInfoString("ansi");
705 _AddInfoString("gtk2");
707 _AddInfoString("gtk1");
711 _AddInfoString("wx-assertions-on");
713 _AddInfoString("wx-assertions-off");
715 _AddInfoString(wxPy_SWIG_VERSION
);
717 #undef _AddInfoString
719 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
721 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
728 //---------------------------------------------------------------------------
730 // Check for existence of a wxApp, setting an exception if there isn't one.
731 // This doesn't need to aquire the GIL because it should only be called from
732 // an %exception before the lock is released.
734 bool wxPyCheckForApp() {
735 if (wxTheApp
!= NULL
)
738 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
743 //---------------------------------------------------------------------------
745 void wxPyUserData_dtor(wxPyUserData
* self
) {
746 if (! wxPyDoingCleanup
) {
747 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
748 Py_DECREF(self
->m_obj
);
750 wxPyEndBlockThreads(blocked
);
755 void wxPyClientData_dtor(wxPyClientData
* self
) {
756 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
757 // may have already garbage collected the object...
758 if (self
->m_incRef
) {
759 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
760 Py_DECREF(self
->m_obj
);
761 wxPyEndBlockThreads(blocked
);
769 // This is called when an OOR controled object is being destroyed. Although
770 // the C++ object is going away there is no way to force the Python object
771 // (and all references to it) to die too. This causes problems (crashes) in
772 // wxPython when a python shadow object attempts to call a C++ method using
773 // the now bogus pointer... So to try and prevent this we'll do a little black
774 // magic and change the class of the python instance to a class that will
775 // raise an exception for any attempt to call methods with it. See
776 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
777 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
779 static PyObject
* deadObjectClass
= NULL
;
781 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
782 if (deadObjectClass
== NULL
) {
783 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
784 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
785 // will lead to a deadlock when it tries to aquire the GIL again.
786 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
787 Py_INCREF(deadObjectClass
);
791 // Only if there is more than one reference to the object and we are
792 // holding the OOR reference:
793 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
794 // bool isInstance = wxPyInstance_Check(self->m_obj);
796 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
798 // Call __del__, if there is one.
799 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
801 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
805 if (PyErr_Occurred())
806 PyErr_Clear(); // just ignore it for now
809 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
811 // Clear the instance's dictionary
814 // put the name of the old class into the instance, and then reset the
815 // class to be the dead class.
816 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
817 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
818 PyDict_SetItemString(dict
, "_name", name
);
819 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
820 //Py_INCREF(deadObjectClass);
826 // m_obj is DECREF'd in the base class dtor...
827 wxPyEndBlockThreads(blocked
);
831 //---------------------------------------------------------------------------
832 // Stuff used by OOR to find the right wxPython class type to return and to
836 // The pointer type map is used when the "pointer" type name generated by SWIG
837 // is not the same as the shadow class name, for example wxPyTreeCtrl
838 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
839 // so we'll just make it a Python dictionary in the wx module's namespace.
840 // (See __wxSetDictionary)
841 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
842 if (! wxPyPtrTypeMap
)
843 wxPyPtrTypeMap
= PyDict_New();
844 PyDict_SetItemString(wxPyPtrTypeMap
,
846 PyString_FromString((char*)ptrName
));
852 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
853 PyObject
* target
= NULL
;
854 bool isEvtHandler
= false;
855 bool isSizer
= false;
858 // If it's derived from wxEvtHandler then there may
859 // already be a pointer to a Python object that we can use
861 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
863 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
864 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
866 target
= data
->m_obj
;
872 // Also check for wxSizer
873 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
875 wxSizer
* sz
= (wxSizer
*)source
;
876 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
878 target
= data
->m_obj
;
885 // Otherwise make it the old fashioned way by making a new shadow
886 // object and putting this pointer in it. Look up the class
887 // heirarchy until we find a class name that is located in the
889 const wxClassInfo
* info
= source
->GetClassInfo();
890 wxString name
= info
->GetClassName();
891 bool exists
= wxPyCheckSwigType(name
);
892 while (info
&& !exists
) {
893 info
= info
->GetBaseClass1();
894 name
= info
->GetClassName();
895 exists
= wxPyCheckSwigType(name
);
898 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
899 if (target
&& isEvtHandler
)
900 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
901 if (target
&& isSizer
)
902 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
904 wxString
msg(wxT("wxPython class not found for "));
905 msg
+= source
->GetClassInfo()->GetClassName();
906 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
910 } else { // source was NULL so return None.
911 Py_INCREF(Py_None
); target
= Py_None
;
917 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
919 return wxPyMake_wxObject(source
, setThisOwn
);
923 //---------------------------------------------------------------------------
926 #ifdef WXP_WITH_THREAD
927 #if !wxPyUSE_GIL_STATE
930 unsigned long wxPyGetCurrentThreadId() {
931 return wxThread::GetCurrentId();
934 static wxPyThreadState gs_shutdownTState
;
937 wxPyThreadState
* wxPyGetThreadState() {
938 if (wxPyTMutex
== NULL
) // Python is shutting down...
939 return &gs_shutdownTState
;
941 unsigned long ctid
= wxPyGetCurrentThreadId();
942 wxPyThreadState
* tstate
= NULL
;
945 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
946 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
947 if (info
.tid
== ctid
) {
952 wxPyTMutex
->Unlock();
953 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
959 void wxPySaveThreadState(PyThreadState
* tstate
) {
960 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
961 gs_shutdownTState
.tstate
= tstate
;
964 unsigned long ctid
= wxPyGetCurrentThreadId();
966 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
967 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
968 if (info
.tid
== ctid
) {
970 if (info
.tstate
!= tstate
)
971 wxLogMessage("*** tstate mismatch!???");
973 info
.tstate
= tstate
; // allow for transient tstates
974 // Normally it will never change, but apparently COM callbacks
975 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
976 // tstate which will then be garbage the next time we try to use
979 wxPyTMutex
->Unlock();
983 // not found, so add it...
984 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
985 wxPyTMutex
->Unlock();
993 // Calls from Python to wxWindows code are wrapped in calls to these
996 PyThreadState
* wxPyBeginAllowThreads() {
997 #ifdef WXP_WITH_THREAD
998 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
999 #if !wxPyUSE_GIL_STATE
1000 wxPySaveThreadState(saved
);
1008 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1009 #ifdef WXP_WITH_THREAD
1010 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1016 // Calls from wxWindows back to Python code, or even any PyObject
1017 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1019 wxPyBlock_t
wxPyBeginBlockThreads() {
1020 #ifdef WXP_WITH_THREAD
1021 if (! Py_IsInitialized()) {
1022 return (wxPyBlock_t
)0;
1024 #if wxPyUSE_GIL_STATE
1025 PyGILState_STATE state
= PyGILState_Ensure();
1028 PyThreadState
*current
= _PyThreadState_Current
;
1030 // Only block if there wasn't already a tstate, or if the current one is
1031 // not the one we are wanting to change to. This should prevent deadlock
1032 // if there are nested calls to wxPyBeginBlockThreads
1033 wxPyBlock_t blocked
= false;
1034 wxPyThreadState
* tstate
= wxPyGetThreadState();
1035 if (current
!= tstate
->tstate
) {
1036 PyEval_RestoreThread(tstate
->tstate
);
1042 return (wxPyBlock_t
)0;
1047 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1048 #ifdef WXP_WITH_THREAD
1049 if (! Py_IsInitialized()) {
1052 #if wxPyUSE_GIL_STATE
1053 PyGILState_Release(blocked
);
1055 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1056 // The value of blocked passed in needs to be the same as that returned
1057 // from wxPyBeginBlockThreads at the same nesting level.
1059 PyEval_SaveThread();
1066 //---------------------------------------------------------------------------
1067 // wxPyInputStream and wxPyCBInputStream methods
1070 void wxPyInputStream::close() {
1071 /* do nothing for now */
1074 void wxPyInputStream::flush() {
1075 /* do nothing for now */
1078 bool wxPyInputStream::eof() {
1080 return m_wxis
->Eof();
1085 wxPyInputStream::~wxPyInputStream() {
1093 PyObject
* wxPyInputStream::read(int size
) {
1094 PyObject
* obj
= NULL
;
1096 const int BUFSIZE
= 1024;
1098 // check if we have a real wxInputStream to work with
1100 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1101 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1102 wxPyEndBlockThreads(blocked
);
1107 // read while bytes are available on the stream
1108 while ( m_wxis
->CanRead() ) {
1109 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1110 buf
.UngetAppendBuf(m_wxis
->LastRead());
1113 } else { // Read only size number of characters
1114 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1115 buf
.UngetWriteBuf(m_wxis
->LastRead());
1119 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1120 wxStreamError err
= m_wxis
->GetLastError();
1121 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1122 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1125 // We use only strings for the streams, not unicode
1126 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1128 wxPyEndBlockThreads(blocked
);
1133 PyObject
* wxPyInputStream::readline(int size
) {
1134 PyObject
* obj
= NULL
;
1139 // check if we have a real wxInputStream to work with
1141 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1142 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1143 wxPyEndBlockThreads(blocked
);
1147 // read until \n or byte limit reached
1148 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1149 ch
= m_wxis
->GetC();
1154 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1155 wxStreamError err
= m_wxis
->GetLastError();
1156 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1157 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1160 // We use only strings for the streams, not unicode
1161 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1163 wxPyEndBlockThreads(blocked
);
1168 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1171 // check if we have a real wxInputStream to work with
1173 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1174 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1175 wxPyEndBlockThreads(blocked
);
1180 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1181 pylist
= PyList_New(0);
1182 wxPyEndBlockThreads(blocked
);
1185 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1187 wxPyEndBlockThreads(blocked
);
1191 // read sizehint bytes or until EOF
1193 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1194 PyObject
* s
= this->readline();
1196 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1198 wxPyEndBlockThreads(blocked
);
1201 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1202 PyList_Append(pylist
, s
);
1203 i
+= PyString_Size(s
);
1204 wxPyEndBlockThreads(blocked
);
1208 wxStreamError err
= m_wxis
->GetLastError();
1209 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1210 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1212 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1213 wxPyEndBlockThreads(blocked
);
1221 void wxPyInputStream::seek(int offset
, int whence
) {
1223 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1226 int wxPyInputStream::tell(){
1228 return m_wxis
->TellI();
1235 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1236 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1239 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1241 m_read
= other
.m_read
;
1242 m_seek
= other
.m_seek
;
1243 m_tell
= other
.m_tell
;
1244 m_block
= other
.m_block
;
1251 wxPyCBInputStream::~wxPyCBInputStream() {
1252 wxPyBlock_t blocked
;
1253 if (m_block
) blocked
= wxPyBeginBlockThreads();
1257 if (m_block
) wxPyEndBlockThreads(blocked
);
1261 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1262 wxPyBlock_t blocked
;
1263 if (block
) blocked
= wxPyBeginBlockThreads();
1265 PyObject
* read
= getMethod(py
, "read");
1266 PyObject
* seek
= getMethod(py
, "seek");
1267 PyObject
* tell
= getMethod(py
, "tell");
1270 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1274 if (block
) wxPyEndBlockThreads(blocked
);
1278 if (block
) wxPyEndBlockThreads(blocked
);
1279 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1283 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1284 return wxPyCBInputStream::create(py
, block
);
1287 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1288 return new wxPyCBInputStream(*other
);
1291 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1292 if (!PyObject_HasAttrString(py
, name
))
1294 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1295 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1303 wxFileOffset
wxPyCBInputStream::GetLength() const {
1304 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1305 if (m_seek
&& m_tell
) {
1306 wxFileOffset temp
= self
->OnSysTell();
1307 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1308 self
->OnSysSeek(temp
, wxFromStart
);
1312 return wxInvalidOffset
;
1316 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1320 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1321 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1322 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1326 if ((result
!= NULL
) && PyString_Check(result
)) {
1327 o
= PyString_Size(result
);
1329 m_lasterror
= wxSTREAM_EOF
;
1332 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1337 m_lasterror
= wxSTREAM_READ_ERROR
;
1338 wxPyEndBlockThreads(blocked
);
1342 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1343 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1348 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1349 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1350 PyObject
* arglist
= PyTuple_New(2);
1352 if (sizeof(wxFileOffset
) > sizeof(long))
1353 // wxFileOffset is a 64-bit value...
1354 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1356 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1358 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1361 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1364 wxPyEndBlockThreads(blocked
);
1369 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1370 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1371 PyObject
* arglist
= Py_BuildValue("()");
1372 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1375 if (result
!= NULL
) {
1376 if (PyLong_Check(result
))
1377 o
= PyLong_AsLongLong(result
);
1379 o
= PyInt_AsLong(result
);
1382 wxPyEndBlockThreads(blocked
);
1386 //----------------------------------------------------------------------
1388 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1390 wxPyCallback::wxPyCallback(PyObject
* func
) {
1395 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1396 m_func
= other
.m_func
;
1400 wxPyCallback::~wxPyCallback() {
1401 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1403 wxPyEndBlockThreads(blocked
);
1407 #define wxPy_PRECALLINIT "_preCallInit"
1408 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1410 // This function is used for all events destined for Python event handlers.
1411 void wxPyCallback::EventThunker(wxEvent
& event
) {
1412 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1413 PyObject
* func
= cb
->m_func
;
1417 bool checkSkip
= false;
1419 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1420 wxString className
= event
.GetClassInfo()->GetClassName();
1422 // If the event is one of these types then pass the original
1423 // event object instead of the one passed to us.
1424 if ( className
== wxT("wxPyEvent") ) {
1425 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1426 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1428 else if ( className
== wxT("wxPyCommandEvent") ) {
1429 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1430 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1433 arg
= wxPyConstructObject((void*)&event
, className
);
1439 // "intern" the pre/post method names to speed up the HasAttr
1440 static PyObject
* s_preName
= NULL
;
1441 static PyObject
* s_postName
= NULL
;
1442 if (s_preName
== NULL
) {
1443 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1444 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1447 // Check if the event object needs some preinitialization
1448 if (PyObject_HasAttr(arg
, s_preName
)) {
1449 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1451 Py_DECREF(result
); // result is ignored, but we still need to decref it
1452 PyErr_Clear(); // Just in case...
1458 // Call the event handler, passing the event object
1459 tuple
= PyTuple_New(1);
1460 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1461 result
= PyEval_CallObject(func
, tuple
);
1463 Py_DECREF(result
); // result is ignored, but we still need to decref it
1464 PyErr_Clear(); // Just in case...
1469 // Check if the event object needs some post cleanup
1470 if (PyObject_HasAttr(arg
, s_postName
)) {
1471 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1473 Py_DECREF(result
); // result is ignored, but we still need to decref it
1474 PyErr_Clear(); // Just in case...
1481 // if the event object was one of our special types and
1482 // it had been cloned, then we need to extract the Skipped
1483 // value from the original and set it in the clone.
1484 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1486 event
.Skip(PyInt_AsLong(result
));
1494 wxPyEndBlockThreads(blocked
);
1498 //----------------------------------------------------------------------
1500 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1502 m_self
= other
.m_self
;
1503 m_class
= other
.m_class
;
1511 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1522 #if PYTHON_API_VERSION >= 1011
1524 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1525 // in which the method was defined. Starting with 2.2 it returns
1526 // "class that asked for the method" which seems totally bogus to me
1527 // but apprently it fixes some obscure problem waiting to happen in
1528 // Python. Since the API was not documented Guido and the gang felt
1529 // safe in changing it. Needless to say that totally screwed up the
1530 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1531 // code to find the class where the method is actually defined...
1534 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1538 if (PyType_Check(klass
)) { // new style classes
1539 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1540 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1541 PyObject
*mro
, *res
, *base
, *dict
;
1542 /* Look in tp_dict of types in MRO */
1544 assert(PyTuple_Check(mro
));
1545 n
= PyTuple_GET_SIZE(mro
);
1546 for (i
= 0; i
< n
; i
++) {
1547 base
= PyTuple_GET_ITEM(mro
, i
);
1548 if (PyClass_Check(base
))
1549 dict
= ((PyClassObject
*)base
)->cl_dict
;
1551 assert(PyType_Check(base
));
1552 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1554 assert(dict
&& PyDict_Check(dict
));
1555 res
= PyDict_GetItem(dict
, name
);
1562 else if (PyClass_Check(klass
)) { // old style classes
1563 // This code is borrowed/adapted from class_lookup in classobject.c
1564 PyClassObject
* cp
= (PyClassObject
*)klass
;
1565 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1566 if (value
!= NULL
) {
1567 return (PyObject
*)cp
;
1569 n
= PyTuple_Size(cp
->cl_bases
);
1570 for (i
= 0; i
< n
; i
++) {
1571 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1572 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1584 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, PyObject
* nameo
)
1586 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1588 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1590 #else // 2.2 and after, the hard way...
1591 return PyFindClassWithAttr(mgc
, nameo
);
1597 // To avoid recursion when an overridden virtual method wants to call the base
1598 // class version, temporarily set an attribute in the instance with the same
1599 // name as the method. Then the PyObject_GetAttr in the next findCallback
1600 // will return this attribute and the PyMethod_Check will fail.
1602 void wxPyCallbackHelper::setRecursionGuard(PyObject
* method
) const
1604 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1605 PyObject_SetAttr(m_self
, func
->func_name
, Py_None
);
1608 void wxPyCallbackHelper::clearRecursionGuard(PyObject
* method
) const
1610 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1611 if (PyObject_HasAttr(m_self
, func
->func_name
)) {
1612 PyObject_DelAttr(m_self
, func
->func_name
);
1616 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1618 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1619 // if (PyObject_HasAttr(m_self, func->func_name)) {
1620 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1621 // bool retval = (attr == Py_None);
1629 bool wxPyCallbackHelper::findCallback(const char* name
, bool setGuard
) const {
1630 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1631 PyObject
*method
, *klass
;
1632 PyObject
* nameo
= PyString_FromString(name
);
1633 self
->m_lastFound
= NULL
;
1635 // If the object (m_self) has an attibute of the given name...
1636 if (m_self
&& PyObject_HasAttr(m_self
, nameo
)) {
1637 method
= PyObject_GetAttr(m_self
, nameo
);
1639 // ...and if that attribute is a method, and if that method's class is
1640 // not from the registered class or a base class...
1641 if (PyMethod_Check(method
) &&
1642 (klass
= PyMethod_GetDefiningClass(method
, nameo
)) != NULL
&&
1643 (klass
!= m_class
) &&
1644 PyObject_IsSubclass(klass
, m_class
)) {
1646 // ...then we'll save a pointer to the method so callCallback can
1647 // call it. But first, set a recursion guard in case the
1648 // overridden method wants to call the base class version.
1650 setRecursionGuard(method
);
1651 self
->m_lastFound
= method
;
1659 return m_lastFound
!= NULL
;
1663 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1667 result
= callCallbackObj(argTuple
);
1668 if (result
) { // Assumes an integer return type...
1669 retval
= PyInt_AsLong(result
);
1671 PyErr_Clear(); // forget about it if it's not...
1676 // Invoke the Python callable object, returning the raw PyObject return
1677 // value. Caller should DECREF the return value and also manage the GIL.
1678 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1681 // Save a copy of the pointer in case the callback generates another
1682 // callback. In that case m_lastFound will have a different value when
1683 // it gets back here...
1684 PyObject
* method
= m_lastFound
;
1686 result
= PyEval_CallObject(method
, argTuple
);
1687 clearRecursionGuard(method
);
1689 Py_DECREF(argTuple
);
1698 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1699 cbh
.setSelf(self
, klass
, incref
);
1702 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
, bool setGuard
) {
1703 return cbh
.findCallback(name
, setGuard
);
1706 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1707 return cbh
.callCallback(argTuple
);
1710 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1711 return cbh
.callCallbackObj(argTuple
);
1715 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1716 if (cbh
->m_incRef
) {
1717 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1718 Py_XDECREF(cbh
->m_self
);
1719 Py_XDECREF(cbh
->m_class
);
1720 wxPyEndBlockThreads(blocked
);
1724 //---------------------------------------------------------------------------
1725 //---------------------------------------------------------------------------
1726 // These event classes can be derived from in Python and passed through the event
1727 // system without losing anything. They do this by keeping a reference to
1728 // themselves and some special case handling in wxPyCallback::EventThunker.
1731 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1732 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1733 //Py_INCREF(m_self); // circular loops...
1737 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1738 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1741 wxPyEndBlockThreads(blocked
);
1744 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1745 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1753 wxPyEndBlockThreads(blocked
);
1756 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1762 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1763 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1766 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1767 : wxEvent(winid
, commandType
) {
1771 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1774 SetSelf(evt
.m_self
, true);
1778 wxPyEvent::~wxPyEvent() {
1782 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1783 : wxCommandEvent(commandType
, id
) {
1787 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1788 : wxCommandEvent(evt
)
1790 SetSelf(evt
.m_self
, true);
1794 wxPyCommandEvent::~wxPyCommandEvent() {
1801 //---------------------------------------------------------------------------
1802 //---------------------------------------------------------------------------
1803 // Convert a wxList to a Python List, only works for lists of wxObjects
1805 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1806 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1810 wxNode
* node
= list
->GetFirst();
1812 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1813 pyList
= PyList_New(0);
1815 wxObj
= node
->GetData();
1816 pyObj
= wxPyMake_wxObject(wxObj
,false);
1817 PyList_Append(pyList
, pyObj
);
1818 node
= node
->GetNext();
1820 wxPyEndBlockThreads(blocked
);
1824 //----------------------------------------------------------------------
1826 long wxPyGetWinHandle(wxWindow
* win
) {
1829 return (long)win
->GetHandle();
1832 #if defined(__WXGTK__) || defined(__WXX11)
1833 return (long)GetXWindow(win
);
1837 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1838 return (long)win
->GetHandle();
1844 //----------------------------------------------------------------------
1845 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1846 // included in every file over and over again...
1848 wxString
* wxString_in_helper(PyObject
* source
) {
1849 wxString
* target
= NULL
;
1851 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1852 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1856 PyObject
* uni
= source
;
1857 if (PyString_Check(source
)) {
1858 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1859 if (PyErr_Occurred()) return NULL
;
1861 target
= new wxString();
1862 size_t len
= PyUnicode_GET_SIZE(uni
);
1864 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1865 target
->UngetWriteBuf(len
);
1868 if (PyString_Check(source
))
1871 // Convert to a string object if it isn't already, then to wxString
1872 PyObject
* str
= source
;
1873 if (PyUnicode_Check(source
)) {
1874 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1875 if (PyErr_Occurred()) return NULL
;
1877 else if (!PyString_Check(source
)) {
1878 str
= PyObject_Str(source
);
1879 if (PyErr_Occurred()) return NULL
;
1881 char* tmpPtr
; Py_ssize_t tmpSize
;
1882 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1883 target
= new wxString(tmpPtr
, tmpSize
);
1885 if (!PyString_Check(source
))
1887 #endif // wxUSE_UNICODE
1893 // Similar to above except doesn't use "new" and doesn't set an exception
1894 wxString
Py2wxString(PyObject
* source
)
1899 // Convert to a unicode object, if not already, then to a wxString
1900 PyObject
* uni
= source
;
1901 if (!PyUnicode_Check(source
)) {
1902 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1903 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1905 size_t len
= PyUnicode_GET_SIZE(uni
);
1907 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1908 target
.UngetWriteBuf();
1911 if (!PyUnicode_Check(source
))
1914 // Convert to a string object if it isn't already, then to wxString
1915 PyObject
* str
= source
;
1916 if (PyUnicode_Check(source
)) {
1917 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1918 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1920 else if (!PyString_Check(source
)) {
1921 str
= PyObject_Str(source
);
1922 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1924 char* tmpPtr
; Py_ssize_t tmpSize
;
1925 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1926 target
= wxString(tmpPtr
, tmpSize
);
1928 if (!PyString_Check(source
))
1930 #endif // wxUSE_UNICODE
1936 // Make either a Python String or Unicode object, depending on build mode
1937 PyObject
* wx2PyString(const wxString
& src
)
1941 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1943 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1950 void wxSetDefaultPyEncoding(const char* encoding
)
1952 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
1955 const char* wxGetDefaultPyEncoding()
1957 return wxPyDefaultEncoding
;
1960 //----------------------------------------------------------------------
1963 byte
* byte_LIST_helper(PyObject
* source
) {
1964 if (!PyList_Check(source
)) {
1965 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1968 int count
= PyList_Size(source
);
1969 byte
* temp
= new byte
[count
];
1971 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1974 for (int x
=0; x
<count
; x
++) {
1975 PyObject
* o
= PyList_GetItem(source
, x
);
1976 if (! PyInt_Check(o
)) {
1977 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1980 temp
[x
] = (byte
)PyInt_AsLong(o
);
1986 int* int_LIST_helper(PyObject
* source
) {
1987 if (!PyList_Check(source
)) {
1988 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1991 int count
= PyList_Size(source
);
1992 int* temp
= new int[count
];
1994 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1997 for (int x
=0; x
<count
; x
++) {
1998 PyObject
* o
= PyList_GetItem(source
, x
);
1999 if (! PyInt_Check(o
)) {
2000 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2003 temp
[x
] = PyInt_AsLong(o
);
2009 long* long_LIST_helper(PyObject
* source
) {
2010 if (!PyList_Check(source
)) {
2011 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2014 int count
= PyList_Size(source
);
2015 long* temp
= new long[count
];
2017 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2020 for (int x
=0; x
<count
; x
++) {
2021 PyObject
* o
= PyList_GetItem(source
, x
);
2022 if (! PyInt_Check(o
)) {
2023 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2026 temp
[x
] = PyInt_AsLong(o
);
2032 char** string_LIST_helper(PyObject
* source
) {
2033 if (!PyList_Check(source
)) {
2034 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2037 int count
= PyList_Size(source
);
2038 char** temp
= new char*[count
];
2040 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2043 for (int x
=0; x
<count
; x
++) {
2044 PyObject
* o
= PyList_GetItem(source
, x
);
2045 if (! PyString_Check(o
)) {
2046 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2049 temp
[x
] = PyString_AsString(o
);
2054 //--------------------------------
2055 // Part of patch from Tim Hochberg
2056 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2057 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2058 point
->x
= PyInt_AS_LONG(o1
);
2059 point
->y
= PyInt_AS_LONG(o2
);
2062 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2063 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2064 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2067 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2068 // Disallow instances because they can cause havok
2071 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2072 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2073 point
->x
= PyInt_AsLong(o1
);
2074 point
->y
= PyInt_AsLong(o2
);
2081 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2082 // Putting all of the declarations here allows
2083 // us to put the error handling all in one place.
2086 PyObject
*o
, *o1
, *o2
;
2087 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2089 if (!PySequence_Check(source
)) {
2093 // The length of the sequence is returned in count.
2094 *count
= PySequence_Length(source
);
2099 temp
= new wxPoint
[*count
];
2101 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2104 for (x
=0; x
<*count
; x
++) {
2105 // Get an item: try fast way first.
2107 o
= PySequence_Fast_GET_ITEM(source
, x
);
2110 o
= PySequence_GetItem(source
, x
);
2116 // Convert o to wxPoint.
2117 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2118 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2119 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2120 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2121 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2125 else if (wxPySwigInstance_Check(o
)) {
2127 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2132 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2133 o1
= PySequence_GetItem(o
, 0);
2134 o2
= PySequence_GetItem(o
, 1);
2135 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2159 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2163 //------------------------------
2166 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2167 if (!PyList_Check(source
)) {
2168 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2171 int count
= PyList_Size(source
);
2172 wxBitmap
** temp
= new wxBitmap
*[count
];
2174 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2177 for (int x
=0; x
<count
; x
++) {
2178 PyObject
* o
= PyList_GetItem(source
, x
);
2179 if (wxPySwigInstance_Check(o
)) {
2181 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2182 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2188 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2197 wxString
* wxString_LIST_helper(PyObject
* source
) {
2198 if (!PyList_Check(source
)) {
2199 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2202 int count
= PyList_Size(source
);
2203 wxString
* temp
= new wxString
[count
];
2205 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2208 for (int x
=0; x
<count
; x
++) {
2209 PyObject
* o
= PyList_GetItem(source
, x
);
2210 #if PYTHON_API_VERSION >= 1009
2211 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2212 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2216 if (! PyString_Check(o
)) {
2217 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2222 wxString
* pStr
= wxString_in_helper(o
);
2230 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2231 if (!PyList_Check(source
)) {
2232 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2235 int count
= PyList_Size(source
);
2236 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2238 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2241 for (int x
=0; x
<count
; x
++) {
2242 PyObject
* o
= PyList_GetItem(source
, x
);
2243 if (wxPySwigInstance_Check(o
)) {
2244 wxAcceleratorEntry
* ae
;
2245 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2246 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2251 else if (PyTuple_Check(o
)) {
2252 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2253 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2254 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2255 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2258 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2266 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2267 if (!PyList_Check(source
)) {
2268 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2271 int count
= PyList_Size(source
);
2272 wxPen
** temp
= new wxPen
*[count
];
2274 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2277 for (int x
=0; x
<count
; x
++) {
2278 PyObject
* o
= PyList_GetItem(source
, x
);
2279 if (wxPySwigInstance_Check(o
)) {
2281 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2283 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2290 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2298 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2299 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2302 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2306 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2307 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2310 o1
= PySequence_GetItem(source
, 0);
2311 o2
= PySequence_GetItem(source
, 1);
2314 *i1
= PyInt_AsLong(o1
);
2315 *i2
= PyInt_AsLong(o2
);
2325 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2326 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2327 PyObject
*o1
, *o2
, *o3
, *o4
;
2329 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2333 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2334 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2335 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2336 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2339 o1
= PySequence_GetItem(source
, 0);
2340 o2
= PySequence_GetItem(source
, 1);
2341 o3
= PySequence_GetItem(source
, 2);
2342 o4
= PySequence_GetItem(source
, 3);
2345 *i1
= PyInt_AsLong(o1
);
2346 *i2
= PyInt_AsLong(o2
);
2347 *i3
= PyInt_AsLong(o3
);
2348 *i4
= PyInt_AsLong(o4
);
2360 //----------------------------------------------------------------------
2362 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2366 if (wxPySwigInstance_Check(source
) &&
2367 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2371 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2377 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2379 if (source
== Py_None
) {
2380 **obj
= wxSize(-1,-1);
2383 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2387 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2389 if (source
== Py_None
) {
2390 **obj
= wxPoint(-1,-1);
2393 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2398 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2400 if (source
== Py_None
) {
2401 **obj
= wxRealPoint(-1,-1);
2405 // If source is an object instance then it may already be the right type
2406 if (wxPySwigInstance_Check(source
)) {
2408 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2413 // otherwise a 2-tuple of floats is expected
2414 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2415 PyObject
* o1
= PySequence_GetItem(source
, 0);
2416 PyObject
* o2
= PySequence_GetItem(source
, 1);
2417 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2422 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2429 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2435 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2437 if (source
== Py_None
) {
2438 **obj
= wxRect(-1,-1,-1,-1);
2442 // If source is an object instance then it may already be the right type
2443 if (wxPySwigInstance_Check(source
)) {
2445 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2450 // otherwise a 4-tuple of integers is expected
2451 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2452 PyObject
* o1
= PySequence_GetItem(source
, 0);
2453 PyObject
* o2
= PySequence_GetItem(source
, 1);
2454 PyObject
* o3
= PySequence_GetItem(source
, 2);
2455 PyObject
* o4
= PySequence_GetItem(source
, 3);
2456 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2457 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2464 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2465 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2474 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2480 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2482 if (source
== Py_None
) {
2483 **obj
= wxNullColour
;
2487 // If source is an object instance then it may already be the right type
2488 if (wxPySwigInstance_Check(source
)) {
2490 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2495 // otherwise check for a string
2496 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2497 wxString spec
= Py2wxString(source
);
2498 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2499 long red
, green
, blue
;
2500 red
= green
= blue
= 0;
2501 spec
.Mid(1,2).ToLong(&red
, 16);
2502 spec
.Mid(3,2).ToLong(&green
, 16);
2503 spec
.Mid(5,2).ToLong(&blue
, 16);
2505 **obj
= wxColour(red
, green
, blue
);
2508 else { // it's a colour name
2509 **obj
= wxColour(spec
);
2513 // last chance: 3-tuple or 4-tuple of integers is expected
2514 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2515 PyObject
* o1
= PySequence_GetItem(source
, 0);
2516 PyObject
* o2
= PySequence_GetItem(source
, 1);
2517 PyObject
* o3
= PySequence_GetItem(source
, 2);
2518 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2524 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2530 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2531 PyObject
* o1
= PySequence_GetItem(source
, 0);
2532 PyObject
* o2
= PySequence_GetItem(source
, 1);
2533 PyObject
* o3
= PySequence_GetItem(source
, 2);
2534 PyObject
* o4
= PySequence_GetItem(source
, 3);
2535 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2542 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2551 PyErr_SetString(PyExc_TypeError
,
2552 "Expected a wxColour object, a string containing a colour name or '#RRGGBB', or a 3- or 4-tuple of integers.");
2557 bool wxColour_typecheck(PyObject
* source
) {
2559 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2562 if (PyString_Check(source
) || PyUnicode_Check(source
))
2570 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2572 if (source
== Py_None
) {
2573 **obj
= wxPoint2D(-1,-1);
2577 // If source is an object instance then it may already be the right type
2578 if (wxPySwigInstance_Check(source
)) {
2580 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2585 // otherwise a length-2 sequence of floats is expected
2586 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2587 PyObject
* o1
= PySequence_GetItem(source
, 0);
2588 PyObject
* o2
= PySequence_GetItem(source
, 1);
2589 // This should really check for floats, not numbers -- but that would break code.
2590 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2595 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2601 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2606 //----------------------------------------------------------------------
2608 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2610 PyObject
* list
= PyList_New(0);
2611 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2613 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2615 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2617 PyList_Append(list
, str
);
2624 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2626 PyObject
* list
= PyList_New(0);
2627 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2628 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2629 PyList_Append(list
, number
);
2636 //----------------------------------------------------------------------
2637 // wxPyImageHandler methods
2639 // TODO: Switch these to use wxPython's standard macros and helper classes
2640 // for calling callbacks.
2642 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2643 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2644 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2645 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2647 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2648 return wxPyConstructObject(new wxPyInputStream(stream
),
2649 wxT("wxPyInputStream"), 0);
2652 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2653 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2656 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2657 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2660 wxPyImageHandler::wxPyImageHandler():
2663 if (!m_DoCanRead_Name
) {
2664 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2665 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2666 m_LoadFile_Name
= PyString_FromString("LoadFile");
2667 m_SaveFile_Name
= PyString_FromString("SaveFile");
2671 wxPyImageHandler::~wxPyImageHandler() {
2678 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2679 // should check here for isinstance(PyImageHandler) ??
2684 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2685 // check if our object has this method
2686 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2687 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2688 wxPyEndBlockThreads(blocked
);
2692 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2693 py_InputStream(&stream
), NULL
);
2694 bool retval
= false;
2696 retval
= PyInt_AsLong(res
);
2702 wxPyEndBlockThreads(blocked
);
2706 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2707 bool verbose
, int index
) {
2708 // check if our object has this method
2709 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2710 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2711 wxPyEndBlockThreads(blocked
);
2714 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2716 py_InputStream(&stream
),
2717 PyInt_FromLong(verbose
),
2718 PyInt_FromLong(index
),
2720 bool retval
= false;
2722 retval
= PyInt_AsLong(res
);
2727 wxPyEndBlockThreads(blocked
);
2731 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2733 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2734 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2735 wxPyEndBlockThreads(blocked
);
2738 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2740 py_OutputStream(&stream
),
2741 PyInt_FromLong(verbose
),
2743 bool retval
= false;
2745 retval
=PyInt_AsLong(res
);
2750 wxPyEndBlockThreads(blocked
);
2754 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2755 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2756 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2757 wxPyEndBlockThreads(blocked
);
2760 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2761 py_InputStream(&stream
),
2765 retval
=PyInt_AsLong(res
);
2770 wxPyEndBlockThreads(blocked
);
2775 //----------------------------------------------------------------------
2776 // Function to test if the Display (or whatever is the platform equivallent)
2777 // can be connected to. This is accessable from wxPython as a staticmethod of
2778 // wx.App called DisplayAvailable().
2781 bool wxPyTestDisplayAvailable()
2785 display
= XOpenDisplay(NULL
);
2786 if (display
== NULL
)
2788 XCloseDisplay(display
);
2793 // This is adapted from Python's Mac/Modules/MacOS.c in the
2794 // MacOS_WMAvailable function.
2796 ProcessSerialNumber psn
;
2799 ** This is a fairly innocuous call to make if we don't have a window
2800 ** manager, or if we have no permission to talk to it. It will print
2801 ** a message on stderr, but at least it won't abort the process.
2802 ** It appears the function caches the result itself, and it's cheap, so
2803 ** no need for us to cache.
2805 #ifdef kCGNullDirectDisplay
2806 /* On 10.1 CGMainDisplayID() isn't available, and
2807 ** kCGNullDirectDisplay isn't defined.
2809 if (CGMainDisplayID() == 0) {
2814 // Also foreground the application on the first call as a side-effect.
2815 if (GetCurrentProcess(&psn
) < 0 || SetFrontProcess(&psn
) < 0) {
2831 //----------------------------------------------------------------------
2832 //----------------------------------------------------------------------