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 //----------------------------------------------------------------------
33 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
34 #error Python must support Unicode to use wxWindows Unicode
37 //----------------------------------------------------------------------
40 int WXDLLEXPORT
wxEntryStart( int& argc
, char** argv
);
42 int WXDLLEXPORT
wxEntryStart( int argc
, char** argv
);
44 int WXDLLEXPORT
wxEntryInitGui();
45 void WXDLLEXPORT
wxEntryCleanup();
47 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
48 bool wxPyDoCleanup
= FALSE
;
49 bool wxPyDoingCleanup
= FALSE
;
52 #ifdef WXP_WITH_THREAD
53 struct wxPyThreadState
{
55 PyThreadState
* tstate
;
57 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
58 : tid(_tid
), tstate(_tstate
) {}
61 #include <wx/dynarray.h>
62 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
63 #include <wx/arrimpl.cpp>
64 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
66 wxPyThreadStateArray
* wxPyTStates
= NULL
;
67 wxMutex
* wxPyTMutex
= NULL
;
71 static PyObject
* wxPython_dict
= NULL
;
72 static PyObject
* wxPyPtrTypeMap
= NULL
;
73 static PyObject
* wxPyAssertionError
= NULL
;
76 #ifdef __WXMSW__ // If building for win32...
77 //----------------------------------------------------------------------
78 // This gets run when the DLL is loaded. We just need to save a handle.
79 //----------------------------------------------------------------------
82 HINSTANCE hinstDLL
, // handle to DLL module
83 DWORD fdwReason
, // reason for calling function
84 LPVOID lpvReserved
// reserved
87 // If wxPython is embedded in another wxWindows app then
88 // the inatance has already been set.
89 if (! wxGetInstance())
90 wxSetInstance(hinstDLL
);
95 //----------------------------------------------------------------------
96 // Classes for implementing the wxp main application shell.
97 //----------------------------------------------------------------------
99 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
103 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
107 wxPyApp::~wxPyApp() {
111 // This one isn't acutally called... We fake it with __wxStart()
112 bool wxPyApp::OnInit() {
117 int wxPyApp::MainLoop() {
120 DeletePendingObjects();
121 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
123 m_initialized
= initialized
;
127 if ( m_exitOnFrameDelete
== Later
) {
128 m_exitOnFrameDelete
= Yes
;
131 retval
= wxApp::MainLoop();
138 bool wxPyApp::OnInitGui() {
140 wxApp::OnInitGui(); // in this case always call the base class version
141 // wxPyBeginBlockThreads(); *** only called from within __wxStart so we already have the GIL
142 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
143 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
144 // wxPyEndBlockThreads(); ***
149 int wxPyApp::OnExit() {
151 wxPyBeginBlockThreads();
152 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
153 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
154 wxPyEndBlockThreads();
155 wxApp::OnExit(); // in this case always call the base class version
161 void wxPyApp::OnAssert(const wxChar
*file
,
166 // If the OnAssert is overloaded in the Python class then call it...
168 wxPyBeginBlockThreads();
169 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
170 PyObject
* fso
= wx2PyString(file
);
171 PyObject
* cso
= wx2PyString(file
);
174 mso
= wx2PyString(file
);
176 mso
= Py_None
; Py_INCREF(Py_None
);
178 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
183 wxPyEndBlockThreads();
185 // ...otherwise do our own thing with it
188 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
191 // turn it into a Python exception?
192 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
195 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
202 wxPyBeginBlockThreads();
203 PyObject
* s
= wx2PyString(buf
);
204 PyErr_SetObject(wxPyAssertionError
, s
);
206 wxPyEndBlockThreads();
208 // Now when control returns to whatever API wrapper was called from
209 // Python it should detect that an exception is set and will return
210 // NULL, signalling the exception to Python.
213 // Send it to the normal log destination, but only if
214 // not _DIALOG because it will call this too
215 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
218 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
227 // do the normal wx assert dialog?
228 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
229 wxApp::OnAssert(file
, line
, cond
, msg
);
236 bool wxPyApp::GetMacDefaultEncodingIsPC() {
238 return s_macDefaultEncodingIsPC
;
245 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
247 return s_macSupportPCMenuShortcuts
;
254 long wxPyApp::GetMacAboutMenuItemId() {
256 return s_macAboutMenuItemId
;
263 long wxPyApp::GetMacPreferencesMenuItemId() {
265 return s_macPreferencesMenuItemId
;
272 long wxPyApp::GetMacExitMenuItemId() {
274 return s_macExitMenuItemId
;
281 wxString
wxPyApp::GetMacHelpMenuTitleName() {
283 return s_macHelpMenuTitleName
;
285 return wxEmptyString
;
290 void wxPyApp::SetMacDefaultEncodingIsPC(bool val
) {
292 s_macDefaultEncodingIsPC
= val
;
297 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
299 s_macSupportPCMenuShortcuts
= val
;
304 void wxPyApp::SetMacAboutMenuItemId(long val
) {
306 s_macAboutMenuItemId
= val
;
311 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
313 s_macPreferencesMenuItemId
= val
;
318 void wxPyApp::SetMacExitMenuItemId(long val
) {
320 s_macExitMenuItemId
= val
;
325 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
327 s_macHelpMenuTitleName
= val
;
333 //---------------------------------------------------------------------
334 //----------------------------------------------------------------------
337 static char* wxPyCopyCString(const wxChar
* src
)
339 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
340 size_t len
= strlen(buff
);
341 char* dest
= new char[len
+1];
347 static char* wxPyCopyCString(const char* src
) // we need a char version too
349 size_t len
= strlen(src
);
350 char* dest
= new char[len
+1];
356 static wxChar
* wxPyCopyWString(const char *src
)
358 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
359 wxString
str(src
, *wxConvCurrent
);
360 return copystring(str
);
364 static wxChar
* wxPyCopyWString(const wxChar
*src
)
366 return copystring(src
);
371 //----------------------------------------------------------------------
373 // This is where we pick up the first part of the wxEntry functionality...
374 // The rest is in __wxStart and __wxCleanup. This function is called when
375 // wxcmodule is imported. (Before there is a wxApp object.)
376 void __wxPreStart(PyObject
* moduleDict
)
380 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
383 #ifdef WXP_WITH_THREAD
384 PyEval_InitThreads();
385 wxPyTStates
= new wxPyThreadStateArray
;
386 wxPyTMutex
= new wxMutex
;
389 // Restore default signal handlers, (prevents crash upon Ctrl-C in the
390 // console that launched a wxPython app...)
391 PyOS_FiniInterrupts();
393 wxApp::CheckBuildOptions(wxBuildOptions());
395 wxPyAssertionError
= PyErr_NewException("wxPython.wxc.wxPyAssertionError",
396 PyExc_AssertionError
, NULL
);
397 PyDict_SetItemString(moduleDict
, "wxPyAssertionError", wxPyAssertionError
);
400 // Bail out if there is already a wxApp created. This means that the
401 // toolkit has already been initialized, as in embedding wxPython in
402 // a C++ wxWindows app, so we don't need to call wxEntryStart.
403 if (wxTheApp
!= NULL
) {
406 wxPyDoCleanup
= TRUE
;
410 PyObject
* sysargv
= PySys_GetObject("argv");
411 if (sysargv
!= NULL
) {
412 argc
= PyList_Size(sysargv
);
413 argv
= new char*[argc
+1];
415 for(x
=0; x
<argc
; x
++) {
416 PyObject
*item
= PyList_GetItem(sysargv
, x
);
417 argv
[x
] = wxPyCopyCString(Py2wxString(item
));
422 wxEntryStart(argc
, argv
);
427 // Start the user application, user App's OnInit method is a parameter here
428 PyObject
* __wxStart(PyObject
* /* self */, PyObject
* args
)
430 PyObject
* onInitFunc
= NULL
;
435 if (!PyArg_ParseTuple(args
, "O", &onInitFunc
))
438 // This is the next part of the wxEntry functionality...
440 wxChar
** argv
= NULL
;
441 PyObject
* sysargv
= PySys_GetObject("argv");
442 if (sysargv
!= NULL
) {
443 argc
= PyList_Size(sysargv
);
444 argv
= new wxChar
*[argc
+1];
446 for(x
=0; x
<argc
; x
++) {
447 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
);
448 argv
[x
] = wxPyCopyWString(Py2wxString(pyArg
));
453 wxPythonApp
->argc
= argc
;
454 wxPythonApp
->argv
= argv
;
458 // Call the Python App's OnInit function
459 arglist
= PyTuple_New(0);
460 result
= PyEval_CallObject(onInitFunc
, arglist
);
462 if (!result
) { // an exception was raised.
466 PyObject
* pyint
= PyNumber_Int(result
);
468 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
471 bResult
= PyInt_AS_LONG(pyint
);
473 PyErr_SetString(PyExc_SystemExit
, "OnInit returned FALSE, exiting...");
478 wxTheApp
->m_initialized
= (wxTopLevelWindows
.GetCount() > 0);
494 wxPyDoingCleanup
= TRUE
;
497 #ifdef WXP_WITH_THREAD
500 wxPyTStates
->Empty();
509 PyObject
* __wxSetDictionary(PyObject
* /* self */, PyObject
* args
)
512 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
515 if (!PyDict_Check(wxPython_dict
)) {
516 PyErr_SetString(PyExc_TypeError
, "_wxSetDictionary must have dictionary object!");
520 if (! wxPyPtrTypeMap
)
521 wxPyPtrTypeMap
= PyDict_New();
522 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
526 #define wxPlatform "__WXMOTIF__"
529 #define wxPlatform "__WXX11__"
532 #define wxPlatform "__WXGTK__"
534 #if defined(__WIN32__) || defined(__WXMSW__)
535 #define wxPlatform "__WXMSW__"
538 #define wxPlatform "__WXMAC__"
547 PyDict_SetItemString(wxPython_dict
, "wxPlatform", PyString_FromString(wxPlatform
));
548 PyDict_SetItemString(wxPython_dict
, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
549 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
555 //---------------------------------------------------------------------------
557 void wxPyClientData_dtor(wxPyClientData
* self
) {
558 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
559 // may have already garbage collected the object...
560 wxPyBeginBlockThreads();
561 Py_DECREF(self
->m_obj
);
562 wxPyEndBlockThreads();
566 void wxPyUserData_dtor(wxPyUserData
* self
) {
567 if (! wxPyDoingCleanup
) {
568 wxPyBeginBlockThreads();
569 Py_DECREF(self
->m_obj
);
570 wxPyEndBlockThreads();
575 // This is called when an OOR controled object is being destroyed. Although
576 // the C++ object is going away there is no way to force the Python object
577 // (and all references to it) to die too. This causes problems (crashes) in
578 // wxPython when a python shadow object attempts to call a C++ method using
579 // the now bogus pointer... So to try and prevent this we'll do a little black
580 // magic and change the class of the python instance to a class that will
581 // raise an exception for any attempt to call methods with it. See
582 // _wxPyDeadObject in _extras.py for the implementation of this class.
583 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
585 static PyObject
* deadObjectClass
= NULL
;
587 wxPyBeginBlockThreads();
588 if (deadObjectClass
== NULL
) {
589 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
590 wxASSERT_MSG(deadObjectClass
!= NULL
, wxT("Can't get _wxPyDeadObject class!"));
591 Py_INCREF(deadObjectClass
);
595 // Only if there is more than one reference to the object
596 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 ) {
597 wxASSERT_MSG(PyInstance_Check(self
->m_obj
), wxT("m_obj not an instance!?!?!"));
599 // Call __del__, if there is one.
600 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
602 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
606 if (PyErr_Occurred())
607 PyErr_Clear(); // just ignore it for now
609 // Clear the instance's dictionary
610 PyInstanceObject
* inst
= (PyInstanceObject
*)self
->m_obj
;
611 PyDict_Clear(inst
->in_dict
);
613 // put the name of the old class into the instance, and then reset the
614 // class to be the dead class.
615 PyDict_SetItemString(inst
->in_dict
, "_name", inst
->in_class
->cl_name
);
616 inst
->in_class
= (PyClassObject
*)deadObjectClass
;
617 Py_INCREF(deadObjectClass
);
620 // m_obj is DECREF's in the base class dtor...
621 wxPyEndBlockThreads();
625 //---------------------------------------------------------------------------
626 // Stuff used by OOR to find the right wxPython class type to return and to
630 // The pointer type map is used when the "pointer" type name generated by SWIG
631 // is not the same as the shadow class name, for example wxPyTreeCtrl
632 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
633 // so we'll just make it a Python dictionary in the wx module's namespace.
634 // (See __wxSetDictionary)
635 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
636 if (! wxPyPtrTypeMap
)
637 wxPyPtrTypeMap
= PyDict_New();
638 PyDict_SetItemString(wxPyPtrTypeMap
,
640 PyString_FromString((char*)ptrName
));
645 PyObject
* wxPyClassExists(const wxString
& className
) {
648 wxString
name(className
);
649 char buff
[64]; // should always be big enough...
654 // Try the name as-is first
655 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
656 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
658 // if not found see if there is a mapped name for it
660 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
661 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
662 sprintf(buff
, "%sPtr", (const char*)name
.mbc_str());
663 classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
667 return classobj
; // returns NULL if not found
671 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool checkEvtHandler
) {
672 PyObject
* target
= NULL
;
673 bool isEvtHandler
= FALSE
;
676 // If it's derived from wxEvtHandler then there may
677 // already be a pointer to a Python object that we can use
679 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
681 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
682 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
684 target
= data
->m_obj
;
690 // Otherwise make it the old fashioned way by making a
691 // new shadow object and putting this pointer in it.
692 wxClassInfo
* info
= source
->GetClassInfo();
693 wxString name
= info
->GetClassName();
694 PyObject
* klass
= wxPyClassExists(name
);
695 while (info
&& !klass
) {
696 name
= (wxChar
*)info
->GetBaseClassName1();
697 info
= wxClassInfo::FindClass(name
);
698 klass
= wxPyClassExists(name
);
701 target
= wxPyConstructObject(source
, name
, klass
, FALSE
);
702 if (target
&& isEvtHandler
)
703 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
705 wxString
msg(wxT("wxPython class not found for "));
706 msg
+= source
->GetClassInfo()->GetClassName();
707 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
711 } else { // source was NULL so return None.
712 Py_INCREF(Py_None
); target
= Py_None
;
718 PyObject
* wxPyMake_wxSizer(wxSizer
* source
) {
719 PyObject
* target
= NULL
;
721 if (source
&& wxIsKindOf(source
, wxSizer
)) {
722 // If it's derived from wxSizer then there may
723 // already be a pointer to a Python object that we can use
725 wxSizer
* sz
= (wxSizer
*)source
;
726 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
728 target
= data
->m_obj
;
733 target
= wxPyMake_wxObject(source
, FALSE
);
734 if (target
!= Py_None
)
735 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
742 //---------------------------------------------------------------------------
744 PyObject
* wxPyConstructObject(void* ptr
,
745 const wxString
& className
,
752 wxString
name(className
);
753 char swigptr
[64]; // should always be big enough...
756 if ((item
= PyDict_GetItemString(wxPyPtrTypeMap
, (char*)(const char*)name
.mbc_str())) != NULL
) {
757 name
= wxString(PyString_AsString(item
), *wxConvCurrent
);
759 sprintf(buff
, "_%s_p", (const char*)name
.mbc_str());
760 SWIG_MakePtr(swigptr
, ptr
, buff
);
762 arg
= Py_BuildValue("(s)", swigptr
);
763 obj
= PyInstance_New(klass
, arg
, NULL
);
767 PyObject
* one
= PyInt_FromLong(1);
768 PyObject_SetAttrString(obj
, "thisown", one
);
776 PyObject
* wxPyConstructObject(void* ptr
,
777 const wxString
& className
,
784 char buff
[64]; // should always be big enough...
785 sprintf(buff
, "%sPtr", (const char*)className
.mbc_str());
787 wxASSERT_MSG(wxPython_dict
, wxT("wxPython_dict is not set yet!!"));
789 PyObject
* classobj
= PyDict_GetItemString(wxPython_dict
, buff
);
791 wxString
msg(wxT("wxPython class not found for "));
793 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
797 return wxPyConstructObject(ptr
, className
, classobj
, setThisOwn
);
801 //---------------------------------------------------------------------------
804 #ifdef WXP_WITH_THREAD
806 unsigned long wxPyGetCurrentThreadId() {
807 return wxThread::GetCurrentId();
810 static PyThreadState
* gs_shutdownTState
;
812 PyThreadState
* wxPyGetThreadState() {
813 if (wxPyTMutex
== NULL
) // Python is shutting down...
814 return gs_shutdownTState
;
816 unsigned long ctid
= wxPyGetCurrentThreadId();
817 PyThreadState
* tstate
= NULL
;
820 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
821 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
822 if (info
.tid
== ctid
) {
823 tstate
= info
.tstate
;
827 wxPyTMutex
->Unlock();
828 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
833 void wxPySaveThreadState(PyThreadState
* tstate
) {
834 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
835 gs_shutdownTState
= tstate
;
838 unsigned long ctid
= wxPyGetCurrentThreadId();
840 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
841 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
842 if (info
.tid
== ctid
) {
844 if (info
.tstate
!= tstate
)
845 wxLogMessage("*** tstate mismatch!???");
847 // info.tstate = tstate; *** DO NOT update existing ones???
848 // Normally it will never change, but apparently COM callbacks
849 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
850 // tstate which will then be garbage the next time we try to use
852 wxPyTMutex
->Unlock();
856 // not found, so add it...
857 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
858 wxPyTMutex
->Unlock();
864 // Calls from Python to wxWindows code are wrapped in calls to these
867 PyThreadState
* wxPyBeginAllowThreads() {
868 #ifdef WXP_WITH_THREAD
869 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
870 wxPySaveThreadState(saved
);
877 void wxPyEndAllowThreads(PyThreadState
* saved
) {
878 #ifdef WXP_WITH_THREAD
879 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
885 // Calls from wxWindows back to Python code, or even any PyObject
886 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
888 void wxPyBeginBlockThreads() {
889 #ifdef WXP_WITH_THREAD
890 PyThreadState
* tstate
= wxPyGetThreadState();
891 PyEval_RestoreThread(tstate
);
896 void wxPyEndBlockThreads() {
897 #ifdef WXP_WITH_THREAD
898 // Is there any need to save it again?
899 // PyThreadState* tstate =
905 //---------------------------------------------------------------------------
906 // wxPyInputStream and wxPyCBInputStream methods
909 void wxPyInputStream::close() {
910 /* do nothing for now */
913 void wxPyInputStream::flush() {
914 /* do nothing for now */
917 bool wxPyInputStream::eof() {
919 return m_wxis
->Eof();
924 wxPyInputStream::~wxPyInputStream() {
931 PyObject
* wxPyInputStream::read(int size
) {
932 PyObject
* obj
= NULL
;
934 const int BUFSIZE
= 1024;
936 // check if we have a real wxInputStream to work with
938 wxPyBeginBlockThreads();
939 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
940 wxPyEndBlockThreads();
945 // read while bytes are available on the stream
946 while ( m_wxis
->CanRead() ) {
947 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
948 buf
.UngetAppendBuf(m_wxis
->LastRead());
951 } else { // Read only size number of characters
952 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
953 buf
.UngetWriteBuf(m_wxis
->LastRead());
957 wxPyBeginBlockThreads();
958 wxStreamError err
= m_wxis
->GetLastError();
959 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
960 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
963 // We use only strings for the streams, not unicode
964 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
966 wxPyEndBlockThreads();
971 PyObject
* wxPyInputStream::readline(int size
) {
972 PyObject
* obj
= NULL
;
977 // check if we have a real wxInputStream to work with
979 wxPyBeginBlockThreads();
980 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
981 wxPyEndBlockThreads();
985 // read until \n or byte limit reached
986 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
992 wxPyBeginBlockThreads();
993 wxStreamError err
= m_wxis
->GetLastError();
994 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
995 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
998 // We use only strings for the streams, not unicode
999 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1001 wxPyEndBlockThreads();
1006 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1009 // check if we have a real wxInputStream to work with
1011 wxPyBeginBlockThreads();
1012 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1013 wxPyEndBlockThreads();
1018 wxPyBeginBlockThreads();
1019 pylist
= PyList_New(0);
1021 wxPyBeginBlockThreads();
1023 wxPyEndBlockThreads();
1027 // read sizehint bytes or until EOF
1029 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1030 PyObject
* s
= this->readline();
1032 wxPyBeginBlockThreads();
1034 wxPyEndBlockThreads();
1037 wxPyBeginBlockThreads();
1038 PyList_Append(pylist
, s
);
1039 i
+= PyString_Size(s
);
1040 wxPyEndBlockThreads();
1044 wxStreamError err
= m_wxis
->GetLastError();
1045 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1046 wxPyBeginBlockThreads();
1048 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1049 wxPyEndBlockThreads();
1057 void wxPyInputStream::seek(int offset
, int whence
) {
1059 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1062 int wxPyInputStream::tell(){
1064 return m_wxis
->TellI();
1071 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1072 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1076 wxPyCBInputStream::~wxPyCBInputStream() {
1077 if (m_block
) wxPyBeginBlockThreads();
1081 if (m_block
) wxPyEndBlockThreads();
1085 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1086 if (block
) wxPyBeginBlockThreads();
1088 PyObject
* read
= getMethod(py
, "read");
1089 PyObject
* seek
= getMethod(py
, "seek");
1090 PyObject
* tell
= getMethod(py
, "tell");
1093 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1097 if (block
) wxPyEndBlockThreads();
1101 if (block
) wxPyEndBlockThreads();
1102 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1106 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1107 return wxPyCBInputStream::create(py
, block
);
1110 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1111 if (!PyObject_HasAttrString(py
, name
))
1113 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1114 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1122 size_t wxPyCBInputStream::GetSize() const {
1123 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1124 if (m_seek
&& m_tell
) {
1125 off_t temp
= self
->OnSysTell();
1126 off_t ret
= self
->OnSysSeek(0, wxFromEnd
);
1127 self
->OnSysSeek(temp
, wxFromStart
);
1135 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1139 wxPyBeginBlockThreads();
1140 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1141 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1145 if ((result
!= NULL
) && PyString_Check(result
)) {
1146 o
= PyString_Size(result
);
1148 m_lasterror
= wxSTREAM_EOF
;
1151 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1156 m_lasterror
= wxSTREAM_READ_ERROR
;
1157 wxPyEndBlockThreads();
1161 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1162 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1166 off_t
wxPyCBInputStream::OnSysSeek(off_t off
, wxSeekMode mode
) {
1167 wxPyBeginBlockThreads();
1169 // off_t is a 64-bit value...
1170 PyObject
* arglist
= Py_BuildValue("(Li)", off
, mode
);
1172 PyObject
* arglist
= Py_BuildValue("(ii)", off
, mode
);
1174 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1177 wxPyEndBlockThreads();
1182 off_t
wxPyCBInputStream::OnSysTell() const {
1183 wxPyBeginBlockThreads();
1184 PyObject
* arglist
= Py_BuildValue("()");
1185 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1188 if (result
!= NULL
) {
1190 if (PyLong_Check(result
))
1191 o
= PyLong_AsLongLong(result
);
1194 o
= PyInt_AsLong(result
);
1198 wxPyEndBlockThreads();
1202 //----------------------------------------------------------------------
1204 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1206 wxPyCallback::wxPyCallback(PyObject
* func
) {
1211 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1212 m_func
= other
.m_func
;
1216 wxPyCallback::~wxPyCallback() {
1217 wxPyBeginBlockThreads();
1219 wxPyEndBlockThreads();
1224 // This function is used for all events destined for Python event handlers.
1225 void wxPyCallback::EventThunker(wxEvent
& event
) {
1226 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1227 PyObject
* func
= cb
->m_func
;
1233 wxPyBeginBlockThreads();
1234 wxString className
= event
.GetClassInfo()->GetClassName();
1236 if (className
== wxT("wxPyEvent"))
1237 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1238 else if (className
== wxT("wxPyCommandEvent"))
1239 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1241 arg
= wxPyConstructObject((void*)&event
, className
);
1244 tuple
= PyTuple_New(1);
1245 PyTuple_SET_ITEM(tuple
, 0, arg
);
1246 result
= PyEval_CallObject(func
, tuple
);
1250 PyErr_Clear(); // Just in case...
1254 wxPyEndBlockThreads();
1258 //----------------------------------------------------------------------
1260 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1262 m_self
= other
.m_self
;
1263 m_class
= other
.m_class
;
1271 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1282 #if PYTHON_API_VERSION >= 1011
1284 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1285 // in which the method was defined. Starting with 2.2 it returns
1286 // "class that asked for the method" which seems totally bogus to me
1287 // but apprently it fixes some obscure problem waiting to happen in
1288 // Python. Since the API was not documented Guido and the gang felt
1289 // safe in changing it. Needless to say that totally screwed up the
1290 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1291 // code to find the class where the method is actually defined...
1294 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1298 if (PyType_Check(klass
)) { // new style classes
1299 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1300 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1301 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1302 PyObject
*mro
, *res
, *base
, *dict
;
1303 /* Look in tp_dict of types in MRO */
1305 assert(PyTuple_Check(mro
));
1306 n
= PyTuple_GET_SIZE(mro
);
1307 for (i
= 0; i
< n
; i
++) {
1308 base
= PyTuple_GET_ITEM(mro
, i
);
1309 if (PyClass_Check(base
))
1310 dict
= ((PyClassObject
*)base
)->cl_dict
;
1312 assert(PyType_Check(base
));
1313 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1315 assert(dict
&& PyDict_Check(dict
));
1316 res
= PyDict_GetItem(dict
, name
);
1323 else if (PyClass_Check(klass
)) { // old style classes
1324 // This code is borrowed/adapted from class_lookup in classobject.c
1325 PyClassObject
* cp
= (PyClassObject
*)klass
;
1326 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1327 if (value
!= NULL
) {
1328 return (PyObject
*)cp
;
1330 n
= PyTuple_Size(cp
->cl_bases
);
1331 for (i
= 0; i
< n
; i
++) {
1332 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1333 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1345 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1347 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1349 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1351 #else // 2.2 and after, the hard way...
1353 PyObject
* nameo
= PyString_FromString(name
);
1354 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1362 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1363 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1364 self
->m_lastFound
= NULL
;
1366 // If the object (m_self) has an attibute of the given name...
1367 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1368 PyObject
*method
, *klass
;
1369 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1371 // ...and if that attribute is a method, and if that method's class is
1372 // not from a base class...
1373 if (PyMethod_Check(method
) &&
1374 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1375 ((klass
== m_class
) || PyClass_IsSubclass(klass
, m_class
))) {
1377 // ...then we'll save a pointer to the method so callCallback can call it.
1378 self
->m_lastFound
= method
;
1384 return m_lastFound
!= NULL
;
1388 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1392 result
= callCallbackObj(argTuple
);
1393 if (result
) { // Assumes an integer return type...
1394 retval
= PyInt_AsLong(result
);
1396 PyErr_Clear(); // forget about it if it's not...
1401 // Invoke the Python callable object, returning the raw PyObject return
1402 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1403 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1406 // Save a copy of the pointer in case the callback generates another
1407 // callback. In that case m_lastFound will have a different value when
1408 // it gets back here...
1409 PyObject
* method
= m_lastFound
;
1411 result
= PyEval_CallObject(method
, argTuple
);
1412 Py_DECREF(argTuple
);
1421 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1422 cbh
.setSelf(self
, klass
, incref
);
1425 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1426 return cbh
.findCallback(name
);
1429 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1430 return cbh
.callCallback(argTuple
);
1433 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1434 return cbh
.callCallbackObj(argTuple
);
1438 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1439 if (cbh
->m_incRef
) {
1440 wxPyBeginBlockThreads();
1441 Py_XDECREF(cbh
->m_self
);
1442 Py_XDECREF(cbh
->m_class
);
1443 wxPyEndBlockThreads();
1447 //---------------------------------------------------------------------------
1448 //---------------------------------------------------------------------------
1449 // These event classes can be derived from in Python and passed through the event
1450 // system without losing anything. They do this by keeping a reference to
1451 // themselves and some special case handling in wxPyCallback::EventThunker.
1454 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1455 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1456 //Py_INCREF(m_self); // circular loops...
1460 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1461 wxPyBeginBlockThreads();
1464 wxPyEndBlockThreads();
1467 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1468 wxPyBeginBlockThreads();
1476 wxPyEndBlockThreads();
1479 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1485 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1486 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1489 wxPyEvent::wxPyEvent(int id
)
1494 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1497 SetSelf(evt
.m_self
, TRUE
);
1501 wxPyEvent::~wxPyEvent() {
1505 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1506 : wxCommandEvent(commandType
, id
) {
1510 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1511 : wxCommandEvent(evt
)
1513 SetSelf(evt
.m_self
, TRUE
);
1517 wxPyCommandEvent::~wxPyCommandEvent() {
1523 //---------------------------------------------------------------------------
1524 //---------------------------------------------------------------------------
1527 wxPyTimer::wxPyTimer(PyObject
* callback
) {
1532 wxPyTimer::~wxPyTimer() {
1533 wxPyBeginBlockThreads();
1535 wxPyEndBlockThreads();
1538 void wxPyTimer::Notify() {
1539 if (!func
|| func
== Py_None
) {
1543 wxPyBeginBlockThreads();
1546 PyObject
* args
= Py_BuildValue("()");
1548 result
= PyEval_CallObject(func
, args
);
1557 wxPyEndBlockThreads();
1563 //---------------------------------------------------------------------------
1564 //---------------------------------------------------------------------------
1565 // Convert a wxList to a Python List
1567 PyObject
* wxPy_ConvertList(wxListBase
* listbase
, const char* className
) {
1568 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1572 wxNode
* node
= list
->GetFirst();
1574 wxPyBeginBlockThreads();
1575 pyList
= PyList_New(0);
1577 wxObj
= node
->GetData();
1578 pyObj
= wxPyMake_wxObject(wxObj
); //wxPyConstructObject(wxObj, className);
1579 PyList_Append(pyList
, pyObj
);
1580 node
= node
->GetNext();
1582 wxPyEndBlockThreads();
1586 //----------------------------------------------------------------------
1588 long wxPyGetWinHandle(wxWindow
* win
) {
1590 return (long)win
->GetHandle();
1593 // Find and return the actual X-Window.
1595 if (win
->m_wxwindow
) {
1597 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win
->m_wxwindow
)->bin_window
);
1599 GdkWindowPrivate
* bwin
= (GdkWindowPrivate
*)GTK_PIZZA(win
->m_wxwindow
)->bin_window
;
1601 return (long)bwin
->xwindow
;
1609 //----------------------------------------------------------------------
1610 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1611 // included in every file over and over again...
1613 #if PYTHON_API_VERSION >= 1009
1614 static char* wxStringErrorMsg
= "String or Unicode type required";
1616 static char* wxStringErrorMsg
= "String type required";
1620 wxString
* wxString_in_helper(PyObject
* source
) {
1622 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1623 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1624 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1628 if (PyUnicode_Check(source
)) {
1629 target
= new wxString();
1630 size_t len
= PyUnicode_GET_SIZE(source
);
1632 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
->GetWriteBuf(len
), len
);
1633 target
->UngetWriteBuf();
1636 // It is a string, get pointers to it and transform to unicode
1637 char* tmpPtr
; int tmpSize
;
1638 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1639 target
= new wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1642 char* tmpPtr
; int tmpSize
;
1643 if (PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
) == -1) {
1644 PyErr_SetString(PyExc_TypeError
, "Unable to convert string");
1647 target
= new wxString(tmpPtr
, tmpSize
);
1648 #endif // wxUSE_UNICODE
1650 #else // No Python unicode API (1.5.2)
1651 if (!PyString_Check(source
)) {
1652 PyErr_SetString(PyExc_TypeError
, wxStringErrorMsg
);
1655 target
= new wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1661 // Similar to above except doesn't use "new" and doesn't set an exception
1662 wxString
Py2wxString(PyObject
* source
)
1665 bool doDecRef
= FALSE
;
1667 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1668 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1669 // Convert to String if not one already... (TODO: Unicode too?)
1670 source
= PyObject_Str(source
);
1675 if (PyUnicode_Check(source
)) {
1676 size_t len
= PyUnicode_GET_SIZE(source
);
1678 PyUnicode_AsWideChar((PyUnicodeObject
*)source
, target
.GetWriteBuf(len
), len
);
1679 target
.UngetWriteBuf();
1682 // It is a string, get pointers to it and transform to unicode
1683 char* tmpPtr
; int tmpSize
;
1684 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1685 target
= wxString(tmpPtr
, *wxConvCurrent
, tmpSize
);
1688 char* tmpPtr
; int tmpSize
;
1689 PyString_AsStringAndSize(source
, &tmpPtr
, &tmpSize
);
1690 target
= wxString(tmpPtr
, tmpSize
);
1691 #endif // wxUSE_UNICODE
1693 #else // No Python unicode API (1.5.2)
1694 if (!PyString_Check(source
)) {
1695 // Convert to String if not one already...
1696 source
= PyObject_Str(source
);
1699 target
= wxString(PyString_AS_STRING(source
), PyString_GET_SIZE(source
));
1708 // Make either a Python String or Unicode object, depending on build mode
1709 PyObject
* wx2PyString(const wxString
& src
)
1713 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1715 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1721 //----------------------------------------------------------------------
1724 byte
* byte_LIST_helper(PyObject
* source
) {
1725 if (!PyList_Check(source
)) {
1726 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1729 int count
= PyList_Size(source
);
1730 byte
* temp
= new byte
[count
];
1732 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1735 for (int x
=0; x
<count
; x
++) {
1736 PyObject
* o
= PyList_GetItem(source
, x
);
1737 if (! PyInt_Check(o
)) {
1738 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1741 temp
[x
] = (byte
)PyInt_AsLong(o
);
1747 int* int_LIST_helper(PyObject
* source
) {
1748 if (!PyList_Check(source
)) {
1749 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1752 int count
= PyList_Size(source
);
1753 int* temp
= new int[count
];
1755 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1758 for (int x
=0; x
<count
; x
++) {
1759 PyObject
* o
= PyList_GetItem(source
, x
);
1760 if (! PyInt_Check(o
)) {
1761 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1764 temp
[x
] = PyInt_AsLong(o
);
1770 long* long_LIST_helper(PyObject
* source
) {
1771 if (!PyList_Check(source
)) {
1772 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1775 int count
= PyList_Size(source
);
1776 long* temp
= new long[count
];
1778 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1781 for (int x
=0; x
<count
; x
++) {
1782 PyObject
* o
= PyList_GetItem(source
, x
);
1783 if (! PyInt_Check(o
)) {
1784 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1787 temp
[x
] = PyInt_AsLong(o
);
1793 char** string_LIST_helper(PyObject
* source
) {
1794 if (!PyList_Check(source
)) {
1795 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1798 int count
= PyList_Size(source
);
1799 char** temp
= new char*[count
];
1801 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1804 for (int x
=0; x
<count
; x
++) {
1805 PyObject
* o
= PyList_GetItem(source
, x
);
1806 if (! PyString_Check(o
)) {
1807 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1810 temp
[x
] = PyString_AsString(o
);
1815 //--------------------------------
1816 // Part of patch from Tim Hochberg
1817 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
1818 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
1819 point
->x
= PyInt_AS_LONG(o1
);
1820 point
->y
= PyInt_AS_LONG(o2
);
1823 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
1824 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
1825 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
1828 if (PyInstance_Check(o1
) || PyInstance_Check(o2
)) {
1829 // Disallow instances because they can cause havok
1832 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
1833 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1834 point
->x
= PyInt_AsLong(o1
);
1835 point
->y
= PyInt_AsLong(o2
);
1842 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
1843 // Putting all of the declarations here allows
1844 // us to put the error handling all in one place.
1847 PyObject
*o
, *o1
, *o2
;
1848 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
1850 if (!PySequence_Check(source
)) {
1854 // The length of the sequence is returned in count.
1855 *count
= PySequence_Length(source
);
1860 temp
= new wxPoint
[*count
];
1862 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1865 for (x
=0; x
<*count
; x
++) {
1866 // Get an item: try fast way first.
1868 o
= PySequence_Fast_GET_ITEM(source
, x
);
1871 o
= PySequence_GetItem(source
, x
);
1877 // Convert o to wxPoint.
1878 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
1879 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
1880 o1
= PySequence_Fast_GET_ITEM(o
, 0);
1881 o2
= PySequence_Fast_GET_ITEM(o
, 1);
1882 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1886 else if (PyInstance_Check(o
)) {
1888 if (SWIG_GetPtrObj(o
, (void **)&pt
, "_wxPoint_p")) {
1893 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
1894 o1
= PySequence_GetItem(o
, 0);
1895 o2
= PySequence_GetItem(o
, 1);
1896 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
1920 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
1924 //------------------------------
1927 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
1928 if (!PyList_Check(source
)) {
1929 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1932 int count
= PyList_Size(source
);
1933 wxBitmap
** temp
= new wxBitmap
*[count
];
1935 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1938 for (int x
=0; x
<count
; x
++) {
1939 PyObject
* o
= PyList_GetItem(source
, x
);
1940 if (PyInstance_Check(o
)) {
1942 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxBitmap_p")) {
1943 PyErr_SetString(PyExc_TypeError
,"Expected _wxBitmap_p.");
1949 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
1958 wxString
* wxString_LIST_helper(PyObject
* source
) {
1959 if (!PyList_Check(source
)) {
1960 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1963 int count
= PyList_Size(source
);
1964 wxString
* temp
= new wxString
[count
];
1966 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1969 for (int x
=0; x
<count
; x
++) {
1970 PyObject
* o
= PyList_GetItem(source
, x
);
1971 #if PYTHON_API_VERSION >= 1009
1972 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
1973 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
1977 if (! PyString_Check(o
)) {
1978 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
1983 wxString
* pStr
= wxString_in_helper(o
);
1991 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
1992 if (!PyList_Check(source
)) {
1993 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1996 int count
= PyList_Size(source
);
1997 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
1999 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2002 for (int x
=0; x
<count
; x
++) {
2003 PyObject
* o
= PyList_GetItem(source
, x
);
2004 if (PyInstance_Check(o
)) {
2005 wxAcceleratorEntry
* ae
;
2006 if (SWIG_GetPtrObj(o
, (void **) &ae
,"_wxAcceleratorEntry_p")) {
2007 PyErr_SetString(PyExc_TypeError
,"Expected _wxAcceleratorEntry_p.");
2012 else if (PyTuple_Check(o
)) {
2013 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2014 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2015 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2016 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2019 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2027 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2028 if (!PyList_Check(source
)) {
2029 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2032 int count
= PyList_Size(source
);
2033 wxPen
** temp
= new wxPen
*[count
];
2035 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2038 for (int x
=0; x
<count
; x
++) {
2039 PyObject
* o
= PyList_GetItem(source
, x
);
2040 if (PyInstance_Check(o
)) {
2042 if (SWIG_GetPtrObj(o
, (void **) &pt
,"_wxPen_p")) {
2044 PyErr_SetString(PyExc_TypeError
,"Expected _wxPen_p.");
2051 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2059 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2060 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2063 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2067 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2068 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2071 o1
= PySequence_GetItem(source
, 0);
2072 o2
= PySequence_GetItem(source
, 1);
2075 *i1
= PyInt_AsLong(o1
);
2076 *i2
= PyInt_AsLong(o2
);
2086 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2087 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2088 PyObject
*o1
, *o2
, *o3
, *o4
;
2090 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2094 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2095 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2096 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2097 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2100 o1
= PySequence_GetItem(source
, 0);
2101 o2
= PySequence_GetItem(source
, 1);
2102 o3
= PySequence_GetItem(source
, 2);
2103 o4
= PySequence_GetItem(source
, 3);
2106 *i1
= PyInt_AsLong(o1
);
2107 *i2
= PyInt_AsLong(o2
);
2108 *i3
= PyInt_AsLong(o3
);
2109 *i4
= PyInt_AsLong(o4
);
2121 //----------------------------------------------------------------------
2123 bool wxSize_helper(PyObject
* source
, wxSize
** obj
) {
2125 // If source is an object instance then it may already be the right type
2126 if (PyInstance_Check(source
)) {
2128 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxSize_p"))
2133 // otherwise a 2-tuple of integers is expected
2134 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2135 PyObject
* o1
= PySequence_GetItem(source
, 0);
2136 PyObject
* o2
= PySequence_GetItem(source
, 1);
2137 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2142 **obj
= wxSize(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2149 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxSize object.");
2154 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
) {
2156 // If source is an object instance then it may already be the right type
2157 if (PyInstance_Check(source
)) {
2159 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint_p"))
2164 // otherwise a length-2 sequence of integers is expected
2165 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2166 PyObject
* o1
= PySequence_GetItem(source
, 0);
2167 PyObject
* o2
= PySequence_GetItem(source
, 1);
2168 // This should really check for integers, not numbers -- but that would break code.
2169 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2174 **obj
= wxPoint(PyInt_AsLong(o1
), PyInt_AsLong(o2
));
2180 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of integers or a wxPoint object.");
2186 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2188 // If source is an object instance then it may already be the right type
2189 if (PyInstance_Check(source
)) {
2191 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRealPoint_p"))
2196 // otherwise a 2-tuple of floats is expected
2197 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2198 PyObject
* o1
= PySequence_GetItem(source
, 0);
2199 PyObject
* o2
= PySequence_GetItem(source
, 1);
2200 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2205 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2212 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2219 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2221 // If source is an object instance then it may already be the right type
2222 if (PyInstance_Check(source
)) {
2224 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxRect_p"))
2229 // otherwise a 4-tuple of integers is expected
2230 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2231 PyObject
* o1
= PySequence_GetItem(source
, 0);
2232 PyObject
* o2
= PySequence_GetItem(source
, 1);
2233 PyObject
* o3
= PySequence_GetItem(source
, 2);
2234 PyObject
* o4
= PySequence_GetItem(source
, 3);
2235 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2236 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2243 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2244 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2253 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2259 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2261 // If source is an object instance then it may already be the right type
2262 if (PyInstance_Check(source
)) {
2264 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxColour_p"))
2269 // otherwise check for a string
2270 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2271 wxString spec
= Py2wxString(source
);
2272 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2273 long red
, green
, blue
;
2274 red
= green
= blue
= 0;
2275 spec
.Mid(1,2).ToLong(&red
, 16);
2276 spec
.Mid(3,2).ToLong(&green
, 16);
2277 spec
.Mid(5,2).ToLong(&blue
, 16);
2279 **obj
= wxColour(red
, green
, blue
);
2282 else { // it's a colour name
2283 **obj
= wxColour(spec
);
2287 // last chance: 3-tuple of integers is expected
2288 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2289 PyObject
* o1
= PySequence_GetItem(source
, 0);
2290 PyObject
* o2
= PySequence_GetItem(source
, 1);
2291 PyObject
* o3
= PySequence_GetItem(source
, 2);
2292 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2298 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2306 PyErr_SetString(PyExc_TypeError
,
2307 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2313 bool wxPoint2DDouble_helper(PyObject
* source
, wxPoint2DDouble
** obj
) {
2314 // If source is an object instance then it may already be the right type
2315 if (PyInstance_Check(source
)) {
2316 wxPoint2DDouble
* ptr
;
2317 if (SWIG_GetPtrObj(source
, (void **)&ptr
, "_wxPoint2DDouble_p"))
2322 // otherwise a length-2 sequence of floats is expected
2323 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2324 PyObject
* o1
= PySequence_GetItem(source
, 0);
2325 PyObject
* o2
= PySequence_GetItem(source
, 1);
2326 // This should really check for integers, not numbers -- but that would break code.
2327 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2332 **obj
= wxPoint2DDouble(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2338 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2344 //----------------------------------------------------------------------
2346 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2348 PyObject
* list
= PyList_New(0);
2349 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2351 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2353 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2355 PyList_Append(list
, str
);
2362 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2364 PyObject
* list
= PyList_New(0);
2365 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2366 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2367 PyList_Append(list
, number
);
2374 //----------------------------------------------------------------------
2375 //----------------------------------------------------------------------