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;
120 if ( m_exitOnFrameDelete
== Later
) {
121 m_exitOnFrameDelete
= Yes
;
124 retval
= wxApp::MainLoop();
131 bool wxPyApp::OnInitGui() {
133 wxApp::OnInitGui(); // in this case always call the base class version
134 // wxPyBeginBlockThreads(); *** only called from within __wxStart so we already have the GIL
135 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
136 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
137 // wxPyEndBlockThreads(); ***
142 int wxPyApp::OnExit() {
144 wxPyBeginBlockThreads();
145 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
146 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
147 wxPyEndBlockThreads();
148 wxApp::OnExit(); // in this case always call the base class version
154 void wxPyApp::OnAssert(const wxChar
*file
,
159 // If the OnAssert is overloaded in the Python class then call it...
161 wxPyBeginBlockThreads();
162 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
163 PyObject
* fso
= wx2PyString(file
);
164 PyObject
* cso
= wx2PyString(file
);
167 mso
= wx2PyString(file
);
169 mso
= Py_None
; Py_INCREF(Py_None
);
171 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
176 wxPyEndBlockThreads();
178 // ...otherwise do our own thing with it
181 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
184 // turn it into a Python exception?
185 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
188 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
195 wxPyBeginBlockThreads();
196 PyObject
* s
= wx2PyString(buf
);
197 PyErr_SetObject(wxPyAssertionError
, s
);
199 wxPyEndBlockThreads();
201 // Now when control returns to whatever API wrapper was called from
202 // Python it should detect that an exception is set and will return
203 // NULL, signalling the exception to Python.
206 // Send it to the normal log destination, but only if
207 // not _DIALOG because it will call this too
208 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
211 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
220 // do the normal wx assert dialog?
221 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
222 wxApp::OnAssert(file
, line
, cond
, msg
);
229 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
231 return s_macSupportPCMenuShortcuts
;
238 long wxPyApp::GetMacAboutMenuItemId() {
240 return s_macAboutMenuItemId
;
247 long wxPyApp::GetMacPreferencesMenuItemId() {
249 return s_macPreferencesMenuItemId
;
256 long wxPyApp::GetMacExitMenuItemId() {
258 return s_macExitMenuItemId
;
265 wxString
wxPyApp::GetMacHelpMenuTitleName() {
267 return s_macHelpMenuTitleName
;
269 return wxEmptyString
;
274 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
276 s_macSupportPCMenuShortcuts
= val
;
281 void wxPyApp::SetMacAboutMenuItemId(long val
) {
283 s_macAboutMenuItemId
= val
;
288 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
290 s_macPreferencesMenuItemId
= val
;
295 void wxPyApp::SetMacExitMenuItemId(long val
) {
297 s_macExitMenuItemId
= val
;
302 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
304 s_macHelpMenuTitleName
= val
;
310 //---------------------------------------------------------------------
311 //----------------------------------------------------------------------
315 static char* wxPyCopyCString(const wxChar
* src
)
317 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
318 size_t len
= strlen(buff
);
319 char* dest
= new char[len
+1];
325 static char* wxPyCopyCString(const char* src
) // we need a char version too
327 size_t len
= strlen(src
);
328 char* dest
= new char[len
+1];
334 static wxChar
* wxPyCopyWString(const char *src
)
336 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
337 wxString
str(src
, *wxConvCurrent
);
338 return copystring(str
);
342 static wxChar
* wxPyCopyWString(const wxChar
*src
)
344 return copystring(src
);
350 //----------------------------------------------------------------------
352 // This function is called when the wxc module is imported to do some initial
353 // setup. (Before there is a wxApp object.)
354 void __wxPreStart(PyObject
* moduleDict
)
358 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
361 #ifdef WXP_WITH_THREAD
362 PyEval_InitThreads();
363 wxPyTStates
= new wxPyThreadStateArray
;
364 wxPyTMutex
= new wxMutex
;
367 // Ensure that the build options in the DLL (or whatever) match this build
368 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
370 // Create an exception object to use for wxASSERTions
371 wxPyAssertionError
= PyErr_NewException("wxPython.wxc.wxPyAssertionError",
372 PyExc_AssertionError
, NULL
);
373 PyDict_SetItemString(moduleDict
, "wxPyAssertionError", wxPyAssertionError
);
378 // Initialize wxWindows and bootstrap the user application by calling the
379 // wxApp's OnInit, which is a parameter to this funciton. See wxApp.__init__
380 // in _extras.py to learn how the bootstrap is started.
381 PyObject
* __wxStart(PyObject
* /* self */, PyObject
* args
)
383 PyObject
* onInitFunc
= NULL
;
384 PyObject
* arglist
= NULL
;
385 PyObject
* result
= NULL
;
386 PyObject
* pyint
= NULL
;
389 if (!PyArg_ParseTuple(args
, "O", &onInitFunc
))
392 // Get any command-line args passed to this program from the sys module
395 PyObject
* sysargv
= PySys_GetObject("argv");
396 if (sysargv
!= NULL
) {
397 argc
= PyList_Size(sysargv
);
398 argv
= new char*[argc
+1];
400 for(x
=0; x
<argc
; x
++) {
401 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
402 argv
[x
] = PyString_AsString(pyArg
);
407 if (! wxEntryStart(argc
, argv
) ) {
408 PyErr_SetString(PyExc_SystemError
, // is this the right one?
409 "wxEntryStart failed!");
415 // The stock objects were all NULL when they were loaded into
416 // SWIG generated proxies, so re-init those now...
417 wxPy_ReinitStockObjects();
420 // Call the Python wxApp's OnInit function
421 arglist
= PyTuple_New(0);
422 result
= PyEval_CallObject(onInitFunc
, arglist
);
424 if (!result
) { // an exception was raised.
428 pyint
= PyNumber_Int(result
);
430 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
433 bResult
= PyInt_AS_LONG(pyint
);
435 PyErr_SetString(PyExc_SystemExit
, "OnInit returned FALSE, exiting...");
453 wxPyDoingCleanup
= TRUE
;
456 #ifdef WXP_WITH_THREAD
459 wxPyTStates
->Empty();
468 PyObject
* __wxSetDictionary(PyObject
* /* self */, PyObject
* args
)
471 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
474 if (!PyDict_Check(wxPython_dict
)) {
475 PyErr_SetString(PyExc_TypeError
, "_wxSetDictionary must have dictionary object!");
479 if (! wxPyPtrTypeMap
)
480 wxPyPtrTypeMap
= PyDict_New();
481 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
485 #define wxPlatform "__WXMOTIF__"
488 #define wxPlatform "__WXX11__"
491 #define wxPlatform "__WXGTK__"
493 #if defined(__WIN32__) || defined(__WXMSW__)
494 #define wxPlatform "__WXMSW__"
497 #define wxPlatform "__WXMAC__"
506 PyDict_SetItemString(wxPython_dict
, "wxPlatform", PyString_FromString(wxPlatform
));
507 PyDict_SetItemString(wxPython_dict
, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
508 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
515 //---------------------------------------------------------------------------
517 // The stock objects are no longer created when the wxc module is imported, but
518 // only after the app object has been created. This function will be called before
519 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
521 void wxPy_ReinitStockObjects()
529 #define REINITOBJ(name, type) \
530 obj = PyDict_GetItemString(wxPython_dict, #name); \
531 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
532 SWIG_MakePtr(ptrbuf, (char *) name, "_" #type "_p"); \
533 ptrobj = PyString_FromString(ptrbuf); \
534 PyObject_SetAttrString(obj, "this", ptrobj); \
537 #define REINITOBJ2(name, type) \
538 obj = PyDict_GetItemString(wxPython_dict, #name); \
539 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
540 SWIG_MakePtr(ptrbuf, (char *) &name, "_" #type "_p"); \
541 ptrobj = PyString_FromString(ptrbuf); \
542 PyObject_SetAttrString(obj, "this", ptrobj); \
546 REINITOBJ(wxNORMAL_FONT
, wxFont
);
547 REINITOBJ(wxSMALL_FONT
, wxFont
);
548 REINITOBJ(wxITALIC_FONT
, wxFont
);
549 REINITOBJ(wxSWISS_FONT
, wxFont
);
551 REINITOBJ(wxRED_PEN
, wxPen
);
552 REINITOBJ(wxCYAN_PEN
, wxPen
);
553 REINITOBJ(wxGREEN_PEN
, wxPen
);
554 REINITOBJ(wxBLACK_PEN
, wxPen
);
555 REINITOBJ(wxWHITE_PEN
, wxPen
);
556 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
557 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
558 REINITOBJ(wxGREY_PEN
, wxPen
);
559 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
560 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
562 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
563 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
564 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
565 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
566 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
567 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
568 REINITOBJ(wxRED_BRUSH
, wxBrush
);
569 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
570 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
571 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
573 REINITOBJ(wxBLACK
, wxColour
);
574 REINITOBJ(wxWHITE
, wxColour
);
575 REINITOBJ(wxRED
, wxColour
);
576 REINITOBJ(wxBLUE
, wxColour
);
577 REINITOBJ(wxGREEN
, wxColour
);
578 REINITOBJ(wxCYAN
, wxColour
);
579 REINITOBJ(wxLIGHT_GREY
, wxColour
);
581 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
582 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
583 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
585 REINITOBJ2(wxNullBitmap
, wxBitmap
);
586 REINITOBJ2(wxNullIcon
, wxIcon
);
587 REINITOBJ2(wxNullCursor
, wxCursor
);
588 REINITOBJ2(wxNullPen
, wxPen
);
589 REINITOBJ2(wxNullBrush
, wxBrush
);
590 REINITOBJ2(wxNullPalette
, wxPalette
);
591 REINITOBJ2(wxNullFont
, wxFont
);
592 REINITOBJ2(wxNullColour
, wxColour
);
594 REINITOBJ(wxTheFontList
, wxFontList
);
595 REINITOBJ(wxThePenList
, wxPenList
);
596 REINITOBJ(wxTheBrushList
, wxBrushList
);
597 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
600 REINITOBJ(wxTheClipboard
, wxClipboard
);
601 REINITOBJ(wxTheMimeTypesManager
, wxMimeTypesManager
);
602 REINITOBJ2(wxDefaultValidator
, wxValidator
);
603 REINITOBJ2(wxNullImage
, wxImage
);
604 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
610 //---------------------------------------------------------------------------
612 void wxPyClientData_dtor(wxPyClientData
* self
) {
613 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
614 // may have already garbage collected the object...
615 wxPyBeginBlockThreads();
616 Py_DECREF(self
->m_obj
);
617 wxPyEndBlockThreads();
621 void wxPyUserData_dtor(wxPyUserData
* self
) {
622 if (! wxPyDoingCleanup
) {
623 wxPyBeginBlockThreads();
624 Py_DECREF(self
->m_obj
);
625 wxPyEndBlockThreads();
630 // This is called when an OOR controled object is being destroyed. Although
631 // the C++ object is going away there is no way to force the Python object
632 // (and all references to it) to die too. This causes problems (crashes) in
633 // wxPython when a python shadow object attempts to call a C++ method using
634 // the now bogus pointer... So to try and prevent this we'll do a little black
635 // magic and change the class of the python instance to a class that will
636 // raise an exception for any attempt to call methods with it. See
637 // _wxPyDeadObject in _extras.py for the implementation of this class.
638 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
640 static PyObject
* deadObjectClass
= NULL
;
642 wxPyBeginBlockThreads();
643 if (deadObjectClass
== NULL
) {
644 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
645 wxASSERT_MSG(deadObjectClass
!= NULL
, wxT("Can't get _wxPyDeadObject class!"));
646 Py_INCREF(deadObjectClass
);
650 // Only if there is more than one reference to the object
651 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
652 wxASSERT_MSG(PyInstance_Check(self
->m_obj
), wxT("m_obj not an instance!?!?!"));
654 // Call __del__, if there is one.
655 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
657 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
661 if (PyErr_Occurred())
662 PyErr_Clear(); // just ignore it for now
664 // Clear the instance's dictionary
665 PyInstanceObject
* inst
= (PyInstanceObject
*)self
->m_obj
;
666 PyDict_Clear(inst
->in_dict
);
668 // put the name of the old class into the instance, and then reset the
669 // class to be the dead class.
670 PyDict_SetItemString(inst
->in_dict
, "_name", inst
->in_class
->cl_name
);
671 inst
->in_class
= (PyClassObject
*)deadObjectClass
;
672 Py_INCREF(deadObjectClass
);
675 // m_obj is DECREF's in the base class dtor...
676 wxPyEndBlockThreads();
680 //---------------------------------------------------------------------------
681 // Stuff used by OOR to find the right wxPython class type to return and to
685 // The pointer type map is used when the "pointer" type name generated by SWIG
686 // is not the same as the shadow class name, for example wxPyTreeCtrl
687 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
688 // so we'll just make it a Python dictionary in the wx module's namespace.
689 // (See __wxSetDictionary)
690 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
691 if (! wxPyPtrTypeMap
)
692 wxPyPtrTypeMap
= PyDict_New();
693 PyDict_SetItemString(wxPyPtrTypeMap
,
695 PyString_FromString((char*)ptrName
));
700 PyObject
* wxPyClassExists(const wxString
& className
) {
703 wxString
name(className
);
704 char buff
[64]; // should always be big enough...
709 // Try the name as-is first
710 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
711 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
713 // if not found see if there is a mapped name for it
715 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
716 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
717 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
718 classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
722 return classobj
; // returns NULL if not found
726 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
727 PyObject
* target
= NULL
;
728 bool isEvtHandler
= FALSE
;
731 // If it's derived from wxEvtHandler then there may
732 // already be a pointer to a Python object that we can use
734 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
736 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
737 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
739 target
= data
->m_obj
;
745 // Otherwise make it the old fashioned way by making a
746 // new shadow object and putting this pointer in it.
747 wxClassInfo
* info
= source
->GetClassInfo();
748 wxString name
= info
->GetClassName();
749 PyObject
* klass
= wxPyClassExists(name
);
750 while (info
&& !klass
) {
751 name
= (wxChar
*)info
->GetBaseClassName1();
752 info
= wxClassInfo::FindClass(name
);
753 klass
= wxPyClassExists(name
);
756 target
= wxPyConstructObject(source
, name
, klass
, FALSE
);
757 if (target
&& isEvtHandler
)
758 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
760 wxString
msg(wxT("wxPython class not found for "));
761 msg
+= source
->GetClassInfo()->GetClassName();
762 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
766 } else { // source was NULL so return None.
767 Py_INCREF(Py_None
); target
= Py_None
;
773 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
774 PyObject
* target
= NULL
;
776 if (source
&& wxIsKindOf(source
, wxSizer
)) {
777 // If it's derived from wxSizer then there may
778 // already be a pointer to a Python object that we can use
780 wxSizer
* sz
= (wxSizer
*)source
;
781 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
783 target
= data
->m_obj
;
788 target
= wxPyMake_wxObject(source
, FALSE
);
789 if (target
!= Py_None
)
790 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
797 //---------------------------------------------------------------------------
799 PyObject
* wxPyConstructObject(void* ptr
,
800 const wxString
& className
,
807 wxString
name(className
);
808 char swigptr
[64]; // should always be big enough...
811 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
812 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
814 sprintf(buff
, "_%s_p", (const char*)name
.mbc_str());
815 SWIG_MakePtr(swigptr
, ptr
, buff
);
817 arg
= Py_BuildValue("(s)", swigptr
);
818 obj
= PyInstance_New(klass
, arg
, NULL
);
822 PyObject
* one
= PyInt_FromLong(1);
823 PyObject_SetAttrString(obj
, "thisown", one
);
831 PyObject
* wxPyConstructObject(void* ptr
,
832 const wxString
& className
,
839 char buff
[64]; // should always be big enough...
840 sprintf(buff
, "%sPtr", (const char*)className
.mbc_str());
842 wxASSERT_MSG(wxPython_dict
, wxT("wxPython_dict is not set yet!!"));
844 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
846 wxString
msg(wxT("wxPython class not found for "));
848 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
852 return wxPyConstructObject(ptr
, className
, classobj
, setThisOwn
);
856 //---------------------------------------------------------------------------
859 #ifdef WXP_WITH_THREAD
861 unsigned long wxPyGetCurrentThreadId() {
862 return wxThread::GetCurrentId();
865 static PyThreadState
* gs_shutdownTState
;
867 PyThreadState
* wxPyGetThreadState() {
868 if (wxPyTMutex
== NULL
) // Python is shutting down...
869 return gs_shutdownTState
;
871 unsigned long ctid
= wxPyGetCurrentThreadId();
872 PyThreadState
* tstate
= NULL
;
875 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
876 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
877 if (info
.tid
== ctid
) {
878 tstate
= info
.tstate
;
882 wxPyTMutex
->Unlock();
883 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
888 void wxPySaveThreadState(PyThreadState
* tstate
) {
889 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
890 gs_shutdownTState
= tstate
;
893 unsigned long ctid
= wxPyGetCurrentThreadId();
895 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
896 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
897 if (info
.tid
== ctid
) {
899 if (info
.tstate
!= tstate
)
900 wxLogMessage("*** tstate mismatch!???");
902 // info.tstate = tstate; *** DO NOT update existing ones???
903 // Normally it will never change, but apparently COM callbacks
904 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
905 // tstate which will then be garbage the next time we try to use
907 wxPyTMutex
->Unlock();
911 // not found, so add it...
912 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
913 wxPyTMutex
->Unlock();
919 // Calls from Python to wxWindows code are wrapped in calls to these
922 PyThreadState
* wxPyBeginAllowThreads() {
923 #ifdef WXP_WITH_THREAD
924 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
925 wxPySaveThreadState(saved
);
932 void wxPyEndAllowThreads(PyThreadState
* saved
) {
933 #ifdef WXP_WITH_THREAD
934 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
940 // Calls from wxWindows back to Python code, or even any PyObject
941 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
943 void wxPyBeginBlockThreads() {
944 #ifdef WXP_WITH_THREAD
945 PyThreadState
* tstate
= wxPyGetThreadState();
946 PyEval_RestoreThread(tstate
);
951 void wxPyEndBlockThreads() {
952 #ifdef WXP_WITH_THREAD
953 // Is there any need to save it again?
954 // PyThreadState* tstate =
960 //---------------------------------------------------------------------------
961 // wxPyInputStream and wxPyCBInputStream methods
964 void wxPyInputStream::close() {
965 /* do nothing for now */
968 void wxPyInputStream::flush() {
969 /* do nothing for now */
972 bool wxPyInputStream::eof() {
974 return m_wxis
->Eof();
979 wxPyInputStream::~wxPyInputStream() {
986 PyObject
* wxPyInputStream::read(int size
) {
987 PyObject
* obj
= NULL
;
989 const int BUFSIZE
= 1024;
991 // check if we have a real wxInputStream to work with
993 wxPyBeginBlockThreads();
994 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
995 wxPyEndBlockThreads();
1000 // read while bytes are available on the stream
1001 while ( m_wxis
->CanRead() ) {
1002 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1003 buf
.UngetAppendBuf(m_wxis
->LastRead());
1006 } else { // Read only size number of characters
1007 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1008 buf
.UngetWriteBuf(m_wxis
->LastRead());
1012 wxPyBeginBlockThreads();
1013 wxStreamError err
= m_wxis
->GetLastError();
1014 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1015 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1018 // We use only strings for the streams, not unicode
1019 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1021 wxPyEndBlockThreads();
1026 PyObject
* wxPyInputStream::readline(int size
) {
1027 PyObject
* obj
= NULL
;
1032 // check if we have a real wxInputStream to work with
1034 wxPyBeginBlockThreads();
1035 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1036 wxPyEndBlockThreads();
1040 // read until \n or byte limit reached
1041 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1042 ch
= m_wxis
->GetC();
1047 wxPyBeginBlockThreads();
1048 wxStreamError err
= m_wxis
->GetLastError();
1049 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1050 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1053 // We use only strings for the streams, not unicode
1054 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1056 wxPyEndBlockThreads();
1061 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1064 // check if we have a real wxInputStream to work with
1066 wxPyBeginBlockThreads();
1067 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1068 wxPyEndBlockThreads();
1073 wxPyBeginBlockThreads();
1074 pylist
= PyList_New(0);
1076 wxPyBeginBlockThreads();
1078 wxPyEndBlockThreads();
1082 // read sizehint bytes or until EOF
1084 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1085 PyObject
* s
= this->readline();
1087 wxPyBeginBlockThreads();
1089 wxPyEndBlockThreads();
1092 wxPyBeginBlockThreads();
1093 PyList_Append(pylist
, s
);
1094 i
+= PyString_Size(s
);
1095 wxPyEndBlockThreads();
1099 wxStreamError err
= m_wxis
->GetLastError();
1100 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1101 wxPyBeginBlockThreads();
1103 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1104 wxPyEndBlockThreads();
1112 void wxPyInputStream::seek(int offset
, int whence
) {
1114 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1117 int wxPyInputStream::tell(){
1119 return m_wxis
->TellI();
1126 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1127 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1131 wxPyCBInputStream::~wxPyCBInputStream() {
1132 if (m_block
) wxPyBeginBlockThreads();
1136 if (m_block
) wxPyEndBlockThreads();
1140 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1141 if (block
) wxPyBeginBlockThreads();
1143 PyObject
* read
= getMethod(py
, "read");
1144 PyObject
* seek
= getMethod(py
, "seek");
1145 PyObject
* tell
= getMethod(py
, "tell");
1148 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1152 if (block
) wxPyEndBlockThreads();
1156 if (block
) wxPyEndBlockThreads();
1157 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1161 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1162 return wxPyCBInputStream::create(py
, block
);
1165 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1166 if (!PyObject_HasAttrString(py
, name
))
1168 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1169 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1177 size_t wxPyCBInputStream::GetSize() const {
1178 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1179 if (m_seek
&& m_tell
) {
1180 off_t temp
= self
->OnSysTell();
1181 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1182 self
->OnSysSeek(temp
, wxFromStart
);
1190 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1194 wxPyBeginBlockThreads();
1195 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1196 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1200 if ((result
!= NULL
) && PyString_Check(result
)) {
1201 o
= PyString_Size(result
);
1203 m_lasterror
= wxSTREAM_EOF
;
1206 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1211 m_lasterror
= wxSTREAM_READ_ERROR
;
1212 wxPyEndBlockThreads();
1216 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1217 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1221 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1222 wxPyBeginBlockThreads();
1224 // off_t is a 64-bit value...
1225 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1227 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1229 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1232 wxPyEndBlockThreads();
1237 off_t
wxPyCBInputStream::OnSysTell() const {
1238 wxPyBeginBlockThreads();
1239 PyObject
* arglist
= Py_BuildValue("()");
1240 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1243 if (result
!= NULL
) {
1245 if (PyLong_Check(result
))
1246 o
= PyLong_AsLongLong(result
);
1249 o
= PyInt_AsLong(result
);
1253 wxPyEndBlockThreads();
1257 //----------------------------------------------------------------------
1259 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1261 wxPyCallback::wxPyCallback(PyObject
* func
) {
1266 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1267 m_func
= other
.m_func
;
1271 wxPyCallback::~wxPyCallback() {
1272 wxPyBeginBlockThreads();
1274 wxPyEndBlockThreads();
1279 // This function is used for all events destined for Python event handlers.
1280 void wxPyCallback::EventThunker(wxEvent
& event
) {
1281 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1282 PyObject
* func
= cb
->m_func
;
1286 bool checkSkip
= FALSE
;
1288 wxPyBeginBlockThreads();
1289 wxString className
= event
.GetClassInfo()->GetClassName();
1291 // If the event is one of these types then pass the original
1292 // event object instead of the one passed to us.
1293 if ( className
== wxT("wxPyEvent") ) {
1294 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1295 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1297 else if ( className
== wxT("wxPyCommandEvent") ) {
1298 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1299 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1302 arg
= wxPyConstructObject((void*)&event
, className
);
1305 // Call the event handler, passing the event object
1306 tuple
= PyTuple_New(1);
1307 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1308 result
= PyEval_CallObject(func
, tuple
);
1310 Py_DECREF(result
); // result is ignored, but we still need to decref it
1311 PyErr_Clear(); // Just in case...
1317 // if the event object was one of our special types and
1318 // it had been cloned, then we need to extract the Skipped
1319 // value from the original and set it in the clone.
1320 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1322 event
.Skip(PyInt_AsLong(result
));
1330 wxPyEndBlockThreads();
1334 //----------------------------------------------------------------------
1336 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1338 m_self
= other
.m_self
;
1339 m_class
= other
.m_class
;
1347 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1358 #if PYTHON_API_VERSION >= 1011
1360 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1361 // in which the method was defined. Starting with 2.2 it returns
1362 // "class that asked for the method" which seems totally bogus to me
1363 // but apprently it fixes some obscure problem waiting to happen in
1364 // Python. Since the API was not documented Guido and the gang felt
1365 // safe in changing it. Needless to say that totally screwed up the
1366 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1367 // code to find the class where the method is actually defined...
1370 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1374 if (PyType_Check(klass
)) { // new style classes
1375 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1376 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1377 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1378 PyObject
*mro
, *res
, *base
, *dict
;
1379 /* Look in tp_dict of types in MRO */
1381 assert(PyTuple_Check(mro
));
1382 n
= PyTuple_GET_SIZE(mro
);
1383 for (i
= 0; i
< n
; i
++) {
1384 base
= PyTuple_GET_ITEM(mro
, i
);
1385 if (PyClass_Check(base
))
1386 dict
= ((PyClassObject
*)base
)->cl_dict
;
1388 assert(PyType_Check(base
));
1389 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1391 assert(dict
&& PyDict_Check(dict
));
1392 res
= PyDict_GetItem(dict
, name
);
1399 else if (PyClass_Check(klass
)) { // old style classes
1400 // This code is borrowed/adapted from class_lookup in classobject.c
1401 PyClassObject
* cp
= (PyClassObject
*)klass
;
1402 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1403 if (value
!= NULL
) {
1404 return (PyObject
*)cp
;
1406 n
= PyTuple_Size(cp
->cl_bases
);
1407 for (i
= 0; i
< n
; i
++) {
1408 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1409 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1421 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1423 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1425 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1427 #else // 2.2 and after, the hard way...
1429 PyObject
* nameo
= PyString_FromString(name
);
1430 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1438 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1439 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1440 self
->m_lastFound
= NULL
;
1442 // If the object (m_self) has an attibute of the given name...
1443 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1444 PyObject
*method
, *klass
;
1445 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1447 // ...and if that attribute is a method, and if that method's class is
1448 // not from a base class...
1449 if (PyMethod_Check(method
) &&
1450 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1451 ((klass
== m_class
) || PyClass_IsSubclass(klass
, m_class
))) {
1453 // ...then we'll save a pointer to the method so callCallback can call it.
1454 self
->m_lastFound
= method
;
1460 return m_lastFound
!= NULL
;
1464 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1468 result
= callCallbackObj(argTuple
);
1469 if (result
) { // Assumes an integer return type...
1470 retval
= PyInt_AsLong(result
);
1472 PyErr_Clear(); // forget about it if it's not...
1477 // Invoke the Python callable object, returning the raw PyObject return
1478 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1479 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1482 // Save a copy of the pointer in case the callback generates another
1483 // callback. In that case m_lastFound will have a different value when
1484 // it gets back here...
1485 PyObject
* method
= m_lastFound
;
1487 result
= PyEval_CallObject(method
, argTuple
);
1488 Py_DECREF(argTuple
);
1497 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1498 cbh
.setSelf(self
, klass
, incref
);
1501 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1502 return cbh
.findCallback(name
);
1505 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1506 return cbh
.callCallback(argTuple
);
1509 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1510 return cbh
.callCallbackObj(argTuple
);
1514 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1515 if (cbh
->m_incRef
) {
1516 wxPyBeginBlockThreads();
1517 Py_XDECREF(cbh
->m_self
);
1518 Py_XDECREF(cbh
->m_class
);
1519 wxPyEndBlockThreads();
1523 //---------------------------------------------------------------------------
1524 //---------------------------------------------------------------------------
1525 // These event classes can be derived from in Python and passed through the event
1526 // system without losing anything. They do this by keeping a reference to
1527 // themselves and some special case handling in wxPyCallback::EventThunker.
1530 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1531 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1532 //Py_INCREF(m_self); // circular loops...
1536 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1537 wxPyBeginBlockThreads();
1540 wxPyEndBlockThreads();
1543 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1544 wxPyBeginBlockThreads();
1552 wxPyEndBlockThreads();
1555 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1561 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1562 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1565 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1566 : wxEvent(winid
, commandType
) {
1570 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1573 SetSelf(evt
.m_self
, TRUE
);
1577 wxPyEvent::~wxPyEvent() {
1581 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1582 : wxCommandEvent(commandType
, id
) {
1586 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1587 : wxCommandEvent(evt
)
1589 SetSelf(evt
.m_self
, TRUE
);
1593 wxPyCommandEvent::~wxPyCommandEvent() {
1599 //---------------------------------------------------------------------------
1600 //---------------------------------------------------------------------------
1603 wxPyTimer::wxPyTimer(PyObject
* callback
) {
1608 wxPyTimer::~wxPyTimer() {
1609 wxPyBeginBlockThreads();
1611 wxPyEndBlockThreads();
1614 void wxPyTimer::Notify() {
1615 if (!func
|| func
== Py_None
) {
1619 wxPyBeginBlockThreads();
1622 PyObject
* args
= Py_BuildValue("()");
1624 result
= PyEval_CallObject(func
, args
);
1633 wxPyEndBlockThreads();
1639 //---------------------------------------------------------------------------
1640 //---------------------------------------------------------------------------
1641 // Convert a wxList to a Python List
1643 PyObject
* wxPy_ConvertList(wxListBase
* listbase
, const char* className
) {
1644 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1648 wxNode
* node
= list
->GetFirst();
1650 wxPyBeginBlockThreads();
1651 pyList
= PyList_New(0);
1653 wxObj
= node
->GetData();
1654 pyObj
= wxPyMake_wxObject(wxObj
); //wxPyConstructObject(wxObj, className);
1655 PyList_Append(pyList
, pyObj
);
1656 node
= node
->GetNext();
1658 wxPyEndBlockThreads();
1662 //----------------------------------------------------------------------
1664 long wxPyGetWinHandle(wxWindow
* win
) {
1666 return (long)win
->GetHandle();
1670 return (long)win
->GetHandle();
1673 // Find and return the actual X-Window.
1675 if (win
->m_wxwindow
) {
1677 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1679 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1681 return (long)bwin
->xwindow
;
1689 //----------------------------------------------------------------------
1690 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1691 // included in every file over and over again...
1693 #if PYTHON_API_VERSION >= 1009
1694 static char* wxStringErrorMsg
= "String or Unicode type required";
1696 static char* wxStringErrorMsg
= "String type required";
1700 wxString
* wxString_in_helper(PyObject
* source
) {
1702 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1703 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1704 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1708 if (PyUnicode_Check(source
)) {
1709 target
= new wxString();
1710 size_t len
= PyUnicode_GET_SIZE(source
);
1712 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1713 target
->UngetWriteBuf();
1716 // It is a string, get pointers to it and transform to unicode
1717 char* tmpPtr
; int tmpSize
;
1718 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1719 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1722 char* tmpPtr
; int tmpSize
;
1723 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1724 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1727 target
= new wxString(tmpPtr
, tmpSize
);
1728 #endif // wxUSE_UNICODE
1730 #else // No Python unicode API (1.5.2)
1731 if (!PyString_Check(source
)) {
1732 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1735 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1741 // Similar to above except doesn't use "new" and doesn't set an exception
1742 wxString
Py2wxString(PyObject
* source
)
1745 bool doDecRef
= FALSE
;
1747 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1748 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1749 // Convert to String if not one already... (TODO: Unicode too?)
1750 source
= PyObject_Str(source
);
1755 if (PyUnicode_Check(source
)) {
1756 size_t len
= PyUnicode_GET_SIZE(source
);
1758 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1759 target
.UngetWriteBuf();
1762 // It is a string, get pointers to it and transform to unicode
1763 char* tmpPtr
; int tmpSize
;
1764 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1765 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1768 char* tmpPtr
; int tmpSize
;
1769 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1770 target
= wxString(tmpPtr
, tmpSize
);
1771 #endif // wxUSE_UNICODE
1773 #else // No Python unicode API (1.5.2)
1774 if (!PyString_Check(source
)) {
1775 // Convert to String if not one already...
1776 source
= PyObject_Str(source
);
1779 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1788 // Make either a Python String or Unicode object, depending on build mode
1789 PyObject
* wx2PyString(const wxString
& src
)
1793 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1795 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1801 //----------------------------------------------------------------------
1804 byte
* byte_LIST_helper(PyObject
* source
) {
1805 if (!PyList_Check(source
)) {
1806 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1809 int count
= PyList_Size(source
);
1810 byte
* temp
= new byte
[count
];
1812 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1815 for (int x
=0; x
<count
; x
++) {
1816 PyObject
* o
= PyList_GetItem(source
, x
);
1817 if (! PyInt_Check(o
)) {
1818 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1821 temp
[x
] = (byte
)PyInt_AsLong(o
);
1827 int* int_LIST_helper(PyObject
* source
) {
1828 if (!PyList_Check(source
)) {
1829 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1832 int count
= PyList_Size(source
);
1833 int* temp
= new int[count
];
1835 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1838 for (int x
=0; x
<count
; x
++) {
1839 PyObject
* o
= PyList_GetItem(source
, x
);
1840 if (! PyInt_Check(o
)) {
1841 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1844 temp
[x
] = PyInt_AsLong(o
);
1850 long* long_LIST_helper(PyObject
* source
) {
1851 if (!PyList_Check(source
)) {
1852 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1855 int count
= PyList_Size(source
);
1856 long* temp
= new long[count
];
1858 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1861 for (int x
=0; x
<count
; x
++) {
1862 PyObject
* o
= PyList_GetItem(source
, x
);
1863 if (! PyInt_Check(o
)) {
1864 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1867 temp
[x
] = PyInt_AsLong(o
);
1873 char** string_LIST_helper(PyObject
* source
) {
1874 if (!PyList_Check(source
)) {
1875 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1878 int count
= PyList_Size(source
);
1879 char** temp
= new char*[count
];
1881 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1884 for (int x
=0; x
<count
; x
++) {
1885 PyObject
* o
= PyList_GetItem(source
, x
);
1886 if (! PyString_Check(o
)) {
1887 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1890 temp
[x
] = PyString_AsString(o
);
1895 //--------------------------------
1896 // Part of patch from Tim Hochberg
1897 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1898 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1899 point
->x
= PyInt_AS_LONG(o1
);
1900 point
->y
= PyInt_AS_LONG(o2
);
1903 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1904 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1905 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1908 if (PyInstance_Check(o1
) || PyInstance_Check(o2
)) {
1909 // Disallow instances because they can cause havok
1912 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1913 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1914 point
->x
= PyInt_AsLong(o1
);
1915 point
->y
= PyInt_AsLong(o2
);
1922 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1923 // Putting all of the declarations here allows
1924 // us to put the error handling all in one place.
1927 PyObject
*o
, *o1
, *o2
;
1928 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1930 if (!PySequence_Check(source
)) {
1934 // The length of the sequence is returned in count.
1935 *count
= PySequence_Length(source
);
1940 temp
= new wxPoint
[*count
];
1942 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1945 for (x
=0; x
<*count
; x
++) {
1946 // Get an item: try fast way first.
1948 o
= PySequence_Fast_GET_ITEM(source
, x
);
1951 o
= PySequence_GetItem(source
, x
);
1957 // Convert o to wxPoint.
1958 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1959 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1960 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1961 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1962 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1966 else if (PyInstance_Check(o
)) {
1968 if (SWIG_GetPtrObj(o
, (void **)&pt
, "_wxPoint_p")) {
1973 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1974 o1
= PySequence_GetItem(o
, 0);
1975 o2
= PySequence_GetItem(o
, 1);
1976 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2000 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2004 //------------------------------
2007 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2008 if (!PyList_Check(source
)) {
2009 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2012 int count
= PyList_Size(source
);
2013 wxBitmap
** temp
= new wxBitmap
*[count
];
2015 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2018 for (int x
=0; x
<count
; x
++) {
2019 PyObject
* o
= PyList_GetItem(source
, x
);
2020 if (PyInstance_Check(o
)) {
2022 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxBitmap_p")) {
2023 PyErr_SetString(PyExc_TypeError
,"Expected _wxBitmap_p.");
2029 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2038 wxString
* wxString_LIST_helper(PyObject
* source
) {
2039 if (!PyList_Check(source
)) {
2040 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2043 int count
= PyList_Size(source
);
2044 wxString
* temp
= new wxString
[count
];
2046 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2049 for (int x
=0; x
<count
; x
++) {
2050 PyObject
* o
= PyList_GetItem(source
, x
);
2051 #if PYTHON_API_VERSION >= 1009
2052 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2053 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2057 if (! PyString_Check(o
)) {
2058 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2063 wxString
* pStr
= wxString_in_helper(o
);
2071 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2072 if (!PyList_Check(source
)) {
2073 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2076 int count
= PyList_Size(source
);
2077 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2079 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2082 for (int x
=0; x
<count
; x
++) {
2083 PyObject
* o
= PyList_GetItem(source
, x
);
2084 if (PyInstance_Check(o
)) {
2085 wxAcceleratorEntry
* ae
;
2086 if (SWIG_GetPtrObj(o
, (void **) &ae
,"_wxAcceleratorEntry_p")) {
2087 PyErr_SetString(PyExc_TypeError
,"Expected _wxAcceleratorEntry_p.");
2092 else if (PyTuple_Check(o
)) {
2093 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2094 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2095 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2096 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2099 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2107 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2108 if (!PyList_Check(source
)) {
2109 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2112 int count
= PyList_Size(source
);
2113 wxPen
** temp
= new wxPen
*[count
];
2115 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2118 for (int x
=0; x
<count
; x
++) {
2119 PyObject
* o
= PyList_GetItem(source
, x
);
2120 if (PyInstance_Check(o
)) {
2122 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxPen_p")) {
2124 PyErr_SetString(PyExc_TypeError
,"Expected _wxPen_p.");
2131 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2139 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2140 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2143 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2147 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2148 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2151 o1
= PySequence_GetItem(source
, 0);
2152 o2
= PySequence_GetItem(source
, 1);
2155 *i1
= PyInt_AsLong(o1
);
2156 *i2
= PyInt_AsLong(o2
);
2166 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2167 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2168 PyObject
*o1
, *o2
, *o3
, *o4
;
2170 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2174 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2175 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2176 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2177 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2180 o1
= PySequence_GetItem(source
, 0);
2181 o2
= PySequence_GetItem(source
, 1);
2182 o3
= PySequence_GetItem(source
, 2);
2183 o4
= PySequence_GetItem(source
, 3);
2186 *i1
= PyInt_AsLong(o1
);
2187 *i2
= PyInt_AsLong(o2
);
2188 *i3
= PyInt_AsLong(o3
);
2189 *i4
= PyInt_AsLong(o4
);
2201 //----------------------------------------------------------------------
2203 bool wxSize_helper(PyObject
* source
, wxSize
** obj
) {
2205 // If source is an object instance then it may already be the right type
2206 if (PyInstance_Check(source
)) {
2208 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxSize_p"))
2213 // otherwise a 2-tuple of integers is expected
2214 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2215 PyObject
* o1
= PySequence_GetItem(source
, 0);
2216 PyObject
* o2
= PySequence_GetItem(source
, 1);
2217 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2222 **obj
= wxSize(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2229 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxSize object.");
2234 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
) {
2236 // If source is an object instance then it may already be the right type
2237 if (PyInstance_Check(source
)) {
2239 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint_p"))
2244 // otherwise a length-2 sequence of integers is expected
2245 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2246 PyObject
* o1
= PySequence_GetItem(source
, 0);
2247 PyObject
* o2
= PySequence_GetItem(source
, 1);
2248 // This should really check for integers, not numbers -- but that would break code.
2249 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2254 **obj
= wxPoint(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2260 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxPoint object.");
2266 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2268 // If source is an object instance then it may already be the right type
2269 if (PyInstance_Check(source
)) {
2271 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRealPoint_p"))
2276 // otherwise a 2-tuple of floats is expected
2277 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2278 PyObject
* o1
= PySequence_GetItem(source
, 0);
2279 PyObject
* o2
= PySequence_GetItem(source
, 1);
2280 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2285 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2292 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2299 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2301 // If source is an object instance then it may already be the right type
2302 if (PyInstance_Check(source
)) {
2304 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRect_p"))
2309 // otherwise a 4-tuple of integers is expected
2310 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2311 PyObject
* o1
= PySequence_GetItem(source
, 0);
2312 PyObject
* o2
= PySequence_GetItem(source
, 1);
2313 PyObject
* o3
= PySequence_GetItem(source
, 2);
2314 PyObject
* o4
= PySequence_GetItem(source
, 3);
2315 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2316 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2323 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2324 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2333 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2339 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2341 // If source is an object instance then it may already be the right type
2342 if (PyInstance_Check(source
)) {
2344 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxColour_p"))
2349 // otherwise check for a string
2350 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2351 wxString spec
= Py2wxString(source
);
2352 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2353 long red
, green
, blue
;
2354 red
= green
= blue
= 0;
2355 spec
.Mid(1,2).ToLong(&red
, 16);
2356 spec
.Mid(3,2).ToLong(&green
, 16);
2357 spec
.Mid(5,2).ToLong(&blue
, 16);
2359 **obj
= wxColour(red
, green
, blue
);
2362 else { // it's a colour name
2363 **obj
= wxColour(spec
);
2367 // last chance: 3-tuple of integers is expected
2368 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2369 PyObject
* o1
= PySequence_GetItem(source
, 0);
2370 PyObject
* o2
= PySequence_GetItem(source
, 1);
2371 PyObject
* o3
= PySequence_GetItem(source
, 2);
2372 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2378 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2386 PyErr_SetString(PyExc_TypeError
,
2387 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2393 bool wxPoint2DDouble_helper(PyObject
* source
, wxPoint2DDouble
** obj
) {
2394 // If source is an object instance then it may already be the right type
2395 if (PyInstance_Check(source
)) {
2396 wxPoint2DDouble
* ptr
;
2397 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint2DDouble_p"))
2402 // otherwise a length-2 sequence of floats is expected
2403 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2404 PyObject
* o1
= PySequence_GetItem(source
, 0);
2405 PyObject
* o2
= PySequence_GetItem(source
, 1);
2406 // This should really check for integers, not numbers -- but that would break code.
2407 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2412 **obj
= wxPoint2DDouble(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2418 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2424 //----------------------------------------------------------------------
2426 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2428 PyObject
* list
= PyList_New(0);
2429 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2431 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2433 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2435 PyList_Append(list
, str
);
2442 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2444 PyObject
* list
= PyList_New(0);
2445 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2446 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2447 PyList_Append(list
, number
);
2454 //----------------------------------------------------------------------
2455 //----------------------------------------------------------------------