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() {
330 long wxPyApp::GetMacAboutMenuItemId() {
332 return s_macAboutMenuItemId
;
339 long wxPyApp::GetMacPreferencesMenuItemId() {
341 return s_macPreferencesMenuItemId
;
348 long wxPyApp::GetMacExitMenuItemId() {
350 return s_macExitMenuItemId
;
357 wxString
wxPyApp::GetMacHelpMenuTitleName() {
359 return s_macHelpMenuTitleName
;
361 return wxEmptyString
;
366 void wxPyApp::SetMacSupportPCMenuShortcuts(bool) {
370 void wxPyApp::SetMacAboutMenuItemId(long val
) {
372 s_macAboutMenuItemId
= val
;
377 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
379 s_macPreferencesMenuItemId
= val
;
384 void wxPyApp::SetMacExitMenuItemId(long val
) {
386 s_macExitMenuItemId
= val
;
391 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
393 s_macHelpMenuTitleName
= val
;
398 // This finishes the initialization of wxWindows and then calls the OnInit
399 // that should be present in the derived (Python) class.
400 void wxPyApp::_BootstrapApp()
402 static bool haveInitialized
= false;
405 PyObject
* retval
= NULL
;
406 PyObject
* pyint
= NULL
;
409 // Only initialize wxWidgets once
410 if (! haveInitialized
) {
412 // Get any command-line args passed to this program from the sys module
415 blocked
= wxPyBeginBlockThreads();
417 PyObject
* sysargv
= PySys_GetObject("argv");
418 PyObject
* executable
= PySys_GetObject("executable");
420 if (sysargv
!= NULL
&& executable
!= NULL
) {
421 argc
= PyList_Size(sysargv
) + 1;
422 argv
= new char*[argc
+1];
423 argv
[0] = strdup(PyString_AsString(executable
));
425 for(x
=1; x
<argc
; x
++) {
426 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
427 argv
[x
] = strdup(PyString_AsString(pyArg
));
431 wxPyEndBlockThreads(blocked
);
433 // Initialize wxWidgets
434 result
= wxEntryStart(argc
, argv
);
435 // wxApp takes ownership of the argv array, don't delete it here
437 blocked
= wxPyBeginBlockThreads();
439 PyErr_SetString(PyExc_SystemError
,
440 "wxEntryStart failed, unable to initialize wxWidgets!"
442 " (Is DISPLAY set properly?)"
448 // On wxGTK the locale will be changed to match the system settings,
449 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
450 // for the floating point conversions and such to work right.
451 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
452 setlocale(LC_NUMERIC
, "C");
455 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
457 wxPyEndBlockThreads(blocked
);
458 haveInitialized
= true;
466 // It's now ok to generate exceptions for assertion errors.
467 wxPythonApp
->SetStartupComplete(true);
470 // Call the Python wxApp's OnPreInit and OnInit functions
471 blocked
= wxPyBeginBlockThreads();
472 if (wxPyCBH_findCallback(m_myInst
, "OnPreInit")) {
473 PyObject
* method
= m_myInst
.GetLastFound();
474 PyObject
* argTuple
= PyTuple_New(0);
475 retval
= PyEval_CallObject(method
, argTuple
);
476 m_myInst
.clearRecursionGuard(method
);
482 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
484 PyObject
* method
= m_myInst
.GetLastFound();
485 PyObject
* argTuple
= PyTuple_New(0);
486 retval
= PyEval_CallObject(method
, argTuple
);
487 m_myInst
.clearRecursionGuard(method
);
491 // Don't PyErr_Print here, let the exception in this case go back
492 // up to the wx.PyApp.__init__ scope.
495 pyint
= PyNumber_Int(retval
);
497 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
500 result
= PyInt_AS_LONG(pyint
);
503 // Is it okay if there is no OnInit? Probably so...
508 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
515 wxPyEndBlockThreads(blocked
);
518 //---------------------------------------------------------------------
519 //----------------------------------------------------------------------
523 static char* wxPyCopyCString(const wxChar
* src
)
525 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
526 size_t len
= strlen(buff
);
527 char* dest
= new char[len
+1];
533 static char* wxPyCopyCString(const char* src
) // we need a char version too
535 size_t len
= strlen(src
);
536 char* dest
= new char[len
+1];
542 static wxChar
* wxPyCopyWString(const char *src
)
544 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
545 wxString
str(src
, *wxConvCurrent
);
546 return copystring(str
);
550 static wxChar
* wxPyCopyWString(const wxChar
*src
)
552 return copystring(src
);
558 inline const char* dropwx(const char* name
) {
559 if (name
[0] == 'w' && name
[1] == 'x')
565 //----------------------------------------------------------------------
567 // This function is called when the wx._core_ module is imported to do some
568 // initial setup. (Before there is a wxApp object.) The rest happens in
569 // wxPyApp::_BootstrapApp
570 void __wxPyPreStart(PyObject
* moduleDict
)
574 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
575 // | _CRTDBG_CHECK_ALWAYS_DF
576 // | _CRTDBG_DELAY_FREE_MEM_DF
580 #ifdef WXP_WITH_THREAD
581 #if wxPyUSE_GIL_STATE
582 PyEval_InitThreads();
584 PyEval_InitThreads();
585 wxPyTStates
= new wxPyThreadStateArray
;
586 wxPyTMutex
= new wxMutex
;
588 // Save the current (main) thread state in our array
589 PyThreadState
* tstate
= wxPyBeginAllowThreads();
590 wxPyEndAllowThreads(tstate
);
594 // Ensure that the build options in the DLL (or whatever) match this build
595 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
597 wxInitAllImageHandlers();
602 void __wxPyCleanup() {
603 wxPyDoingCleanup
= true;
605 wxPyDoCleanup
= false;
608 #ifdef WXP_WITH_THREAD
609 #if !wxPyUSE_GIL_STATE
612 wxPyTStates
->Empty();
620 // Save a reference to the dictionary of the wx._core module, and inject
621 // a few more things into it.
622 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
625 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
628 if (!PyDict_Check(wxPython_dict
)) {
629 PyErr_SetString(PyExc_TypeError
,
630 "_wxPySetDictionary must have dictionary object!");
634 if (! wxPyPtrTypeMap
)
635 wxPyPtrTypeMap
= PyDict_New();
636 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
638 // Create an exception object to use for wxASSERTions
639 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
640 PyExc_AssertionError
, NULL
);
641 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
643 // Create an exception object to use when the app object hasn't been created yet
644 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
645 PyExc_RuntimeError
, NULL
);
646 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
651 #define wxPlatform "__WXMOTIF__"
652 #define wxPlatName "wxMotif"
655 #define wxPlatform "__WXX11__"
656 #define wxPlatName "wxX11"
659 #define wxPlatform "__WXGTK__"
660 #define wxPlatName "wxGTK"
663 #define wxPlatform "__WXMSW__"
664 #define wxPlatName "wxMSW"
667 #define wxPlatform "__WXMAC__"
668 #define wxPlatName "wxMac"
677 // These should be deprecated in favor of the PlatformInfo tuple built below...
678 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
679 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
680 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
682 // Make a tuple of strings that gives more info about the platform.
683 PyObject
* PlatInfo
= PyList_New(0);
686 #define _AddInfoString(st) \
687 obj = PyString_FromString(st); \
688 PyList_Append(PlatInfo, obj); \
691 _AddInfoString(wxPlatform
);
692 _AddInfoString(wxPlatName
);
694 _AddInfoString("unicode");
696 _AddInfoString("ansi");
700 _AddInfoString("gtk2");
702 _AddInfoString("gtk1");
706 _AddInfoString("wx-assertions-on");
708 _AddInfoString("wx-assertions-off");
710 _AddInfoString(wxPy_SWIG_VERSION
);
712 #if wxMAC_USE_CORE_GRAPHICS
713 _AddInfoString("mac-cg");
715 _AddInfoString("mac-qd");
717 #if wxMAC_USE_NATIVE_TOOLBAR
718 _AddInfoString("mac-native-tb");
720 _AddInfoString("mac-no-native-tb");
724 #undef _AddInfoString
726 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
728 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
735 //---------------------------------------------------------------------------
737 // Check for existence of a wxApp, setting an exception if there isn't one.
738 // This doesn't need to aquire the GIL because it should only be called from
739 // an %exception before the lock is released.
741 bool wxPyCheckForApp() {
742 if (wxTheApp
!= NULL
)
745 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
750 //---------------------------------------------------------------------------
752 void wxPyUserData_dtor(wxPyUserData
* self
) {
753 if (! wxPyDoingCleanup
) {
754 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
755 Py_DECREF(self
->m_obj
);
757 wxPyEndBlockThreads(blocked
);
762 void wxPyClientData_dtor(wxPyClientData
* self
) {
763 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
764 // may have already garbage collected the object...
765 if (self
->m_incRef
) {
766 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
767 Py_DECREF(self
->m_obj
);
768 wxPyEndBlockThreads(blocked
);
776 // This is called when an OOR controled object is being destroyed. Although
777 // the C++ object is going away there is no way to force the Python object
778 // (and all references to it) to die too. This causes problems (crashes) in
779 // wxPython when a python shadow object attempts to call a C++ method using
780 // the now bogus pointer... So to try and prevent this we'll do a little black
781 // magic and change the class of the python instance to a class that will
782 // raise an exception for any attempt to call methods with it. See
783 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
784 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
786 static PyObject
* deadObjectClass
= NULL
;
788 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
789 if (deadObjectClass
== NULL
) {
790 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
791 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
792 // will lead to a deadlock when it tries to aquire the GIL again.
793 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
794 Py_INCREF(deadObjectClass
);
798 // Only if there is more than one reference to the object and we are
799 // holding the OOR reference:
800 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
801 // bool isInstance = wxPyInstance_Check(self->m_obj);
803 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
805 // Call __del__, if there is one.
806 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
808 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
812 if (PyErr_Occurred())
813 PyErr_Clear(); // just ignore it for now
816 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
818 // Clear the instance's dictionary
821 // put the name of the old class into the instance, and then reset the
822 // class to be the dead class.
823 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
824 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
825 PyDict_SetItemString(dict
, "_name", name
);
826 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
827 //Py_INCREF(deadObjectClass);
833 // m_obj is DECREF'd in the base class dtor...
834 wxPyEndBlockThreads(blocked
);
838 //---------------------------------------------------------------------------
839 // Stuff used by OOR to find the right wxPython class type to return and to
843 // The pointer type map is used when the "pointer" type name generated by SWIG
844 // is not the same as the shadow class name, for example wxPyTreeCtrl
845 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
846 // so we'll just make it a Python dictionary in the wx module's namespace.
847 // (See __wxSetDictionary)
848 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
849 if (! wxPyPtrTypeMap
)
850 wxPyPtrTypeMap
= PyDict_New();
851 PyDict_SetItemString(wxPyPtrTypeMap
,
853 PyString_FromString((char*)ptrName
));
859 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
860 PyObject
* target
= NULL
;
861 bool isEvtHandler
= false;
862 bool isSizer
= false;
865 // If it's derived from wxEvtHandler then there may
866 // already be a pointer to a Python object that we can use
868 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
870 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
871 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
873 target
= data
->m_obj
;
879 // Also check for wxSizer
880 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
882 wxSizer
* sz
= (wxSizer
*)source
;
883 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
885 target
= data
->m_obj
;
892 // Otherwise make it the old fashioned way by making a new shadow
893 // object and putting this pointer in it. Look up the class
894 // heirarchy until we find a class name that is located in the
896 const wxClassInfo
* info
= source
->GetClassInfo();
897 wxString name
= info
->GetClassName();
898 bool exists
= wxPyCheckSwigType(name
);
899 while (info
&& !exists
) {
900 info
= info
->GetBaseClass1();
901 name
= info
->GetClassName();
902 exists
= wxPyCheckSwigType(name
);
905 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
906 if (target
&& isEvtHandler
)
907 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
908 if (target
&& isSizer
)
909 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
911 wxString
msg(wxT("wxPython class not found for "));
912 msg
+= source
->GetClassInfo()->GetClassName();
913 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
917 } else { // source was NULL so return None.
918 Py_INCREF(Py_None
); target
= Py_None
;
924 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
926 return wxPyMake_wxObject(source
, setThisOwn
);
930 //---------------------------------------------------------------------------
933 #ifdef WXP_WITH_THREAD
934 #if !wxPyUSE_GIL_STATE
937 unsigned long wxPyGetCurrentThreadId() {
938 return wxThread::GetCurrentId();
941 static wxPyThreadState gs_shutdownTState
;
944 wxPyThreadState
* wxPyGetThreadState() {
945 if (wxPyTMutex
== NULL
) // Python is shutting down...
946 return &gs_shutdownTState
;
948 unsigned long ctid
= wxPyGetCurrentThreadId();
949 wxPyThreadState
* tstate
= NULL
;
952 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
953 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
954 if (info
.tid
== ctid
) {
959 wxPyTMutex
->Unlock();
960 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
966 void wxPySaveThreadState(PyThreadState
* tstate
) {
967 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
968 gs_shutdownTState
.tstate
= tstate
;
971 unsigned long ctid
= wxPyGetCurrentThreadId();
973 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
974 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
975 if (info
.tid
== ctid
) {
977 if (info
.tstate
!= tstate
)
978 wxLogMessage("*** tstate mismatch!???");
980 info
.tstate
= tstate
; // allow for transient tstates
981 // Normally it will never change, but apparently COM callbacks
982 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
983 // tstate which will then be garbage the next time we try to use
986 wxPyTMutex
->Unlock();
990 // not found, so add it...
991 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
992 wxPyTMutex
->Unlock();
1000 // Calls from Python to wxWindows code are wrapped in calls to these
1003 PyThreadState
* wxPyBeginAllowThreads() {
1004 #ifdef WXP_WITH_THREAD
1005 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1006 #if !wxPyUSE_GIL_STATE
1007 wxPySaveThreadState(saved
);
1015 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1016 #ifdef WXP_WITH_THREAD
1017 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1023 // Calls from wxWindows back to Python code, or even any PyObject
1024 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1026 wxPyBlock_t
wxPyBeginBlockThreads() {
1027 #ifdef WXP_WITH_THREAD
1028 if (! Py_IsInitialized()) {
1029 return (wxPyBlock_t
)0;
1031 #if wxPyUSE_GIL_STATE
1032 PyGILState_STATE state
= PyGILState_Ensure();
1035 PyThreadState
*current
= _PyThreadState_Current
;
1037 // Only block if there wasn't already a tstate, or if the current one is
1038 // not the one we are wanting to change to. This should prevent deadlock
1039 // if there are nested calls to wxPyBeginBlockThreads
1040 wxPyBlock_t blocked
= false;
1041 wxPyThreadState
* tstate
= wxPyGetThreadState();
1042 if (current
!= tstate
->tstate
) {
1043 PyEval_RestoreThread(tstate
->tstate
);
1049 return (wxPyBlock_t
)0;
1054 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1055 #ifdef WXP_WITH_THREAD
1056 if (! Py_IsInitialized()) {
1059 #if wxPyUSE_GIL_STATE
1060 PyGILState_Release(blocked
);
1062 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1063 // The value of blocked passed in needs to be the same as that returned
1064 // from wxPyBeginBlockThreads at the same nesting level.
1066 PyEval_SaveThread();
1073 //---------------------------------------------------------------------------
1074 // wxPyInputStream and wxPyCBInputStream methods
1077 void wxPyInputStream::close() {
1078 /* do nothing for now */
1081 void wxPyInputStream::flush() {
1082 /* do nothing for now */
1085 bool wxPyInputStream::eof() {
1087 return m_wxis
->Eof();
1092 wxPyInputStream::~wxPyInputStream() {
1100 PyObject
* wxPyInputStream::read(int size
) {
1101 PyObject
* obj
= NULL
;
1103 const int BUFSIZE
= 1024;
1105 // check if we have a real wxInputStream to work with
1107 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1108 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1109 wxPyEndBlockThreads(blocked
);
1114 // read while bytes are available on the stream
1115 while ( m_wxis
->CanRead() ) {
1116 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1117 buf
.UngetAppendBuf(m_wxis
->LastRead());
1120 } else { // Read only size number of characters
1121 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1122 buf
.UngetWriteBuf(m_wxis
->LastRead());
1126 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1127 wxStreamError err
= m_wxis
->GetLastError();
1128 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1129 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1132 // We use only strings for the streams, not unicode
1133 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1135 wxPyEndBlockThreads(blocked
);
1140 PyObject
* wxPyInputStream::readline(int size
) {
1141 PyObject
* obj
= NULL
;
1146 // check if we have a real wxInputStream to work with
1148 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1149 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1150 wxPyEndBlockThreads(blocked
);
1154 // read until \n or byte limit reached
1155 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1156 ch
= m_wxis
->GetC();
1161 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1162 wxStreamError err
= m_wxis
->GetLastError();
1163 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1164 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1167 // We use only strings for the streams, not unicode
1168 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1170 wxPyEndBlockThreads(blocked
);
1175 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1178 // check if we have a real wxInputStream to work with
1180 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1181 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1182 wxPyEndBlockThreads(blocked
);
1187 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1188 pylist
= PyList_New(0);
1189 wxPyEndBlockThreads(blocked
);
1192 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1194 wxPyEndBlockThreads(blocked
);
1198 // read sizehint bytes or until EOF
1200 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1201 PyObject
* s
= this->readline();
1203 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1205 wxPyEndBlockThreads(blocked
);
1208 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1209 PyList_Append(pylist
, s
);
1210 i
+= PyString_Size(s
);
1211 wxPyEndBlockThreads(blocked
);
1215 wxStreamError err
= m_wxis
->GetLastError();
1216 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1217 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1219 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1220 wxPyEndBlockThreads(blocked
);
1228 void wxPyInputStream::seek(int offset
, int whence
) {
1230 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1233 int wxPyInputStream::tell(){
1235 return m_wxis
->TellI();
1242 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1243 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1246 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1248 m_read
= other
.m_read
;
1249 m_seek
= other
.m_seek
;
1250 m_tell
= other
.m_tell
;
1251 m_block
= other
.m_block
;
1258 wxPyCBInputStream::~wxPyCBInputStream() {
1259 wxPyBlock_t blocked
;
1260 if (m_block
) blocked
= wxPyBeginBlockThreads();
1264 if (m_block
) wxPyEndBlockThreads(blocked
);
1268 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1269 wxPyBlock_t blocked
;
1270 if (block
) blocked
= wxPyBeginBlockThreads();
1272 PyObject
* read
= getMethod(py
, "read");
1273 PyObject
* seek
= getMethod(py
, "seek");
1274 PyObject
* tell
= getMethod(py
, "tell");
1277 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1281 if (block
) wxPyEndBlockThreads(blocked
);
1285 if (block
) wxPyEndBlockThreads(blocked
);
1286 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1290 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1291 return wxPyCBInputStream::create(py
, block
);
1294 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1295 return new wxPyCBInputStream(*other
);
1298 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1299 if (!PyObject_HasAttrString(py
, name
))
1301 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1302 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1310 wxFileOffset
wxPyCBInputStream::GetLength() const {
1311 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1312 if (m_seek
&& m_tell
) {
1313 wxFileOffset temp
= self
->OnSysTell();
1314 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1315 self
->OnSysSeek(temp
, wxFromStart
);
1319 return wxInvalidOffset
;
1323 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1327 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1328 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1329 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1333 if ((result
!= NULL
) && PyString_Check(result
)) {
1334 o
= PyString_Size(result
);
1336 m_lasterror
= wxSTREAM_EOF
;
1339 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1344 m_lasterror
= wxSTREAM_READ_ERROR
;
1345 wxPyEndBlockThreads(blocked
);
1349 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1350 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1355 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1356 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1357 PyObject
* arglist
= PyTuple_New(2);
1359 if (sizeof(wxFileOffset
) > sizeof(long))
1360 // wxFileOffset is a 64-bit value...
1361 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1363 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1365 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1368 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1371 wxPyEndBlockThreads(blocked
);
1376 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1377 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1378 PyObject
* arglist
= Py_BuildValue("()");
1379 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1382 if (result
!= NULL
) {
1383 if (PyLong_Check(result
))
1384 o
= PyLong_AsLongLong(result
);
1386 o
= PyInt_AsLong(result
);
1389 wxPyEndBlockThreads(blocked
);
1393 //----------------------------------------------------------------------
1395 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1397 wxPyCallback::wxPyCallback(PyObject
* func
) {
1402 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1403 m_func
= other
.m_func
;
1407 wxPyCallback::~wxPyCallback() {
1408 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1410 wxPyEndBlockThreads(blocked
);
1414 #define wxPy_PRECALLINIT "_preCallInit"
1415 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1417 // This function is used for all events destined for Python event handlers.
1418 void wxPyCallback::EventThunker(wxEvent
& event
) {
1419 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1420 PyObject
* func
= cb
->m_func
;
1424 bool checkSkip
= false;
1426 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1427 wxString className
= event
.GetClassInfo()->GetClassName();
1429 // If the event is one of these types then pass the original
1430 // event object instead of the one passed to us.
1431 if ( className
== wxT("wxPyEvent") ) {
1432 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1433 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1435 else if ( className
== wxT("wxPyCommandEvent") ) {
1436 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1437 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1440 arg
= wxPyConstructObject((void*)&event
, className
);
1446 // "intern" the pre/post method names to speed up the HasAttr
1447 static PyObject
* s_preName
= NULL
;
1448 static PyObject
* s_postName
= NULL
;
1449 if (s_preName
== NULL
) {
1450 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1451 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1454 // Check if the event object needs some preinitialization
1455 if (PyObject_HasAttr(arg
, s_preName
)) {
1456 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1458 Py_DECREF(result
); // result is ignored, but we still need to decref it
1459 PyErr_Clear(); // Just in case...
1465 // Call the event handler, passing the event object
1466 tuple
= PyTuple_New(1);
1467 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1468 result
= PyEval_CallObject(func
, tuple
);
1470 Py_DECREF(result
); // result is ignored, but we still need to decref it
1471 PyErr_Clear(); // Just in case...
1476 // Check if the event object needs some post cleanup
1477 if (PyObject_HasAttr(arg
, s_postName
)) {
1478 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1480 Py_DECREF(result
); // result is ignored, but we still need to decref it
1481 PyErr_Clear(); // Just in case...
1488 // if the event object was one of our special types and
1489 // it had been cloned, then we need to extract the Skipped
1490 // value from the original and set it in the clone.
1491 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1493 event
.Skip(PyInt_AsLong(result
));
1501 wxPyEndBlockThreads(blocked
);
1505 //----------------------------------------------------------------------
1507 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1509 m_self
= other
.m_self
;
1510 m_class
= other
.m_class
;
1518 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1529 #if PYTHON_API_VERSION >= 1011
1531 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1532 // in which the method was defined. Starting with 2.2 it returns
1533 // "class that asked for the method" which seems totally bogus to me
1534 // but apprently it fixes some obscure problem waiting to happen in
1535 // Python. Since the API was not documented Guido and the gang felt
1536 // safe in changing it. Needless to say that totally screwed up the
1537 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1538 // code to find the class where the method is actually defined...
1541 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1545 if (PyType_Check(klass
)) { // new style classes
1546 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1547 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1548 PyObject
*mro
, *res
, *base
, *dict
;
1549 /* Look in tp_dict of types in MRO */
1551 assert(PyTuple_Check(mro
));
1552 n
= PyTuple_GET_SIZE(mro
);
1553 for (i
= 0; i
< n
; i
++) {
1554 base
= PyTuple_GET_ITEM(mro
, i
);
1555 if (PyClass_Check(base
))
1556 dict
= ((PyClassObject
*)base
)->cl_dict
;
1558 assert(PyType_Check(base
));
1559 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1561 assert(dict
&& PyDict_Check(dict
));
1562 res
= PyDict_GetItem(dict
, name
);
1569 else if (PyClass_Check(klass
)) { // old style classes
1570 // This code is borrowed/adapted from class_lookup in classobject.c
1571 PyClassObject
* cp
= (PyClassObject
*)klass
;
1572 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1573 if (value
!= NULL
) {
1574 return (PyObject
*)cp
;
1576 n
= PyTuple_Size(cp
->cl_bases
);
1577 for (i
= 0; i
< n
; i
++) {
1578 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1579 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1591 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, PyObject
* nameo
)
1593 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1595 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1597 #else // 2.2 and after, the hard way...
1598 return PyFindClassWithAttr(mgc
, nameo
);
1604 // To avoid recursion when an overridden virtual method wants to call the base
1605 // class version, temporarily set an attribute in the instance with the same
1606 // name as the method. Then the PyObject_GetAttr in the next findCallback
1607 // will return this attribute and the PyMethod_Check will fail.
1609 void wxPyCallbackHelper::setRecursionGuard(PyObject
* method
) const
1611 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1612 PyObject_SetAttr(m_self
, func
->func_name
, Py_None
);
1615 void wxPyCallbackHelper::clearRecursionGuard(PyObject
* method
) const
1617 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1618 if (PyObject_HasAttr(m_self
, func
->func_name
)) {
1619 PyObject_DelAttr(m_self
, func
->func_name
);
1623 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1625 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1626 // if (PyObject_HasAttr(m_self, func->func_name)) {
1627 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1628 // bool retval = (attr == Py_None);
1636 bool wxPyCallbackHelper::findCallback(const char* name
, bool setGuard
) const {
1637 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1638 PyObject
*method
, *klass
;
1639 PyObject
* nameo
= PyString_FromString(name
);
1640 self
->m_lastFound
= NULL
;
1642 // If the object (m_self) has an attibute of the given name...
1643 if (m_self
&& PyObject_HasAttr(m_self
, nameo
)) {
1644 method
= PyObject_GetAttr(m_self
, nameo
);
1646 // ...and if that attribute is a method, and if that method's class is
1647 // not from the registered class or a base class...
1648 if (PyMethod_Check(method
) &&
1649 (klass
= PyMethod_GetDefiningClass(method
, nameo
)) != NULL
&&
1650 (klass
!= m_class
) &&
1651 PyObject_IsSubclass(klass
, m_class
)) {
1653 // ...then we'll save a pointer to the method so callCallback can
1654 // call it. But first, set a recursion guard in case the
1655 // overridden method wants to call the base class version.
1657 setRecursionGuard(method
);
1658 self
->m_lastFound
= method
;
1666 return m_lastFound
!= NULL
;
1670 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1674 result
= callCallbackObj(argTuple
);
1675 if (result
) { // Assumes an integer return type...
1676 retval
= PyInt_AsLong(result
);
1678 PyErr_Clear(); // forget about it if it's not...
1683 // Invoke the Python callable object, returning the raw PyObject return
1684 // value. Caller should DECREF the return value and also manage the GIL.
1685 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1688 // Save a copy of the pointer in case the callback generates another
1689 // callback. In that case m_lastFound will have a different value when
1690 // it gets back here...
1691 PyObject
* method
= m_lastFound
;
1693 result
= PyEval_CallObject(method
, argTuple
);
1694 clearRecursionGuard(method
);
1696 Py_DECREF(argTuple
);
1705 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1706 cbh
.setSelf(self
, klass
, incref
);
1709 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
, bool setGuard
) {
1710 return cbh
.findCallback(name
, setGuard
);
1713 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1714 return cbh
.callCallback(argTuple
);
1717 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1718 return cbh
.callCallbackObj(argTuple
);
1722 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1723 if (cbh
->m_incRef
) {
1724 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1725 Py_XDECREF(cbh
->m_self
);
1726 Py_XDECREF(cbh
->m_class
);
1727 wxPyEndBlockThreads(blocked
);
1731 //---------------------------------------------------------------------------
1732 //---------------------------------------------------------------------------
1733 // These event classes can be derived from in Python and passed through the event
1734 // system without losing anything. They do this by keeping a reference to
1735 // themselves and some special case handling in wxPyCallback::EventThunker.
1738 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1739 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1740 //Py_INCREF(m_self); // circular loops...
1744 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1745 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1748 wxPyEndBlockThreads(blocked
);
1751 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1752 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1760 wxPyEndBlockThreads(blocked
);
1763 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1769 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1770 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1773 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1774 : wxEvent(winid
, commandType
) {
1778 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1781 SetSelf(evt
.m_self
, true);
1785 wxPyEvent::~wxPyEvent() {
1789 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1790 : wxCommandEvent(commandType
, id
) {
1794 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1795 : wxCommandEvent(evt
)
1797 SetSelf(evt
.m_self
, true);
1801 wxPyCommandEvent::~wxPyCommandEvent() {
1808 //---------------------------------------------------------------------------
1809 //---------------------------------------------------------------------------
1810 // Convert a wxList to a Python List, only works for lists of wxObjects
1812 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1813 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1817 wxNode
* node
= list
->GetFirst();
1819 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1820 pyList
= PyList_New(0);
1822 wxObj
= node
->GetData();
1823 pyObj
= wxPyMake_wxObject(wxObj
,false);
1824 PyList_Append(pyList
, pyObj
);
1825 node
= node
->GetNext();
1827 wxPyEndBlockThreads(blocked
);
1831 //----------------------------------------------------------------------
1833 long wxPyGetWinHandle(wxWindow
* win
) {
1836 return (long)win
->GetHandle();
1839 #if defined(__WXGTK__) || defined(__WXX11)
1840 return (long)GetXWindow(win
);
1844 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1845 return (long)win
->GetHandle();
1851 //----------------------------------------------------------------------
1852 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1853 // included in every file over and over again...
1855 wxString
* wxString_in_helper(PyObject
* source
) {
1856 wxString
* target
= NULL
;
1858 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1859 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1863 PyObject
* uni
= source
;
1864 if (PyString_Check(source
)) {
1865 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1866 if (PyErr_Occurred()) return NULL
;
1868 target
= new wxString();
1869 size_t len
= PyUnicode_GET_SIZE(uni
);
1871 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1872 target
->UngetWriteBuf(len
);
1875 if (PyString_Check(source
))
1878 // Convert to a string object if it isn't already, then to wxString
1879 PyObject
* str
= source
;
1880 if (PyUnicode_Check(source
)) {
1881 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1882 if (PyErr_Occurred()) return NULL
;
1884 else if (!PyString_Check(source
)) {
1885 str
= PyObject_Str(source
);
1886 if (PyErr_Occurred()) return NULL
;
1888 char* tmpPtr
; Py_ssize_t tmpSize
;
1889 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1890 target
= new wxString(tmpPtr
, tmpSize
);
1892 if (!PyString_Check(source
))
1894 #endif // wxUSE_UNICODE
1900 // Similar to above except doesn't use "new" and doesn't set an exception
1901 wxString
Py2wxString(PyObject
* source
)
1906 // Convert to a unicode object, if not already, then to a wxString
1907 PyObject
* uni
= source
;
1908 if (!PyUnicode_Check(source
)) {
1909 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1910 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1912 size_t len
= PyUnicode_GET_SIZE(uni
);
1914 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1915 target
.UngetWriteBuf();
1918 if (!PyUnicode_Check(source
))
1921 // Convert to a string object if it isn't already, then to wxString
1922 PyObject
* str
= source
;
1923 if (PyUnicode_Check(source
)) {
1924 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1925 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1927 else if (!PyString_Check(source
)) {
1928 str
= PyObject_Str(source
);
1929 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1931 char* tmpPtr
; Py_ssize_t tmpSize
;
1932 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1933 target
= wxString(tmpPtr
, tmpSize
);
1935 if (!PyString_Check(source
))
1937 #endif // wxUSE_UNICODE
1943 // Make either a Python String or Unicode object, depending on build mode
1944 PyObject
* wx2PyString(const wxString
& src
)
1948 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1950 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1957 void wxSetDefaultPyEncoding(const char* encoding
)
1959 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
1962 const char* wxGetDefaultPyEncoding()
1964 return wxPyDefaultEncoding
;
1967 //----------------------------------------------------------------------
1970 byte
* byte_LIST_helper(PyObject
* source
) {
1971 if (!PyList_Check(source
)) {
1972 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1975 int count
= PyList_Size(source
);
1976 byte
* temp
= new byte
[count
];
1978 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1981 for (int x
=0; x
<count
; x
++) {
1982 PyObject
* o
= PyList_GetItem(source
, x
);
1983 if (! PyInt_Check(o
)) {
1984 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1987 temp
[x
] = (byte
)PyInt_AsLong(o
);
1993 int* int_LIST_helper(PyObject
* source
) {
1994 if (!PyList_Check(source
)) {
1995 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1998 int count
= PyList_Size(source
);
1999 int* temp
= new int[count
];
2001 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2004 for (int x
=0; x
<count
; x
++) {
2005 PyObject
* o
= PyList_GetItem(source
, x
);
2006 if (! PyInt_Check(o
)) {
2007 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2010 temp
[x
] = PyInt_AsLong(o
);
2016 long* long_LIST_helper(PyObject
* source
) {
2017 if (!PyList_Check(source
)) {
2018 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2021 int count
= PyList_Size(source
);
2022 long* temp
= new long[count
];
2024 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2027 for (int x
=0; x
<count
; x
++) {
2028 PyObject
* o
= PyList_GetItem(source
, x
);
2029 if (! PyInt_Check(o
)) {
2030 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2033 temp
[x
] = PyInt_AsLong(o
);
2039 char** string_LIST_helper(PyObject
* source
) {
2040 if (!PyList_Check(source
)) {
2041 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2044 int count
= PyList_Size(source
);
2045 char** temp
= new char*[count
];
2047 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2050 for (int x
=0; x
<count
; x
++) {
2051 PyObject
* o
= PyList_GetItem(source
, x
);
2052 if (! PyString_Check(o
)) {
2053 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2056 temp
[x
] = PyString_AsString(o
);
2061 //---------------------------------------------------------------------------
2062 // NOTE: The following functions could really use some refactoring using
2063 // templates to make things somewhat simpler...
2065 inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
)
2068 if (PyInt_Check(o1
))
2069 point
->x
= (int)PyInt_AS_LONG(o1
);
2070 else if (PyFloat_Check(o1
))
2071 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2072 else if (PyNumber_Check(o1
))
2073 point
->x
= (int)PyInt_AsLong(o1
);
2078 if (PyInt_Check(o2
))
2079 point
->y
= (int)PyInt_AS_LONG(o2
);
2080 else if (PyFloat_Check(o2
))
2081 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2082 else if (PyNumber_Check(o2
))
2083 point
->y
= (int)PyInt_AsLong(o2
);
2089 // NOTE: This function used to have this code in it, but I don't know why it
2090 // is a problem nor what havok it will cause, so removing for now...
2091 // if (wxPySwigInstance_Check(o1) || wxPySwigInstance_Check(o2)) {
2092 // // Disallow instances because they can cause havok
2098 inline bool wxPoint2DFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint2D
* point
)
2101 if (PyInt_Check(o1
))
2102 point
->m_x
= (double)PyInt_AS_LONG(o1
);
2103 else if (PyFloat_Check(o1
))
2104 point
->m_x
= (double)PyFloat_AS_DOUBLE(o1
);
2105 else if (PyNumber_Check(o1
))
2106 point
->m_x
= (double)PyFloat_AsDouble(o1
);
2111 if (PyInt_Check(o2
))
2112 point
->m_y
= (double)PyInt_AS_LONG(o2
);
2113 else if (PyFloat_Check(o2
))
2114 point
->m_y
= (double)PyFloat_AS_DOUBLE(o2
);
2115 else if (PyNumber_Check(o2
))
2116 point
->m_y
= (double)PyFloat_AsDouble(o2
);
2125 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
)
2129 PyObject
*o
, *o1
, *o2
;
2130 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2132 if (!PySequence_Check(source
)) {
2136 // The length of the sequence is returned in count.
2137 *count
= PySequence_Length(source
);
2142 temp
= new wxPoint
[*count
];
2144 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2147 for (idx
=0; idx
<*count
; idx
++) {
2148 // Get an item: try fast way first.
2150 o
= PySequence_Fast_GET_ITEM(source
, idx
);
2153 o
= PySequence_GetItem(source
, idx
);
2159 // Convert o to wxPoint.
2160 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2161 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2162 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2163 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2164 if (!wxPointFromObjects(o1
, o2
, &temp
[idx
])) {
2168 else if (wxPySwigInstance_Check(o
)) {
2170 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2175 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2176 o1
= PySequence_GetItem(o
, 0);
2177 o2
= PySequence_GetItem(o
, 1);
2178 if (!wxPointFromObjects(o1
, o2
, &temp
[idx
])) {
2202 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2208 wxPoint2D
* wxPoint2D_LIST_helper(PyObject
* source
, size_t *count
)
2212 PyObject
*o
, *o1
, *o2
;
2213 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2215 if (!PySequence_Check(source
)) {
2219 // The length of the sequence is returned in count.
2220 *count
= PySequence_Length(source
);
2225 temp
= new wxPoint2D
[*count
];
2227 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2230 for (idx
=0; idx
<*count
; idx
++) {
2231 // Get an item: try fast way first.
2233 o
= PySequence_Fast_GET_ITEM(source
, idx
);
2236 o
= PySequence_GetItem(source
, idx
);
2242 // Convert o to wxPoint.
2243 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2244 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2245 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2246 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2247 if (!wxPoint2DFromObjects(o1
, o2
, &temp
[idx
])) {
2251 else if (wxPySwigInstance_Check(o
)) {
2253 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint2D"))) {
2258 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2259 o1
= PySequence_GetItem(o
, 0);
2260 o2
= PySequence_GetItem(o
, 1);
2261 if (!wxPoint2DFromObjects(o1
, o2
, &temp
[idx
])) {
2285 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoint2Ds.");
2289 //---------------------------------------------------------------------------
2292 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2293 if (!PyList_Check(source
)) {
2294 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2297 int count
= PyList_Size(source
);
2298 wxBitmap
** temp
= new wxBitmap
*[count
];
2300 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2303 for (int x
=0; x
<count
; x
++) {
2304 PyObject
* o
= PyList_GetItem(source
, x
);
2305 if (wxPySwigInstance_Check(o
)) {
2307 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2308 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2314 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2323 wxString
* wxString_LIST_helper(PyObject
* source
) {
2324 if (!PyList_Check(source
)) {
2325 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2328 int count
= PyList_Size(source
);
2329 wxString
* temp
= new wxString
[count
];
2331 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2334 for (int x
=0; x
<count
; x
++) {
2335 PyObject
* o
= PyList_GetItem(source
, x
);
2336 #if PYTHON_API_VERSION >= 1009
2337 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2338 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2342 if (! PyString_Check(o
)) {
2343 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2348 wxString
* pStr
= wxString_in_helper(o
);
2356 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2357 if (!PyList_Check(source
)) {
2358 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2361 int count
= PyList_Size(source
);
2362 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2364 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2367 for (int x
=0; x
<count
; x
++) {
2368 PyObject
* o
= PyList_GetItem(source
, x
);
2369 if (wxPySwigInstance_Check(o
)) {
2370 wxAcceleratorEntry
* ae
;
2371 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2372 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2377 else if (PyTuple_Check(o
)) {
2378 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2379 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2380 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2381 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2384 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2392 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2393 if (!PyList_Check(source
)) {
2394 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2397 int count
= PyList_Size(source
);
2398 wxPen
** temp
= new wxPen
*[count
];
2400 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2403 for (int x
=0; x
<count
; x
++) {
2404 PyObject
* o
= PyList_GetItem(source
, x
);
2405 if (wxPySwigInstance_Check(o
)) {
2407 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2409 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2416 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2424 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2425 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2428 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2432 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2433 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2436 o1
= PySequence_GetItem(source
, 0);
2437 o2
= PySequence_GetItem(source
, 1);
2440 *i1
= PyInt_AsLong(o1
);
2441 *i2
= PyInt_AsLong(o2
);
2451 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2452 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2453 PyObject
*o1
, *o2
, *o3
, *o4
;
2455 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2459 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2460 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2461 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2462 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2465 o1
= PySequence_GetItem(source
, 0);
2466 o2
= PySequence_GetItem(source
, 1);
2467 o3
= PySequence_GetItem(source
, 2);
2468 o4
= PySequence_GetItem(source
, 3);
2471 *i1
= PyInt_AsLong(o1
);
2472 *i2
= PyInt_AsLong(o2
);
2473 *i3
= PyInt_AsLong(o3
);
2474 *i4
= PyInt_AsLong(o4
);
2486 //----------------------------------------------------------------------
2488 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2492 if (wxPySwigInstance_Check(source
) &&
2493 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2497 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2503 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2505 if (source
== Py_None
) {
2506 **obj
= wxSize(-1,-1);
2509 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2513 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2515 if (source
== Py_None
) {
2516 **obj
= wxPoint(-1,-1);
2519 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2524 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2526 if (source
== Py_None
) {
2527 **obj
= wxRealPoint(-1,-1);
2531 // If source is an object instance then it may already be the right type
2532 if (wxPySwigInstance_Check(source
)) {
2534 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2539 // otherwise a 2-tuple of floats is expected
2540 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2541 PyObject
* o1
= PySequence_GetItem(source
, 0);
2542 PyObject
* o2
= PySequence_GetItem(source
, 1);
2543 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2548 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2555 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2561 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2563 if (source
== Py_None
) {
2564 **obj
= wxRect(-1,-1,-1,-1);
2568 // If source is an object instance then it may already be the right type
2569 if (wxPySwigInstance_Check(source
)) {
2571 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2576 // otherwise a 4-tuple of integers is expected
2577 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2578 PyObject
* o1
= PySequence_GetItem(source
, 0);
2579 PyObject
* o2
= PySequence_GetItem(source
, 1);
2580 PyObject
* o3
= PySequence_GetItem(source
, 2);
2581 PyObject
* o4
= PySequence_GetItem(source
, 3);
2582 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2583 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2590 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2591 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2600 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2606 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2608 if (source
== Py_None
) {
2609 **obj
= wxNullColour
;
2613 // If source is an object instance then it may already be the right type
2614 if (wxPySwigInstance_Check(source
)) {
2616 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2621 // otherwise check for a string
2622 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2623 wxString spec
= Py2wxString(source
);
2624 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2625 long red
, green
, blue
;
2626 red
= green
= blue
= 0;
2627 spec
.Mid(1,2).ToLong(&red
, 16);
2628 spec
.Mid(3,2).ToLong(&green
, 16);
2629 spec
.Mid(5,2).ToLong(&blue
, 16);
2631 **obj
= wxColour(red
, green
, blue
);
2634 else { // it's a colour name
2635 **obj
= wxColour(spec
);
2639 // last chance: 3-tuple or 4-tuple of integers is expected
2640 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2641 PyObject
* o1
= PySequence_GetItem(source
, 0);
2642 PyObject
* o2
= PySequence_GetItem(source
, 1);
2643 PyObject
* o3
= PySequence_GetItem(source
, 2);
2644 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2650 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2656 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2657 PyObject
* o1
= PySequence_GetItem(source
, 0);
2658 PyObject
* o2
= PySequence_GetItem(source
, 1);
2659 PyObject
* o3
= PySequence_GetItem(source
, 2);
2660 PyObject
* o4
= PySequence_GetItem(source
, 3);
2661 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2668 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2677 PyErr_SetString(PyExc_TypeError
,
2678 "Expected a wxColour object, a string containing a colour name or '#RRGGBB', or a 3- or 4-tuple of integers.");
2683 bool wxColour_typecheck(PyObject
* source
) {
2685 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2688 if (PyString_Check(source
) || PyUnicode_Check(source
))
2696 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2698 if (source
== Py_None
) {
2699 **obj
= wxPoint2D(-1,-1);
2703 // If source is an object instance then it may already be the right type
2704 if (wxPySwigInstance_Check(source
)) {
2706 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2711 // otherwise a length-2 sequence of floats is expected
2712 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2713 PyObject
* o1
= PySequence_GetItem(source
, 0);
2714 PyObject
* o2
= PySequence_GetItem(source
, 1);
2715 // This should really check for floats, not numbers -- but that would break code.
2716 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2721 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2727 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2732 //----------------------------------------------------------------------
2734 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
)
2736 PyObject
* list
= PyList_New(0);
2737 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2739 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2741 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2743 PyList_Append(list
, str
);
2750 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
)
2752 PyObject
* list
= PyList_New(0);
2753 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2754 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2755 PyList_Append(list
, number
);
2762 PyObject
* wxArrayDouble2PyList_helper(const wxArrayDouble
& arr
)
2764 PyObject
* list
= PyList_New(0);
2765 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2766 PyObject
* number
= PyFloat_FromDouble(arr
[i
]);
2767 PyList_Append(list
, number
);
2774 //----------------------------------------------------------------------
2775 // wxPyImageHandler methods
2777 // TODO: Switch these to use wxPython's standard macros and helper classes
2778 // for calling callbacks.
2780 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2781 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2782 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2783 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2785 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2786 return wxPyConstructObject(new wxPyInputStream(stream
),
2787 wxT("wxPyInputStream"), 0);
2790 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2791 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2794 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2795 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2798 wxPyImageHandler::wxPyImageHandler():
2801 if (!m_DoCanRead_Name
) {
2802 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2803 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2804 m_LoadFile_Name
= PyString_FromString("LoadFile");
2805 m_SaveFile_Name
= PyString_FromString("SaveFile");
2809 wxPyImageHandler::~wxPyImageHandler() {
2816 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2817 // should check here for isinstance(PyImageHandler) ??
2822 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2823 // check if our object has this method
2824 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2825 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2826 wxPyEndBlockThreads(blocked
);
2830 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2831 py_InputStream(&stream
), NULL
);
2832 bool retval
= false;
2834 retval
= PyInt_AsLong(res
);
2840 wxPyEndBlockThreads(blocked
);
2844 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2845 bool verbose
, int index
) {
2846 // check if our object has this method
2847 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2848 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2849 wxPyEndBlockThreads(blocked
);
2852 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2854 py_InputStream(&stream
),
2855 PyInt_FromLong(verbose
),
2856 PyInt_FromLong(index
),
2858 bool retval
= false;
2860 retval
= PyInt_AsLong(res
);
2865 wxPyEndBlockThreads(blocked
);
2869 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2871 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2872 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2873 wxPyEndBlockThreads(blocked
);
2876 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2878 py_OutputStream(&stream
),
2879 PyInt_FromLong(verbose
),
2881 bool retval
= false;
2883 retval
=PyInt_AsLong(res
);
2888 wxPyEndBlockThreads(blocked
);
2892 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2893 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2894 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2895 wxPyEndBlockThreads(blocked
);
2898 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2899 py_InputStream(&stream
),
2903 retval
=PyInt_AsLong(res
);
2908 wxPyEndBlockThreads(blocked
);
2913 //----------------------------------------------------------------------
2914 // Function to test if the Display (or whatever is the platform equivallent)
2915 // can be connected to. This is accessable from wxPython as a staticmethod of
2916 // wx.App called DisplayAvailable().
2919 bool wxPyTestDisplayAvailable()
2923 display
= XOpenDisplay(NULL
);
2924 if (display
== NULL
)
2926 XCloseDisplay(display
);
2931 // This is adapted from Python's Mac/Modules/MacOS.c in the
2932 // MacOS_WMAvailable function.
2934 ProcessSerialNumber psn
;
2937 ** This is a fairly innocuous call to make if we don't have a window
2938 ** manager, or if we have no permission to talk to it. It will print
2939 ** a message on stderr, but at least it won't abort the process.
2940 ** It appears the function caches the result itself, and it's cheap, so
2941 ** no need for us to cache.
2943 #ifdef kCGNullDirectDisplay
2944 /* On 10.1 CGMainDisplayID() isn't available, and
2945 ** kCGNullDirectDisplay isn't defined.
2947 if (CGMainDisplayID() == 0) {
2952 // Also foreground the application on the first call as a side-effect.
2953 if (GetCurrentProcess(&psn
) < 0 || SetFrontProcess(&psn
) < 0) {
2969 //----------------------------------------------------------------------
2970 //----------------------------------------------------------------------