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"
21 #include <wx/msw/private.h>
22 #include <wx/msw/winundef.h>
23 #include <wx/msw/msvcrt.h>
30 #include <gdk/gdkprivate.h>
31 #include <wx/gtk/win_gtk.h>
32 #define GetXWindow(wxwin) (wxwin)->m_wxwindow ? \
33 GDK_WINDOW_XWINDOW(GTK_PIZZA((wxwin)->m_wxwindow)->bin_window) : \
34 GDK_WINDOW_XWINDOW((wxwin)->m_widget->window)
39 #include "wx/x11/privx.h"
40 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
44 #include <wx/mac/private.h>
47 #include <wx/clipbrd.h>
48 #include <wx/mimetype.h>
51 //----------------------------------------------------------------------
53 #if PYTHON_API_VERSION < 1009 && wxUSE_UNICODE
54 #error Python must support Unicode to use wxWindows Unicode
57 //----------------------------------------------------------------------
59 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
60 bool wxPyDoCleanup
= false;
61 bool wxPyDoingCleanup
= false;
64 #ifdef WXP_WITH_THREAD
65 #if !wxPyUSE_GIL_STATE
66 struct wxPyThreadState
{
68 PyThreadState
* tstate
;
70 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
71 : tid(_tid
), tstate(_tstate
) {}
74 #include <wx/dynarray.h>
75 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
76 #include <wx/arrimpl.cpp>
77 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
79 wxPyThreadStateArray
* wxPyTStates
= NULL
;
80 wxMutex
* wxPyTMutex
= NULL
;
86 #define DEFAULTENCODING_SIZE 64
87 static char wxPyDefaultEncoding
[DEFAULTENCODING_SIZE
] = "ascii";
89 static PyObject
* wxPython_dict
= NULL
;
90 static PyObject
* wxPyAssertionError
= NULL
;
91 static PyObject
* wxPyNoAppError
= NULL
;
93 PyObject
* wxPyPtrTypeMap
= NULL
;
96 #ifdef __WXMSW__ // If building for win32...
97 //----------------------------------------------------------------------
98 // This gets run when the DLL is loaded. We just need to save a handle.
99 //----------------------------------------------------------------------
103 HINSTANCE hinstDLL
, // handle to DLL module
104 DWORD fdwReason
, // reason for calling function
105 LPVOID lpvReserved
// reserved
108 // If wxPython is embedded in another wxWidgets app then
109 // the instance has already been set.
110 if (! wxGetInstance())
111 wxSetInstance(hinstDLL
);
116 //----------------------------------------------------------------------
117 // Classes for implementing the wxp main application shell.
118 //----------------------------------------------------------------------
120 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
124 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
125 m_startupComplete
= false;
129 wxPyApp::~wxPyApp() {
131 wxApp::SetInstance(NULL
);
135 // This one isn't acutally called... We fake it with _BootstrapApp
136 bool wxPyApp::OnInit() {
141 int wxPyApp::MainLoop() {
144 DeletePendingObjects();
145 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
147 if ( m_exitOnFrameDelete
== Later
) {
148 m_exitOnFrameDelete
= Yes
;
151 retval
= wxApp::MainLoop();
158 bool wxPyApp::OnInitGui() {
160 wxApp::OnInitGui(); // in this case always call the base class version
161 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
162 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
163 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
164 wxPyEndBlockThreads(blocked
);
169 int wxPyApp::OnExit() {
171 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
172 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
173 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
174 wxPyEndBlockThreads(blocked
);
175 wxApp::OnExit(); // in this case always call the base class version
181 void wxPyApp::ExitMainLoop() {
183 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
184 if ((found
= wxPyCBH_findCallback(m_myInst
, "ExitMainLoop")))
185 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
186 wxPyEndBlockThreads(blocked
);
188 wxApp::ExitMainLoop();
193 void wxPyApp::OnAssert(const wxChar
*file
,
198 // if we're not fully initialized then just log the error
199 if (! m_startupComplete
) {
202 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
212 // If the OnAssert is overloaded in the Python class then call it...
214 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
215 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
216 PyObject
* fso
= wx2PyString(file
);
217 PyObject
* cso
= wx2PyString(file
);
220 mso
= wx2PyString(file
);
222 mso
= Py_None
; Py_INCREF(Py_None
);
224 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
229 wxPyEndBlockThreads(blocked
);
231 // ...otherwise do our own thing with it
234 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
237 // turn it into a Python exception?
238 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
241 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
248 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
249 PyObject
* s
= wx2PyString(buf
);
250 PyErr_SetObject(wxPyAssertionError
, s
);
252 wxPyEndBlockThreads(blocked
);
254 // Now when control returns to whatever API wrapper was called from
255 // Python it should detect that an exception is set and will return
256 // NULL, signalling the exception to Python.
259 // Send it to the normal log destination, but only if
260 // not _DIALOG because it will call this too
261 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
264 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
273 // do the normal wx assert dialog?
274 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
275 wxApp::OnAssert(file
, line
, cond
, msg
);
280 // For catching Apple Events
281 void wxPyApp::MacOpenFile(const wxString
&fileName
)
283 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
284 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
285 PyObject
* s
= wx2PyString(fileName
);
286 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
289 wxPyEndBlockThreads(blocked
);
292 void wxPyApp::MacPrintFile(const wxString
&fileName
)
294 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
295 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
296 PyObject
* s
= wx2PyString(fileName
);
297 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
300 wxPyEndBlockThreads(blocked
);
303 void wxPyApp::MacNewFile()
305 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
306 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
307 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
308 wxPyEndBlockThreads(blocked
);
311 void wxPyApp::MacReopenApp()
313 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
314 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
315 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
316 wxPyEndBlockThreads(blocked
);
321 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
323 return s_macSupportPCMenuShortcuts
;
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 val
) {
368 s_macSupportPCMenuShortcuts
= val
;
373 void wxPyApp::SetMacAboutMenuItemId(long val
) {
375 s_macAboutMenuItemId
= val
;
380 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
382 s_macPreferencesMenuItemId
= val
;
387 void wxPyApp::SetMacExitMenuItemId(long val
) {
389 s_macExitMenuItemId
= val
;
394 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
396 s_macHelpMenuTitleName
= val
;
401 // This finishes the initialization of wxWindows and then calls the OnInit
402 // that should be present in the derived (Python) class.
403 void wxPyApp::_BootstrapApp()
405 static bool haveInitialized
= false;
408 PyObject
* retval
= NULL
;
409 PyObject
* pyint
= NULL
;
412 // Only initialize wxWidgets once
413 if (! haveInitialized
) {
415 // Get any command-line args passed to this program from the sys module
418 blocked
= wxPyBeginBlockThreads();
420 PyObject
* sysargv
= PySys_GetObject("argv");
421 PyObject
* executable
= PySys_GetObject("executable");
423 if (sysargv
!= NULL
&& executable
!= NULL
) {
424 argc
= PyList_Size(sysargv
) + 1;
425 argv
= new char*[argc
+1];
426 argv
[0] = strdup(PyString_AsString(executable
));
428 for(x
=1; x
<argc
; x
++) {
429 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
430 argv
[x
] = strdup(PyString_AsString(pyArg
));
434 wxPyEndBlockThreads(blocked
);
436 // Initialize wxWidgets
437 result
= wxEntryStart(argc
, argv
);
438 // wxApp takes ownership of the argv array, don't delete it here
440 blocked
= wxPyBeginBlockThreads();
442 PyErr_SetString(PyExc_SystemError
,
443 "wxEntryStart failed, unable to initialize wxWidgets!"
445 " (Is DISPLAY set properly?)"
451 // On wxGTK the locale will be changed to match the system settings,
452 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
453 // for the floating point conversions and such to work right.
454 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
455 setlocale(LC_NUMERIC
, "C");
458 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
460 wxPyEndBlockThreads(blocked
);
461 haveInitialized
= true;
469 // It's now ok to generate exceptions for assertion errors.
470 wxPythonApp
->SetStartupComplete(true);
472 // Call the Python wxApp's OnInit function
473 blocked
= wxPyBeginBlockThreads();
474 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
476 PyObject
* method
= m_myInst
.GetLastFound();
477 PyObject
* argTuple
= PyTuple_New(0);
478 retval
= PyEval_CallObject(method
, argTuple
);
479 m_myInst
.clearRecursionGuard(method
);
485 pyint
= PyNumber_Int(retval
);
487 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
490 result
= PyInt_AS_LONG(pyint
);
493 // Is it okay if there is no OnInit? Probably so...
498 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
505 wxPyEndBlockThreads(blocked
);
508 //---------------------------------------------------------------------
509 //----------------------------------------------------------------------
513 static char* wxPyCopyCString(const wxChar
* src
)
515 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
516 size_t len
= strlen(buff
);
517 char* dest
= new char[len
+1];
523 static char* wxPyCopyCString(const char* src
) // we need a char version too
525 size_t len
= strlen(src
);
526 char* dest
= new char[len
+1];
532 static wxChar
* wxPyCopyWString(const char *src
)
534 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
535 wxString
str(src
, *wxConvCurrent
);
536 return copystring(str
);
540 static wxChar
* wxPyCopyWString(const wxChar
*src
)
542 return copystring(src
);
548 inline const char* dropwx(const char* name
) {
549 if (name
[0] == 'w' && name
[1] == 'x')
555 //----------------------------------------------------------------------
557 // This function is called when the wx._core_ module is imported to do some
558 // initial setup. (Before there is a wxApp object.) The rest happens in
559 // wxPyApp::_BootstrapApp
560 void __wxPyPreStart(PyObject
* moduleDict
)
564 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
565 // | _CRTDBG_CHECK_ALWAYS_DF
566 // | _CRTDBG_DELAY_FREE_MEM_DF
570 #ifdef WXP_WITH_THREAD
571 #if wxPyUSE_GIL_STATE
572 PyEval_InitThreads();
574 PyEval_InitThreads();
575 wxPyTStates
= new wxPyThreadStateArray
;
576 wxPyTMutex
= new wxMutex
;
578 // Save the current (main) thread state in our array
579 PyThreadState
* tstate
= wxPyBeginAllowThreads();
580 wxPyEndAllowThreads(tstate
);
584 // Ensure that the build options in the DLL (or whatever) match this build
585 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
587 wxInitAllImageHandlers();
592 void __wxPyCleanup() {
593 wxPyDoingCleanup
= true;
595 wxPyDoCleanup
= false;
598 #ifdef WXP_WITH_THREAD
599 #if !wxPyUSE_GIL_STATE
602 wxPyTStates
->Empty();
610 // Save a reference to the dictionary of the wx._core module, and inject
611 // a few more things into it.
612 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
615 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
618 if (!PyDict_Check(wxPython_dict
)) {
619 PyErr_SetString(PyExc_TypeError
,
620 "_wxPySetDictionary must have dictionary object!");
624 if (! wxPyPtrTypeMap
)
625 wxPyPtrTypeMap
= PyDict_New();
626 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
628 // Create an exception object to use for wxASSERTions
629 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
630 PyExc_AssertionError
, NULL
);
631 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
633 // Create an exception object to use when the app object hasn't been created yet
634 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
635 PyExc_RuntimeError
, NULL
);
636 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
641 #define wxPlatform "__WXMOTIF__"
642 #define wxPlatName "wxMotif"
645 #define wxPlatform "__WXX11__"
646 #define wxPlatName "wxX11"
649 #define wxPlatform "__WXGTK__"
650 #define wxPlatName "wxGTK"
653 #define wxPlatform "__WXMSW__"
654 #define wxPlatName "wxMSW"
657 #define wxPlatform "__WXMAC__"
658 #define wxPlatName "wxMac"
667 // These should be deprecated in favor of the PlatformInfo tuple built below...
668 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
669 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
670 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
672 // Make a tuple of strings that gives more info about the platform.
673 PyObject
* PlatInfo
= PyList_New(0);
676 #define _AddInfoString(st) \
677 obj = PyString_FromString(st); \
678 PyList_Append(PlatInfo, obj); \
681 _AddInfoString(wxPlatform
);
682 _AddInfoString(wxPlatName
);
684 _AddInfoString("unicode");
686 _AddInfoString("ansi");
690 _AddInfoString("gtk2");
692 _AddInfoString("gtk1");
696 _AddInfoString("wx-assertions-on");
698 _AddInfoString("wx-assertions-off");
700 _AddInfoString(wxPy_SWIG_VERSION
);
702 #undef _AddInfoString
704 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
706 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
713 //---------------------------------------------------------------------------
715 // Check for existence of a wxApp, setting an exception if there isn't one.
716 // This doesn't need to aquire the GIL because it should only be called from
717 // an %exception before the lock is released.
719 bool wxPyCheckForApp() {
720 if (wxTheApp
!= NULL
)
723 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
728 //---------------------------------------------------------------------------
730 void wxPyUserData_dtor(wxPyUserData
* self
) {
731 if (! wxPyDoingCleanup
) {
732 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
733 Py_DECREF(self
->m_obj
);
735 wxPyEndBlockThreads(blocked
);
740 void wxPyClientData_dtor(wxPyClientData
* self
) {
741 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
742 // may have already garbage collected the object...
743 if (self
->m_incRef
) {
744 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
745 Py_DECREF(self
->m_obj
);
746 wxPyEndBlockThreads(blocked
);
754 // This is called when an OOR controled object is being destroyed. Although
755 // the C++ object is going away there is no way to force the Python object
756 // (and all references to it) to die too. This causes problems (crashes) in
757 // wxPython when a python shadow object attempts to call a C++ method using
758 // the now bogus pointer... So to try and prevent this we'll do a little black
759 // magic and change the class of the python instance to a class that will
760 // raise an exception for any attempt to call methods with it. See
761 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
762 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
764 static PyObject
* deadObjectClass
= NULL
;
766 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
767 if (deadObjectClass
== NULL
) {
768 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
769 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
770 // will lead to a deadlock when it tries to aquire the GIL again.
771 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
772 Py_INCREF(deadObjectClass
);
776 // Only if there is more than one reference to the object and we are
777 // holding the OOR reference:
778 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
779 // bool isInstance = wxPyInstance_Check(self->m_obj);
781 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
783 // Call __del__, if there is one.
784 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
786 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
790 if (PyErr_Occurred())
791 PyErr_Clear(); // just ignore it for now
794 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
796 // Clear the instance's dictionary
799 // put the name of the old class into the instance, and then reset the
800 // class to be the dead class.
801 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
802 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
803 PyDict_SetItemString(dict
, "_name", name
);
804 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
805 //Py_INCREF(deadObjectClass);
811 // m_obj is DECREF'd in the base class dtor...
812 wxPyEndBlockThreads(blocked
);
816 //---------------------------------------------------------------------------
817 // Stuff used by OOR to find the right wxPython class type to return and to
821 // The pointer type map is used when the "pointer" type name generated by SWIG
822 // is not the same as the shadow class name, for example wxPyTreeCtrl
823 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
824 // so we'll just make it a Python dictionary in the wx module's namespace.
825 // (See __wxSetDictionary)
826 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
827 if (! wxPyPtrTypeMap
)
828 wxPyPtrTypeMap
= PyDict_New();
829 PyDict_SetItemString(wxPyPtrTypeMap
,
831 PyString_FromString((char*)ptrName
));
837 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
838 PyObject
* target
= NULL
;
839 bool isEvtHandler
= false;
840 bool isSizer
= false;
843 // If it's derived from wxEvtHandler then there may
844 // already be a pointer to a Python object that we can use
846 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
848 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
849 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
851 target
= data
->m_obj
;
857 // Also check for wxSizer
858 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
860 wxSizer
* sz
= (wxSizer
*)source
;
861 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
863 target
= data
->m_obj
;
870 // Otherwise make it the old fashioned way by making a new shadow
871 // object and putting this pointer in it. Look up the class
872 // heirarchy until we find a class name that is located in the
874 const wxClassInfo
* info
= source
->GetClassInfo();
875 wxString name
= info
->GetClassName();
876 bool exists
= wxPyCheckSwigType(name
);
877 while (info
&& !exists
) {
878 info
= info
->GetBaseClass1();
879 name
= info
->GetClassName();
880 exists
= wxPyCheckSwigType(name
);
883 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
884 if (target
&& isEvtHandler
)
885 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
886 if (target
&& isSizer
)
887 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
889 wxString
msg(wxT("wxPython class not found for "));
890 msg
+= source
->GetClassInfo()->GetClassName();
891 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
895 } else { // source was NULL so return None.
896 Py_INCREF(Py_None
); target
= Py_None
;
902 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
904 return wxPyMake_wxObject(source
, setThisOwn
);
908 //---------------------------------------------------------------------------
911 #ifdef WXP_WITH_THREAD
912 #if !wxPyUSE_GIL_STATE
915 unsigned long wxPyGetCurrentThreadId() {
916 return wxThread::GetCurrentId();
919 static wxPyThreadState gs_shutdownTState
;
922 wxPyThreadState
* wxPyGetThreadState() {
923 if (wxPyTMutex
== NULL
) // Python is shutting down...
924 return &gs_shutdownTState
;
926 unsigned long ctid
= wxPyGetCurrentThreadId();
927 wxPyThreadState
* tstate
= NULL
;
930 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
931 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
932 if (info
.tid
== ctid
) {
937 wxPyTMutex
->Unlock();
938 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
944 void wxPySaveThreadState(PyThreadState
* tstate
) {
945 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
946 gs_shutdownTState
.tstate
= tstate
;
949 unsigned long ctid
= wxPyGetCurrentThreadId();
951 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
952 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
953 if (info
.tid
== ctid
) {
955 if (info
.tstate
!= tstate
)
956 wxLogMessage("*** tstate mismatch!???");
958 info
.tstate
= tstate
; // allow for transient tstates
959 // Normally it will never change, but apparently COM callbacks
960 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
961 // tstate which will then be garbage the next time we try to use
964 wxPyTMutex
->Unlock();
968 // not found, so add it...
969 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
970 wxPyTMutex
->Unlock();
978 // Calls from Python to wxWindows code are wrapped in calls to these
981 PyThreadState
* wxPyBeginAllowThreads() {
982 #ifdef WXP_WITH_THREAD
983 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
984 #if !wxPyUSE_GIL_STATE
985 wxPySaveThreadState(saved
);
993 void wxPyEndAllowThreads(PyThreadState
* saved
) {
994 #ifdef WXP_WITH_THREAD
995 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1001 // Calls from wxWindows back to Python code, or even any PyObject
1002 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1004 wxPyBlock_t
wxPyBeginBlockThreads() {
1005 #ifdef WXP_WITH_THREAD
1006 if (! Py_IsInitialized()) {
1007 return (wxPyBlock_t
)0;
1009 #if wxPyUSE_GIL_STATE
1010 PyGILState_STATE state
= PyGILState_Ensure();
1013 PyThreadState
*current
= _PyThreadState_Current
;
1015 // Only block if there wasn't already a tstate, or if the current one is
1016 // not the one we are wanting to change to. This should prevent deadlock
1017 // if there are nested calls to wxPyBeginBlockThreads
1018 wxPyBlock_t blocked
= false;
1019 wxPyThreadState
* tstate
= wxPyGetThreadState();
1020 if (current
!= tstate
->tstate
) {
1021 PyEval_RestoreThread(tstate
->tstate
);
1027 return (wxPyBlock_t
)0;
1032 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1033 #ifdef WXP_WITH_THREAD
1034 if (! Py_IsInitialized()) {
1037 #if wxPyUSE_GIL_STATE
1038 PyGILState_Release(blocked
);
1040 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1041 // The value of blocked passed in needs to be the same as that returned
1042 // from wxPyBeginBlockThreads at the same nesting level.
1044 PyEval_SaveThread();
1051 //---------------------------------------------------------------------------
1052 // wxPyInputStream and wxPyCBInputStream methods
1055 void wxPyInputStream::close() {
1056 /* do nothing for now */
1059 void wxPyInputStream::flush() {
1060 /* do nothing for now */
1063 bool wxPyInputStream::eof() {
1065 return m_wxis
->Eof();
1070 wxPyInputStream::~wxPyInputStream() {
1078 PyObject
* wxPyInputStream::read(int size
) {
1079 PyObject
* obj
= NULL
;
1081 const int BUFSIZE
= 1024;
1083 // check if we have a real wxInputStream to work with
1085 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1086 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1087 wxPyEndBlockThreads(blocked
);
1092 // read while bytes are available on the stream
1093 while ( m_wxis
->CanRead() ) {
1094 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1095 buf
.UngetAppendBuf(m_wxis
->LastRead());
1098 } else { // Read only size number of characters
1099 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1100 buf
.UngetWriteBuf(m_wxis
->LastRead());
1104 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1105 wxStreamError err
= m_wxis
->GetLastError();
1106 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1107 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1110 // We use only strings for the streams, not unicode
1111 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1113 wxPyEndBlockThreads(blocked
);
1118 PyObject
* wxPyInputStream::readline(int size
) {
1119 PyObject
* obj
= NULL
;
1124 // check if we have a real wxInputStream to work with
1126 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1127 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1128 wxPyEndBlockThreads(blocked
);
1132 // read until \n or byte limit reached
1133 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1134 ch
= m_wxis
->GetC();
1139 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1140 wxStreamError err
= m_wxis
->GetLastError();
1141 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1142 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1145 // We use only strings for the streams, not unicode
1146 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1148 wxPyEndBlockThreads(blocked
);
1153 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1156 // check if we have a real wxInputStream to work with
1158 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1159 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1160 wxPyEndBlockThreads(blocked
);
1165 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1166 pylist
= PyList_New(0);
1167 wxPyEndBlockThreads(blocked
);
1170 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1172 wxPyEndBlockThreads(blocked
);
1176 // read sizehint bytes or until EOF
1178 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1179 PyObject
* s
= this->readline();
1181 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1183 wxPyEndBlockThreads(blocked
);
1186 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1187 PyList_Append(pylist
, s
);
1188 i
+= PyString_Size(s
);
1189 wxPyEndBlockThreads(blocked
);
1193 wxStreamError err
= m_wxis
->GetLastError();
1194 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1195 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1197 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1198 wxPyEndBlockThreads(blocked
);
1206 void wxPyInputStream::seek(int offset
, int whence
) {
1208 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1211 int wxPyInputStream::tell(){
1213 return m_wxis
->TellI();
1220 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1221 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1224 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1226 m_read
= other
.m_read
;
1227 m_seek
= other
.m_seek
;
1228 m_tell
= other
.m_tell
;
1229 m_block
= other
.m_block
;
1236 wxPyCBInputStream::~wxPyCBInputStream() {
1237 wxPyBlock_t blocked
;
1238 if (m_block
) blocked
= wxPyBeginBlockThreads();
1242 if (m_block
) wxPyEndBlockThreads(blocked
);
1246 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1247 wxPyBlock_t blocked
;
1248 if (block
) blocked
= wxPyBeginBlockThreads();
1250 PyObject
* read
= getMethod(py
, "read");
1251 PyObject
* seek
= getMethod(py
, "seek");
1252 PyObject
* tell
= getMethod(py
, "tell");
1255 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1259 if (block
) wxPyEndBlockThreads(blocked
);
1263 if (block
) wxPyEndBlockThreads(blocked
);
1264 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1268 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1269 return wxPyCBInputStream::create(py
, block
);
1272 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1273 return new wxPyCBInputStream(*other
);
1276 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1277 if (!PyObject_HasAttrString(py
, name
))
1279 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1280 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1288 wxFileOffset
wxPyCBInputStream::GetLength() const {
1289 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1290 if (m_seek
&& m_tell
) {
1291 wxFileOffset temp
= self
->OnSysTell();
1292 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1293 self
->OnSysSeek(temp
, wxFromStart
);
1297 return wxInvalidOffset
;
1301 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1305 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1306 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1307 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1311 if ((result
!= NULL
) && PyString_Check(result
)) {
1312 o
= PyString_Size(result
);
1314 m_lasterror
= wxSTREAM_EOF
;
1317 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1322 m_lasterror
= wxSTREAM_READ_ERROR
;
1323 wxPyEndBlockThreads(blocked
);
1327 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1328 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1333 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1334 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1335 PyObject
* arglist
= PyTuple_New(2);
1337 if (sizeof(wxFileOffset
) > sizeof(long))
1338 // wxFileOffset is a 64-bit value...
1339 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1341 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1343 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1346 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1349 wxPyEndBlockThreads(blocked
);
1354 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1355 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1356 PyObject
* arglist
= Py_BuildValue("()");
1357 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1360 if (result
!= NULL
) {
1361 if (PyLong_Check(result
))
1362 o
= PyLong_AsLongLong(result
);
1364 o
= PyInt_AsLong(result
);
1367 wxPyEndBlockThreads(blocked
);
1371 //----------------------------------------------------------------------
1373 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1375 wxPyCallback::wxPyCallback(PyObject
* func
) {
1380 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1381 m_func
= other
.m_func
;
1385 wxPyCallback::~wxPyCallback() {
1386 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1388 wxPyEndBlockThreads(blocked
);
1392 #define wxPy_PRECALLINIT "_preCallInit"
1393 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1395 // This function is used for all events destined for Python event handlers.
1396 void wxPyCallback::EventThunker(wxEvent
& event
) {
1397 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1398 PyObject
* func
= cb
->m_func
;
1402 bool checkSkip
= false;
1404 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1405 wxString className
= event
.GetClassInfo()->GetClassName();
1407 // If the event is one of these types then pass the original
1408 // event object instead of the one passed to us.
1409 if ( className
== wxT("wxPyEvent") ) {
1410 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1411 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1413 else if ( className
== wxT("wxPyCommandEvent") ) {
1414 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1415 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1418 arg
= wxPyConstructObject((void*)&event
, className
);
1424 // "intern" the pre/post method names to speed up the HasAttr
1425 static PyObject
* s_preName
= NULL
;
1426 static PyObject
* s_postName
= NULL
;
1427 if (s_preName
== NULL
) {
1428 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1429 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1432 // Check if the event object needs some preinitialization
1433 if (PyObject_HasAttr(arg
, s_preName
)) {
1434 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1436 Py_DECREF(result
); // result is ignored, but we still need to decref it
1437 PyErr_Clear(); // Just in case...
1443 // Call the event handler, passing the event object
1444 tuple
= PyTuple_New(1);
1445 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1446 result
= PyEval_CallObject(func
, tuple
);
1448 Py_DECREF(result
); // result is ignored, but we still need to decref it
1449 PyErr_Clear(); // Just in case...
1454 // Check if the event object needs some post cleanup
1455 if (PyObject_HasAttr(arg
, s_postName
)) {
1456 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1458 Py_DECREF(result
); // result is ignored, but we still need to decref it
1459 PyErr_Clear(); // Just in case...
1466 // if the event object was one of our special types and
1467 // it had been cloned, then we need to extract the Skipped
1468 // value from the original and set it in the clone.
1469 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1471 event
.Skip(PyInt_AsLong(result
));
1479 wxPyEndBlockThreads(blocked
);
1483 //----------------------------------------------------------------------
1485 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1487 m_self
= other
.m_self
;
1488 m_class
= other
.m_class
;
1496 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1507 #if PYTHON_API_VERSION >= 1011
1509 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1510 // in which the method was defined. Starting with 2.2 it returns
1511 // "class that asked for the method" which seems totally bogus to me
1512 // but apprently it fixes some obscure problem waiting to happen in
1513 // Python. Since the API was not documented Guido and the gang felt
1514 // safe in changing it. Needless to say that totally screwed up the
1515 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1516 // code to find the class where the method is actually defined...
1519 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1523 if (PyType_Check(klass
)) { // new style classes
1524 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1525 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1526 PyObject
*mro
, *res
, *base
, *dict
;
1527 /* Look in tp_dict of types in MRO */
1529 assert(PyTuple_Check(mro
));
1530 n
= PyTuple_GET_SIZE(mro
);
1531 for (i
= 0; i
< n
; i
++) {
1532 base
= PyTuple_GET_ITEM(mro
, i
);
1533 if (PyClass_Check(base
))
1534 dict
= ((PyClassObject
*)base
)->cl_dict
;
1536 assert(PyType_Check(base
));
1537 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1539 assert(dict
&& PyDict_Check(dict
));
1540 res
= PyDict_GetItem(dict
, name
);
1547 else if (PyClass_Check(klass
)) { // old style classes
1548 // This code is borrowed/adapted from class_lookup in classobject.c
1549 PyClassObject
* cp
= (PyClassObject
*)klass
;
1550 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1551 if (value
!= NULL
) {
1552 return (PyObject
*)cp
;
1554 n
= PyTuple_Size(cp
->cl_bases
);
1555 for (i
= 0; i
< n
; i
++) {
1556 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1557 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1569 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, PyObject
* nameo
)
1571 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1573 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1575 #else // 2.2 and after, the hard way...
1576 return PyFindClassWithAttr(mgc
, nameo
);
1582 // To avoid recursion when an overridden virtual method wants to call the base
1583 // class version, temporarily set an attribute in the instance with the same
1584 // name as the method. Then the PyObject_GetAttr in the next findCallback
1585 // will return this attribute and the PyMethod_Check will fail.
1587 void wxPyCallbackHelper::setRecursionGuard(PyObject
* method
) const
1589 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1590 PyObject_SetAttr(m_self
, func
->func_name
, Py_None
);
1593 void wxPyCallbackHelper::clearRecursionGuard(PyObject
* method
) const
1595 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1596 if (PyObject_HasAttr(m_self
, func
->func_name
)) {
1597 PyObject_DelAttr(m_self
, func
->func_name
);
1601 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1603 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1604 // if (PyObject_HasAttr(m_self, func->func_name)) {
1605 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1606 // bool retval = (attr == Py_None);
1614 bool wxPyCallbackHelper::findCallback(const char* name
, bool setGuard
) const {
1615 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1616 PyObject
*method
, *klass
;
1617 PyObject
* nameo
= PyString_FromString(name
);
1618 self
->m_lastFound
= NULL
;
1620 // If the object (m_self) has an attibute of the given name...
1621 if (m_self
&& PyObject_HasAttr(m_self
, nameo
)) {
1622 method
= PyObject_GetAttr(m_self
, nameo
);
1624 // ...and if that attribute is a method, and if that method's class is
1625 // not from the registered class or a base class...
1626 if (PyMethod_Check(method
) &&
1627 (klass
= PyMethod_GetDefiningClass(method
, nameo
)) != NULL
&&
1628 (klass
!= m_class
) &&
1629 PyObject_IsSubclass(klass
, m_class
)) {
1631 // ...then we'll save a pointer to the method so callCallback can
1632 // call it. But first, set a recursion guard in case the
1633 // overridden method wants to call the base class version.
1635 setRecursionGuard(method
);
1636 self
->m_lastFound
= method
;
1644 return m_lastFound
!= NULL
;
1648 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1652 result
= callCallbackObj(argTuple
);
1653 if (result
) { // Assumes an integer return type...
1654 retval
= PyInt_AsLong(result
);
1656 PyErr_Clear(); // forget about it if it's not...
1661 // Invoke the Python callable object, returning the raw PyObject return
1662 // value. Caller should DECREF the return value and also manage the GIL.
1663 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1666 // Save a copy of the pointer in case the callback generates another
1667 // callback. In that case m_lastFound will have a different value when
1668 // it gets back here...
1669 PyObject
* method
= m_lastFound
;
1671 result
= PyEval_CallObject(method
, argTuple
);
1672 clearRecursionGuard(method
);
1674 Py_DECREF(argTuple
);
1683 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1684 cbh
.setSelf(self
, klass
, incref
);
1687 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
, bool setGuard
) {
1688 return cbh
.findCallback(name
, setGuard
);
1691 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1692 return cbh
.callCallback(argTuple
);
1695 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1696 return cbh
.callCallbackObj(argTuple
);
1700 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1701 if (cbh
->m_incRef
) {
1702 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1703 Py_XDECREF(cbh
->m_self
);
1704 Py_XDECREF(cbh
->m_class
);
1705 wxPyEndBlockThreads(blocked
);
1709 //---------------------------------------------------------------------------
1710 //---------------------------------------------------------------------------
1711 // These event classes can be derived from in Python and passed through the event
1712 // system without losing anything. They do this by keeping a reference to
1713 // themselves and some special case handling in wxPyCallback::EventThunker.
1716 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1717 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1718 //Py_INCREF(m_self); // circular loops...
1722 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1723 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1726 wxPyEndBlockThreads(blocked
);
1729 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1730 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1738 wxPyEndBlockThreads(blocked
);
1741 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1747 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1748 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1751 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1752 : wxEvent(winid
, commandType
) {
1756 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1759 SetSelf(evt
.m_self
, true);
1763 wxPyEvent::~wxPyEvent() {
1767 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1768 : wxCommandEvent(commandType
, id
) {
1772 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1773 : wxCommandEvent(evt
)
1775 SetSelf(evt
.m_self
, true);
1779 wxPyCommandEvent::~wxPyCommandEvent() {
1786 //---------------------------------------------------------------------------
1787 //---------------------------------------------------------------------------
1788 // Convert a wxList to a Python List, only works for lists of wxObjects
1790 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1791 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1795 wxNode
* node
= list
->GetFirst();
1797 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1798 pyList
= PyList_New(0);
1800 wxObj
= node
->GetData();
1801 pyObj
= wxPyMake_wxObject(wxObj
,false);
1802 PyList_Append(pyList
, pyObj
);
1803 node
= node
->GetNext();
1805 wxPyEndBlockThreads(blocked
);
1809 //----------------------------------------------------------------------
1811 long wxPyGetWinHandle(wxWindow
* win
) {
1814 return (long)win
->GetHandle();
1817 #if defined(__WXGTK__) || defined(__WXX11)
1818 return (long)GetXWindow(win
);
1822 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1823 return (long)win
->GetHandle();
1829 //----------------------------------------------------------------------
1830 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1831 // included in every file over and over again...
1833 wxString
* wxString_in_helper(PyObject
* source
) {
1834 wxString
* target
= NULL
;
1836 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1837 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1841 PyObject
* uni
= source
;
1842 if (PyString_Check(source
)) {
1843 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1844 if (PyErr_Occurred()) return NULL
;
1846 target
= new wxString();
1847 size_t len
= PyUnicode_GET_SIZE(uni
);
1849 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1850 target
->UngetWriteBuf(len
);
1853 if (PyString_Check(source
))
1856 // Convert to a string object if it isn't already, then to wxString
1857 PyObject
* str
= source
;
1858 if (PyUnicode_Check(source
)) {
1859 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1860 if (PyErr_Occurred()) return NULL
;
1862 else if (!PyString_Check(source
)) {
1863 str
= PyObject_Str(source
);
1864 if (PyErr_Occurred()) return NULL
;
1866 char* tmpPtr
; int tmpSize
;
1867 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1868 target
= new wxString(tmpPtr
, tmpSize
);
1870 if (!PyString_Check(source
))
1872 #endif // wxUSE_UNICODE
1878 // Similar to above except doesn't use "new" and doesn't set an exception
1879 wxString
Py2wxString(PyObject
* source
)
1884 // Convert to a unicode object, if not already, then to a wxString
1885 PyObject
* uni
= source
;
1886 if (!PyUnicode_Check(source
)) {
1887 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1888 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1890 size_t len
= PyUnicode_GET_SIZE(uni
);
1892 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1893 target
.UngetWriteBuf();
1896 if (!PyUnicode_Check(source
))
1899 // Convert to a string object if it isn't already, then to wxString
1900 PyObject
* str
= source
;
1901 if (PyUnicode_Check(source
)) {
1902 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1903 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1905 else if (!PyString_Check(source
)) {
1906 str
= PyObject_Str(source
);
1907 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1909 char* tmpPtr
; int tmpSize
;
1910 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1911 target
= wxString(tmpPtr
, tmpSize
);
1913 if (!PyString_Check(source
))
1915 #endif // wxUSE_UNICODE
1921 // Make either a Python String or Unicode object, depending on build mode
1922 PyObject
* wx2PyString(const wxString
& src
)
1926 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1928 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1935 void wxSetDefaultPyEncoding(const char* encoding
)
1937 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
1940 const char* wxGetDefaultPyEncoding()
1942 return wxPyDefaultEncoding
;
1945 //----------------------------------------------------------------------
1948 byte
* byte_LIST_helper(PyObject
* source
) {
1949 if (!PyList_Check(source
)) {
1950 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1953 int count
= PyList_Size(source
);
1954 byte
* temp
= new byte
[count
];
1956 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1959 for (int x
=0; x
<count
; x
++) {
1960 PyObject
* o
= PyList_GetItem(source
, x
);
1961 if (! PyInt_Check(o
)) {
1962 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1965 temp
[x
] = (byte
)PyInt_AsLong(o
);
1971 int* int_LIST_helper(PyObject
* source
) {
1972 if (!PyList_Check(source
)) {
1973 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1976 int count
= PyList_Size(source
);
1977 int* temp
= new int[count
];
1979 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1982 for (int x
=0; x
<count
; x
++) {
1983 PyObject
* o
= PyList_GetItem(source
, x
);
1984 if (! PyInt_Check(o
)) {
1985 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1988 temp
[x
] = PyInt_AsLong(o
);
1994 long* long_LIST_helper(PyObject
* source
) {
1995 if (!PyList_Check(source
)) {
1996 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1999 int count
= PyList_Size(source
);
2000 long* temp
= new long[count
];
2002 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2005 for (int x
=0; x
<count
; x
++) {
2006 PyObject
* o
= PyList_GetItem(source
, x
);
2007 if (! PyInt_Check(o
)) {
2008 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2011 temp
[x
] = PyInt_AsLong(o
);
2017 char** string_LIST_helper(PyObject
* source
) {
2018 if (!PyList_Check(source
)) {
2019 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2022 int count
= PyList_Size(source
);
2023 char** temp
= new char*[count
];
2025 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2028 for (int x
=0; x
<count
; x
++) {
2029 PyObject
* o
= PyList_GetItem(source
, x
);
2030 if (! PyString_Check(o
)) {
2031 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2034 temp
[x
] = PyString_AsString(o
);
2039 //--------------------------------
2040 // Part of patch from Tim Hochberg
2041 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2042 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2043 point
->x
= PyInt_AS_LONG(o1
);
2044 point
->y
= PyInt_AS_LONG(o2
);
2047 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2048 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2049 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2052 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2053 // Disallow instances because they can cause havok
2056 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2057 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2058 point
->x
= PyInt_AsLong(o1
);
2059 point
->y
= PyInt_AsLong(o2
);
2066 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2067 // Putting all of the declarations here allows
2068 // us to put the error handling all in one place.
2071 PyObject
*o
, *o1
, *o2
;
2072 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2074 if (!PySequence_Check(source
)) {
2078 // The length of the sequence is returned in count.
2079 *count
= PySequence_Length(source
);
2084 temp
= new wxPoint
[*count
];
2086 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2089 for (x
=0; x
<*count
; x
++) {
2090 // Get an item: try fast way first.
2092 o
= PySequence_Fast_GET_ITEM(source
, x
);
2095 o
= PySequence_GetItem(source
, x
);
2101 // Convert o to wxPoint.
2102 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2103 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2104 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2105 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2106 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2110 else if (wxPySwigInstance_Check(o
)) {
2112 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2117 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2118 o1
= PySequence_GetItem(o
, 0);
2119 o2
= PySequence_GetItem(o
, 1);
2120 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2144 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2148 //------------------------------
2151 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2152 if (!PyList_Check(source
)) {
2153 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2156 int count
= PyList_Size(source
);
2157 wxBitmap
** temp
= new wxBitmap
*[count
];
2159 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2162 for (int x
=0; x
<count
; x
++) {
2163 PyObject
* o
= PyList_GetItem(source
, x
);
2164 if (wxPySwigInstance_Check(o
)) {
2166 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2167 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2173 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2182 wxString
* wxString_LIST_helper(PyObject
* source
) {
2183 if (!PyList_Check(source
)) {
2184 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2187 int count
= PyList_Size(source
);
2188 wxString
* temp
= new wxString
[count
];
2190 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2193 for (int x
=0; x
<count
; x
++) {
2194 PyObject
* o
= PyList_GetItem(source
, x
);
2195 #if PYTHON_API_VERSION >= 1009
2196 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2197 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2201 if (! PyString_Check(o
)) {
2202 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2207 wxString
* pStr
= wxString_in_helper(o
);
2215 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2216 if (!PyList_Check(source
)) {
2217 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2220 int count
= PyList_Size(source
);
2221 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2223 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2226 for (int x
=0; x
<count
; x
++) {
2227 PyObject
* o
= PyList_GetItem(source
, x
);
2228 if (wxPySwigInstance_Check(o
)) {
2229 wxAcceleratorEntry
* ae
;
2230 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2231 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2236 else if (PyTuple_Check(o
)) {
2237 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2238 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2239 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2240 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2243 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2251 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2252 if (!PyList_Check(source
)) {
2253 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2256 int count
= PyList_Size(source
);
2257 wxPen
** temp
= new wxPen
*[count
];
2259 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2262 for (int x
=0; x
<count
; x
++) {
2263 PyObject
* o
= PyList_GetItem(source
, x
);
2264 if (wxPySwigInstance_Check(o
)) {
2266 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2268 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2275 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2283 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2284 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2287 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2291 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2292 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2295 o1
= PySequence_GetItem(source
, 0);
2296 o2
= PySequence_GetItem(source
, 1);
2299 *i1
= PyInt_AsLong(o1
);
2300 *i2
= PyInt_AsLong(o2
);
2310 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2311 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2312 PyObject
*o1
, *o2
, *o3
, *o4
;
2314 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2318 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2319 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2320 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2321 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2324 o1
= PySequence_GetItem(source
, 0);
2325 o2
= PySequence_GetItem(source
, 1);
2326 o3
= PySequence_GetItem(source
, 2);
2327 o4
= PySequence_GetItem(source
, 3);
2330 *i1
= PyInt_AsLong(o1
);
2331 *i2
= PyInt_AsLong(o2
);
2332 *i3
= PyInt_AsLong(o3
);
2333 *i4
= PyInt_AsLong(o4
);
2345 //----------------------------------------------------------------------
2347 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2351 if (wxPySwigInstance_Check(source
) &&
2352 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2356 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2362 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2364 if (source
== Py_None
) {
2365 **obj
= wxSize(-1,-1);
2368 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2372 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2374 if (source
== Py_None
) {
2375 **obj
= wxPoint(-1,-1);
2378 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2383 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2385 if (source
== Py_None
) {
2386 **obj
= wxRealPoint(-1,-1);
2390 // If source is an object instance then it may already be the right type
2391 if (wxPySwigInstance_Check(source
)) {
2393 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2398 // otherwise a 2-tuple of floats is expected
2399 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2400 PyObject
* o1
= PySequence_GetItem(source
, 0);
2401 PyObject
* o2
= PySequence_GetItem(source
, 1);
2402 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2407 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2414 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2420 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2422 if (source
== Py_None
) {
2423 **obj
= wxRect(-1,-1,-1,-1);
2427 // If source is an object instance then it may already be the right type
2428 if (wxPySwigInstance_Check(source
)) {
2430 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2435 // otherwise a 4-tuple of integers is expected
2436 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2437 PyObject
* o1
= PySequence_GetItem(source
, 0);
2438 PyObject
* o2
= PySequence_GetItem(source
, 1);
2439 PyObject
* o3
= PySequence_GetItem(source
, 2);
2440 PyObject
* o4
= PySequence_GetItem(source
, 3);
2441 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2442 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2449 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2450 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2459 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2465 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2467 if (source
== Py_None
) {
2468 **obj
= wxNullColour
;
2472 // If source is an object instance then it may already be the right type
2473 if (wxPySwigInstance_Check(source
)) {
2475 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2480 // otherwise check for a string
2481 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2482 wxString spec
= Py2wxString(source
);
2483 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2484 long red
, green
, blue
;
2485 red
= green
= blue
= 0;
2486 spec
.Mid(1,2).ToLong(&red
, 16);
2487 spec
.Mid(3,2).ToLong(&green
, 16);
2488 spec
.Mid(5,2).ToLong(&blue
, 16);
2490 **obj
= wxColour(red
, green
, blue
);
2493 else { // it's a colour name
2494 **obj
= wxColour(spec
);
2498 // last chance: 3-tuple of integers is expected
2499 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2500 PyObject
* o1
= PySequence_GetItem(source
, 0);
2501 PyObject
* o2
= PySequence_GetItem(source
, 1);
2502 PyObject
* o3
= PySequence_GetItem(source
, 2);
2503 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2509 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2517 PyErr_SetString(PyExc_TypeError
,
2518 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2523 bool wxColour_typecheck(PyObject
* source
) {
2525 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2528 if (PyString_Check(source
) || PyUnicode_Check(source
))
2536 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2538 if (source
== Py_None
) {
2539 **obj
= wxPoint2D(-1,-1);
2543 // If source is an object instance then it may already be the right type
2544 if (wxPySwigInstance_Check(source
)) {
2546 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2551 // otherwise a length-2 sequence of floats is expected
2552 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2553 PyObject
* o1
= PySequence_GetItem(source
, 0);
2554 PyObject
* o2
= PySequence_GetItem(source
, 1);
2555 // This should really check for floats, not numbers -- but that would break code.
2556 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2561 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2567 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2572 //----------------------------------------------------------------------
2574 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2576 PyObject
* list
= PyList_New(0);
2577 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2579 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2581 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2583 PyList_Append(list
, str
);
2590 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2592 PyObject
* list
= PyList_New(0);
2593 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2594 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2595 PyList_Append(list
, number
);
2602 //----------------------------------------------------------------------
2603 // wxPyImageHandler methods
2605 // TODO: Switch these to use wxPython's standard macros and helper classes
2606 // for calling callbacks.
2608 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2609 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2610 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2611 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2613 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2614 return wxPyConstructObject(new wxPyInputStream(stream
),
2615 wxT("wxPyInputStream"), 0);
2618 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2619 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2622 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2623 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2626 wxPyImageHandler::wxPyImageHandler():
2629 if (!m_DoCanRead_Name
) {
2630 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2631 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2632 m_LoadFile_Name
= PyString_FromString("LoadFile");
2633 m_SaveFile_Name
= PyString_FromString("SaveFile");
2637 wxPyImageHandler::~wxPyImageHandler() {
2644 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2645 // should check here for isinstance(PyImageHandler) ??
2650 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2651 // check if our object has this method
2652 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2653 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2654 wxPyEndBlockThreads(blocked
);
2658 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2659 py_InputStream(&stream
), NULL
);
2660 bool retval
= false;
2662 retval
= PyInt_AsLong(res
);
2668 wxPyEndBlockThreads(blocked
);
2672 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2673 bool verbose
, int index
) {
2674 // check if our object has this method
2675 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2676 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2677 wxPyEndBlockThreads(blocked
);
2680 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2682 py_InputStream(&stream
),
2683 PyInt_FromLong(verbose
),
2684 PyInt_FromLong(index
),
2686 bool retval
= false;
2688 retval
= PyInt_AsLong(res
);
2693 wxPyEndBlockThreads(blocked
);
2697 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2699 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2700 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2701 wxPyEndBlockThreads(blocked
);
2704 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2706 py_OutputStream(&stream
),
2707 PyInt_FromLong(verbose
),
2709 bool retval
= false;
2711 retval
=PyInt_AsLong(res
);
2716 wxPyEndBlockThreads(blocked
);
2720 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2721 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2722 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2723 wxPyEndBlockThreads(blocked
);
2726 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2727 py_InputStream(&stream
),
2731 retval
=PyInt_AsLong(res
);
2736 wxPyEndBlockThreads(blocked
);
2741 //----------------------------------------------------------------------
2742 //----------------------------------------------------------------------