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