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>
35 //----------------------------------------------------------------------
37 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
38 #error Python must support Unicode to use wxWindows Unicode
41 //----------------------------------------------------------------------
43 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
44 bool wxPyDoCleanup
= FALSE
;
45 bool wxPyDoingCleanup
= FALSE
;
48 #ifdef WXP_WITH_THREAD
49 struct wxPyThreadState
{
51 PyThreadState
* tstate
;
53 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
54 : tid(_tid
), tstate(_tstate
) {}
57 #include <wx/dynarray.h>
58 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
59 #include <wx/arrimpl.cpp>
60 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
62 wxPyThreadStateArray
* wxPyTStates
= NULL
;
63 wxMutex
* wxPyTMutex
= NULL
;
67 static PyObject
* wxPython_dict
= NULL
;
68 static PyObject
* wxPyPtrTypeMap
= NULL
;
69 static PyObject
* wxPyAssertionError
= NULL
;
72 #ifdef __WXMSW__ // If building for win32...
73 //----------------------------------------------------------------------
74 // This gets run when the DLL is loaded. We just need to save a handle.
75 //----------------------------------------------------------------------
78 HINSTANCE hinstDLL
, // handle to DLL module
79 DWORD fdwReason
, // reason for calling function
80 LPVOID lpvReserved
// reserved
83 // If wxPython is embedded in another wxWindows app then
84 // the inatance has already been set.
85 if (! wxGetInstance())
86 wxSetInstance(hinstDLL
);
91 //----------------------------------------------------------------------
92 // Classes for implementing the wxp main application shell.
93 //----------------------------------------------------------------------
95 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
99 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
103 wxPyApp::~wxPyApp() {
107 // This one isn't acutally called... We fake it with __wxStart()
108 bool wxPyApp::OnInit() {
113 int wxPyApp::MainLoop() {
116 DeletePendingObjects();
117 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
119 m_initialized
= initialized
;
123 if ( m_exitOnFrameDelete
== Later
) {
124 m_exitOnFrameDelete
= Yes
;
127 retval
= wxApp::MainLoop();
134 bool wxPyApp::OnInitGui() {
136 wxApp::OnInitGui(); // in this case always call the base class version
137 // wxPyBeginBlockThreads(); *** only called from within __wxStart so we already have the GIL
138 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
139 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
140 // wxPyEndBlockThreads(); ***
145 int wxPyApp::OnExit() {
147 wxPyBeginBlockThreads();
148 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
149 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
150 wxPyEndBlockThreads();
151 wxApp::OnExit(); // in this case always call the base class version
157 void wxPyApp::OnAssert(const wxChar
*file
,
162 // If the OnAssert is overloaded in the Python class then call it...
164 wxPyBeginBlockThreads();
165 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
166 PyObject
* fso
= wx2PyString(file
);
167 PyObject
* cso
= wx2PyString(file
);
170 mso
= wx2PyString(file
);
172 mso
= Py_None
; Py_INCREF(Py_None
);
174 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
179 wxPyEndBlockThreads();
181 // ...otherwise do our own thing with it
184 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
187 // turn it into a Python exception?
188 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
191 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
198 wxPyBeginBlockThreads();
199 PyObject
* s
= wx2PyString(buf
);
200 PyErr_SetObject(wxPyAssertionError
, s
);
202 wxPyEndBlockThreads();
204 // Now when control returns to whatever API wrapper was called from
205 // Python it should detect that an exception is set and will return
206 // NULL, signalling the exception to Python.
209 // Send it to the normal log destination, but only if
210 // not _DIALOG because it will call this too
211 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
214 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
223 // do the normal wx assert dialog?
224 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
225 wxApp::OnAssert(file
, line
, cond
, msg
);
232 bool wxPyApp::GetMacDefaultEncodingIsPC() {
234 return s_macDefaultEncodingIsPC
;
241 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
243 return s_macSupportPCMenuShortcuts
;
250 long wxPyApp::GetMacAboutMenuItemId() {
252 return s_macAboutMenuItemId
;
259 long wxPyApp::GetMacPreferencesMenuItemId() {
261 return s_macPreferencesMenuItemId
;
268 long wxPyApp::GetMacExitMenuItemId() {
270 return s_macExitMenuItemId
;
277 wxString
wxPyApp::GetMacHelpMenuTitleName() {
279 return s_macHelpMenuTitleName
;
281 return wxEmptyString
;
286 void wxPyApp::SetMacDefaultEncodingIsPC(bool val
) {
288 s_macDefaultEncodingIsPC
= val
;
293 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
295 s_macSupportPCMenuShortcuts
= val
;
300 void wxPyApp::SetMacAboutMenuItemId(long val
) {
302 s_macAboutMenuItemId
= val
;
307 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
309 s_macPreferencesMenuItemId
= val
;
314 void wxPyApp::SetMacExitMenuItemId(long val
) {
316 s_macExitMenuItemId
= val
;
321 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
323 s_macHelpMenuTitleName
= val
;
329 //---------------------------------------------------------------------
330 //----------------------------------------------------------------------
334 static char* wxPyCopyCString(const wxChar
* src
)
336 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
337 size_t len
= strlen(buff
);
338 char* dest
= new char[len
+1];
344 static char* wxPyCopyCString(const char* src
) // we need a char version too
346 size_t len
= strlen(src
);
347 char* dest
= new char[len
+1];
353 static wxChar
* wxPyCopyWString(const char *src
)
355 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
356 wxString
str(src
, *wxConvCurrent
);
357 return copystring(str
);
361 static wxChar
* wxPyCopyWString(const wxChar
*src
)
363 return copystring(src
);
369 //----------------------------------------------------------------------
371 // This function is called when the wxc module is imported to do some initial
372 // setup. (Before there is a wxApp object.)
373 void __wxPreStart(PyObject
* moduleDict
)
377 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
380 #ifdef WXP_WITH_THREAD
381 PyEval_InitThreads();
382 wxPyTStates
= new wxPyThreadStateArray
;
383 wxPyTMutex
= new wxMutex
;
386 // Ensure that the build options in the DLL (or whatever) match this build
387 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
389 // Create an exception object to use for wxASSERTions
390 wxPyAssertionError
= PyErr_NewException("wxPython.wxc.wxPyAssertionError",
391 PyExc_AssertionError
, NULL
);
392 PyDict_SetItemString(moduleDict
, "wxPyAssertionError", wxPyAssertionError
);
397 // Initialize wxWindows and bootstrap the user application by calling the
398 // wxApp's OnInit, which is a parameter to this funciton. See wxApp.__init__
399 // in _extras.py to learn how the bootstrap is started.
400 PyObject
* __wxStart(PyObject
* /* self */, PyObject
* args
)
402 PyObject
* onInitFunc
= NULL
;
403 PyObject
* arglist
= NULL
;
404 PyObject
* result
= NULL
;
405 PyObject
* pyint
= NULL
;
408 if (!PyArg_ParseTuple(args
, "O", &onInitFunc
))
411 // Get any command-line args passed to this program from the sys module
414 PyObject
* sysargv
= PySys_GetObject("argv");
415 if (sysargv
!= NULL
) {
416 argc
= PyList_Size(sysargv
);
417 argv
= new char*[argc
+1];
419 for(x
=0; x
<argc
; x
++) {
420 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
421 argv
[x
] = PyString_AsString(pyArg
);
426 if (! wxEntryStart(argc
, argv
) ) {
427 PyErr_SetString(PyExc_SystemError
, // is this the right one?
428 "wxEntryStart failed!");
434 // The stock objects were all NULL when they were loaded into
435 // SWIG generated proxies, so re-init those now...
436 wxPy_ReinitStockObjects();
439 // Call the Python wxApp's OnInit function
440 arglist
= PyTuple_New(0);
441 result
= PyEval_CallObject(onInitFunc
, arglist
);
443 if (!result
) { // an exception was raised.
447 pyint
= PyNumber_Int(result
);
449 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
452 bResult
= PyInt_AS_LONG(pyint
);
454 PyErr_SetString(PyExc_SystemExit
, "OnInit returned FALSE, exiting...");
459 wxTheApp
->m_initialized
= (wxTopLevelWindows
.GetCount() > 0);
476 wxPyDoingCleanup
= TRUE
;
479 #ifdef WXP_WITH_THREAD
482 wxPyTStates
->Empty();
491 PyObject
* __wxSetDictionary(PyObject
* /* self */, PyObject
* args
)
494 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
497 if (!PyDict_Check(wxPython_dict
)) {
498 PyErr_SetString(PyExc_TypeError
, "_wxSetDictionary must have dictionary object!");
502 if (! wxPyPtrTypeMap
)
503 wxPyPtrTypeMap
= PyDict_New();
504 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
508 #define wxPlatform "__WXMOTIF__"
511 #define wxPlatform "__WXX11__"
514 #define wxPlatform "__WXGTK__"
516 #if defined(__WIN32__) || defined(__WXMSW__)
517 #define wxPlatform "__WXMSW__"
520 #define wxPlatform "__WXMAC__"
529 PyDict_SetItemString(wxPython_dict
, "wxPlatform", PyString_FromString(wxPlatform
));
530 PyDict_SetItemString(wxPython_dict
, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
531 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
538 //---------------------------------------------------------------------------
540 // The stock objects are no longer created when the wxc module is imported, but
541 // only after the app object has been created. This function will be called before
542 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
544 void wxPy_ReinitStockObjects()
552 #define REINITOBJ(name, type) \
553 obj = PyDict_GetItemString(wxPython_dict, #name); \
554 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
555 SWIG_MakePtr(ptrbuf, (char *) name, "_" #type "_p"); \
556 ptrobj = PyString_FromString(ptrbuf); \
557 PyObject_SetAttrString(obj, "this", ptrobj); \
560 #define REINITOBJ2(name, type) \
561 obj = PyDict_GetItemString(wxPython_dict, #name); \
562 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
563 SWIG_MakePtr(ptrbuf, (char *) &name, "_" #type "_p"); \
564 ptrobj = PyString_FromString(ptrbuf); \
565 PyObject_SetAttrString(obj, "this", ptrobj); \
569 REINITOBJ(wxNORMAL_FONT
, wxFont
);
570 REINITOBJ(wxSMALL_FONT
, wxFont
);
571 REINITOBJ(wxITALIC_FONT
, wxFont
);
572 REINITOBJ(wxSWISS_FONT
, wxFont
);
574 REINITOBJ(wxRED_PEN
, wxPen
);
575 REINITOBJ(wxCYAN_PEN
, wxPen
);
576 REINITOBJ(wxGREEN_PEN
, wxPen
);
577 REINITOBJ(wxBLACK_PEN
, wxPen
);
578 REINITOBJ(wxWHITE_PEN
, wxPen
);
579 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
580 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
581 REINITOBJ(wxGREY_PEN
, wxPen
);
582 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
583 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
585 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
586 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
587 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
588 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
589 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
590 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
591 REINITOBJ(wxRED_BRUSH
, wxBrush
);
592 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
593 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
594 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
596 REINITOBJ(wxBLACK
, wxColour
);
597 REINITOBJ(wxWHITE
, wxColour
);
598 REINITOBJ(wxRED
, wxColour
);
599 REINITOBJ(wxBLUE
, wxColour
);
600 REINITOBJ(wxGREEN
, wxColour
);
601 REINITOBJ(wxCYAN
, wxColour
);
602 REINITOBJ(wxLIGHT_GREY
, wxColour
);
604 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
605 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
606 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
608 REINITOBJ2(wxNullBitmap
, wxBitmap
);
609 REINITOBJ2(wxNullIcon
, wxIcon
);
610 REINITOBJ2(wxNullCursor
, wxCursor
);
611 REINITOBJ2(wxNullPen
, wxPen
);
612 REINITOBJ2(wxNullBrush
, wxBrush
);
613 REINITOBJ2(wxNullPalette
, wxPalette
);
614 REINITOBJ2(wxNullFont
, wxFont
);
615 REINITOBJ2(wxNullColour
, wxColour
);
617 REINITOBJ(wxTheFontList
, wxFontList
);
618 REINITOBJ(wxThePenList
, wxPenList
);
619 REINITOBJ(wxTheBrushList
, wxBrushList
);
620 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
623 REINITOBJ(wxTheClipboard
, wxClipboard
);
624 REINITOBJ(wxTheMimeTypesManager
, wxMimeTypesManager
);
625 REINITOBJ2(wxDefaultValidator
, wxValidator
);
626 REINITOBJ2(wxNullImage
, wxImage
);
627 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
633 //---------------------------------------------------------------------------
635 void wxPyClientData_dtor(wxPyClientData
* self
) {
636 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
637 // may have already garbage collected the object...
638 wxPyBeginBlockThreads();
639 Py_DECREF(self
->m_obj
);
640 wxPyEndBlockThreads();
644 void wxPyUserData_dtor(wxPyUserData
* self
) {
645 if (! wxPyDoingCleanup
) {
646 wxPyBeginBlockThreads();
647 Py_DECREF(self
->m_obj
);
648 wxPyEndBlockThreads();
653 // This is called when an OOR controled object is being destroyed. Although
654 // the C++ object is going away there is no way to force the Python object
655 // (and all references to it) to die too. This causes problems (crashes) in
656 // wxPython when a python shadow object attempts to call a C++ method using
657 // the now bogus pointer... So to try and prevent this we'll do a little black
658 // magic and change the class of the python instance to a class that will
659 // raise an exception for any attempt to call methods with it. See
660 // _wxPyDeadObject in _extras.py for the implementation of this class.
661 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
663 static PyObject
* deadObjectClass
= NULL
;
665 wxPyBeginBlockThreads();
666 if (deadObjectClass
== NULL
) {
667 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
668 wxASSERT_MSG(deadObjectClass
!= NULL
, wxT("Can't get _wxPyDeadObject class!"));
669 Py_INCREF(deadObjectClass
);
673 // Only if there is more than one reference to the object
674 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
675 wxASSERT_MSG(PyInstance_Check(self
->m_obj
), wxT("m_obj not an instance!?!?!"));
677 // Call __del__, if there is one.
678 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
680 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
684 if (PyErr_Occurred())
685 PyErr_Clear(); // just ignore it for now
687 // Clear the instance's dictionary
688 PyInstanceObject
* inst
= (PyInstanceObject
*)self
->m_obj
;
689 PyDict_Clear(inst
->in_dict
);
691 // put the name of the old class into the instance, and then reset the
692 // class to be the dead class.
693 PyDict_SetItemString(inst
->in_dict
, "_name", inst
->in_class
->cl_name
);
694 inst
->in_class
= (PyClassObject
*)deadObjectClass
;
695 Py_INCREF(deadObjectClass
);
698 // m_obj is DECREF's in the base class dtor...
699 wxPyEndBlockThreads();
703 //---------------------------------------------------------------------------
704 // Stuff used by OOR to find the right wxPython class type to return and to
708 // The pointer type map is used when the "pointer" type name generated by SWIG
709 // is not the same as the shadow class name, for example wxPyTreeCtrl
710 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
711 // so we'll just make it a Python dictionary in the wx module's namespace.
712 // (See __wxSetDictionary)
713 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
714 if (! wxPyPtrTypeMap
)
715 wxPyPtrTypeMap
= PyDict_New();
716 PyDict_SetItemString(wxPyPtrTypeMap
,
718 PyString_FromString((char*)ptrName
));
723 PyObject
* wxPyClassExists(const wxString
& className
) {
726 wxString
name(className
);
727 char buff
[64]; // should always be big enough...
732 // Try the name as-is first
733 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
734 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
736 // if not found see if there is a mapped name for it
738 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
739 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
740 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
741 classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
745 return classobj
; // returns NULL if not found
749 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
750 PyObject
* target
= NULL
;
751 bool isEvtHandler
= FALSE
;
754 // If it's derived from wxEvtHandler then there may
755 // already be a pointer to a Python object that we can use
757 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
759 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
760 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
762 target
= data
->m_obj
;
768 // Otherwise make it the old fashioned way by making a
769 // new shadow object and putting this pointer in it.
770 wxClassInfo
* info
= source
->GetClassInfo();
771 wxString name
= info
->GetClassName();
772 PyObject
* klass
= wxPyClassExists(name
);
773 while (info
&& !klass
) {
774 name
= (wxChar
*)info
->GetBaseClassName1();
775 info
= wxClassInfo::FindClass(name
);
776 klass
= wxPyClassExists(name
);
779 target
= wxPyConstructObject(source
, name
, klass
, FALSE
);
780 if (target
&& isEvtHandler
)
781 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
783 wxString
msg(wxT("wxPython class not found for "));
784 msg
+= source
->GetClassInfo()->GetClassName();
785 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
789 } else { // source was NULL so return None.
790 Py_INCREF(Py_None
); target
= Py_None
;
796 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
797 PyObject
* target
= NULL
;
799 if (source
&& wxIsKindOf(source
, wxSizer
)) {
800 // If it's derived from wxSizer then there may
801 // already be a pointer to a Python object that we can use
803 wxSizer
* sz
= (wxSizer
*)source
;
804 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
806 target
= data
->m_obj
;
811 target
= wxPyMake_wxObject(source
, FALSE
);
812 if (target
!= Py_None
)
813 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
820 //---------------------------------------------------------------------------
822 PyObject
* wxPyConstructObject(void* ptr
,
823 const wxString
& className
,
830 wxString
name(className
);
831 char swigptr
[64]; // should always be big enough...
834 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
835 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
837 sprintf(buff
, "_%s_p", (const char*)name
.mbc_str());
838 SWIG_MakePtr(swigptr
, ptr
, buff
);
840 arg
= Py_BuildValue("(s)", swigptr
);
841 obj
= PyInstance_New(klass
, arg
, NULL
);
845 PyObject
* one
= PyInt_FromLong(1);
846 PyObject_SetAttrString(obj
, "thisown", one
);
854 PyObject
* wxPyConstructObject(void* ptr
,
855 const wxString
& className
,
862 char buff
[64]; // should always be big enough...
863 sprintf(buff
, "%sPtr", (const char*)className
.mbc_str());
865 wxASSERT_MSG(wxPython_dict
, wxT("wxPython_dict is not set yet!!"));
867 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
869 wxString
msg(wxT("wxPython class not found for "));
871 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
875 return wxPyConstructObject(ptr
, className
, classobj
, setThisOwn
);
879 //---------------------------------------------------------------------------
882 #ifdef WXP_WITH_THREAD
884 unsigned long wxPyGetCurrentThreadId() {
885 return wxThread::GetCurrentId();
888 static PyThreadState
* gs_shutdownTState
;
890 PyThreadState
* wxPyGetThreadState() {
891 if (wxPyTMutex
== NULL
) // Python is shutting down...
892 return gs_shutdownTState
;
894 unsigned long ctid
= wxPyGetCurrentThreadId();
895 PyThreadState
* tstate
= NULL
;
898 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
899 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
900 if (info
.tid
== ctid
) {
901 tstate
= info
.tstate
;
905 wxPyTMutex
->Unlock();
906 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
911 void wxPySaveThreadState(PyThreadState
* tstate
) {
912 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
913 gs_shutdownTState
= tstate
;
916 unsigned long ctid
= wxPyGetCurrentThreadId();
918 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
919 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
920 if (info
.tid
== ctid
) {
922 if (info
.tstate
!= tstate
)
923 wxLogMessage("*** tstate mismatch!???");
925 // info.tstate = tstate; *** DO NOT update existing ones???
926 // Normally it will never change, but apparently COM callbacks
927 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
928 // tstate which will then be garbage the next time we try to use
930 wxPyTMutex
->Unlock();
934 // not found, so add it...
935 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
936 wxPyTMutex
->Unlock();
942 // Calls from Python to wxWindows code are wrapped in calls to these
945 PyThreadState
* wxPyBeginAllowThreads() {
946 #ifdef WXP_WITH_THREAD
947 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
948 wxPySaveThreadState(saved
);
955 void wxPyEndAllowThreads(PyThreadState
* saved
) {
956 #ifdef WXP_WITH_THREAD
957 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
963 // Calls from wxWindows back to Python code, or even any PyObject
964 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
966 void wxPyBeginBlockThreads() {
967 #ifdef WXP_WITH_THREAD
968 PyThreadState
* tstate
= wxPyGetThreadState();
969 PyEval_RestoreThread(tstate
);
974 void wxPyEndBlockThreads() {
975 #ifdef WXP_WITH_THREAD
976 // Is there any need to save it again?
977 // PyThreadState* tstate =
983 //---------------------------------------------------------------------------
984 // wxPyInputStream and wxPyCBInputStream methods
987 void wxPyInputStream::close() {
988 /* do nothing for now */
991 void wxPyInputStream::flush() {
992 /* do nothing for now */
995 bool wxPyInputStream::eof() {
997 return m_wxis
->Eof();
1002 wxPyInputStream::~wxPyInputStream() {
1009 PyObject
* wxPyInputStream::read(int size
) {
1010 PyObject
* obj
= NULL
;
1012 const int BUFSIZE
= 1024;
1014 // check if we have a real wxInputStream to work with
1016 wxPyBeginBlockThreads();
1017 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1018 wxPyEndBlockThreads();
1023 // read while bytes are available on the stream
1024 while ( m_wxis
->CanRead() ) {
1025 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1026 buf
.UngetAppendBuf(m_wxis
->LastRead());
1029 } else { // Read only size number of characters
1030 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1031 buf
.UngetWriteBuf(m_wxis
->LastRead());
1035 wxPyBeginBlockThreads();
1036 wxStreamError err
= m_wxis
->GetLastError();
1037 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1038 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1041 // We use only strings for the streams, not unicode
1042 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1044 wxPyEndBlockThreads();
1049 PyObject
* wxPyInputStream::readline(int size
) {
1050 PyObject
* obj
= NULL
;
1055 // check if we have a real wxInputStream to work with
1057 wxPyBeginBlockThreads();
1058 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1059 wxPyEndBlockThreads();
1063 // read until \n or byte limit reached
1064 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1065 ch
= m_wxis
->GetC();
1070 wxPyBeginBlockThreads();
1071 wxStreamError err
= m_wxis
->GetLastError();
1072 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1073 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1076 // We use only strings for the streams, not unicode
1077 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1079 wxPyEndBlockThreads();
1084 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1087 // check if we have a real wxInputStream to work with
1089 wxPyBeginBlockThreads();
1090 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1091 wxPyEndBlockThreads();
1096 wxPyBeginBlockThreads();
1097 pylist
= PyList_New(0);
1099 wxPyBeginBlockThreads();
1101 wxPyEndBlockThreads();
1105 // read sizehint bytes or until EOF
1107 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1108 PyObject
* s
= this->readline();
1110 wxPyBeginBlockThreads();
1112 wxPyEndBlockThreads();
1115 wxPyBeginBlockThreads();
1116 PyList_Append(pylist
, s
);
1117 i
+= PyString_Size(s
);
1118 wxPyEndBlockThreads();
1122 wxStreamError err
= m_wxis
->GetLastError();
1123 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1124 wxPyBeginBlockThreads();
1126 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1127 wxPyEndBlockThreads();
1135 void wxPyInputStream::seek(int offset
, int whence
) {
1137 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1140 int wxPyInputStream::tell(){
1142 return m_wxis
->TellI();
1149 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1150 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1154 wxPyCBInputStream::~wxPyCBInputStream() {
1155 if (m_block
) wxPyBeginBlockThreads();
1159 if (m_block
) wxPyEndBlockThreads();
1163 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1164 if (block
) wxPyBeginBlockThreads();
1166 PyObject
* read
= getMethod(py
, "read");
1167 PyObject
* seek
= getMethod(py
, "seek");
1168 PyObject
* tell
= getMethod(py
, "tell");
1171 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1175 if (block
) wxPyEndBlockThreads();
1179 if (block
) wxPyEndBlockThreads();
1180 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1184 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1185 return wxPyCBInputStream::create(py
, block
);
1188 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1189 if (!PyObject_HasAttrString(py
, name
))
1191 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1192 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1200 size_t wxPyCBInputStream::GetSize() const {
1201 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1202 if (m_seek
&& m_tell
) {
1203 off_t temp
= self
->OnSysTell();
1204 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1205 self
->OnSysSeek(temp
, wxFromStart
);
1213 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1217 wxPyBeginBlockThreads();
1218 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1219 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1223 if ((result
!= NULL
) && PyString_Check(result
)) {
1224 o
= PyString_Size(result
);
1226 m_lasterror
= wxSTREAM_EOF
;
1229 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1234 m_lasterror
= wxSTREAM_READ_ERROR
;
1235 wxPyEndBlockThreads();
1239 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1240 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1244 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1245 wxPyBeginBlockThreads();
1247 // off_t is a 64-bit value...
1248 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1250 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1252 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1255 wxPyEndBlockThreads();
1260 off_t
wxPyCBInputStream::OnSysTell() const {
1261 wxPyBeginBlockThreads();
1262 PyObject
* arglist
= Py_BuildValue("()");
1263 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1266 if (result
!= NULL
) {
1268 if (PyLong_Check(result
))
1269 o
= PyLong_AsLongLong(result
);
1272 o
= PyInt_AsLong(result
);
1276 wxPyEndBlockThreads();
1280 //----------------------------------------------------------------------
1282 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1284 wxPyCallback::wxPyCallback(PyObject
* func
) {
1289 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1290 m_func
= other
.m_func
;
1294 wxPyCallback::~wxPyCallback() {
1295 wxPyBeginBlockThreads();
1297 wxPyEndBlockThreads();
1302 // This function is used for all events destined for Python event handlers.
1303 void wxPyCallback::EventThunker(wxEvent
& event
) {
1304 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1305 PyObject
* func
= cb
->m_func
;
1309 bool checkSkip
= FALSE
;
1311 wxPyBeginBlockThreads();
1312 wxString className
= event
.GetClassInfo()->GetClassName();
1314 // If the event is one of these types then pass the original
1315 // event object instead of the one passed to us.
1316 if ( className
== wxT("wxPyEvent") ) {
1317 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1318 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1320 else if ( className
== wxT("wxPyCommandEvent") ) {
1321 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1322 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1325 arg
= wxPyConstructObject((void*)&event
, className
);
1328 // Call the event handler, passing the event object
1329 tuple
= PyTuple_New(1);
1330 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1331 result
= PyEval_CallObject(func
, tuple
);
1333 Py_DECREF(result
); // result is ignored, but we still need to decref it
1334 PyErr_Clear(); // Just in case...
1340 // if the event object was one of our special types and
1341 // it had been cloned, then we need to extract the Skipped
1342 // value from the original and set it in the clone.
1343 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1345 event
.Skip(PyInt_AsLong(result
));
1353 wxPyEndBlockThreads();
1357 //----------------------------------------------------------------------
1359 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1361 m_self
= other
.m_self
;
1362 m_class
= other
.m_class
;
1370 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1381 #if PYTHON_API_VERSION >= 1011
1383 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1384 // in which the method was defined. Starting with 2.2 it returns
1385 // "class that asked for the method" which seems totally bogus to me
1386 // but apprently it fixes some obscure problem waiting to happen in
1387 // Python. Since the API was not documented Guido and the gang felt
1388 // safe in changing it. Needless to say that totally screwed up the
1389 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1390 // code to find the class where the method is actually defined...
1393 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1397 if (PyType_Check(klass
)) { // new style classes
1398 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1399 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1400 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1401 PyObject
*mro
, *res
, *base
, *dict
;
1402 /* Look in tp_dict of types in MRO */
1404 assert(PyTuple_Check(mro
));
1405 n
= PyTuple_GET_SIZE(mro
);
1406 for (i
= 0; i
< n
; i
++) {
1407 base
= PyTuple_GET_ITEM(mro
, i
);
1408 if (PyClass_Check(base
))
1409 dict
= ((PyClassObject
*)base
)->cl_dict
;
1411 assert(PyType_Check(base
));
1412 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1414 assert(dict
&& PyDict_Check(dict
));
1415 res
= PyDict_GetItem(dict
, name
);
1422 else if (PyClass_Check(klass
)) { // old style classes
1423 // This code is borrowed/adapted from class_lookup in classobject.c
1424 PyClassObject
* cp
= (PyClassObject
*)klass
;
1425 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1426 if (value
!= NULL
) {
1427 return (PyObject
*)cp
;
1429 n
= PyTuple_Size(cp
->cl_bases
);
1430 for (i
= 0; i
< n
; i
++) {
1431 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1432 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1444 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1446 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1448 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1450 #else // 2.2 and after, the hard way...
1452 PyObject
* nameo
= PyString_FromString(name
);
1453 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1461 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1462 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1463 self
->m_lastFound
= NULL
;
1465 // If the object (m_self) has an attibute of the given name...
1466 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1467 PyObject
*method
, *klass
;
1468 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1470 // ...and if that attribute is a method, and if that method's class is
1471 // not from a base class...
1472 if (PyMethod_Check(method
) &&
1473 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1474 ((klass
== m_class
) || PyClass_IsSubclass(klass
, m_class
))) {
1476 // ...then we'll save a pointer to the method so callCallback can call it.
1477 self
->m_lastFound
= method
;
1483 return m_lastFound
!= NULL
;
1487 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1491 result
= callCallbackObj(argTuple
);
1492 if (result
) { // Assumes an integer return type...
1493 retval
= PyInt_AsLong(result
);
1495 PyErr_Clear(); // forget about it if it's not...
1500 // Invoke the Python callable object, returning the raw PyObject return
1501 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1502 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1505 // Save a copy of the pointer in case the callback generates another
1506 // callback. In that case m_lastFound will have a different value when
1507 // it gets back here...
1508 PyObject
* method
= m_lastFound
;
1510 result
= PyEval_CallObject(method
, argTuple
);
1511 Py_DECREF(argTuple
);
1520 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1521 cbh
.setSelf(self
, klass
, incref
);
1524 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1525 return cbh
.findCallback(name
);
1528 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1529 return cbh
.callCallback(argTuple
);
1532 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1533 return cbh
.callCallbackObj(argTuple
);
1537 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1538 if (cbh
->m_incRef
) {
1539 wxPyBeginBlockThreads();
1540 Py_XDECREF(cbh
->m_self
);
1541 Py_XDECREF(cbh
->m_class
);
1542 wxPyEndBlockThreads();
1546 //---------------------------------------------------------------------------
1547 //---------------------------------------------------------------------------
1548 // These event classes can be derived from in Python and passed through the event
1549 // system without losing anything. They do this by keeping a reference to
1550 // themselves and some special case handling in wxPyCallback::EventThunker.
1553 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1554 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1555 //Py_INCREF(m_self); // circular loops...
1559 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1560 wxPyBeginBlockThreads();
1563 wxPyEndBlockThreads();
1566 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1567 wxPyBeginBlockThreads();
1575 wxPyEndBlockThreads();
1578 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1584 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1585 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1588 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1589 : wxEvent(winid
, commandType
) {
1593 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1596 SetSelf(evt
.m_self
, TRUE
);
1600 wxPyEvent::~wxPyEvent() {
1604 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1605 : wxCommandEvent(commandType
, id
) {
1609 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1610 : wxCommandEvent(evt
)
1612 SetSelf(evt
.m_self
, TRUE
);
1616 wxPyCommandEvent::~wxPyCommandEvent() {
1622 //---------------------------------------------------------------------------
1623 //---------------------------------------------------------------------------
1626 wxPyTimer::wxPyTimer(PyObject
* callback
) {
1631 wxPyTimer::~wxPyTimer() {
1632 wxPyBeginBlockThreads();
1634 wxPyEndBlockThreads();
1637 void wxPyTimer::Notify() {
1638 if (!func
|| func
== Py_None
) {
1642 wxPyBeginBlockThreads();
1645 PyObject
* args
= Py_BuildValue("()");
1647 result
= PyEval_CallObject(func
, args
);
1656 wxPyEndBlockThreads();
1662 //---------------------------------------------------------------------------
1663 //---------------------------------------------------------------------------
1664 // Convert a wxList to a Python List
1666 PyObject
* wxPy_ConvertList(wxListBase
* listbase
, const char* className
) {
1667 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1671 wxNode
* node
= list
->GetFirst();
1673 wxPyBeginBlockThreads();
1674 pyList
= PyList_New(0);
1676 wxObj
= node
->GetData();
1677 pyObj
= wxPyMake_wxObject(wxObj
); //wxPyConstructObject(wxObj, className);
1678 PyList_Append(pyList
, pyObj
);
1679 node
= node
->GetNext();
1681 wxPyEndBlockThreads();
1685 //----------------------------------------------------------------------
1687 long wxPyGetWinHandle(wxWindow
* win
) {
1689 return (long)win
->GetHandle();
1692 // Find and return the actual X-Window.
1694 if (win
->m_wxwindow
) {
1696 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1698 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1700 return (long)bwin
->xwindow
;
1708 //----------------------------------------------------------------------
1709 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1710 // included in every file over and over again...
1712 #if PYTHON_API_VERSION >= 1009
1713 static char* wxStringErrorMsg
= "String or Unicode type required";
1715 static char* wxStringErrorMsg
= "String type required";
1719 wxString
* wxString_in_helper(PyObject
* source
) {
1721 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1722 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1723 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1727 if (PyUnicode_Check(source
)) {
1728 target
= new wxString();
1729 size_t len
= PyUnicode_GET_SIZE(source
);
1731 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1732 target
->UngetWriteBuf();
1735 // It is a string, get pointers to it and transform to unicode
1736 char* tmpPtr
; int tmpSize
;
1737 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1738 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1741 char* tmpPtr
; int tmpSize
;
1742 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1743 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1746 target
= new wxString(tmpPtr
, tmpSize
);
1747 #endif // wxUSE_UNICODE
1749 #else // No Python unicode API (1.5.2)
1750 if (!PyString_Check(source
)) {
1751 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1754 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1760 // Similar to above except doesn't use "new" and doesn't set an exception
1761 wxString
Py2wxString(PyObject
* source
)
1764 bool doDecRef
= FALSE
;
1766 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1767 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1768 // Convert to String if not one already... (TODO: Unicode too?)
1769 source
= PyObject_Str(source
);
1774 if (PyUnicode_Check(source
)) {
1775 size_t len
= PyUnicode_GET_SIZE(source
);
1777 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1778 target
.UngetWriteBuf();
1781 // It is a string, get pointers to it and transform to unicode
1782 char* tmpPtr
; int tmpSize
;
1783 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1784 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1787 char* tmpPtr
; int tmpSize
;
1788 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1789 target
= wxString(tmpPtr
, tmpSize
);
1790 #endif // wxUSE_UNICODE
1792 #else // No Python unicode API (1.5.2)
1793 if (!PyString_Check(source
)) {
1794 // Convert to String if not one already...
1795 source
= PyObject_Str(source
);
1798 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1807 // Make either a Python String or Unicode object, depending on build mode
1808 PyObject
* wx2PyString(const wxString
& src
)
1812 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1814 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1820 //----------------------------------------------------------------------
1823 byte
* byte_LIST_helper(PyObject
* source
) {
1824 if (!PyList_Check(source
)) {
1825 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1828 int count
= PyList_Size(source
);
1829 byte
* temp
= new byte
[count
];
1831 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1834 for (int x
=0; x
<count
; x
++) {
1835 PyObject
* o
= PyList_GetItem(source
, x
);
1836 if (! PyInt_Check(o
)) {
1837 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1840 temp
[x
] = (byte
)PyInt_AsLong(o
);
1846 int* int_LIST_helper(PyObject
* source
) {
1847 if (!PyList_Check(source
)) {
1848 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1851 int count
= PyList_Size(source
);
1852 int* temp
= new int[count
];
1854 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1857 for (int x
=0; x
<count
; x
++) {
1858 PyObject
* o
= PyList_GetItem(source
, x
);
1859 if (! PyInt_Check(o
)) {
1860 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1863 temp
[x
] = PyInt_AsLong(o
);
1869 long* long_LIST_helper(PyObject
* source
) {
1870 if (!PyList_Check(source
)) {
1871 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1874 int count
= PyList_Size(source
);
1875 long* temp
= new long[count
];
1877 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1880 for (int x
=0; x
<count
; x
++) {
1881 PyObject
* o
= PyList_GetItem(source
, x
);
1882 if (! PyInt_Check(o
)) {
1883 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1886 temp
[x
] = PyInt_AsLong(o
);
1892 char** string_LIST_helper(PyObject
* source
) {
1893 if (!PyList_Check(source
)) {
1894 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1897 int count
= PyList_Size(source
);
1898 char** temp
= new char*[count
];
1900 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1903 for (int x
=0; x
<count
; x
++) {
1904 PyObject
* o
= PyList_GetItem(source
, x
);
1905 if (! PyString_Check(o
)) {
1906 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1909 temp
[x
] = PyString_AsString(o
);
1914 //--------------------------------
1915 // Part of patch from Tim Hochberg
1916 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1917 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1918 point
->x
= PyInt_AS_LONG(o1
);
1919 point
->y
= PyInt_AS_LONG(o2
);
1922 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1923 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1924 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1927 if (PyInstance_Check(o1
) || PyInstance_Check(o2
)) {
1928 // Disallow instances because they can cause havok
1931 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1932 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1933 point
->x
= PyInt_AsLong(o1
);
1934 point
->y
= PyInt_AsLong(o2
);
1941 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1942 // Putting all of the declarations here allows
1943 // us to put the error handling all in one place.
1946 PyObject
*o
, *o1
, *o2
;
1947 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1949 if (!PySequence_Check(source
)) {
1953 // The length of the sequence is returned in count.
1954 *count
= PySequence_Length(source
);
1959 temp
= new wxPoint
[*count
];
1961 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1964 for (x
=0; x
<*count
; x
++) {
1965 // Get an item: try fast way first.
1967 o
= PySequence_Fast_GET_ITEM(source
, x
);
1970 o
= PySequence_GetItem(source
, x
);
1976 // Convert o to wxPoint.
1977 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1978 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1979 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1980 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1981 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1985 else if (PyInstance_Check(o
)) {
1987 if (SWIG_GetPtrObj(o
, (void **)&pt
, "_wxPoint_p")) {
1992 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1993 o1
= PySequence_GetItem(o
, 0);
1994 o2
= PySequence_GetItem(o
, 1);
1995 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2019 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2023 //------------------------------
2026 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2027 if (!PyList_Check(source
)) {
2028 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2031 int count
= PyList_Size(source
);
2032 wxBitmap
** temp
= new wxBitmap
*[count
];
2034 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2037 for (int x
=0; x
<count
; x
++) {
2038 PyObject
* o
= PyList_GetItem(source
, x
);
2039 if (PyInstance_Check(o
)) {
2041 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxBitmap_p")) {
2042 PyErr_SetString(PyExc_TypeError
,"Expected _wxBitmap_p.");
2048 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2057 wxString
* wxString_LIST_helper(PyObject
* source
) {
2058 if (!PyList_Check(source
)) {
2059 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2062 int count
= PyList_Size(source
);
2063 wxString
* temp
= new wxString
[count
];
2065 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2068 for (int x
=0; x
<count
; x
++) {
2069 PyObject
* o
= PyList_GetItem(source
, x
);
2070 #if PYTHON_API_VERSION >= 1009
2071 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2072 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2076 if (! PyString_Check(o
)) {
2077 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2082 wxString
* pStr
= wxString_in_helper(o
);
2090 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2091 if (!PyList_Check(source
)) {
2092 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2095 int count
= PyList_Size(source
);
2096 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2098 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2101 for (int x
=0; x
<count
; x
++) {
2102 PyObject
* o
= PyList_GetItem(source
, x
);
2103 if (PyInstance_Check(o
)) {
2104 wxAcceleratorEntry
* ae
;
2105 if (SWIG_GetPtrObj(o
, (void **) &ae
,"_wxAcceleratorEntry_p")) {
2106 PyErr_SetString(PyExc_TypeError
,"Expected _wxAcceleratorEntry_p.");
2111 else if (PyTuple_Check(o
)) {
2112 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2113 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2114 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2115 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2118 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2126 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2127 if (!PyList_Check(source
)) {
2128 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2131 int count
= PyList_Size(source
);
2132 wxPen
** temp
= new wxPen
*[count
];
2134 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2137 for (int x
=0; x
<count
; x
++) {
2138 PyObject
* o
= PyList_GetItem(source
, x
);
2139 if (PyInstance_Check(o
)) {
2141 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxPen_p")) {
2143 PyErr_SetString(PyExc_TypeError
,"Expected _wxPen_p.");
2150 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2158 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2159 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2162 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2166 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2167 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2170 o1
= PySequence_GetItem(source
, 0);
2171 o2
= PySequence_GetItem(source
, 1);
2174 *i1
= PyInt_AsLong(o1
);
2175 *i2
= PyInt_AsLong(o2
);
2185 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2186 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2187 PyObject
*o1
, *o2
, *o3
, *o4
;
2189 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2193 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2194 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2195 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2196 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2199 o1
= PySequence_GetItem(source
, 0);
2200 o2
= PySequence_GetItem(source
, 1);
2201 o3
= PySequence_GetItem(source
, 2);
2202 o4
= PySequence_GetItem(source
, 3);
2205 *i1
= PyInt_AsLong(o1
);
2206 *i2
= PyInt_AsLong(o2
);
2207 *i3
= PyInt_AsLong(o3
);
2208 *i4
= PyInt_AsLong(o4
);
2220 //----------------------------------------------------------------------
2222 bool wxSize_helper(PyObject
* source
, wxSize
** obj
) {
2224 // If source is an object instance then it may already be the right type
2225 if (PyInstance_Check(source
)) {
2227 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxSize_p"))
2232 // otherwise a 2-tuple of integers is expected
2233 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2234 PyObject
* o1
= PySequence_GetItem(source
, 0);
2235 PyObject
* o2
= PySequence_GetItem(source
, 1);
2236 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2241 **obj
= wxSize(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2248 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxSize object.");
2253 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
) {
2255 // If source is an object instance then it may already be the right type
2256 if (PyInstance_Check(source
)) {
2258 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint_p"))
2263 // otherwise a length-2 sequence of integers is expected
2264 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2265 PyObject
* o1
= PySequence_GetItem(source
, 0);
2266 PyObject
* o2
= PySequence_GetItem(source
, 1);
2267 // This should really check for integers, not numbers -- but that would break code.
2268 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2273 **obj
= wxPoint(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2279 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxPoint object.");
2285 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2287 // If source is an object instance then it may already be the right type
2288 if (PyInstance_Check(source
)) {
2290 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRealPoint_p"))
2295 // otherwise a 2-tuple of floats is expected
2296 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2297 PyObject
* o1
= PySequence_GetItem(source
, 0);
2298 PyObject
* o2
= PySequence_GetItem(source
, 1);
2299 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2304 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2311 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2318 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2320 // If source is an object instance then it may already be the right type
2321 if (PyInstance_Check(source
)) {
2323 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRect_p"))
2328 // otherwise a 4-tuple of integers is expected
2329 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2330 PyObject
* o1
= PySequence_GetItem(source
, 0);
2331 PyObject
* o2
= PySequence_GetItem(source
, 1);
2332 PyObject
* o3
= PySequence_GetItem(source
, 2);
2333 PyObject
* o4
= PySequence_GetItem(source
, 3);
2334 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2335 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2342 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2343 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2352 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2358 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2360 // If source is an object instance then it may already be the right type
2361 if (PyInstance_Check(source
)) {
2363 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxColour_p"))
2368 // otherwise check for a string
2369 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2370 wxString spec
= Py2wxString(source
);
2371 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2372 long red
, green
, blue
;
2373 red
= green
= blue
= 0;
2374 spec
.Mid(1,2).ToLong(&red
, 16);
2375 spec
.Mid(3,2).ToLong(&green
, 16);
2376 spec
.Mid(5,2).ToLong(&blue
, 16);
2378 **obj
= wxColour(red
, green
, blue
);
2381 else { // it's a colour name
2382 **obj
= wxColour(spec
);
2386 // last chance: 3-tuple of integers is expected
2387 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2388 PyObject
* o1
= PySequence_GetItem(source
, 0);
2389 PyObject
* o2
= PySequence_GetItem(source
, 1);
2390 PyObject
* o3
= PySequence_GetItem(source
, 2);
2391 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2397 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2405 PyErr_SetString(PyExc_TypeError
,
2406 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2412 bool wxPoint2DDouble_helper(PyObject
* source
, wxPoint2DDouble
** obj
) {
2413 // If source is an object instance then it may already be the right type
2414 if (PyInstance_Check(source
)) {
2415 wxPoint2DDouble
* ptr
;
2416 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint2DDouble_p"))
2421 // otherwise a length-2 sequence of floats is expected
2422 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2423 PyObject
* o1
= PySequence_GetItem(source
, 0);
2424 PyObject
* o2
= PySequence_GetItem(source
, 1);
2425 // This should really check for integers, not numbers -- but that would break code.
2426 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2431 **obj
= wxPoint2DDouble(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2437 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2443 //----------------------------------------------------------------------
2445 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2447 PyObject
* list
= PyList_New(0);
2448 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2450 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2452 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2454 PyList_Append(list
, str
);
2461 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2463 PyObject
* list
= PyList_New(0);
2464 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2465 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2466 PyList_Append(list
, number
);
2473 //----------------------------------------------------------------------
2474 //----------------------------------------------------------------------