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::OnAssert(const wxChar
*file
,
199 // if we're not fully initialized then just log the error
200 if (! m_startupComplete
) {
203 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
213 // If the OnAssert is overloaded in the Python class then call it...
215 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
216 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
217 PyObject
* fso
= wx2PyString(file
);
218 PyObject
* cso
= wx2PyString(file
);
221 mso
= wx2PyString(file
);
223 mso
= Py_None
; Py_INCREF(Py_None
);
225 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
230 wxPyEndBlockThreads(blocked
);
232 // ...otherwise do our own thing with it
235 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
238 // turn it into a Python exception?
239 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
242 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
249 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
250 PyObject
* s
= wx2PyString(buf
);
251 PyErr_SetObject(wxPyAssertionError
, s
);
253 wxPyEndBlockThreads(blocked
);
255 // Now when control returns to whatever API wrapper was called from
256 // Python it should detect that an exception is set and will return
257 // NULL, signalling the exception to Python.
260 // Send it to the normal log destination, but only if
261 // not _DIALOG because it will call this too
262 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
265 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
274 // do the normal wx assert dialog?
275 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
276 wxApp::OnAssert(file
, line
, cond
, msg
);
281 // For catching Apple Events
282 void wxPyApp::MacOpenFile(const wxString
&fileName
)
284 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
285 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
286 PyObject
* s
= wx2PyString(fileName
);
287 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
290 wxPyEndBlockThreads(blocked
);
293 void wxPyApp::MacPrintFile(const wxString
&fileName
)
295 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
296 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
297 PyObject
* s
= wx2PyString(fileName
);
298 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
301 wxPyEndBlockThreads(blocked
);
304 void wxPyApp::MacNewFile()
306 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
307 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
308 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
309 wxPyEndBlockThreads(blocked
);
312 void wxPyApp::MacReopenApp()
314 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
315 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
316 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
317 wxPyEndBlockThreads(blocked
);
322 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
324 return s_macSupportPCMenuShortcuts
;
331 long wxPyApp::GetMacAboutMenuItemId() {
333 return s_macAboutMenuItemId
;
340 long wxPyApp::GetMacPreferencesMenuItemId() {
342 return s_macPreferencesMenuItemId
;
349 long wxPyApp::GetMacExitMenuItemId() {
351 return s_macExitMenuItemId
;
358 wxString
wxPyApp::GetMacHelpMenuTitleName() {
360 return s_macHelpMenuTitleName
;
362 return wxEmptyString
;
367 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
369 s_macSupportPCMenuShortcuts
= val
;
374 void wxPyApp::SetMacAboutMenuItemId(long val
) {
376 s_macAboutMenuItemId
= val
;
381 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
383 s_macPreferencesMenuItemId
= val
;
388 void wxPyApp::SetMacExitMenuItemId(long val
) {
390 s_macExitMenuItemId
= val
;
395 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
397 s_macHelpMenuTitleName
= val
;
402 // This finishes the initialization of wxWindows and then calls the OnInit
403 // that should be present in the derived (Python) class.
404 void wxPyApp::_BootstrapApp()
406 static bool haveInitialized
= false;
409 PyObject
* retval
= NULL
;
410 PyObject
* pyint
= NULL
;
413 // Only initialize wxWidgets once
414 if (! haveInitialized
) {
416 // Get any command-line args passed to this program from the sys module
419 blocked
= wxPyBeginBlockThreads();
421 PyObject
* sysargv
= PySys_GetObject("argv");
422 PyObject
* executable
= PySys_GetObject("executable");
424 if (sysargv
!= NULL
&& executable
!= NULL
) {
425 argc
= PyList_Size(sysargv
) + 1;
426 argv
= new char*[argc
+1];
427 argv
[0] = strdup(PyString_AsString(executable
));
429 for(x
=1; x
<argc
; x
++) {
430 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
431 argv
[x
] = strdup(PyString_AsString(pyArg
));
435 wxPyEndBlockThreads(blocked
);
437 // Initialize wxWidgets
438 result
= wxEntryStart(argc
, argv
);
439 // wxApp takes ownership of the argv array, don't delete it here
441 blocked
= wxPyBeginBlockThreads();
443 PyErr_SetString(PyExc_SystemError
,
444 "wxEntryStart failed, unable to initialize wxWidgets!"
446 " (Is DISPLAY set properly?)"
452 // On wxGTK the locale will be changed to match the system settings,
453 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
454 // for the floating point conversions and such to work right.
455 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
456 setlocale(LC_NUMERIC
, "C");
459 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
461 wxPyEndBlockThreads(blocked
);
462 haveInitialized
= true;
470 // It's now ok to generate exceptions for assertion errors.
471 wxPythonApp
->SetStartupComplete(true);
474 // Call the Python wxApp's OnPreInit and OnInit functions
475 blocked
= wxPyBeginBlockThreads();
476 if (wxPyCBH_findCallback(m_myInst
, "OnPreInit")) {
477 PyObject
* method
= m_myInst
.GetLastFound();
478 PyObject
* argTuple
= PyTuple_New(0);
479 retval
= PyEval_CallObject(method
, argTuple
);
480 m_myInst
.clearRecursionGuard(method
);
486 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
488 PyObject
* method
= m_myInst
.GetLastFound();
489 PyObject
* argTuple
= PyTuple_New(0);
490 retval
= PyEval_CallObject(method
, argTuple
);
491 m_myInst
.clearRecursionGuard(method
);
497 pyint
= PyNumber_Int(retval
);
499 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
502 result
= PyInt_AS_LONG(pyint
);
505 // Is it okay if there is no OnInit? Probably so...
510 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
517 wxPyEndBlockThreads(blocked
);
520 //---------------------------------------------------------------------
521 //----------------------------------------------------------------------
525 static char* wxPyCopyCString(const wxChar
* src
)
527 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
528 size_t len
= strlen(buff
);
529 char* dest
= new char[len
+1];
535 static char* wxPyCopyCString(const char* src
) // we need a char version too
537 size_t len
= strlen(src
);
538 char* dest
= new char[len
+1];
544 static wxChar
* wxPyCopyWString(const char *src
)
546 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
547 wxString
str(src
, *wxConvCurrent
);
548 return copystring(str
);
552 static wxChar
* wxPyCopyWString(const wxChar
*src
)
554 return copystring(src
);
560 inline const char* dropwx(const char* name
) {
561 if (name
[0] == 'w' && name
[1] == 'x')
567 //----------------------------------------------------------------------
569 // This function is called when the wx._core_ module is imported to do some
570 // initial setup. (Before there is a wxApp object.) The rest happens in
571 // wxPyApp::_BootstrapApp
572 void __wxPyPreStart(PyObject
* moduleDict
)
576 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
577 // | _CRTDBG_CHECK_ALWAYS_DF
578 // | _CRTDBG_DELAY_FREE_MEM_DF
582 #ifdef WXP_WITH_THREAD
583 #if wxPyUSE_GIL_STATE
584 PyEval_InitThreads();
586 PyEval_InitThreads();
587 wxPyTStates
= new wxPyThreadStateArray
;
588 wxPyTMutex
= new wxMutex
;
590 // Save the current (main) thread state in our array
591 PyThreadState
* tstate
= wxPyBeginAllowThreads();
592 wxPyEndAllowThreads(tstate
);
596 // Ensure that the build options in the DLL (or whatever) match this build
597 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
599 wxInitAllImageHandlers();
604 void __wxPyCleanup() {
605 wxPyDoingCleanup
= true;
607 wxPyDoCleanup
= false;
610 #ifdef WXP_WITH_THREAD
611 #if !wxPyUSE_GIL_STATE
614 wxPyTStates
->Empty();
622 // Save a reference to the dictionary of the wx._core module, and inject
623 // a few more things into it.
624 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
627 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
630 if (!PyDict_Check(wxPython_dict
)) {
631 PyErr_SetString(PyExc_TypeError
,
632 "_wxPySetDictionary must have dictionary object!");
636 if (! wxPyPtrTypeMap
)
637 wxPyPtrTypeMap
= PyDict_New();
638 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
640 // Create an exception object to use for wxASSERTions
641 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
642 PyExc_AssertionError
, NULL
);
643 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
645 // Create an exception object to use when the app object hasn't been created yet
646 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
647 PyExc_RuntimeError
, NULL
);
648 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
653 #define wxPlatform "__WXMOTIF__"
654 #define wxPlatName "wxMotif"
657 #define wxPlatform "__WXX11__"
658 #define wxPlatName "wxX11"
661 #define wxPlatform "__WXGTK__"
662 #define wxPlatName "wxGTK"
665 #define wxPlatform "__WXMSW__"
666 #define wxPlatName "wxMSW"
669 #define wxPlatform "__WXMAC__"
670 #define wxPlatName "wxMac"
679 // These should be deprecated in favor of the PlatformInfo tuple built below...
680 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
681 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
682 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
684 // Make a tuple of strings that gives more info about the platform.
685 PyObject
* PlatInfo
= PyList_New(0);
688 #define _AddInfoString(st) \
689 obj = PyString_FromString(st); \
690 PyList_Append(PlatInfo, obj); \
693 _AddInfoString(wxPlatform
);
694 _AddInfoString(wxPlatName
);
696 _AddInfoString("unicode");
698 _AddInfoString("ansi");
702 _AddInfoString("gtk2");
704 _AddInfoString("gtk1");
708 _AddInfoString("wx-assertions-on");
710 _AddInfoString("wx-assertions-off");
712 _AddInfoString(wxPy_SWIG_VERSION
);
714 #undef _AddInfoString
716 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
718 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
725 //---------------------------------------------------------------------------
727 // Check for existence of a wxApp, setting an exception if there isn't one.
728 // This doesn't need to aquire the GIL because it should only be called from
729 // an %exception before the lock is released.
731 bool wxPyCheckForApp() {
732 if (wxTheApp
!= NULL
)
735 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
740 //---------------------------------------------------------------------------
742 void wxPyUserData_dtor(wxPyUserData
* self
) {
743 if (! wxPyDoingCleanup
) {
744 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
745 Py_DECREF(self
->m_obj
);
747 wxPyEndBlockThreads(blocked
);
752 void wxPyClientData_dtor(wxPyClientData
* self
) {
753 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
754 // may have already garbage collected the object...
755 if (self
->m_incRef
) {
756 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
757 Py_DECREF(self
->m_obj
);
758 wxPyEndBlockThreads(blocked
);
766 // This is called when an OOR controled object is being destroyed. Although
767 // the C++ object is going away there is no way to force the Python object
768 // (and all references to it) to die too. This causes problems (crashes) in
769 // wxPython when a python shadow object attempts to call a C++ method using
770 // the now bogus pointer... So to try and prevent this we'll do a little black
771 // magic and change the class of the python instance to a class that will
772 // raise an exception for any attempt to call methods with it. See
773 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
774 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
776 static PyObject
* deadObjectClass
= NULL
;
778 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
779 if (deadObjectClass
== NULL
) {
780 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
781 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
782 // will lead to a deadlock when it tries to aquire the GIL again.
783 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
784 Py_INCREF(deadObjectClass
);
788 // Only if there is more than one reference to the object and we are
789 // holding the OOR reference:
790 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
791 // bool isInstance = wxPyInstance_Check(self->m_obj);
793 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
795 // Call __del__, if there is one.
796 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
798 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
802 if (PyErr_Occurred())
803 PyErr_Clear(); // just ignore it for now
806 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
808 // Clear the instance's dictionary
811 // put the name of the old class into the instance, and then reset the
812 // class to be the dead class.
813 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
814 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
815 PyDict_SetItemString(dict
, "_name", name
);
816 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
817 //Py_INCREF(deadObjectClass);
823 // m_obj is DECREF'd in the base class dtor...
824 wxPyEndBlockThreads(blocked
);
828 //---------------------------------------------------------------------------
829 // Stuff used by OOR to find the right wxPython class type to return and to
833 // The pointer type map is used when the "pointer" type name generated by SWIG
834 // is not the same as the shadow class name, for example wxPyTreeCtrl
835 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
836 // so we'll just make it a Python dictionary in the wx module's namespace.
837 // (See __wxSetDictionary)
838 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
839 if (! wxPyPtrTypeMap
)
840 wxPyPtrTypeMap
= PyDict_New();
841 PyDict_SetItemString(wxPyPtrTypeMap
,
843 PyString_FromString((char*)ptrName
));
849 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
850 PyObject
* target
= NULL
;
851 bool isEvtHandler
= false;
852 bool isSizer
= false;
855 // If it's derived from wxEvtHandler then there may
856 // already be a pointer to a Python object that we can use
858 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
860 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
861 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
863 target
= data
->m_obj
;
869 // Also check for wxSizer
870 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
872 wxSizer
* sz
= (wxSizer
*)source
;
873 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
875 target
= data
->m_obj
;
882 // Otherwise make it the old fashioned way by making a new shadow
883 // object and putting this pointer in it. Look up the class
884 // heirarchy until we find a class name that is located in the
886 const wxClassInfo
* info
= source
->GetClassInfo();
887 wxString name
= info
->GetClassName();
888 bool exists
= wxPyCheckSwigType(name
);
889 while (info
&& !exists
) {
890 info
= info
->GetBaseClass1();
891 name
= info
->GetClassName();
892 exists
= wxPyCheckSwigType(name
);
895 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
896 if (target
&& isEvtHandler
)
897 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
898 if (target
&& isSizer
)
899 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
901 wxString
msg(wxT("wxPython class not found for "));
902 msg
+= source
->GetClassInfo()->GetClassName();
903 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
907 } else { // source was NULL so return None.
908 Py_INCREF(Py_None
); target
= Py_None
;
914 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
916 return wxPyMake_wxObject(source
, setThisOwn
);
920 //---------------------------------------------------------------------------
923 #ifdef WXP_WITH_THREAD
924 #if !wxPyUSE_GIL_STATE
927 unsigned long wxPyGetCurrentThreadId() {
928 return wxThread::GetCurrentId();
931 static wxPyThreadState gs_shutdownTState
;
934 wxPyThreadState
* wxPyGetThreadState() {
935 if (wxPyTMutex
== NULL
) // Python is shutting down...
936 return &gs_shutdownTState
;
938 unsigned long ctid
= wxPyGetCurrentThreadId();
939 wxPyThreadState
* tstate
= NULL
;
942 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
943 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
944 if (info
.tid
== ctid
) {
949 wxPyTMutex
->Unlock();
950 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
956 void wxPySaveThreadState(PyThreadState
* tstate
) {
957 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
958 gs_shutdownTState
.tstate
= tstate
;
961 unsigned long ctid
= wxPyGetCurrentThreadId();
963 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
964 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
965 if (info
.tid
== ctid
) {
967 if (info
.tstate
!= tstate
)
968 wxLogMessage("*** tstate mismatch!???");
970 info
.tstate
= tstate
; // allow for transient tstates
971 // Normally it will never change, but apparently COM callbacks
972 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
973 // tstate which will then be garbage the next time we try to use
976 wxPyTMutex
->Unlock();
980 // not found, so add it...
981 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
982 wxPyTMutex
->Unlock();
990 // Calls from Python to wxWindows code are wrapped in calls to these
993 PyThreadState
* wxPyBeginAllowThreads() {
994 #ifdef WXP_WITH_THREAD
995 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
996 #if !wxPyUSE_GIL_STATE
997 wxPySaveThreadState(saved
);
1005 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1006 #ifdef WXP_WITH_THREAD
1007 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1013 // Calls from wxWindows back to Python code, or even any PyObject
1014 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1016 wxPyBlock_t
wxPyBeginBlockThreads() {
1017 #ifdef WXP_WITH_THREAD
1018 if (! Py_IsInitialized()) {
1019 return (wxPyBlock_t
)0;
1021 #if wxPyUSE_GIL_STATE
1022 PyGILState_STATE state
= PyGILState_Ensure();
1025 PyThreadState
*current
= _PyThreadState_Current
;
1027 // Only block if there wasn't already a tstate, or if the current one is
1028 // not the one we are wanting to change to. This should prevent deadlock
1029 // if there are nested calls to wxPyBeginBlockThreads
1030 wxPyBlock_t blocked
= false;
1031 wxPyThreadState
* tstate
= wxPyGetThreadState();
1032 if (current
!= tstate
->tstate
) {
1033 PyEval_RestoreThread(tstate
->tstate
);
1039 return (wxPyBlock_t
)0;
1044 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1045 #ifdef WXP_WITH_THREAD
1046 if (! Py_IsInitialized()) {
1049 #if wxPyUSE_GIL_STATE
1050 PyGILState_Release(blocked
);
1052 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1053 // The value of blocked passed in needs to be the same as that returned
1054 // from wxPyBeginBlockThreads at the same nesting level.
1056 PyEval_SaveThread();
1063 //---------------------------------------------------------------------------
1064 // wxPyInputStream and wxPyCBInputStream methods
1067 void wxPyInputStream::close() {
1068 /* do nothing for now */
1071 void wxPyInputStream::flush() {
1072 /* do nothing for now */
1075 bool wxPyInputStream::eof() {
1077 return m_wxis
->Eof();
1082 wxPyInputStream::~wxPyInputStream() {
1090 PyObject
* wxPyInputStream::read(int size
) {
1091 PyObject
* obj
= NULL
;
1093 const int BUFSIZE
= 1024;
1095 // check if we have a real wxInputStream to work with
1097 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1098 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1099 wxPyEndBlockThreads(blocked
);
1104 // read while bytes are available on the stream
1105 while ( m_wxis
->CanRead() ) {
1106 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1107 buf
.UngetAppendBuf(m_wxis
->LastRead());
1110 } else { // Read only size number of characters
1111 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1112 buf
.UngetWriteBuf(m_wxis
->LastRead());
1116 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1117 wxStreamError err
= m_wxis
->GetLastError();
1118 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1119 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1122 // We use only strings for the streams, not unicode
1123 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1125 wxPyEndBlockThreads(blocked
);
1130 PyObject
* wxPyInputStream::readline(int size
) {
1131 PyObject
* obj
= NULL
;
1136 // check if we have a real wxInputStream to work with
1138 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1139 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1140 wxPyEndBlockThreads(blocked
);
1144 // read until \n or byte limit reached
1145 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1146 ch
= m_wxis
->GetC();
1151 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1152 wxStreamError err
= m_wxis
->GetLastError();
1153 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1154 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1157 // We use only strings for the streams, not unicode
1158 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1160 wxPyEndBlockThreads(blocked
);
1165 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1168 // check if we have a real wxInputStream to work with
1170 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1171 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1172 wxPyEndBlockThreads(blocked
);
1177 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1178 pylist
= PyList_New(0);
1179 wxPyEndBlockThreads(blocked
);
1182 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1184 wxPyEndBlockThreads(blocked
);
1188 // read sizehint bytes or until EOF
1190 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1191 PyObject
* s
= this->readline();
1193 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1195 wxPyEndBlockThreads(blocked
);
1198 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1199 PyList_Append(pylist
, s
);
1200 i
+= PyString_Size(s
);
1201 wxPyEndBlockThreads(blocked
);
1205 wxStreamError err
= m_wxis
->GetLastError();
1206 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1207 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1209 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1210 wxPyEndBlockThreads(blocked
);
1218 void wxPyInputStream::seek(int offset
, int whence
) {
1220 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1223 int wxPyInputStream::tell(){
1225 return m_wxis
->TellI();
1232 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1233 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1236 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1238 m_read
= other
.m_read
;
1239 m_seek
= other
.m_seek
;
1240 m_tell
= other
.m_tell
;
1241 m_block
= other
.m_block
;
1248 wxPyCBInputStream::~wxPyCBInputStream() {
1249 wxPyBlock_t blocked
;
1250 if (m_block
) blocked
= wxPyBeginBlockThreads();
1254 if (m_block
) wxPyEndBlockThreads(blocked
);
1258 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1259 wxPyBlock_t blocked
;
1260 if (block
) blocked
= wxPyBeginBlockThreads();
1262 PyObject
* read
= getMethod(py
, "read");
1263 PyObject
* seek
= getMethod(py
, "seek");
1264 PyObject
* tell
= getMethod(py
, "tell");
1267 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1271 if (block
) wxPyEndBlockThreads(blocked
);
1275 if (block
) wxPyEndBlockThreads(blocked
);
1276 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1280 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1281 return wxPyCBInputStream::create(py
, block
);
1284 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1285 return new wxPyCBInputStream(*other
);
1288 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1289 if (!PyObject_HasAttrString(py
, name
))
1291 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1292 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1300 wxFileOffset
wxPyCBInputStream::GetLength() const {
1301 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1302 if (m_seek
&& m_tell
) {
1303 wxFileOffset temp
= self
->OnSysTell();
1304 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1305 self
->OnSysSeek(temp
, wxFromStart
);
1309 return wxInvalidOffset
;
1313 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1317 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1318 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1319 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1323 if ((result
!= NULL
) && PyString_Check(result
)) {
1324 o
= PyString_Size(result
);
1326 m_lasterror
= wxSTREAM_EOF
;
1329 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1334 m_lasterror
= wxSTREAM_READ_ERROR
;
1335 wxPyEndBlockThreads(blocked
);
1339 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1340 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1345 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1346 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1347 PyObject
* arglist
= PyTuple_New(2);
1349 if (sizeof(wxFileOffset
) > sizeof(long))
1350 // wxFileOffset is a 64-bit value...
1351 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1353 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1355 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1358 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1361 wxPyEndBlockThreads(blocked
);
1366 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1367 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1368 PyObject
* arglist
= Py_BuildValue("()");
1369 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1372 if (result
!= NULL
) {
1373 if (PyLong_Check(result
))
1374 o
= PyLong_AsLongLong(result
);
1376 o
= PyInt_AsLong(result
);
1379 wxPyEndBlockThreads(blocked
);
1383 //----------------------------------------------------------------------
1385 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1387 wxPyCallback::wxPyCallback(PyObject
* func
) {
1392 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1393 m_func
= other
.m_func
;
1397 wxPyCallback::~wxPyCallback() {
1398 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1400 wxPyEndBlockThreads(blocked
);
1404 #define wxPy_PRECALLINIT "_preCallInit"
1405 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1407 // This function is used for all events destined for Python event handlers.
1408 void wxPyCallback::EventThunker(wxEvent
& event
) {
1409 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1410 PyObject
* func
= cb
->m_func
;
1414 bool checkSkip
= false;
1416 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1417 wxString className
= event
.GetClassInfo()->GetClassName();
1419 // If the event is one of these types then pass the original
1420 // event object instead of the one passed to us.
1421 if ( className
== wxT("wxPyEvent") ) {
1422 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1423 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1425 else if ( className
== wxT("wxPyCommandEvent") ) {
1426 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1427 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1430 arg
= wxPyConstructObject((void*)&event
, className
);
1436 // "intern" the pre/post method names to speed up the HasAttr
1437 static PyObject
* s_preName
= NULL
;
1438 static PyObject
* s_postName
= NULL
;
1439 if (s_preName
== NULL
) {
1440 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1441 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1444 // Check if the event object needs some preinitialization
1445 if (PyObject_HasAttr(arg
, s_preName
)) {
1446 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1448 Py_DECREF(result
); // result is ignored, but we still need to decref it
1449 PyErr_Clear(); // Just in case...
1455 // Call the event handler, passing the event object
1456 tuple
= PyTuple_New(1);
1457 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1458 result
= PyEval_CallObject(func
, tuple
);
1460 Py_DECREF(result
); // result is ignored, but we still need to decref it
1461 PyErr_Clear(); // Just in case...
1466 // Check if the event object needs some post cleanup
1467 if (PyObject_HasAttr(arg
, s_postName
)) {
1468 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1470 Py_DECREF(result
); // result is ignored, but we still need to decref it
1471 PyErr_Clear(); // Just in case...
1478 // if the event object was one of our special types and
1479 // it had been cloned, then we need to extract the Skipped
1480 // value from the original and set it in the clone.
1481 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1483 event
.Skip(PyInt_AsLong(result
));
1491 wxPyEndBlockThreads(blocked
);
1495 //----------------------------------------------------------------------
1497 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1499 m_self
= other
.m_self
;
1500 m_class
= other
.m_class
;
1508 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1519 #if PYTHON_API_VERSION >= 1011
1521 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1522 // in which the method was defined. Starting with 2.2 it returns
1523 // "class that asked for the method" which seems totally bogus to me
1524 // but apprently it fixes some obscure problem waiting to happen in
1525 // Python. Since the API was not documented Guido and the gang felt
1526 // safe in changing it. Needless to say that totally screwed up the
1527 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1528 // code to find the class where the method is actually defined...
1531 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1535 if (PyType_Check(klass
)) { // new style classes
1536 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1537 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1538 PyObject
*mro
, *res
, *base
, *dict
;
1539 /* Look in tp_dict of types in MRO */
1541 assert(PyTuple_Check(mro
));
1542 n
= PyTuple_GET_SIZE(mro
);
1543 for (i
= 0; i
< n
; i
++) {
1544 base
= PyTuple_GET_ITEM(mro
, i
);
1545 if (PyClass_Check(base
))
1546 dict
= ((PyClassObject
*)base
)->cl_dict
;
1548 assert(PyType_Check(base
));
1549 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1551 assert(dict
&& PyDict_Check(dict
));
1552 res
= PyDict_GetItem(dict
, name
);
1559 else if (PyClass_Check(klass
)) { // old style classes
1560 // This code is borrowed/adapted from class_lookup in classobject.c
1561 PyClassObject
* cp
= (PyClassObject
*)klass
;
1562 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1563 if (value
!= NULL
) {
1564 return (PyObject
*)cp
;
1566 n
= PyTuple_Size(cp
->cl_bases
);
1567 for (i
= 0; i
< n
; i
++) {
1568 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1569 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1581 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, PyObject
* nameo
)
1583 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1585 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1587 #else // 2.2 and after, the hard way...
1588 return PyFindClassWithAttr(mgc
, nameo
);
1594 // To avoid recursion when an overridden virtual method wants to call the base
1595 // class version, temporarily set an attribute in the instance with the same
1596 // name as the method. Then the PyObject_GetAttr in the next findCallback
1597 // will return this attribute and the PyMethod_Check will fail.
1599 void wxPyCallbackHelper::setRecursionGuard(PyObject
* method
) const
1601 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1602 PyObject_SetAttr(m_self
, func
->func_name
, Py_None
);
1605 void wxPyCallbackHelper::clearRecursionGuard(PyObject
* method
) const
1607 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1608 if (PyObject_HasAttr(m_self
, func
->func_name
)) {
1609 PyObject_DelAttr(m_self
, func
->func_name
);
1613 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1615 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1616 // if (PyObject_HasAttr(m_self, func->func_name)) {
1617 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1618 // bool retval = (attr == Py_None);
1626 bool wxPyCallbackHelper::findCallback(const char* name
, bool setGuard
) const {
1627 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1628 PyObject
*method
, *klass
;
1629 PyObject
* nameo
= PyString_FromString(name
);
1630 self
->m_lastFound
= NULL
;
1632 // If the object (m_self) has an attibute of the given name...
1633 if (m_self
&& PyObject_HasAttr(m_self
, nameo
)) {
1634 method
= PyObject_GetAttr(m_self
, nameo
);
1636 // ...and if that attribute is a method, and if that method's class is
1637 // not from the registered class or a base class...
1638 if (PyMethod_Check(method
) &&
1639 (klass
= PyMethod_GetDefiningClass(method
, nameo
)) != NULL
&&
1640 (klass
!= m_class
) &&
1641 PyObject_IsSubclass(klass
, m_class
)) {
1643 // ...then we'll save a pointer to the method so callCallback can
1644 // call it. But first, set a recursion guard in case the
1645 // overridden method wants to call the base class version.
1647 setRecursionGuard(method
);
1648 self
->m_lastFound
= method
;
1656 return m_lastFound
!= NULL
;
1660 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1664 result
= callCallbackObj(argTuple
);
1665 if (result
) { // Assumes an integer return type...
1666 retval
= PyInt_AsLong(result
);
1668 PyErr_Clear(); // forget about it if it's not...
1673 // Invoke the Python callable object, returning the raw PyObject return
1674 // value. Caller should DECREF the return value and also manage the GIL.
1675 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1678 // Save a copy of the pointer in case the callback generates another
1679 // callback. In that case m_lastFound will have a different value when
1680 // it gets back here...
1681 PyObject
* method
= m_lastFound
;
1683 result
= PyEval_CallObject(method
, argTuple
);
1684 clearRecursionGuard(method
);
1686 Py_DECREF(argTuple
);
1695 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1696 cbh
.setSelf(self
, klass
, incref
);
1699 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
, bool setGuard
) {
1700 return cbh
.findCallback(name
, setGuard
);
1703 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1704 return cbh
.callCallback(argTuple
);
1707 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1708 return cbh
.callCallbackObj(argTuple
);
1712 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1713 if (cbh
->m_incRef
) {
1714 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1715 Py_XDECREF(cbh
->m_self
);
1716 Py_XDECREF(cbh
->m_class
);
1717 wxPyEndBlockThreads(blocked
);
1721 //---------------------------------------------------------------------------
1722 //---------------------------------------------------------------------------
1723 // These event classes can be derived from in Python and passed through the event
1724 // system without losing anything. They do this by keeping a reference to
1725 // themselves and some special case handling in wxPyCallback::EventThunker.
1728 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1729 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1730 //Py_INCREF(m_self); // circular loops...
1734 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1735 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1738 wxPyEndBlockThreads(blocked
);
1741 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1742 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1750 wxPyEndBlockThreads(blocked
);
1753 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1759 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1760 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1763 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1764 : wxEvent(winid
, commandType
) {
1768 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1771 SetSelf(evt
.m_self
, true);
1775 wxPyEvent::~wxPyEvent() {
1779 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1780 : wxCommandEvent(commandType
, id
) {
1784 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1785 : wxCommandEvent(evt
)
1787 SetSelf(evt
.m_self
, true);
1791 wxPyCommandEvent::~wxPyCommandEvent() {
1798 //---------------------------------------------------------------------------
1799 //---------------------------------------------------------------------------
1800 // Convert a wxList to a Python List, only works for lists of wxObjects
1802 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1803 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1807 wxNode
* node
= list
->GetFirst();
1809 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1810 pyList
= PyList_New(0);
1812 wxObj
= node
->GetData();
1813 pyObj
= wxPyMake_wxObject(wxObj
,false);
1814 PyList_Append(pyList
, pyObj
);
1815 node
= node
->GetNext();
1817 wxPyEndBlockThreads(blocked
);
1821 //----------------------------------------------------------------------
1823 long wxPyGetWinHandle(wxWindow
* win
) {
1826 return (long)win
->GetHandle();
1829 #if defined(__WXGTK__) || defined(__WXX11)
1830 return (long)GetXWindow(win
);
1834 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1835 return (long)win
->GetHandle();
1841 //----------------------------------------------------------------------
1842 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1843 // included in every file over and over again...
1845 wxString
* wxString_in_helper(PyObject
* source
) {
1846 wxString
* target
= NULL
;
1848 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1849 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1853 PyObject
* uni
= source
;
1854 if (PyString_Check(source
)) {
1855 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1856 if (PyErr_Occurred()) return NULL
;
1858 target
= new wxString();
1859 size_t len
= PyUnicode_GET_SIZE(uni
);
1861 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1862 target
->UngetWriteBuf(len
);
1865 if (PyString_Check(source
))
1868 // Convert to a string object if it isn't already, then to wxString
1869 PyObject
* str
= source
;
1870 if (PyUnicode_Check(source
)) {
1871 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1872 if (PyErr_Occurred()) return NULL
;
1874 else if (!PyString_Check(source
)) {
1875 str
= PyObject_Str(source
);
1876 if (PyErr_Occurred()) return NULL
;
1878 char* tmpPtr
; int tmpSize
;
1879 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1880 target
= new wxString(tmpPtr
, tmpSize
);
1882 if (!PyString_Check(source
))
1884 #endif // wxUSE_UNICODE
1890 // Similar to above except doesn't use "new" and doesn't set an exception
1891 wxString
Py2wxString(PyObject
* source
)
1896 // Convert to a unicode object, if not already, then to a wxString
1897 PyObject
* uni
= source
;
1898 if (!PyUnicode_Check(source
)) {
1899 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1900 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1902 size_t len
= PyUnicode_GET_SIZE(uni
);
1904 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1905 target
.UngetWriteBuf();
1908 if (!PyUnicode_Check(source
))
1911 // Convert to a string object if it isn't already, then to wxString
1912 PyObject
* str
= source
;
1913 if (PyUnicode_Check(source
)) {
1914 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1915 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1917 else if (!PyString_Check(source
)) {
1918 str
= PyObject_Str(source
);
1919 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1921 char* tmpPtr
; int tmpSize
;
1922 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1923 target
= wxString(tmpPtr
, tmpSize
);
1925 if (!PyString_Check(source
))
1927 #endif // wxUSE_UNICODE
1933 // Make either a Python String or Unicode object, depending on build mode
1934 PyObject
* wx2PyString(const wxString
& src
)
1938 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1940 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1947 void wxSetDefaultPyEncoding(const char* encoding
)
1949 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
1952 const char* wxGetDefaultPyEncoding()
1954 return wxPyDefaultEncoding
;
1957 //----------------------------------------------------------------------
1960 byte
* byte_LIST_helper(PyObject
* source
) {
1961 if (!PyList_Check(source
)) {
1962 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1965 int count
= PyList_Size(source
);
1966 byte
* temp
= new byte
[count
];
1968 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1971 for (int x
=0; x
<count
; x
++) {
1972 PyObject
* o
= PyList_GetItem(source
, x
);
1973 if (! PyInt_Check(o
)) {
1974 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1977 temp
[x
] = (byte
)PyInt_AsLong(o
);
1983 int* int_LIST_helper(PyObject
* source
) {
1984 if (!PyList_Check(source
)) {
1985 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1988 int count
= PyList_Size(source
);
1989 int* temp
= new int[count
];
1991 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1994 for (int x
=0; x
<count
; x
++) {
1995 PyObject
* o
= PyList_GetItem(source
, x
);
1996 if (! PyInt_Check(o
)) {
1997 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2000 temp
[x
] = PyInt_AsLong(o
);
2006 long* long_LIST_helper(PyObject
* source
) {
2007 if (!PyList_Check(source
)) {
2008 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2011 int count
= PyList_Size(source
);
2012 long* temp
= new long[count
];
2014 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2017 for (int x
=0; x
<count
; x
++) {
2018 PyObject
* o
= PyList_GetItem(source
, x
);
2019 if (! PyInt_Check(o
)) {
2020 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2023 temp
[x
] = PyInt_AsLong(o
);
2029 char** string_LIST_helper(PyObject
* source
) {
2030 if (!PyList_Check(source
)) {
2031 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2034 int count
= PyList_Size(source
);
2035 char** temp
= new char*[count
];
2037 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2040 for (int x
=0; x
<count
; x
++) {
2041 PyObject
* o
= PyList_GetItem(source
, x
);
2042 if (! PyString_Check(o
)) {
2043 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2046 temp
[x
] = PyString_AsString(o
);
2051 //--------------------------------
2052 // Part of patch from Tim Hochberg
2053 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2054 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2055 point
->x
= PyInt_AS_LONG(o1
);
2056 point
->y
= PyInt_AS_LONG(o2
);
2059 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2060 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2061 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2064 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2065 // Disallow instances because they can cause havok
2068 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2069 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2070 point
->x
= PyInt_AsLong(o1
);
2071 point
->y
= PyInt_AsLong(o2
);
2078 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2079 // Putting all of the declarations here allows
2080 // us to put the error handling all in one place.
2083 PyObject
*o
, *o1
, *o2
;
2084 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2086 if (!PySequence_Check(source
)) {
2090 // The length of the sequence is returned in count.
2091 *count
= PySequence_Length(source
);
2096 temp
= new wxPoint
[*count
];
2098 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2101 for (x
=0; x
<*count
; x
++) {
2102 // Get an item: try fast way first.
2104 o
= PySequence_Fast_GET_ITEM(source
, x
);
2107 o
= PySequence_GetItem(source
, x
);
2113 // Convert o to wxPoint.
2114 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2115 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2116 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2117 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2118 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2122 else if (wxPySwigInstance_Check(o
)) {
2124 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2129 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2130 o1
= PySequence_GetItem(o
, 0);
2131 o2
= PySequence_GetItem(o
, 1);
2132 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2156 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2160 //------------------------------
2163 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2164 if (!PyList_Check(source
)) {
2165 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2168 int count
= PyList_Size(source
);
2169 wxBitmap
** temp
= new wxBitmap
*[count
];
2171 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2174 for (int x
=0; x
<count
; x
++) {
2175 PyObject
* o
= PyList_GetItem(source
, x
);
2176 if (wxPySwigInstance_Check(o
)) {
2178 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2179 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2185 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2194 wxString
* wxString_LIST_helper(PyObject
* source
) {
2195 if (!PyList_Check(source
)) {
2196 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2199 int count
= PyList_Size(source
);
2200 wxString
* temp
= new wxString
[count
];
2202 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2205 for (int x
=0; x
<count
; x
++) {
2206 PyObject
* o
= PyList_GetItem(source
, x
);
2207 #if PYTHON_API_VERSION >= 1009
2208 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2209 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2213 if (! PyString_Check(o
)) {
2214 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2219 wxString
* pStr
= wxString_in_helper(o
);
2227 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2228 if (!PyList_Check(source
)) {
2229 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2232 int count
= PyList_Size(source
);
2233 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2235 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2238 for (int x
=0; x
<count
; x
++) {
2239 PyObject
* o
= PyList_GetItem(source
, x
);
2240 if (wxPySwigInstance_Check(o
)) {
2241 wxAcceleratorEntry
* ae
;
2242 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2243 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2248 else if (PyTuple_Check(o
)) {
2249 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2250 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2251 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2252 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2255 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2263 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2264 if (!PyList_Check(source
)) {
2265 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2268 int count
= PyList_Size(source
);
2269 wxPen
** temp
= new wxPen
*[count
];
2271 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2274 for (int x
=0; x
<count
; x
++) {
2275 PyObject
* o
= PyList_GetItem(source
, x
);
2276 if (wxPySwigInstance_Check(o
)) {
2278 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2280 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2287 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2295 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2296 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2299 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2303 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2304 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2307 o1
= PySequence_GetItem(source
, 0);
2308 o2
= PySequence_GetItem(source
, 1);
2311 *i1
= PyInt_AsLong(o1
);
2312 *i2
= PyInt_AsLong(o2
);
2322 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2323 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2324 PyObject
*o1
, *o2
, *o3
, *o4
;
2326 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2330 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2331 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2332 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2333 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2336 o1
= PySequence_GetItem(source
, 0);
2337 o2
= PySequence_GetItem(source
, 1);
2338 o3
= PySequence_GetItem(source
, 2);
2339 o4
= PySequence_GetItem(source
, 3);
2342 *i1
= PyInt_AsLong(o1
);
2343 *i2
= PyInt_AsLong(o2
);
2344 *i3
= PyInt_AsLong(o3
);
2345 *i4
= PyInt_AsLong(o4
);
2357 //----------------------------------------------------------------------
2359 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2363 if (wxPySwigInstance_Check(source
) &&
2364 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2368 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2374 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2376 if (source
== Py_None
) {
2377 **obj
= wxSize(-1,-1);
2380 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2384 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2386 if (source
== Py_None
) {
2387 **obj
= wxPoint(-1,-1);
2390 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2395 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2397 if (source
== Py_None
) {
2398 **obj
= wxRealPoint(-1,-1);
2402 // If source is an object instance then it may already be the right type
2403 if (wxPySwigInstance_Check(source
)) {
2405 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2410 // otherwise a 2-tuple of floats is expected
2411 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2412 PyObject
* o1
= PySequence_GetItem(source
, 0);
2413 PyObject
* o2
= PySequence_GetItem(source
, 1);
2414 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2419 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2426 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2432 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2434 if (source
== Py_None
) {
2435 **obj
= wxRect(-1,-1,-1,-1);
2439 // If source is an object instance then it may already be the right type
2440 if (wxPySwigInstance_Check(source
)) {
2442 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2447 // otherwise a 4-tuple of integers is expected
2448 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2449 PyObject
* o1
= PySequence_GetItem(source
, 0);
2450 PyObject
* o2
= PySequence_GetItem(source
, 1);
2451 PyObject
* o3
= PySequence_GetItem(source
, 2);
2452 PyObject
* o4
= PySequence_GetItem(source
, 3);
2453 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2454 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2461 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2462 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2471 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2477 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2479 if (source
== Py_None
) {
2480 **obj
= wxNullColour
;
2484 // If source is an object instance then it may already be the right type
2485 if (wxPySwigInstance_Check(source
)) {
2487 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2492 // otherwise check for a string
2493 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2494 wxString spec
= Py2wxString(source
);
2495 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2496 long red
, green
, blue
;
2497 red
= green
= blue
= 0;
2498 spec
.Mid(1,2).ToLong(&red
, 16);
2499 spec
.Mid(3,2).ToLong(&green
, 16);
2500 spec
.Mid(5,2).ToLong(&blue
, 16);
2502 **obj
= wxColour(red
, green
, blue
);
2505 else { // it's a colour name
2506 **obj
= wxColour(spec
);
2510 // last chance: 3-tuple of integers is expected
2511 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2512 PyObject
* o1
= PySequence_GetItem(source
, 0);
2513 PyObject
* o2
= PySequence_GetItem(source
, 1);
2514 PyObject
* o3
= PySequence_GetItem(source
, 2);
2515 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2521 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2529 PyErr_SetString(PyExc_TypeError
,
2530 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2535 bool wxColour_typecheck(PyObject
* source
) {
2537 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2540 if (PyString_Check(source
) || PyUnicode_Check(source
))
2548 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2550 if (source
== Py_None
) {
2551 **obj
= wxPoint2D(-1,-1);
2555 // If source is an object instance then it may already be the right type
2556 if (wxPySwigInstance_Check(source
)) {
2558 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2563 // otherwise a length-2 sequence of floats is expected
2564 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2565 PyObject
* o1
= PySequence_GetItem(source
, 0);
2566 PyObject
* o2
= PySequence_GetItem(source
, 1);
2567 // This should really check for floats, not numbers -- but that would break code.
2568 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2573 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2579 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2584 //----------------------------------------------------------------------
2586 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2588 PyObject
* list
= PyList_New(0);
2589 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2591 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2593 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2595 PyList_Append(list
, str
);
2602 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2604 PyObject
* list
= PyList_New(0);
2605 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2606 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2607 PyList_Append(list
, number
);
2614 //----------------------------------------------------------------------
2615 // wxPyImageHandler methods
2617 // TODO: Switch these to use wxPython's standard macros and helper classes
2618 // for calling callbacks.
2620 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2621 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2622 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2623 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2625 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2626 return wxPyConstructObject(new wxPyInputStream(stream
),
2627 wxT("wxPyInputStream"), 0);
2630 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2631 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2634 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2635 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2638 wxPyImageHandler::wxPyImageHandler():
2641 if (!m_DoCanRead_Name
) {
2642 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2643 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2644 m_LoadFile_Name
= PyString_FromString("LoadFile");
2645 m_SaveFile_Name
= PyString_FromString("SaveFile");
2649 wxPyImageHandler::~wxPyImageHandler() {
2656 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2657 // should check here for isinstance(PyImageHandler) ??
2662 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2663 // check if our object has this method
2664 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2665 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2666 wxPyEndBlockThreads(blocked
);
2670 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2671 py_InputStream(&stream
), NULL
);
2672 bool retval
= false;
2674 retval
= PyInt_AsLong(res
);
2680 wxPyEndBlockThreads(blocked
);
2684 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2685 bool verbose
, int index
) {
2686 // check if our object has this method
2687 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2688 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2689 wxPyEndBlockThreads(blocked
);
2692 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2694 py_InputStream(&stream
),
2695 PyInt_FromLong(verbose
),
2696 PyInt_FromLong(index
),
2698 bool retval
= false;
2700 retval
= PyInt_AsLong(res
);
2705 wxPyEndBlockThreads(blocked
);
2709 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2711 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2712 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2713 wxPyEndBlockThreads(blocked
);
2716 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2718 py_OutputStream(&stream
),
2719 PyInt_FromLong(verbose
),
2721 bool retval
= false;
2723 retval
=PyInt_AsLong(res
);
2728 wxPyEndBlockThreads(blocked
);
2732 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2733 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2734 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2735 wxPyEndBlockThreads(blocked
);
2738 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2739 py_InputStream(&stream
),
2743 retval
=PyInt_AsLong(res
);
2748 wxPyEndBlockThreads(blocked
);
2753 //----------------------------------------------------------------------
2754 //----------------------------------------------------------------------