1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Helper functions/classes for the wxPython extension module
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
17 #include "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>
34 //----------------------------------------------------------------------
36 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
37 #error Python must support Unicode to use wxWindows Unicode
40 //----------------------------------------------------------------------
42 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
43 bool wxPyDoCleanup
= FALSE
;
44 bool wxPyDoingCleanup
= FALSE
;
47 #ifdef WXP_WITH_THREAD
48 struct wxPyThreadState
{
50 PyThreadState
* tstate
;
52 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
53 : tid(_tid
), tstate(_tstate
) {}
56 #include <wx/dynarray.h>
57 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
58 #include <wx/arrimpl.cpp>
59 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
61 wxPyThreadStateArray
* wxPyTStates
= NULL
;
62 wxMutex
* wxPyTMutex
= NULL
;
66 static PyObject
* wxPython_dict
= NULL
;
67 static PyObject
* wxPyPtrTypeMap
= NULL
;
68 static PyObject
* wxPyAssertionError
= NULL
;
71 #ifdef __WXMSW__ // If building for win32...
72 //----------------------------------------------------------------------
73 // This gets run when the DLL is loaded. We just need to save a handle.
74 //----------------------------------------------------------------------
77 HINSTANCE hinstDLL
, // handle to DLL module
78 DWORD fdwReason
, // reason for calling function
79 LPVOID lpvReserved
// reserved
82 // If wxPython is embedded in another wxWindows app then
83 // the inatance has already been set.
84 if (! wxGetInstance())
85 wxSetInstance(hinstDLL
);
90 //----------------------------------------------------------------------
91 // Classes for implementing the wxp main application shell.
92 //----------------------------------------------------------------------
94 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
98 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
102 wxPyApp::~wxPyApp() {
106 // This one isn't acutally called... We fake it with __wxStart()
107 bool wxPyApp::OnInit() {
112 int wxPyApp::MainLoop() {
115 DeletePendingObjects();
116 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
118 m_initialized
= initialized
;
122 if ( m_exitOnFrameDelete
== Later
) {
123 m_exitOnFrameDelete
= Yes
;
126 retval
= wxApp::MainLoop();
133 bool wxPyApp::OnInitGui() {
135 wxApp::OnInitGui(); // in this case always call the base class version
136 // wxPyBeginBlockThreads(); *** only called from within __wxStart so we already have the GIL
137 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
138 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
139 // wxPyEndBlockThreads(); ***
144 int wxPyApp::OnExit() {
146 wxPyBeginBlockThreads();
147 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
148 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
149 wxPyEndBlockThreads();
150 wxApp::OnExit(); // in this case always call the base class version
156 void wxPyApp::OnAssert(const wxChar
*file
,
161 // If the OnAssert is overloaded in the Python class then call it...
163 wxPyBeginBlockThreads();
164 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
165 PyObject
* fso
= wx2PyString(file
);
166 PyObject
* cso
= wx2PyString(file
);
169 mso
= wx2PyString(file
);
171 mso
= Py_None
; Py_INCREF(Py_None
);
173 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
178 wxPyEndBlockThreads();
180 // ...otherwise do our own thing with it
183 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
186 // turn it into a Python exception?
187 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
190 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
197 wxPyBeginBlockThreads();
198 PyObject
* s
= wx2PyString(buf
);
199 PyErr_SetObject(wxPyAssertionError
, s
);
201 wxPyEndBlockThreads();
203 // Now when control returns to whatever API wrapper was called from
204 // Python it should detect that an exception is set and will return
205 // NULL, signalling the exception to Python.
208 // Send it to the normal log destination, but only if
209 // not _DIALOG because it will call this too
210 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
213 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
222 // do the normal wx assert dialog?
223 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
224 wxApp::OnAssert(file
, line
, cond
, msg
);
231 bool wxPyApp::GetMacDefaultEncodingIsPC() {
233 return s_macDefaultEncodingIsPC
;
240 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
242 return s_macSupportPCMenuShortcuts
;
249 long wxPyApp::GetMacAboutMenuItemId() {
251 return s_macAboutMenuItemId
;
258 long wxPyApp::GetMacPreferencesMenuItemId() {
260 return s_macPreferencesMenuItemId
;
267 long wxPyApp::GetMacExitMenuItemId() {
269 return s_macExitMenuItemId
;
276 wxString
wxPyApp::GetMacHelpMenuTitleName() {
278 return s_macHelpMenuTitleName
;
280 return wxEmptyString
;
285 void wxPyApp::SetMacDefaultEncodingIsPC(bool val
) {
287 s_macDefaultEncodingIsPC
= val
;
292 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
294 s_macSupportPCMenuShortcuts
= val
;
299 void wxPyApp::SetMacAboutMenuItemId(long val
) {
301 s_macAboutMenuItemId
= val
;
306 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
308 s_macPreferencesMenuItemId
= val
;
313 void wxPyApp::SetMacExitMenuItemId(long val
) {
315 s_macExitMenuItemId
= val
;
320 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
322 s_macHelpMenuTitleName
= val
;
328 //---------------------------------------------------------------------
329 //----------------------------------------------------------------------
333 static char* wxPyCopyCString(const wxChar
* src
)
335 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
336 size_t len
= strlen(buff
);
337 char* dest
= new char[len
+1];
343 static char* wxPyCopyCString(const char* src
) // we need a char version too
345 size_t len
= strlen(src
);
346 char* dest
= new char[len
+1];
352 static wxChar
* wxPyCopyWString(const char *src
)
354 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
355 wxString
str(src
, *wxConvCurrent
);
356 return copystring(str
);
360 static wxChar
* wxPyCopyWString(const wxChar
*src
)
362 return copystring(src
);
368 //----------------------------------------------------------------------
370 // This function is called when the wxc module is imported to do some initial
371 // setup. (Before there is a wxApp object.)
372 void __wxPreStart(PyObject
* moduleDict
)
376 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
379 #ifdef WXP_WITH_THREAD
380 PyEval_InitThreads();
381 wxPyTStates
= new wxPyThreadStateArray
;
382 wxPyTMutex
= new wxMutex
;
385 // Ensure that the build options in the DLL (or whatever) match this build
386 wxApp::CheckBuildOptions(wxBuildOptions());
388 // Create an exception object to use for wxASSERTions
389 wxPyAssertionError
= PyErr_NewException("wxPython.wxc.wxPyAssertionError",
390 PyExc_AssertionError
, NULL
);
391 PyDict_SetItemString(moduleDict
, "wxPyAssertionError", wxPyAssertionError
);
396 // Initialize wxWindows and bootstrap the user application by calling the
397 // wxApp's OnInit, which is a parameter to this funciton. See wxApp.__init__
398 // in _extras.py to learn how the bootstrap is started.
399 PyObject
* __wxStart(PyObject
* /* self */, PyObject
* args
)
401 PyObject
* onInitFunc
= NULL
;
402 PyObject
* arglist
= NULL
;
403 PyObject
* result
= NULL
;
404 PyObject
* pyint
= NULL
;
407 if (!PyArg_ParseTuple(args
, "O", &onInitFunc
))
410 // Get any command-line args passed to this program from the sys module
413 PyObject
* sysargv
= PySys_GetObject("argv");
414 if (sysargv
!= NULL
) {
415 argc
= PyList_Size(sysargv
);
416 argv
= new char*[argc
+1];
418 for(x
=0; x
<argc
; x
++) {
419 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
420 argv
[x
] = PyString_AsString(pyArg
);
425 if (! wxEntryStart(argc
, argv
) ) {
426 PyErr_SetString(PyExc_SystemError
, // is this the right one?
427 "wxEntryStart failed!");
433 // The stock objects were all NULL when they were loaded into
434 // SWIG generated proxies, so re-init those now...
435 wxPy_ReinitStockObjects();
438 // Call the Python wxApp's OnInit function
439 arglist
= PyTuple_New(0);
440 result
= PyEval_CallObject(onInitFunc
, arglist
);
442 if (!result
) { // an exception was raised.
446 pyint
= PyNumber_Int(result
);
448 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
451 bResult
= PyInt_AS_LONG(pyint
);
453 PyErr_SetString(PyExc_SystemExit
, "OnInit returned FALSE, exiting...");
458 wxTheApp
->m_initialized
= (wxTopLevelWindows
.GetCount() > 0);
475 wxPyDoingCleanup
= TRUE
;
478 #ifdef WXP_WITH_THREAD
481 wxPyTStates
->Empty();
490 PyObject
* __wxSetDictionary(PyObject
* /* self */, PyObject
* args
)
493 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
496 if (!PyDict_Check(wxPython_dict
)) {
497 PyErr_SetString(PyExc_TypeError
, "_wxSetDictionary must have dictionary object!");
501 if (! wxPyPtrTypeMap
)
502 wxPyPtrTypeMap
= PyDict_New();
503 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
507 #define wxPlatform "__WXMOTIF__"
510 #define wxPlatform "__WXX11__"
513 #define wxPlatform "__WXGTK__"
515 #if defined(__WIN32__) || defined(__WXMSW__)
516 #define wxPlatform "__WXMSW__"
519 #define wxPlatform "__WXMAC__"
528 PyDict_SetItemString(wxPython_dict
, "wxPlatform", PyString_FromString(wxPlatform
));
529 PyDict_SetItemString(wxPython_dict
, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
530 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
537 //---------------------------------------------------------------------------
539 // The stock objects are no longer created when the wxc module is imported, but
540 // only after the app object has been created. This function will be called before
541 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
543 void wxPy_ReinitStockObjects()
551 #define REINITOBJ(name, type) \
552 obj = PyDict_GetItemString(wxPython_dict, #name); \
553 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
554 SWIG_MakePtr(ptrbuf, (char *) name, "_" #type "_p"); \
555 ptrobj = PyString_FromString(ptrbuf); \
556 PyObject_SetAttrString(obj, "this", ptrobj); \
559 #define REINITOBJ2(name, type) \
560 obj = PyDict_GetItemString(wxPython_dict, #name); \
561 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
562 SWIG_MakePtr(ptrbuf, (char *) &name, "_" #type "_p"); \
563 ptrobj = PyString_FromString(ptrbuf); \
564 PyObject_SetAttrString(obj, "this", ptrobj); \
568 REINITOBJ(wxNORMAL_FONT
, wxFont
);
569 REINITOBJ(wxSMALL_FONT
, wxFont
);
570 REINITOBJ(wxITALIC_FONT
, wxFont
);
571 REINITOBJ(wxSWISS_FONT
, wxFont
);
573 REINITOBJ(wxRED_PEN
, wxPen
);
574 REINITOBJ(wxCYAN_PEN
, wxPen
);
575 REINITOBJ(wxGREEN_PEN
, wxPen
);
576 REINITOBJ(wxBLACK_PEN
, wxPen
);
577 REINITOBJ(wxWHITE_PEN
, wxPen
);
578 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
579 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
580 REINITOBJ(wxGREY_PEN
, wxPen
);
581 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
582 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
584 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
585 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
586 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
587 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
588 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
589 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
590 REINITOBJ(wxRED_BRUSH
, wxBrush
);
591 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
592 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
593 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
595 REINITOBJ(wxBLACK
, wxColour
);
596 REINITOBJ(wxWHITE
, wxColour
);
597 REINITOBJ(wxRED
, wxColour
);
598 REINITOBJ(wxBLUE
, wxColour
);
599 REINITOBJ(wxGREEN
, wxColour
);
600 REINITOBJ(wxCYAN
, wxColour
);
601 REINITOBJ(wxLIGHT_GREY
, wxColour
);
603 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
604 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
605 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
607 REINITOBJ2(wxNullBitmap
, wxBitmap
);
608 REINITOBJ2(wxNullIcon
, wxIcon
);
609 REINITOBJ2(wxNullCursor
, wxCursor
);
610 REINITOBJ2(wxNullPen
, wxPen
);
611 REINITOBJ2(wxNullBrush
, wxBrush
);
612 REINITOBJ2(wxNullPalette
, wxPalette
);
613 REINITOBJ2(wxNullFont
, wxFont
);
614 REINITOBJ2(wxNullColour
, wxColour
);
616 REINITOBJ(wxTheFontList
, wxFontList
);
617 REINITOBJ(wxThePenList
, wxPenList
);
618 REINITOBJ(wxTheBrushList
, wxBrushList
);
619 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
622 REINITOBJ(wxTheClipboard
, wxClipboard
);
623 REINITOBJ(wxTheMimeTypesManager
, wxMimeTypesManager
);
624 REINITOBJ2(wxDefaultValidator
, wxValidator
);
625 REINITOBJ2(wxNullImage
, wxImage
);
626 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
632 //---------------------------------------------------------------------------
634 void wxPyClientData_dtor(wxPyClientData
* self
) {
635 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
636 // may have already garbage collected the object...
637 wxPyBeginBlockThreads();
638 Py_DECREF(self
->m_obj
);
639 wxPyEndBlockThreads();
643 void wxPyUserData_dtor(wxPyUserData
* self
) {
644 if (! wxPyDoingCleanup
) {
645 wxPyBeginBlockThreads();
646 Py_DECREF(self
->m_obj
);
647 wxPyEndBlockThreads();
652 // This is called when an OOR controled object is being destroyed. Although
653 // the C++ object is going away there is no way to force the Python object
654 // (and all references to it) to die too. This causes problems (crashes) in
655 // wxPython when a python shadow object attempts to call a C++ method using
656 // the now bogus pointer... So to try and prevent this we'll do a little black
657 // magic and change the class of the python instance to a class that will
658 // raise an exception for any attempt to call methods with it. See
659 // _wxPyDeadObject in _extras.py for the implementation of this class.
660 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
662 static PyObject
* deadObjectClass
= NULL
;
664 wxPyBeginBlockThreads();
665 if (deadObjectClass
== NULL
) {
666 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
667 wxASSERT_MSG(deadObjectClass
!= NULL
, wxT("Can't get _wxPyDeadObject class!"));
668 Py_INCREF(deadObjectClass
);
672 // Only if there is more than one reference to the object
673 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
674 wxASSERT_MSG(PyInstance_Check(self
->m_obj
), wxT("m_obj not an instance!?!?!"));
676 // Call __del__, if there is one.
677 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
679 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
683 if (PyErr_Occurred())
684 PyErr_Clear(); // just ignore it for now
686 // Clear the instance's dictionary
687 PyInstanceObject
* inst
= (PyInstanceObject
*)self
->m_obj
;
688 PyDict_Clear(inst
->in_dict
);
690 // put the name of the old class into the instance, and then reset the
691 // class to be the dead class.
692 PyDict_SetItemString(inst
->in_dict
, "_name", inst
->in_class
->cl_name
);
693 inst
->in_class
= (PyClassObject
*)deadObjectClass
;
694 Py_INCREF(deadObjectClass
);
697 // m_obj is DECREF's in the base class dtor...
698 wxPyEndBlockThreads();
702 //---------------------------------------------------------------------------
703 // Stuff used by OOR to find the right wxPython class type to return and to
707 // The pointer type map is used when the "pointer" type name generated by SWIG
708 // is not the same as the shadow class name, for example wxPyTreeCtrl
709 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
710 // so we'll just make it a Python dictionary in the wx module's namespace.
711 // (See __wxSetDictionary)
712 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
713 if (! wxPyPtrTypeMap
)
714 wxPyPtrTypeMap
= PyDict_New();
715 PyDict_SetItemString(wxPyPtrTypeMap
,
717 PyString_FromString((char*)ptrName
));
722 PyObject
* wxPyClassExists(const wxString
& className
) {
725 wxString
name(className
);
726 char buff
[64]; // should always be big enough...
731 // Try the name as-is first
732 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
733 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
735 // if not found see if there is a mapped name for it
737 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
738 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
739 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
740 classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
744 return classobj
; // returns NULL if not found
748 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
749 PyObject
* target
= NULL
;
750 bool isEvtHandler
= FALSE
;
753 // If it's derived from wxEvtHandler then there may
754 // already be a pointer to a Python object that we can use
756 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
758 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
759 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
761 target
= data
->m_obj
;
767 // Otherwise make it the old fashioned way by making a
768 // new shadow object and putting this pointer in it.
769 wxClassInfo
* info
= source
->GetClassInfo();
770 wxString name
= info
->GetClassName();
771 PyObject
* klass
= wxPyClassExists(name
);
772 while (info
&& !klass
) {
773 name
= (wxChar
*)info
->GetBaseClassName1();
774 info
= wxClassInfo::FindClass(name
);
775 klass
= wxPyClassExists(name
);
778 target
= wxPyConstructObject(source
, name
, klass
, FALSE
);
779 if (target
&& isEvtHandler
)
780 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
782 wxString
msg(wxT("wxPython class not found for "));
783 msg
+= source
->GetClassInfo()->GetClassName();
784 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
788 } else { // source was NULL so return None.
789 Py_INCREF(Py_None
); target
= Py_None
;
795 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
796 PyObject
* target
= NULL
;
798 if (source
&& wxIsKindOf(source
, wxSizer
)) {
799 // If it's derived from wxSizer then there may
800 // already be a pointer to a Python object that we can use
802 wxSizer
* sz
= (wxSizer
*)source
;
803 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
805 target
= data
->m_obj
;
810 target
= wxPyMake_wxObject(source
, FALSE
);
811 if (target
!= Py_None
)
812 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
819 //---------------------------------------------------------------------------
821 PyObject
* wxPyConstructObject(void* ptr
,
822 const wxString
& className
,
829 wxString
name(className
);
830 char swigptr
[64]; // should always be big enough...
833 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
834 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
836 sprintf(buff
, "_%s_p", (const char*)name
.mbc_str());
837 SWIG_MakePtr(swigptr
, ptr
, buff
);
839 arg
= Py_BuildValue("(s)", swigptr
);
840 obj
= PyInstance_New(klass
, arg
, NULL
);
844 PyObject
* one
= PyInt_FromLong(1);
845 PyObject_SetAttrString(obj
, "thisown", one
);
853 PyObject
* wxPyConstructObject(void* ptr
,
854 const wxString
& className
,
861 char buff
[64]; // should always be big enough...
862 sprintf(buff
, "%sPtr", (const char*)className
.mbc_str());
864 wxASSERT_MSG(wxPython_dict
, wxT("wxPython_dict is not set yet!!"));
866 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
868 wxString
msg(wxT("wxPython class not found for "));
870 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
874 return wxPyConstructObject(ptr
, className
, classobj
, setThisOwn
);
878 //---------------------------------------------------------------------------
881 #ifdef WXP_WITH_THREAD
883 unsigned long wxPyGetCurrentThreadId() {
884 return wxThread::GetCurrentId();
887 static PyThreadState
* gs_shutdownTState
;
889 PyThreadState
* wxPyGetThreadState() {
890 if (wxPyTMutex
== NULL
) // Python is shutting down...
891 return gs_shutdownTState
;
893 unsigned long ctid
= wxPyGetCurrentThreadId();
894 PyThreadState
* tstate
= NULL
;
897 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
898 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
899 if (info
.tid
== ctid
) {
900 tstate
= info
.tstate
;
904 wxPyTMutex
->Unlock();
905 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
910 void wxPySaveThreadState(PyThreadState
* tstate
) {
911 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
912 gs_shutdownTState
= tstate
;
915 unsigned long ctid
= wxPyGetCurrentThreadId();
917 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
918 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
919 if (info
.tid
== ctid
) {
921 if (info
.tstate
!= tstate
)
922 wxLogMessage("*** tstate mismatch!???");
924 // info.tstate = tstate; *** DO NOT update existing ones???
925 // Normally it will never change, but apparently COM callbacks
926 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
927 // tstate which will then be garbage the next time we try to use
929 wxPyTMutex
->Unlock();
933 // not found, so add it...
934 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
935 wxPyTMutex
->Unlock();
941 // Calls from Python to wxWindows code are wrapped in calls to these
944 PyThreadState
* wxPyBeginAllowThreads() {
945 #ifdef WXP_WITH_THREAD
946 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
947 wxPySaveThreadState(saved
);
954 void wxPyEndAllowThreads(PyThreadState
* saved
) {
955 #ifdef WXP_WITH_THREAD
956 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
962 // Calls from wxWindows back to Python code, or even any PyObject
963 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
965 void wxPyBeginBlockThreads() {
966 #ifdef WXP_WITH_THREAD
967 PyThreadState
* tstate
= wxPyGetThreadState();
968 PyEval_RestoreThread(tstate
);
973 void wxPyEndBlockThreads() {
974 #ifdef WXP_WITH_THREAD
975 // Is there any need to save it again?
976 // PyThreadState* tstate =
982 //---------------------------------------------------------------------------
983 // wxPyInputStream and wxPyCBInputStream methods
986 void wxPyInputStream::close() {
987 /* do nothing for now */
990 void wxPyInputStream::flush() {
991 /* do nothing for now */
994 bool wxPyInputStream::eof() {
996 return m_wxis
->Eof();
1001 wxPyInputStream::~wxPyInputStream() {
1008 PyObject
* wxPyInputStream::read(int size
) {
1009 PyObject
* obj
= NULL
;
1011 const int BUFSIZE
= 1024;
1013 // check if we have a real wxInputStream to work with
1015 wxPyBeginBlockThreads();
1016 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1017 wxPyEndBlockThreads();
1022 // read while bytes are available on the stream
1023 while ( m_wxis
->CanRead() ) {
1024 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1025 buf
.UngetAppendBuf(m_wxis
->LastRead());
1028 } else { // Read only size number of characters
1029 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1030 buf
.UngetWriteBuf(m_wxis
->LastRead());
1034 wxPyBeginBlockThreads();
1035 wxStreamError err
= m_wxis
->GetLastError();
1036 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1037 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1040 // We use only strings for the streams, not unicode
1041 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1043 wxPyEndBlockThreads();
1048 PyObject
* wxPyInputStream::readline(int size
) {
1049 PyObject
* obj
= NULL
;
1054 // check if we have a real wxInputStream to work with
1056 wxPyBeginBlockThreads();
1057 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1058 wxPyEndBlockThreads();
1062 // read until \n or byte limit reached
1063 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1064 ch
= m_wxis
->GetC();
1069 wxPyBeginBlockThreads();
1070 wxStreamError err
= m_wxis
->GetLastError();
1071 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1072 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1075 // We use only strings for the streams, not unicode
1076 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1078 wxPyEndBlockThreads();
1083 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1086 // check if we have a real wxInputStream to work with
1088 wxPyBeginBlockThreads();
1089 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1090 wxPyEndBlockThreads();
1095 wxPyBeginBlockThreads();
1096 pylist
= PyList_New(0);
1098 wxPyBeginBlockThreads();
1100 wxPyEndBlockThreads();
1104 // read sizehint bytes or until EOF
1106 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1107 PyObject
* s
= this->readline();
1109 wxPyBeginBlockThreads();
1111 wxPyEndBlockThreads();
1114 wxPyBeginBlockThreads();
1115 PyList_Append(pylist
, s
);
1116 i
+= PyString_Size(s
);
1117 wxPyEndBlockThreads();
1121 wxStreamError err
= m_wxis
->GetLastError();
1122 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1123 wxPyBeginBlockThreads();
1125 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1126 wxPyEndBlockThreads();
1134 void wxPyInputStream::seek(int offset
, int whence
) {
1136 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1139 int wxPyInputStream::tell(){
1141 return m_wxis
->TellI();
1148 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1149 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1153 wxPyCBInputStream::~wxPyCBInputStream() {
1154 if (m_block
) wxPyBeginBlockThreads();
1158 if (m_block
) wxPyEndBlockThreads();
1162 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1163 if (block
) wxPyBeginBlockThreads();
1165 PyObject
* read
= getMethod(py
, "read");
1166 PyObject
* seek
= getMethod(py
, "seek");
1167 PyObject
* tell
= getMethod(py
, "tell");
1170 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1174 if (block
) wxPyEndBlockThreads();
1178 if (block
) wxPyEndBlockThreads();
1179 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1183 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1184 return wxPyCBInputStream::create(py
, block
);
1187 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1188 if (!PyObject_HasAttrString(py
, name
))
1190 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1191 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1199 size_t wxPyCBInputStream::GetSize() const {
1200 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1201 if (m_seek
&& m_tell
) {
1202 off_t temp
= self
->OnSysTell();
1203 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1204 self
->OnSysSeek(temp
, wxFromStart
);
1212 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1216 wxPyBeginBlockThreads();
1217 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1218 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1222 if ((result
!= NULL
) && PyString_Check(result
)) {
1223 o
= PyString_Size(result
);
1225 m_lasterror
= wxSTREAM_EOF
;
1228 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1233 m_lasterror
= wxSTREAM_READ_ERROR
;
1234 wxPyEndBlockThreads();
1238 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1239 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1243 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1244 wxPyBeginBlockThreads();
1246 // off_t is a 64-bit value...
1247 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1249 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1251 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1254 wxPyEndBlockThreads();
1259 off_t
wxPyCBInputStream::OnSysTell() const {
1260 wxPyBeginBlockThreads();
1261 PyObject
* arglist
= Py_BuildValue("()");
1262 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1265 if (result
!= NULL
) {
1267 if (PyLong_Check(result
))
1268 o
= PyLong_AsLongLong(result
);
1271 o
= PyInt_AsLong(result
);
1275 wxPyEndBlockThreads();
1279 //----------------------------------------------------------------------
1281 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1283 wxPyCallback::wxPyCallback(PyObject
* func
) {
1288 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1289 m_func
= other
.m_func
;
1293 wxPyCallback::~wxPyCallback() {
1294 wxPyBeginBlockThreads();
1296 wxPyEndBlockThreads();
1301 // This function is used for all events destined for Python event handlers.
1302 void wxPyCallback::EventThunker(wxEvent
& event
) {
1303 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1304 PyObject
* func
= cb
->m_func
;
1310 wxPyBeginBlockThreads();
1311 wxString className
= event
.GetClassInfo()->GetClassName();
1313 if (className
== wxT("wxPyEvent"))
1314 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1315 else if (className
== wxT("wxPyCommandEvent"))
1316 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1318 arg
= wxPyConstructObject((void*)&event
, className
);
1321 tuple
= PyTuple_New(1);
1322 PyTuple_SET_ITEM(tuple
, 0, arg
);
1323 result
= PyEval_CallObject(func
, tuple
);
1327 PyErr_Clear(); // Just in case...
1331 wxPyEndBlockThreads();
1335 //----------------------------------------------------------------------
1337 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1339 m_self
= other
.m_self
;
1340 m_class
= other
.m_class
;
1348 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1359 #if PYTHON_API_VERSION >= 1011
1361 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1362 // in which the method was defined. Starting with 2.2 it returns
1363 // "class that asked for the method" which seems totally bogus to me
1364 // but apprently it fixes some obscure problem waiting to happen in
1365 // Python. Since the API was not documented Guido and the gang felt
1366 // safe in changing it. Needless to say that totally screwed up the
1367 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1368 // code to find the class where the method is actually defined...
1371 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1375 if (PyType_Check(klass
)) { // new style classes
1376 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1377 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1378 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1379 PyObject
*mro
, *res
, *base
, *dict
;
1380 /* Look in tp_dict of types in MRO */
1382 assert(PyTuple_Check(mro
));
1383 n
= PyTuple_GET_SIZE(mro
);
1384 for (i
= 0; i
< n
; i
++) {
1385 base
= PyTuple_GET_ITEM(mro
, i
);
1386 if (PyClass_Check(base
))
1387 dict
= ((PyClassObject
*)base
)->cl_dict
;
1389 assert(PyType_Check(base
));
1390 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1392 assert(dict
&& PyDict_Check(dict
));
1393 res
= PyDict_GetItem(dict
, name
);
1400 else if (PyClass_Check(klass
)) { // old style classes
1401 // This code is borrowed/adapted from class_lookup in classobject.c
1402 PyClassObject
* cp
= (PyClassObject
*)klass
;
1403 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1404 if (value
!= NULL
) {
1405 return (PyObject
*)cp
;
1407 n
= PyTuple_Size(cp
->cl_bases
);
1408 for (i
= 0; i
< n
; i
++) {
1409 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1410 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1422 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1424 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1426 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1428 #else // 2.2 and after, the hard way...
1430 PyObject
* nameo
= PyString_FromString(name
);
1431 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1439 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1440 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1441 self
->m_lastFound
= NULL
;
1443 // If the object (m_self) has an attibute of the given name...
1444 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1445 PyObject
*method
, *klass
;
1446 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1448 // ...and if that attribute is a method, and if that method's class is
1449 // not from a base class...
1450 if (PyMethod_Check(method
) &&
1451 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1452 ((klass
== m_class
) || PyClass_IsSubclass(klass
, m_class
))) {
1454 // ...then we'll save a pointer to the method so callCallback can call it.
1455 self
->m_lastFound
= method
;
1461 return m_lastFound
!= NULL
;
1465 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1469 result
= callCallbackObj(argTuple
);
1470 if (result
) { // Assumes an integer return type...
1471 retval
= PyInt_AsLong(result
);
1473 PyErr_Clear(); // forget about it if it's not...
1478 // Invoke the Python callable object, returning the raw PyObject return
1479 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1480 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1483 // Save a copy of the pointer in case the callback generates another
1484 // callback. In that case m_lastFound will have a different value when
1485 // it gets back here...
1486 PyObject
* method
= m_lastFound
;
1488 result
= PyEval_CallObject(method
, argTuple
);
1489 Py_DECREF(argTuple
);
1498 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1499 cbh
.setSelf(self
, klass
, incref
);
1502 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1503 return cbh
.findCallback(name
);
1506 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1507 return cbh
.callCallback(argTuple
);
1510 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1511 return cbh
.callCallbackObj(argTuple
);
1515 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1516 if (cbh
->m_incRef
) {
1517 wxPyBeginBlockThreads();
1518 Py_XDECREF(cbh
->m_self
);
1519 Py_XDECREF(cbh
->m_class
);
1520 wxPyEndBlockThreads();
1524 //---------------------------------------------------------------------------
1525 //---------------------------------------------------------------------------
1526 // These event classes can be derived from in Python and passed through the event
1527 // system without losing anything. They do this by keeping a reference to
1528 // themselves and some special case handling in wxPyCallback::EventThunker.
1531 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1532 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1533 //Py_INCREF(m_self); // circular loops...
1537 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1538 wxPyBeginBlockThreads();
1541 wxPyEndBlockThreads();
1544 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1545 wxPyBeginBlockThreads();
1553 wxPyEndBlockThreads();
1556 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1562 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1563 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1566 wxPyEvent::wxPyEvent(int id
)
1571 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1574 SetSelf(evt
.m_self
, TRUE
);
1578 wxPyEvent::~wxPyEvent() {
1582 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1583 : wxCommandEvent(commandType
, id
) {
1587 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1588 : wxCommandEvent(evt
)
1590 SetSelf(evt
.m_self
, TRUE
);
1594 wxPyCommandEvent::~wxPyCommandEvent() {
1600 //---------------------------------------------------------------------------
1601 //---------------------------------------------------------------------------
1604 wxPyTimer::wxPyTimer(PyObject
* callback
) {
1609 wxPyTimer::~wxPyTimer() {
1610 wxPyBeginBlockThreads();
1612 wxPyEndBlockThreads();
1615 void wxPyTimer::Notify() {
1616 if (!func
|| func
== Py_None
) {
1620 wxPyBeginBlockThreads();
1623 PyObject
* args
= Py_BuildValue("()");
1625 result
= PyEval_CallObject(func
, args
);
1634 wxPyEndBlockThreads();
1640 //---------------------------------------------------------------------------
1641 //---------------------------------------------------------------------------
1642 // Convert a wxList to a Python List
1644 PyObject
* wxPy_ConvertList(wxListBase
* listbase
, const char* className
) {
1645 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1649 wxNode
* node
= list
->GetFirst();
1651 wxPyBeginBlockThreads();
1652 pyList
= PyList_New(0);
1654 wxObj
= node
->GetData();
1655 pyObj
= wxPyMake_wxObject(wxObj
); //wxPyConstructObject(wxObj, className);
1656 PyList_Append(pyList
, pyObj
);
1657 node
= node
->GetNext();
1659 wxPyEndBlockThreads();
1663 //----------------------------------------------------------------------
1665 long wxPyGetWinHandle(wxWindow
* win
) {
1667 return (long)win
->GetHandle();
1670 // Find and return the actual X-Window.
1672 if (win
->m_wxwindow
) {
1674 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1676 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1678 return (long)bwin
->xwindow
;
1686 //----------------------------------------------------------------------
1687 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1688 // included in every file over and over again...
1690 #if PYTHON_API_VERSION >= 1009
1691 static char* wxStringErrorMsg
= "String or Unicode type required";
1693 static char* wxStringErrorMsg
= "String type required";
1697 wxString
* wxString_in_helper(PyObject
* source
) {
1699 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1700 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1701 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1705 if (PyUnicode_Check(source
)) {
1706 target
= new wxString();
1707 size_t len
= PyUnicode_GET_SIZE(source
);
1709 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1710 target
->UngetWriteBuf();
1713 // It is a string, get pointers to it and transform to unicode
1714 char* tmpPtr
; int tmpSize
;
1715 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1716 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1719 char* tmpPtr
; int tmpSize
;
1720 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1721 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1724 target
= new wxString(tmpPtr
, tmpSize
);
1725 #endif // wxUSE_UNICODE
1727 #else // No Python unicode API (1.5.2)
1728 if (!PyString_Check(source
)) {
1729 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1732 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1738 // Similar to above except doesn't use "new" and doesn't set an exception
1739 wxString
Py2wxString(PyObject
* source
)
1742 bool doDecRef
= FALSE
;
1744 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1745 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1746 // Convert to String if not one already... (TODO: Unicode too?)
1747 source
= PyObject_Str(source
);
1752 if (PyUnicode_Check(source
)) {
1753 size_t len
= PyUnicode_GET_SIZE(source
);
1755 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1756 target
.UngetWriteBuf();
1759 // It is a string, get pointers to it and transform to unicode
1760 char* tmpPtr
; int tmpSize
;
1761 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1762 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1765 char* tmpPtr
; int tmpSize
;
1766 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1767 target
= wxString(tmpPtr
, tmpSize
);
1768 #endif // wxUSE_UNICODE
1770 #else // No Python unicode API (1.5.2)
1771 if (!PyString_Check(source
)) {
1772 // Convert to String if not one already...
1773 source
= PyObject_Str(source
);
1776 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1785 // Make either a Python String or Unicode object, depending on build mode
1786 PyObject
* wx2PyString(const wxString
& src
)
1790 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1792 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1798 //----------------------------------------------------------------------
1801 byte
* byte_LIST_helper(PyObject
* source
) {
1802 if (!PyList_Check(source
)) {
1803 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1806 int count
= PyList_Size(source
);
1807 byte
* temp
= new byte
[count
];
1809 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1812 for (int x
=0; x
<count
; x
++) {
1813 PyObject
* o
= PyList_GetItem(source
, x
);
1814 if (! PyInt_Check(o
)) {
1815 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1818 temp
[x
] = (byte
)PyInt_AsLong(o
);
1824 int* int_LIST_helper(PyObject
* source
) {
1825 if (!PyList_Check(source
)) {
1826 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1829 int count
= PyList_Size(source
);
1830 int* temp
= new int[count
];
1832 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1835 for (int x
=0; x
<count
; x
++) {
1836 PyObject
* o
= PyList_GetItem(source
, x
);
1837 if (! PyInt_Check(o
)) {
1838 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1841 temp
[x
] = PyInt_AsLong(o
);
1847 long* long_LIST_helper(PyObject
* source
) {
1848 if (!PyList_Check(source
)) {
1849 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1852 int count
= PyList_Size(source
);
1853 long* temp
= new long[count
];
1855 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1858 for (int x
=0; x
<count
; x
++) {
1859 PyObject
* o
= PyList_GetItem(source
, x
);
1860 if (! PyInt_Check(o
)) {
1861 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1864 temp
[x
] = PyInt_AsLong(o
);
1870 char** string_LIST_helper(PyObject
* source
) {
1871 if (!PyList_Check(source
)) {
1872 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1875 int count
= PyList_Size(source
);
1876 char** temp
= new char*[count
];
1878 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1881 for (int x
=0; x
<count
; x
++) {
1882 PyObject
* o
= PyList_GetItem(source
, x
);
1883 if (! PyString_Check(o
)) {
1884 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1887 temp
[x
] = PyString_AsString(o
);
1892 //--------------------------------
1893 // Part of patch from Tim Hochberg
1894 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1895 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1896 point
->x
= PyInt_AS_LONG(o1
);
1897 point
->y
= PyInt_AS_LONG(o2
);
1900 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1901 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1902 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1905 if (PyInstance_Check(o1
) || PyInstance_Check(o2
)) {
1906 // Disallow instances because they can cause havok
1909 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1910 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1911 point
->x
= PyInt_AsLong(o1
);
1912 point
->y
= PyInt_AsLong(o2
);
1919 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1920 // Putting all of the declarations here allows
1921 // us to put the error handling all in one place.
1924 PyObject
*o
, *o1
, *o2
;
1925 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1927 if (!PySequence_Check(source
)) {
1931 // The length of the sequence is returned in count.
1932 *count
= PySequence_Length(source
);
1937 temp
= new wxPoint
[*count
];
1939 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1942 for (x
=0; x
<*count
; x
++) {
1943 // Get an item: try fast way first.
1945 o
= PySequence_Fast_GET_ITEM(source
, x
);
1948 o
= PySequence_GetItem(source
, x
);
1954 // Convert o to wxPoint.
1955 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1956 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1957 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1958 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1959 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1963 else if (PyInstance_Check(o
)) {
1965 if (SWIG_GetPtrObj(o
, (void **)&pt
, "_wxPoint_p")) {
1970 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1971 o1
= PySequence_GetItem(o
, 0);
1972 o2
= PySequence_GetItem(o
, 1);
1973 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1997 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2001 //------------------------------
2004 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2005 if (!PyList_Check(source
)) {
2006 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2009 int count
= PyList_Size(source
);
2010 wxBitmap
** temp
= new wxBitmap
*[count
];
2012 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2015 for (int x
=0; x
<count
; x
++) {
2016 PyObject
* o
= PyList_GetItem(source
, x
);
2017 if (PyInstance_Check(o
)) {
2019 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxBitmap_p")) {
2020 PyErr_SetString(PyExc_TypeError
,"Expected _wxBitmap_p.");
2026 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2035 wxString
* wxString_LIST_helper(PyObject
* source
) {
2036 if (!PyList_Check(source
)) {
2037 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2040 int count
= PyList_Size(source
);
2041 wxString
* temp
= new wxString
[count
];
2043 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2046 for (int x
=0; x
<count
; x
++) {
2047 PyObject
* o
= PyList_GetItem(source
, x
);
2048 #if PYTHON_API_VERSION >= 1009
2049 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2050 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2054 if (! PyString_Check(o
)) {
2055 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2060 wxString
* pStr
= wxString_in_helper(o
);
2068 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2069 if (!PyList_Check(source
)) {
2070 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2073 int count
= PyList_Size(source
);
2074 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2076 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2079 for (int x
=0; x
<count
; x
++) {
2080 PyObject
* o
= PyList_GetItem(source
, x
);
2081 if (PyInstance_Check(o
)) {
2082 wxAcceleratorEntry
* ae
;
2083 if (SWIG_GetPtrObj(o
, (void **) &ae
,"_wxAcceleratorEntry_p")) {
2084 PyErr_SetString(PyExc_TypeError
,"Expected _wxAcceleratorEntry_p.");
2089 else if (PyTuple_Check(o
)) {
2090 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2091 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2092 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2093 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2096 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2104 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2105 if (!PyList_Check(source
)) {
2106 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2109 int count
= PyList_Size(source
);
2110 wxPen
** temp
= new wxPen
*[count
];
2112 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2115 for (int x
=0; x
<count
; x
++) {
2116 PyObject
* o
= PyList_GetItem(source
, x
);
2117 if (PyInstance_Check(o
)) {
2119 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxPen_p")) {
2121 PyErr_SetString(PyExc_TypeError
,"Expected _wxPen_p.");
2128 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2136 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2137 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2140 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2144 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2145 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2148 o1
= PySequence_GetItem(source
, 0);
2149 o2
= PySequence_GetItem(source
, 1);
2152 *i1
= PyInt_AsLong(o1
);
2153 *i2
= PyInt_AsLong(o2
);
2163 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2164 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2165 PyObject
*o1
, *o2
, *o3
, *o4
;
2167 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2171 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2172 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2173 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2174 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2177 o1
= PySequence_GetItem(source
, 0);
2178 o2
= PySequence_GetItem(source
, 1);
2179 o3
= PySequence_GetItem(source
, 2);
2180 o4
= PySequence_GetItem(source
, 3);
2183 *i1
= PyInt_AsLong(o1
);
2184 *i2
= PyInt_AsLong(o2
);
2185 *i3
= PyInt_AsLong(o3
);
2186 *i4
= PyInt_AsLong(o4
);
2198 //----------------------------------------------------------------------
2200 bool wxSize_helper(PyObject
* source
, wxSize
** obj
) {
2202 // If source is an object instance then it may already be the right type
2203 if (PyInstance_Check(source
)) {
2205 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxSize_p"))
2210 // otherwise a 2-tuple of integers is expected
2211 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2212 PyObject
* o1
= PySequence_GetItem(source
, 0);
2213 PyObject
* o2
= PySequence_GetItem(source
, 1);
2214 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2219 **obj
= wxSize(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2226 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxSize object.");
2231 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
) {
2233 // If source is an object instance then it may already be the right type
2234 if (PyInstance_Check(source
)) {
2236 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint_p"))
2241 // otherwise a length-2 sequence of integers is expected
2242 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2243 PyObject
* o1
= PySequence_GetItem(source
, 0);
2244 PyObject
* o2
= PySequence_GetItem(source
, 1);
2245 // This should really check for integers, not numbers -- but that would break code.
2246 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2251 **obj
= wxPoint(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2257 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxPoint object.");
2263 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2265 // If source is an object instance then it may already be the right type
2266 if (PyInstance_Check(source
)) {
2268 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRealPoint_p"))
2273 // otherwise a 2-tuple of floats is expected
2274 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2275 PyObject
* o1
= PySequence_GetItem(source
, 0);
2276 PyObject
* o2
= PySequence_GetItem(source
, 1);
2277 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2282 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2289 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2296 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2298 // If source is an object instance then it may already be the right type
2299 if (PyInstance_Check(source
)) {
2301 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRect_p"))
2306 // otherwise a 4-tuple of integers is expected
2307 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2308 PyObject
* o1
= PySequence_GetItem(source
, 0);
2309 PyObject
* o2
= PySequence_GetItem(source
, 1);
2310 PyObject
* o3
= PySequence_GetItem(source
, 2);
2311 PyObject
* o4
= PySequence_GetItem(source
, 3);
2312 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2313 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2320 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2321 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2330 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2336 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2338 // If source is an object instance then it may already be the right type
2339 if (PyInstance_Check(source
)) {
2341 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxColour_p"))
2346 // otherwise check for a string
2347 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2348 wxString spec
= Py2wxString(source
);
2349 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2350 long red
, green
, blue
;
2351 red
= green
= blue
= 0;
2352 spec
.Mid(1,2).ToLong(&red
, 16);
2353 spec
.Mid(3,2).ToLong(&green
, 16);
2354 spec
.Mid(5,2).ToLong(&blue
, 16);
2356 **obj
= wxColour(red
, green
, blue
);
2359 else { // it's a colour name
2360 **obj
= wxColour(spec
);
2364 // last chance: 3-tuple of integers is expected
2365 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2366 PyObject
* o1
= PySequence_GetItem(source
, 0);
2367 PyObject
* o2
= PySequence_GetItem(source
, 1);
2368 PyObject
* o3
= PySequence_GetItem(source
, 2);
2369 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2375 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2383 PyErr_SetString(PyExc_TypeError
,
2384 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2390 bool wxPoint2DDouble_helper(PyObject
* source
, wxPoint2DDouble
** obj
) {
2391 // If source is an object instance then it may already be the right type
2392 if (PyInstance_Check(source
)) {
2393 wxPoint2DDouble
* ptr
;
2394 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint2DDouble_p"))
2399 // otherwise a length-2 sequence of floats is expected
2400 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2401 PyObject
* o1
= PySequence_GetItem(source
, 0);
2402 PyObject
* o2
= PySequence_GetItem(source
, 1);
2403 // This should really check for integers, not numbers -- but that would break code.
2404 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2409 **obj
= wxPoint2DDouble(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2415 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2421 //----------------------------------------------------------------------
2423 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2425 PyObject
* list
= PyList_New(0);
2426 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2428 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2430 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2432 PyList_Append(list
, str
);
2439 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2441 PyObject
* list
= PyList_New(0);
2442 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2443 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2444 PyList_Append(list
, number
);
2451 //----------------------------------------------------------------------
2452 //----------------------------------------------------------------------