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