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
;
54 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
55 : tid(_tid
), tstate(_tstate
), blocked(1) {}
58 #include <wx/dynarray.h>
59 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
60 #include <wx/arrimpl.cpp>
61 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
63 wxPyThreadStateArray
* wxPyTStates
= NULL
;
64 wxMutex
* wxPyTMutex
= NULL
;
68 static PyObject
* wxPython_dict
= NULL
;
69 static PyObject
* wxPyAssertionError
= NULL
;
71 PyObject
* wxPyPtrTypeMap
= NULL
;
74 #ifdef __WXMSW__ // If building for win32...
75 //----------------------------------------------------------------------
76 // This gets run when the DLL is loaded. We just need to save a handle.
77 //----------------------------------------------------------------------
80 HINSTANCE hinstDLL
, // handle to DLL module
81 DWORD fdwReason
, // reason for calling function
82 LPVOID lpvReserved
// reserved
85 // If wxPython is embedded in another wxWindows app then
86 // the inatance has already been set.
87 if (! wxGetInstance())
88 wxSetInstance(hinstDLL
);
93 //----------------------------------------------------------------------
94 // Classes for implementing the wxp main application shell.
95 //----------------------------------------------------------------------
97 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
101 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
102 m_startupComplete
= False
;
106 wxPyApp::~wxPyApp() {
110 // This one isn't acutally called... We fake it with _BootstrapApp
111 bool wxPyApp::OnInit() {
116 int wxPyApp::MainLoop() {
119 DeletePendingObjects();
120 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
122 if ( m_exitOnFrameDelete
== Later
) {
123 m_exitOnFrameDelete
= Yes
;
126 retval
= wxApp::MainLoop();
133 bool wxPyApp::OnInitGui() {
135 wxApp::OnInitGui(); // in this case always call the base class version
136 wxPyBeginBlockThreads();
137 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
138 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
139 wxPyEndBlockThreads();
144 int wxPyApp::OnExit() {
146 wxPyBeginBlockThreads();
147 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
148 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
149 wxPyEndBlockThreads();
150 wxApp::OnExit(); // in this case always call the base class version
156 void wxPyApp::OnAssert(const wxChar
*file
,
161 // if we're not fully initialized then just log the error
162 if (! m_startupComplete
) {
165 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
175 // If the OnAssert is overloaded in the Python class then call it...
177 wxPyBeginBlockThreads();
178 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
179 PyObject
* fso
= wx2PyString(file
);
180 PyObject
* cso
= wx2PyString(file
);
183 mso
= wx2PyString(file
);
185 mso
= Py_None
; Py_INCREF(Py_None
);
187 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
192 wxPyEndBlockThreads();
194 // ...otherwise do our own thing with it
197 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
200 // turn it into a Python exception?
201 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
204 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
211 wxPyBeginBlockThreads();
212 PyObject
* s
= wx2PyString(buf
);
213 PyErr_SetObject(wxPyAssertionError
, s
);
215 wxPyEndBlockThreads();
217 // Now when control returns to whatever API wrapper was called from
218 // Python it should detect that an exception is set and will return
219 // NULL, signalling the exception to Python.
222 // Send it to the normal log destination, but only if
223 // not _DIALOG because it will call this too
224 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
227 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
236 // do the normal wx assert dialog?
237 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
238 wxApp::OnAssert(file
, line
, cond
, msg
);
246 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
248 return s_macSupportPCMenuShortcuts
;
255 long wxPyApp::GetMacAboutMenuItemId() {
257 return s_macAboutMenuItemId
;
264 long wxPyApp::GetMacPreferencesMenuItemId() {
266 return s_macPreferencesMenuItemId
;
273 long wxPyApp::GetMacExitMenuItemId() {
275 return s_macExitMenuItemId
;
282 wxString
wxPyApp::GetMacHelpMenuTitleName() {
284 return s_macHelpMenuTitleName
;
286 return wxEmptyString
;
291 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
293 s_macSupportPCMenuShortcuts
= val
;
298 void wxPyApp::SetMacAboutMenuItemId(long val
) {
300 s_macAboutMenuItemId
= val
;
305 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
307 s_macPreferencesMenuItemId
= val
;
312 void wxPyApp::SetMacExitMenuItemId(long val
) {
314 s_macExitMenuItemId
= val
;
319 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
321 s_macHelpMenuTitleName
= val
;
326 // This finishes the initialization of wxWindows and then calls the OnInit
327 // that should be present in the derived (Python) class.
328 void wxPyApp::_BootstrapApp()
331 PyObject
* retval
= NULL
;
332 PyObject
* pyint
= NULL
;
335 // Get any command-line args passed to this program from the sys module
338 wxPyBeginBlockThreads();
339 PyObject
* sysargv
= PySys_GetObject("argv");
340 if (sysargv
!= NULL
) {
341 argc
= PyList_Size(sysargv
);
342 argv
= new char*[argc
+1];
344 for(x
=0; x
<argc
; x
++) {
345 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
346 argv
[x
] = PyString_AsString(pyArg
);
350 wxPyEndBlockThreads();
352 result
= wxEntryStart(argc
, argv
);
355 wxPyBeginBlockThreads();
357 PyErr_SetString(PyExc_SystemError
, "wxEntryStart failed!");
361 // The stock objects were all NULL when they were loaded into
362 // SWIG generated proxies, so re-init those now...
363 wxPy_ReinitStockObjects(3);
365 // It's now ok to generate exceptions for assertion errors.
366 wxPythonApp
->SetStartupComplete(True
);
368 // Call the Python wxApp's OnInit function
369 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
371 PyObject
* method
= m_myInst
.GetLastFound();
372 PyObject
* argTuple
= PyTuple_New(0);
373 retval
= PyEval_CallObject(method
, argTuple
);
379 pyint
= PyNumber_Int(retval
);
381 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
384 result
= PyInt_AS_LONG(pyint
);
387 // Is it okay if there is no OnInit? Probably so...
393 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
400 wxPyEndBlockThreads();
403 //---------------------------------------------------------------------
404 //----------------------------------------------------------------------
408 static char* wxPyCopyCString(const wxChar
* src
)
410 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
411 size_t len
= strlen(buff
);
412 char* dest
= new char[len
+1];
418 static char* wxPyCopyCString(const char* src
) // we need a char version too
420 size_t len
= strlen(src
);
421 char* dest
= new char[len
+1];
427 static wxChar
* wxPyCopyWString(const char *src
)
429 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
430 wxString
str(src
, *wxConvCurrent
);
431 return copystring(str
);
435 static wxChar
* wxPyCopyWString(const wxChar
*src
)
437 return copystring(src
);
443 inline const char* dropwx(const char* name
) {
444 if (name
[0] == 'w' && name
[1] == 'x')
450 //----------------------------------------------------------------------
452 // This function is called when the wxc module is imported to do some initial
453 // setup. (Before there is a wxApp object.) The rest happens in
454 // wxPyApp::_BootstrapApp
455 void __wxPyPreStart(PyObject
* moduleDict
)
459 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
462 #ifdef WXP_WITH_THREAD
463 PyEval_InitThreads();
464 wxPyTStates
= new wxPyThreadStateArray
;
465 wxPyTMutex
= new wxMutex
;
467 // Save the current (main) thread state in our array
468 PyThreadState
* tstate
= wxPyBeginAllowThreads();
469 wxPyEndAllowThreads(tstate
);
472 // Ensure that the build options in the DLL (or whatever) match this build
473 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
475 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
476 wxPy_ReinitStockObjects(1);
481 void __wxPyCleanup() {
482 wxPyDoingCleanup
= True
;
484 wxPyDoCleanup
= False
;
487 #ifdef WXP_WITH_THREAD
490 wxPyTStates
->Empty();
497 // Save a reference to the dictionary of the wx.core module, and inject
498 // a few more things into it.
499 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
502 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
505 if (!PyDict_Check(wxPython_dict
)) {
506 PyErr_SetString(PyExc_TypeError
, "_wxPySetDictionary must have dictionary object!");
510 if (! wxPyPtrTypeMap
)
511 wxPyPtrTypeMap
= PyDict_New();
512 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
514 // Create an exception object to use for wxASSERTions
515 wxPyAssertionError
= PyErr_NewException("wx.core.PyAssertionError",
516 PyExc_AssertionError
, NULL
);
517 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
521 #define wxPlatform "__WXMOTIF__"
524 #define wxPlatform "__WXX11__"
527 #define wxPlatform "__WXGTK__"
529 #if defined(__WIN32__) || defined(__WXMSW__)
530 #define wxPlatform "__WXMSW__"
533 #define wxPlatform "__WXMAC__"
542 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
543 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
544 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
550 //---------------------------------------------------------------------------
552 // Python's PyInstance_Check does not return True for instances of new-style
553 // classes. This should get close enough for both new and old classes but I
554 // should re-evaluate the need for doing instance checks...
555 bool wxPyInstance_Check(PyObject
* obj
) {
556 return PyObject_HasAttrString(obj
, "__class__") != 0;
560 // This one checks if the object is an instance of a SWIG proxy class (it has
561 // a .this attribute)
562 bool wxPySwigInstance_Check(PyObject
* obj
) {
563 return PyObject_HasAttrString(obj
, "this") != 0;
566 //---------------------------------------------------------------------------
568 // The stock objects are no longer created when the wxc module is imported,
569 // but only after the app object has been created. The
570 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
571 // objects though various stages of evolution:
573 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
574 // object will be created (otherwise it will just use None.)
576 // pass 2: After the module has been imported and the python proxys have
577 // been created, then set the __class__ to be _wxPyUnbornObject so
578 // it will catch any access to the object and will raise an exception.
580 // pass 3: Finally, from OnInit patch things up so the stock objects can
584 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
586 wxPy_ReinitStockObjects(2);
591 static void rsoPass2(const char* name
)
593 static PyObject
* unbornObjectClass
= NULL
;
596 if (unbornObjectClass
== NULL
) {
597 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
598 Py_INCREF(unbornObjectClass
);
601 // Find the object instance
602 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
603 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
604 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
607 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
611 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
617 // Find the object instance
618 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
619 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
620 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
622 // Find the class object and put it back in the instance
623 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
624 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
625 PyObject_SetAttrString(obj
, "__class__", classobj
);
627 // Rebuild the .this swigified pointer with the new value of the C++ pointer
628 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
629 PyObject_SetAttrString(obj
, "this", ptrobj
);
635 void wxPy_ReinitStockObjects(int pass
)
638 #define REINITOBJ(name, classname) \
639 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
640 else if (pass == 2) { rsoPass2(#name); } \
641 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
644 #define REINITOBJ2(name, classname) \
646 else if (pass == 2) { rsoPass2(#name); } \
647 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
650 REINITOBJ(wxNORMAL_FONT
, wxFont
);
651 REINITOBJ(wxSMALL_FONT
, wxFont
);
652 REINITOBJ(wxITALIC_FONT
, wxFont
);
653 REINITOBJ(wxSWISS_FONT
, wxFont
);
655 REINITOBJ(wxRED_PEN
, wxPen
);
656 REINITOBJ(wxCYAN_PEN
, wxPen
);
657 REINITOBJ(wxGREEN_PEN
, wxPen
);
658 REINITOBJ(wxBLACK_PEN
, wxPen
);
659 REINITOBJ(wxWHITE_PEN
, wxPen
);
660 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
661 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
662 REINITOBJ(wxGREY_PEN
, wxPen
);
663 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
664 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
666 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
667 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
668 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
669 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
670 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
671 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
672 REINITOBJ(wxRED_BRUSH
, wxBrush
);
673 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
674 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
675 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
677 REINITOBJ(wxBLACK
, wxColour
);
678 REINITOBJ(wxWHITE
, wxColour
);
679 REINITOBJ(wxRED
, wxColour
);
680 REINITOBJ(wxBLUE
, wxColour
);
681 REINITOBJ(wxGREEN
, wxColour
);
682 REINITOBJ(wxCYAN
, wxColour
);
683 REINITOBJ(wxLIGHT_GREY
, wxColour
);
685 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
686 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
687 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
689 REINITOBJ2(wxNullBitmap
, wxBitmap
);
690 REINITOBJ2(wxNullIcon
, wxIcon
);
691 REINITOBJ2(wxNullCursor
, wxCursor
);
692 REINITOBJ2(wxNullPen
, wxPen
);
693 REINITOBJ2(wxNullBrush
, wxBrush
);
694 REINITOBJ2(wxNullPalette
, wxPalette
);
695 REINITOBJ2(wxNullFont
, wxFont
);
696 REINITOBJ2(wxNullColour
, wxColour
);
698 REINITOBJ(wxTheFontList
, wxFontList
);
699 REINITOBJ(wxThePenList
, wxPenList
);
700 REINITOBJ(wxTheBrushList
, wxBrushList
);
701 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
704 REINITOBJ(wxTheClipboard
, wxClipboard
);
705 REINITOBJ2(wxDefaultValidator
, wxValidator
);
706 REINITOBJ2(wxNullImage
, wxImage
);
707 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
713 //---------------------------------------------------------------------------
715 void wxPyClientData_dtor(wxPyClientData
* self
) {
716 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
717 // may have already garbage collected the object...
718 wxPyBeginBlockThreads();
719 Py_DECREF(self
->m_obj
);
721 wxPyEndBlockThreads();
725 void wxPyUserData_dtor(wxPyUserData
* self
) {
726 if (! wxPyDoingCleanup
) {
727 wxPyBeginBlockThreads();
728 Py_DECREF(self
->m_obj
);
730 wxPyEndBlockThreads();
735 // This is called when an OOR controled object is being destroyed. Although
736 // the C++ object is going away there is no way to force the Python object
737 // (and all references to it) to die too. This causes problems (crashes) in
738 // wxPython when a python shadow object attempts to call a C++ method using
739 // the now bogus pointer... So to try and prevent this we'll do a little black
740 // magic and change the class of the python instance to a class that will
741 // raise an exception for any attempt to call methods with it. See
742 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
743 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
745 static PyObject
* deadObjectClass
= NULL
;
747 wxPyBeginBlockThreads();
748 if (deadObjectClass
== NULL
) {
749 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
750 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
751 // will lead to a deadlock when it tries to aquire the GIL again.
752 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
753 Py_INCREF(deadObjectClass
);
757 // Only if there is more than one reference to the object
758 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
759 // bool isInstance = wxPyInstance_Check(self->m_obj);
761 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
763 // Call __del__, if there is one.
764 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
766 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
770 if (PyErr_Occurred())
771 PyErr_Clear(); // just ignore it for now
774 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
776 // Clear the instance's dictionary
779 // put the name of the old class into the instance, and then reset the
780 // class to be the dead class.
781 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
782 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
783 PyDict_SetItemString(dict
, "_name", name
);
784 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
785 //Py_INCREF(deadObjectClass);
791 // m_obj is DECREF'd in the base class dtor...
792 wxPyEndBlockThreads();
796 //---------------------------------------------------------------------------
797 // Stuff used by OOR to find the right wxPython class type to return and to
801 // The pointer type map is used when the "pointer" type name generated by SWIG
802 // is not the same as the shadow class name, for example wxPyTreeCtrl
803 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
804 // so we'll just make it a Python dictionary in the wx module's namespace.
805 // (See __wxSetDictionary)
806 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
807 if (! wxPyPtrTypeMap
)
808 wxPyPtrTypeMap
= PyDict_New();
809 PyDict_SetItemString(wxPyPtrTypeMap
,
811 PyString_FromString((char*)ptrName
));
817 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
818 PyObject
* target
= NULL
;
819 bool isEvtHandler
= False
;
822 // If it's derived from wxEvtHandler then there may
823 // already be a pointer to a Python object that we can use
825 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
827 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
828 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
830 target
= data
->m_obj
;
837 // Otherwise make it the old fashioned way by making a new shadow
838 // object and putting this pointer in it. Look up the class
839 // heirarchy until we find a class name that is located in the
841 const wxClassInfo
* info
= source
->GetClassInfo();
842 wxString name
= info
->GetClassName();
843 bool exists
= wxPyCheckSwigType(name
);
844 while (info
&& !exists
) {
845 info
= info
->GetBaseClass1();
846 name
= info
->GetClassName();
847 exists
= wxPyCheckSwigType(name
);
850 target
= wxPyConstructObject((void*)source
, name
, False
);
851 if (target
&& isEvtHandler
)
852 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
854 wxString
msg(wxT("wxPython class not found for "));
855 msg
+= source
->GetClassInfo()->GetClassName();
856 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
860 } else { // source was NULL so return None.
861 Py_INCREF(Py_None
); target
= Py_None
;
867 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
868 PyObject
* target
= NULL
;
870 if (source
&& wxIsKindOf(source
, wxSizer
)) {
871 // If it's derived from wxSizer then there may already be a pointer to
872 // a Python object that we can use in the OOR data.
873 wxSizer
* sz
= (wxSizer
*)source
;
874 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
876 target
= data
->m_obj
;
882 target
= wxPyMake_wxObject(source
, False
);
883 if (target
!= Py_None
)
884 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
890 //---------------------------------------------------------------------------
893 #ifdef WXP_WITH_THREAD
895 unsigned long wxPyGetCurrentThreadId() {
896 return wxThread::GetCurrentId();
899 static wxPyThreadState gs_shutdownTState
;
902 wxPyThreadState
* wxPyGetThreadState() {
903 if (wxPyTMutex
== NULL
) // Python is shutting down...
904 return &gs_shutdownTState
;
906 unsigned long ctid
= wxPyGetCurrentThreadId();
907 wxPyThreadState
* tstate
= NULL
;
910 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
911 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
912 if (info
.tid
== ctid
) {
917 wxPyTMutex
->Unlock();
918 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
924 void wxPySaveThreadState(PyThreadState
* tstate
) {
925 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
926 gs_shutdownTState
.tstate
= tstate
;
929 unsigned long ctid
= wxPyGetCurrentThreadId();
931 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
932 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
933 if (info
.tid
== ctid
) {
935 if (info
.tstate
!= tstate
)
936 wxLogMessage("*** tstate mismatch!???");
938 // info.tstate = tstate; *** DO NOT update existing ones???
939 // Normally it will never change, but apparently COM callbacks
940 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
941 // tstate which will then be garbage the next time we try to use
943 wxPyTMutex
->Unlock();
947 // not found, so add it...
948 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
949 wxPyTMutex
->Unlock();
956 // Calls from Python to wxWindows code are wrapped in calls to these
959 PyThreadState
* wxPyBeginAllowThreads() {
960 #ifdef WXP_WITH_THREAD
961 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
962 wxPySaveThreadState(saved
);
963 wxPyGetThreadState()->blocked
-= 1;
970 void wxPyEndAllowThreads(PyThreadState
* saved
) {
971 #ifdef WXP_WITH_THREAD
972 wxPyGetThreadState()->blocked
+= 1;
973 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
979 // Calls from wxWindows back to Python code, or even any PyObject
980 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
982 void wxPyBeginBlockThreads() {
983 #ifdef WXP_WITH_THREAD
984 wxPyThreadState
* tstate
= wxPyGetThreadState();
985 if (tstate
->blocked
++ == 0) { // if nested calls then do nothing
986 PyEval_RestoreThread(tstate
->tstate
);
992 void wxPyEndBlockThreads() {
993 #ifdef WXP_WITH_THREAD
994 wxPyThreadState
* tstate
= wxPyGetThreadState();
995 tstate
->blocked
-= 1;
996 if ( tstate
->blocked
== 0) { // if nested calls then do nothing
1003 //---------------------------------------------------------------------------
1004 // wxPyInputStream and wxPyCBInputStream methods
1007 void wxPyInputStream::close() {
1008 /* do nothing for now */
1011 void wxPyInputStream::flush() {
1012 /* do nothing for now */
1015 bool wxPyInputStream::eof() {
1017 return m_wxis
->Eof();
1022 wxPyInputStream::~wxPyInputStream() {
1029 PyObject
* wxPyInputStream::read(int size
) {
1030 PyObject
* obj
= NULL
;
1032 const int BUFSIZE
= 1024;
1034 // check if we have a real wxInputStream to work with
1036 wxPyBeginBlockThreads();
1037 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1038 wxPyEndBlockThreads();
1043 // read while bytes are available on the stream
1044 while ( m_wxis
->CanRead() ) {
1045 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1046 buf
.UngetAppendBuf(m_wxis
->LastRead());
1049 } else { // Read only size number of characters
1050 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1051 buf
.UngetWriteBuf(m_wxis
->LastRead());
1055 wxPyBeginBlockThreads();
1056 wxStreamError err
= m_wxis
->GetLastError();
1057 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1058 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1061 // We use only strings for the streams, not unicode
1062 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1064 wxPyEndBlockThreads();
1069 PyObject
* wxPyInputStream::readline(int size
) {
1070 PyObject
* obj
= NULL
;
1075 // check if we have a real wxInputStream to work with
1077 wxPyBeginBlockThreads();
1078 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1079 wxPyEndBlockThreads();
1083 // read until \n or byte limit reached
1084 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1085 ch
= m_wxis
->GetC();
1090 wxPyBeginBlockThreads();
1091 wxStreamError err
= m_wxis
->GetLastError();
1092 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1093 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1096 // We use only strings for the streams, not unicode
1097 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1099 wxPyEndBlockThreads();
1104 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1107 // check if we have a real wxInputStream to work with
1109 wxPyBeginBlockThreads();
1110 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1111 wxPyEndBlockThreads();
1116 wxPyBeginBlockThreads();
1117 pylist
= PyList_New(0);
1119 wxPyBeginBlockThreads();
1121 wxPyEndBlockThreads();
1125 // read sizehint bytes or until EOF
1127 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1128 PyObject
* s
= this->readline();
1130 wxPyBeginBlockThreads();
1132 wxPyEndBlockThreads();
1135 wxPyBeginBlockThreads();
1136 PyList_Append(pylist
, s
);
1137 i
+= PyString_Size(s
);
1138 wxPyEndBlockThreads();
1142 wxStreamError err
= m_wxis
->GetLastError();
1143 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1144 wxPyBeginBlockThreads();
1146 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1147 wxPyEndBlockThreads();
1155 void wxPyInputStream::seek(int offset
, int whence
) {
1157 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1160 int wxPyInputStream::tell(){
1162 return m_wxis
->TellI();
1169 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1170 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1174 wxPyCBInputStream::~wxPyCBInputStream() {
1175 if (m_block
) wxPyBeginBlockThreads();
1179 if (m_block
) wxPyEndBlockThreads();
1183 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1184 if (block
) wxPyBeginBlockThreads();
1186 PyObject
* read
= getMethod(py
, "read");
1187 PyObject
* seek
= getMethod(py
, "seek");
1188 PyObject
* tell
= getMethod(py
, "tell");
1191 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1195 if (block
) wxPyEndBlockThreads();
1199 if (block
) wxPyEndBlockThreads();
1200 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1204 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1205 return wxPyCBInputStream::create(py
, block
);
1208 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1209 if (!PyObject_HasAttrString(py
, name
))
1211 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1212 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1220 size_t wxPyCBInputStream::GetSize() const {
1221 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1222 if (m_seek
&& m_tell
) {
1223 off_t temp
= self
->OnSysTell();
1224 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1225 self
->OnSysSeek(temp
, wxFromStart
);
1233 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1237 wxPyBeginBlockThreads();
1238 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1239 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1243 if ((result
!= NULL
) && PyString_Check(result
)) {
1244 o
= PyString_Size(result
);
1246 m_lasterror
= wxSTREAM_EOF
;
1249 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1254 m_lasterror
= wxSTREAM_READ_ERROR
;
1255 wxPyEndBlockThreads();
1259 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1260 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1264 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1265 wxPyBeginBlockThreads();
1267 // off_t is a 64-bit value...
1268 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1270 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1272 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1275 wxPyEndBlockThreads();
1280 off_t
wxPyCBInputStream::OnSysTell() const {
1281 wxPyBeginBlockThreads();
1282 PyObject
* arglist
= Py_BuildValue("()");
1283 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1286 if (result
!= NULL
) {
1288 if (PyLong_Check(result
))
1289 o
= PyLong_AsLongLong(result
);
1292 o
= PyInt_AsLong(result
);
1295 wxPyEndBlockThreads();
1299 //----------------------------------------------------------------------
1301 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1303 wxPyCallback::wxPyCallback(PyObject
* func
) {
1308 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1309 m_func
= other
.m_func
;
1313 wxPyCallback::~wxPyCallback() {
1314 wxPyBeginBlockThreads();
1316 wxPyEndBlockThreads();
1321 // This function is used for all events destined for Python event handlers.
1322 void wxPyCallback::EventThunker(wxEvent
& event
) {
1323 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1324 PyObject
* func
= cb
->m_func
;
1328 bool checkSkip
= False
;
1330 wxPyBeginBlockThreads();
1331 wxString className
= event
.GetClassInfo()->GetClassName();
1333 // If the event is one of these types then pass the original
1334 // event object instead of the one passed to us.
1335 if ( className
== wxT("wxPyEvent") ) {
1336 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1337 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1339 else if ( className
== wxT("wxPyCommandEvent") ) {
1340 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1341 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1344 arg
= wxPyConstructObject((void*)&event
, className
);
1350 // Call the event handler, passing the event object
1351 tuple
= PyTuple_New(1);
1352 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1353 result
= PyEval_CallObject(func
, tuple
);
1355 Py_DECREF(result
); // result is ignored, but we still need to decref it
1356 PyErr_Clear(); // Just in case...
1362 // if the event object was one of our special types and
1363 // it had been cloned, then we need to extract the Skipped
1364 // value from the original and set it in the clone.
1365 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1367 event
.Skip(PyInt_AsLong(result
));
1375 wxPyEndBlockThreads();
1379 //----------------------------------------------------------------------
1381 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1383 m_self
= other
.m_self
;
1384 m_class
= other
.m_class
;
1392 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1403 #if PYTHON_API_VERSION >= 1011
1405 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1406 // in which the method was defined. Starting with 2.2 it returns
1407 // "class that asked for the method" which seems totally bogus to me
1408 // but apprently it fixes some obscure problem waiting to happen in
1409 // Python. Since the API was not documented Guido and the gang felt
1410 // safe in changing it. Needless to say that totally screwed up the
1411 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1412 // code to find the class where the method is actually defined...
1415 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1419 if (PyType_Check(klass
)) { // new style classes
1420 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1421 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1422 PyObject
*mro
, *res
, *base
, *dict
;
1423 /* Look in tp_dict of types in MRO */
1425 assert(PyTuple_Check(mro
));
1426 n
= PyTuple_GET_SIZE(mro
);
1427 for (i
= 0; i
< n
; i
++) {
1428 base
= PyTuple_GET_ITEM(mro
, i
);
1429 if (PyClass_Check(base
))
1430 dict
= ((PyClassObject
*)base
)->cl_dict
;
1432 assert(PyType_Check(base
));
1433 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1435 assert(dict
&& PyDict_Check(dict
));
1436 res
= PyDict_GetItem(dict
, name
);
1443 else if (PyClass_Check(klass
)) { // old style classes
1444 // This code is borrowed/adapted from class_lookup in classobject.c
1445 PyClassObject
* cp
= (PyClassObject
*)klass
;
1446 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1447 if (value
!= NULL
) {
1448 return (PyObject
*)cp
;
1450 n
= PyTuple_Size(cp
->cl_bases
);
1451 for (i
= 0; i
< n
; i
++) {
1452 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1453 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1465 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1467 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1469 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1471 #else // 2.2 and after, the hard way...
1473 PyObject
* nameo
= PyString_FromString(name
);
1474 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1482 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1483 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1484 self
->m_lastFound
= NULL
;
1486 // If the object (m_self) has an attibute of the given name...
1487 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1488 PyObject
*method
, *klass
;
1489 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1491 // ...and if that attribute is a method, and if that method's class is
1492 // not from a base class...
1493 if (PyMethod_Check(method
) &&
1494 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1495 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1497 // ...then we'll save a pointer to the method so callCallback can call it.
1498 self
->m_lastFound
= method
;
1504 return m_lastFound
!= NULL
;
1508 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1512 result
= callCallbackObj(argTuple
);
1513 if (result
) { // Assumes an integer return type...
1514 retval
= PyInt_AsLong(result
);
1516 PyErr_Clear(); // forget about it if it's not...
1521 // Invoke the Python callable object, returning the raw PyObject return
1522 // value. Caller should DECREF the return value and also manage the GIL.
1523 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1526 // Save a copy of the pointer in case the callback generates another
1527 // callback. In that case m_lastFound will have a different value when
1528 // it gets back here...
1529 PyObject
* method
= m_lastFound
;
1531 result
= PyEval_CallObject(method
, argTuple
);
1532 Py_DECREF(argTuple
);
1541 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1542 cbh
.setSelf(self
, klass
, incref
);
1545 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1546 return cbh
.findCallback(name
);
1549 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1550 return cbh
.callCallback(argTuple
);
1553 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1554 return cbh
.callCallbackObj(argTuple
);
1558 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1559 if (cbh
->m_incRef
) {
1560 wxPyBeginBlockThreads();
1561 Py_XDECREF(cbh
->m_self
);
1562 Py_XDECREF(cbh
->m_class
);
1563 wxPyEndBlockThreads();
1567 //---------------------------------------------------------------------------
1568 //---------------------------------------------------------------------------
1569 // These event classes can be derived from in Python and passed through the event
1570 // system without losing anything. They do this by keeping a reference to
1571 // themselves and some special case handling in wxPyCallback::EventThunker.
1574 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1575 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1576 //Py_INCREF(m_self); // circular loops...
1580 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1581 wxPyBeginBlockThreads();
1584 wxPyEndBlockThreads();
1587 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1588 wxPyBeginBlockThreads();
1596 wxPyEndBlockThreads();
1599 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1605 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1606 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1609 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1610 : wxEvent(winid
, commandType
) {
1614 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1617 SetSelf(evt
.m_self
, True
);
1621 wxPyEvent::~wxPyEvent() {
1625 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1626 : wxCommandEvent(commandType
, id
) {
1630 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1631 : wxCommandEvent(evt
)
1633 SetSelf(evt
.m_self
, True
);
1637 wxPyCommandEvent::~wxPyCommandEvent() {
1644 //---------------------------------------------------------------------------
1645 //---------------------------------------------------------------------------
1646 // Convert a wxList to a Python List, only works for lists of wxObjects
1648 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1649 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1653 wxNode
* node
= list
->GetFirst();
1655 wxPyBeginBlockThreads();
1656 pyList
= PyList_New(0);
1658 wxObj
= node
->GetData();
1659 pyObj
= wxPyMake_wxObject(wxObj
);
1660 PyList_Append(pyList
, pyObj
);
1661 node
= node
->GetNext();
1663 wxPyEndBlockThreads();
1667 //----------------------------------------------------------------------
1669 long wxPyGetWinHandle(wxWindow
* win
) {
1671 return (long)win
->GetHandle();
1674 // Find and return the actual X-Window.
1676 if (win
->m_wxwindow
) {
1678 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1680 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1682 return (long)bwin
->xwindow
;
1690 //----------------------------------------------------------------------
1691 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1692 // included in every file over and over again...
1694 #if PYTHON_API_VERSION >= 1009
1695 static char* wxStringErrorMsg
= "String or Unicode type required";
1697 static char* wxStringErrorMsg
= "String type required";
1701 wxString
* wxString_in_helper(PyObject
* source
) {
1703 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1704 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1705 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1709 if (PyUnicode_Check(source
)) {
1710 target
= new wxString();
1711 size_t len
= PyUnicode_GET_SIZE(source
);
1713 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1714 target
->UngetWriteBuf();
1717 // It is a string, get pointers to it and transform to unicode
1718 char* tmpPtr
; int tmpSize
;
1719 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1720 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1723 char* tmpPtr
; int tmpSize
;
1724 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1725 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1728 target
= new wxString(tmpPtr
, tmpSize
);
1729 #endif // wxUSE_UNICODE
1731 #else // No Python unicode API (1.5.2)
1732 if (!PyString_Check(source
)) {
1733 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1736 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1742 // Similar to above except doesn't use "new" and doesn't set an exception
1743 wxString
Py2wxString(PyObject
* source
)
1746 bool doDecRef
= False
;
1748 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1749 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1750 // Convert to String if not one already... (TODO: Unicode too?)
1751 source
= PyObject_Str(source
);
1756 if (PyUnicode_Check(source
)) {
1757 size_t len
= PyUnicode_GET_SIZE(source
);
1759 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1760 target
.UngetWriteBuf();
1763 // It is a string, get pointers to it and transform to unicode
1764 char* tmpPtr
; int tmpSize
;
1765 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1766 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1769 char* tmpPtr
; int tmpSize
;
1770 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1771 target
= wxString(tmpPtr
, tmpSize
);
1772 #endif // wxUSE_UNICODE
1774 #else // No Python unicode API (1.5.2)
1775 if (!PyString_Check(source
)) {
1776 // Convert to String if not one already...
1777 source
= PyObject_Str(source
);
1780 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1789 // Make either a Python String or Unicode object, depending on build mode
1790 PyObject
* wx2PyString(const wxString
& src
)
1794 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1796 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1802 //----------------------------------------------------------------------
1805 byte
* byte_LIST_helper(PyObject
* source
) {
1806 if (!PyList_Check(source
)) {
1807 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1810 int count
= PyList_Size(source
);
1811 byte
* temp
= new byte
[count
];
1813 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1816 for (int x
=0; x
<count
; x
++) {
1817 PyObject
* o
= PyList_GetItem(source
, x
);
1818 if (! PyInt_Check(o
)) {
1819 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1822 temp
[x
] = (byte
)PyInt_AsLong(o
);
1828 int* int_LIST_helper(PyObject
* source
) {
1829 if (!PyList_Check(source
)) {
1830 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1833 int count
= PyList_Size(source
);
1834 int* temp
= new int[count
];
1836 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1839 for (int x
=0; x
<count
; x
++) {
1840 PyObject
* o
= PyList_GetItem(source
, x
);
1841 if (! PyInt_Check(o
)) {
1842 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1845 temp
[x
] = PyInt_AsLong(o
);
1851 long* long_LIST_helper(PyObject
* source
) {
1852 if (!PyList_Check(source
)) {
1853 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1856 int count
= PyList_Size(source
);
1857 long* temp
= new long[count
];
1859 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1862 for (int x
=0; x
<count
; x
++) {
1863 PyObject
* o
= PyList_GetItem(source
, x
);
1864 if (! PyInt_Check(o
)) {
1865 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1868 temp
[x
] = PyInt_AsLong(o
);
1874 char** string_LIST_helper(PyObject
* source
) {
1875 if (!PyList_Check(source
)) {
1876 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1879 int count
= PyList_Size(source
);
1880 char** temp
= new char*[count
];
1882 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1885 for (int x
=0; x
<count
; x
++) {
1886 PyObject
* o
= PyList_GetItem(source
, x
);
1887 if (! PyString_Check(o
)) {
1888 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1891 temp
[x
] = PyString_AsString(o
);
1896 //--------------------------------
1897 // Part of patch from Tim Hochberg
1898 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1899 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1900 point
->x
= PyInt_AS_LONG(o1
);
1901 point
->y
= PyInt_AS_LONG(o2
);
1904 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1905 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1906 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1909 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1910 // Disallow instances because they can cause havok
1913 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1914 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1915 point
->x
= PyInt_AsLong(o1
);
1916 point
->y
= PyInt_AsLong(o2
);
1923 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1924 // Putting all of the declarations here allows
1925 // us to put the error handling all in one place.
1928 PyObject
*o
, *o1
, *o2
;
1929 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1931 if (!PySequence_Check(source
)) {
1935 // The length of the sequence is returned in count.
1936 *count
= PySequence_Length(source
);
1941 temp
= new wxPoint
[*count
];
1943 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1946 for (x
=0; x
<*count
; x
++) {
1947 // Get an item: try fast way first.
1949 o
= PySequence_Fast_GET_ITEM(source
, x
);
1952 o
= PySequence_GetItem(source
, x
);
1958 // Convert o to wxPoint.
1959 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1960 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1961 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1962 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1963 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1967 else if (wxPySwigInstance_Check(o
)) {
1969 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1974 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1975 o1
= PySequence_GetItem(o
, 0);
1976 o2
= PySequence_GetItem(o
, 1);
1977 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2001 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2005 //------------------------------
2008 wxBitmap
** wxBitmap_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 wxBitmap
** temp
= new wxBitmap
*[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
)) {
2023 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2024 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2030 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2039 wxString
* wxString_LIST_helper(PyObject
* source
) {
2040 if (!PyList_Check(source
)) {
2041 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2044 int count
= PyList_Size(source
);
2045 wxString
* temp
= new wxString
[count
];
2047 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2050 for (int x
=0; x
<count
; x
++) {
2051 PyObject
* o
= PyList_GetItem(source
, x
);
2052 #if PYTHON_API_VERSION >= 1009
2053 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2054 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2058 if (! PyString_Check(o
)) {
2059 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2064 wxString
* pStr
= wxString_in_helper(o
);
2072 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2073 if (!PyList_Check(source
)) {
2074 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2077 int count
= PyList_Size(source
);
2078 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2080 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2083 for (int x
=0; x
<count
; x
++) {
2084 PyObject
* o
= PyList_GetItem(source
, x
);
2085 if (wxPySwigInstance_Check(o
)) {
2086 wxAcceleratorEntry
* ae
;
2087 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2088 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2093 else if (PyTuple_Check(o
)) {
2094 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2095 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2096 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2097 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2100 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2108 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2109 if (!PyList_Check(source
)) {
2110 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2113 int count
= PyList_Size(source
);
2114 wxPen
** temp
= new wxPen
*[count
];
2116 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2119 for (int x
=0; x
<count
; x
++) {
2120 PyObject
* o
= PyList_GetItem(source
, x
);
2121 if (wxPySwigInstance_Check(o
)) {
2123 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2125 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2132 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2140 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2141 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2144 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2148 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2149 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2152 o1
= PySequence_GetItem(source
, 0);
2153 o2
= PySequence_GetItem(source
, 1);
2156 *i1
= PyInt_AsLong(o1
);
2157 *i2
= PyInt_AsLong(o2
);
2167 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2168 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2169 PyObject
*o1
, *o2
, *o3
, *o4
;
2171 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2175 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2176 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2177 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2178 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2181 o1
= PySequence_GetItem(source
, 0);
2182 o2
= PySequence_GetItem(source
, 1);
2183 o3
= PySequence_GetItem(source
, 2);
2184 o4
= PySequence_GetItem(source
, 3);
2187 *i1
= PyInt_AsLong(o1
);
2188 *i2
= PyInt_AsLong(o2
);
2189 *i3
= PyInt_AsLong(o3
);
2190 *i4
= PyInt_AsLong(o4
);
2202 //----------------------------------------------------------------------
2204 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2208 if (wxPySwigInstance_Check(source
) &&
2209 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2213 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2219 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2221 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2225 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2227 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2232 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** 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("wxRealPoint")))
2242 // otherwise a 2-tuple of floats is expected
2243 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2244 PyObject
* o1
= PySequence_GetItem(source
, 0);
2245 PyObject
* o2
= PySequence_GetItem(source
, 1);
2246 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2251 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2258 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2264 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2266 // If source is an object instance then it may already be the right type
2267 if (wxPySwigInstance_Check(source
)) {
2269 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2274 // otherwise a 4-tuple of integers is expected
2275 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2276 PyObject
* o1
= PySequence_GetItem(source
, 0);
2277 PyObject
* o2
= PySequence_GetItem(source
, 1);
2278 PyObject
* o3
= PySequence_GetItem(source
, 2);
2279 PyObject
* o4
= PySequence_GetItem(source
, 3);
2280 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2281 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2288 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2289 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2298 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2304 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2306 // If source is an object instance then it may already be the right type
2307 if (wxPySwigInstance_Check(source
)) {
2309 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2314 // otherwise check for a string
2315 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2316 wxString spec
= Py2wxString(source
);
2317 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2318 long red
, green
, blue
;
2319 red
= green
= blue
= 0;
2320 spec
.Mid(1,2).ToLong(&red
, 16);
2321 spec
.Mid(3,2).ToLong(&green
, 16);
2322 spec
.Mid(5,2).ToLong(&blue
, 16);
2324 **obj
= wxColour(red
, green
, blue
);
2327 else { // it's a colour name
2328 **obj
= wxColour(spec
);
2332 // last chance: 3-tuple of integers is expected
2333 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2334 PyObject
* o1
= PySequence_GetItem(source
, 0);
2335 PyObject
* o2
= PySequence_GetItem(source
, 1);
2336 PyObject
* o3
= PySequence_GetItem(source
, 2);
2337 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2343 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2351 PyErr_SetString(PyExc_TypeError
,
2352 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2357 bool wxColour_typecheck(PyObject
* source
) {
2359 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2362 if (PyString_Check(source
) || PyUnicode_Check(source
))
2370 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2371 // If source is an object instance then it may already be the right type
2372 if (wxPySwigInstance_Check(source
)) {
2374 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2379 // otherwise a length-2 sequence of floats is expected
2380 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2381 PyObject
* o1
= PySequence_GetItem(source
, 0);
2382 PyObject
* o2
= PySequence_GetItem(source
, 1);
2383 // This should really check for floats, not numbers -- but that would break code.
2384 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2389 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2395 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2400 //----------------------------------------------------------------------
2402 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2404 PyObject
* list
= PyList_New(0);
2405 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2407 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2409 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2411 PyList_Append(list
, str
);
2418 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2420 PyObject
* list
= PyList_New(0);
2421 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2422 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2423 PyList_Append(list
, number
);
2430 //----------------------------------------------------------------------
2431 //----------------------------------------------------------------------