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::GetMacSupportPCMenuShortcuts() {
234 return s_macSupportPCMenuShortcuts
;
241 long wxPyApp::GetMacAboutMenuItemId() {
243 return s_macAboutMenuItemId
;
250 long wxPyApp::GetMacPreferencesMenuItemId() {
252 return s_macPreferencesMenuItemId
;
259 long wxPyApp::GetMacExitMenuItemId() {
261 return s_macExitMenuItemId
;
268 wxString
wxPyApp::GetMacHelpMenuTitleName() {
270 return s_macHelpMenuTitleName
;
272 return wxEmptyString
;
277 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
279 s_macSupportPCMenuShortcuts
= val
;
284 void wxPyApp::SetMacAboutMenuItemId(long val
) {
286 s_macAboutMenuItemId
= val
;
291 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
293 s_macPreferencesMenuItemId
= val
;
298 void wxPyApp::SetMacExitMenuItemId(long val
) {
300 s_macExitMenuItemId
= val
;
305 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
307 s_macHelpMenuTitleName
= val
;
313 //---------------------------------------------------------------------
314 //----------------------------------------------------------------------
318 static char* wxPyCopyCString(const wxChar
* src
)
320 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
321 size_t len
= strlen(buff
);
322 char* dest
= new char[len
+1];
328 static char* wxPyCopyCString(const char* src
) // we need a char version too
330 size_t len
= strlen(src
);
331 char* dest
= new char[len
+1];
337 static wxChar
* wxPyCopyWString(const char *src
)
339 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
340 wxString
str(src
, *wxConvCurrent
);
341 return copystring(str
);
345 static wxChar
* wxPyCopyWString(const wxChar
*src
)
347 return copystring(src
);
353 //----------------------------------------------------------------------
355 // This function is called when the wxc module is imported to do some initial
356 // setup. (Before there is a wxApp object.)
357 void __wxPreStart(PyObject
* moduleDict
)
361 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
364 #ifdef WXP_WITH_THREAD
365 PyEval_InitThreads();
366 wxPyTStates
= new wxPyThreadStateArray
;
367 wxPyTMutex
= new wxMutex
;
370 // Ensure that the build options in the DLL (or whatever) match this build
371 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
373 // Create an exception object to use for wxASSERTions
374 wxPyAssertionError
= PyErr_NewException("wxPython.wxc.wxPyAssertionError",
375 PyExc_AssertionError
, NULL
);
376 PyDict_SetItemString(moduleDict
, "wxPyAssertionError", wxPyAssertionError
);
381 // Initialize wxWindows and bootstrap the user application by calling the
382 // wxApp's OnInit, which is a parameter to this funciton. See wxApp.__init__
383 // in _extras.py to learn how the bootstrap is started.
384 PyObject
* __wxStart(PyObject
* /* self */, PyObject
* args
)
386 PyObject
* onInitFunc
= NULL
;
387 PyObject
* arglist
= NULL
;
388 PyObject
* result
= NULL
;
389 PyObject
* pyint
= NULL
;
392 if (!PyArg_ParseTuple(args
, "O", &onInitFunc
))
395 // Get any command-line args passed to this program from the sys module
398 PyObject
* sysargv
= PySys_GetObject("argv");
399 if (sysargv
!= NULL
) {
400 argc
= PyList_Size(sysargv
);
401 argv
= new char*[argc
+1];
403 for(x
=0; x
<argc
; x
++) {
404 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
405 argv
[x
] = PyString_AsString(pyArg
);
410 if (! wxEntryStart(argc
, argv
) ) {
411 PyErr_SetString(PyExc_SystemError
, // is this the right one?
412 "wxEntryStart failed!");
418 // The stock objects were all NULL when they were loaded into
419 // SWIG generated proxies, so re-init those now...
420 wxPy_ReinitStockObjects();
423 // Call the Python wxApp's OnInit function
424 arglist
= PyTuple_New(0);
425 result
= PyEval_CallObject(onInitFunc
, arglist
);
427 if (!result
) { // an exception was raised.
431 pyint
= PyNumber_Int(result
);
433 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
436 bResult
= PyInt_AS_LONG(pyint
);
438 PyErr_SetString(PyExc_SystemExit
, "OnInit returned FALSE, exiting...");
443 wxTheApp
->m_initialized
= (wxTopLevelWindows
.GetCount() > 0);
460 wxPyDoingCleanup
= TRUE
;
463 #ifdef WXP_WITH_THREAD
466 wxPyTStates
->Empty();
475 PyObject
* __wxSetDictionary(PyObject
* /* self */, PyObject
* args
)
478 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
481 if (!PyDict_Check(wxPython_dict
)) {
482 PyErr_SetString(PyExc_TypeError
, "_wxSetDictionary must have dictionary object!");
486 if (! wxPyPtrTypeMap
)
487 wxPyPtrTypeMap
= PyDict_New();
488 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
492 #define wxPlatform "__WXMOTIF__"
495 #define wxPlatform "__WXX11__"
498 #define wxPlatform "__WXGTK__"
500 #if defined(__WIN32__) || defined(__WXMSW__)
501 #define wxPlatform "__WXMSW__"
504 #define wxPlatform "__WXMAC__"
513 PyDict_SetItemString(wxPython_dict
, "wxPlatform", PyString_FromString(wxPlatform
));
514 PyDict_SetItemString(wxPython_dict
, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
515 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
522 //---------------------------------------------------------------------------
524 // The stock objects are no longer created when the wxc module is imported, but
525 // only after the app object has been created. This function will be called before
526 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
528 void wxPy_ReinitStockObjects()
536 #define REINITOBJ(name, type) \
537 obj = PyDict_GetItemString(wxPython_dict, #name); \
538 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
539 SWIG_MakePtr(ptrbuf, (char *) name, "_" #type "_p"); \
540 ptrobj = PyString_FromString(ptrbuf); \
541 PyObject_SetAttrString(obj, "this", ptrobj); \
544 #define REINITOBJ2(name, type) \
545 obj = PyDict_GetItemString(wxPython_dict, #name); \
546 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
547 SWIG_MakePtr(ptrbuf, (char *) &name, "_" #type "_p"); \
548 ptrobj = PyString_FromString(ptrbuf); \
549 PyObject_SetAttrString(obj, "this", ptrobj); \
553 REINITOBJ(wxNORMAL_FONT
, wxFont
);
554 REINITOBJ(wxSMALL_FONT
, wxFont
);
555 REINITOBJ(wxITALIC_FONT
, wxFont
);
556 REINITOBJ(wxSWISS_FONT
, wxFont
);
558 REINITOBJ(wxRED_PEN
, wxPen
);
559 REINITOBJ(wxCYAN_PEN
, wxPen
);
560 REINITOBJ(wxGREEN_PEN
, wxPen
);
561 REINITOBJ(wxBLACK_PEN
, wxPen
);
562 REINITOBJ(wxWHITE_PEN
, wxPen
);
563 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
564 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
565 REINITOBJ(wxGREY_PEN
, wxPen
);
566 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
567 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
569 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
570 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
571 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
572 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
573 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
574 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
575 REINITOBJ(wxRED_BRUSH
, wxBrush
);
576 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
577 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
578 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
580 REINITOBJ(wxBLACK
, wxColour
);
581 REINITOBJ(wxWHITE
, wxColour
);
582 REINITOBJ(wxRED
, wxColour
);
583 REINITOBJ(wxBLUE
, wxColour
);
584 REINITOBJ(wxGREEN
, wxColour
);
585 REINITOBJ(wxCYAN
, wxColour
);
586 REINITOBJ(wxLIGHT_GREY
, wxColour
);
588 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
589 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
590 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
592 REINITOBJ2(wxNullBitmap
, wxBitmap
);
593 REINITOBJ2(wxNullIcon
, wxIcon
);
594 REINITOBJ2(wxNullCursor
, wxCursor
);
595 REINITOBJ2(wxNullPen
, wxPen
);
596 REINITOBJ2(wxNullBrush
, wxBrush
);
597 REINITOBJ2(wxNullPalette
, wxPalette
);
598 REINITOBJ2(wxNullFont
, wxFont
);
599 REINITOBJ2(wxNullColour
, wxColour
);
601 REINITOBJ(wxTheFontList
, wxFontList
);
602 REINITOBJ(wxThePenList
, wxPenList
);
603 REINITOBJ(wxTheBrushList
, wxBrushList
);
604 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
607 REINITOBJ(wxTheClipboard
, wxClipboard
);
608 REINITOBJ(wxTheMimeTypesManager
, wxMimeTypesManager
);
609 REINITOBJ2(wxDefaultValidator
, wxValidator
);
610 REINITOBJ2(wxNullImage
, wxImage
);
611 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
617 //---------------------------------------------------------------------------
619 void wxPyClientData_dtor(wxPyClientData
* self
) {
620 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
621 // may have already garbage collected the object...
622 wxPyBeginBlockThreads();
623 Py_DECREF(self
->m_obj
);
624 wxPyEndBlockThreads();
628 void wxPyUserData_dtor(wxPyUserData
* self
) {
629 if (! wxPyDoingCleanup
) {
630 wxPyBeginBlockThreads();
631 Py_DECREF(self
->m_obj
);
632 wxPyEndBlockThreads();
637 // This is called when an OOR controled object is being destroyed. Although
638 // the C++ object is going away there is no way to force the Python object
639 // (and all references to it) to die too. This causes problems (crashes) in
640 // wxPython when a python shadow object attempts to call a C++ method using
641 // the now bogus pointer... So to try and prevent this we'll do a little black
642 // magic and change the class of the python instance to a class that will
643 // raise an exception for any attempt to call methods with it. See
644 // _wxPyDeadObject in _extras.py for the implementation of this class.
645 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
647 static PyObject
* deadObjectClass
= NULL
;
649 wxPyBeginBlockThreads();
650 if (deadObjectClass
== NULL
) {
651 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
652 wxASSERT_MSG(deadObjectClass
!= NULL
, wxT("Can't get _wxPyDeadObject class!"));
653 Py_INCREF(deadObjectClass
);
657 // Only if there is more than one reference to the object
658 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
659 wxASSERT_MSG(PyInstance_Check(self
->m_obj
), wxT("m_obj not an instance!?!?!"));
661 // Call __del__, if there is one.
662 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
664 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
668 if (PyErr_Occurred())
669 PyErr_Clear(); // just ignore it for now
671 // Clear the instance's dictionary
672 PyInstanceObject
* inst
= (PyInstanceObject
*)self
->m_obj
;
673 PyDict_Clear(inst
->in_dict
);
675 // put the name of the old class into the instance, and then reset the
676 // class to be the dead class.
677 PyDict_SetItemString(inst
->in_dict
, "_name", inst
->in_class
->cl_name
);
678 inst
->in_class
= (PyClassObject
*)deadObjectClass
;
679 Py_INCREF(deadObjectClass
);
682 // m_obj is DECREF's in the base class dtor...
683 wxPyEndBlockThreads();
687 //---------------------------------------------------------------------------
688 // Stuff used by OOR to find the right wxPython class type to return and to
692 // The pointer type map is used when the "pointer" type name generated by SWIG
693 // is not the same as the shadow class name, for example wxPyTreeCtrl
694 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
695 // so we'll just make it a Python dictionary in the wx module's namespace.
696 // (See __wxSetDictionary)
697 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
698 if (! wxPyPtrTypeMap
)
699 wxPyPtrTypeMap
= PyDict_New();
700 PyDict_SetItemString(wxPyPtrTypeMap
,
702 PyString_FromString((char*)ptrName
));
707 PyObject
* wxPyClassExists(const wxString
& className
) {
710 wxString
name(className
);
711 char buff
[64]; // should always be big enough...
716 // Try the name as-is first
717 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
718 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
720 // if not found see if there is a mapped name for it
722 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
723 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
724 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
725 classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
729 return classobj
; // returns NULL if not found
733 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
734 PyObject
* target
= NULL
;
735 bool isEvtHandler
= FALSE
;
738 // If it's derived from wxEvtHandler then there may
739 // already be a pointer to a Python object that we can use
741 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
743 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
744 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
746 target
= data
->m_obj
;
752 // Otherwise make it the old fashioned way by making a
753 // new shadow object and putting this pointer in it.
754 wxClassInfo
* info
= source
->GetClassInfo();
755 wxString name
= info
->GetClassName();
756 PyObject
* klass
= wxPyClassExists(name
);
757 while (info
&& !klass
) {
758 name
= (wxChar
*)info
->GetBaseClassName1();
759 info
= wxClassInfo::FindClass(name
);
760 klass
= wxPyClassExists(name
);
763 target
= wxPyConstructObject(source
, name
, klass
, FALSE
);
764 if (target
&& isEvtHandler
)
765 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
767 wxString
msg(wxT("wxPython class not found for "));
768 msg
+= source
->GetClassInfo()->GetClassName();
769 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
773 } else { // source was NULL so return None.
774 Py_INCREF(Py_None
); target
= Py_None
;
780 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
781 PyObject
* target
= NULL
;
783 if (source
&& wxIsKindOf(source
, wxSizer
)) {
784 // If it's derived from wxSizer then there may
785 // already be a pointer to a Python object that we can use
787 wxSizer
* sz
= (wxSizer
*)source
;
788 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
790 target
= data
->m_obj
;
795 target
= wxPyMake_wxObject(source
, FALSE
);
796 if (target
!= Py_None
)
797 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
804 //---------------------------------------------------------------------------
806 PyObject
* wxPyConstructObject(void* ptr
,
807 const wxString
& className
,
814 wxString
name(className
);
815 char swigptr
[64]; // should always be big enough...
818 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
819 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
821 sprintf(buff
, "_%s_p", (const char*)name
.mbc_str());
822 SWIG_MakePtr(swigptr
, ptr
, buff
);
824 arg
= Py_BuildValue("(s)", swigptr
);
825 obj
= PyInstance_New(klass
, arg
, NULL
);
829 PyObject
* one
= PyInt_FromLong(1);
830 PyObject_SetAttrString(obj
, "thisown", one
);
838 PyObject
* wxPyConstructObject(void* ptr
,
839 const wxString
& className
,
846 char buff
[64]; // should always be big enough...
847 sprintf(buff
, "%sPtr", (const char*)className
.mbc_str());
849 wxASSERT_MSG(wxPython_dict
, wxT("wxPython_dict is not set yet!!"));
851 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
853 wxString
msg(wxT("wxPython class not found for "));
855 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
859 return wxPyConstructObject(ptr
, className
, classobj
, setThisOwn
);
863 //---------------------------------------------------------------------------
866 #ifdef WXP_WITH_THREAD
868 unsigned long wxPyGetCurrentThreadId() {
869 return wxThread::GetCurrentId();
872 static PyThreadState
* gs_shutdownTState
;
874 PyThreadState
* wxPyGetThreadState() {
875 if (wxPyTMutex
== NULL
) // Python is shutting down...
876 return gs_shutdownTState
;
878 unsigned long ctid
= wxPyGetCurrentThreadId();
879 PyThreadState
* tstate
= NULL
;
882 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
883 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
884 if (info
.tid
== ctid
) {
885 tstate
= info
.tstate
;
889 wxPyTMutex
->Unlock();
890 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
895 void wxPySaveThreadState(PyThreadState
* tstate
) {
896 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
897 gs_shutdownTState
= tstate
;
900 unsigned long ctid
= wxPyGetCurrentThreadId();
902 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
903 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
904 if (info
.tid
== ctid
) {
906 if (info
.tstate
!= tstate
)
907 wxLogMessage("*** tstate mismatch!???");
909 // info.tstate = tstate; *** DO NOT update existing ones???
910 // Normally it will never change, but apparently COM callbacks
911 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
912 // tstate which will then be garbage the next time we try to use
914 wxPyTMutex
->Unlock();
918 // not found, so add it...
919 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
920 wxPyTMutex
->Unlock();
926 // Calls from Python to wxWindows code are wrapped in calls to these
929 PyThreadState
* wxPyBeginAllowThreads() {
930 #ifdef WXP_WITH_THREAD
931 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
932 wxPySaveThreadState(saved
);
939 void wxPyEndAllowThreads(PyThreadState
* saved
) {
940 #ifdef WXP_WITH_THREAD
941 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
947 // Calls from wxWindows back to Python code, or even any PyObject
948 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
950 void wxPyBeginBlockThreads() {
951 #ifdef WXP_WITH_THREAD
952 PyThreadState
* tstate
= wxPyGetThreadState();
953 PyEval_RestoreThread(tstate
);
958 void wxPyEndBlockThreads() {
959 #ifdef WXP_WITH_THREAD
960 // Is there any need to save it again?
961 // PyThreadState* tstate =
967 //---------------------------------------------------------------------------
968 // wxPyInputStream and wxPyCBInputStream methods
971 void wxPyInputStream::close() {
972 /* do nothing for now */
975 void wxPyInputStream::flush() {
976 /* do nothing for now */
979 bool wxPyInputStream::eof() {
981 return m_wxis
->Eof();
986 wxPyInputStream::~wxPyInputStream() {
993 PyObject
* wxPyInputStream::read(int size
) {
994 PyObject
* obj
= NULL
;
996 const int BUFSIZE
= 1024;
998 // check if we have a real wxInputStream to work with
1000 wxPyBeginBlockThreads();
1001 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1002 wxPyEndBlockThreads();
1007 // read while bytes are available on the stream
1008 while ( m_wxis
->CanRead() ) {
1009 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1010 buf
.UngetAppendBuf(m_wxis
->LastRead());
1013 } else { // Read only size number of characters
1014 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1015 buf
.UngetWriteBuf(m_wxis
->LastRead());
1019 wxPyBeginBlockThreads();
1020 wxStreamError err
= m_wxis
->GetLastError();
1021 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1022 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1025 // We use only strings for the streams, not unicode
1026 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1028 wxPyEndBlockThreads();
1033 PyObject
* wxPyInputStream::readline(int size
) {
1034 PyObject
* obj
= NULL
;
1039 // check if we have a real wxInputStream to work with
1041 wxPyBeginBlockThreads();
1042 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1043 wxPyEndBlockThreads();
1047 // read until \n or byte limit reached
1048 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1049 ch
= m_wxis
->GetC();
1054 wxPyBeginBlockThreads();
1055 wxStreamError err
= m_wxis
->GetLastError();
1056 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1057 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1060 // We use only strings for the streams, not unicode
1061 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1063 wxPyEndBlockThreads();
1068 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1071 // check if we have a real wxInputStream to work with
1073 wxPyBeginBlockThreads();
1074 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1075 wxPyEndBlockThreads();
1080 wxPyBeginBlockThreads();
1081 pylist
= PyList_New(0);
1083 wxPyBeginBlockThreads();
1085 wxPyEndBlockThreads();
1089 // read sizehint bytes or until EOF
1091 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1092 PyObject
* s
= this->readline();
1094 wxPyBeginBlockThreads();
1096 wxPyEndBlockThreads();
1099 wxPyBeginBlockThreads();
1100 PyList_Append(pylist
, s
);
1101 i
+= PyString_Size(s
);
1102 wxPyEndBlockThreads();
1106 wxStreamError err
= m_wxis
->GetLastError();
1107 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1108 wxPyBeginBlockThreads();
1110 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1111 wxPyEndBlockThreads();
1119 void wxPyInputStream::seek(int offset
, int whence
) {
1121 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1124 int wxPyInputStream::tell(){
1126 return m_wxis
->TellI();
1133 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1134 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1138 wxPyCBInputStream::~wxPyCBInputStream() {
1139 if (m_block
) wxPyBeginBlockThreads();
1143 if (m_block
) wxPyEndBlockThreads();
1147 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1148 if (block
) wxPyBeginBlockThreads();
1150 PyObject
* read
= getMethod(py
, "read");
1151 PyObject
* seek
= getMethod(py
, "seek");
1152 PyObject
* tell
= getMethod(py
, "tell");
1155 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1159 if (block
) wxPyEndBlockThreads();
1163 if (block
) wxPyEndBlockThreads();
1164 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1168 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1169 return wxPyCBInputStream::create(py
, block
);
1172 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1173 if (!PyObject_HasAttrString(py
, name
))
1175 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1176 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1184 size_t wxPyCBInputStream::GetSize() const {
1185 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1186 if (m_seek
&& m_tell
) {
1187 off_t temp
= self
->OnSysTell();
1188 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1189 self
->OnSysSeek(temp
, wxFromStart
);
1197 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1201 wxPyBeginBlockThreads();
1202 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1203 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1207 if ((result
!= NULL
) && PyString_Check(result
)) {
1208 o
= PyString_Size(result
);
1210 m_lasterror
= wxSTREAM_EOF
;
1213 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1218 m_lasterror
= wxSTREAM_READ_ERROR
;
1219 wxPyEndBlockThreads();
1223 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1224 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1228 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1229 wxPyBeginBlockThreads();
1231 // off_t is a 64-bit value...
1232 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1234 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1236 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1239 wxPyEndBlockThreads();
1244 off_t
wxPyCBInputStream::OnSysTell() const {
1245 wxPyBeginBlockThreads();
1246 PyObject
* arglist
= Py_BuildValue("()");
1247 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1250 if (result
!= NULL
) {
1252 if (PyLong_Check(result
))
1253 o
= PyLong_AsLongLong(result
);
1256 o
= PyInt_AsLong(result
);
1260 wxPyEndBlockThreads();
1264 //----------------------------------------------------------------------
1266 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1268 wxPyCallback::wxPyCallback(PyObject
* func
) {
1273 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1274 m_func
= other
.m_func
;
1278 wxPyCallback::~wxPyCallback() {
1279 wxPyBeginBlockThreads();
1281 wxPyEndBlockThreads();
1286 // This function is used for all events destined for Python event handlers.
1287 void wxPyCallback::EventThunker(wxEvent
& event
) {
1288 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1289 PyObject
* func
= cb
->m_func
;
1293 bool checkSkip
= FALSE
;
1295 wxPyBeginBlockThreads();
1296 wxString className
= event
.GetClassInfo()->GetClassName();
1298 // If the event is one of these types then pass the original
1299 // event object instead of the one passed to us.
1300 if ( className
== wxT("wxPyEvent") ) {
1301 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1302 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1304 else if ( className
== wxT("wxPyCommandEvent") ) {
1305 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1306 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1309 arg
= wxPyConstructObject((void*)&event
, className
);
1312 // Call the event handler, passing the event object
1313 tuple
= PyTuple_New(1);
1314 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1315 result
= PyEval_CallObject(func
, tuple
);
1317 Py_DECREF(result
); // result is ignored, but we still need to decref it
1318 PyErr_Clear(); // Just in case...
1324 // if the event object was one of our special types and
1325 // it had been cloned, then we need to extract the Skipped
1326 // value from the original and set it in the clone.
1327 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1329 event
.Skip(PyInt_AsLong(result
));
1337 wxPyEndBlockThreads();
1341 //----------------------------------------------------------------------
1343 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1345 m_self
= other
.m_self
;
1346 m_class
= other
.m_class
;
1354 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1365 #if PYTHON_API_VERSION >= 1011
1367 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1368 // in which the method was defined. Starting with 2.2 it returns
1369 // "class that asked for the method" which seems totally bogus to me
1370 // but apprently it fixes some obscure problem waiting to happen in
1371 // Python. Since the API was not documented Guido and the gang felt
1372 // safe in changing it. Needless to say that totally screwed up the
1373 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1374 // code to find the class where the method is actually defined...
1377 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1381 if (PyType_Check(klass
)) { // new style classes
1382 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1383 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1384 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1385 PyObject
*mro
, *res
, *base
, *dict
;
1386 /* Look in tp_dict of types in MRO */
1388 assert(PyTuple_Check(mro
));
1389 n
= PyTuple_GET_SIZE(mro
);
1390 for (i
= 0; i
< n
; i
++) {
1391 base
= PyTuple_GET_ITEM(mro
, i
);
1392 if (PyClass_Check(base
))
1393 dict
= ((PyClassObject
*)base
)->cl_dict
;
1395 assert(PyType_Check(base
));
1396 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1398 assert(dict
&& PyDict_Check(dict
));
1399 res
= PyDict_GetItem(dict
, name
);
1406 else if (PyClass_Check(klass
)) { // old style classes
1407 // This code is borrowed/adapted from class_lookup in classobject.c
1408 PyClassObject
* cp
= (PyClassObject
*)klass
;
1409 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1410 if (value
!= NULL
) {
1411 return (PyObject
*)cp
;
1413 n
= PyTuple_Size(cp
->cl_bases
);
1414 for (i
= 0; i
< n
; i
++) {
1415 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1416 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1428 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1430 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1432 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1434 #else // 2.2 and after, the hard way...
1436 PyObject
* nameo
= PyString_FromString(name
);
1437 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1445 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1446 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1447 self
->m_lastFound
= NULL
;
1449 // If the object (m_self) has an attibute of the given name...
1450 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1451 PyObject
*method
, *klass
;
1452 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1454 // ...and if that attribute is a method, and if that method's class is
1455 // not from a base class...
1456 if (PyMethod_Check(method
) &&
1457 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1458 ((klass
== m_class
) || PyClass_IsSubclass(klass
, m_class
))) {
1460 // ...then we'll save a pointer to the method so callCallback can call it.
1461 self
->m_lastFound
= method
;
1467 return m_lastFound
!= NULL
;
1471 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1475 result
= callCallbackObj(argTuple
);
1476 if (result
) { // Assumes an integer return type...
1477 retval
= PyInt_AsLong(result
);
1479 PyErr_Clear(); // forget about it if it's not...
1484 // Invoke the Python callable object, returning the raw PyObject return
1485 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1486 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1489 // Save a copy of the pointer in case the callback generates another
1490 // callback. In that case m_lastFound will have a different value when
1491 // it gets back here...
1492 PyObject
* method
= m_lastFound
;
1494 result
= PyEval_CallObject(method
, argTuple
);
1495 Py_DECREF(argTuple
);
1504 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1505 cbh
.setSelf(self
, klass
, incref
);
1508 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1509 return cbh
.findCallback(name
);
1512 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1513 return cbh
.callCallback(argTuple
);
1516 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1517 return cbh
.callCallbackObj(argTuple
);
1521 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1522 if (cbh
->m_incRef
) {
1523 wxPyBeginBlockThreads();
1524 Py_XDECREF(cbh
->m_self
);
1525 Py_XDECREF(cbh
->m_class
);
1526 wxPyEndBlockThreads();
1530 //---------------------------------------------------------------------------
1531 //---------------------------------------------------------------------------
1532 // These event classes can be derived from in Python and passed through the event
1533 // system without losing anything. They do this by keeping a reference to
1534 // themselves and some special case handling in wxPyCallback::EventThunker.
1537 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1538 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1539 //Py_INCREF(m_self); // circular loops...
1543 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1544 wxPyBeginBlockThreads();
1547 wxPyEndBlockThreads();
1550 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1551 wxPyBeginBlockThreads();
1559 wxPyEndBlockThreads();
1562 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1568 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1569 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1572 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1573 : wxEvent(winid
, commandType
) {
1577 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1580 SetSelf(evt
.m_self
, TRUE
);
1584 wxPyEvent::~wxPyEvent() {
1588 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1589 : wxCommandEvent(commandType
, id
) {
1593 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1594 : wxCommandEvent(evt
)
1596 SetSelf(evt
.m_self
, TRUE
);
1600 wxPyCommandEvent::~wxPyCommandEvent() {
1606 //---------------------------------------------------------------------------
1607 //---------------------------------------------------------------------------
1610 wxPyTimer::wxPyTimer(PyObject
* callback
) {
1615 wxPyTimer::~wxPyTimer() {
1616 wxPyBeginBlockThreads();
1618 wxPyEndBlockThreads();
1621 void wxPyTimer::Notify() {
1622 if (!func
|| func
== Py_None
) {
1626 wxPyBeginBlockThreads();
1629 PyObject
* args
= Py_BuildValue("()");
1631 result
= PyEval_CallObject(func
, args
);
1640 wxPyEndBlockThreads();
1646 //---------------------------------------------------------------------------
1647 //---------------------------------------------------------------------------
1648 // Convert a wxList to a Python List
1650 PyObject
* wxPy_ConvertList(wxListBase
* listbase
, const char* className
) {
1651 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1655 wxNode
* node
= list
->GetFirst();
1657 wxPyBeginBlockThreads();
1658 pyList
= PyList_New(0);
1660 wxObj
= node
->GetData();
1661 pyObj
= wxPyMake_wxObject(wxObj
); //wxPyConstructObject(wxObj, className);
1662 PyList_Append(pyList
, pyObj
);
1663 node
= node
->GetNext();
1665 wxPyEndBlockThreads();
1669 //----------------------------------------------------------------------
1671 long wxPyGetWinHandle(wxWindow
* win
) {
1673 return (long)win
->GetHandle();
1677 return (long)win
->GetHandle();
1680 // Find and return the actual X-Window.
1682 if (win
->m_wxwindow
) {
1684 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1686 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1688 return (long)bwin
->xwindow
;
1696 //----------------------------------------------------------------------
1697 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1698 // included in every file over and over again...
1700 #if PYTHON_API_VERSION >= 1009
1701 static char* wxStringErrorMsg
= "String or Unicode type required";
1703 static char* wxStringErrorMsg
= "String type required";
1707 wxString
* wxString_in_helper(PyObject
* source
) {
1709 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1710 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1711 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1715 if (PyUnicode_Check(source
)) {
1716 target
= new wxString();
1717 size_t len
= PyUnicode_GET_SIZE(source
);
1719 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1720 target
->UngetWriteBuf();
1723 // It is a string, get pointers to it and transform to unicode
1724 char* tmpPtr
; int tmpSize
;
1725 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1726 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1729 char* tmpPtr
; int tmpSize
;
1730 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1731 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1734 target
= new wxString(tmpPtr
, tmpSize
);
1735 #endif // wxUSE_UNICODE
1737 #else // No Python unicode API (1.5.2)
1738 if (!PyString_Check(source
)) {
1739 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1742 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1748 // Similar to above except doesn't use "new" and doesn't set an exception
1749 wxString
Py2wxString(PyObject
* source
)
1752 bool doDecRef
= FALSE
;
1754 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1755 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1756 // Convert to String if not one already... (TODO: Unicode too?)
1757 source
= PyObject_Str(source
);
1762 if (PyUnicode_Check(source
)) {
1763 size_t len
= PyUnicode_GET_SIZE(source
);
1765 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1766 target
.UngetWriteBuf();
1769 // It is a string, get pointers to it and transform to unicode
1770 char* tmpPtr
; int tmpSize
;
1771 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1772 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1775 char* tmpPtr
; int tmpSize
;
1776 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1777 target
= wxString(tmpPtr
, tmpSize
);
1778 #endif // wxUSE_UNICODE
1780 #else // No Python unicode API (1.5.2)
1781 if (!PyString_Check(source
)) {
1782 // Convert to String if not one already...
1783 source
= PyObject_Str(source
);
1786 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1795 // Make either a Python String or Unicode object, depending on build mode
1796 PyObject
* wx2PyString(const wxString
& src
)
1800 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1802 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1808 //----------------------------------------------------------------------
1811 byte
* byte_LIST_helper(PyObject
* source
) {
1812 if (!PyList_Check(source
)) {
1813 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1816 int count
= PyList_Size(source
);
1817 byte
* temp
= new byte
[count
];
1819 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1822 for (int x
=0; x
<count
; x
++) {
1823 PyObject
* o
= PyList_GetItem(source
, x
);
1824 if (! PyInt_Check(o
)) {
1825 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1828 temp
[x
] = (byte
)PyInt_AsLong(o
);
1834 int* int_LIST_helper(PyObject
* source
) {
1835 if (!PyList_Check(source
)) {
1836 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1839 int count
= PyList_Size(source
);
1840 int* temp
= new int[count
];
1842 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1845 for (int x
=0; x
<count
; x
++) {
1846 PyObject
* o
= PyList_GetItem(source
, x
);
1847 if (! PyInt_Check(o
)) {
1848 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1851 temp
[x
] = PyInt_AsLong(o
);
1857 long* long_LIST_helper(PyObject
* source
) {
1858 if (!PyList_Check(source
)) {
1859 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1862 int count
= PyList_Size(source
);
1863 long* temp
= new long[count
];
1865 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1868 for (int x
=0; x
<count
; x
++) {
1869 PyObject
* o
= PyList_GetItem(source
, x
);
1870 if (! PyInt_Check(o
)) {
1871 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1874 temp
[x
] = PyInt_AsLong(o
);
1880 char** string_LIST_helper(PyObject
* source
) {
1881 if (!PyList_Check(source
)) {
1882 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1885 int count
= PyList_Size(source
);
1886 char** temp
= new char*[count
];
1888 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1891 for (int x
=0; x
<count
; x
++) {
1892 PyObject
* o
= PyList_GetItem(source
, x
);
1893 if (! PyString_Check(o
)) {
1894 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1897 temp
[x
] = PyString_AsString(o
);
1902 //--------------------------------
1903 // Part of patch from Tim Hochberg
1904 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1905 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1906 point
->x
= PyInt_AS_LONG(o1
);
1907 point
->y
= PyInt_AS_LONG(o2
);
1910 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1911 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1912 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1915 if (PyInstance_Check(o1
) || PyInstance_Check(o2
)) {
1916 // Disallow instances because they can cause havok
1919 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1920 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1921 point
->x
= PyInt_AsLong(o1
);
1922 point
->y
= PyInt_AsLong(o2
);
1929 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1930 // Putting all of the declarations here allows
1931 // us to put the error handling all in one place.
1934 PyObject
*o
, *o1
, *o2
;
1935 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1937 if (!PySequence_Check(source
)) {
1941 // The length of the sequence is returned in count.
1942 *count
= PySequence_Length(source
);
1947 temp
= new wxPoint
[*count
];
1949 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1952 for (x
=0; x
<*count
; x
++) {
1953 // Get an item: try fast way first.
1955 o
= PySequence_Fast_GET_ITEM(source
, x
);
1958 o
= PySequence_GetItem(source
, x
);
1964 // Convert o to wxPoint.
1965 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1966 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1967 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1968 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1969 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1973 else if (PyInstance_Check(o
)) {
1975 if (SWIG_GetPtrObj(o
, (void **)&pt
, "_wxPoint_p")) {
1980 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1981 o1
= PySequence_GetItem(o
, 0);
1982 o2
= PySequence_GetItem(o
, 1);
1983 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2007 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2011 //------------------------------
2014 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2015 if (!PyList_Check(source
)) {
2016 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2019 int count
= PyList_Size(source
);
2020 wxBitmap
** temp
= new wxBitmap
*[count
];
2022 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2025 for (int x
=0; x
<count
; x
++) {
2026 PyObject
* o
= PyList_GetItem(source
, x
);
2027 if (PyInstance_Check(o
)) {
2029 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxBitmap_p")) {
2030 PyErr_SetString(PyExc_TypeError
,"Expected _wxBitmap_p.");
2036 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2045 wxString
* wxString_LIST_helper(PyObject
* source
) {
2046 if (!PyList_Check(source
)) {
2047 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2050 int count
= PyList_Size(source
);
2051 wxString
* temp
= new wxString
[count
];
2053 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2056 for (int x
=0; x
<count
; x
++) {
2057 PyObject
* o
= PyList_GetItem(source
, x
);
2058 #if PYTHON_API_VERSION >= 1009
2059 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2060 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2064 if (! PyString_Check(o
)) {
2065 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2070 wxString
* pStr
= wxString_in_helper(o
);
2078 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2079 if (!PyList_Check(source
)) {
2080 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2083 int count
= PyList_Size(source
);
2084 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2086 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2089 for (int x
=0; x
<count
; x
++) {
2090 PyObject
* o
= PyList_GetItem(source
, x
);
2091 if (PyInstance_Check(o
)) {
2092 wxAcceleratorEntry
* ae
;
2093 if (SWIG_GetPtrObj(o
, (void **) &ae
,"_wxAcceleratorEntry_p")) {
2094 PyErr_SetString(PyExc_TypeError
,"Expected _wxAcceleratorEntry_p.");
2099 else if (PyTuple_Check(o
)) {
2100 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2101 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2102 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2103 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2106 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2114 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2115 if (!PyList_Check(source
)) {
2116 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2119 int count
= PyList_Size(source
);
2120 wxPen
** temp
= new wxPen
*[count
];
2122 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2125 for (int x
=0; x
<count
; x
++) {
2126 PyObject
* o
= PyList_GetItem(source
, x
);
2127 if (PyInstance_Check(o
)) {
2129 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxPen_p")) {
2131 PyErr_SetString(PyExc_TypeError
,"Expected _wxPen_p.");
2138 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2146 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2147 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2150 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2154 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2155 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2158 o1
= PySequence_GetItem(source
, 0);
2159 o2
= PySequence_GetItem(source
, 1);
2162 *i1
= PyInt_AsLong(o1
);
2163 *i2
= PyInt_AsLong(o2
);
2173 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2174 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2175 PyObject
*o1
, *o2
, *o3
, *o4
;
2177 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2181 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2182 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2183 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2184 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2187 o1
= PySequence_GetItem(source
, 0);
2188 o2
= PySequence_GetItem(source
, 1);
2189 o3
= PySequence_GetItem(source
, 2);
2190 o4
= PySequence_GetItem(source
, 3);
2193 *i1
= PyInt_AsLong(o1
);
2194 *i2
= PyInt_AsLong(o2
);
2195 *i3
= PyInt_AsLong(o3
);
2196 *i4
= PyInt_AsLong(o4
);
2208 //----------------------------------------------------------------------
2210 bool wxSize_helper(PyObject
* source
, wxSize
** obj
) {
2212 // If source is an object instance then it may already be the right type
2213 if (PyInstance_Check(source
)) {
2215 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxSize_p"))
2220 // otherwise a 2-tuple of integers is expected
2221 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2222 PyObject
* o1
= PySequence_GetItem(source
, 0);
2223 PyObject
* o2
= PySequence_GetItem(source
, 1);
2224 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2229 **obj
= wxSize(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2236 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxSize object.");
2241 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
) {
2243 // If source is an object instance then it may already be the right type
2244 if (PyInstance_Check(source
)) {
2246 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint_p"))
2251 // otherwise a length-2 sequence of integers is expected
2252 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2253 PyObject
* o1
= PySequence_GetItem(source
, 0);
2254 PyObject
* o2
= PySequence_GetItem(source
, 1);
2255 // This should really check for integers, not numbers -- but that would break code.
2256 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2261 **obj
= wxPoint(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2267 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxPoint object.");
2273 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2275 // If source is an object instance then it may already be the right type
2276 if (PyInstance_Check(source
)) {
2278 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRealPoint_p"))
2283 // otherwise a 2-tuple of floats is expected
2284 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2285 PyObject
* o1
= PySequence_GetItem(source
, 0);
2286 PyObject
* o2
= PySequence_GetItem(source
, 1);
2287 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2292 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2299 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2306 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2308 // If source is an object instance then it may already be the right type
2309 if (PyInstance_Check(source
)) {
2311 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRect_p"))
2316 // otherwise a 4-tuple of integers is expected
2317 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2318 PyObject
* o1
= PySequence_GetItem(source
, 0);
2319 PyObject
* o2
= PySequence_GetItem(source
, 1);
2320 PyObject
* o3
= PySequence_GetItem(source
, 2);
2321 PyObject
* o4
= PySequence_GetItem(source
, 3);
2322 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2323 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2330 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2331 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2340 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2346 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2348 // If source is an object instance then it may already be the right type
2349 if (PyInstance_Check(source
)) {
2351 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxColour_p"))
2356 // otherwise check for a string
2357 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2358 wxString spec
= Py2wxString(source
);
2359 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2360 long red
, green
, blue
;
2361 red
= green
= blue
= 0;
2362 spec
.Mid(1,2).ToLong(&red
, 16);
2363 spec
.Mid(3,2).ToLong(&green
, 16);
2364 spec
.Mid(5,2).ToLong(&blue
, 16);
2366 **obj
= wxColour(red
, green
, blue
);
2369 else { // it's a colour name
2370 **obj
= wxColour(spec
);
2374 // last chance: 3-tuple of integers is expected
2375 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2376 PyObject
* o1
= PySequence_GetItem(source
, 0);
2377 PyObject
* o2
= PySequence_GetItem(source
, 1);
2378 PyObject
* o3
= PySequence_GetItem(source
, 2);
2379 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2385 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2393 PyErr_SetString(PyExc_TypeError
,
2394 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2400 bool wxPoint2DDouble_helper(PyObject
* source
, wxPoint2DDouble
** obj
) {
2401 // If source is an object instance then it may already be the right type
2402 if (PyInstance_Check(source
)) {
2403 wxPoint2DDouble
* ptr
;
2404 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint2DDouble_p"))
2409 // otherwise a length-2 sequence of floats is expected
2410 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2411 PyObject
* o1
= PySequence_GetItem(source
, 0);
2412 PyObject
* o2
= PySequence_GetItem(source
, 1);
2413 // This should really check for integers, not numbers -- but that would break code.
2414 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2419 **obj
= wxPoint2DDouble(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2425 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2431 //----------------------------------------------------------------------
2433 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2435 PyObject
* list
= PyList_New(0);
2436 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2438 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2440 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2442 PyList_Append(list
, str
);
2449 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2451 PyObject
* list
= PyList_New(0);
2452 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2453 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2454 PyList_Append(list
, number
);
2461 //----------------------------------------------------------------------
2462 //----------------------------------------------------------------------