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