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