]> git.saurik.com Git - wxWidgets.git/blob - wxPython/src/helpers.cpp
Allow compiling when _WIN32_IE < 0x300
[wxWidgets.git] / wxPython / src / helpers.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: helpers.cpp
3 // Purpose: Helper functions/classes for the wxPython extension module
4 //
5 // Author: Robin Dunn
6 //
7 // Created: 7/1/97
8 // RCS-ID: $Id$
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13
14 #undef DEBUG
15 #include <Python.h>
16 #include "helpers.h"
17 #include "pyistream.h"
18
19 #ifdef __WXMSW__
20 #include <wx/msw/private.h>
21 #include <wx/msw/winundef.h>
22 #include <wx/msw/msvcrt.h>
23 #endif
24
25 #ifdef __WXGTK__
26 #include <gtk/gtk.h>
27 #include <gdk/gdkprivate.h>
28 #include <wx/gtk/win_gtk.h>
29 #endif
30
31 //----------------------------------------------------------------------
32
33 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
34 #error Python must support Unicode to use wxWindows Unicode
35 #endif
36
37 //----------------------------------------------------------------------
38
39 #ifdef __WXGTK__
40 int WXDLLEXPORT wxEntryStart( int& argc, char** argv );
41 #else
42 int WXDLLEXPORT wxEntryStart( int argc, char** argv );
43 #endif
44 int WXDLLEXPORT wxEntryInitGui();
45 void WXDLLEXPORT wxEntryCleanup();
46
47 wxPyApp* wxPythonApp = NULL; // Global instance of application object
48 bool wxPyDoCleanup = FALSE;
49
50
51 #ifdef WXP_WITH_THREAD
52 struct wxPyThreadState {
53 unsigned long tid;
54 PyThreadState* tstate;
55
56 wxPyThreadState(unsigned long _tid=0, PyThreadState* _tstate=NULL)
57 : tid(_tid), tstate(_tstate) {}
58 };
59
60 #include <wx/dynarray.h>
61 WX_DECLARE_OBJARRAY(wxPyThreadState, wxPyThreadStateArray);
62 #include <wx/arrimpl.cpp>
63 WX_DEFINE_OBJARRAY(wxPyThreadStateArray);
64
65 wxPyThreadStateArray* wxPyTStates = NULL;
66 wxMutex* wxPyTMutex = NULL;
67 #endif
68
69
70 #ifdef __WXMSW__ // If building for win32...
71 //----------------------------------------------------------------------
72 // This gets run when the DLL is loaded. We just need to save a handle.
73 //----------------------------------------------------------------------
74
75 BOOL WINAPI DllMain(
76 HINSTANCE hinstDLL, // handle to DLL module
77 DWORD fdwReason, // reason for calling function
78 LPVOID lpvReserved // reserved
79 )
80 {
81 // If wxPython is embedded in another wxWindows app then
82 // the inatance has already been set.
83 if (! wxGetInstance())
84 wxSetInstance(hinstDLL);
85 return TRUE;
86 }
87 #endif
88
89 //----------------------------------------------------------------------
90 // Classes for implementing the wxp main application shell.
91 //----------------------------------------------------------------------
92
93
94 wxPyApp::wxPyApp() {
95 SetUseBestVisual(TRUE);
96 }
97
98 wxPyApp::~wxPyApp() {
99 }
100
101
102 // This one isn't acutally called... See __wxStart()
103 bool wxPyApp::OnInit() {
104 return FALSE;
105 }
106
107
108 int wxPyApp::MainLoop() {
109 int retval = 0;
110
111 DeletePendingObjects();
112 bool initialized = wxTopLevelWindows.GetCount() != 0;
113 #ifdef __WXGTK__
114 m_initialized = initialized;
115 #endif
116
117 if (initialized) {
118 retval = wxApp::MainLoop();
119 OnExit();
120 }
121 return retval;
122 }
123
124
125
126 //---------------------------------------------------------------------
127 //----------------------------------------------------------------------
128
129
130 static char* wxPyCopyCString(const wxChar* src)
131 {
132 wxWX2MBbuf buff = (wxWX2MBbuf)wxConvCurrent->cWX2MB(src);
133 size_t len = strlen(buff);
134 char* dest = new char[len+1];
135 strcpy(dest, buff);
136 return dest;
137 }
138
139 #if wxUSE_UNICODE
140 static char* wxPyCopyCString(const char* src) // we need a char version too
141 {
142 size_t len = strlen(src);
143 char* dest = new char[len+1];
144 strcpy(dest, src);
145 return dest;
146 }
147 #endif
148
149 static wxChar* wxPyCopyWString(const char *src)
150 {
151 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
152 wxString str(src, *wxConvCurrent);
153 return copystring(str);
154 }
155
156 #if wxUSE_UNICODE
157 static wxChar* wxPyCopyWString(const wxChar *src)
158 {
159 return copystring(src);
160 }
161 #endif
162
163
164 //----------------------------------------------------------------------
165
166 // This is where we pick up the first part of the wxEntry functionality...
167 // The rest is in __wxStart and __wxCleanup. This function is called when
168 // wxcmodule is imported. (Before there is a wxApp object.)
169 void __wxPreStart()
170 {
171
172 #ifdef __WXMSW__
173 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
174 #endif
175
176 #ifdef WXP_WITH_THREAD
177 PyEval_InitThreads();
178 wxPyTStates = new wxPyThreadStateArray;
179 wxPyTMutex = new wxMutex;
180 #endif
181
182 wxApp::CheckBuildOptions(wxBuildOptions());
183
184 // Bail out if there is already a wxApp created. This means that the
185 // toolkit has already been initialized, as in embedding wxPython in
186 // a C++ wxWindows app, so we don't need to call wxEntryStart.
187 if (wxTheApp != NULL) {
188 return;
189 }
190 wxPyDoCleanup = TRUE;
191
192 int argc = 0;
193 char** argv = NULL;
194 PyObject* sysargv = PySys_GetObject("argv");
195 if (sysargv != NULL) {
196 argc = PyList_Size(sysargv);
197 argv = new char*[argc+1];
198 int x;
199 for(x=0; x<argc; x++) {
200 PyObject *item = PyList_GetItem(sysargv, x);
201 #if wxUSE_UNICODE
202 if (PyUnicode_Check(item))
203 argv[x] = wxPyCopyCString(PyUnicode_AS_UNICODE(item));
204 else
205 #endif
206 argv[x] = wxPyCopyCString(PyString_AsString(item));
207 }
208 argv[argc] = NULL;
209 }
210
211 wxEntryStart(argc, argv);
212 delete [] argv;
213 }
214
215
216
217 // Start the user application, user App's OnInit method is a parameter here
218 PyObject* __wxStart(PyObject* /* self */, PyObject* args)
219 {
220 PyObject* onInitFunc = NULL;
221 PyObject* arglist;
222 PyObject* result;
223 long bResult;
224
225 if (!PyArg_ParseTuple(args, "O", &onInitFunc))
226 return NULL;
227
228 // This is the next part of the wxEntry functionality...
229 int argc = 0;
230 wxChar** argv = NULL;
231 PyObject* sysargv = PySys_GetObject("argv");
232 if (sysargv != NULL) {
233 argc = PyList_Size(sysargv);
234 argv = new wxChar*[argc+1];
235 int x;
236 for(x=0; x<argc; x++) {
237 PyObject *pyArg = PyList_GetItem(sysargv, x);
238 #if wxUSE_UNICODE
239 if (PyUnicode_Check(pyArg))
240 argv[x] = wxPyCopyWString(PyUnicode_AS_UNICODE(pyArg));
241 else
242 #endif
243 argv[x] = wxPyCopyWString(PyString_AsString(pyArg));
244 }
245 argv[argc] = NULL;
246 }
247
248 wxPythonApp->argc = argc;
249 wxPythonApp->argv = argv;
250
251 wxEntryInitGui();
252
253 // Call the Python App's OnInit function
254 arglist = PyTuple_New(0);
255 result = PyEval_CallObject(onInitFunc, arglist);
256 if (!result) { // an exception was raised.
257 return NULL;
258 }
259
260 if (! PyInt_Check(result)) {
261 PyErr_SetString(PyExc_TypeError, "OnInit should return a boolean value");
262 return NULL;
263 }
264 bResult = PyInt_AS_LONG(result);
265 if (! bResult) {
266 PyErr_SetString(PyExc_SystemExit, "OnInit returned FALSE, exiting...");
267 return NULL;
268 }
269
270 #ifdef __WXGTK__
271 wxTheApp->m_initialized = (wxTopLevelWindows.GetCount() > 0);
272 #endif
273
274 Py_INCREF(Py_None);
275 return Py_None;
276 }
277
278
279 void __wxCleanup() {
280 if (wxPyDoCleanup)
281 wxEntryCleanup();
282 #ifdef WXP_WITH_THREAD
283 delete wxPyTMutex;
284 wxPyTMutex = NULL;
285 wxPyTStates->Empty();
286 delete wxPyTStates;
287 wxPyTStates = NULL;
288 #endif
289 }
290
291
292
293 static PyObject* wxPython_dict = NULL;
294 static PyObject* wxPyPtrTypeMap = NULL;
295
296
297 PyObject* __wxSetDictionary(PyObject* /* self */, PyObject* args)
298 {
299
300 if (!PyArg_ParseTuple(args, "O", &wxPython_dict))
301 return NULL;
302
303 if (!PyDict_Check(wxPython_dict)) {
304 PyErr_SetString(PyExc_TypeError, "_wxSetDictionary must have dictionary object!");
305 return NULL;
306 }
307
308 if (! wxPyPtrTypeMap)
309 wxPyPtrTypeMap = PyDict_New();
310 PyDict_SetItemString(wxPython_dict, "__wxPyPtrTypeMap", wxPyPtrTypeMap);
311
312
313 #ifdef __WXMOTIF__
314 #define wxPlatform "__WXMOTIF__"
315 #endif
316 #ifdef __WXX11__
317 #define wxPlatform "__WXX11__"
318 #endif
319 #ifdef __WXGTK__
320 #define wxPlatform "__WXGTK__"
321 #endif
322 #if defined(__WIN32__) || defined(__WXMSW__)
323 #define wxPlatform "__WXMSW__"
324 #endif
325 #ifdef __WXMAC__
326 #define wxPlatform "__WXMAC__"
327 #endif
328
329 PyDict_SetItemString(wxPython_dict, "wxPlatform", PyString_FromString(wxPlatform));
330 PyDict_SetItemString(wxPython_dict, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE));
331
332 Py_INCREF(Py_None);
333 return Py_None;
334 }
335
336 //---------------------------------------------------------------------------
337
338 void wxPyClientData_dtor(wxPyClientData* self) {
339 wxPyBeginBlockThreads();
340 Py_DECREF(self->m_obj);
341 wxPyEndBlockThreads();
342 }
343
344 void wxPyUserData_dtor(wxPyUserData* self) {
345 wxPyBeginBlockThreads();
346 Py_DECREF(self->m_obj);
347 wxPyEndBlockThreads();
348 }
349
350
351 // This is called when an OOR controled object is being destroyed. Although
352 // the C++ object is going away there is no way to force the Python object
353 // (and all references to it) to die too. This causes problems (crashes) in
354 // wxPython when a python shadow object attempts to call a C++ method using
355 // the now bogus pointer... So to try and prevent this we'll do a little black
356 // magic and change the class of the python instance to a class that will
357 // raise an exception for any attempt to call methods with it. See
358 // _wxPyDeadObject in _extras.py for the implementation of this class.
359 void wxPyOORClientData_dtor(wxPyOORClientData* self) {
360
361 static PyObject* deadObjectClass = NULL;
362
363 wxPyBeginBlockThreads();
364 if (deadObjectClass == NULL) {
365 deadObjectClass = PyDict_GetItemString(wxPython_dict, "_wxPyDeadObject");
366 wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
367 Py_INCREF(deadObjectClass);
368 }
369
370 // Clear the instance's dictionary, put the name of the old class into the
371 // instance, and then reset the class to be the dead class.
372 if (self->m_obj->ob_refcnt > 1) { // but only if there is more than one reference
373 wxASSERT_MSG(PyInstance_Check(self->m_obj), wxT("m_obj not an instance!?!?!"));
374 PyInstanceObject* inst = (PyInstanceObject*)self->m_obj;
375 PyDict_Clear(inst->in_dict);
376 PyDict_SetItemString(inst->in_dict, "_name", inst->in_class->cl_name);
377 inst->in_class = (PyClassObject*)deadObjectClass;
378 Py_INCREF(deadObjectClass);
379 }
380 wxPyEndBlockThreads();
381 }
382
383 //---------------------------------------------------------------------------
384 // Stuff used by OOR to find the right wxPython class type to return and to
385 // build it.
386
387
388 // The pointer type map is used when the "pointer" type name generated by SWIG
389 // is not the same as the shadow class name, for example wxPyTreeCtrl
390 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
391 // so we'll just make it a Python dictionary in the wx module's namespace.
392 // (See __wxSetDictionary)
393 void wxPyPtrTypeMap_Add(const char* commonName, const char* ptrName) {
394 if (! wxPyPtrTypeMap)
395 wxPyPtrTypeMap = PyDict_New();
396 PyDict_SetItemString(wxPyPtrTypeMap,
397 (char*)commonName,
398 PyString_FromString((char*)ptrName));
399 }
400
401
402
403 PyObject* wxPyClassExists(const wxString& className) {
404
405 if (!className)
406 return NULL;
407
408 char buff[64]; // should always be big enough...
409
410 sprintf(buff, "%sPtr", className.mbc_str());
411 PyObject* classobj = PyDict_GetItemString(wxPython_dict, buff);
412
413 return classobj; // returns NULL if not found
414 }
415
416
417 PyObject* wxPyMake_wxObject(wxObject* source, bool checkEvtHandler) {
418 PyObject* target = NULL;
419 bool isEvtHandler = FALSE;
420
421 if (source) {
422 // If it's derived from wxEvtHandler then there may
423 // already be a pointer to a Python object that we can use
424 // in the OOR data.
425 if (checkEvtHandler && wxIsKindOf(source, wxEvtHandler)) {
426 isEvtHandler = TRUE;
427 wxEvtHandler* eh = (wxEvtHandler*)source;
428 wxPyOORClientData* data = (wxPyOORClientData*)eh->GetClientObject();
429 if (data) {
430 target = data->m_obj;
431 Py_INCREF(target);
432 }
433 }
434
435 if (! target) {
436 // Otherwise make it the old fashioned way by making a
437 // new shadow object and putting this pointer in it.
438 wxClassInfo* info = source->GetClassInfo();
439 wxChar* name = (wxChar*)info->GetClassName();
440 PyObject* klass = wxPyClassExists(name);
441 while (info && !klass) {
442 name = (wxChar*)info->GetBaseClassName1();
443 info = wxClassInfo::FindClass(name);
444 klass = wxPyClassExists(name);
445 }
446 if (info) {
447 target = wxPyConstructObject(source, name, klass, FALSE);
448 if (target && isEvtHandler)
449 ((wxEvtHandler*)source)->SetClientObject(new wxPyOORClientData(target));
450 } else {
451 wxString msg(wxT("wxPython class not found for "));
452 msg += source->GetClassInfo()->GetClassName();
453 PyErr_SetString(PyExc_NameError, msg.mbc_str());
454 target = NULL;
455 }
456 }
457 } else { // source was NULL so return None.
458 Py_INCREF(Py_None); target = Py_None;
459 }
460 return target;
461 }
462
463
464 PyObject* wxPyMake_wxSizer(wxSizer* source) {
465 PyObject* target = NULL;
466
467 if (source && wxIsKindOf(source, wxSizer)) {
468 // If it's derived from wxSizer then there may
469 // already be a pointer to a Python object that we can use
470 // in the OOR data.
471 wxSizer* sz = (wxSizer*)source;
472 wxPyOORClientData* data = (wxPyOORClientData*)sz->GetClientObject();
473 if (data) {
474 target = data->m_obj;
475 Py_INCREF(target);
476 }
477 }
478 if (! target) {
479 target = wxPyMake_wxObject(source, FALSE);
480 if (target != Py_None)
481 ((wxSizer*)source)->SetClientObject(new wxPyOORClientData(target));
482 }
483 return target;
484 }
485
486
487
488 //---------------------------------------------------------------------------
489
490 PyObject* wxPyConstructObject(void* ptr,
491 const wxString& className,
492 PyObject* klass,
493 int setThisOwn) {
494
495 PyObject* obj;
496 PyObject* arg;
497 PyObject* item;
498 wxString name(className);
499 char swigptr[64]; // should always be big enough...
500 char buff[64];
501
502 if ((item = PyDict_GetItemString(wxPyPtrTypeMap, (char*)(const char*)name.mbc_str())) != NULL) {
503 name = wxString(PyString_AsString(item), *wxConvCurrent);
504 }
505 sprintf(buff, "_%s_p", (const char*)name.mbc_str());
506 SWIG_MakePtr(swigptr, ptr, buff);
507
508 arg = Py_BuildValue("(s)", swigptr);
509 obj = PyInstance_New(klass, arg, NULL);
510 Py_DECREF(arg);
511
512 if (setThisOwn) {
513 PyObject* one = PyInt_FromLong(1);
514 PyObject_SetAttrString(obj, "thisown", one);
515 Py_DECREF(one);
516 }
517
518 return obj;
519 }
520
521
522 PyObject* wxPyConstructObject(void* ptr,
523 const wxString& className,
524 int setThisOwn) {
525 if (!ptr) {
526 Py_INCREF(Py_None);
527 return Py_None;
528 }
529
530 char buff[64]; // should always be big enough...
531 sprintf(buff, "%sPtr", (const char*)className.mbc_str());
532
533 wxASSERT_MSG(wxPython_dict, wxT("wxPython_dict is not set yet!!"));
534
535 PyObject* classobj = PyDict_GetItemString(wxPython_dict, buff);
536 if (! classobj) {
537 wxString msg(wxT("wxPython class not found for "));
538 msg += className;
539 PyErr_SetString(PyExc_NameError, msg.mbc_str());
540 return NULL;
541 }
542
543 return wxPyConstructObject(ptr, className, classobj, setThisOwn);
544 }
545
546
547 //---------------------------------------------------------------------------
548
549
550 #ifdef WXP_WITH_THREAD
551 inline
552 unsigned long wxPyGetCurrentThreadId() {
553 return wxThread::GetCurrentId();
554 }
555
556 static PyThreadState* gs_shutdownTState;
557 static
558 PyThreadState* wxPyGetThreadState() {
559 if (wxPyTMutex == NULL) // Python is shutting down...
560 return gs_shutdownTState;
561
562 unsigned long ctid = wxPyGetCurrentThreadId();
563 PyThreadState* tstate = NULL;
564
565 wxPyTMutex->Lock();
566 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
567 wxPyThreadState& info = wxPyTStates->Item(i);
568 if (info.tid == ctid) {
569 tstate = info.tstate;
570 break;
571 }
572 }
573 wxPyTMutex->Unlock();
574 wxASSERT_MSG(tstate, wxT("PyThreadState should not be NULL!"));
575 return tstate;
576 }
577
578 static
579 void wxPySaveThreadState(PyThreadState* tstate) {
580 if (wxPyTMutex == NULL) { // Python is shutting down, assume a single thread...
581 gs_shutdownTState = tstate;
582 return;
583 }
584 unsigned long ctid = wxPyGetCurrentThreadId();
585 wxPyTMutex->Lock();
586 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
587 wxPyThreadState& info = wxPyTStates->Item(i);
588 if (info.tid == ctid) {
589 info.tstate = tstate;
590 wxPyTMutex->Unlock();
591 return;
592 }
593 }
594 // not found, so add it...
595 wxPyTStates->Add(new wxPyThreadState(ctid, tstate));
596 wxPyTMutex->Unlock();
597 }
598
599 #endif
600
601
602 // Calls from Python to wxWindows code are wrapped in calls to these
603 // functions:
604
605 PyThreadState* wxPyBeginAllowThreads() {
606 #ifdef WXP_WITH_THREAD
607 PyThreadState* saved = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
608 wxPySaveThreadState(saved);
609 return saved;
610 #else
611 return NULL;
612 #endif
613 }
614
615 void wxPyEndAllowThreads(PyThreadState* saved) {
616 #ifdef WXP_WITH_THREAD
617 PyEval_RestoreThread(saved); // Py_END_ALLOW_THREADS;
618 #endif
619 }
620
621
622
623 // Calls from wxWindows back to Python code, or even any PyObject
624 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
625
626 void wxPyBeginBlockThreads() {
627 #ifdef WXP_WITH_THREAD
628 PyThreadState* tstate = wxPyGetThreadState();
629 PyEval_RestoreThread(tstate);
630 #endif
631 }
632
633
634 void wxPyEndBlockThreads() {
635 #ifdef WXP_WITH_THREAD
636 // Is there any need to save it again?
637 // PyThreadState* tstate =
638 PyEval_SaveThread();
639 #endif
640 }
641
642
643 //---------------------------------------------------------------------------
644 // wxPyInputStream and wxPyCBInputStream methods
645
646
647 void wxPyInputStream::close() {
648 /* do nothing for now */
649 }
650
651 void wxPyInputStream::flush() {
652 /* do nothing for now */
653 }
654
655 bool wxPyInputStream::eof() {
656 if (m_wxis)
657 return m_wxis->Eof();
658 else
659 return TRUE;
660 }
661
662 wxPyInputStream::~wxPyInputStream() {
663 /* do nothing */
664 }
665
666
667
668
669 PyObject* wxPyInputStream::read(int size) {
670 PyObject* obj = NULL;
671 wxMemoryBuffer buf;
672 const int BUFSIZE = 1024;
673
674 // check if we have a real wxInputStream to work with
675 if (!m_wxis) {
676 PyErr_SetString(PyExc_IOError, "no valid C-wxInputStream");
677 return NULL;
678 }
679
680 if (size < 0) {
681 // read until EOF
682 while (! m_wxis->Eof()) {
683 m_wxis->Read(buf.GetAppendBuf(BUFSIZE), BUFSIZE);
684 buf.UngetAppendBuf(m_wxis->LastRead());
685 }
686
687 } else { // Read only size number of characters
688 m_wxis->Read(buf.GetWriteBuf(size), size);
689 buf.UngetWriteBuf(m_wxis->LastRead());
690 }
691
692 // error check
693 if (m_wxis->LastError() == wxSTREAM_READ_ERROR) {
694 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
695 }
696 else {
697 // We use only strings for the streams, not unicode
698 obj = PyString_FromStringAndSize(buf, buf.GetDataLen());
699 }
700 return obj;
701 }
702
703
704 PyObject* wxPyInputStream::readline(int size) {
705 PyObject* obj = NULL;
706 wxMemoryBuffer buf;
707 int i;
708 char ch;
709
710 // check if we have a real wxInputStream to work with
711 if (!m_wxis) {
712 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
713 return NULL;
714 }
715
716 // read until \n or byte limit reached
717 for (i=ch=0; (ch != '\n') && (!m_wxis->Eof()) && ((size < 0) || (i < size)); i++) {
718 ch = m_wxis->GetC();
719 buf.AppendByte(ch);
720 }
721
722 // errorcheck
723 if (m_wxis->LastError() == wxSTREAM_READ_ERROR) {
724 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
725 }
726 else {
727 // We use only strings for the streams, not unicode
728 obj = PyString_FromStringAndSize((char*)buf.GetData(), buf.GetDataLen());
729 }
730 return obj;
731 }
732
733
734 PyObject* wxPyInputStream::readlines(int sizehint) {
735 PyObject* pylist;
736
737 // check if we have a real wxInputStream to work with
738 if (!m_wxis) {
739 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream below");
740 return NULL;
741 }
742
743 // init list
744 pylist = PyList_New(0);
745 if (!pylist) {
746 PyErr_NoMemory();
747 return NULL;
748 }
749
750 // read sizehint bytes or until EOF
751 int i;
752 for (i=0; (!m_wxis->Eof()) && ((sizehint < 0) || (i < sizehint));) {
753 PyObject* s = this->readline();
754 if (s == NULL) {
755 Py_DECREF(pylist);
756 return NULL;
757 }
758 PyList_Append(pylist, s);
759 i += PyString_Size(s);
760 }
761
762 // error check
763 if (m_wxis->LastError() == wxSTREAM_READ_ERROR) {
764 Py_DECREF(pylist);
765 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
766 return NULL;
767 }
768
769 return pylist;
770 }
771
772
773 void wxPyInputStream::seek(int offset, int whence) {
774 if (m_wxis)
775 m_wxis->SeekI(offset, wxSeekMode(whence));
776 }
777
778 int wxPyInputStream::tell(){
779 if (m_wxis)
780 return m_wxis->TellI();
781 else return 0;
782 }
783
784
785
786
787 wxPyCBInputStream::wxPyCBInputStream(PyObject *r, PyObject *s, PyObject *t, bool block)
788 : wxInputStream(), m_read(r), m_seek(s), m_tell(t), m_block(block)
789 {}
790
791
792 wxPyCBInputStream::~wxPyCBInputStream() {
793 if (m_block) wxPyBeginBlockThreads();
794 Py_XDECREF(m_read);
795 Py_XDECREF(m_seek);
796 Py_XDECREF(m_tell);
797 if (m_block) wxPyEndBlockThreads();
798 }
799
800
801 wxPyCBInputStream* wxPyCBInputStream::create(PyObject *py, bool block) {
802 if (block) wxPyBeginBlockThreads();
803
804 PyObject* read = getMethod(py, "read");
805 PyObject* seek = getMethod(py, "seek");
806 PyObject* tell = getMethod(py, "tell");
807
808 if (!read) {
809 PyErr_SetString(PyExc_TypeError, "Not a file-like object");
810 Py_XDECREF(read);
811 Py_XDECREF(seek);
812 Py_XDECREF(tell);
813 if (block) wxPyEndBlockThreads();
814 return NULL;
815 }
816
817 if (block) wxPyEndBlockThreads();
818 return new wxPyCBInputStream(read, seek, tell, block);
819 }
820
821 PyObject* wxPyCBInputStream::getMethod(PyObject* py, char* name) {
822 if (!PyObject_HasAttrString(py, name))
823 return NULL;
824 PyObject* o = PyObject_GetAttrString(py, name);
825 if (!PyMethod_Check(o) && !PyCFunction_Check(o)) {
826 Py_DECREF(o);
827 return NULL;
828 }
829 return o;
830 }
831
832
833 size_t wxPyCBInputStream::GetSize() const {
834 wxPyCBInputStream* self = (wxPyCBInputStream*)this; // cast off const
835 if (m_seek && m_tell) {
836 off_t temp = self->OnSysTell();
837 off_t ret = self->OnSysSeek(0, wxFromEnd);
838 self->OnSysSeek(temp, wxFromStart);
839 return ret;
840 }
841 else
842 return 0;
843 }
844
845
846 size_t wxPyCBInputStream::OnSysRead(void *buffer, size_t bufsize) {
847 if (bufsize == 0)
848 return 0;
849
850 wxPyBeginBlockThreads();
851 PyObject* arglist = Py_BuildValue("(i)", bufsize);
852 PyObject* result = PyEval_CallObject(m_read, arglist);
853 Py_DECREF(arglist);
854
855 size_t o = 0;
856 if ((result != NULL) && PyString_Check(result)) {
857 o = PyString_Size(result);
858 if (o == 0)
859 m_lasterror = wxSTREAM_EOF;
860 if (o > bufsize)
861 o = bufsize;
862 memcpy((char*)buffer, PyString_AsString(result), o); // strings only, not unicode...
863 Py_DECREF(result);
864
865 }
866 else
867 m_lasterror = wxSTREAM_READ_ERROR;
868 wxPyEndBlockThreads();
869 m_lastcount = o;
870 return o;
871 }
872
873 size_t wxPyCBInputStream::OnSysWrite(const void *buffer, size_t bufsize) {
874 m_lasterror = wxSTREAM_WRITE_ERROR;
875 return 0;
876 }
877
878 off_t wxPyCBInputStream::OnSysSeek(off_t off, wxSeekMode mode) {
879 wxPyBeginBlockThreads();
880 PyObject* arglist = Py_BuildValue("(ii)", off, mode);
881 PyObject* result = PyEval_CallObject(m_seek, arglist);
882 Py_DECREF(arglist);
883 Py_XDECREF(result);
884 wxPyEndBlockThreads();
885 return OnSysTell();
886 }
887
888 off_t wxPyCBInputStream::OnSysTell() const {
889 wxPyBeginBlockThreads();
890 PyObject* arglist = Py_BuildValue("()");
891 PyObject* result = PyEval_CallObject(m_tell, arglist);
892 Py_DECREF(arglist);
893 off_t o = 0;
894 if (result != NULL) {
895 o = PyInt_AsLong(result);
896 Py_DECREF(result);
897 };
898 wxPyEndBlockThreads();
899 return o;
900 }
901
902 //----------------------------------------------------------------------
903
904 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback, wxObject);
905
906 wxPyCallback::wxPyCallback(PyObject* func) {
907 m_func = func;
908 Py_INCREF(m_func);
909 }
910
911 wxPyCallback::wxPyCallback(const wxPyCallback& other) {
912 m_func = other.m_func;
913 Py_INCREF(m_func);
914 }
915
916 wxPyCallback::~wxPyCallback() {
917 wxPyBeginBlockThreads();
918 Py_DECREF(m_func);
919 wxPyEndBlockThreads();
920 }
921
922
923
924 // This function is used for all events destined for Python event handlers.
925 void wxPyCallback::EventThunker(wxEvent& event) {
926 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
927 PyObject* func = cb->m_func;
928 PyObject* result;
929 PyObject* arg;
930 PyObject* tuple;
931
932
933 wxPyBeginBlockThreads();
934 wxString className = event.GetClassInfo()->GetClassName();
935
936 if (className == "wxPyEvent")
937 arg = ((wxPyEvent*)&event)->GetSelf();
938 else if (className == "wxPyCommandEvent")
939 arg = ((wxPyCommandEvent*)&event)->GetSelf();
940 else {
941 arg = wxPyConstructObject((void*)&event, className);
942 }
943
944 tuple = PyTuple_New(1);
945 PyTuple_SET_ITEM(tuple, 0, arg);
946 result = PyEval_CallObject(func, tuple);
947 Py_DECREF(tuple);
948 if (result) {
949 Py_DECREF(result);
950 PyErr_Clear(); // Just in case...
951 } else {
952 PyErr_Print();
953 }
954 wxPyEndBlockThreads();
955 }
956
957
958 //----------------------------------------------------------------------
959
960 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper& other) {
961 m_lastFound = NULL;
962 m_self = other.m_self;
963 m_class = other.m_class;
964 if (m_self) {
965 Py_INCREF(m_self);
966 Py_INCREF(m_class);
967 }
968 }
969
970
971 void wxPyCallbackHelper::setSelf(PyObject* self, PyObject* klass, int incref) {
972 m_self = self;
973 m_class = klass;
974 m_incRef = incref;
975 if (incref) {
976 Py_INCREF(m_self);
977 Py_INCREF(m_class);
978 }
979 }
980
981
982 #if PYTHON_API_VERSION >= 1011
983
984 // Prior to Python 2.2 PyMethod_GetClass returned the class object
985 // in which the method was defined. Starting with 2.2 it returns
986 // "class that asked for the method" which seems totally bogus to me
987 // but apprently it fixes some obscure problem waiting to happen in
988 // Python. Since the API was not documented Guido and the gang felt
989 // safe in changing it. Needless to say that totally screwed up the
990 // logic below in wxPyCallbackHelper::findCallback, hence this icky
991 // code to find the class where the method is actually defined...
992
993 static
994 PyObject* PyFindClassWithAttr(PyObject *klass, PyObject *name)
995 {
996 int i, n;
997
998 if (PyType_Check(klass)) { // new style classes
999 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1000 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1001 PyTypeObject* type = (PyTypeObject*)klass;
1002 PyObject *mro, *res, *base, *dict;
1003 /* Look in tp_dict of types in MRO */
1004 mro = type->tp_mro;
1005 assert(PyTuple_Check(mro));
1006 n = PyTuple_GET_SIZE(mro);
1007 for (i = 0; i < n; i++) {
1008 base = PyTuple_GET_ITEM(mro, i);
1009 if (PyClass_Check(base))
1010 dict = ((PyClassObject *)base)->cl_dict;
1011 else {
1012 assert(PyType_Check(base));
1013 dict = ((PyTypeObject *)base)->tp_dict;
1014 }
1015 assert(dict && PyDict_Check(dict));
1016 res = PyDict_GetItem(dict, name);
1017 if (res != NULL)
1018 return base;
1019 }
1020 return NULL;
1021 }
1022
1023 else if (PyClass_Check(klass)) { // old style classes
1024 // This code is borrowed/adapted from class_lookup in classobject.c
1025 PyClassObject* cp = (PyClassObject*)klass;
1026 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
1027 if (value != NULL) {
1028 return (PyObject*)cp;
1029 }
1030 n = PyTuple_Size(cp->cl_bases);
1031 for (i = 0; i < n; i++) {
1032 PyObject* base = PyTuple_GetItem(cp->cl_bases, i);
1033 PyObject *v = PyFindClassWithAttr(base, name);
1034 if (v != NULL)
1035 return v;
1036 }
1037 return NULL;
1038 }
1039 return NULL;
1040 }
1041 #endif
1042
1043
1044 static
1045 PyObject* PyMethod_GetDefiningClass(PyObject* method, const char* name)
1046 {
1047 PyObject* mgc = PyMethod_GET_CLASS(method);
1048
1049 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1050 return mgc;
1051 #else // 2.2 and after, the hard way...
1052
1053 PyObject* nameo = PyString_FromString(name);
1054 PyObject* klass = PyFindClassWithAttr(mgc, nameo);
1055 Py_DECREF(nameo);
1056 return klass;
1057 #endif
1058 }
1059
1060
1061
1062 bool wxPyCallbackHelper::findCallback(const char* name) const {
1063 wxPyCallbackHelper* self = (wxPyCallbackHelper*)this; // cast away const
1064 self->m_lastFound = NULL;
1065
1066 // If the object (m_self) has an attibute of the given name...
1067 if (m_self && PyObject_HasAttrString(m_self, (char*)name)) {
1068 PyObject *method, *klass;
1069 method = PyObject_GetAttrString(m_self, (char*)name);
1070
1071 // ...and if that attribute is a method, and if that method's class is
1072 // not from a base class...
1073 if (PyMethod_Check(method) &&
1074 (klass = PyMethod_GetDefiningClass(method, (char*)name)) != NULL &&
1075 ((klass == m_class) || PyClass_IsSubclass(klass, m_class))) {
1076
1077 // ...then we'll save a pointer to the method so callCallback can call it.
1078 self->m_lastFound = method;
1079 }
1080 else {
1081 Py_DECREF(method);
1082 }
1083 }
1084 return m_lastFound != NULL;
1085 }
1086
1087
1088 int wxPyCallbackHelper::callCallback(PyObject* argTuple) const {
1089 PyObject* result;
1090 int retval = FALSE;
1091
1092 result = callCallbackObj(argTuple);
1093 if (result) { // Assumes an integer return type...
1094 retval = PyInt_AsLong(result);
1095 Py_DECREF(result);
1096 PyErr_Clear(); // forget about it if it's not...
1097 }
1098 return retval;
1099 }
1100
1101 // Invoke the Python callable object, returning the raw PyObject return
1102 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1103 PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) const {
1104 PyObject* result;
1105
1106 // Save a copy of the pointer in case the callback generates another
1107 // callback. In that case m_lastFound will have a different value when
1108 // it gets back here...
1109 PyObject* method = m_lastFound;
1110
1111 result = PyEval_CallObject(method, argTuple);
1112 Py_DECREF(argTuple);
1113 Py_DECREF(method);
1114 if (!result) {
1115 PyErr_Print();
1116 }
1117 return result;
1118 }
1119
1120
1121 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper& cbh, PyObject* self, PyObject* klass, int incref) {
1122 cbh.setSelf(self, klass, incref);
1123 }
1124
1125 bool wxPyCBH_findCallback(const wxPyCallbackHelper& cbh, const char* name) {
1126 return cbh.findCallback(name);
1127 }
1128
1129 int wxPyCBH_callCallback(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1130 return cbh.callCallback(argTuple);
1131 }
1132
1133 PyObject* wxPyCBH_callCallbackObj(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1134 return cbh.callCallbackObj(argTuple);
1135 }
1136
1137
1138 void wxPyCBH_delete(wxPyCallbackHelper* cbh) {
1139 if (cbh->m_incRef) {
1140 wxPyBeginBlockThreads();
1141 Py_XDECREF(cbh->m_self);
1142 Py_XDECREF(cbh->m_class);
1143 wxPyEndBlockThreads();
1144 }
1145 }
1146
1147 //---------------------------------------------------------------------------
1148 //---------------------------------------------------------------------------
1149 // These event classes can be derived from in Python and passed through the event
1150 // system without losing anything. They do this by keeping a reference to
1151 // themselves and some special case handling in wxPyCallback::EventThunker.
1152
1153
1154 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1155 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1156 //Py_INCREF(m_self); // circular loops...
1157 m_cloned = FALSE;
1158 }
1159
1160 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1161 wxPyBeginBlockThreads();
1162 if (m_cloned)
1163 Py_DECREF(m_self);
1164 wxPyEndBlockThreads();
1165 }
1166
1167 void wxPyEvtSelfRef::SetSelf(PyObject* self, bool clone) {
1168 wxPyBeginBlockThreads();
1169 if (m_cloned)
1170 Py_DECREF(m_self);
1171 m_self = self;
1172 if (clone) {
1173 Py_INCREF(m_self);
1174 m_cloned = TRUE;
1175 }
1176 wxPyEndBlockThreads();
1177 }
1178
1179 PyObject* wxPyEvtSelfRef::GetSelf() const {
1180 Py_INCREF(m_self);
1181 return m_self;
1182 }
1183
1184
1185 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent, wxEvent);
1186 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent, wxCommandEvent);
1187
1188
1189 wxPyEvent::wxPyEvent(int id)
1190 : wxEvent(id) {
1191 }
1192
1193
1194 wxPyEvent::wxPyEvent(const wxPyEvent& evt)
1195 : wxEvent(evt)
1196 {
1197 SetSelf(evt.m_self, TRUE);
1198 }
1199
1200
1201 wxPyEvent::~wxPyEvent() {
1202 }
1203
1204
1205 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType, int id)
1206 : wxCommandEvent(commandType, id) {
1207 }
1208
1209
1210 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent& evt)
1211 : wxCommandEvent(evt)
1212 {
1213 SetSelf(evt.m_self, TRUE);
1214 }
1215
1216
1217 wxPyCommandEvent::~wxPyCommandEvent() {
1218 }
1219
1220
1221
1222
1223 //---------------------------------------------------------------------------
1224 //---------------------------------------------------------------------------
1225
1226
1227 wxPyTimer::wxPyTimer(PyObject* callback) {
1228 func = callback;
1229 Py_INCREF(func);
1230 }
1231
1232 wxPyTimer::~wxPyTimer() {
1233 wxPyBeginBlockThreads();
1234 Py_DECREF(func);
1235 wxPyEndBlockThreads();
1236 }
1237
1238 void wxPyTimer::Notify() {
1239 if (!func || func == Py_None) {
1240 wxTimer::Notify();
1241 }
1242 else {
1243 wxPyBeginBlockThreads();
1244
1245 PyObject* result;
1246 PyObject* args = Py_BuildValue("()");
1247
1248 result = PyEval_CallObject(func, args);
1249 Py_DECREF(args);
1250 if (result) {
1251 Py_DECREF(result);
1252 PyErr_Clear();
1253 } else {
1254 PyErr_Print();
1255 }
1256
1257 wxPyEndBlockThreads();
1258 }
1259 }
1260
1261
1262
1263 //---------------------------------------------------------------------------
1264 //---------------------------------------------------------------------------
1265 // Convert a wxList to a Python List
1266
1267 PyObject* wxPy_ConvertList(wxListBase* list, const char* className) {
1268 PyObject* pyList;
1269 PyObject* pyObj;
1270 wxObject* wxObj;
1271 wxNode* node = list->First();
1272
1273 wxPyBeginBlockThreads();
1274 pyList = PyList_New(0);
1275 while (node) {
1276 wxObj = node->Data();
1277 pyObj = wxPyMake_wxObject(wxObj); //wxPyConstructObject(wxObj, className);
1278 PyList_Append(pyList, pyObj);
1279 node = node->Next();
1280 }
1281 wxPyEndBlockThreads();
1282 return pyList;
1283 }
1284
1285 //----------------------------------------------------------------------
1286
1287 long wxPyGetWinHandle(wxWindow* win) {
1288 #ifdef __WXMSW__
1289 return (long)win->GetHandle();
1290 #endif
1291
1292 // Find and return the actual X-Window.
1293 #ifdef __WXGTK__
1294 if (win->m_wxwindow) {
1295 GdkWindowPrivate* bwin = (GdkWindowPrivate*)GTK_PIZZA(win->m_wxwindow)->bin_window;
1296 if (bwin) {
1297 return (long)bwin->xwindow;
1298 }
1299 }
1300 #endif
1301 return 0;
1302 }
1303
1304 //----------------------------------------------------------------------
1305 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1306 // included in every file over and over again...
1307
1308 #if PYTHON_API_VERSION >= 1009
1309 static char* wxStringErrorMsg = "String or Unicode type required";
1310 #else
1311 static char* wxStringErrorMsg = "String type required";
1312 #endif
1313
1314
1315 wxString* wxString_in_helper(PyObject* source) {
1316 wxString* target;
1317 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1318 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1319 PyErr_SetString(PyExc_TypeError, wxStringErrorMsg);
1320 return NULL;
1321 }
1322 #if wxUSE_UNICODE
1323 if (PyUnicode_Check(source)) {
1324 target = new wxString(PyUnicode_AS_UNICODE(source));
1325 } else {
1326 // It is a string, get pointers to it and transform to unicode
1327 char* tmpPtr; int tmpSize;
1328 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1329 target = new wxString(tmpPtr, *wxConvCurrent, tmpSize);
1330 }
1331 #else
1332 char* tmpPtr; int tmpSize;
1333 if (PyString_AsStringAndSize(source, &tmpPtr, &tmpSize) == -1) {
1334 PyErr_SetString(PyExc_TypeError, "Unable to convert string");
1335 return NULL;
1336 }
1337 target = new wxString(tmpPtr, tmpSize);
1338 #endif // wxUSE_UNICODE
1339
1340 #else // No Python unicode API (1.5.2)
1341 if (!PyString_Check(source)) {
1342 PyErr_SetString(PyExc_TypeError, wxStringErrorMsg);
1343 return NULL;
1344 }
1345 target = new wxString(PyString_AS_STRING(source), PyString_GET_SIZE(source));
1346 #endif
1347 return target;
1348 }
1349
1350
1351 // Similar to above except doesn't use "new" and doesn't set an exception
1352 wxString Py2wxString(PyObject* source)
1353 {
1354 wxString target;
1355 bool doDecRef = FALSE;
1356
1357 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1358 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1359 // Convert to String if not one already... (TODO: Unicode too?)
1360 source = PyObject_Str(source);
1361 doDecRef = TRUE;
1362 }
1363
1364 #if wxUSE_UNICODE
1365 if (PyUnicode_Check(source)) {
1366 target = PyUnicode_AS_UNICODE(source);
1367 } else {
1368 // It is a string, get pointers to it and transform to unicode
1369 char* tmpPtr; int tmpSize;
1370 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1371 target = wxString(tmpPtr, *wxConvCurrent, tmpSize);
1372 }
1373 #else
1374 char* tmpPtr; int tmpSize;
1375 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1376 target = wxString(tmpPtr, tmpSize);
1377 #endif // wxUSE_UNICODE
1378
1379 #else // No Python unicode API (1.5.2)
1380 if (!PyString_Check(source)) {
1381 // Convert to String if not one already...
1382 source = PyObject_Str(source);
1383 doDecRef = TRUE;
1384 }
1385 target = wxString(PyString_AS_STRING(source), PyString_GET_SIZE(source));
1386 #endif
1387
1388 if (doDecRef)
1389 Py_DECREF(source);
1390 return target;
1391 }
1392
1393
1394 // Make either a Python String or Unicode object, depending on build mode
1395 PyObject* wx2PyString(const wxString& src)
1396 {
1397 PyObject* str;
1398 #if wxUSE_UNICODE
1399 str = PyUnicode_FromUnicode(src.c_str(), src.Len());
1400 #else
1401 str = PyString_FromStringAndSize(src.c_str(), src.Len());
1402 #endif
1403 return str;
1404 }
1405
1406
1407 //----------------------------------------------------------------------
1408
1409
1410 byte* byte_LIST_helper(PyObject* source) {
1411 if (!PyList_Check(source)) {
1412 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1413 return NULL;
1414 }
1415 int count = PyList_Size(source);
1416 byte* temp = new byte[count];
1417 if (! temp) {
1418 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1419 return NULL;
1420 }
1421 for (int x=0; x<count; x++) {
1422 PyObject* o = PyList_GetItem(source, x);
1423 if (! PyInt_Check(o)) {
1424 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1425 return NULL;
1426 }
1427 temp[x] = (byte)PyInt_AsLong(o);
1428 }
1429 return temp;
1430 }
1431
1432
1433 int* int_LIST_helper(PyObject* source) {
1434 if (!PyList_Check(source)) {
1435 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1436 return NULL;
1437 }
1438 int count = PyList_Size(source);
1439 int* temp = new int[count];
1440 if (! temp) {
1441 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1442 return NULL;
1443 }
1444 for (int x=0; x<count; x++) {
1445 PyObject* o = PyList_GetItem(source, x);
1446 if (! PyInt_Check(o)) {
1447 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1448 return NULL;
1449 }
1450 temp[x] = PyInt_AsLong(o);
1451 }
1452 return temp;
1453 }
1454
1455
1456 long* long_LIST_helper(PyObject* source) {
1457 if (!PyList_Check(source)) {
1458 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1459 return NULL;
1460 }
1461 int count = PyList_Size(source);
1462 long* temp = new long[count];
1463 if (! temp) {
1464 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1465 return NULL;
1466 }
1467 for (int x=0; x<count; x++) {
1468 PyObject* o = PyList_GetItem(source, x);
1469 if (! PyInt_Check(o)) {
1470 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1471 return NULL;
1472 }
1473 temp[x] = PyInt_AsLong(o);
1474 }
1475 return temp;
1476 }
1477
1478
1479 char** string_LIST_helper(PyObject* source) {
1480 if (!PyList_Check(source)) {
1481 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1482 return NULL;
1483 }
1484 int count = PyList_Size(source);
1485 char** temp = new char*[count];
1486 if (! temp) {
1487 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1488 return NULL;
1489 }
1490 for (int x=0; x<count; x++) {
1491 PyObject* o = PyList_GetItem(source, x);
1492 if (! PyString_Check(o)) {
1493 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
1494 return NULL;
1495 }
1496 temp[x] = PyString_AsString(o);
1497 }
1498 return temp;
1499 }
1500
1501 //--------------------------------
1502 // Part of patch from Tim Hochberg
1503 static inline bool wxPointFromObjects(PyObject* o1, PyObject* o2, wxPoint* point) {
1504 if (PyInt_Check(o1) && PyInt_Check(o2)) {
1505 point->x = PyInt_AS_LONG(o1);
1506 point->y = PyInt_AS_LONG(o2);
1507 return true;
1508 }
1509 if (PyFloat_Check(o1) && PyFloat_Check(o2)) {
1510 point->x = (int)PyFloat_AS_DOUBLE(o1);
1511 point->y = (int)PyFloat_AS_DOUBLE(o2);
1512 return true;
1513 }
1514 if (PyInstance_Check(o1) || PyInstance_Check(o2)) {
1515 // Disallow instances because they can cause havok
1516 return false;
1517 }
1518 if (PyNumber_Check(o1) && PyNumber_Check(o2)) {
1519 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1520 point->x = PyInt_AsLong(o1);
1521 point->y = PyInt_AsLong(o2);
1522 return true;
1523 }
1524 return false;
1525 }
1526
1527
1528 wxPoint* wxPoint_LIST_helper(PyObject* source, int *count) {
1529 // Putting all of the declarations here allows
1530 // us to put the error handling all in one place.
1531 int x;
1532 wxPoint* temp;
1533 PyObject *o, *o1, *o2;
1534 bool isFast = PyList_Check(source) || PyTuple_Check(source);
1535
1536 if (!PySequence_Check(source)) {
1537 goto error0;
1538 }
1539
1540 // The length of the sequence is returned in count.
1541 *count = PySequence_Length(source);
1542 if (*count < 0) {
1543 goto error0;
1544 }
1545
1546 temp = new wxPoint[*count];
1547 if (!temp) {
1548 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1549 return NULL;
1550 }
1551 for (x=0; x<*count; x++) {
1552 // Get an item: try fast way first.
1553 if (isFast) {
1554 o = PySequence_Fast_GET_ITEM(source, x);
1555 }
1556 else {
1557 o = PySequence_GetItem(source, x);
1558 if (o == NULL) {
1559 goto error1;
1560 }
1561 }
1562
1563 // Convert o to wxPoint.
1564 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
1565 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
1566 o1 = PySequence_Fast_GET_ITEM(o, 0);
1567 o2 = PySequence_Fast_GET_ITEM(o, 1);
1568 if (!wxPointFromObjects(o1, o2, &temp[x])) {
1569 goto error2;
1570 }
1571 }
1572 else if (PyInstance_Check(o)) {
1573 wxPoint* pt;
1574 if (SWIG_GetPtrObj(o, (void **)&pt, "_wxPoint_p")) {
1575 goto error2;
1576 }
1577 temp[x] = *pt;
1578 }
1579 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
1580 o1 = PySequence_GetItem(o, 0);
1581 o2 = PySequence_GetItem(o, 1);
1582 if (!wxPointFromObjects(o1, o2, &temp[x])) {
1583 goto error3;
1584 }
1585 Py_DECREF(o1);
1586 Py_DECREF(o2);
1587 }
1588 else {
1589 goto error2;
1590 }
1591 // Clean up.
1592 if (!isFast)
1593 Py_DECREF(o);
1594 }
1595 return temp;
1596
1597 error3:
1598 Py_DECREF(o1);
1599 Py_DECREF(o2);
1600 error2:
1601 if (!isFast)
1602 Py_DECREF(o);
1603 error1:
1604 delete temp;
1605 error0:
1606 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoints.");
1607 return NULL;
1608 }
1609 // end of patch
1610 //------------------------------
1611
1612
1613 wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
1614 if (!PyList_Check(source)) {
1615 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1616 return NULL;
1617 }
1618 int count = PyList_Size(source);
1619 wxBitmap** temp = new wxBitmap*[count];
1620 if (! temp) {
1621 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1622 return NULL;
1623 }
1624 for (int x=0; x<count; x++) {
1625 PyObject* o = PyList_GetItem(source, x);
1626 if (PyInstance_Check(o)) {
1627 wxBitmap* pt;
1628 if (SWIG_GetPtrObj(o, (void **) &pt,"_wxBitmap_p")) {
1629 PyErr_SetString(PyExc_TypeError,"Expected _wxBitmap_p.");
1630 return NULL;
1631 }
1632 temp[x] = pt;
1633 }
1634 else {
1635 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
1636 return NULL;
1637 }
1638 }
1639 return temp;
1640 }
1641
1642
1643
1644 wxString* wxString_LIST_helper(PyObject* source) {
1645 if (!PyList_Check(source)) {
1646 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1647 return NULL;
1648 }
1649 int count = PyList_Size(source);
1650 wxString* temp = new wxString[count];
1651 if (! temp) {
1652 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1653 return NULL;
1654 }
1655 for (int x=0; x<count; x++) {
1656 PyObject* o = PyList_GetItem(source, x);
1657 #if PYTHON_API_VERSION >= 1009
1658 if (! PyString_Check(o) && ! PyUnicode_Check(o)) {
1659 PyErr_SetString(PyExc_TypeError, "Expected a list of string or unicode objects.");
1660 return NULL;
1661 }
1662 #else
1663 if (! PyString_Check(o)) {
1664 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
1665 return NULL;
1666 }
1667 #endif
1668
1669 wxString* pStr = wxString_in_helper(o);
1670 temp[x] = *pStr;
1671 delete pStr;
1672 }
1673 return temp;
1674 }
1675
1676
1677 wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
1678 if (!PyList_Check(source)) {
1679 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1680 return NULL;
1681 }
1682 int count = PyList_Size(source);
1683 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
1684 if (! temp) {
1685 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1686 return NULL;
1687 }
1688 for (int x=0; x<count; x++) {
1689 PyObject* o = PyList_GetItem(source, x);
1690 if (PyInstance_Check(o)) {
1691 wxAcceleratorEntry* ae;
1692 if (SWIG_GetPtrObj(o, (void **) &ae,"_wxAcceleratorEntry_p")) {
1693 PyErr_SetString(PyExc_TypeError,"Expected _wxAcceleratorEntry_p.");
1694 return NULL;
1695 }
1696 temp[x] = *ae;
1697 }
1698 else if (PyTuple_Check(o)) {
1699 PyObject* o1 = PyTuple_GetItem(o, 0);
1700 PyObject* o2 = PyTuple_GetItem(o, 1);
1701 PyObject* o3 = PyTuple_GetItem(o, 2);
1702 temp[x].Set(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
1703 }
1704 else {
1705 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
1706 return NULL;
1707 }
1708 }
1709 return temp;
1710 }
1711
1712
1713 wxPen** wxPen_LIST_helper(PyObject* source) {
1714 if (!PyList_Check(source)) {
1715 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1716 return NULL;
1717 }
1718 int count = PyList_Size(source);
1719 wxPen** temp = new wxPen*[count];
1720 if (!temp) {
1721 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1722 return NULL;
1723 }
1724 for (int x=0; x<count; x++) {
1725 PyObject* o = PyList_GetItem(source, x);
1726 if (PyInstance_Check(o)) {
1727 wxPen* pt;
1728 if (SWIG_GetPtrObj(o, (void **) &pt,"_wxPen_p")) {
1729 delete temp;
1730 PyErr_SetString(PyExc_TypeError,"Expected _wxPen_p.");
1731 return NULL;
1732 }
1733 temp[x] = pt;
1734 }
1735 else {
1736 delete temp;
1737 PyErr_SetString(PyExc_TypeError, "Expected a list of wxPens.");
1738 return NULL;
1739 }
1740 }
1741 return temp;
1742 }
1743
1744
1745 bool _2int_seq_helper(PyObject* source, int* i1, int* i2) {
1746 bool isFast = PyList_Check(source) || PyTuple_Check(source);
1747 PyObject *o1, *o2;
1748
1749 if (!PySequence_Check(source) || PySequence_Length(source) != 2)
1750 return FALSE;
1751
1752 if (isFast) {
1753 o1 = PySequence_Fast_GET_ITEM(source, 0);
1754 o2 = PySequence_Fast_GET_ITEM(source, 1);
1755 }
1756 else {
1757 o1 = PySequence_GetItem(source, 0);
1758 o2 = PySequence_GetItem(source, 1);
1759 }
1760
1761 *i1 = PyInt_AsLong(o1);
1762 *i2 = PyInt_AsLong(o2);
1763
1764 if (! isFast) {
1765 Py_DECREF(o1);
1766 Py_DECREF(o2);
1767 }
1768 return TRUE;
1769 }
1770
1771
1772 bool _4int_seq_helper(PyObject* source, int* i1, int* i2, int* i3, int* i4) {
1773 bool isFast = PyList_Check(source) || PyTuple_Check(source);
1774 PyObject *o1, *o2, *o3, *o4;
1775
1776 if (!PySequence_Check(source) || PySequence_Length(source) != 4)
1777 return FALSE;
1778
1779 if (isFast) {
1780 o1 = PySequence_Fast_GET_ITEM(source, 0);
1781 o2 = PySequence_Fast_GET_ITEM(source, 1);
1782 o3 = PySequence_Fast_GET_ITEM(source, 2);
1783 o4 = PySequence_Fast_GET_ITEM(source, 3);
1784 }
1785 else {
1786 o1 = PySequence_GetItem(source, 0);
1787 o2 = PySequence_GetItem(source, 1);
1788 o3 = PySequence_GetItem(source, 2);
1789 o4 = PySequence_GetItem(source, 3);
1790 }
1791
1792 *i1 = PyInt_AsLong(o1);
1793 *i2 = PyInt_AsLong(o2);
1794 *i3 = PyInt_AsLong(o3);
1795 *i4 = PyInt_AsLong(o4);
1796
1797 if (! isFast) {
1798 Py_DECREF(o1);
1799 Py_DECREF(o2);
1800 Py_DECREF(o3);
1801 Py_DECREF(o4);
1802 }
1803 return TRUE;
1804 }
1805
1806
1807 //----------------------------------------------------------------------
1808
1809 bool wxSize_helper(PyObject* source, wxSize** obj) {
1810
1811 // If source is an object instance then it may already be the right type
1812 if (PyInstance_Check(source)) {
1813 wxSize* ptr;
1814 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxSize_p"))
1815 goto error;
1816 *obj = ptr;
1817 return TRUE;
1818 }
1819 // otherwise a 2-tuple of integers is expected
1820 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
1821 PyObject* o1 = PySequence_GetItem(source, 0);
1822 PyObject* o2 = PySequence_GetItem(source, 1);
1823 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
1824 Py_DECREF(o1);
1825 Py_DECREF(o2);
1826 goto error;
1827 }
1828 **obj = wxSize(PyInt_AsLong(o1), PyInt_AsLong(o2));
1829 Py_DECREF(o1);
1830 Py_DECREF(o2);
1831 return TRUE;
1832 }
1833
1834 error:
1835 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of integers or a wxSize object.");
1836 return FALSE;
1837 }
1838
1839 bool wxPoint_helper(PyObject* source, wxPoint** obj) {
1840
1841 // If source is an object instance then it may already be the right type
1842 if (PyInstance_Check(source)) {
1843 wxPoint* ptr;
1844 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxPoint_p"))
1845 goto error;
1846 *obj = ptr;
1847 return TRUE;
1848 }
1849 // otherwise a length-2 sequence of integers is expected
1850 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
1851 PyObject* o1 = PySequence_GetItem(source, 0);
1852 PyObject* o2 = PySequence_GetItem(source, 1);
1853 // This should really check for integers, not numbers -- but that would break code.
1854 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
1855 Py_DECREF(o1);
1856 Py_DECREF(o2);
1857 goto error;
1858 }
1859 **obj = wxPoint(PyInt_AsLong(o1), PyInt_AsLong(o2));
1860 Py_DECREF(o1);
1861 Py_DECREF(o2);
1862 return TRUE;
1863 }
1864 error:
1865 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of integers or a wxPoint object.");
1866 return FALSE;
1867 }
1868
1869
1870
1871 bool wxRealPoint_helper(PyObject* source, wxRealPoint** obj) {
1872
1873 // If source is an object instance then it may already be the right type
1874 if (PyInstance_Check(source)) {
1875 wxRealPoint* ptr;
1876 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxRealPoint_p"))
1877 goto error;
1878 *obj = ptr;
1879 return TRUE;
1880 }
1881 // otherwise a 2-tuple of floats is expected
1882 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
1883 PyObject* o1 = PySequence_GetItem(source, 0);
1884 PyObject* o2 = PySequence_GetItem(source, 1);
1885 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
1886 Py_DECREF(o1);
1887 Py_DECREF(o2);
1888 goto error;
1889 }
1890 **obj = wxRealPoint(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
1891 Py_DECREF(o1);
1892 Py_DECREF(o2);
1893 return TRUE;
1894 }
1895
1896 error:
1897 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxRealPoint object.");
1898 return FALSE;
1899 }
1900
1901
1902
1903
1904 bool wxRect_helper(PyObject* source, wxRect** obj) {
1905
1906 // If source is an object instance then it may already be the right type
1907 if (PyInstance_Check(source)) {
1908 wxRect* ptr;
1909 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxRect_p"))
1910 goto error;
1911 *obj = ptr;
1912 return TRUE;
1913 }
1914 // otherwise a 4-tuple of integers is expected
1915 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
1916 PyObject* o1 = PySequence_GetItem(source, 0);
1917 PyObject* o2 = PySequence_GetItem(source, 1);
1918 PyObject* o3 = PySequence_GetItem(source, 2);
1919 PyObject* o4 = PySequence_GetItem(source, 3);
1920 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
1921 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
1922 Py_DECREF(o1);
1923 Py_DECREF(o2);
1924 Py_DECREF(o3);
1925 Py_DECREF(o4);
1926 goto error;
1927 }
1928 **obj = wxRect(PyInt_AsLong(o1), PyInt_AsLong(o2),
1929 PyInt_AsLong(o3), PyInt_AsLong(o4));
1930 Py_DECREF(o1);
1931 Py_DECREF(o2);
1932 Py_DECREF(o3);
1933 Py_DECREF(o4);
1934 return TRUE;
1935 }
1936
1937 error:
1938 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of integers or a wxRect object.");
1939 return FALSE;
1940 }
1941
1942
1943
1944 bool wxColour_helper(PyObject* source, wxColour** obj) {
1945
1946 // If source is an object instance then it may already be the right type
1947 if (PyInstance_Check(source)) {
1948 wxColour* ptr;
1949 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxColour_p"))
1950 goto error;
1951 *obj = ptr;
1952 return TRUE;
1953 }
1954 // otherwise a string is expected
1955 else if (PyString_Check(source)) {
1956 wxString spec(PyString_AS_STRING(source), *wxConvCurrent);
1957 if (spec.GetChar(0) == '#' && spec.Length() == 7) { // It's #RRGGBB
1958 long red, green, blue;
1959 red = green = blue = 0;
1960 spec.Mid(1,2).ToLong(&red, 16);
1961 spec.Mid(3,2).ToLong(&green, 16);
1962 spec.Mid(5,2).ToLong(&blue, 16);
1963
1964 **obj = wxColour(red, green, blue);
1965 return TRUE;
1966 }
1967 else { // it's a colour name
1968 **obj = wxColour(spec);
1969 return TRUE;
1970 }
1971 }
1972
1973 error:
1974 PyErr_SetString(PyExc_TypeError,
1975 "Expected a wxColour object or a string containing a colour "
1976 "name or '#RRGGBB'.");
1977 return FALSE;
1978 }
1979
1980
1981 //----------------------------------------------------------------------
1982
1983 PyObject* wxArrayString2PyList_helper(const wxArrayString& arr) {
1984
1985 PyObject* list = PyList_New(0);
1986 for (size_t i=0; i < arr.GetCount(); i++) {
1987 #if wxUSE_UNICODE
1988 PyObject* str = PyUnicode_FromUnicode(arr[i].c_str(), arr[i].Len());
1989 #else
1990 PyObject* str = PyString_FromStringAndSize(arr[i].c_str(), arr[i].Len());
1991 #endif
1992 PyList_Append(list, str);
1993 Py_DECREF(str);
1994 }
1995 return list;
1996 }
1997
1998
1999 PyObject* wxArrayInt2PyList_helper(const wxArrayInt& arr) {
2000
2001 PyObject* list = PyList_New(0);
2002 for (size_t i=0; i < arr.GetCount(); i++) {
2003 PyObject* number = PyInt_FromLong(arr[i]);
2004 PyList_Append(list, number);
2005 Py_DECREF(number);
2006 }
2007 return list;
2008 }
2009
2010
2011 //----------------------------------------------------------------------
2012 //----------------------------------------------------------------------
2013
2014
2015
2016