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