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
, (char*)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
, (char*)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
, (char*)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
)
637 #define REINITOBJ(name, classname) \
638 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
639 else if (pass == 2) { rsoPass2(#name); } \
640 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
643 #define REINITOBJ2(name, classname) \
645 else if (pass == 2) { rsoPass2(#name); } \
646 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
649 REINITOBJ(wxNORMAL_FONT
, wxFont
);
650 REINITOBJ(wxSMALL_FONT
, wxFont
);
651 REINITOBJ(wxITALIC_FONT
, wxFont
);
652 REINITOBJ(wxSWISS_FONT
, wxFont
);
654 REINITOBJ(wxRED_PEN
, wxPen
);
655 REINITOBJ(wxCYAN_PEN
, wxPen
);
656 REINITOBJ(wxGREEN_PEN
, wxPen
);
657 REINITOBJ(wxBLACK_PEN
, wxPen
);
658 REINITOBJ(wxWHITE_PEN
, wxPen
);
659 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
660 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
661 REINITOBJ(wxGREY_PEN
, wxPen
);
662 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
663 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
665 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
666 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
667 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
668 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
669 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
670 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
671 REINITOBJ(wxRED_BRUSH
, wxBrush
);
672 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
673 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
674 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
676 REINITOBJ(wxBLACK
, wxColour
);
677 REINITOBJ(wxWHITE
, wxColour
);
678 REINITOBJ(wxRED
, wxColour
);
679 REINITOBJ(wxBLUE
, wxColour
);
680 REINITOBJ(wxGREEN
, wxColour
);
681 REINITOBJ(wxCYAN
, wxColour
);
682 REINITOBJ(wxLIGHT_GREY
, wxColour
);
684 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
685 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
686 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
688 REINITOBJ2(wxNullBitmap
, wxBitmap
);
689 REINITOBJ2(wxNullIcon
, wxIcon
);
690 REINITOBJ2(wxNullCursor
, wxCursor
);
691 REINITOBJ2(wxNullPen
, wxPen
);
692 REINITOBJ2(wxNullBrush
, wxBrush
);
693 REINITOBJ2(wxNullPalette
, wxPalette
);
694 REINITOBJ2(wxNullFont
, wxFont
);
695 REINITOBJ2(wxNullColour
, wxColour
);
697 REINITOBJ(wxTheFontList
, wxFontList
);
698 REINITOBJ(wxThePenList
, wxPenList
);
699 REINITOBJ(wxTheBrushList
, wxBrushList
);
700 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
703 REINITOBJ(wxTheClipboard
, wxClipboard
);
704 REINITOBJ2(wxDefaultValidator
, wxValidator
);
705 REINITOBJ2(wxNullImage
, wxImage
);
706 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
712 //---------------------------------------------------------------------------
714 void wxPyClientData_dtor(wxPyClientData
* self
) {
715 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
716 // may have already garbage collected the object...
717 wxPyBeginBlockThreads();
718 Py_DECREF(self
->m_obj
);
720 wxPyEndBlockThreads();
724 void wxPyUserData_dtor(wxPyUserData
* self
) {
725 if (! wxPyDoingCleanup
) {
726 wxPyBeginBlockThreads();
727 Py_DECREF(self
->m_obj
);
729 wxPyEndBlockThreads();
734 // This is called when an OOR controled object is being destroyed. Although
735 // the C++ object is going away there is no way to force the Python object
736 // (and all references to it) to die too. This causes problems (crashes) in
737 // wxPython when a python shadow object attempts to call a C++ method using
738 // the now bogus pointer... So to try and prevent this we'll do a little black
739 // magic and change the class of the python instance to a class that will
740 // raise an exception for any attempt to call methods with it. See
741 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
742 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
744 static PyObject
* deadObjectClass
= NULL
;
746 wxPyBeginBlockThreads();
747 if (deadObjectClass
== NULL
) {
748 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
749 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
750 // will lead to a deadlock when it tries to aquire the GIL again.
751 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
752 Py_INCREF(deadObjectClass
);
756 // Only if there is more than one reference to the object
757 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
758 // bool isInstance = wxPyInstance_Check(self->m_obj);
760 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
762 // Call __del__, if there is one.
763 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
765 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
769 if (PyErr_Occurred())
770 PyErr_Clear(); // just ignore it for now
773 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
775 // Clear the instance's dictionary
778 // put the name of the old class into the instance, and then reset the
779 // class to be the dead class.
780 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
781 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
782 PyDict_SetItemString(dict
, "_name", name
);
783 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
784 //Py_INCREF(deadObjectClass);
790 // m_obj is DECREF'd in the base class dtor...
791 wxPyEndBlockThreads();
795 //---------------------------------------------------------------------------
796 // Stuff used by OOR to find the right wxPython class type to return and to
800 // The pointer type map is used when the "pointer" type name generated by SWIG
801 // is not the same as the shadow class name, for example wxPyTreeCtrl
802 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
803 // so we'll just make it a Python dictionary in the wx module's namespace.
804 // (See __wxSetDictionary)
805 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
806 if (! wxPyPtrTypeMap
)
807 wxPyPtrTypeMap
= PyDict_New();
808 PyDict_SetItemString(wxPyPtrTypeMap
,
810 PyString_FromString((char*)ptrName
));
816 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
817 PyObject
* target
= NULL
;
818 bool isEvtHandler
= False
;
821 // If it's derived from wxEvtHandler then there may
822 // already be a pointer to a Python object that we can use
824 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
826 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
827 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
829 target
= data
->m_obj
;
836 // Otherwise make it the old fashioned way by making a new shadow
837 // object and putting this pointer in it. Look up the class
838 // heirarchy until we find a class name that is located in the
840 const wxClassInfo
* info
= source
->GetClassInfo();
841 wxString name
= info
->GetClassName();
842 bool exists
= wxPyCheckSwigType(name
);
843 while (info
&& !exists
) {
844 info
= info
->GetBaseClass1();
845 name
= info
->GetClassName();
846 exists
= wxPyCheckSwigType(name
);
849 target
= wxPyConstructObject((void*)source
, name
, False
);
850 if (target
&& isEvtHandler
)
851 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
853 wxString
msg(wxT("wxPython class not found for "));
854 msg
+= source
->GetClassInfo()->GetClassName();
855 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
859 } else { // source was NULL so return None.
860 Py_INCREF(Py_None
); target
= Py_None
;
866 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
867 PyObject
* target
= NULL
;
869 if (source
&& wxIsKindOf(source
, wxSizer
)) {
870 // If it's derived from wxSizer then there may already be a pointer to
871 // a Python object that we can use in the OOR data.
872 wxSizer
* sz
= (wxSizer
*)source
;
873 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
875 target
= data
->m_obj
;
881 target
= wxPyMake_wxObject(source
, False
);
882 if (target
!= Py_None
)
883 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
889 //---------------------------------------------------------------------------
892 #ifdef WXP_WITH_THREAD
894 unsigned long wxPyGetCurrentThreadId() {
895 return wxThread::GetCurrentId();
898 static PyThreadState
* gs_shutdownTState
;
901 PyThreadState
* wxPyGetThreadState() {
902 if (wxPyTMutex
== NULL
) // Python is shutting down...
903 return gs_shutdownTState
;
905 unsigned long ctid
= wxPyGetCurrentThreadId();
906 PyThreadState
* tstate
= NULL
;
909 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
910 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
911 if (info
.tid
== ctid
) {
912 tstate
= info
.tstate
;
916 wxPyTMutex
->Unlock();
917 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
922 void wxPySaveThreadState(PyThreadState
* tstate
) {
923 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
924 gs_shutdownTState
= tstate
;
927 unsigned long ctid
= wxPyGetCurrentThreadId();
929 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
930 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
931 if (info
.tid
== ctid
) {
933 if (info
.tstate
!= tstate
)
934 wxLogMessage("*** tstate mismatch!???");
936 // info.tstate = tstate; *** DO NOT update existing ones???
937 // Normally it will never change, but apparently COM callbacks
938 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
939 // tstate which will then be garbage the next time we try to use
941 wxPyTMutex
->Unlock();
945 // not found, so add it...
946 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
947 wxPyTMutex
->Unlock();
953 // Calls from Python to wxWindows code are wrapped in calls to these
956 PyThreadState
* wxPyBeginAllowThreads() {
957 #ifdef WXP_WITH_THREAD
958 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
959 wxPySaveThreadState(saved
);
966 void wxPyEndAllowThreads(PyThreadState
* saved
) {
967 #ifdef WXP_WITH_THREAD
968 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
974 // Calls from wxWindows back to Python code, or even any PyObject
975 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
977 void wxPyBeginBlockThreads() {
978 #ifdef WXP_WITH_THREAD
979 PyThreadState
* tstate
= wxPyGetThreadState();
980 PyEval_RestoreThread(tstate
);
985 void wxPyEndBlockThreads() {
986 #ifdef WXP_WITH_THREAD
987 // Is there any need to save it again?
988 // PyThreadState* tstate =
994 //---------------------------------------------------------------------------
995 // wxPyInputStream and wxPyCBInputStream methods
998 void wxPyInputStream::close() {
999 /* do nothing for now */
1002 void wxPyInputStream::flush() {
1003 /* do nothing for now */
1006 bool wxPyInputStream::eof() {
1008 return m_wxis
->Eof();
1013 wxPyInputStream::~wxPyInputStream() {
1020 PyObject
* wxPyInputStream::read(int size
) {
1021 PyObject
* obj
= NULL
;
1023 const int BUFSIZE
= 1024;
1025 // check if we have a real wxInputStream to work with
1027 wxPyBeginBlockThreads();
1028 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1029 wxPyEndBlockThreads();
1034 // read while bytes are available on the stream
1035 while ( m_wxis
->CanRead() ) {
1036 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1037 buf
.UngetAppendBuf(m_wxis
->LastRead());
1040 } else { // Read only size number of characters
1041 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1042 buf
.UngetWriteBuf(m_wxis
->LastRead());
1046 wxPyBeginBlockThreads();
1047 wxStreamError err
= m_wxis
->GetLastError();
1048 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1049 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1052 // We use only strings for the streams, not unicode
1053 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1055 wxPyEndBlockThreads();
1060 PyObject
* wxPyInputStream::readline(int size
) {
1061 PyObject
* obj
= NULL
;
1066 // check if we have a real wxInputStream to work with
1068 wxPyBeginBlockThreads();
1069 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1070 wxPyEndBlockThreads();
1074 // read until \n or byte limit reached
1075 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1076 ch
= m_wxis
->GetC();
1081 wxPyBeginBlockThreads();
1082 wxStreamError err
= m_wxis
->GetLastError();
1083 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1084 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1087 // We use only strings for the streams, not unicode
1088 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1090 wxPyEndBlockThreads();
1095 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1098 // check if we have a real wxInputStream to work with
1100 wxPyBeginBlockThreads();
1101 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1102 wxPyEndBlockThreads();
1107 wxPyBeginBlockThreads();
1108 pylist
= PyList_New(0);
1110 wxPyBeginBlockThreads();
1112 wxPyEndBlockThreads();
1116 // read sizehint bytes or until EOF
1118 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1119 PyObject
* s
= this->readline();
1121 wxPyBeginBlockThreads();
1123 wxPyEndBlockThreads();
1126 wxPyBeginBlockThreads();
1127 PyList_Append(pylist
, s
);
1128 i
+= PyString_Size(s
);
1129 wxPyEndBlockThreads();
1133 wxStreamError err
= m_wxis
->GetLastError();
1134 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1135 wxPyBeginBlockThreads();
1137 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1138 wxPyEndBlockThreads();
1146 void wxPyInputStream::seek(int offset
, int whence
) {
1148 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1151 int wxPyInputStream::tell(){
1153 return m_wxis
->TellI();
1160 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1161 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1165 wxPyCBInputStream::~wxPyCBInputStream() {
1166 if (m_block
) wxPyBeginBlockThreads();
1170 if (m_block
) wxPyEndBlockThreads();
1174 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1175 if (block
) wxPyBeginBlockThreads();
1177 PyObject
* read
= getMethod(py
, "read");
1178 PyObject
* seek
= getMethod(py
, "seek");
1179 PyObject
* tell
= getMethod(py
, "tell");
1182 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1186 if (block
) wxPyEndBlockThreads();
1190 if (block
) wxPyEndBlockThreads();
1191 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1195 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1196 return wxPyCBInputStream::create(py
, block
);
1199 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1200 if (!PyObject_HasAttrString(py
, name
))
1202 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1203 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1211 size_t wxPyCBInputStream::GetSize() const {
1212 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1213 if (m_seek
&& m_tell
) {
1214 off_t temp
= self
->OnSysTell();
1215 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1216 self
->OnSysSeek(temp
, wxFromStart
);
1224 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1228 wxPyBeginBlockThreads();
1229 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1230 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1234 if ((result
!= NULL
) && PyString_Check(result
)) {
1235 o
= PyString_Size(result
);
1237 m_lasterror
= wxSTREAM_EOF
;
1240 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1245 m_lasterror
= wxSTREAM_READ_ERROR
;
1246 wxPyEndBlockThreads();
1250 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1251 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1255 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1256 wxPyBeginBlockThreads();
1258 // off_t is a 64-bit value...
1259 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1261 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1263 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1266 wxPyEndBlockThreads();
1271 off_t
wxPyCBInputStream::OnSysTell() const {
1272 wxPyBeginBlockThreads();
1273 PyObject
* arglist
= Py_BuildValue("()");
1274 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1277 if (result
!= NULL
) {
1279 if (PyLong_Check(result
))
1280 o
= PyLong_AsLongLong(result
);
1283 o
= PyInt_AsLong(result
);
1287 wxPyEndBlockThreads();
1291 //----------------------------------------------------------------------
1293 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1295 wxPyCallback::wxPyCallback(PyObject
* func
) {
1300 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1301 m_func
= other
.m_func
;
1305 wxPyCallback::~wxPyCallback() {
1306 wxPyBeginBlockThreads();
1308 wxPyEndBlockThreads();
1313 // This function is used for all events destined for Python event handlers.
1314 void wxPyCallback::EventThunker(wxEvent
& event
) {
1315 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1316 PyObject
* func
= cb
->m_func
;
1320 bool checkSkip
= False
;
1322 wxPyBeginBlockThreads();
1323 wxString className
= event
.GetClassInfo()->GetClassName();
1325 // If the event is one of these types then pass the original
1326 // event object instead of the one passed to us.
1327 if ( className
== wxT("wxPyEvent") ) {
1328 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1329 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1331 else if ( className
== wxT("wxPyCommandEvent") ) {
1332 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1333 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1336 arg
= wxPyConstructObject((void*)&event
, className
);
1339 // Call the event handler, passing the event object
1340 tuple
= PyTuple_New(1);
1341 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1342 result
= PyEval_CallObject(func
, tuple
);
1344 Py_DECREF(result
); // result is ignored, but we still need to decref it
1345 PyErr_Clear(); // Just in case...
1351 // if the event object was one of our special types and
1352 // it had been cloned, then we need to extract the Skipped
1353 // value from the original and set it in the clone.
1354 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1356 event
.Skip(PyInt_AsLong(result
));
1364 wxPyEndBlockThreads();
1368 //----------------------------------------------------------------------
1370 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1372 m_self
= other
.m_self
;
1373 m_class
= other
.m_class
;
1381 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1392 #if PYTHON_API_VERSION >= 1011
1394 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1395 // in which the method was defined. Starting with 2.2 it returns
1396 // "class that asked for the method" which seems totally bogus to me
1397 // but apprently it fixes some obscure problem waiting to happen in
1398 // Python. Since the API was not documented Guido and the gang felt
1399 // safe in changing it. Needless to say that totally screwed up the
1400 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1401 // code to find the class where the method is actually defined...
1404 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1408 if (PyType_Check(klass
)) { // new style classes
1409 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1410 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1411 PyObject
*mro
, *res
, *base
, *dict
;
1412 /* Look in tp_dict of types in MRO */
1414 assert(PyTuple_Check(mro
));
1415 n
= PyTuple_GET_SIZE(mro
);
1416 for (i
= 0; i
< n
; i
++) {
1417 base
= PyTuple_GET_ITEM(mro
, i
);
1418 if (PyClass_Check(base
))
1419 dict
= ((PyClassObject
*)base
)->cl_dict
;
1421 assert(PyType_Check(base
));
1422 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1424 assert(dict
&& PyDict_Check(dict
));
1425 res
= PyDict_GetItem(dict
, name
);
1432 else if (PyClass_Check(klass
)) { // old style classes
1433 // This code is borrowed/adapted from class_lookup in classobject.c
1434 PyClassObject
* cp
= (PyClassObject
*)klass
;
1435 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1436 if (value
!= NULL
) {
1437 return (PyObject
*)cp
;
1439 n
= PyTuple_Size(cp
->cl_bases
);
1440 for (i
= 0; i
< n
; i
++) {
1441 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1442 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1454 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1456 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1458 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1460 #else // 2.2 and after, the hard way...
1462 PyObject
* nameo
= PyString_FromString(name
);
1463 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1471 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1472 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1473 self
->m_lastFound
= NULL
;
1475 // If the object (m_self) has an attibute of the given name...
1476 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1477 PyObject
*method
, *klass
;
1478 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1480 // ...and if that attribute is a method, and if that method's class is
1481 // not from a base class...
1482 if (PyMethod_Check(method
) &&
1483 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1484 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1486 // ...then we'll save a pointer to the method so callCallback can call it.
1487 self
->m_lastFound
= method
;
1493 return m_lastFound
!= NULL
;
1497 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1501 result
= callCallbackObj(argTuple
);
1502 if (result
) { // Assumes an integer return type...
1503 retval
= PyInt_AsLong(result
);
1505 PyErr_Clear(); // forget about it if it's not...
1510 // Invoke the Python callable object, returning the raw PyObject return
1511 // value. Caller should DECREF the return value and also manage the GIL.
1512 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1515 // Save a copy of the pointer in case the callback generates another
1516 // callback. In that case m_lastFound will have a different value when
1517 // it gets back here...
1518 PyObject
* method
= m_lastFound
;
1520 result
= PyEval_CallObject(method
, argTuple
);
1521 Py_DECREF(argTuple
);
1530 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1531 cbh
.setSelf(self
, klass
, incref
);
1534 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1535 return cbh
.findCallback(name
);
1538 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1539 return cbh
.callCallback(argTuple
);
1542 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1543 return cbh
.callCallbackObj(argTuple
);
1547 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1548 if (cbh
->m_incRef
) {
1549 wxPyBeginBlockThreads();
1550 Py_XDECREF(cbh
->m_self
);
1551 Py_XDECREF(cbh
->m_class
);
1552 wxPyEndBlockThreads();
1556 //---------------------------------------------------------------------------
1557 //---------------------------------------------------------------------------
1558 // These event classes can be derived from in Python and passed through the event
1559 // system without losing anything. They do this by keeping a reference to
1560 // themselves and some special case handling in wxPyCallback::EventThunker.
1563 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1564 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1565 //Py_INCREF(m_self); // circular loops...
1569 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1570 wxPyBeginBlockThreads();
1573 wxPyEndBlockThreads();
1576 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1577 wxPyBeginBlockThreads();
1585 wxPyEndBlockThreads();
1588 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1594 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1595 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1598 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1599 : wxEvent(winid
, commandType
) {
1603 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1606 SetSelf(evt
.m_self
, True
);
1610 wxPyEvent::~wxPyEvent() {
1614 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1615 : wxCommandEvent(commandType
, id
) {
1619 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1620 : wxCommandEvent(evt
)
1622 SetSelf(evt
.m_self
, True
);
1626 wxPyCommandEvent::~wxPyCommandEvent() {
1633 //---------------------------------------------------------------------------
1634 //---------------------------------------------------------------------------
1635 // Convert a wxList to a Python List, only works for lists of wxObjects
1637 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1638 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1642 wxNode
* node
= list
->GetFirst();
1644 wxPyBeginBlockThreads();
1645 pyList
= PyList_New(0);
1647 wxObj
= node
->GetData();
1648 pyObj
= wxPyMake_wxObject(wxObj
);
1649 PyList_Append(pyList
, pyObj
);
1650 node
= node
->GetNext();
1652 wxPyEndBlockThreads();
1656 //----------------------------------------------------------------------
1658 long wxPyGetWinHandle(wxWindow
* win
) {
1660 return (long)win
->GetHandle();
1663 // Find and return the actual X-Window.
1665 if (win
->m_wxwindow
) {
1667 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1669 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1671 return (long)bwin
->xwindow
;
1679 //----------------------------------------------------------------------
1680 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1681 // included in every file over and over again...
1683 #if PYTHON_API_VERSION >= 1009
1684 static char* wxStringErrorMsg
= "String or Unicode type required";
1686 static char* wxStringErrorMsg
= "String type required";
1690 wxString
* wxString_in_helper(PyObject
* source
) {
1692 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1693 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1694 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1698 if (PyUnicode_Check(source
)) {
1699 target
= new wxString();
1700 size_t len
= PyUnicode_GET_SIZE(source
);
1702 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1703 target
->UngetWriteBuf();
1706 // It is a string, get pointers to it and transform to unicode
1707 char* tmpPtr
; int tmpSize
;
1708 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1709 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1712 char* tmpPtr
; int tmpSize
;
1713 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1714 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1717 target
= new wxString(tmpPtr
, tmpSize
);
1718 #endif // wxUSE_UNICODE
1720 #else // No Python unicode API (1.5.2)
1721 if (!PyString_Check(source
)) {
1722 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1725 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1731 // Similar to above except doesn't use "new" and doesn't set an exception
1732 wxString
Py2wxString(PyObject
* source
)
1735 bool doDecRef
= False
;
1737 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1738 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1739 // Convert to String if not one already... (TODO: Unicode too?)
1740 source
= PyObject_Str(source
);
1745 if (PyUnicode_Check(source
)) {
1746 size_t len
= PyUnicode_GET_SIZE(source
);
1748 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1749 target
.UngetWriteBuf();
1752 // It is a string, get pointers to it and transform to unicode
1753 char* tmpPtr
; int tmpSize
;
1754 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1755 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1758 char* tmpPtr
; int tmpSize
;
1759 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1760 target
= wxString(tmpPtr
, tmpSize
);
1761 #endif // wxUSE_UNICODE
1763 #else // No Python unicode API (1.5.2)
1764 if (!PyString_Check(source
)) {
1765 // Convert to String if not one already...
1766 source
= PyObject_Str(source
);
1769 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1778 // Make either a Python String or Unicode object, depending on build mode
1779 PyObject
* wx2PyString(const wxString
& src
)
1783 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1785 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1791 //----------------------------------------------------------------------
1794 byte
* byte_LIST_helper(PyObject
* source
) {
1795 if (!PyList_Check(source
)) {
1796 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1799 int count
= PyList_Size(source
);
1800 byte
* temp
= new byte
[count
];
1802 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1805 for (int x
=0; x
<count
; x
++) {
1806 PyObject
* o
= PyList_GetItem(source
, x
);
1807 if (! PyInt_Check(o
)) {
1808 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1811 temp
[x
] = (byte
)PyInt_AsLong(o
);
1817 int* int_LIST_helper(PyObject
* source
) {
1818 if (!PyList_Check(source
)) {
1819 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1822 int count
= PyList_Size(source
);
1823 int* temp
= new int[count
];
1825 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1828 for (int x
=0; x
<count
; x
++) {
1829 PyObject
* o
= PyList_GetItem(source
, x
);
1830 if (! PyInt_Check(o
)) {
1831 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1834 temp
[x
] = PyInt_AsLong(o
);
1840 long* long_LIST_helper(PyObject
* source
) {
1841 if (!PyList_Check(source
)) {
1842 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1845 int count
= PyList_Size(source
);
1846 long* temp
= new long[count
];
1848 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1851 for (int x
=0; x
<count
; x
++) {
1852 PyObject
* o
= PyList_GetItem(source
, x
);
1853 if (! PyInt_Check(o
)) {
1854 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1857 temp
[x
] = PyInt_AsLong(o
);
1863 char** string_LIST_helper(PyObject
* source
) {
1864 if (!PyList_Check(source
)) {
1865 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1868 int count
= PyList_Size(source
);
1869 char** temp
= new char*[count
];
1871 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1874 for (int x
=0; x
<count
; x
++) {
1875 PyObject
* o
= PyList_GetItem(source
, x
);
1876 if (! PyString_Check(o
)) {
1877 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1880 temp
[x
] = PyString_AsString(o
);
1885 //--------------------------------
1886 // Part of patch from Tim Hochberg
1887 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1888 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1889 point
->x
= PyInt_AS_LONG(o1
);
1890 point
->y
= PyInt_AS_LONG(o2
);
1893 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1894 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1895 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1898 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1899 // Disallow instances because they can cause havok
1902 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1903 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1904 point
->x
= PyInt_AsLong(o1
);
1905 point
->y
= PyInt_AsLong(o2
);
1912 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1913 // Putting all of the declarations here allows
1914 // us to put the error handling all in one place.
1917 PyObject
*o
, *o1
, *o2
;
1918 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1920 if (!PySequence_Check(source
)) {
1924 // The length of the sequence is returned in count.
1925 *count
= PySequence_Length(source
);
1930 temp
= new wxPoint
[*count
];
1932 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1935 for (x
=0; x
<*count
; x
++) {
1936 // Get an item: try fast way first.
1938 o
= PySequence_Fast_GET_ITEM(source
, x
);
1941 o
= PySequence_GetItem(source
, x
);
1947 // Convert o to wxPoint.
1948 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1949 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1950 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1951 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1952 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1956 else if (wxPySwigInstance_Check(o
)) {
1958 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1963 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1964 o1
= PySequence_GetItem(o
, 0);
1965 o2
= PySequence_GetItem(o
, 1);
1966 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1990 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
1994 //------------------------------
1997 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
1998 if (!PyList_Check(source
)) {
1999 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2002 int count
= PyList_Size(source
);
2003 wxBitmap
** temp
= new wxBitmap
*[count
];
2005 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2008 for (int x
=0; x
<count
; x
++) {
2009 PyObject
* o
= PyList_GetItem(source
, x
);
2010 if (wxPySwigInstance_Check(o
)) {
2012 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2013 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2019 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2028 wxString
* wxString_LIST_helper(PyObject
* source
) {
2029 if (!PyList_Check(source
)) {
2030 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2033 int count
= PyList_Size(source
);
2034 wxString
* temp
= new wxString
[count
];
2036 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2039 for (int x
=0; x
<count
; x
++) {
2040 PyObject
* o
= PyList_GetItem(source
, x
);
2041 #if PYTHON_API_VERSION >= 1009
2042 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2043 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2047 if (! PyString_Check(o
)) {
2048 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2053 wxString
* pStr
= wxString_in_helper(o
);
2061 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2062 if (!PyList_Check(source
)) {
2063 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2066 int count
= PyList_Size(source
);
2067 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2069 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2072 for (int x
=0; x
<count
; x
++) {
2073 PyObject
* o
= PyList_GetItem(source
, x
);
2074 if (wxPySwigInstance_Check(o
)) {
2075 wxAcceleratorEntry
* ae
;
2076 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2077 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2082 else if (PyTuple_Check(o
)) {
2083 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2084 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2085 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2086 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2089 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2097 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2098 if (!PyList_Check(source
)) {
2099 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2102 int count
= PyList_Size(source
);
2103 wxPen
** temp
= new wxPen
*[count
];
2105 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2108 for (int x
=0; x
<count
; x
++) {
2109 PyObject
* o
= PyList_GetItem(source
, x
);
2110 if (wxPySwigInstance_Check(o
)) {
2112 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2114 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2121 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2129 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2130 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2133 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2137 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2138 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2141 o1
= PySequence_GetItem(source
, 0);
2142 o2
= PySequence_GetItem(source
, 1);
2145 *i1
= PyInt_AsLong(o1
);
2146 *i2
= PyInt_AsLong(o2
);
2156 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2157 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2158 PyObject
*o1
, *o2
, *o3
, *o4
;
2160 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2164 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2165 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2166 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2167 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2170 o1
= PySequence_GetItem(source
, 0);
2171 o2
= PySequence_GetItem(source
, 1);
2172 o3
= PySequence_GetItem(source
, 2);
2173 o4
= PySequence_GetItem(source
, 3);
2176 *i1
= PyInt_AsLong(o1
);
2177 *i2
= PyInt_AsLong(o2
);
2178 *i3
= PyInt_AsLong(o3
);
2179 *i4
= PyInt_AsLong(o4
);
2191 //----------------------------------------------------------------------
2193 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2197 if (wxPySwigInstance_Check(source
) &&
2198 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2202 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2208 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2210 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2214 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2216 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2221 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2223 // If source is an object instance then it may already be the right type
2224 if (wxPySwigInstance_Check(source
)) {
2226 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2231 // otherwise a 2-tuple of floats is expected
2232 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2233 PyObject
* o1
= PySequence_GetItem(source
, 0);
2234 PyObject
* o2
= PySequence_GetItem(source
, 1);
2235 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2240 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2247 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2253 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2255 // If source is an object instance then it may already be the right type
2256 if (wxPySwigInstance_Check(source
)) {
2258 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2263 // otherwise a 4-tuple of integers is expected
2264 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2265 PyObject
* o1
= PySequence_GetItem(source
, 0);
2266 PyObject
* o2
= PySequence_GetItem(source
, 1);
2267 PyObject
* o3
= PySequence_GetItem(source
, 2);
2268 PyObject
* o4
= PySequence_GetItem(source
, 3);
2269 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2270 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2277 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2278 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2287 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2293 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2295 // If source is an object instance then it may already be the right type
2296 if (wxPySwigInstance_Check(source
)) {
2298 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2303 // otherwise check for a string
2304 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2305 wxString spec
= Py2wxString(source
);
2306 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2307 long red
, green
, blue
;
2308 red
= green
= blue
= 0;
2309 spec
.Mid(1,2).ToLong(&red
, 16);
2310 spec
.Mid(3,2).ToLong(&green
, 16);
2311 spec
.Mid(5,2).ToLong(&blue
, 16);
2313 **obj
= wxColour(red
, green
, blue
);
2316 else { // it's a colour name
2317 **obj
= wxColour(spec
);
2321 // last chance: 3-tuple of integers is expected
2322 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2323 PyObject
* o1
= PySequence_GetItem(source
, 0);
2324 PyObject
* o2
= PySequence_GetItem(source
, 1);
2325 PyObject
* o3
= PySequence_GetItem(source
, 2);
2326 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2332 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2340 PyErr_SetString(PyExc_TypeError
,
2341 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2346 bool wxColour_typecheck(PyObject
* source
) {
2348 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2351 if (PyString_Check(source
) || PyUnicode_Check(source
))
2359 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2360 // If source is an object instance then it may already be the right type
2361 if (wxPySwigInstance_Check(source
)) {
2363 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2368 // otherwise a length-2 sequence of floats is expected
2369 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2370 PyObject
* o1
= PySequence_GetItem(source
, 0);
2371 PyObject
* o2
= PySequence_GetItem(source
, 1);
2372 // This should really check for floats, not numbers -- but that would break code.
2373 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2378 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2384 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2389 //----------------------------------------------------------------------
2391 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2393 PyObject
* list
= PyList_New(0);
2394 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2396 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2398 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2400 PyList_Append(list
, str
);
2407 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2409 PyObject
* list
= PyList_New(0);
2410 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2411 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2412 PyList_Append(list
, number
);
2419 //----------------------------------------------------------------------
2420 //----------------------------------------------------------------------