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>
32 #include <wx/mac/private.h>
35 #include <wx/clipbrd.h>
36 #include <wx/mimetype.h>
39 //----------------------------------------------------------------------
41 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
42 #error Python must support Unicode to use wxWindows Unicode
45 //----------------------------------------------------------------------
47 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
48 bool wxPyDoCleanup
= False
;
49 bool wxPyDoingCleanup
= False
;
52 #ifdef WXP_WITH_THREAD
53 struct wxPyThreadState
{
55 PyThreadState
* tstate
;
58 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
59 : tid(_tid
), tstate(_tstate
), blocked(1) {}
62 #include <wx/dynarray.h>
63 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
64 #include <wx/arrimpl.cpp>
65 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
67 wxPyThreadStateArray
* wxPyTStates
= NULL
;
68 wxMutex
* wxPyTMutex
= NULL
;
72 static PyObject
* wxPython_dict
= NULL
;
73 static PyObject
* wxPyAssertionError
= NULL
;
75 PyObject
* wxPyPtrTypeMap
= NULL
;
78 #ifdef __WXMSW__ // If building for win32...
79 //----------------------------------------------------------------------
80 // This gets run when the DLL is loaded. We just need to save a handle.
81 //----------------------------------------------------------------------
84 HINSTANCE hinstDLL
, // handle to DLL module
85 DWORD fdwReason
, // reason for calling function
86 LPVOID lpvReserved
// reserved
89 // If wxPython is embedded in another wxWindows app then
90 // the inatance has already been set.
91 if (! wxGetInstance())
92 wxSetInstance(hinstDLL
);
97 //----------------------------------------------------------------------
98 // Classes for implementing the wxp main application shell.
99 //----------------------------------------------------------------------
101 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
105 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
106 m_startupComplete
= False
;
110 wxPyApp::~wxPyApp() {
114 // This one isn't acutally called... We fake it with _BootstrapApp
115 bool wxPyApp::OnInit() {
120 int wxPyApp::MainLoop() {
123 DeletePendingObjects();
124 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
126 if ( m_exitOnFrameDelete
== Later
) {
127 m_exitOnFrameDelete
= Yes
;
130 retval
= wxApp::MainLoop();
137 bool wxPyApp::OnInitGui() {
139 wxApp::OnInitGui(); // in this case always call the base class version
140 wxPyBeginBlockThreads();
141 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
142 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
143 wxPyEndBlockThreads();
148 int wxPyApp::OnExit() {
150 wxPyBeginBlockThreads();
151 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
152 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
153 wxPyEndBlockThreads();
154 wxApp::OnExit(); // in this case always call the base class version
160 void wxPyApp::OnAssert(const wxChar
*file
,
165 // if we're not fully initialized then just log the error
166 if (! m_startupComplete
) {
169 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
179 // If the OnAssert is overloaded in the Python class then call it...
181 wxPyBeginBlockThreads();
182 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
183 PyObject
* fso
= wx2PyString(file
);
184 PyObject
* cso
= wx2PyString(file
);
187 mso
= wx2PyString(file
);
189 mso
= Py_None
; Py_INCREF(Py_None
);
191 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
196 wxPyEndBlockThreads();
198 // ...otherwise do our own thing with it
201 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
204 // turn it into a Python exception?
205 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
208 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
215 wxPyBeginBlockThreads();
216 PyObject
* s
= wx2PyString(buf
);
217 PyErr_SetObject(wxPyAssertionError
, s
);
219 wxPyEndBlockThreads();
221 // Now when control returns to whatever API wrapper was called from
222 // Python it should detect that an exception is set and will return
223 // NULL, signalling the exception to Python.
226 // Send it to the normal log destination, but only if
227 // not _DIALOG because it will call this too
228 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
231 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
240 // do the normal wx assert dialog?
241 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
242 wxApp::OnAssert(file
, line
, cond
, msg
);
250 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
252 return s_macSupportPCMenuShortcuts
;
259 long wxPyApp::GetMacAboutMenuItemId() {
261 return s_macAboutMenuItemId
;
268 long wxPyApp::GetMacPreferencesMenuItemId() {
270 return s_macPreferencesMenuItemId
;
277 long wxPyApp::GetMacExitMenuItemId() {
279 return s_macExitMenuItemId
;
286 wxString
wxPyApp::GetMacHelpMenuTitleName() {
288 return s_macHelpMenuTitleName
;
290 return wxEmptyString
;
295 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
297 s_macSupportPCMenuShortcuts
= val
;
302 void wxPyApp::SetMacAboutMenuItemId(long val
) {
304 s_macAboutMenuItemId
= val
;
309 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
311 s_macPreferencesMenuItemId
= val
;
316 void wxPyApp::SetMacExitMenuItemId(long val
) {
318 s_macExitMenuItemId
= val
;
323 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
325 s_macHelpMenuTitleName
= val
;
330 // This finishes the initialization of wxWindows and then calls the OnInit
331 // that should be present in the derived (Python) class.
332 void wxPyApp::_BootstrapApp()
335 PyObject
* retval
= NULL
;
336 PyObject
* pyint
= NULL
;
339 // Get any command-line args passed to this program from the sys module
342 wxPyBeginBlockThreads();
343 PyObject
* sysargv
= PySys_GetObject("argv");
344 if (sysargv
!= NULL
) {
345 argc
= PyList_Size(sysargv
);
346 argv
= new char*[argc
+1];
348 for(x
=0; x
<argc
; x
++) {
349 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
350 argv
[x
] = PyString_AsString(pyArg
);
354 wxPyEndBlockThreads();
356 result
= wxEntryStart(argc
, argv
);
359 wxPyBeginBlockThreads();
361 PyErr_SetString(PyExc_SystemError
, "wxEntryStart failed!");
365 // The stock objects were all NULL when they were loaded into
366 // SWIG generated proxies, so re-init those now...
367 wxPy_ReinitStockObjects(3);
369 // It's now ok to generate exceptions for assertion errors.
370 wxPythonApp
->SetStartupComplete(True
);
372 // Call the Python wxApp's OnInit function
373 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
375 PyObject
* method
= m_myInst
.GetLastFound();
376 PyObject
* argTuple
= PyTuple_New(0);
377 retval
= PyEval_CallObject(method
, argTuple
);
383 pyint
= PyNumber_Int(retval
);
385 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
388 result
= PyInt_AS_LONG(pyint
);
391 // Is it okay if there is no OnInit? Probably so...
397 PyErr_SetString(PyExc_SystemExit
, "OnInit returned False, exiting...");
404 wxPyEndBlockThreads();
407 //---------------------------------------------------------------------
408 //----------------------------------------------------------------------
412 static char* wxPyCopyCString(const wxChar
* src
)
414 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
415 size_t len
= strlen(buff
);
416 char* dest
= new char[len
+1];
422 static char* wxPyCopyCString(const char* src
) // we need a char version too
424 size_t len
= strlen(src
);
425 char* dest
= new char[len
+1];
431 static wxChar
* wxPyCopyWString(const char *src
)
433 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
434 wxString
str(src
, *wxConvCurrent
);
435 return copystring(str
);
439 static wxChar
* wxPyCopyWString(const wxChar
*src
)
441 return copystring(src
);
447 inline const char* dropwx(const char* name
) {
448 if (name
[0] == 'w' && name
[1] == 'x')
454 //----------------------------------------------------------------------
456 // This function is called when the wxc module is imported to do some initial
457 // setup. (Before there is a wxApp object.) The rest happens in
458 // wxPyApp::_BootstrapApp
459 void __wxPyPreStart(PyObject
* moduleDict
)
463 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
466 #ifdef WXP_WITH_THREAD
467 PyEval_InitThreads();
468 wxPyTStates
= new wxPyThreadStateArray
;
469 wxPyTMutex
= new wxMutex
;
471 // Save the current (main) thread state in our array
472 PyThreadState
* tstate
= wxPyBeginAllowThreads();
473 wxPyEndAllowThreads(tstate
);
476 // Ensure that the build options in the DLL (or whatever) match this build
477 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
479 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
480 wxPy_ReinitStockObjects(1);
485 void __wxPyCleanup() {
486 wxPyDoingCleanup
= True
;
488 wxPyDoCleanup
= False
;
491 #ifdef WXP_WITH_THREAD
494 wxPyTStates
->Empty();
501 // Save a reference to the dictionary of the wx.core module, and inject
502 // a few more things into it.
503 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
506 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
509 if (!PyDict_Check(wxPython_dict
)) {
510 PyErr_SetString(PyExc_TypeError
, "_wxPySetDictionary must have dictionary object!");
514 if (! wxPyPtrTypeMap
)
515 wxPyPtrTypeMap
= PyDict_New();
516 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
518 // Create an exception object to use for wxASSERTions
519 wxPyAssertionError
= PyErr_NewException("wx.core.PyAssertionError",
520 PyExc_AssertionError
, NULL
);
521 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
525 #define wxPlatform "__WXMOTIF__"
528 #define wxPlatform "__WXX11__"
531 #define wxPlatform "__WXGTK__"
533 #if defined(__WIN32__) || defined(__WXMSW__)
534 #define wxPlatform "__WXMSW__"
537 #define wxPlatform "__WXMAC__"
546 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
547 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
548 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
554 //---------------------------------------------------------------------------
556 // Python's PyInstance_Check does not return True for instances of new-style
557 // classes. This should get close enough for both new and old classes but I
558 // should re-evaluate the need for doing instance checks...
559 bool wxPyInstance_Check(PyObject
* obj
) {
560 return PyObject_HasAttrString(obj
, "__class__") != 0;
564 // This one checks if the object is an instance of a SWIG proxy class (it has
565 // a .this attribute)
566 bool wxPySwigInstance_Check(PyObject
* obj
) {
567 return PyObject_HasAttrString(obj
, "this") != 0;
570 //---------------------------------------------------------------------------
572 // The stock objects are no longer created when the wxc module is imported,
573 // but only after the app object has been created. The
574 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
575 // objects though various stages of evolution:
577 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
578 // object will be created (otherwise it will just use None.)
580 // pass 2: After the module has been imported and the python proxys have
581 // been created, then set the __class__ to be _wxPyUnbornObject so
582 // it will catch any access to the object and will raise an exception.
584 // pass 3: Finally, from OnInit patch things up so the stock objects can
588 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
590 wxPy_ReinitStockObjects(2);
595 static void rsoPass2(const char* name
)
597 static PyObject
* unbornObjectClass
= NULL
;
600 if (unbornObjectClass
== NULL
) {
601 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
602 Py_INCREF(unbornObjectClass
);
605 // Find the object instance
606 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
607 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
608 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
611 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
615 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
621 // Find the object instance
622 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
623 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
624 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
626 // Find the class object and put it back in the instance
627 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
628 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
629 PyObject_SetAttrString(obj
, "__class__", classobj
);
631 // Rebuild the .this swigified pointer with the new value of the C++ pointer
632 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
633 PyObject_SetAttrString(obj
, "this", ptrobj
);
639 void wxPy_ReinitStockObjects(int pass
)
642 #define REINITOBJ(name, classname) \
643 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
644 else if (pass == 2) { rsoPass2(#name); } \
645 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
648 #define REINITOBJ2(name, classname) \
650 else if (pass == 2) { rsoPass2(#name); } \
651 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
654 REINITOBJ(wxNORMAL_FONT
, wxFont
);
655 REINITOBJ(wxSMALL_FONT
, wxFont
);
656 REINITOBJ(wxITALIC_FONT
, wxFont
);
657 REINITOBJ(wxSWISS_FONT
, wxFont
);
659 REINITOBJ(wxRED_PEN
, wxPen
);
660 REINITOBJ(wxCYAN_PEN
, wxPen
);
661 REINITOBJ(wxGREEN_PEN
, wxPen
);
662 REINITOBJ(wxBLACK_PEN
, wxPen
);
663 REINITOBJ(wxWHITE_PEN
, wxPen
);
664 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
665 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
666 REINITOBJ(wxGREY_PEN
, wxPen
);
667 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
668 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
670 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
671 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
672 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
673 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
674 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
675 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
676 REINITOBJ(wxRED_BRUSH
, wxBrush
);
677 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
678 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
679 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
681 REINITOBJ(wxBLACK
, wxColour
);
682 REINITOBJ(wxWHITE
, wxColour
);
683 REINITOBJ(wxRED
, wxColour
);
684 REINITOBJ(wxBLUE
, wxColour
);
685 REINITOBJ(wxGREEN
, wxColour
);
686 REINITOBJ(wxCYAN
, wxColour
);
687 REINITOBJ(wxLIGHT_GREY
, wxColour
);
689 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
690 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
691 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
693 REINITOBJ2(wxNullBitmap
, wxBitmap
);
694 REINITOBJ2(wxNullIcon
, wxIcon
);
695 REINITOBJ2(wxNullCursor
, wxCursor
);
696 REINITOBJ2(wxNullPen
, wxPen
);
697 REINITOBJ2(wxNullBrush
, wxBrush
);
698 REINITOBJ2(wxNullPalette
, wxPalette
);
699 REINITOBJ2(wxNullFont
, wxFont
);
700 REINITOBJ2(wxNullColour
, wxColour
);
702 REINITOBJ(wxTheFontList
, wxFontList
);
703 REINITOBJ(wxThePenList
, wxPenList
);
704 REINITOBJ(wxTheBrushList
, wxBrushList
);
705 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
708 REINITOBJ(wxTheClipboard
, wxClipboard
);
709 REINITOBJ2(wxDefaultValidator
, wxValidator
);
710 REINITOBJ2(wxNullImage
, wxImage
);
711 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
717 //---------------------------------------------------------------------------
719 void wxPyClientData_dtor(wxPyClientData
* self
) {
720 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
721 // may have already garbage collected the object...
722 wxPyBeginBlockThreads();
723 Py_DECREF(self
->m_obj
);
725 wxPyEndBlockThreads();
729 void wxPyUserData_dtor(wxPyUserData
* self
) {
730 if (! wxPyDoingCleanup
) {
731 wxPyBeginBlockThreads();
732 Py_DECREF(self
->m_obj
);
734 wxPyEndBlockThreads();
739 // This is called when an OOR controled object is being destroyed. Although
740 // the C++ object is going away there is no way to force the Python object
741 // (and all references to it) to die too. This causes problems (crashes) in
742 // wxPython when a python shadow object attempts to call a C++ method using
743 // the now bogus pointer... So to try and prevent this we'll do a little black
744 // magic and change the class of the python instance to a class that will
745 // raise an exception for any attempt to call methods with it. See
746 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
747 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
749 static PyObject
* deadObjectClass
= NULL
;
751 wxPyBeginBlockThreads();
752 if (deadObjectClass
== NULL
) {
753 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
754 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
755 // will lead to a deadlock when it tries to aquire the GIL again.
756 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
757 Py_INCREF(deadObjectClass
);
761 // Only if there is more than one reference to the object
762 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
763 // bool isInstance = wxPyInstance_Check(self->m_obj);
765 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
767 // Call __del__, if there is one.
768 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
770 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
774 if (PyErr_Occurred())
775 PyErr_Clear(); // just ignore it for now
778 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
780 // Clear the instance's dictionary
783 // put the name of the old class into the instance, and then reset the
784 // class to be the dead class.
785 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
786 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
787 PyDict_SetItemString(dict
, "_name", name
);
788 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
789 //Py_INCREF(deadObjectClass);
795 // m_obj is DECREF'd in the base class dtor...
796 wxPyEndBlockThreads();
800 //---------------------------------------------------------------------------
801 // Stuff used by OOR to find the right wxPython class type to return and to
805 // The pointer type map is used when the "pointer" type name generated by SWIG
806 // is not the same as the shadow class name, for example wxPyTreeCtrl
807 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
808 // so we'll just make it a Python dictionary in the wx module's namespace.
809 // (See __wxSetDictionary)
810 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
811 if (! wxPyPtrTypeMap
)
812 wxPyPtrTypeMap
= PyDict_New();
813 PyDict_SetItemString(wxPyPtrTypeMap
,
815 PyString_FromString((char*)ptrName
));
821 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
822 PyObject
* target
= NULL
;
823 bool isEvtHandler
= False
;
826 // If it's derived from wxEvtHandler then there may
827 // already be a pointer to a Python object that we can use
829 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
831 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
832 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
834 target
= data
->m_obj
;
841 // Otherwise make it the old fashioned way by making a new shadow
842 // object and putting this pointer in it. Look up the class
843 // heirarchy until we find a class name that is located in the
845 const wxClassInfo
* info
= source
->GetClassInfo();
846 wxString name
= info
->GetClassName();
847 bool exists
= wxPyCheckSwigType(name
);
848 while (info
&& !exists
) {
849 info
= info
->GetBaseClass1();
850 name
= info
->GetClassName();
851 exists
= wxPyCheckSwigType(name
);
854 target
= wxPyConstructObject((void*)source
, name
, False
);
855 if (target
&& isEvtHandler
)
856 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
858 wxString
msg(wxT("wxPython class not found for "));
859 msg
+= source
->GetClassInfo()->GetClassName();
860 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
864 } else { // source was NULL so return None.
865 Py_INCREF(Py_None
); target
= Py_None
;
871 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
872 PyObject
* target
= NULL
;
874 if (source
&& wxIsKindOf(source
, wxSizer
)) {
875 // If it's derived from wxSizer then there may already be a pointer to
876 // a Python object that we can use in the OOR data.
877 wxSizer
* sz
= (wxSizer
*)source
;
878 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
880 target
= data
->m_obj
;
886 target
= wxPyMake_wxObject(source
, False
);
887 if (target
!= Py_None
)
888 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
894 //---------------------------------------------------------------------------
897 #ifdef WXP_WITH_THREAD
899 unsigned long wxPyGetCurrentThreadId() {
900 return wxThread::GetCurrentId();
903 static wxPyThreadState gs_shutdownTState
;
906 wxPyThreadState
* wxPyGetThreadState() {
907 if (wxPyTMutex
== NULL
) // Python is shutting down...
908 return &gs_shutdownTState
;
910 unsigned long ctid
= wxPyGetCurrentThreadId();
911 wxPyThreadState
* tstate
= NULL
;
914 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
915 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
916 if (info
.tid
== ctid
) {
921 wxPyTMutex
->Unlock();
922 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
928 void wxPySaveThreadState(PyThreadState
* tstate
) {
929 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
930 gs_shutdownTState
.tstate
= tstate
;
933 unsigned long ctid
= wxPyGetCurrentThreadId();
935 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
936 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
937 if (info
.tid
== ctid
) {
939 if (info
.tstate
!= tstate
)
940 wxLogMessage("*** tstate mismatch!???");
942 // info.tstate = tstate; *** DO NOT update existing ones???
943 // Normally it will never change, but apparently COM callbacks
944 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
945 // tstate which will then be garbage the next time we try to use
947 wxPyTMutex
->Unlock();
951 // not found, so add it...
952 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
953 wxPyTMutex
->Unlock();
960 // Calls from Python to wxWindows code are wrapped in calls to these
963 PyThreadState
* wxPyBeginAllowThreads() {
964 #ifdef WXP_WITH_THREAD
965 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
966 wxPySaveThreadState(saved
);
967 wxPyGetThreadState()->blocked
-= 1;
974 void wxPyEndAllowThreads(PyThreadState
* saved
) {
975 #ifdef WXP_WITH_THREAD
976 wxPyGetThreadState()->blocked
+= 1;
977 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
983 // Calls from wxWindows back to Python code, or even any PyObject
984 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
986 void wxPyBeginBlockThreads() {
987 #ifdef WXP_WITH_THREAD
988 wxPyThreadState
* tstate
= wxPyGetThreadState();
989 if (tstate
->blocked
++ == 0) { // if nested calls then do nothing
990 PyEval_RestoreThread(tstate
->tstate
);
996 void wxPyEndBlockThreads() {
997 #ifdef WXP_WITH_THREAD
998 wxPyThreadState
* tstate
= wxPyGetThreadState();
999 tstate
->blocked
-= 1;
1000 if ( tstate
->blocked
== 0) { // if nested calls then do nothing
1001 PyEval_SaveThread();
1007 //---------------------------------------------------------------------------
1008 // wxPyInputStream and wxPyCBInputStream methods
1011 void wxPyInputStream::close() {
1012 /* do nothing for now */
1015 void wxPyInputStream::flush() {
1016 /* do nothing for now */
1019 bool wxPyInputStream::eof() {
1021 return m_wxis
->Eof();
1026 wxPyInputStream::~wxPyInputStream() {
1033 PyObject
* wxPyInputStream::read(int size
) {
1034 PyObject
* obj
= NULL
;
1036 const int BUFSIZE
= 1024;
1038 // check if we have a real wxInputStream to work with
1040 wxPyBeginBlockThreads();
1041 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1042 wxPyEndBlockThreads();
1047 // read while bytes are available on the stream
1048 while ( m_wxis
->CanRead() ) {
1049 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1050 buf
.UngetAppendBuf(m_wxis
->LastRead());
1053 } else { // Read only size number of characters
1054 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1055 buf
.UngetWriteBuf(m_wxis
->LastRead());
1059 wxPyBeginBlockThreads();
1060 wxStreamError err
= m_wxis
->GetLastError();
1061 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1062 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1065 // We use only strings for the streams, not unicode
1066 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1068 wxPyEndBlockThreads();
1073 PyObject
* wxPyInputStream::readline(int size
) {
1074 PyObject
* obj
= NULL
;
1079 // check if we have a real wxInputStream to work with
1081 wxPyBeginBlockThreads();
1082 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1083 wxPyEndBlockThreads();
1087 // read until \n or byte limit reached
1088 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1089 ch
= m_wxis
->GetC();
1094 wxPyBeginBlockThreads();
1095 wxStreamError err
= m_wxis
->GetLastError();
1096 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1097 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1100 // We use only strings for the streams, not unicode
1101 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1103 wxPyEndBlockThreads();
1108 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1111 // check if we have a real wxInputStream to work with
1113 wxPyBeginBlockThreads();
1114 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1115 wxPyEndBlockThreads();
1120 wxPyBeginBlockThreads();
1121 pylist
= PyList_New(0);
1123 wxPyBeginBlockThreads();
1125 wxPyEndBlockThreads();
1129 // read sizehint bytes or until EOF
1131 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1132 PyObject
* s
= this->readline();
1134 wxPyBeginBlockThreads();
1136 wxPyEndBlockThreads();
1139 wxPyBeginBlockThreads();
1140 PyList_Append(pylist
, s
);
1141 i
+= PyString_Size(s
);
1142 wxPyEndBlockThreads();
1146 wxStreamError err
= m_wxis
->GetLastError();
1147 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1148 wxPyBeginBlockThreads();
1150 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1151 wxPyEndBlockThreads();
1159 void wxPyInputStream::seek(int offset
, int whence
) {
1161 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1164 int wxPyInputStream::tell(){
1166 return m_wxis
->TellI();
1173 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1174 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1178 wxPyCBInputStream::~wxPyCBInputStream() {
1179 if (m_block
) wxPyBeginBlockThreads();
1183 if (m_block
) wxPyEndBlockThreads();
1187 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1188 if (block
) wxPyBeginBlockThreads();
1190 PyObject
* read
= getMethod(py
, "read");
1191 PyObject
* seek
= getMethod(py
, "seek");
1192 PyObject
* tell
= getMethod(py
, "tell");
1195 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1199 if (block
) wxPyEndBlockThreads();
1203 if (block
) wxPyEndBlockThreads();
1204 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1208 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1209 return wxPyCBInputStream::create(py
, block
);
1212 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1213 if (!PyObject_HasAttrString(py
, name
))
1215 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1216 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1224 size_t wxPyCBInputStream::GetSize() const {
1225 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1226 if (m_seek
&& m_tell
) {
1227 off_t temp
= self
->OnSysTell();
1228 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1229 self
->OnSysSeek(temp
, wxFromStart
);
1237 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1241 wxPyBeginBlockThreads();
1242 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1243 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1247 if ((result
!= NULL
) && PyString_Check(result
)) {
1248 o
= PyString_Size(result
);
1250 m_lasterror
= wxSTREAM_EOF
;
1253 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1258 m_lasterror
= wxSTREAM_READ_ERROR
;
1259 wxPyEndBlockThreads();
1263 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1264 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1268 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1269 wxPyBeginBlockThreads();
1271 // off_t is a 64-bit value...
1272 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1274 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1276 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1279 wxPyEndBlockThreads();
1284 off_t
wxPyCBInputStream::OnSysTell() const {
1285 wxPyBeginBlockThreads();
1286 PyObject
* arglist
= Py_BuildValue("()");
1287 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1290 if (result
!= NULL
) {
1292 if (PyLong_Check(result
))
1293 o
= PyLong_AsLongLong(result
);
1296 o
= PyInt_AsLong(result
);
1299 wxPyEndBlockThreads();
1303 //----------------------------------------------------------------------
1305 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1307 wxPyCallback::wxPyCallback(PyObject
* func
) {
1312 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1313 m_func
= other
.m_func
;
1317 wxPyCallback::~wxPyCallback() {
1318 wxPyBeginBlockThreads();
1320 wxPyEndBlockThreads();
1325 // This function is used for all events destined for Python event handlers.
1326 void wxPyCallback::EventThunker(wxEvent
& event
) {
1327 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1328 PyObject
* func
= cb
->m_func
;
1332 bool checkSkip
= False
;
1334 wxPyBeginBlockThreads();
1335 wxString className
= event
.GetClassInfo()->GetClassName();
1337 // If the event is one of these types then pass the original
1338 // event object instead of the one passed to us.
1339 if ( className
== wxT("wxPyEvent") ) {
1340 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1341 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1343 else if ( className
== wxT("wxPyCommandEvent") ) {
1344 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1345 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1348 arg
= wxPyConstructObject((void*)&event
, className
);
1354 // Call the event handler, passing the event object
1355 tuple
= PyTuple_New(1);
1356 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1357 result
= PyEval_CallObject(func
, tuple
);
1359 Py_DECREF(result
); // result is ignored, but we still need to decref it
1360 PyErr_Clear(); // Just in case...
1366 // if the event object was one of our special types and
1367 // it had been cloned, then we need to extract the Skipped
1368 // value from the original and set it in the clone.
1369 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1371 event
.Skip(PyInt_AsLong(result
));
1379 wxPyEndBlockThreads();
1383 //----------------------------------------------------------------------
1385 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1387 m_self
= other
.m_self
;
1388 m_class
= other
.m_class
;
1396 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1407 #if PYTHON_API_VERSION >= 1011
1409 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1410 // in which the method was defined. Starting with 2.2 it returns
1411 // "class that asked for the method" which seems totally bogus to me
1412 // but apprently it fixes some obscure problem waiting to happen in
1413 // Python. Since the API was not documented Guido and the gang felt
1414 // safe in changing it. Needless to say that totally screwed up the
1415 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1416 // code to find the class where the method is actually defined...
1419 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1423 if (PyType_Check(klass
)) { // new style classes
1424 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1425 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1426 PyObject
*mro
, *res
, *base
, *dict
;
1427 /* Look in tp_dict of types in MRO */
1429 assert(PyTuple_Check(mro
));
1430 n
= PyTuple_GET_SIZE(mro
);
1431 for (i
= 0; i
< n
; i
++) {
1432 base
= PyTuple_GET_ITEM(mro
, i
);
1433 if (PyClass_Check(base
))
1434 dict
= ((PyClassObject
*)base
)->cl_dict
;
1436 assert(PyType_Check(base
));
1437 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1439 assert(dict
&& PyDict_Check(dict
));
1440 res
= PyDict_GetItem(dict
, name
);
1447 else if (PyClass_Check(klass
)) { // old style classes
1448 // This code is borrowed/adapted from class_lookup in classobject.c
1449 PyClassObject
* cp
= (PyClassObject
*)klass
;
1450 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1451 if (value
!= NULL
) {
1452 return (PyObject
*)cp
;
1454 n
= PyTuple_Size(cp
->cl_bases
);
1455 for (i
= 0; i
< n
; i
++) {
1456 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1457 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1469 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1471 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1473 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1475 #else // 2.2 and after, the hard way...
1477 PyObject
* nameo
= PyString_FromString(name
);
1478 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1486 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1487 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1488 self
->m_lastFound
= NULL
;
1490 // If the object (m_self) has an attibute of the given name...
1491 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1492 PyObject
*method
, *klass
;
1493 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1495 // ...and if that attribute is a method, and if that method's class is
1496 // not from a base class...
1497 if (PyMethod_Check(method
) &&
1498 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1499 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1501 // ...then we'll save a pointer to the method so callCallback can call it.
1502 self
->m_lastFound
= method
;
1508 return m_lastFound
!= NULL
;
1512 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1516 result
= callCallbackObj(argTuple
);
1517 if (result
) { // Assumes an integer return type...
1518 retval
= PyInt_AsLong(result
);
1520 PyErr_Clear(); // forget about it if it's not...
1525 // Invoke the Python callable object, returning the raw PyObject return
1526 // value. Caller should DECREF the return value and also manage the GIL.
1527 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1530 // Save a copy of the pointer in case the callback generates another
1531 // callback. In that case m_lastFound will have a different value when
1532 // it gets back here...
1533 PyObject
* method
= m_lastFound
;
1535 result
= PyEval_CallObject(method
, argTuple
);
1536 Py_DECREF(argTuple
);
1545 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1546 cbh
.setSelf(self
, klass
, incref
);
1549 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1550 return cbh
.findCallback(name
);
1553 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1554 return cbh
.callCallback(argTuple
);
1557 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1558 return cbh
.callCallbackObj(argTuple
);
1562 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1563 if (cbh
->m_incRef
) {
1564 wxPyBeginBlockThreads();
1565 Py_XDECREF(cbh
->m_self
);
1566 Py_XDECREF(cbh
->m_class
);
1567 wxPyEndBlockThreads();
1571 //---------------------------------------------------------------------------
1572 //---------------------------------------------------------------------------
1573 // These event classes can be derived from in Python and passed through the event
1574 // system without losing anything. They do this by keeping a reference to
1575 // themselves and some special case handling in wxPyCallback::EventThunker.
1578 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1579 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1580 //Py_INCREF(m_self); // circular loops...
1584 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1585 wxPyBeginBlockThreads();
1588 wxPyEndBlockThreads();
1591 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1592 wxPyBeginBlockThreads();
1600 wxPyEndBlockThreads();
1603 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1609 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1610 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1613 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1614 : wxEvent(winid
, commandType
) {
1618 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1621 SetSelf(evt
.m_self
, True
);
1625 wxPyEvent::~wxPyEvent() {
1629 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1630 : wxCommandEvent(commandType
, id
) {
1634 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1635 : wxCommandEvent(evt
)
1637 SetSelf(evt
.m_self
, True
);
1641 wxPyCommandEvent::~wxPyCommandEvent() {
1648 //---------------------------------------------------------------------------
1649 //---------------------------------------------------------------------------
1650 // Convert a wxList to a Python List, only works for lists of wxObjects
1652 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1653 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1657 wxNode
* node
= list
->GetFirst();
1659 wxPyBeginBlockThreads();
1660 pyList
= PyList_New(0);
1662 wxObj
= node
->GetData();
1663 pyObj
= wxPyMake_wxObject(wxObj
);
1664 PyList_Append(pyList
, pyObj
);
1665 node
= node
->GetNext();
1667 wxPyEndBlockThreads();
1671 //----------------------------------------------------------------------
1673 long wxPyGetWinHandle(wxWindow
* win
) {
1676 return (long)win
->GetHandle();
1679 // Find and return the actual X-Window.
1681 if (win
->m_wxwindow
) {
1683 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1685 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1687 return (long)bwin
->xwindow
;
1694 return (long)MAC_WXHWND(win
->MacGetRootWindow());
1700 //----------------------------------------------------------------------
1701 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1702 // included in every file over and over again...
1704 #if PYTHON_API_VERSION >= 1009
1705 static char* wxStringErrorMsg
= "String or Unicode type required";
1707 static char* wxStringErrorMsg
= "String type required";
1711 wxString
* wxString_in_helper(PyObject
* source
) {
1713 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1714 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1715 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1719 if (PyUnicode_Check(source
)) {
1720 target
= new wxString();
1721 size_t len
= PyUnicode_GET_SIZE(source
);
1723 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1724 target
->UngetWriteBuf();
1727 // It is a string, get pointers to it and transform to unicode
1728 char* tmpPtr
; int tmpSize
;
1729 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1730 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1733 char* tmpPtr
; int tmpSize
;
1734 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1735 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1738 target
= new wxString(tmpPtr
, tmpSize
);
1739 #endif // wxUSE_UNICODE
1741 #else // No Python unicode API (1.5.2)
1742 if (!PyString_Check(source
)) {
1743 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1746 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1752 // Similar to above except doesn't use "new" and doesn't set an exception
1753 wxString
Py2wxString(PyObject
* source
)
1756 bool doDecRef
= False
;
1758 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1759 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1760 // Convert to String if not one already... (TODO: Unicode too?)
1761 source
= PyObject_Str(source
);
1766 if (PyUnicode_Check(source
)) {
1767 size_t len
= PyUnicode_GET_SIZE(source
);
1769 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1770 target
.UngetWriteBuf();
1773 // It is a string, get pointers to it and transform to unicode
1774 char* tmpPtr
; int tmpSize
;
1775 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1776 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1779 char* tmpPtr
; int tmpSize
;
1780 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1781 target
= wxString(tmpPtr
, tmpSize
);
1782 #endif // wxUSE_UNICODE
1784 #else // No Python unicode API (1.5.2)
1785 if (!PyString_Check(source
)) {
1786 // Convert to String if not one already...
1787 source
= PyObject_Str(source
);
1790 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1799 // Make either a Python String or Unicode object, depending on build mode
1800 PyObject
* wx2PyString(const wxString
& src
)
1804 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1806 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1812 //----------------------------------------------------------------------
1815 byte
* byte_LIST_helper(PyObject
* source
) {
1816 if (!PyList_Check(source
)) {
1817 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1820 int count
= PyList_Size(source
);
1821 byte
* temp
= new byte
[count
];
1823 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1826 for (int x
=0; x
<count
; x
++) {
1827 PyObject
* o
= PyList_GetItem(source
, x
);
1828 if (! PyInt_Check(o
)) {
1829 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1832 temp
[x
] = (byte
)PyInt_AsLong(o
);
1838 int* int_LIST_helper(PyObject
* source
) {
1839 if (!PyList_Check(source
)) {
1840 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1843 int count
= PyList_Size(source
);
1844 int* temp
= new int[count
];
1846 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1849 for (int x
=0; x
<count
; x
++) {
1850 PyObject
* o
= PyList_GetItem(source
, x
);
1851 if (! PyInt_Check(o
)) {
1852 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1855 temp
[x
] = PyInt_AsLong(o
);
1861 long* long_LIST_helper(PyObject
* source
) {
1862 if (!PyList_Check(source
)) {
1863 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1866 int count
= PyList_Size(source
);
1867 long* temp
= new long[count
];
1869 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1872 for (int x
=0; x
<count
; x
++) {
1873 PyObject
* o
= PyList_GetItem(source
, x
);
1874 if (! PyInt_Check(o
)) {
1875 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1878 temp
[x
] = PyInt_AsLong(o
);
1884 char** string_LIST_helper(PyObject
* source
) {
1885 if (!PyList_Check(source
)) {
1886 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1889 int count
= PyList_Size(source
);
1890 char** temp
= new char*[count
];
1892 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1895 for (int x
=0; x
<count
; x
++) {
1896 PyObject
* o
= PyList_GetItem(source
, x
);
1897 if (! PyString_Check(o
)) {
1898 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1901 temp
[x
] = PyString_AsString(o
);
1906 //--------------------------------
1907 // Part of patch from Tim Hochberg
1908 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1909 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1910 point
->x
= PyInt_AS_LONG(o1
);
1911 point
->y
= PyInt_AS_LONG(o2
);
1914 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1915 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1916 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1919 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
1920 // Disallow instances because they can cause havok
1923 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1924 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1925 point
->x
= PyInt_AsLong(o1
);
1926 point
->y
= PyInt_AsLong(o2
);
1933 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1934 // Putting all of the declarations here allows
1935 // us to put the error handling all in one place.
1938 PyObject
*o
, *o1
, *o2
;
1939 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1941 if (!PySequence_Check(source
)) {
1945 // The length of the sequence is returned in count.
1946 *count
= PySequence_Length(source
);
1951 temp
= new wxPoint
[*count
];
1953 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1956 for (x
=0; x
<*count
; x
++) {
1957 // Get an item: try fast way first.
1959 o
= PySequence_Fast_GET_ITEM(source
, x
);
1962 o
= PySequence_GetItem(source
, x
);
1968 // Convert o to wxPoint.
1969 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1970 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1971 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1972 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1973 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1977 else if (wxPySwigInstance_Check(o
)) {
1979 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
1984 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1985 o1
= PySequence_GetItem(o
, 0);
1986 o2
= PySequence_GetItem(o
, 1);
1987 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2011 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2015 //------------------------------
2018 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2019 if (!PyList_Check(source
)) {
2020 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2023 int count
= PyList_Size(source
);
2024 wxBitmap
** temp
= new wxBitmap
*[count
];
2026 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2029 for (int x
=0; x
<count
; x
++) {
2030 PyObject
* o
= PyList_GetItem(source
, x
);
2031 if (wxPySwigInstance_Check(o
)) {
2033 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2034 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2040 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2049 wxString
* wxString_LIST_helper(PyObject
* source
) {
2050 if (!PyList_Check(source
)) {
2051 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2054 int count
= PyList_Size(source
);
2055 wxString
* temp
= new wxString
[count
];
2057 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2060 for (int x
=0; x
<count
; x
++) {
2061 PyObject
* o
= PyList_GetItem(source
, x
);
2062 #if PYTHON_API_VERSION >= 1009
2063 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2064 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2068 if (! PyString_Check(o
)) {
2069 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2074 wxString
* pStr
= wxString_in_helper(o
);
2082 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2083 if (!PyList_Check(source
)) {
2084 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2087 int count
= PyList_Size(source
);
2088 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2090 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2093 for (int x
=0; x
<count
; x
++) {
2094 PyObject
* o
= PyList_GetItem(source
, x
);
2095 if (wxPySwigInstance_Check(o
)) {
2096 wxAcceleratorEntry
* ae
;
2097 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2098 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2103 else if (PyTuple_Check(o
)) {
2104 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2105 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2106 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2107 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2110 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2118 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2119 if (!PyList_Check(source
)) {
2120 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2123 int count
= PyList_Size(source
);
2124 wxPen
** temp
= new wxPen
*[count
];
2126 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2129 for (int x
=0; x
<count
; x
++) {
2130 PyObject
* o
= PyList_GetItem(source
, x
);
2131 if (wxPySwigInstance_Check(o
)) {
2133 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2135 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2142 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2150 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2151 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2154 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2158 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2159 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2162 o1
= PySequence_GetItem(source
, 0);
2163 o2
= PySequence_GetItem(source
, 1);
2166 *i1
= PyInt_AsLong(o1
);
2167 *i2
= PyInt_AsLong(o2
);
2177 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2178 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2179 PyObject
*o1
, *o2
, *o3
, *o4
;
2181 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2185 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2186 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2187 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2188 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2191 o1
= PySequence_GetItem(source
, 0);
2192 o2
= PySequence_GetItem(source
, 1);
2193 o3
= PySequence_GetItem(source
, 2);
2194 o4
= PySequence_GetItem(source
, 3);
2197 *i1
= PyInt_AsLong(o1
);
2198 *i2
= PyInt_AsLong(o2
);
2199 *i3
= PyInt_AsLong(o3
);
2200 *i4
= PyInt_AsLong(o4
);
2212 //----------------------------------------------------------------------
2214 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2218 if (wxPySwigInstance_Check(source
) &&
2219 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2223 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2229 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2231 if (source
== Py_None
) {
2232 **obj
= wxSize(-1,-1);
2235 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2239 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2241 if (source
== Py_None
) {
2242 **obj
= wxPoint(-1,-1);
2245 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2250 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2252 if (source
== Py_None
) {
2253 **obj
= wxRealPoint(-1,-1);
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("wxRealPoint")))
2265 // otherwise a 2-tuple of floats is expected
2266 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2267 PyObject
* o1
= PySequence_GetItem(source
, 0);
2268 PyObject
* o2
= PySequence_GetItem(source
, 1);
2269 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2274 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2281 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2287 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2289 if (source
== Py_None
) {
2290 **obj
= wxRect(-1,-1,-1,-1);
2294 // If source is an object instance then it may already be the right type
2295 if (wxPySwigInstance_Check(source
)) {
2297 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2302 // otherwise a 4-tuple of integers is expected
2303 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2304 PyObject
* o1
= PySequence_GetItem(source
, 0);
2305 PyObject
* o2
= PySequence_GetItem(source
, 1);
2306 PyObject
* o3
= PySequence_GetItem(source
, 2);
2307 PyObject
* o4
= PySequence_GetItem(source
, 3);
2308 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2309 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2316 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2317 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2326 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2332 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2334 if (source
== Py_None
) {
2335 **obj
= wxNullColour
;
2339 // If source is an object instance then it may already be the right type
2340 if (wxPySwigInstance_Check(source
)) {
2342 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2347 // otherwise check for a string
2348 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2349 wxString spec
= Py2wxString(source
);
2350 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2351 long red
, green
, blue
;
2352 red
= green
= blue
= 0;
2353 spec
.Mid(1,2).ToLong(&red
, 16);
2354 spec
.Mid(3,2).ToLong(&green
, 16);
2355 spec
.Mid(5,2).ToLong(&blue
, 16);
2357 **obj
= wxColour(red
, green
, blue
);
2360 else { // it's a colour name
2361 **obj
= wxColour(spec
);
2365 // last chance: 3-tuple of integers is expected
2366 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2367 PyObject
* o1
= PySequence_GetItem(source
, 0);
2368 PyObject
* o2
= PySequence_GetItem(source
, 1);
2369 PyObject
* o3
= PySequence_GetItem(source
, 2);
2370 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2376 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2384 PyErr_SetString(PyExc_TypeError
,
2385 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2390 bool wxColour_typecheck(PyObject
* source
) {
2392 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2395 if (PyString_Check(source
) || PyUnicode_Check(source
))
2403 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2405 if (source
== Py_None
) {
2406 **obj
= wxPoint2D(-1,-1);
2410 // If source is an object instance then it may already be the right type
2411 if (wxPySwigInstance_Check(source
)) {
2413 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2418 // otherwise a length-2 sequence of floats is expected
2419 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2420 PyObject
* o1
= PySequence_GetItem(source
, 0);
2421 PyObject
* o2
= PySequence_GetItem(source
, 1);
2422 // This should really check for floats, not numbers -- but that would break code.
2423 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2428 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2434 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2439 //----------------------------------------------------------------------
2441 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2443 PyObject
* list
= PyList_New(0);
2444 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2446 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2448 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2450 PyList_Append(list
, str
);
2457 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2459 PyObject
* list
= PyList_New(0);
2460 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2461 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2462 PyList_Append(list
, number
);
2469 //----------------------------------------------------------------------
2470 //----------------------------------------------------------------------