1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Helper functions/classes for the wxPython extension module
7 // Created: 1-July-1997
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
16 #include "wx/wxPython/wxPython_int.h"
17 #include "wx/wxPython/pyistream.h"
20 #include <wx/msw/private.h>
21 #include <wx/msw/winundef.h>
22 #include <wx/msw/msvcrt.h>
27 #include <gdk/gdkprivate.h>
28 #include <wx/gtk/win_gtk.h>
31 #include <wx/clipbrd.h>
32 #include <wx/mimetype.h>
35 //----------------------------------------------------------------------
37 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
38 #error Python must support Unicode to use wxWindows Unicode
41 //----------------------------------------------------------------------
43 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
44 bool wxPyDoCleanup
= False
;
45 bool wxPyDoingCleanup
= False
;
48 #ifdef WXP_WITH_THREAD
49 struct wxPyThreadState
{
51 PyThreadState
* tstate
;
53 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
54 : tid(_tid
), tstate(_tstate
) {}
57 #include <wx/dynarray.h>
58 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
59 #include <wx/arrimpl.cpp>
60 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
62 wxPyThreadStateArray
* wxPyTStates
= NULL
;
63 wxMutex
* wxPyTMutex
= NULL
;
67 static PyObject
* wxPython_dict
= NULL
;
68 static PyObject
* wxPyAssertionError
= NULL
;
70 PyObject
* wxPyPtrTypeMap
= NULL
;
73 #ifdef __WXMSW__ // If building for win32...
74 //----------------------------------------------------------------------
75 // This gets run when the DLL is loaded. We just need to save a handle.
76 //----------------------------------------------------------------------
79 HINSTANCE hinstDLL
, // handle to DLL module
80 DWORD fdwReason
, // reason for calling function
81 LPVOID lpvReserved
// reserved
84 // If wxPython is embedded in another wxWindows app then
85 // the inatance has already been set.
86 if (! wxGetInstance())
87 wxSetInstance(hinstDLL
);
92 //----------------------------------------------------------------------
93 // Classes for implementing the wxp main application shell.
94 //----------------------------------------------------------------------
96 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
100 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
101 m_startupComplete
= False
;
105 wxPyApp::~wxPyApp() {
109 // This one isn't acutally called... We fake it with _BootstrapApp
110 bool wxPyApp::OnInit() {
115 int wxPyApp::MainLoop() {
118 DeletePendingObjects();
119 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
121 if ( m_exitOnFrameDelete
== Later
) {
122 m_exitOnFrameDelete
= Yes
;
125 retval
= wxApp::MainLoop();
132 bool wxPyApp::OnInitGui() {
134 wxApp::OnInitGui(); // in this case always call the base class version
135 wxPyBeginBlockThreads();
136 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
137 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
138 wxPyEndBlockThreads();
143 int wxPyApp::OnExit() {
145 wxPyBeginBlockThreads();
146 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
147 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
148 wxPyEndBlockThreads();
149 wxApp::OnExit(); // in this case always call the base class version
155 void wxPyApp::OnAssert(const wxChar
*file
,
160 // if we're not fully initialized then just log the error
161 if (! m_startupComplete
) {
164 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
174 // If the OnAssert is overloaded in the Python class then call it...
176 wxPyBeginBlockThreads();
177 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
178 PyObject
* fso
= wx2PyString(file
);
179 PyObject
* cso
= wx2PyString(file
);
182 mso
= wx2PyString(file
);
184 mso
= Py_None
; Py_INCREF(Py_None
);
186 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
191 wxPyEndBlockThreads();
193 // ...otherwise do our own thing with it
196 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
199 // turn it into a Python exception?
200 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
203 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
210 wxPyBeginBlockThreads();
211 PyObject
* s
= wx2PyString(buf
);
212 PyErr_SetObject(wxPyAssertionError
, s
);
214 wxPyEndBlockThreads();
216 // Now when control returns to whatever API wrapper was called from
217 // Python it should detect that an exception is set and will return
218 // NULL, signalling the exception to Python.
221 // Send it to the normal log destination, but only if
222 // not _DIALOG because it will call this too
223 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
226 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
235 // do the normal wx assert dialog?
236 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
237 wxApp::OnAssert(file
, line
, cond
, msg
);
245 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
247 return s_macSupportPCMenuShortcuts
;
254 long wxPyApp::GetMacAboutMenuItemId() {
256 return s_macAboutMenuItemId
;
263 long wxPyApp::GetMacPreferencesMenuItemId() {
265 return s_macPreferencesMenuItemId
;
272 long wxPyApp::GetMacExitMenuItemId() {
274 return s_macExitMenuItemId
;
281 wxString
wxPyApp::GetMacHelpMenuTitleName() {
283 return s_macHelpMenuTitleName
;
285 return wxEmptyString
;
290 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
292 s_macSupportPCMenuShortcuts
= val
;
297 void wxPyApp::SetMacAboutMenuItemId(long val
) {
299 s_macAboutMenuItemId
= val
;
304 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
306 s_macPreferencesMenuItemId
= val
;
311 void wxPyApp::SetMacExitMenuItemId(long val
) {
313 s_macExitMenuItemId
= val
;
318 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
320 s_macHelpMenuTitleName
= val
;
325 // This finishes the initialization of wxWindows and then calls the OnInit
326 // that should be present in the derived (Python) class.
327 void wxPyApp::_BootstrapApp()
330 PyObject
* retval
= NULL
;
331 PyObject
* pyint
= NULL
;
334 // Get any command-line args passed to this program from the sys module
337 wxPyBeginBlockThreads();
338 PyObject
* sysargv
= PySys_GetObject("argv");
339 if (sysargv
!= NULL
) {
340 argc
= PyList_Size(sysargv
);
341 argv
= new char*[argc
+1];
343 for(x
=0; x
<argc
; x
++) {
344 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
345 argv
[x
] = PyString_AsString(pyArg
);
349 wxPyEndBlockThreads();
351 result
= wxEntryStart(argc
, argv
);
354 wxPyBeginBlockThreads();
356 PyErr_SetString(PyExc_SystemError
, "wxEntryStart failed!");
360 // The stock objects were all NULL when they were loaded into
361 // SWIG generated proxies, so re-init those now...
362 wxPy_ReinitStockObjects(False
);
364 // It's now ok to generate exceptions for assertion errors.
365 wxPythonApp
->SetStartupComplete(True
);
367 // Call the Python wxApp's OnInit function
368 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
369 retval
= wxPyCBH_callCallbackObj(m_myInst
, Py_BuildValue("()"));
370 pyint
= PyNumber_Int(retval
);
372 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
375 result
= PyInt_AS_LONG(pyint
);
378 // Is it okay if there is no OnInit? Probably so...
384 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
391 wxPyEndBlockThreads();
394 //---------------------------------------------------------------------
395 //----------------------------------------------------------------------
399 static char* wxPyCopyCString(const wxChar
* src
)
401 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
402 size_t len
= strlen(buff
);
403 char* dest
= new char[len
+1];
409 static char* wxPyCopyCString(const char* src
) // we need a char version too
411 size_t len
= strlen(src
);
412 char* dest
= new char[len
+1];
418 static wxChar
* wxPyCopyWString(const char *src
)
420 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
421 wxString
str(src
, *wxConvCurrent
);
422 return copystring(str
);
426 static wxChar
* wxPyCopyWString(const wxChar
*src
)
428 return copystring(src
);
434 inline const char* dropwx(const char* name
) {
435 if (name
[0] == 'w' && name
[1] == 'x')
441 //----------------------------------------------------------------------
443 // This function is called when the wxc module is imported to do some initial
444 // setup. (Before there is a wxApp object.) The rest happens in
445 // wxPyApp::_BootstrapApp
446 void __wxPyPreStart(PyObject
* moduleDict
)
450 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
453 #ifdef WXP_WITH_THREAD
454 PyEval_InitThreads();
455 wxPyTStates
= new wxPyThreadStateArray
;
456 wxPyTMutex
= new wxMutex
;
458 // Save the current (main) thread state in our array
459 PyThreadState
* tstate
= wxPyBeginAllowThreads();
460 wxPyEndAllowThreads(tstate
);
463 // Ensure that the build options in the DLL (or whatever) match this build
464 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
466 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
467 wxPy_ReinitStockObjects(True
);
472 void __wxPyCleanup() {
473 wxPyDoingCleanup
= True
;
475 wxPyDoCleanup
= False
;
478 #ifdef WXP_WITH_THREAD
481 wxPyTStates
->Empty();
488 // Save a reference to the dictionary of the wx.core module, and inject
489 // a few more things into it.
490 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
493 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
496 if (!PyDict_Check(wxPython_dict
)) {
497 PyErr_SetString(PyExc_TypeError
, "_wxPySetDictionary must have dictionary object!");
501 if (! wxPyPtrTypeMap
)
502 wxPyPtrTypeMap
= PyDict_New();
503 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
505 // Create an exception object to use for wxASSERTions
506 wxPyAssertionError
= PyErr_NewException("wx.core.PyAssertionError",
507 PyExc_AssertionError
, NULL
);
508 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
512 #define wxPlatform "__WXMOTIF__"
515 #define wxPlatform "__WXX11__"
518 #define wxPlatform "__WXGTK__"
520 #if defined(__WIN32__) || defined(__WXMSW__)
521 #define wxPlatform "__WXMSW__"
524 #define wxPlatform "__WXMAC__"
533 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
534 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
535 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
541 //---------------------------------------------------------------------------
543 // Python's PyInstance_Check does not return True for instances of new-style
544 // classes. This should get close enough for both new and old classes but I
545 // should re-evaluate the need for doing instance checks...
546 bool wxPyInstance_Check(PyObject
* obj
) {
547 return PyObject_HasAttrString(obj
, "__class__") != 0;
551 // This one checks if the object is an instance of a SWIG proxy class (it has
552 // a .this attribute)
553 bool wxPySwigInstance_Check(PyObject
* obj
) {
554 return PyObject_HasAttrString(obj
, "this") != 0;
557 //---------------------------------------------------------------------------
559 // The stock objects are no longer created when the wxc module is imported, but
560 // only after the app object has been created. This function will be called before
561 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
563 void wxPy_ReinitStockObjects(bool init
)
569 #define REINITOBJ(name, classname) \
570 if ( init ) { name = (classname*)0xC0C0C0C0; } else { \
571 obj = PyDict_GetItemString(wxPython_dict, dropwx(#name)); \
572 wxCHECK_RET(obj != NULL, wxT("Unable to find stock object for " #name)) \
573 wxCHECK_RET(wxPySwigInstance_Check(obj), wxT("Not a swig instance: " #name)); \
574 ptrobj = wxPyMakeSwigPtr((void*)name, #classname); \
575 PyObject_SetAttrString(obj, "this", ptrobj); \
578 #define REINITOBJ2(name, classname) \
579 if ( init ) { } else { \
580 obj = PyDict_GetItemString(wxPython_dict, dropwx(#name)); \
581 wxCHECK_RET(obj != NULL, wxT("Unable to find stock object for " #name)) \
582 wxCHECK_RET(wxPySwigInstance_Check(obj), wxT("Not a swig instance: " #name)); \
583 ptrobj = wxPyMakeSwigPtr((void*)&name, #classname); \
584 PyObject_SetAttrString(obj, "this", ptrobj); \
588 REINITOBJ(wxNORMAL_FONT
, wxFont
);
589 REINITOBJ(wxSMALL_FONT
, wxFont
);
590 REINITOBJ(wxITALIC_FONT
, wxFont
);
591 REINITOBJ(wxSWISS_FONT
, wxFont
);
593 REINITOBJ(wxRED_PEN
, wxPen
);
594 REINITOBJ(wxCYAN_PEN
, wxPen
);
595 REINITOBJ(wxGREEN_PEN
, wxPen
);
596 REINITOBJ(wxBLACK_PEN
, wxPen
);
597 REINITOBJ(wxWHITE_PEN
, wxPen
);
598 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
599 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
600 REINITOBJ(wxGREY_PEN
, wxPen
);
601 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
602 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
604 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
605 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
606 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
607 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
608 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
609 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
610 REINITOBJ(wxRED_BRUSH
, wxBrush
);
611 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
612 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
613 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
615 REINITOBJ(wxBLACK
, wxColour
);
616 REINITOBJ(wxWHITE
, wxColour
);
617 REINITOBJ(wxRED
, wxColour
);
618 REINITOBJ(wxBLUE
, wxColour
);
619 REINITOBJ(wxGREEN
, wxColour
);
620 REINITOBJ(wxCYAN
, wxColour
);
621 REINITOBJ(wxLIGHT_GREY
, wxColour
);
623 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
624 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
625 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
627 REINITOBJ2(wxNullBitmap
, wxBitmap
);
628 REINITOBJ2(wxNullIcon
, wxIcon
);
629 REINITOBJ2(wxNullCursor
, wxCursor
);
630 REINITOBJ2(wxNullPen
, wxPen
);
631 REINITOBJ2(wxNullBrush
, wxBrush
);
632 REINITOBJ2(wxNullPalette
, wxPalette
);
633 REINITOBJ2(wxNullFont
, wxFont
);
634 REINITOBJ2(wxNullColour
, wxColour
);
636 REINITOBJ(wxTheFontList
, wxFontList
);
637 REINITOBJ(wxThePenList
, wxPenList
);
638 REINITOBJ(wxTheBrushList
, wxBrushList
);
639 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
642 REINITOBJ(wxTheClipboard
, wxClipboard
);
643 REINITOBJ2(wxDefaultValidator
, wxValidator
);
644 REINITOBJ2(wxNullImage
, wxImage
);
645 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
651 //---------------------------------------------------------------------------
653 void wxPyClientData_dtor(wxPyClientData
* self
) {
654 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
655 // may have already garbage collected the object...
656 wxPyBeginBlockThreads();
657 Py_DECREF(self
->m_obj
);
659 wxPyEndBlockThreads();
663 void wxPyUserData_dtor(wxPyUserData
* self
) {
664 if (! wxPyDoingCleanup
) {
665 wxPyBeginBlockThreads();
666 Py_DECREF(self
->m_obj
);
668 wxPyEndBlockThreads();
673 // This is called when an OOR controled object is being destroyed. Although
674 // the C++ object is going away there is no way to force the Python object
675 // (and all references to it) to die too. This causes problems (crashes) in
676 // wxPython when a python shadow object attempts to call a C++ method using
677 // the now bogus pointer... So to try and prevent this we'll do a little black
678 // magic and change the class of the python instance to a class that will
679 // raise an exception for any attempt to call methods with it. See
680 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
681 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
683 static PyObject
* deadObjectClass
= NULL
;
685 wxPyBeginBlockThreads();
686 if (deadObjectClass
== NULL
) {
687 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
688 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
689 // will lead to a deadlock when it tries to aquire the GIL again.
690 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
691 Py_INCREF(deadObjectClass
);
695 // Only if there is more than one reference to the object
696 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
697 // bool isInstance = wxPyInstance_Check(self->m_obj);
699 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
701 // Call __del__, if there is one.
702 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
704 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
708 if (PyErr_Occurred())
709 PyErr_Clear(); // just ignore it for now
712 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
714 // Clear the instance's dictionary
717 // put the name of the old class into the instance, and then reset the
718 // class to be the dead class.
719 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
720 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
721 PyDict_SetItemString(dict
, "_name", name
);
722 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
723 //Py_INCREF(deadObjectClass);
729 // m_obj is DECREF'd in the base class dtor...
730 wxPyEndBlockThreads();
734 //---------------------------------------------------------------------------
735 // Stuff used by OOR to find the right wxPython class type to return and to
739 // The pointer type map is used when the "pointer" type name generated by SWIG
740 // is not the same as the shadow class name, for example wxPyTreeCtrl
741 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
742 // so we'll just make it a Python dictionary in the wx module's namespace.
743 // (See __wxSetDictionary)
744 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
745 if (! wxPyPtrTypeMap
)
746 wxPyPtrTypeMap
= PyDict_New();
747 PyDict_SetItemString(wxPyPtrTypeMap
,
749 PyString_FromString((char*)ptrName
));
755 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
756 PyObject
* target
= NULL
;
757 bool isEvtHandler
= False
;
760 // If it's derived from wxEvtHandler then there may
761 // already be a pointer to a Python object that we can use
763 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
765 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
766 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
768 target
= data
->m_obj
;
775 // Otherwise make it the old fashioned way by making a new shadow
776 // object and putting this pointer in it. Look up the class
777 // heirarchy until we find a class name that is located in the
779 const wxClassInfo
* info
= source
->GetClassInfo();
780 wxString name
= info
->GetClassName();
781 bool exists
= wxPyCheckSwigType(name
);
782 while (info
&& !exists
) {
783 info
= info
->GetBaseClass1();
784 name
= info
->GetClassName();
785 exists
= wxPyCheckSwigType(name
);
788 target
= wxPyConstructObject((void*)source
, name
, False
);
789 if (target
&& isEvtHandler
)
790 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
792 wxString
msg(wxT("wxPython class not found for "));
793 msg
+= source
->GetClassInfo()->GetClassName();
794 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
798 } else { // source was NULL so return None.
799 Py_INCREF(Py_None
); target
= Py_None
;
805 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
806 PyObject
* target
= NULL
;
808 if (source
&& wxIsKindOf(source
, wxSizer
)) {
809 // If it's derived from wxSizer then there may already be a pointer to
810 // a Python object that we can use in the OOR data.
811 wxSizer
* sz
= (wxSizer
*)source
;
812 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
814 target
= data
->m_obj
;
820 target
= wxPyMake_wxObject(source
, False
);
821 if (target
!= Py_None
)
822 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
828 //---------------------------------------------------------------------------
831 #ifdef WXP_WITH_THREAD
833 unsigned long wxPyGetCurrentThreadId() {
834 return wxThread::GetCurrentId();
837 static PyThreadState
* gs_shutdownTState
;
840 PyThreadState
* wxPyGetThreadState() {
841 if (wxPyTMutex
== NULL
) // Python is shutting down...
842 return gs_shutdownTState
;
844 unsigned long ctid
= wxPyGetCurrentThreadId();
845 PyThreadState
* tstate
= NULL
;
848 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
849 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
850 if (info
.tid
== ctid
) {
851 tstate
= info
.tstate
;
855 wxPyTMutex
->Unlock();
856 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
861 void wxPySaveThreadState(PyThreadState
* tstate
) {
862 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
863 gs_shutdownTState
= tstate
;
866 unsigned long ctid
= wxPyGetCurrentThreadId();
868 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
869 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
870 if (info
.tid
== ctid
) {
872 if (info
.tstate
!= tstate
)
873 wxLogMessage("*** tstate mismatch!???");
875 // info.tstate = tstate; *** DO NOT update existing ones???
876 // Normally it will never change, but apparently COM callbacks
877 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
878 // tstate which will then be garbage the next time we try to use
880 wxPyTMutex
->Unlock();
884 // not found, so add it...
885 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
886 wxPyTMutex
->Unlock();
892 // Calls from Python to wxWindows code are wrapped in calls to these
895 PyThreadState
* wxPyBeginAllowThreads() {
896 #ifdef WXP_WITH_THREAD
897 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
898 wxPySaveThreadState(saved
);
905 void wxPyEndAllowThreads(PyThreadState
* saved
) {
906 #ifdef WXP_WITH_THREAD
907 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
913 // Calls from wxWindows back to Python code, or even any PyObject
914 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
916 void wxPyBeginBlockThreads() {
917 #ifdef WXP_WITH_THREAD
918 PyThreadState
* tstate
= wxPyGetThreadState();
919 PyEval_RestoreThread(tstate
);
924 void wxPyEndBlockThreads() {
925 #ifdef WXP_WITH_THREAD
926 // Is there any need to save it again?
927 // PyThreadState* tstate =
933 //---------------------------------------------------------------------------
934 // wxPyInputStream and wxPyCBInputStream methods
937 void wxPyInputStream::close() {
938 /* do nothing for now */
941 void wxPyInputStream::flush() {
942 /* do nothing for now */
945 bool wxPyInputStream::eof() {
947 return m_wxis
->Eof();
952 wxPyInputStream::~wxPyInputStream() {
959 PyObject
* wxPyInputStream::read(int size
) {
960 PyObject
* obj
= NULL
;
962 const int BUFSIZE
= 1024;
964 // check if we have a real wxInputStream to work with
966 wxPyBeginBlockThreads();
967 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
968 wxPyEndBlockThreads();
973 // read while bytes are available on the stream
974 while ( m_wxis
->CanRead() ) {
975 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
976 buf
.UngetAppendBuf(m_wxis
->LastRead());
979 } else { // Read only size number of characters
980 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
981 buf
.UngetWriteBuf(m_wxis
->LastRead());
985 wxPyBeginBlockThreads();
986 wxStreamError err
= m_wxis
->GetLastError();
987 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
988 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
991 // We use only strings for the streams, not unicode
992 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
994 wxPyEndBlockThreads();
999 PyObject
* wxPyInputStream::readline(int size
) {
1000 PyObject
* obj
= NULL
;
1005 // check if we have a real wxInputStream to work with
1007 wxPyBeginBlockThreads();
1008 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1009 wxPyEndBlockThreads();
1013 // read until \n or byte limit reached
1014 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1015 ch
= m_wxis
->GetC();
1020 wxPyBeginBlockThreads();
1021 wxStreamError err
= m_wxis
->GetLastError();
1022 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1023 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1026 // We use only strings for the streams, not unicode
1027 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1029 wxPyEndBlockThreads();
1034 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1037 // check if we have a real wxInputStream to work with
1039 wxPyBeginBlockThreads();
1040 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1041 wxPyEndBlockThreads();
1046 wxPyBeginBlockThreads();
1047 pylist
= PyList_New(0);
1049 wxPyBeginBlockThreads();
1051 wxPyEndBlockThreads();
1055 // read sizehint bytes or until EOF
1057 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1058 PyObject
* s
= this->readline();
1060 wxPyBeginBlockThreads();
1062 wxPyEndBlockThreads();
1065 wxPyBeginBlockThreads();
1066 PyList_Append(pylist
, s
);
1067 i
+= PyString_Size(s
);
1068 wxPyEndBlockThreads();
1072 wxStreamError err
= m_wxis
->GetLastError();
1073 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1074 wxPyBeginBlockThreads();
1076 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1077 wxPyEndBlockThreads();
1085 void wxPyInputStream::seek(int offset
, int whence
) {
1087 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1090 int wxPyInputStream::tell(){
1092 return m_wxis
->TellI();
1099 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1100 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1104 wxPyCBInputStream::~wxPyCBInputStream() {
1105 if (m_block
) wxPyBeginBlockThreads();
1109 if (m_block
) wxPyEndBlockThreads();
1113 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1114 if (block
) wxPyBeginBlockThreads();
1116 PyObject
* read
= getMethod(py
, "read");
1117 PyObject
* seek
= getMethod(py
, "seek");
1118 PyObject
* tell
= getMethod(py
, "tell");
1121 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1125 if (block
) wxPyEndBlockThreads();
1129 if (block
) wxPyEndBlockThreads();
1130 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1134 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1135 return wxPyCBInputStream::create(py
, block
);
1138 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1139 if (!PyObject_HasAttrString(py
, name
))
1141 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1142 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1150 size_t wxPyCBInputStream::GetSize() const {
1151 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1152 if (m_seek
&& m_tell
) {
1153 off_t temp
= self
->OnSysTell();
1154 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1155 self
->OnSysSeek(temp
, wxFromStart
);
1163 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1167 wxPyBeginBlockThreads();
1168 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1169 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1173 if ((result
!= NULL
) && PyString_Check(result
)) {
1174 o
= PyString_Size(result
);
1176 m_lasterror
= wxSTREAM_EOF
;
1179 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1184 m_lasterror
= wxSTREAM_READ_ERROR
;
1185 wxPyEndBlockThreads();
1189 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1190 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1194 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1195 wxPyBeginBlockThreads();
1197 // off_t is a 64-bit value...
1198 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1200 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1202 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1205 wxPyEndBlockThreads();
1210 off_t
wxPyCBInputStream::OnSysTell() const {
1211 wxPyBeginBlockThreads();
1212 PyObject
* arglist
= Py_BuildValue("()");
1213 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1216 if (result
!= NULL
) {
1218 if (PyLong_Check(result
))
1219 o
= PyLong_AsLongLong(result
);
1222 o
= PyInt_AsLong(result
);
1226 wxPyEndBlockThreads();
1230 //----------------------------------------------------------------------
1232 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1234 wxPyCallback::wxPyCallback(PyObject
* func
) {
1239 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1240 m_func
= other
.m_func
;
1244 wxPyCallback::~wxPyCallback() {
1245 wxPyBeginBlockThreads();
1247 wxPyEndBlockThreads();
1252 // This function is used for all events destined for Python event handlers.
1253 void wxPyCallback::EventThunker(wxEvent
& event
) {
1254 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1255 PyObject
* func
= cb
->m_func
;
1259 bool checkSkip
= False
;
1261 wxPyBeginBlockThreads();
1262 wxString className
= event
.GetClassInfo()->GetClassName();
1264 // If the event is one of these types then pass the original
1265 // event object instead of the one passed to us.
1266 if ( className
== wxT("wxPyEvent") ) {
1267 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1268 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1270 else if ( className
== wxT("wxPyCommandEvent") ) {
1271 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1272 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1275 arg
= wxPyConstructObject((void*)&event
, className
);
1278 // Call the event handler, passing the event object
1279 tuple
= PyTuple_New(1);
1280 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1281 result
= PyEval_CallObject(func
, tuple
);
1283 Py_DECREF(result
); // result is ignored, but we still need to decref it
1284 PyErr_Clear(); // Just in case...
1290 // if the event object was one of our special types and
1291 // it had been cloned, then we need to extract the Skipped
1292 // value from the original and set it in the clone.
1293 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1295 event
.Skip(PyInt_AsLong(result
));
1303 wxPyEndBlockThreads();
1307 //----------------------------------------------------------------------
1309 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1311 m_self
= other
.m_self
;
1312 m_class
= other
.m_class
;
1320 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1331 #if PYTHON_API_VERSION >= 1011
1333 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1334 // in which the method was defined. Starting with 2.2 it returns
1335 // "class that asked for the method" which seems totally bogus to me
1336 // but apprently it fixes some obscure problem waiting to happen in
1337 // Python. Since the API was not documented Guido and the gang felt
1338 // safe in changing it. Needless to say that totally screwed up the
1339 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1340 // code to find the class where the method is actually defined...
1343 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1347 if (PyType_Check(klass
)) { // new style classes
1348 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1349 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1350 PyObject
*mro
, *res
, *base
, *dict
;
1351 /* Look in tp_dict of types in MRO */
1353 assert(PyTuple_Check(mro
));
1354 n
= PyTuple_GET_SIZE(mro
);
1355 for (i
= 0; i
< n
; i
++) {
1356 base
= PyTuple_GET_ITEM(mro
, i
);
1357 if (PyClass_Check(base
))
1358 dict
= ((PyClassObject
*)base
)->cl_dict
;
1360 assert(PyType_Check(base
));
1361 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1363 assert(dict
&& PyDict_Check(dict
));
1364 res
= PyDict_GetItem(dict
, name
);
1371 else if (PyClass_Check(klass
)) { // old style classes
1372 // This code is borrowed/adapted from class_lookup in classobject.c
1373 PyClassObject
* cp
= (PyClassObject
*)klass
;
1374 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1375 if (value
!= NULL
) {
1376 return (PyObject
*)cp
;
1378 n
= PyTuple_Size(cp
->cl_bases
);
1379 for (i
= 0; i
< n
; i
++) {
1380 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1381 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1393 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1395 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1397 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1399 #else // 2.2 and after, the hard way...
1401 PyObject
* nameo
= PyString_FromString(name
);
1402 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1410 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1411 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1412 self
->m_lastFound
= NULL
;
1414 // If the object (m_self) has an attibute of the given name...
1415 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1416 PyObject
*method
, *klass
;
1417 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1419 // ...and if that attribute is a method, and if that method's class is
1420 // not from a base class...
1421 if (PyMethod_Check(method
) &&
1422 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1423 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1425 // ...then we'll save a pointer to the method so callCallback can call it.
1426 self
->m_lastFound
= method
;
1432 return m_lastFound
!= NULL
;
1436 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1440 result
= callCallbackObj(argTuple
);
1441 if (result
) { // Assumes an integer return type...
1442 retval
= PyInt_AsLong(result
);
1444 PyErr_Clear(); // forget about it if it's not...
1449 // Invoke the Python callable object, returning the raw PyObject return
1450 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1451 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1454 // Save a copy of the pointer in case the callback generates another
1455 // callback. In that case m_lastFound will have a different value when
1456 // it gets back here...
1457 PyObject
* method
= m_lastFound
;
1459 result
= PyEval_CallObject(method
, argTuple
);
1460 Py_DECREF(argTuple
);
1469 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1470 cbh
.setSelf(self
, klass
, incref
);
1473 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1474 return cbh
.findCallback(name
);
1477 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1478 return cbh
.callCallback(argTuple
);
1481 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1482 return cbh
.callCallbackObj(argTuple
);
1486 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1487 if (cbh
->m_incRef
) {
1488 wxPyBeginBlockThreads();
1489 Py_XDECREF(cbh
->m_self
);
1490 Py_XDECREF(cbh
->m_class
);
1491 wxPyEndBlockThreads();
1495 //---------------------------------------------------------------------------
1496 //---------------------------------------------------------------------------
1497 // These event classes can be derived from in Python and passed through the event
1498 // system without losing anything. They do this by keeping a reference to
1499 // themselves and some special case handling in wxPyCallback::EventThunker.
1502 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1503 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1504 //Py_INCREF(m_self); // circular loops...
1508 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1509 wxPyBeginBlockThreads();
1512 wxPyEndBlockThreads();
1515 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1516 wxPyBeginBlockThreads();
1524 wxPyEndBlockThreads();
1527 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1533 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1534 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1537 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1538 : wxEvent(winid
, commandType
) {
1542 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1545 SetSelf(evt
.m_self
, True
);
1549 wxPyEvent::~wxPyEvent() {
1553 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1554 : wxCommandEvent(commandType
, id
) {
1558 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1559 : wxCommandEvent(evt
)
1561 SetSelf(evt
.m_self
, True
);
1565 wxPyCommandEvent::~wxPyCommandEvent() {
1572 //---------------------------------------------------------------------------
1573 //---------------------------------------------------------------------------
1574 // Convert a wxList to a Python List, only works for lists of wxObjects
1576 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1577 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1581 wxNode
* node
= list
->GetFirst();
1583 wxPyBeginBlockThreads();
1584 pyList
= PyList_New(0);
1586 wxObj
= node
->GetData();
1587 pyObj
= wxPyMake_wxObject(wxObj
);
1588 PyList_Append(pyList
, pyObj
);
1589 node
= node
->GetNext();
1591 wxPyEndBlockThreads();
1595 //----------------------------------------------------------------------
1597 long wxPyGetWinHandle(wxWindow
* win
) {
1599 return (long)win
->GetHandle();
1602 // Find and return the actual X-Window.
1604 if (win
->m_wxwindow
) {
1606 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1608 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1610 return (long)bwin
->xwindow
;
1618 //----------------------------------------------------------------------
1619 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1620 // included in every file over and over again...
1622 #if PYTHON_API_VERSION >= 1009
1623 static char* wxStringErrorMsg
= "String or Unicode type required";
1625 static char* wxStringErrorMsg
= "String type required";
1629 wxString
* wxString_in_helper(PyObject
* source
) {
1631 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1632 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1633 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1637 if (PyUnicode_Check(source
)) {
1638 target
= new wxString();
1639 size_t len
= PyUnicode_GET_SIZE(source
);
1641 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1642 target
->UngetWriteBuf();
1645 // It is a string, get pointers to it and transform to unicode
1646 char* tmpPtr
; int tmpSize
;
1647 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1648 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1651 char* tmpPtr
; int tmpSize
;
1652 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1653 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1656 target
= new wxString(tmpPtr
, tmpSize
);
1657 #endif // wxUSE_UNICODE
1659 #else // No Python unicode API (1.5.2)
1660 if (!PyString_Check(source
)) {
1661 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1664 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1670 // Similar to above except doesn't use "new" and doesn't set an exception
1671 wxString
Py2wxString(PyObject
* source
)
1674 bool doDecRef
= False
;
1676 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1677 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1678 // Convert to String if not one already... (TODO: Unicode too?)
1679 source
= PyObject_Str(source
);
1684 if (PyUnicode_Check(source
)) {
1685 size_t len
= PyUnicode_GET_SIZE(source
);
1687 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1688 target
.UngetWriteBuf();
1691 // It is a string, get pointers to it and transform to unicode
1692 char* tmpPtr
; int tmpSize
;
1693 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1694 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1697 char* tmpPtr
; int tmpSize
;
1698 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1699 target
= wxString(tmpPtr
, tmpSize
);
1700 #endif // wxUSE_UNICODE
1702 #else // No Python unicode API (1.5.2)
1703 if (!PyString_Check(source
)) {
1704 // Convert to String if not one already...
1705 source
= PyObject_Str(source
);
1708 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1717 // Make either a Python String or Unicode object, depending on build mode
1718 PyObject
* wx2PyString(const wxString
& src
)
1722 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1724 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1730 //----------------------------------------------------------------------
1733 byte
* byte_LIST_helper(PyObject
* source
) {
1734 if (!PyList_Check(source
)) {
1735 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1738 int count
= PyList_Size(source
);
1739 byte
* temp
= new byte
[count
];
1741 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1744 for (int x
=0; x
<count
; x
++) {
1745 PyObject
* o
= PyList_GetItem(source
, x
);
1746 if (! PyInt_Check(o
)) {
1747 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1750 temp
[x
] = (byte
)PyInt_AsLong(o
);
1756 int* int_LIST_helper(PyObject
* source
) {
1757 if (!PyList_Check(source
)) {
1758 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1761 int count
= PyList_Size(source
);
1762 int* temp
= new int[count
];
1764 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1767 for (int x
=0; x
<count
; x
++) {
1768 PyObject
* o
= PyList_GetItem(source
, x
);
1769 if (! PyInt_Check(o
)) {
1770 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1773 temp
[x
] = PyInt_AsLong(o
);
1779 long* long_LIST_helper(PyObject
* source
) {
1780 if (!PyList_Check(source
)) {
1781 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1784 int count
= PyList_Size(source
);
1785 long* temp
= new long[count
];
1787 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1790 for (int x
=0; x
<count
; x
++) {
1791 PyObject
* o
= PyList_GetItem(source
, x
);
1792 if (! PyInt_Check(o
)) {
1793 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1796 temp
[x
] = PyInt_AsLong(o
);
1802 char** string_LIST_helper(PyObject
* source
) {
1803 if (!PyList_Check(source
)) {
1804 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1807 int count
= PyList_Size(source
);
1808 char** temp
= new char*[count
];
1810 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1813 for (int x
=0; x
<count
; x
++) {
1814 PyObject
* o
= PyList_GetItem(source
, x
);
1815 if (! PyString_Check(o
)) {
1816 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1819 temp
[x
] = PyString_AsString(o
);
1824 //--------------------------------
1825 // Part of patch from Tim Hochberg
1826 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1827 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1828 point
->x
= PyInt_AS_LONG(o1
);
1829 point
->y
= PyInt_AS_LONG(o2
);
1832 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1833 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1834 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1837 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1838 // Disallow instances because they can cause havok
1841 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1842 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1843 point
->x
= PyInt_AsLong(o1
);
1844 point
->y
= PyInt_AsLong(o2
);
1851 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1852 // Putting all of the declarations here allows
1853 // us to put the error handling all in one place.
1856 PyObject
*o
, *o1
, *o2
;
1857 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1859 if (!PySequence_Check(source
)) {
1863 // The length of the sequence is returned in count.
1864 *count
= PySequence_Length(source
);
1869 temp
= new wxPoint
[*count
];
1871 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1874 for (x
=0; x
<*count
; x
++) {
1875 // Get an item: try fast way first.
1877 o
= PySequence_Fast_GET_ITEM(source
, x
);
1880 o
= PySequence_GetItem(source
, x
);
1886 // Convert o to wxPoint.
1887 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1888 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1889 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1890 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1891 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1895 else if (wxPySwigInstance_Check(o
)) {
1897 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1902 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1903 o1
= PySequence_GetItem(o
, 0);
1904 o2
= PySequence_GetItem(o
, 1);
1905 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1929 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
1933 //------------------------------
1936 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
1937 if (!PyList_Check(source
)) {
1938 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1941 int count
= PyList_Size(source
);
1942 wxBitmap
** temp
= new wxBitmap
*[count
];
1944 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1947 for (int x
=0; x
<count
; x
++) {
1948 PyObject
* o
= PyList_GetItem(source
, x
);
1949 if (wxPySwigInstance_Check(o
)) {
1951 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
1952 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
1958 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
1967 wxString
* wxString_LIST_helper(PyObject
* source
) {
1968 if (!PyList_Check(source
)) {
1969 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1972 int count
= PyList_Size(source
);
1973 wxString
* temp
= new wxString
[count
];
1975 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1978 for (int x
=0; x
<count
; x
++) {
1979 PyObject
* o
= PyList_GetItem(source
, x
);
1980 #if PYTHON_API_VERSION >= 1009
1981 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
1982 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
1986 if (! PyString_Check(o
)) {
1987 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1992 wxString
* pStr
= wxString_in_helper(o
);
2000 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2001 if (!PyList_Check(source
)) {
2002 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2005 int count
= PyList_Size(source
);
2006 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2008 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2011 for (int x
=0; x
<count
; x
++) {
2012 PyObject
* o
= PyList_GetItem(source
, x
);
2013 if (wxPySwigInstance_Check(o
)) {
2014 wxAcceleratorEntry
* ae
;
2015 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2016 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2021 else if (PyTuple_Check(o
)) {
2022 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2023 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2024 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2025 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2028 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2036 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2037 if (!PyList_Check(source
)) {
2038 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2041 int count
= PyList_Size(source
);
2042 wxPen
** temp
= new wxPen
*[count
];
2044 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2047 for (int x
=0; x
<count
; x
++) {
2048 PyObject
* o
= PyList_GetItem(source
, x
);
2049 if (wxPySwigInstance_Check(o
)) {
2051 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2053 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2060 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2068 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2069 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2072 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2076 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2077 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2080 o1
= PySequence_GetItem(source
, 0);
2081 o2
= PySequence_GetItem(source
, 1);
2084 *i1
= PyInt_AsLong(o1
);
2085 *i2
= PyInt_AsLong(o2
);
2095 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2096 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2097 PyObject
*o1
, *o2
, *o3
, *o4
;
2099 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2103 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2104 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2105 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2106 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2109 o1
= PySequence_GetItem(source
, 0);
2110 o2
= PySequence_GetItem(source
, 1);
2111 o3
= PySequence_GetItem(source
, 2);
2112 o4
= PySequence_GetItem(source
, 3);
2115 *i1
= PyInt_AsLong(o1
);
2116 *i2
= PyInt_AsLong(o2
);
2117 *i3
= PyInt_AsLong(o3
);
2118 *i4
= PyInt_AsLong(o4
);
2130 //----------------------------------------------------------------------
2132 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2136 if (wxPySwigInstance_Check(source
) &&
2137 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2141 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2147 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2149 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2153 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2155 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2160 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2162 // If source is an object instance then it may already be the right type
2163 if (wxPySwigInstance_Check(source
)) {
2165 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2170 // otherwise a 2-tuple of floats is expected
2171 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2172 PyObject
* o1
= PySequence_GetItem(source
, 0);
2173 PyObject
* o2
= PySequence_GetItem(source
, 1);
2174 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2179 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2186 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2192 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2194 // If source is an object instance then it may already be the right type
2195 if (wxPySwigInstance_Check(source
)) {
2197 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2202 // otherwise a 4-tuple of integers is expected
2203 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2204 PyObject
* o1
= PySequence_GetItem(source
, 0);
2205 PyObject
* o2
= PySequence_GetItem(source
, 1);
2206 PyObject
* o3
= PySequence_GetItem(source
, 2);
2207 PyObject
* o4
= PySequence_GetItem(source
, 3);
2208 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2209 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2216 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2217 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2226 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2232 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2234 // If source is an object instance then it may already be the right type
2235 if (wxPySwigInstance_Check(source
)) {
2237 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2242 // otherwise check for a string
2243 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2244 wxString spec
= Py2wxString(source
);
2245 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2246 long red
, green
, blue
;
2247 red
= green
= blue
= 0;
2248 spec
.Mid(1,2).ToLong(&red
, 16);
2249 spec
.Mid(3,2).ToLong(&green
, 16);
2250 spec
.Mid(5,2).ToLong(&blue
, 16);
2252 **obj
= wxColour(red
, green
, blue
);
2255 else { // it's a colour name
2256 **obj
= wxColour(spec
);
2260 // last chance: 3-tuple of integers is expected
2261 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2262 PyObject
* o1
= PySequence_GetItem(source
, 0);
2263 PyObject
* o2
= PySequence_GetItem(source
, 1);
2264 PyObject
* o3
= PySequence_GetItem(source
, 2);
2265 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2271 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2279 PyErr_SetString(PyExc_TypeError
,
2280 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2285 bool wxColour_typecheck(PyObject
* source
) {
2287 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2290 if (PyString_Check(source
) || PyUnicode_Check(source
))
2298 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2299 // If source is an object instance then it may already be the right type
2300 if (wxPySwigInstance_Check(source
)) {
2302 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2307 // otherwise a length-2 sequence of floats is expected
2308 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2309 PyObject
* o1
= PySequence_GetItem(source
, 0);
2310 PyObject
* o2
= PySequence_GetItem(source
, 1);
2311 // This should really check for floats, not numbers -- but that would break code.
2312 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2317 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2323 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2328 //----------------------------------------------------------------------
2330 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2332 PyObject
* list
= PyList_New(0);
2333 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2335 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2337 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2339 PyList_Append(list
, str
);
2346 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2348 PyObject
* list
= PyList_New(0);
2349 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2350 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2351 PyList_Append(list
, number
);
2358 //----------------------------------------------------------------------
2359 //----------------------------------------------------------------------