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")) {
370 PyObject
* method
= m_myInst
.GetLastFound();
371 PyObject
* argTuple
= PyTuple_New(0);
372 retval
= PyEval_CallObject(method
, argTuple
);
378 pyint
= PyNumber_Int(retval
);
380 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
383 result
= PyInt_AS_LONG(pyint
);
386 // Is it okay if there is no OnInit? Probably so...
392 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
399 wxPyEndBlockThreads();
402 //---------------------------------------------------------------------
403 //----------------------------------------------------------------------
407 static char* wxPyCopyCString(const wxChar
* src
)
409 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
410 size_t len
= strlen(buff
);
411 char* dest
= new char[len
+1];
417 static char* wxPyCopyCString(const char* src
) // we need a char version too
419 size_t len
= strlen(src
);
420 char* dest
= new char[len
+1];
426 static wxChar
* wxPyCopyWString(const char *src
)
428 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
429 wxString
str(src
, *wxConvCurrent
);
430 return copystring(str
);
434 static wxChar
* wxPyCopyWString(const wxChar
*src
)
436 return copystring(src
);
442 inline const char* dropwx(const char* name
) {
443 if (name
[0] == 'w' && name
[1] == 'x')
449 //----------------------------------------------------------------------
451 // This function is called when the wxc module is imported to do some initial
452 // setup. (Before there is a wxApp object.) The rest happens in
453 // wxPyApp::_BootstrapApp
454 void __wxPyPreStart(PyObject
* moduleDict
)
458 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
461 #ifdef WXP_WITH_THREAD
462 PyEval_InitThreads();
463 wxPyTStates
= new wxPyThreadStateArray
;
464 wxPyTMutex
= new wxMutex
;
466 // Save the current (main) thread state in our array
467 PyThreadState
* tstate
= wxPyBeginAllowThreads();
468 wxPyEndAllowThreads(tstate
);
471 // Ensure that the build options in the DLL (or whatever) match this build
472 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
474 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
475 wxPy_ReinitStockObjects(True
);
480 void __wxPyCleanup() {
481 wxPyDoingCleanup
= True
;
483 wxPyDoCleanup
= False
;
486 #ifdef WXP_WITH_THREAD
489 wxPyTStates
->Empty();
496 // Save a reference to the dictionary of the wx.core module, and inject
497 // a few more things into it.
498 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
501 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
504 if (!PyDict_Check(wxPython_dict
)) {
505 PyErr_SetString(PyExc_TypeError
, "_wxPySetDictionary must have dictionary object!");
509 if (! wxPyPtrTypeMap
)
510 wxPyPtrTypeMap
= PyDict_New();
511 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
513 // Create an exception object to use for wxASSERTions
514 wxPyAssertionError
= PyErr_NewException("wx.core.PyAssertionError",
515 PyExc_AssertionError
, NULL
);
516 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
520 #define wxPlatform "__WXMOTIF__"
523 #define wxPlatform "__WXX11__"
526 #define wxPlatform "__WXGTK__"
528 #if defined(__WIN32__) || defined(__WXMSW__)
529 #define wxPlatform "__WXMSW__"
532 #define wxPlatform "__WXMAC__"
541 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
542 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
543 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
549 //---------------------------------------------------------------------------
551 // Python's PyInstance_Check does not return True for instances of new-style
552 // classes. This should get close enough for both new and old classes but I
553 // should re-evaluate the need for doing instance checks...
554 bool wxPyInstance_Check(PyObject
* obj
) {
555 return PyObject_HasAttrString(obj
, "__class__") != 0;
559 // This one checks if the object is an instance of a SWIG proxy class (it has
560 // a .this attribute)
561 bool wxPySwigInstance_Check(PyObject
* obj
) {
562 return PyObject_HasAttrString(obj
, "this") != 0;
565 //---------------------------------------------------------------------------
567 // The stock objects are no longer created when the wxc module is imported, but
568 // only after the app object has been created. This function will be called before
569 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
571 void wxPy_ReinitStockObjects(bool init
)
577 #define REINITOBJ(name, classname) \
578 if ( init ) { name = (classname*)0xC0C0C0C0; } else { \
579 obj = PyDict_GetItemString(wxPython_dict, dropwx(#name)); \
580 wxCHECK_RET(obj != NULL, wxT("Unable to find stock object for " #name)) \
581 wxCHECK_RET(wxPySwigInstance_Check(obj), wxT("Not a swig instance: " #name)); \
582 ptrobj = wxPyMakeSwigPtr((void*)name, wxT(#classname)); \
583 PyObject_SetAttrString(obj, "this", ptrobj); \
586 #define REINITOBJ2(name, classname) \
587 if ( init ) { } else { \
588 obj = PyDict_GetItemString(wxPython_dict, dropwx(#name)); \
589 wxCHECK_RET(obj != NULL, wxT("Unable to find stock object for " #name)) \
590 wxCHECK_RET(wxPySwigInstance_Check(obj), wxT("Not a swig instance: " #name)); \
591 ptrobj = wxPyMakeSwigPtr((void*)&name, wxT(#classname)); \
592 PyObject_SetAttrString(obj, "this", ptrobj); \
596 REINITOBJ(wxNORMAL_FONT
, wxFont
);
597 REINITOBJ(wxSMALL_FONT
, wxFont
);
598 REINITOBJ(wxITALIC_FONT
, wxFont
);
599 REINITOBJ(wxSWISS_FONT
, wxFont
);
601 REINITOBJ(wxRED_PEN
, wxPen
);
602 REINITOBJ(wxCYAN_PEN
, wxPen
);
603 REINITOBJ(wxGREEN_PEN
, wxPen
);
604 REINITOBJ(wxBLACK_PEN
, wxPen
);
605 REINITOBJ(wxWHITE_PEN
, wxPen
);
606 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
607 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
608 REINITOBJ(wxGREY_PEN
, wxPen
);
609 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
610 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
612 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
613 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
614 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
615 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
616 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
617 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
618 REINITOBJ(wxRED_BRUSH
, wxBrush
);
619 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
620 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
621 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
623 REINITOBJ(wxBLACK
, wxColour
);
624 REINITOBJ(wxWHITE
, wxColour
);
625 REINITOBJ(wxRED
, wxColour
);
626 REINITOBJ(wxBLUE
, wxColour
);
627 REINITOBJ(wxGREEN
, wxColour
);
628 REINITOBJ(wxCYAN
, wxColour
);
629 REINITOBJ(wxLIGHT_GREY
, wxColour
);
631 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
632 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
633 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
635 REINITOBJ2(wxNullBitmap
, wxBitmap
);
636 REINITOBJ2(wxNullIcon
, wxIcon
);
637 REINITOBJ2(wxNullCursor
, wxCursor
);
638 REINITOBJ2(wxNullPen
, wxPen
);
639 REINITOBJ2(wxNullBrush
, wxBrush
);
640 REINITOBJ2(wxNullPalette
, wxPalette
);
641 REINITOBJ2(wxNullFont
, wxFont
);
642 REINITOBJ2(wxNullColour
, wxColour
);
644 REINITOBJ(wxTheFontList
, wxFontList
);
645 REINITOBJ(wxThePenList
, wxPenList
);
646 REINITOBJ(wxTheBrushList
, wxBrushList
);
647 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
650 REINITOBJ(wxTheClipboard
, wxClipboard
);
651 REINITOBJ2(wxDefaultValidator
, wxValidator
);
652 REINITOBJ2(wxNullImage
, wxImage
);
653 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
659 //---------------------------------------------------------------------------
661 void wxPyClientData_dtor(wxPyClientData
* self
) {
662 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
663 // may have already garbage collected the object...
664 wxPyBeginBlockThreads();
665 Py_DECREF(self
->m_obj
);
667 wxPyEndBlockThreads();
671 void wxPyUserData_dtor(wxPyUserData
* self
) {
672 if (! wxPyDoingCleanup
) {
673 wxPyBeginBlockThreads();
674 Py_DECREF(self
->m_obj
);
676 wxPyEndBlockThreads();
681 // This is called when an OOR controled object is being destroyed. Although
682 // the C++ object is going away there is no way to force the Python object
683 // (and all references to it) to die too. This causes problems (crashes) in
684 // wxPython when a python shadow object attempts to call a C++ method using
685 // the now bogus pointer... So to try and prevent this we'll do a little black
686 // magic and change the class of the python instance to a class that will
687 // raise an exception for any attempt to call methods with it. See
688 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
689 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
691 static PyObject
* deadObjectClass
= NULL
;
693 wxPyBeginBlockThreads();
694 if (deadObjectClass
== NULL
) {
695 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
696 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
697 // will lead to a deadlock when it tries to aquire the GIL again.
698 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
699 Py_INCREF(deadObjectClass
);
703 // Only if there is more than one reference to the object
704 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
705 // bool isInstance = wxPyInstance_Check(self->m_obj);
707 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
709 // Call __del__, if there is one.
710 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
712 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
716 if (PyErr_Occurred())
717 PyErr_Clear(); // just ignore it for now
720 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
722 // Clear the instance's dictionary
725 // put the name of the old class into the instance, and then reset the
726 // class to be the dead class.
727 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
728 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
729 PyDict_SetItemString(dict
, "_name", name
);
730 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
731 //Py_INCREF(deadObjectClass);
737 // m_obj is DECREF'd in the base class dtor...
738 wxPyEndBlockThreads();
742 //---------------------------------------------------------------------------
743 // Stuff used by OOR to find the right wxPython class type to return and to
747 // The pointer type map is used when the "pointer" type name generated by SWIG
748 // is not the same as the shadow class name, for example wxPyTreeCtrl
749 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
750 // so we'll just make it a Python dictionary in the wx module's namespace.
751 // (See __wxSetDictionary)
752 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
753 if (! wxPyPtrTypeMap
)
754 wxPyPtrTypeMap
= PyDict_New();
755 PyDict_SetItemString(wxPyPtrTypeMap
,
757 PyString_FromString((char*)ptrName
));
763 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
764 PyObject
* target
= NULL
;
765 bool isEvtHandler
= False
;
768 // If it's derived from wxEvtHandler then there may
769 // already be a pointer to a Python object that we can use
771 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
773 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
774 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
776 target
= data
->m_obj
;
783 // Otherwise make it the old fashioned way by making a new shadow
784 // object and putting this pointer in it. Look up the class
785 // heirarchy until we find a class name that is located in the
787 const wxClassInfo
* info
= source
->GetClassInfo();
788 wxString name
= info
->GetClassName();
789 bool exists
= wxPyCheckSwigType(name
);
790 while (info
&& !exists
) {
791 info
= info
->GetBaseClass1();
792 name
= info
->GetClassName();
793 exists
= wxPyCheckSwigType(name
);
796 target
= wxPyConstructObject((void*)source
, name
, False
);
797 if (target
&& isEvtHandler
)
798 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
800 wxString
msg(wxT("wxPython class not found for "));
801 msg
+= source
->GetClassInfo()->GetClassName();
802 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
806 } else { // source was NULL so return None.
807 Py_INCREF(Py_None
); target
= Py_None
;
813 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
814 PyObject
* target
= NULL
;
816 if (source
&& wxIsKindOf(source
, wxSizer
)) {
817 // If it's derived from wxSizer then there may already be a pointer to
818 // a Python object that we can use in the OOR data.
819 wxSizer
* sz
= (wxSizer
*)source
;
820 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
822 target
= data
->m_obj
;
828 target
= wxPyMake_wxObject(source
, False
);
829 if (target
!= Py_None
)
830 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
836 //---------------------------------------------------------------------------
839 #ifdef WXP_WITH_THREAD
841 unsigned long wxPyGetCurrentThreadId() {
842 return wxThread::GetCurrentId();
845 static PyThreadState
* gs_shutdownTState
;
848 PyThreadState
* wxPyGetThreadState() {
849 if (wxPyTMutex
== NULL
) // Python is shutting down...
850 return gs_shutdownTState
;
852 unsigned long ctid
= wxPyGetCurrentThreadId();
853 PyThreadState
* tstate
= NULL
;
856 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
857 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
858 if (info
.tid
== ctid
) {
859 tstate
= info
.tstate
;
863 wxPyTMutex
->Unlock();
864 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
869 void wxPySaveThreadState(PyThreadState
* tstate
) {
870 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
871 gs_shutdownTState
= tstate
;
874 unsigned long ctid
= wxPyGetCurrentThreadId();
876 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
877 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
878 if (info
.tid
== ctid
) {
880 if (info
.tstate
!= tstate
)
881 wxLogMessage("*** tstate mismatch!???");
883 // info.tstate = tstate; *** DO NOT update existing ones???
884 // Normally it will never change, but apparently COM callbacks
885 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
886 // tstate which will then be garbage the next time we try to use
888 wxPyTMutex
->Unlock();
892 // not found, so add it...
893 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
894 wxPyTMutex
->Unlock();
900 // Calls from Python to wxWindows code are wrapped in calls to these
903 PyThreadState
* wxPyBeginAllowThreads() {
904 #ifdef WXP_WITH_THREAD
905 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
906 wxPySaveThreadState(saved
);
913 void wxPyEndAllowThreads(PyThreadState
* saved
) {
914 #ifdef WXP_WITH_THREAD
915 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
921 // Calls from wxWindows back to Python code, or even any PyObject
922 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
924 void wxPyBeginBlockThreads() {
925 #ifdef WXP_WITH_THREAD
926 PyThreadState
* tstate
= wxPyGetThreadState();
927 PyEval_RestoreThread(tstate
);
932 void wxPyEndBlockThreads() {
933 #ifdef WXP_WITH_THREAD
934 // Is there any need to save it again?
935 // PyThreadState* tstate =
941 //---------------------------------------------------------------------------
942 // wxPyInputStream and wxPyCBInputStream methods
945 void wxPyInputStream::close() {
946 /* do nothing for now */
949 void wxPyInputStream::flush() {
950 /* do nothing for now */
953 bool wxPyInputStream::eof() {
955 return m_wxis
->Eof();
960 wxPyInputStream::~wxPyInputStream() {
967 PyObject
* wxPyInputStream::read(int size
) {
968 PyObject
* obj
= NULL
;
970 const int BUFSIZE
= 1024;
972 // check if we have a real wxInputStream to work with
974 wxPyBeginBlockThreads();
975 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
976 wxPyEndBlockThreads();
981 // read while bytes are available on the stream
982 while ( m_wxis
->CanRead() ) {
983 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
984 buf
.UngetAppendBuf(m_wxis
->LastRead());
987 } else { // Read only size number of characters
988 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
989 buf
.UngetWriteBuf(m_wxis
->LastRead());
993 wxPyBeginBlockThreads();
994 wxStreamError err
= m_wxis
->GetLastError();
995 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
996 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
999 // We use only strings for the streams, not unicode
1000 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1002 wxPyEndBlockThreads();
1007 PyObject
* wxPyInputStream::readline(int size
) {
1008 PyObject
* obj
= NULL
;
1013 // check if we have a real wxInputStream to work with
1015 wxPyBeginBlockThreads();
1016 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1017 wxPyEndBlockThreads();
1021 // read until \n or byte limit reached
1022 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1023 ch
= m_wxis
->GetC();
1028 wxPyBeginBlockThreads();
1029 wxStreamError err
= m_wxis
->GetLastError();
1030 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1031 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1034 // We use only strings for the streams, not unicode
1035 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1037 wxPyEndBlockThreads();
1042 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1045 // check if we have a real wxInputStream to work with
1047 wxPyBeginBlockThreads();
1048 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1049 wxPyEndBlockThreads();
1054 wxPyBeginBlockThreads();
1055 pylist
= PyList_New(0);
1057 wxPyBeginBlockThreads();
1059 wxPyEndBlockThreads();
1063 // read sizehint bytes or until EOF
1065 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1066 PyObject
* s
= this->readline();
1068 wxPyBeginBlockThreads();
1070 wxPyEndBlockThreads();
1073 wxPyBeginBlockThreads();
1074 PyList_Append(pylist
, s
);
1075 i
+= PyString_Size(s
);
1076 wxPyEndBlockThreads();
1080 wxStreamError err
= m_wxis
->GetLastError();
1081 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1082 wxPyBeginBlockThreads();
1084 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1085 wxPyEndBlockThreads();
1093 void wxPyInputStream::seek(int offset
, int whence
) {
1095 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1098 int wxPyInputStream::tell(){
1100 return m_wxis
->TellI();
1107 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1108 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1112 wxPyCBInputStream::~wxPyCBInputStream() {
1113 if (m_block
) wxPyBeginBlockThreads();
1117 if (m_block
) wxPyEndBlockThreads();
1121 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1122 if (block
) wxPyBeginBlockThreads();
1124 PyObject
* read
= getMethod(py
, "read");
1125 PyObject
* seek
= getMethod(py
, "seek");
1126 PyObject
* tell
= getMethod(py
, "tell");
1129 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1133 if (block
) wxPyEndBlockThreads();
1137 if (block
) wxPyEndBlockThreads();
1138 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1142 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1143 return wxPyCBInputStream::create(py
, block
);
1146 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1147 if (!PyObject_HasAttrString(py
, name
))
1149 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1150 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1158 size_t wxPyCBInputStream::GetSize() const {
1159 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1160 if (m_seek
&& m_tell
) {
1161 off_t temp
= self
->OnSysTell();
1162 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1163 self
->OnSysSeek(temp
, wxFromStart
);
1171 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1175 wxPyBeginBlockThreads();
1176 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1177 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1181 if ((result
!= NULL
) && PyString_Check(result
)) {
1182 o
= PyString_Size(result
);
1184 m_lasterror
= wxSTREAM_EOF
;
1187 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1192 m_lasterror
= wxSTREAM_READ_ERROR
;
1193 wxPyEndBlockThreads();
1197 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1198 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1202 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1203 wxPyBeginBlockThreads();
1205 // off_t is a 64-bit value...
1206 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1208 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1210 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1213 wxPyEndBlockThreads();
1218 off_t
wxPyCBInputStream::OnSysTell() const {
1219 wxPyBeginBlockThreads();
1220 PyObject
* arglist
= Py_BuildValue("()");
1221 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1224 if (result
!= NULL
) {
1226 if (PyLong_Check(result
))
1227 o
= PyLong_AsLongLong(result
);
1230 o
= PyInt_AsLong(result
);
1234 wxPyEndBlockThreads();
1238 //----------------------------------------------------------------------
1240 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1242 wxPyCallback::wxPyCallback(PyObject
* func
) {
1247 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1248 m_func
= other
.m_func
;
1252 wxPyCallback::~wxPyCallback() {
1253 wxPyBeginBlockThreads();
1255 wxPyEndBlockThreads();
1260 // This function is used for all events destined for Python event handlers.
1261 void wxPyCallback::EventThunker(wxEvent
& event
) {
1262 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1263 PyObject
* func
= cb
->m_func
;
1267 bool checkSkip
= False
;
1269 wxPyBeginBlockThreads();
1270 wxString className
= event
.GetClassInfo()->GetClassName();
1272 // If the event is one of these types then pass the original
1273 // event object instead of the one passed to us.
1274 if ( className
== wxT("wxPyEvent") ) {
1275 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1276 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1278 else if ( className
== wxT("wxPyCommandEvent") ) {
1279 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1280 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1283 arg
= wxPyConstructObject((void*)&event
, className
);
1286 // Call the event handler, passing the event object
1287 tuple
= PyTuple_New(1);
1288 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1289 result
= PyEval_CallObject(func
, tuple
);
1291 Py_DECREF(result
); // result is ignored, but we still need to decref it
1292 PyErr_Clear(); // Just in case...
1298 // if the event object was one of our special types and
1299 // it had been cloned, then we need to extract the Skipped
1300 // value from the original and set it in the clone.
1301 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1303 event
.Skip(PyInt_AsLong(result
));
1311 wxPyEndBlockThreads();
1315 //----------------------------------------------------------------------
1317 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1319 m_self
= other
.m_self
;
1320 m_class
= other
.m_class
;
1328 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1339 #if PYTHON_API_VERSION >= 1011
1341 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1342 // in which the method was defined. Starting with 2.2 it returns
1343 // "class that asked for the method" which seems totally bogus to me
1344 // but apprently it fixes some obscure problem waiting to happen in
1345 // Python. Since the API was not documented Guido and the gang felt
1346 // safe in changing it. Needless to say that totally screwed up the
1347 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1348 // code to find the class where the method is actually defined...
1351 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1355 if (PyType_Check(klass
)) { // new style classes
1356 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1357 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1358 PyObject
*mro
, *res
, *base
, *dict
;
1359 /* Look in tp_dict of types in MRO */
1361 assert(PyTuple_Check(mro
));
1362 n
= PyTuple_GET_SIZE(mro
);
1363 for (i
= 0; i
< n
; i
++) {
1364 base
= PyTuple_GET_ITEM(mro
, i
);
1365 if (PyClass_Check(base
))
1366 dict
= ((PyClassObject
*)base
)->cl_dict
;
1368 assert(PyType_Check(base
));
1369 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1371 assert(dict
&& PyDict_Check(dict
));
1372 res
= PyDict_GetItem(dict
, name
);
1379 else if (PyClass_Check(klass
)) { // old style classes
1380 // This code is borrowed/adapted from class_lookup in classobject.c
1381 PyClassObject
* cp
= (PyClassObject
*)klass
;
1382 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1383 if (value
!= NULL
) {
1384 return (PyObject
*)cp
;
1386 n
= PyTuple_Size(cp
->cl_bases
);
1387 for (i
= 0; i
< n
; i
++) {
1388 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1389 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1401 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1403 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1405 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1407 #else // 2.2 and after, the hard way...
1409 PyObject
* nameo
= PyString_FromString(name
);
1410 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1418 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1419 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1420 self
->m_lastFound
= NULL
;
1422 // If the object (m_self) has an attibute of the given name...
1423 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1424 PyObject
*method
, *klass
;
1425 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1427 // ...and if that attribute is a method, and if that method's class is
1428 // not from a base class...
1429 if (PyMethod_Check(method
) &&
1430 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1431 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1433 // ...then we'll save a pointer to the method so callCallback can call it.
1434 self
->m_lastFound
= method
;
1440 return m_lastFound
!= NULL
;
1444 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1448 result
= callCallbackObj(argTuple
);
1449 if (result
) { // Assumes an integer return type...
1450 retval
= PyInt_AsLong(result
);
1452 PyErr_Clear(); // forget about it if it's not...
1457 // Invoke the Python callable object, returning the raw PyObject return
1458 // value. Caller should DECREF the return value and also manage the GIL.
1459 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1462 // Save a copy of the pointer in case the callback generates another
1463 // callback. In that case m_lastFound will have a different value when
1464 // it gets back here...
1465 PyObject
* method
= m_lastFound
;
1467 result
= PyEval_CallObject(method
, argTuple
);
1468 Py_DECREF(argTuple
);
1477 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1478 cbh
.setSelf(self
, klass
, incref
);
1481 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1482 return cbh
.findCallback(name
);
1485 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1486 return cbh
.callCallback(argTuple
);
1489 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1490 return cbh
.callCallbackObj(argTuple
);
1494 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1495 if (cbh
->m_incRef
) {
1496 wxPyBeginBlockThreads();
1497 Py_XDECREF(cbh
->m_self
);
1498 Py_XDECREF(cbh
->m_class
);
1499 wxPyEndBlockThreads();
1503 //---------------------------------------------------------------------------
1504 //---------------------------------------------------------------------------
1505 // These event classes can be derived from in Python and passed through the event
1506 // system without losing anything. They do this by keeping a reference to
1507 // themselves and some special case handling in wxPyCallback::EventThunker.
1510 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1511 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1512 //Py_INCREF(m_self); // circular loops...
1516 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1517 wxPyBeginBlockThreads();
1520 wxPyEndBlockThreads();
1523 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1524 wxPyBeginBlockThreads();
1532 wxPyEndBlockThreads();
1535 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1541 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1542 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1545 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1546 : wxEvent(winid
, commandType
) {
1550 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1553 SetSelf(evt
.m_self
, True
);
1557 wxPyEvent::~wxPyEvent() {
1561 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1562 : wxCommandEvent(commandType
, id
) {
1566 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1567 : wxCommandEvent(evt
)
1569 SetSelf(evt
.m_self
, True
);
1573 wxPyCommandEvent::~wxPyCommandEvent() {
1580 //---------------------------------------------------------------------------
1581 //---------------------------------------------------------------------------
1582 // Convert a wxList to a Python List, only works for lists of wxObjects
1584 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1585 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1589 wxNode
* node
= list
->GetFirst();
1591 wxPyBeginBlockThreads();
1592 pyList
= PyList_New(0);
1594 wxObj
= node
->GetData();
1595 pyObj
= wxPyMake_wxObject(wxObj
);
1596 PyList_Append(pyList
, pyObj
);
1597 node
= node
->GetNext();
1599 wxPyEndBlockThreads();
1603 //----------------------------------------------------------------------
1605 long wxPyGetWinHandle(wxWindow
* win
) {
1607 return (long)win
->GetHandle();
1610 // Find and return the actual X-Window.
1612 if (win
->m_wxwindow
) {
1614 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1616 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1618 return (long)bwin
->xwindow
;
1626 //----------------------------------------------------------------------
1627 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1628 // included in every file over and over again...
1630 #if PYTHON_API_VERSION >= 1009
1631 static char* wxStringErrorMsg
= "String or Unicode type required";
1633 static char* wxStringErrorMsg
= "String type required";
1637 wxString
* wxString_in_helper(PyObject
* source
) {
1639 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1640 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1641 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1645 if (PyUnicode_Check(source
)) {
1646 target
= new wxString();
1647 size_t len
= PyUnicode_GET_SIZE(source
);
1649 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1650 target
->UngetWriteBuf();
1653 // It is a string, get pointers to it and transform to unicode
1654 char* tmpPtr
; int tmpSize
;
1655 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1656 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1659 char* tmpPtr
; int tmpSize
;
1660 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1661 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1664 target
= new wxString(tmpPtr
, tmpSize
);
1665 #endif // wxUSE_UNICODE
1667 #else // No Python unicode API (1.5.2)
1668 if (!PyString_Check(source
)) {
1669 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1672 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1678 // Similar to above except doesn't use "new" and doesn't set an exception
1679 wxString
Py2wxString(PyObject
* source
)
1682 bool doDecRef
= False
;
1684 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1685 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1686 // Convert to String if not one already... (TODO: Unicode too?)
1687 source
= PyObject_Str(source
);
1692 if (PyUnicode_Check(source
)) {
1693 size_t len
= PyUnicode_GET_SIZE(source
);
1695 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1696 target
.UngetWriteBuf();
1699 // It is a string, get pointers to it and transform to unicode
1700 char* tmpPtr
; int tmpSize
;
1701 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1702 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1705 char* tmpPtr
; int tmpSize
;
1706 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1707 target
= wxString(tmpPtr
, tmpSize
);
1708 #endif // wxUSE_UNICODE
1710 #else // No Python unicode API (1.5.2)
1711 if (!PyString_Check(source
)) {
1712 // Convert to String if not one already...
1713 source
= PyObject_Str(source
);
1716 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1725 // Make either a Python String or Unicode object, depending on build mode
1726 PyObject
* wx2PyString(const wxString
& src
)
1730 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1732 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1738 //----------------------------------------------------------------------
1741 byte
* byte_LIST_helper(PyObject
* source
) {
1742 if (!PyList_Check(source
)) {
1743 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1746 int count
= PyList_Size(source
);
1747 byte
* temp
= new byte
[count
];
1749 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1752 for (int x
=0; x
<count
; x
++) {
1753 PyObject
* o
= PyList_GetItem(source
, x
);
1754 if (! PyInt_Check(o
)) {
1755 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1758 temp
[x
] = (byte
)PyInt_AsLong(o
);
1764 int* int_LIST_helper(PyObject
* source
) {
1765 if (!PyList_Check(source
)) {
1766 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1769 int count
= PyList_Size(source
);
1770 int* temp
= new int[count
];
1772 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1775 for (int x
=0; x
<count
; x
++) {
1776 PyObject
* o
= PyList_GetItem(source
, x
);
1777 if (! PyInt_Check(o
)) {
1778 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1781 temp
[x
] = PyInt_AsLong(o
);
1787 long* long_LIST_helper(PyObject
* source
) {
1788 if (!PyList_Check(source
)) {
1789 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1792 int count
= PyList_Size(source
);
1793 long* temp
= new long[count
];
1795 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1798 for (int x
=0; x
<count
; x
++) {
1799 PyObject
* o
= PyList_GetItem(source
, x
);
1800 if (! PyInt_Check(o
)) {
1801 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1804 temp
[x
] = PyInt_AsLong(o
);
1810 char** string_LIST_helper(PyObject
* source
) {
1811 if (!PyList_Check(source
)) {
1812 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1815 int count
= PyList_Size(source
);
1816 char** temp
= new char*[count
];
1818 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1821 for (int x
=0; x
<count
; x
++) {
1822 PyObject
* o
= PyList_GetItem(source
, x
);
1823 if (! PyString_Check(o
)) {
1824 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1827 temp
[x
] = PyString_AsString(o
);
1832 //--------------------------------
1833 // Part of patch from Tim Hochberg
1834 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1835 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1836 point
->x
= PyInt_AS_LONG(o1
);
1837 point
->y
= PyInt_AS_LONG(o2
);
1840 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1841 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1842 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1845 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1846 // Disallow instances because they can cause havok
1849 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1850 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1851 point
->x
= PyInt_AsLong(o1
);
1852 point
->y
= PyInt_AsLong(o2
);
1859 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1860 // Putting all of the declarations here allows
1861 // us to put the error handling all in one place.
1864 PyObject
*o
, *o1
, *o2
;
1865 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1867 if (!PySequence_Check(source
)) {
1871 // The length of the sequence is returned in count.
1872 *count
= PySequence_Length(source
);
1877 temp
= new wxPoint
[*count
];
1879 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1882 for (x
=0; x
<*count
; x
++) {
1883 // Get an item: try fast way first.
1885 o
= PySequence_Fast_GET_ITEM(source
, x
);
1888 o
= PySequence_GetItem(source
, x
);
1894 // Convert o to wxPoint.
1895 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1896 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1897 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1898 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1899 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1903 else if (wxPySwigInstance_Check(o
)) {
1905 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1910 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1911 o1
= PySequence_GetItem(o
, 0);
1912 o2
= PySequence_GetItem(o
, 1);
1913 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1937 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
1941 //------------------------------
1944 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
1945 if (!PyList_Check(source
)) {
1946 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1949 int count
= PyList_Size(source
);
1950 wxBitmap
** temp
= new wxBitmap
*[count
];
1952 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1955 for (int x
=0; x
<count
; x
++) {
1956 PyObject
* o
= PyList_GetItem(source
, x
);
1957 if (wxPySwigInstance_Check(o
)) {
1959 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
1960 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
1966 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
1975 wxString
* wxString_LIST_helper(PyObject
* source
) {
1976 if (!PyList_Check(source
)) {
1977 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1980 int count
= PyList_Size(source
);
1981 wxString
* temp
= new wxString
[count
];
1983 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1986 for (int x
=0; x
<count
; x
++) {
1987 PyObject
* o
= PyList_GetItem(source
, x
);
1988 #if PYTHON_API_VERSION >= 1009
1989 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
1990 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
1994 if (! PyString_Check(o
)) {
1995 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2000 wxString
* pStr
= wxString_in_helper(o
);
2008 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2009 if (!PyList_Check(source
)) {
2010 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2013 int count
= PyList_Size(source
);
2014 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2016 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2019 for (int x
=0; x
<count
; x
++) {
2020 PyObject
* o
= PyList_GetItem(source
, x
);
2021 if (wxPySwigInstance_Check(o
)) {
2022 wxAcceleratorEntry
* ae
;
2023 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2024 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2029 else if (PyTuple_Check(o
)) {
2030 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2031 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2032 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2033 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2036 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2044 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2045 if (!PyList_Check(source
)) {
2046 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2049 int count
= PyList_Size(source
);
2050 wxPen
** temp
= new wxPen
*[count
];
2052 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2055 for (int x
=0; x
<count
; x
++) {
2056 PyObject
* o
= PyList_GetItem(source
, x
);
2057 if (wxPySwigInstance_Check(o
)) {
2059 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2061 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2068 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2076 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2077 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2080 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2084 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2085 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2088 o1
= PySequence_GetItem(source
, 0);
2089 o2
= PySequence_GetItem(source
, 1);
2092 *i1
= PyInt_AsLong(o1
);
2093 *i2
= PyInt_AsLong(o2
);
2103 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2104 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2105 PyObject
*o1
, *o2
, *o3
, *o4
;
2107 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2111 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2112 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2113 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2114 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2117 o1
= PySequence_GetItem(source
, 0);
2118 o2
= PySequence_GetItem(source
, 1);
2119 o3
= PySequence_GetItem(source
, 2);
2120 o4
= PySequence_GetItem(source
, 3);
2123 *i1
= PyInt_AsLong(o1
);
2124 *i2
= PyInt_AsLong(o2
);
2125 *i3
= PyInt_AsLong(o3
);
2126 *i4
= PyInt_AsLong(o4
);
2138 //----------------------------------------------------------------------
2140 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2144 if (wxPySwigInstance_Check(source
) &&
2145 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2149 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2155 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2157 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2161 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2163 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2168 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2170 // If source is an object instance then it may already be the right type
2171 if (wxPySwigInstance_Check(source
)) {
2173 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2178 // otherwise a 2-tuple of floats is expected
2179 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2180 PyObject
* o1
= PySequence_GetItem(source
, 0);
2181 PyObject
* o2
= PySequence_GetItem(source
, 1);
2182 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2187 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2194 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2200 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2202 // If source is an object instance then it may already be the right type
2203 if (wxPySwigInstance_Check(source
)) {
2205 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2210 // otherwise a 4-tuple of integers is expected
2211 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2212 PyObject
* o1
= PySequence_GetItem(source
, 0);
2213 PyObject
* o2
= PySequence_GetItem(source
, 1);
2214 PyObject
* o3
= PySequence_GetItem(source
, 2);
2215 PyObject
* o4
= PySequence_GetItem(source
, 3);
2216 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2217 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2224 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2225 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2234 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2240 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2242 // If source is an object instance then it may already be the right type
2243 if (wxPySwigInstance_Check(source
)) {
2245 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2250 // otherwise check for a string
2251 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2252 wxString spec
= Py2wxString(source
);
2253 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2254 long red
, green
, blue
;
2255 red
= green
= blue
= 0;
2256 spec
.Mid(1,2).ToLong(&red
, 16);
2257 spec
.Mid(3,2).ToLong(&green
, 16);
2258 spec
.Mid(5,2).ToLong(&blue
, 16);
2260 **obj
= wxColour(red
, green
, blue
);
2263 else { // it's a colour name
2264 **obj
= wxColour(spec
);
2268 // last chance: 3-tuple of integers is expected
2269 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2270 PyObject
* o1
= PySequence_GetItem(source
, 0);
2271 PyObject
* o2
= PySequence_GetItem(source
, 1);
2272 PyObject
* o3
= PySequence_GetItem(source
, 2);
2273 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2279 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2287 PyErr_SetString(PyExc_TypeError
,
2288 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2293 bool wxColour_typecheck(PyObject
* source
) {
2295 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2298 if (PyString_Check(source
) || PyUnicode_Check(source
))
2306 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2307 // If source is an object instance then it may already be the right type
2308 if (wxPySwigInstance_Check(source
)) {
2310 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2315 // otherwise a length-2 sequence of floats is expected
2316 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2317 PyObject
* o1
= PySequence_GetItem(source
, 0);
2318 PyObject
* o2
= PySequence_GetItem(source
, 1);
2319 // This should really check for floats, not numbers -- but that would break code.
2320 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2325 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2331 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2336 //----------------------------------------------------------------------
2338 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2340 PyObject
* list
= PyList_New(0);
2341 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2343 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2345 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2347 PyList_Append(list
, str
);
2354 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2356 PyObject
* list
= PyList_New(0);
2357 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2358 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2359 PyList_Append(list
, number
);
2366 //----------------------------------------------------------------------
2367 //----------------------------------------------------------------------