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(3);
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(1);
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,
568 // but only after the app object has been created. The
569 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
570 // objects though various stages of evolution:
572 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
573 // object will be created (otherwise it will just use None.)
575 // pass 2: After the module has been imported and the python proxys have
576 // been created, then set the __class__ to be _wxPyUnbornObject so
577 // it will catch any access to the object and will raise an exception.
579 // pass 3: Finally, from OnInit patch things up so the stock objects can
583 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
585 wxPy_ReinitStockObjects(2);
590 static void rsoPass2(const char* name
)
592 static PyObject
* unbornObjectClass
= NULL
;
595 if (unbornObjectClass
== NULL
) {
596 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
597 Py_INCREF(unbornObjectClass
);
600 // Find the object instance
601 obj
= PyDict_GetItemString(wxPython_dict
, dropwx(name
));
602 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
603 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
606 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
610 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
616 // Find the object instance
617 obj
= PyDict_GetItemString(wxPython_dict
, dropwx(name
));
618 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
619 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
621 // Find the class object and put it back in the instance
622 classobj
= PyDict_GetItemString(wxPython_dict
, dropwx(classname
));
623 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
624 PyObject_SetAttrString(obj
, "__class__", classobj
);
626 // Rebuild the .this swigified pointer with the new value of the C++ pointer
627 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
628 PyObject_SetAttrString(obj
, "this", ptrobj
);
634 void wxPy_ReinitStockObjects(int pass
)
639 #define REINITOBJ(name, classname) \
640 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
641 else if (pass == 2) { rsoPass2(#name); } \
642 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
645 #define REINITOBJ2(name, classname) \
647 else if (pass == 2) { rsoPass2(#name); } \
648 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
651 REINITOBJ(wxNORMAL_FONT
, wxFont
);
652 REINITOBJ(wxSMALL_FONT
, wxFont
);
653 REINITOBJ(wxITALIC_FONT
, wxFont
);
654 REINITOBJ(wxSWISS_FONT
, wxFont
);
656 REINITOBJ(wxRED_PEN
, wxPen
);
657 REINITOBJ(wxCYAN_PEN
, wxPen
);
658 REINITOBJ(wxGREEN_PEN
, wxPen
);
659 REINITOBJ(wxBLACK_PEN
, wxPen
);
660 REINITOBJ(wxWHITE_PEN
, wxPen
);
661 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
662 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
663 REINITOBJ(wxGREY_PEN
, wxPen
);
664 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
665 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
667 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
668 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
669 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
670 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
671 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
672 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
673 REINITOBJ(wxRED_BRUSH
, wxBrush
);
674 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
675 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
676 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
678 REINITOBJ(wxBLACK
, wxColour
);
679 REINITOBJ(wxWHITE
, wxColour
);
680 REINITOBJ(wxRED
, wxColour
);
681 REINITOBJ(wxBLUE
, wxColour
);
682 REINITOBJ(wxGREEN
, wxColour
);
683 REINITOBJ(wxCYAN
, wxColour
);
684 REINITOBJ(wxLIGHT_GREY
, wxColour
);
686 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
687 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
688 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
690 REINITOBJ2(wxNullBitmap
, wxBitmap
);
691 REINITOBJ2(wxNullIcon
, wxIcon
);
692 REINITOBJ2(wxNullCursor
, wxCursor
);
693 REINITOBJ2(wxNullPen
, wxPen
);
694 REINITOBJ2(wxNullBrush
, wxBrush
);
695 REINITOBJ2(wxNullPalette
, wxPalette
);
696 REINITOBJ2(wxNullFont
, wxFont
);
697 REINITOBJ2(wxNullColour
, wxColour
);
699 REINITOBJ(wxTheFontList
, wxFontList
);
700 REINITOBJ(wxThePenList
, wxPenList
);
701 REINITOBJ(wxTheBrushList
, wxBrushList
);
702 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
705 REINITOBJ(wxTheClipboard
, wxClipboard
);
706 REINITOBJ2(wxDefaultValidator
, wxValidator
);
707 REINITOBJ2(wxNullImage
, wxImage
);
708 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
714 //---------------------------------------------------------------------------
716 void wxPyClientData_dtor(wxPyClientData
* self
) {
717 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
718 // may have already garbage collected the object...
719 wxPyBeginBlockThreads();
720 Py_DECREF(self
->m_obj
);
722 wxPyEndBlockThreads();
726 void wxPyUserData_dtor(wxPyUserData
* self
) {
727 if (! wxPyDoingCleanup
) {
728 wxPyBeginBlockThreads();
729 Py_DECREF(self
->m_obj
);
731 wxPyEndBlockThreads();
736 // This is called when an OOR controled object is being destroyed. Although
737 // the C++ object is going away there is no way to force the Python object
738 // (and all references to it) to die too. This causes problems (crashes) in
739 // wxPython when a python shadow object attempts to call a C++ method using
740 // the now bogus pointer... So to try and prevent this we'll do a little black
741 // magic and change the class of the python instance to a class that will
742 // raise an exception for any attempt to call methods with it. See
743 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
744 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
746 static PyObject
* deadObjectClass
= NULL
;
748 wxPyBeginBlockThreads();
749 if (deadObjectClass
== NULL
) {
750 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
751 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
752 // will lead to a deadlock when it tries to aquire the GIL again.
753 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
754 Py_INCREF(deadObjectClass
);
758 // Only if there is more than one reference to the object
759 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
760 // bool isInstance = wxPyInstance_Check(self->m_obj);
762 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
764 // Call __del__, if there is one.
765 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
767 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
771 if (PyErr_Occurred())
772 PyErr_Clear(); // just ignore it for now
775 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
777 // Clear the instance's dictionary
780 // put the name of the old class into the instance, and then reset the
781 // class to be the dead class.
782 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
783 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
784 PyDict_SetItemString(dict
, "_name", name
);
785 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
786 //Py_INCREF(deadObjectClass);
792 // m_obj is DECREF'd in the base class dtor...
793 wxPyEndBlockThreads();
797 //---------------------------------------------------------------------------
798 // Stuff used by OOR to find the right wxPython class type to return and to
802 // The pointer type map is used when the "pointer" type name generated by SWIG
803 // is not the same as the shadow class name, for example wxPyTreeCtrl
804 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
805 // so we'll just make it a Python dictionary in the wx module's namespace.
806 // (See __wxSetDictionary)
807 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
808 if (! wxPyPtrTypeMap
)
809 wxPyPtrTypeMap
= PyDict_New();
810 PyDict_SetItemString(wxPyPtrTypeMap
,
812 PyString_FromString((char*)ptrName
));
818 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
819 PyObject
* target
= NULL
;
820 bool isEvtHandler
= False
;
823 // If it's derived from wxEvtHandler then there may
824 // already be a pointer to a Python object that we can use
826 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
828 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
829 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
831 target
= data
->m_obj
;
838 // Otherwise make it the old fashioned way by making a new shadow
839 // object and putting this pointer in it. Look up the class
840 // heirarchy until we find a class name that is located in the
842 const wxClassInfo
* info
= source
->GetClassInfo();
843 wxString name
= info
->GetClassName();
844 bool exists
= wxPyCheckSwigType(name
);
845 while (info
&& !exists
) {
846 info
= info
->GetBaseClass1();
847 name
= info
->GetClassName();
848 exists
= wxPyCheckSwigType(name
);
851 target
= wxPyConstructObject((void*)source
, name
, False
);
852 if (target
&& isEvtHandler
)
853 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
855 wxString
msg(wxT("wxPython class not found for "));
856 msg
+= source
->GetClassInfo()->GetClassName();
857 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
861 } else { // source was NULL so return None.
862 Py_INCREF(Py_None
); target
= Py_None
;
868 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
869 PyObject
* target
= NULL
;
871 if (source
&& wxIsKindOf(source
, wxSizer
)) {
872 // If it's derived from wxSizer then there may already be a pointer to
873 // a Python object that we can use in the OOR data.
874 wxSizer
* sz
= (wxSizer
*)source
;
875 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
877 target
= data
->m_obj
;
883 target
= wxPyMake_wxObject(source
, False
);
884 if (target
!= Py_None
)
885 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
891 //---------------------------------------------------------------------------
894 #ifdef WXP_WITH_THREAD
896 unsigned long wxPyGetCurrentThreadId() {
897 return wxThread::GetCurrentId();
900 static PyThreadState
* gs_shutdownTState
;
903 PyThreadState
* wxPyGetThreadState() {
904 if (wxPyTMutex
== NULL
) // Python is shutting down...
905 return gs_shutdownTState
;
907 unsigned long ctid
= wxPyGetCurrentThreadId();
908 PyThreadState
* tstate
= NULL
;
911 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
912 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
913 if (info
.tid
== ctid
) {
914 tstate
= info
.tstate
;
918 wxPyTMutex
->Unlock();
919 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
;
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();
955 // Calls from Python to wxWindows code are wrapped in calls to these
958 PyThreadState
* wxPyBeginAllowThreads() {
959 #ifdef WXP_WITH_THREAD
960 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
961 wxPySaveThreadState(saved
);
968 void wxPyEndAllowThreads(PyThreadState
* saved
) {
969 #ifdef WXP_WITH_THREAD
970 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
976 // Calls from wxWindows back to Python code, or even any PyObject
977 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
979 void wxPyBeginBlockThreads() {
980 #ifdef WXP_WITH_THREAD
981 PyThreadState
* tstate
= wxPyGetThreadState();
982 PyEval_RestoreThread(tstate
);
987 void wxPyEndBlockThreads() {
988 #ifdef WXP_WITH_THREAD
989 // Is there any need to save it again?
990 // PyThreadState* tstate =
996 //---------------------------------------------------------------------------
997 // wxPyInputStream and wxPyCBInputStream methods
1000 void wxPyInputStream::close() {
1001 /* do nothing for now */
1004 void wxPyInputStream::flush() {
1005 /* do nothing for now */
1008 bool wxPyInputStream::eof() {
1010 return m_wxis
->Eof();
1015 wxPyInputStream::~wxPyInputStream() {
1022 PyObject
* wxPyInputStream::read(int size
) {
1023 PyObject
* obj
= NULL
;
1025 const int BUFSIZE
= 1024;
1027 // check if we have a real wxInputStream to work with
1029 wxPyBeginBlockThreads();
1030 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1031 wxPyEndBlockThreads();
1036 // read while bytes are available on the stream
1037 while ( m_wxis
->CanRead() ) {
1038 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1039 buf
.UngetAppendBuf(m_wxis
->LastRead());
1042 } else { // Read only size number of characters
1043 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1044 buf
.UngetWriteBuf(m_wxis
->LastRead());
1048 wxPyBeginBlockThreads();
1049 wxStreamError err
= m_wxis
->GetLastError();
1050 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1051 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1054 // We use only strings for the streams, not unicode
1055 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1057 wxPyEndBlockThreads();
1062 PyObject
* wxPyInputStream::readline(int size
) {
1063 PyObject
* obj
= NULL
;
1068 // check if we have a real wxInputStream to work with
1070 wxPyBeginBlockThreads();
1071 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1072 wxPyEndBlockThreads();
1076 // read until \n or byte limit reached
1077 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1078 ch
= m_wxis
->GetC();
1083 wxPyBeginBlockThreads();
1084 wxStreamError err
= m_wxis
->GetLastError();
1085 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1086 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1089 // We use only strings for the streams, not unicode
1090 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1092 wxPyEndBlockThreads();
1097 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1100 // check if we have a real wxInputStream to work with
1102 wxPyBeginBlockThreads();
1103 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1104 wxPyEndBlockThreads();
1109 wxPyBeginBlockThreads();
1110 pylist
= PyList_New(0);
1112 wxPyBeginBlockThreads();
1114 wxPyEndBlockThreads();
1118 // read sizehint bytes or until EOF
1120 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1121 PyObject
* s
= this->readline();
1123 wxPyBeginBlockThreads();
1125 wxPyEndBlockThreads();
1128 wxPyBeginBlockThreads();
1129 PyList_Append(pylist
, s
);
1130 i
+= PyString_Size(s
);
1131 wxPyEndBlockThreads();
1135 wxStreamError err
= m_wxis
->GetLastError();
1136 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1137 wxPyBeginBlockThreads();
1139 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1140 wxPyEndBlockThreads();
1148 void wxPyInputStream::seek(int offset
, int whence
) {
1150 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1153 int wxPyInputStream::tell(){
1155 return m_wxis
->TellI();
1162 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1163 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1167 wxPyCBInputStream::~wxPyCBInputStream() {
1168 if (m_block
) wxPyBeginBlockThreads();
1172 if (m_block
) wxPyEndBlockThreads();
1176 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1177 if (block
) wxPyBeginBlockThreads();
1179 PyObject
* read
= getMethod(py
, "read");
1180 PyObject
* seek
= getMethod(py
, "seek");
1181 PyObject
* tell
= getMethod(py
, "tell");
1184 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1188 if (block
) wxPyEndBlockThreads();
1192 if (block
) wxPyEndBlockThreads();
1193 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1197 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1198 return wxPyCBInputStream::create(py
, block
);
1201 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1202 if (!PyObject_HasAttrString(py
, name
))
1204 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1205 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1213 size_t wxPyCBInputStream::GetSize() const {
1214 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1215 if (m_seek
&& m_tell
) {
1216 off_t temp
= self
->OnSysTell();
1217 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1218 self
->OnSysSeek(temp
, wxFromStart
);
1226 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1230 wxPyBeginBlockThreads();
1231 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1232 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1236 if ((result
!= NULL
) && PyString_Check(result
)) {
1237 o
= PyString_Size(result
);
1239 m_lasterror
= wxSTREAM_EOF
;
1242 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1247 m_lasterror
= wxSTREAM_READ_ERROR
;
1248 wxPyEndBlockThreads();
1252 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1253 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1257 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1258 wxPyBeginBlockThreads();
1260 // off_t is a 64-bit value...
1261 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1263 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1265 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1268 wxPyEndBlockThreads();
1273 off_t
wxPyCBInputStream::OnSysTell() const {
1274 wxPyBeginBlockThreads();
1275 PyObject
* arglist
= Py_BuildValue("()");
1276 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1279 if (result
!= NULL
) {
1281 if (PyLong_Check(result
))
1282 o
= PyLong_AsLongLong(result
);
1285 o
= PyInt_AsLong(result
);
1289 wxPyEndBlockThreads();
1293 //----------------------------------------------------------------------
1295 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1297 wxPyCallback::wxPyCallback(PyObject
* func
) {
1302 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1303 m_func
= other
.m_func
;
1307 wxPyCallback::~wxPyCallback() {
1308 wxPyBeginBlockThreads();
1310 wxPyEndBlockThreads();
1315 // This function is used for all events destined for Python event handlers.
1316 void wxPyCallback::EventThunker(wxEvent
& event
) {
1317 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1318 PyObject
* func
= cb
->m_func
;
1322 bool checkSkip
= False
;
1324 wxPyBeginBlockThreads();
1325 wxString className
= event
.GetClassInfo()->GetClassName();
1327 // If the event is one of these types then pass the original
1328 // event object instead of the one passed to us.
1329 if ( className
== wxT("wxPyEvent") ) {
1330 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1331 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1333 else if ( className
== wxT("wxPyCommandEvent") ) {
1334 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1335 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1338 arg
= wxPyConstructObject((void*)&event
, className
);
1341 // Call the event handler, passing the event object
1342 tuple
= PyTuple_New(1);
1343 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1344 result
= PyEval_CallObject(func
, tuple
);
1346 Py_DECREF(result
); // result is ignored, but we still need to decref it
1347 PyErr_Clear(); // Just in case...
1353 // if the event object was one of our special types and
1354 // it had been cloned, then we need to extract the Skipped
1355 // value from the original and set it in the clone.
1356 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1358 event
.Skip(PyInt_AsLong(result
));
1366 wxPyEndBlockThreads();
1370 //----------------------------------------------------------------------
1372 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1374 m_self
= other
.m_self
;
1375 m_class
= other
.m_class
;
1383 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1394 #if PYTHON_API_VERSION >= 1011
1396 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1397 // in which the method was defined. Starting with 2.2 it returns
1398 // "class that asked for the method" which seems totally bogus to me
1399 // but apprently it fixes some obscure problem waiting to happen in
1400 // Python. Since the API was not documented Guido and the gang felt
1401 // safe in changing it. Needless to say that totally screwed up the
1402 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1403 // code to find the class where the method is actually defined...
1406 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1410 if (PyType_Check(klass
)) { // new style classes
1411 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1412 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1413 PyObject
*mro
, *res
, *base
, *dict
;
1414 /* Look in tp_dict of types in MRO */
1416 assert(PyTuple_Check(mro
));
1417 n
= PyTuple_GET_SIZE(mro
);
1418 for (i
= 0; i
< n
; i
++) {
1419 base
= PyTuple_GET_ITEM(mro
, i
);
1420 if (PyClass_Check(base
))
1421 dict
= ((PyClassObject
*)base
)->cl_dict
;
1423 assert(PyType_Check(base
));
1424 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1426 assert(dict
&& PyDict_Check(dict
));
1427 res
= PyDict_GetItem(dict
, name
);
1434 else if (PyClass_Check(klass
)) { // old style classes
1435 // This code is borrowed/adapted from class_lookup in classobject.c
1436 PyClassObject
* cp
= (PyClassObject
*)klass
;
1437 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1438 if (value
!= NULL
) {
1439 return (PyObject
*)cp
;
1441 n
= PyTuple_Size(cp
->cl_bases
);
1442 for (i
= 0; i
< n
; i
++) {
1443 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1444 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1456 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1458 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1460 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1462 #else // 2.2 and after, the hard way...
1464 PyObject
* nameo
= PyString_FromString(name
);
1465 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1473 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1474 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1475 self
->m_lastFound
= NULL
;
1477 // If the object (m_self) has an attibute of the given name...
1478 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1479 PyObject
*method
, *klass
;
1480 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1482 // ...and if that attribute is a method, and if that method's class is
1483 // not from a base class...
1484 if (PyMethod_Check(method
) &&
1485 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1486 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1488 // ...then we'll save a pointer to the method so callCallback can call it.
1489 self
->m_lastFound
= method
;
1495 return m_lastFound
!= NULL
;
1499 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1503 result
= callCallbackObj(argTuple
);
1504 if (result
) { // Assumes an integer return type...
1505 retval
= PyInt_AsLong(result
);
1507 PyErr_Clear(); // forget about it if it's not...
1512 // Invoke the Python callable object, returning the raw PyObject return
1513 // value. Caller should DECREF the return value and also manage the GIL.
1514 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1517 // Save a copy of the pointer in case the callback generates another
1518 // callback. In that case m_lastFound will have a different value when
1519 // it gets back here...
1520 PyObject
* method
= m_lastFound
;
1522 result
= PyEval_CallObject(method
, argTuple
);
1523 Py_DECREF(argTuple
);
1532 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1533 cbh
.setSelf(self
, klass
, incref
);
1536 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1537 return cbh
.findCallback(name
);
1540 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1541 return cbh
.callCallback(argTuple
);
1544 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1545 return cbh
.callCallbackObj(argTuple
);
1549 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1550 if (cbh
->m_incRef
) {
1551 wxPyBeginBlockThreads();
1552 Py_XDECREF(cbh
->m_self
);
1553 Py_XDECREF(cbh
->m_class
);
1554 wxPyEndBlockThreads();
1558 //---------------------------------------------------------------------------
1559 //---------------------------------------------------------------------------
1560 // These event classes can be derived from in Python and passed through the event
1561 // system without losing anything. They do this by keeping a reference to
1562 // themselves and some special case handling in wxPyCallback::EventThunker.
1565 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1566 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1567 //Py_INCREF(m_self); // circular loops...
1571 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1572 wxPyBeginBlockThreads();
1575 wxPyEndBlockThreads();
1578 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1579 wxPyBeginBlockThreads();
1587 wxPyEndBlockThreads();
1590 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1596 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1597 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1600 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1601 : wxEvent(winid
, commandType
) {
1605 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1608 SetSelf(evt
.m_self
, True
);
1612 wxPyEvent::~wxPyEvent() {
1616 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1617 : wxCommandEvent(commandType
, id
) {
1621 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1622 : wxCommandEvent(evt
)
1624 SetSelf(evt
.m_self
, True
);
1628 wxPyCommandEvent::~wxPyCommandEvent() {
1635 //---------------------------------------------------------------------------
1636 //---------------------------------------------------------------------------
1637 // Convert a wxList to a Python List, only works for lists of wxObjects
1639 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1640 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1644 wxNode
* node
= list
->GetFirst();
1646 wxPyBeginBlockThreads();
1647 pyList
= PyList_New(0);
1649 wxObj
= node
->GetData();
1650 pyObj
= wxPyMake_wxObject(wxObj
);
1651 PyList_Append(pyList
, pyObj
);
1652 node
= node
->GetNext();
1654 wxPyEndBlockThreads();
1658 //----------------------------------------------------------------------
1660 long wxPyGetWinHandle(wxWindow
* win
) {
1662 return (long)win
->GetHandle();
1665 // Find and return the actual X-Window.
1667 if (win
->m_wxwindow
) {
1669 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1671 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1673 return (long)bwin
->xwindow
;
1681 //----------------------------------------------------------------------
1682 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1683 // included in every file over and over again...
1685 #if PYTHON_API_VERSION >= 1009
1686 static char* wxStringErrorMsg
= "String or Unicode type required";
1688 static char* wxStringErrorMsg
= "String type required";
1692 wxString
* wxString_in_helper(PyObject
* source
) {
1694 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1695 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1696 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1700 if (PyUnicode_Check(source
)) {
1701 target
= new wxString();
1702 size_t len
= PyUnicode_GET_SIZE(source
);
1704 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1705 target
->UngetWriteBuf();
1708 // It is a string, get pointers to it and transform to unicode
1709 char* tmpPtr
; int tmpSize
;
1710 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1711 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1714 char* tmpPtr
; int tmpSize
;
1715 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1716 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1719 target
= new wxString(tmpPtr
, tmpSize
);
1720 #endif // wxUSE_UNICODE
1722 #else // No Python unicode API (1.5.2)
1723 if (!PyString_Check(source
)) {
1724 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1727 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1733 // Similar to above except doesn't use "new" and doesn't set an exception
1734 wxString
Py2wxString(PyObject
* source
)
1737 bool doDecRef
= False
;
1739 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1740 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1741 // Convert to String if not one already... (TODO: Unicode too?)
1742 source
= PyObject_Str(source
);
1747 if (PyUnicode_Check(source
)) {
1748 size_t len
= PyUnicode_GET_SIZE(source
);
1750 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1751 target
.UngetWriteBuf();
1754 // It is a string, get pointers to it and transform to unicode
1755 char* tmpPtr
; int tmpSize
;
1756 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1757 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1760 char* tmpPtr
; int tmpSize
;
1761 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1762 target
= wxString(tmpPtr
, tmpSize
);
1763 #endif // wxUSE_UNICODE
1765 #else // No Python unicode API (1.5.2)
1766 if (!PyString_Check(source
)) {
1767 // Convert to String if not one already...
1768 source
= PyObject_Str(source
);
1771 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1780 // Make either a Python String or Unicode object, depending on build mode
1781 PyObject
* wx2PyString(const wxString
& src
)
1785 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1787 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1793 //----------------------------------------------------------------------
1796 byte
* byte_LIST_helper(PyObject
* source
) {
1797 if (!PyList_Check(source
)) {
1798 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1801 int count
= PyList_Size(source
);
1802 byte
* temp
= new byte
[count
];
1804 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1807 for (int x
=0; x
<count
; x
++) {
1808 PyObject
* o
= PyList_GetItem(source
, x
);
1809 if (! PyInt_Check(o
)) {
1810 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1813 temp
[x
] = (byte
)PyInt_AsLong(o
);
1819 int* int_LIST_helper(PyObject
* source
) {
1820 if (!PyList_Check(source
)) {
1821 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1824 int count
= PyList_Size(source
);
1825 int* temp
= new int[count
];
1827 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1830 for (int x
=0; x
<count
; x
++) {
1831 PyObject
* o
= PyList_GetItem(source
, x
);
1832 if (! PyInt_Check(o
)) {
1833 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1836 temp
[x
] = PyInt_AsLong(o
);
1842 long* long_LIST_helper(PyObject
* source
) {
1843 if (!PyList_Check(source
)) {
1844 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1847 int count
= PyList_Size(source
);
1848 long* temp
= new long[count
];
1850 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1853 for (int x
=0; x
<count
; x
++) {
1854 PyObject
* o
= PyList_GetItem(source
, x
);
1855 if (! PyInt_Check(o
)) {
1856 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1859 temp
[x
] = PyInt_AsLong(o
);
1865 char** string_LIST_helper(PyObject
* source
) {
1866 if (!PyList_Check(source
)) {
1867 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1870 int count
= PyList_Size(source
);
1871 char** temp
= new char*[count
];
1873 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1876 for (int x
=0; x
<count
; x
++) {
1877 PyObject
* o
= PyList_GetItem(source
, x
);
1878 if (! PyString_Check(o
)) {
1879 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1882 temp
[x
] = PyString_AsString(o
);
1887 //--------------------------------
1888 // Part of patch from Tim Hochberg
1889 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1890 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1891 point
->x
= PyInt_AS_LONG(o1
);
1892 point
->y
= PyInt_AS_LONG(o2
);
1895 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1896 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1897 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1900 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1901 // Disallow instances because they can cause havok
1904 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1905 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1906 point
->x
= PyInt_AsLong(o1
);
1907 point
->y
= PyInt_AsLong(o2
);
1914 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1915 // Putting all of the declarations here allows
1916 // us to put the error handling all in one place.
1919 PyObject
*o
, *o1
, *o2
;
1920 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1922 if (!PySequence_Check(source
)) {
1926 // The length of the sequence is returned in count.
1927 *count
= PySequence_Length(source
);
1932 temp
= new wxPoint
[*count
];
1934 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1937 for (x
=0; x
<*count
; x
++) {
1938 // Get an item: try fast way first.
1940 o
= PySequence_Fast_GET_ITEM(source
, x
);
1943 o
= PySequence_GetItem(source
, x
);
1949 // Convert o to wxPoint.
1950 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1951 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1952 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1953 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1954 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1958 else if (wxPySwigInstance_Check(o
)) {
1960 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1965 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1966 o1
= PySequence_GetItem(o
, 0);
1967 o2
= PySequence_GetItem(o
, 1);
1968 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1992 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
1996 //------------------------------
1999 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2000 if (!PyList_Check(source
)) {
2001 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2004 int count
= PyList_Size(source
);
2005 wxBitmap
** temp
= new wxBitmap
*[count
];
2007 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2010 for (int x
=0; x
<count
; x
++) {
2011 PyObject
* o
= PyList_GetItem(source
, x
);
2012 if (wxPySwigInstance_Check(o
)) {
2014 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2015 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2021 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2030 wxString
* wxString_LIST_helper(PyObject
* source
) {
2031 if (!PyList_Check(source
)) {
2032 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2035 int count
= PyList_Size(source
);
2036 wxString
* temp
= new wxString
[count
];
2038 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2041 for (int x
=0; x
<count
; x
++) {
2042 PyObject
* o
= PyList_GetItem(source
, x
);
2043 #if PYTHON_API_VERSION >= 1009
2044 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2045 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2049 if (! PyString_Check(o
)) {
2050 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2055 wxString
* pStr
= wxString_in_helper(o
);
2063 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2064 if (!PyList_Check(source
)) {
2065 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2068 int count
= PyList_Size(source
);
2069 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2071 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2074 for (int x
=0; x
<count
; x
++) {
2075 PyObject
* o
= PyList_GetItem(source
, x
);
2076 if (wxPySwigInstance_Check(o
)) {
2077 wxAcceleratorEntry
* ae
;
2078 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2079 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2084 else if (PyTuple_Check(o
)) {
2085 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2086 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2087 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2088 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2091 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2099 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2100 if (!PyList_Check(source
)) {
2101 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2104 int count
= PyList_Size(source
);
2105 wxPen
** temp
= new wxPen
*[count
];
2107 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2110 for (int x
=0; x
<count
; x
++) {
2111 PyObject
* o
= PyList_GetItem(source
, x
);
2112 if (wxPySwigInstance_Check(o
)) {
2114 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2116 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2123 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2131 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2132 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2135 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2139 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2140 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2143 o1
= PySequence_GetItem(source
, 0);
2144 o2
= PySequence_GetItem(source
, 1);
2147 *i1
= PyInt_AsLong(o1
);
2148 *i2
= PyInt_AsLong(o2
);
2158 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2159 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2160 PyObject
*o1
, *o2
, *o3
, *o4
;
2162 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2166 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2167 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2168 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2169 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2172 o1
= PySequence_GetItem(source
, 0);
2173 o2
= PySequence_GetItem(source
, 1);
2174 o3
= PySequence_GetItem(source
, 2);
2175 o4
= PySequence_GetItem(source
, 3);
2178 *i1
= PyInt_AsLong(o1
);
2179 *i2
= PyInt_AsLong(o2
);
2180 *i3
= PyInt_AsLong(o3
);
2181 *i4
= PyInt_AsLong(o4
);
2193 //----------------------------------------------------------------------
2195 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2199 if (wxPySwigInstance_Check(source
) &&
2200 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2204 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2210 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2212 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2216 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2218 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2223 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2225 // If source is an object instance then it may already be the right type
2226 if (wxPySwigInstance_Check(source
)) {
2228 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2233 // otherwise a 2-tuple of floats is expected
2234 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2235 PyObject
* o1
= PySequence_GetItem(source
, 0);
2236 PyObject
* o2
= PySequence_GetItem(source
, 1);
2237 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2242 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2249 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2255 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2257 // If source is an object instance then it may already be the right type
2258 if (wxPySwigInstance_Check(source
)) {
2260 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2265 // otherwise a 4-tuple of integers is expected
2266 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2267 PyObject
* o1
= PySequence_GetItem(source
, 0);
2268 PyObject
* o2
= PySequence_GetItem(source
, 1);
2269 PyObject
* o3
= PySequence_GetItem(source
, 2);
2270 PyObject
* o4
= PySequence_GetItem(source
, 3);
2271 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2272 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2279 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2280 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2289 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2295 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2297 // If source is an object instance then it may already be the right type
2298 if (wxPySwigInstance_Check(source
)) {
2300 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2305 // otherwise check for a string
2306 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2307 wxString spec
= Py2wxString(source
);
2308 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2309 long red
, green
, blue
;
2310 red
= green
= blue
= 0;
2311 spec
.Mid(1,2).ToLong(&red
, 16);
2312 spec
.Mid(3,2).ToLong(&green
, 16);
2313 spec
.Mid(5,2).ToLong(&blue
, 16);
2315 **obj
= wxColour(red
, green
, blue
);
2318 else { // it's a colour name
2319 **obj
= wxColour(spec
);
2323 // last chance: 3-tuple of integers is expected
2324 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2325 PyObject
* o1
= PySequence_GetItem(source
, 0);
2326 PyObject
* o2
= PySequence_GetItem(source
, 1);
2327 PyObject
* o3
= PySequence_GetItem(source
, 2);
2328 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2334 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2342 PyErr_SetString(PyExc_TypeError
,
2343 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2348 bool wxColour_typecheck(PyObject
* source
) {
2350 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2353 if (PyString_Check(source
) || PyUnicode_Check(source
))
2361 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2362 // If source is an object instance then it may already be the right type
2363 if (wxPySwigInstance_Check(source
)) {
2365 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2370 // otherwise a length-2 sequence of floats is expected
2371 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2372 PyObject
* o1
= PySequence_GetItem(source
, 0);
2373 PyObject
* o2
= PySequence_GetItem(source
, 1);
2374 // This should really check for floats, not numbers -- but that would break code.
2375 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2380 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2386 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2391 //----------------------------------------------------------------------
2393 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2395 PyObject
* list
= PyList_New(0);
2396 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2398 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2400 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2402 PyList_Append(list
, str
);
2409 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2411 PyObject
* list
= PyList_New(0);
2412 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2413 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2414 PyList_Append(list
, number
);
2421 //----------------------------------------------------------------------
2422 //----------------------------------------------------------------------