]> git.saurik.com Git - wxWidgets.git/blob - wxPython/src/helpers.cpp
fix text scrolling in GTK2 (patch 703988)
[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
14 #undef DEBUG
15 #include <Python.h>
16 #include "helpers.h"
17 #include "pyistream.h"
18
19 #ifdef __WXMSW__
20 #include <wx/msw/private.h>
21 #include <wx/msw/winundef.h>
22 #include <wx/msw/msvcrt.h>
23 #endif
24
25 #ifdef __WXGTK__
26 #include <gtk/gtk.h>
27 #include <gdk/gdkprivate.h>
28 #include <wx/gtk/win_gtk.h>
29 #endif
30
31 #include <wx/clipbrd.h>
32 #include <wx/mimetype.h>
33 #include <wx/image.h>
34
35 //----------------------------------------------------------------------
36
37 #if PYTHON_API_VERSION <= 1007 && wxUSE_UNICODE
38 #error Python must support Unicode to use wxWindows Unicode
39 #endif
40
41 //----------------------------------------------------------------------
42
43 wxPyApp* wxPythonApp = NULL; // Global instance of application object
44 bool wxPyDoCleanup = FALSE;
45 bool wxPyDoingCleanup = FALSE;
46
47
48 #ifdef WXP_WITH_THREAD
49 struct wxPyThreadState {
50 unsigned long tid;
51 PyThreadState* tstate;
52
53 wxPyThreadState(unsigned long _tid=0, PyThreadState* _tstate=NULL)
54 : tid(_tid), tstate(_tstate) {}
55 };
56
57 #include <wx/dynarray.h>
58 WX_DECLARE_OBJARRAY(wxPyThreadState, wxPyThreadStateArray);
59 #include <wx/arrimpl.cpp>
60 WX_DEFINE_OBJARRAY(wxPyThreadStateArray);
61
62 wxPyThreadStateArray* wxPyTStates = NULL;
63 wxMutex* wxPyTMutex = NULL;
64 #endif
65
66
67 static PyObject* wxPython_dict = NULL;
68 static PyObject* wxPyPtrTypeMap = NULL;
69 static PyObject* wxPyAssertionError = NULL;
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 IMPLEMENT_ABSTRACT_CLASS(wxPyApp, wxApp);
96
97
98 wxPyApp::wxPyApp() {
99 m_assertMode = wxPYAPP_ASSERT_EXCEPTION;
100 }
101
102
103 wxPyApp::~wxPyApp() {
104 }
105
106
107 // This one isn't acutally called... We fake it with __wxStart()
108 bool wxPyApp::OnInit() {
109 return FALSE;
110 }
111
112
113 int wxPyApp::MainLoop() {
114 int retval = 0;
115
116 DeletePendingObjects();
117 bool initialized = wxTopLevelWindows.GetCount() != 0;
118 #ifdef __WXGTK__
119 m_initialized = initialized;
120 #endif
121
122 if (initialized) {
123 if ( m_exitOnFrameDelete == Later ) {
124 m_exitOnFrameDelete = Yes;
125 }
126
127 retval = wxApp::MainLoop();
128 OnExit();
129 }
130 return retval;
131 }
132
133
134 bool wxPyApp::OnInitGui() {
135 bool rval=TRUE;
136 wxApp::OnInitGui(); // in this case always call the base class version
137 // wxPyBeginBlockThreads(); *** only called from within __wxStart so we already have the GIL
138 if (wxPyCBH_findCallback(m_myInst, "OnInitGui"))
139 rval = wxPyCBH_callCallback(m_myInst, Py_BuildValue("()"));
140 // wxPyEndBlockThreads(); ***
141 return rval;
142 }
143
144
145 int wxPyApp::OnExit() {
146 int rval=0;
147 wxPyBeginBlockThreads();
148 if (wxPyCBH_findCallback(m_myInst, "OnExit"))
149 rval = wxPyCBH_callCallback(m_myInst, Py_BuildValue("()"));
150 wxPyEndBlockThreads();
151 wxApp::OnExit(); // in this case always call the base class version
152 return rval;
153 }
154
155
156 #ifdef __WXDEBUG__
157 void wxPyApp::OnAssert(const wxChar *file,
158 int line,
159 const wxChar *cond,
160 const wxChar *msg) {
161
162 // If the OnAssert is overloaded in the Python class then call it...
163 bool found;
164 wxPyBeginBlockThreads();
165 if ((found = wxPyCBH_findCallback(m_myInst, "OnAssert"))) {
166 PyObject* fso = wx2PyString(file);
167 PyObject* cso = wx2PyString(file);
168 PyObject* mso;
169 if (msg != NULL)
170 mso = wx2PyString(file);
171 else {
172 mso = Py_None; Py_INCREF(Py_None);
173 }
174 wxPyCBH_callCallback(m_myInst, Py_BuildValue("(OiOO)", fso, line, cso, mso));
175 Py_DECREF(fso);
176 Py_DECREF(cso);
177 Py_DECREF(mso);
178 }
179 wxPyEndBlockThreads();
180
181 // ...otherwise do our own thing with it
182 if (! found) {
183 // ignore it?
184 if (m_assertMode & wxPYAPP_ASSERT_SUPPRESS)
185 return;
186
187 // turn it into a Python exception?
188 if (m_assertMode & wxPYAPP_ASSERT_EXCEPTION) {
189 wxString buf;
190 buf.Alloc(4096);
191 buf.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond, file, line);
192 if (msg != NULL) {
193 buf += wxT(": ");
194 buf += msg;
195 }
196
197 // set the exception
198 wxPyBeginBlockThreads();
199 PyObject* s = wx2PyString(buf);
200 PyErr_SetObject(wxPyAssertionError, s);
201 Py_DECREF(s);
202 wxPyEndBlockThreads();
203
204 // Now when control returns to whatever API wrapper was called from
205 // Python it should detect that an exception is set and will return
206 // NULL, signalling the exception to Python.
207 }
208
209 // Send it to the normal log destination, but only if
210 // not _DIALOG because it will call this too
211 if ( (m_assertMode & wxPYAPP_ASSERT_LOG) && !(m_assertMode & wxPYAPP_ASSERT_DIALOG)) {
212 wxString buf;
213 buf.Alloc(4096);
214 buf.Printf(wxT("%s(%d): assert \"%s\" failed"),
215 file, line, cond);
216 if (msg != NULL) {
217 buf += wxT(": ");
218 buf += msg;
219 }
220 wxLogDebug(buf);
221 }
222
223 // do the normal wx assert dialog?
224 if (m_assertMode & wxPYAPP_ASSERT_DIALOG)
225 wxApp::OnAssert(file, line, cond, msg);
226 }
227 }
228 #endif
229
230
231 /*static*/
232 bool wxPyApp::GetMacDefaultEncodingIsPC() {
233 #ifdef __WXMAC__
234 return s_macDefaultEncodingIsPC;
235 #else
236 return 0;
237 #endif
238 }
239
240 /*static*/
241 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
242 #ifdef __WXMAC__
243 return s_macSupportPCMenuShortcuts;
244 #else
245 return 0;
246 #endif
247 }
248
249 /*static*/
250 long wxPyApp::GetMacAboutMenuItemId() {
251 #ifdef __WXMAC__
252 return s_macAboutMenuItemId;
253 #else
254 return 0;
255 #endif
256 }
257
258 /*static*/
259 long wxPyApp::GetMacPreferencesMenuItemId() {
260 #ifdef __WXMAC__
261 return s_macPreferencesMenuItemId;
262 #else
263 return 0;
264 #endif
265 }
266
267 /*static*/
268 long wxPyApp::GetMacExitMenuItemId() {
269 #ifdef __WXMAC__
270 return s_macExitMenuItemId;
271 #else
272 return 0;
273 #endif
274 }
275
276 /*static*/
277 wxString wxPyApp::GetMacHelpMenuTitleName() {
278 #ifdef __WXMAC__
279 return s_macHelpMenuTitleName;
280 #else
281 return wxEmptyString;
282 #endif
283 }
284
285 /*static*/
286 void wxPyApp::SetMacDefaultEncodingIsPC(bool val) {
287 #ifdef __WXMAC__
288 s_macDefaultEncodingIsPC = val;
289 #endif
290 }
291
292 /*static*/
293 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val) {
294 #ifdef __WXMAC__
295 s_macSupportPCMenuShortcuts = val;
296 #endif
297 }
298
299 /*static*/
300 void wxPyApp::SetMacAboutMenuItemId(long val) {
301 #ifdef __WXMAC__
302 s_macAboutMenuItemId = val;
303 #endif
304 }
305
306 /*static*/
307 void wxPyApp::SetMacPreferencesMenuItemId(long val) {
308 #ifdef __WXMAC__
309 s_macPreferencesMenuItemId = val;
310 #endif
311 }
312
313 /*static*/
314 void wxPyApp::SetMacExitMenuItemId(long val) {
315 #ifdef __WXMAC__
316 s_macExitMenuItemId = val;
317 #endif
318 }
319
320 /*static*/
321 void wxPyApp::SetMacHelpMenuTitleName(const wxString& val) {
322 #ifdef __WXMAC__
323 s_macHelpMenuTitleName = val;
324 #endif
325 }
326
327
328
329 //---------------------------------------------------------------------
330 //----------------------------------------------------------------------
331
332
333 #if 0
334 static char* wxPyCopyCString(const wxChar* src)
335 {
336 wxWX2MBbuf buff = (wxWX2MBbuf)wxConvCurrent->cWX2MB(src);
337 size_t len = strlen(buff);
338 char* dest = new char[len+1];
339 strcpy(dest, buff);
340 return dest;
341 }
342
343 #if wxUSE_UNICODE
344 static char* wxPyCopyCString(const char* src) // we need a char version too
345 {
346 size_t len = strlen(src);
347 char* dest = new char[len+1];
348 strcpy(dest, src);
349 return dest;
350 }
351 #endif
352
353 static wxChar* wxPyCopyWString(const char *src)
354 {
355 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
356 wxString str(src, *wxConvCurrent);
357 return copystring(str);
358 }
359
360 #if wxUSE_UNICODE
361 static wxChar* wxPyCopyWString(const wxChar *src)
362 {
363 return copystring(src);
364 }
365 #endif
366 #endif
367
368
369 //----------------------------------------------------------------------
370
371 // This function is called when the wxc module is imported to do some initial
372 // setup. (Before there is a wxApp object.)
373 void __wxPreStart(PyObject* moduleDict)
374 {
375
376 #ifdef __WXMSW__
377 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
378 #endif
379
380 #ifdef WXP_WITH_THREAD
381 PyEval_InitThreads();
382 wxPyTStates = new wxPyThreadStateArray;
383 wxPyTMutex = new wxMutex;
384 #endif
385
386 // Ensure that the build options in the DLL (or whatever) match this build
387 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "wxPython");
388
389 // Create an exception object to use for wxASSERTions
390 wxPyAssertionError = PyErr_NewException("wxPython.wxc.wxPyAssertionError",
391 PyExc_AssertionError, NULL);
392 PyDict_SetItemString(moduleDict, "wxPyAssertionError", wxPyAssertionError);
393 }
394
395
396
397 // Initialize wxWindows and bootstrap the user application by calling the
398 // wxApp's OnInit, which is a parameter to this funciton. See wxApp.__init__
399 // in _extras.py to learn how the bootstrap is started.
400 PyObject* __wxStart(PyObject* /* self */, PyObject* args)
401 {
402 PyObject* onInitFunc = NULL;
403 PyObject* arglist= NULL;
404 PyObject* result = NULL;
405 PyObject* pyint = NULL;
406 long bResult;
407
408 if (!PyArg_ParseTuple(args, "O", &onInitFunc))
409 return NULL;
410
411 // Get any command-line args passed to this program from the sys module
412 int argc = 0;
413 char** argv = NULL;
414 PyObject* sysargv = PySys_GetObject("argv");
415 if (sysargv != NULL) {
416 argc = PyList_Size(sysargv);
417 argv = new char*[argc+1];
418 int x;
419 for(x=0; x<argc; x++) {
420 PyObject *pyArg = PyList_GetItem(sysargv, x);
421 argv[x] = PyString_AsString(pyArg);
422 }
423 argv[argc] = NULL;
424 }
425
426 if (! wxEntryStart(argc, argv) ) {
427 PyErr_SetString(PyExc_SystemError, // is this the right one?
428 "wxEntryStart failed!");
429 goto error;
430 }
431 delete [] argv;
432
433
434 // The stock objects were all NULL when they were loaded into
435 // SWIG generated proxies, so re-init those now...
436 wxPy_ReinitStockObjects();
437
438
439 // Call the Python wxApp's OnInit function
440 arglist = PyTuple_New(0);
441 result = PyEval_CallObject(onInitFunc, arglist);
442 Py_DECREF(arglist);
443 if (!result) { // an exception was raised.
444 return NULL;
445 }
446
447 pyint = PyNumber_Int(result);
448 if (! pyint) {
449 PyErr_SetString(PyExc_TypeError, "OnInit should return a boolean value");
450 goto error;
451 }
452 bResult = PyInt_AS_LONG(pyint);
453 if (! bResult) {
454 PyErr_SetString(PyExc_SystemExit, "OnInit returned FALSE, exiting...");
455 goto error;
456 }
457
458 #ifdef __WXGTK__
459 wxTheApp->m_initialized = (wxTopLevelWindows.GetCount() > 0);
460 #endif
461
462 Py_DECREF(result);
463 Py_DECREF(pyint);
464 Py_INCREF(Py_None);
465 return Py_None;
466
467 error:
468 Py_XDECREF(result);
469 Py_XDECREF(pyint);
470 return NULL;
471 }
472
473
474
475 void __wxCleanup() {
476 wxPyDoingCleanup = TRUE;
477 if (wxPyDoCleanup)
478 wxEntryCleanup();
479 #ifdef WXP_WITH_THREAD
480 delete wxPyTMutex;
481 wxPyTMutex = NULL;
482 wxPyTStates->Empty();
483 delete wxPyTStates;
484 wxPyTStates = NULL;
485 #endif
486 }
487
488
489
490
491 PyObject* __wxSetDictionary(PyObject* /* self */, PyObject* args)
492 {
493
494 if (!PyArg_ParseTuple(args, "O", &wxPython_dict))
495 return NULL;
496
497 if (!PyDict_Check(wxPython_dict)) {
498 PyErr_SetString(PyExc_TypeError, "_wxSetDictionary must have dictionary object!");
499 return NULL;
500 }
501
502 if (! wxPyPtrTypeMap)
503 wxPyPtrTypeMap = PyDict_New();
504 PyDict_SetItemString(wxPython_dict, "__wxPyPtrTypeMap", wxPyPtrTypeMap);
505
506
507 #ifdef __WXMOTIF__
508 #define wxPlatform "__WXMOTIF__"
509 #endif
510 #ifdef __WXX11__
511 #define wxPlatform "__WXX11__"
512 #endif
513 #ifdef __WXGTK__
514 #define wxPlatform "__WXGTK__"
515 #endif
516 #if defined(__WIN32__) || defined(__WXMSW__)
517 #define wxPlatform "__WXMSW__"
518 #endif
519 #ifdef __WXMAC__
520 #define wxPlatform "__WXMAC__"
521 #endif
522
523 #ifdef __WXDEBUG__
524 int wxdebug = 1;
525 #else
526 int wxdebug = 0;
527 #endif
528
529 PyDict_SetItemString(wxPython_dict, "wxPlatform", PyString_FromString(wxPlatform));
530 PyDict_SetItemString(wxPython_dict, "wxUSE_UNICODE", PyInt_FromLong(wxUSE_UNICODE));
531 PyDict_SetItemString(wxPython_dict, "__WXDEBUG__", PyInt_FromLong(wxdebug));
532
533 Py_INCREF(Py_None);
534 return Py_None;
535 }
536
537
538 //---------------------------------------------------------------------------
539
540 // The stock objects are no longer created when the wxc module is imported, but
541 // only after the app object has been created. This function will be called before
542 // OnInit is called so we can hack the new pointer values into the obj.this attributes.
543
544 void wxPy_ReinitStockObjects()
545 {
546 char ptrbuf[128];
547 PyObject* obj;
548 PyObject* ptrobj;
549
550
551
552 #define REINITOBJ(name, type) \
553 obj = PyDict_GetItemString(wxPython_dict, #name); \
554 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
555 SWIG_MakePtr(ptrbuf, (char *) name, "_" #type "_p"); \
556 ptrobj = PyString_FromString(ptrbuf); \
557 PyObject_SetAttrString(obj, "this", ptrobj); \
558 Py_DECREF(ptrobj)
559
560 #define REINITOBJ2(name, type) \
561 obj = PyDict_GetItemString(wxPython_dict, #name); \
562 wxASSERT_MSG(obj != NULL, wxT("Unable to find stock object for " #name)); \
563 SWIG_MakePtr(ptrbuf, (char *) &name, "_" #type "_p"); \
564 ptrobj = PyString_FromString(ptrbuf); \
565 PyObject_SetAttrString(obj, "this", ptrobj); \
566 Py_DECREF(ptrobj)
567
568
569 REINITOBJ(wxNORMAL_FONT, wxFont);
570 REINITOBJ(wxSMALL_FONT, wxFont);
571 REINITOBJ(wxITALIC_FONT, wxFont);
572 REINITOBJ(wxSWISS_FONT, wxFont);
573
574 REINITOBJ(wxRED_PEN, wxPen);
575 REINITOBJ(wxCYAN_PEN, wxPen);
576 REINITOBJ(wxGREEN_PEN, wxPen);
577 REINITOBJ(wxBLACK_PEN, wxPen);
578 REINITOBJ(wxWHITE_PEN, wxPen);
579 REINITOBJ(wxTRANSPARENT_PEN, wxPen);
580 REINITOBJ(wxBLACK_DASHED_PEN, wxPen);
581 REINITOBJ(wxGREY_PEN, wxPen);
582 REINITOBJ(wxMEDIUM_GREY_PEN, wxPen);
583 REINITOBJ(wxLIGHT_GREY_PEN, wxPen);
584
585 REINITOBJ(wxBLUE_BRUSH, wxBrush);
586 REINITOBJ(wxGREEN_BRUSH, wxBrush);
587 REINITOBJ(wxWHITE_BRUSH, wxBrush);
588 REINITOBJ(wxBLACK_BRUSH, wxBrush);
589 REINITOBJ(wxTRANSPARENT_BRUSH, wxBrush);
590 REINITOBJ(wxCYAN_BRUSH, wxBrush);
591 REINITOBJ(wxRED_BRUSH, wxBrush);
592 REINITOBJ(wxGREY_BRUSH, wxBrush);
593 REINITOBJ(wxMEDIUM_GREY_BRUSH, wxBrush);
594 REINITOBJ(wxLIGHT_GREY_BRUSH, wxBrush);
595
596 REINITOBJ(wxBLACK, wxColour);
597 REINITOBJ(wxWHITE, wxColour);
598 REINITOBJ(wxRED, wxColour);
599 REINITOBJ(wxBLUE, wxColour);
600 REINITOBJ(wxGREEN, wxColour);
601 REINITOBJ(wxCYAN, wxColour);
602 REINITOBJ(wxLIGHT_GREY, wxColour);
603
604 REINITOBJ(wxSTANDARD_CURSOR, wxCursor);
605 REINITOBJ(wxHOURGLASS_CURSOR, wxCursor);
606 REINITOBJ(wxCROSS_CURSOR, wxCursor);
607
608 REINITOBJ2(wxNullBitmap, wxBitmap);
609 REINITOBJ2(wxNullIcon, wxIcon);
610 REINITOBJ2(wxNullCursor, wxCursor);
611 REINITOBJ2(wxNullPen, wxPen);
612 REINITOBJ2(wxNullBrush, wxBrush);
613 REINITOBJ2(wxNullPalette, wxPalette);
614 REINITOBJ2(wxNullFont, wxFont);
615 REINITOBJ2(wxNullColour, wxColour);
616
617 REINITOBJ(wxTheFontList, wxFontList);
618 REINITOBJ(wxThePenList, wxPenList);
619 REINITOBJ(wxTheBrushList, wxBrushList);
620 REINITOBJ(wxTheColourDatabase, wxColourDatabase);
621
622
623 REINITOBJ(wxTheClipboard, wxClipboard);
624 REINITOBJ(wxTheMimeTypesManager, wxMimeTypesManager);
625 REINITOBJ2(wxDefaultValidator, wxValidator);
626 REINITOBJ2(wxNullImage, wxImage);
627 REINITOBJ2(wxNullAcceleratorTable, wxAcceleratorTable);
628
629 #undef REINITOBJ
630 #undef REINITOBJ2
631 }
632
633 //---------------------------------------------------------------------------
634
635 void wxPyClientData_dtor(wxPyClientData* self) {
636 if (! wxPyDoingCleanup) { // Don't do it during cleanup as Python
637 // may have already garbage collected the object...
638 wxPyBeginBlockThreads();
639 Py_DECREF(self->m_obj);
640 wxPyEndBlockThreads();
641 }
642 }
643
644 void wxPyUserData_dtor(wxPyUserData* self) {
645 if (! wxPyDoingCleanup) {
646 wxPyBeginBlockThreads();
647 Py_DECREF(self->m_obj);
648 wxPyEndBlockThreads();
649 }
650 }
651
652
653 // This is called when an OOR controled object is being destroyed. Although
654 // the C++ object is going away there is no way to force the Python object
655 // (and all references to it) to die too. This causes problems (crashes) in
656 // wxPython when a python shadow object attempts to call a C++ method using
657 // the now bogus pointer... So to try and prevent this we'll do a little black
658 // magic and change the class of the python instance to a class that will
659 // raise an exception for any attempt to call methods with it. See
660 // _wxPyDeadObject in _extras.py for the implementation of this class.
661 void wxPyOORClientData_dtor(wxPyOORClientData* self) {
662
663 static PyObject* deadObjectClass = NULL;
664
665 wxPyBeginBlockThreads();
666 if (deadObjectClass == NULL) {
667 deadObjectClass = PyDict_GetItemString(wxPython_dict, "_wxPyDeadObject");
668 wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
669 Py_INCREF(deadObjectClass);
670 }
671
672
673 // Only if there is more than one reference to the object
674 if ( !wxPyDoingCleanup && self->m_obj->ob_refcnt > 1 ) {
675 wxASSERT_MSG(PyInstance_Check(self->m_obj), wxT("m_obj not an instance!?!?!"));
676
677 // Call __del__, if there is one.
678 PyObject* func = PyObject_GetAttrString(self->m_obj, "__del__");
679 if (func) {
680 PyObject* rv = PyObject_CallMethod(self->m_obj, "__del__", NULL);
681 Py_XDECREF(rv);
682 Py_DECREF(func);
683 }
684 if (PyErr_Occurred())
685 PyErr_Clear(); // just ignore it for now
686
687 // Clear the instance's dictionary
688 PyInstanceObject* inst = (PyInstanceObject*)self->m_obj;
689 PyDict_Clear(inst->in_dict);
690
691 // put the name of the old class into the instance, and then reset the
692 // class to be the dead class.
693 PyDict_SetItemString(inst->in_dict, "_name", inst->in_class->cl_name);
694 inst->in_class = (PyClassObject*)deadObjectClass;
695 Py_INCREF(deadObjectClass);
696 }
697
698 // m_obj is DECREF's in the base class dtor...
699 wxPyEndBlockThreads();
700 }
701
702
703 //---------------------------------------------------------------------------
704 // Stuff used by OOR to find the right wxPython class type to return and to
705 // build it.
706
707
708 // The pointer type map is used when the "pointer" type name generated by SWIG
709 // is not the same as the shadow class name, for example wxPyTreeCtrl
710 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
711 // so we'll just make it a Python dictionary in the wx module's namespace.
712 // (See __wxSetDictionary)
713 void wxPyPtrTypeMap_Add(const char* commonName, const char* ptrName) {
714 if (! wxPyPtrTypeMap)
715 wxPyPtrTypeMap = PyDict_New();
716 PyDict_SetItemString(wxPyPtrTypeMap,
717 (char*)commonName,
718 PyString_FromString((char*)ptrName));
719 }
720
721
722
723 PyObject* wxPyClassExists(const wxString& className) {
724
725 PyObject* item;
726 wxString name(className);
727 char buff[64]; // should always be big enough...
728
729 if (!className)
730 return NULL;
731
732 // Try the name as-is first
733 sprintf(buff, "%sPtr", (const char*)name.mbc_str());
734 PyObject* classobj = PyDict_GetItemString(wxPython_dict, buff);
735
736 // if not found see if there is a mapped name for it
737 if ( ! classobj) {
738 if ((item = PyDict_GetItemString(wxPyPtrTypeMap, (char*)(const char*)name.mbc_str())) != NULL) {
739 name = wxString(PyString_AsString(item), *wxConvCurrent);
740 sprintf(buff, "%sPtr", (const char*)name.mbc_str());
741 classobj = PyDict_GetItemString(wxPython_dict, buff);
742 }
743 }
744
745 return classobj; // returns NULL if not found
746 }
747
748
749 PyObject* wxPyMake_wxObject(wxObject* source, bool checkEvtHandler) {
750 PyObject* target = NULL;
751 bool isEvtHandler = FALSE;
752
753 if (source) {
754 // If it's derived from wxEvtHandler then there may
755 // already be a pointer to a Python object that we can use
756 // in the OOR data.
757 if (checkEvtHandler && wxIsKindOf(source, wxEvtHandler)) {
758 isEvtHandler = TRUE;
759 wxEvtHandler* eh = (wxEvtHandler*)source;
760 wxPyOORClientData* data = (wxPyOORClientData*)eh->GetClientObject();
761 if (data) {
762 target = data->m_obj;
763 Py_INCREF(target);
764 }
765 }
766
767 if (! target) {
768 // Otherwise make it the old fashioned way by making a
769 // new shadow object and putting this pointer in it.
770 wxClassInfo* info = source->GetClassInfo();
771 wxString name = info->GetClassName();
772 PyObject* klass = wxPyClassExists(name);
773 while (info && !klass) {
774 name = (wxChar*)info->GetBaseClassName1();
775 info = wxClassInfo::FindClass(name);
776 klass = wxPyClassExists(name);
777 }
778 if (info) {
779 target = wxPyConstructObject(source, name, klass, FALSE);
780 if (target && isEvtHandler)
781 ((wxEvtHandler*)source)->SetClientObject(new wxPyOORClientData(target));
782 } else {
783 wxString msg(wxT("wxPython class not found for "));
784 msg += source->GetClassInfo()->GetClassName();
785 PyErr_SetString(PyExc_NameError, msg.mbc_str());
786 target = NULL;
787 }
788 }
789 } else { // source was NULL so return None.
790 Py_INCREF(Py_None); target = Py_None;
791 }
792 return target;
793 }
794
795
796 PyObject* wxPyMake_wxSizer(wxSizer* source) {
797 PyObject* target = NULL;
798
799 if (source && wxIsKindOf(source, wxSizer)) {
800 // If it's derived from wxSizer then there may
801 // already be a pointer to a Python object that we can use
802 // in the OOR data.
803 wxSizer* sz = (wxSizer*)source;
804 wxPyOORClientData* data = (wxPyOORClientData*)sz->GetClientObject();
805 if (data) {
806 target = data->m_obj;
807 Py_INCREF(target);
808 }
809 }
810 if (! target) {
811 target = wxPyMake_wxObject(source, FALSE);
812 if (target != Py_None)
813 ((wxSizer*)source)->SetClientObject(new wxPyOORClientData(target));
814 }
815 return target;
816 }
817
818
819
820 //---------------------------------------------------------------------------
821
822 PyObject* wxPyConstructObject(void* ptr,
823 const wxString& className,
824 PyObject* klass,
825 int setThisOwn) {
826
827 PyObject* obj;
828 PyObject* arg;
829 PyObject* item;
830 wxString name(className);
831 char swigptr[64]; // should always be big enough...
832 char buff[64];
833
834 if ((item = PyDict_GetItemString(wxPyPtrTypeMap, (char*)(const char*)name.mbc_str())) != NULL) {
835 name = wxString(PyString_AsString(item), *wxConvCurrent);
836 }
837 sprintf(buff, "_%s_p", (const char*)name.mbc_str());
838 SWIG_MakePtr(swigptr, ptr, buff);
839
840 arg = Py_BuildValue("(s)", swigptr);
841 obj = PyInstance_New(klass, arg, NULL);
842 Py_DECREF(arg);
843
844 if (setThisOwn) {
845 PyObject* one = PyInt_FromLong(1);
846 PyObject_SetAttrString(obj, "thisown", one);
847 Py_DECREF(one);
848 }
849
850 return obj;
851 }
852
853
854 PyObject* wxPyConstructObject(void* ptr,
855 const wxString& className,
856 int setThisOwn) {
857 if (!ptr) {
858 Py_INCREF(Py_None);
859 return Py_None;
860 }
861
862 char buff[64]; // should always be big enough...
863 sprintf(buff, "%sPtr", (const char*)className.mbc_str());
864
865 wxASSERT_MSG(wxPython_dict, wxT("wxPython_dict is not set yet!!"));
866
867 PyObject* classobj = PyDict_GetItemString(wxPython_dict, buff);
868 if (! classobj) {
869 wxString msg(wxT("wxPython class not found for "));
870 msg += className;
871 PyErr_SetString(PyExc_NameError, msg.mbc_str());
872 return NULL;
873 }
874
875 return wxPyConstructObject(ptr, className, classobj, setThisOwn);
876 }
877
878
879 //---------------------------------------------------------------------------
880
881
882 #ifdef WXP_WITH_THREAD
883 inline
884 unsigned long wxPyGetCurrentThreadId() {
885 return wxThread::GetCurrentId();
886 }
887
888 static PyThreadState* gs_shutdownTState;
889 static
890 PyThreadState* wxPyGetThreadState() {
891 if (wxPyTMutex == NULL) // Python is shutting down...
892 return gs_shutdownTState;
893
894 unsigned long ctid = wxPyGetCurrentThreadId();
895 PyThreadState* tstate = NULL;
896
897 wxPyTMutex->Lock();
898 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
899 wxPyThreadState& info = wxPyTStates->Item(i);
900 if (info.tid == ctid) {
901 tstate = info.tstate;
902 break;
903 }
904 }
905 wxPyTMutex->Unlock();
906 wxASSERT_MSG(tstate, wxT("PyThreadState should not be NULL!"));
907 return tstate;
908 }
909
910 static
911 void wxPySaveThreadState(PyThreadState* tstate) {
912 if (wxPyTMutex == NULL) { // Python is shutting down, assume a single thread...
913 gs_shutdownTState = tstate;
914 return;
915 }
916 unsigned long ctid = wxPyGetCurrentThreadId();
917 wxPyTMutex->Lock();
918 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
919 wxPyThreadState& info = wxPyTStates->Item(i);
920 if (info.tid == ctid) {
921 #if 0
922 if (info.tstate != tstate)
923 wxLogMessage("*** tstate mismatch!???");
924 #endif
925 // info.tstate = tstate; *** DO NOT update existing ones???
926 // Normally it will never change, but apparently COM callbacks
927 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
928 // tstate which will then be garbage the next time we try to use
929 // it...
930 wxPyTMutex->Unlock();
931 return;
932 }
933 }
934 // not found, so add it...
935 wxPyTStates->Add(new wxPyThreadState(ctid, tstate));
936 wxPyTMutex->Unlock();
937 }
938
939 #endif
940
941
942 // Calls from Python to wxWindows code are wrapped in calls to these
943 // functions:
944
945 PyThreadState* wxPyBeginAllowThreads() {
946 #ifdef WXP_WITH_THREAD
947 PyThreadState* saved = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
948 wxPySaveThreadState(saved);
949 return saved;
950 #else
951 return NULL;
952 #endif
953 }
954
955 void wxPyEndAllowThreads(PyThreadState* saved) {
956 #ifdef WXP_WITH_THREAD
957 PyEval_RestoreThread(saved); // Py_END_ALLOW_THREADS;
958 #endif
959 }
960
961
962
963 // Calls from wxWindows back to Python code, or even any PyObject
964 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
965
966 void wxPyBeginBlockThreads() {
967 #ifdef WXP_WITH_THREAD
968 PyThreadState* tstate = wxPyGetThreadState();
969 PyEval_RestoreThread(tstate);
970 #endif
971 }
972
973
974 void wxPyEndBlockThreads() {
975 #ifdef WXP_WITH_THREAD
976 // Is there any need to save it again?
977 // PyThreadState* tstate =
978 PyEval_SaveThread();
979 #endif
980 }
981
982
983 //---------------------------------------------------------------------------
984 // wxPyInputStream and wxPyCBInputStream methods
985
986
987 void wxPyInputStream::close() {
988 /* do nothing for now */
989 }
990
991 void wxPyInputStream::flush() {
992 /* do nothing for now */
993 }
994
995 bool wxPyInputStream::eof() {
996 if (m_wxis)
997 return m_wxis->Eof();
998 else
999 return TRUE;
1000 }
1001
1002 wxPyInputStream::~wxPyInputStream() {
1003 /* do nothing */
1004 }
1005
1006
1007
1008
1009 PyObject* wxPyInputStream::read(int size) {
1010 PyObject* obj = NULL;
1011 wxMemoryBuffer buf;
1012 const int BUFSIZE = 1024;
1013
1014 // check if we have a real wxInputStream to work with
1015 if (!m_wxis) {
1016 wxPyBeginBlockThreads();
1017 PyErr_SetString(PyExc_IOError, "no valid C-wxInputStream");
1018 wxPyEndBlockThreads();
1019 return NULL;
1020 }
1021
1022 if (size < 0) {
1023 // read while bytes are available on the stream
1024 while ( m_wxis->CanRead() ) {
1025 m_wxis->Read(buf.GetAppendBuf(BUFSIZE), BUFSIZE);
1026 buf.UngetAppendBuf(m_wxis->LastRead());
1027 }
1028
1029 } else { // Read only size number of characters
1030 m_wxis->Read(buf.GetWriteBuf(size), size);
1031 buf.UngetWriteBuf(m_wxis->LastRead());
1032 }
1033
1034 // error check
1035 wxPyBeginBlockThreads();
1036 wxStreamError err = m_wxis->GetLastError();
1037 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1038 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1039 }
1040 else {
1041 // We use only strings for the streams, not unicode
1042 obj = PyString_FromStringAndSize(buf, buf.GetDataLen());
1043 }
1044 wxPyEndBlockThreads();
1045 return obj;
1046 }
1047
1048
1049 PyObject* wxPyInputStream::readline(int size) {
1050 PyObject* obj = NULL;
1051 wxMemoryBuffer buf;
1052 int i;
1053 char ch;
1054
1055 // check if we have a real wxInputStream to work with
1056 if (!m_wxis) {
1057 wxPyBeginBlockThreads();
1058 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1059 wxPyEndBlockThreads();
1060 return NULL;
1061 }
1062
1063 // read until \n or byte limit reached
1064 for (i=ch=0; (ch != '\n') && (m_wxis->CanRead()) && ((size < 0) || (i < size)); i++) {
1065 ch = m_wxis->GetC();
1066 buf.AppendByte(ch);
1067 }
1068
1069 // errorcheck
1070 wxPyBeginBlockThreads();
1071 wxStreamError err = m_wxis->GetLastError();
1072 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1073 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1074 }
1075 else {
1076 // We use only strings for the streams, not unicode
1077 obj = PyString_FromStringAndSize((char*)buf.GetData(), buf.GetDataLen());
1078 }
1079 wxPyEndBlockThreads();
1080 return obj;
1081 }
1082
1083
1084 PyObject* wxPyInputStream::readlines(int sizehint) {
1085 PyObject* pylist;
1086
1087 // check if we have a real wxInputStream to work with
1088 if (!m_wxis) {
1089 wxPyBeginBlockThreads();
1090 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1091 wxPyEndBlockThreads();
1092 return NULL;
1093 }
1094
1095 // init list
1096 wxPyBeginBlockThreads();
1097 pylist = PyList_New(0);
1098 if (!pylist) {
1099 wxPyBeginBlockThreads();
1100 PyErr_NoMemory();
1101 wxPyEndBlockThreads();
1102 return NULL;
1103 }
1104
1105 // read sizehint bytes or until EOF
1106 int i;
1107 for (i=0; (m_wxis->CanRead()) && ((sizehint < 0) || (i < sizehint));) {
1108 PyObject* s = this->readline();
1109 if (s == NULL) {
1110 wxPyBeginBlockThreads();
1111 Py_DECREF(pylist);
1112 wxPyEndBlockThreads();
1113 return NULL;
1114 }
1115 wxPyBeginBlockThreads();
1116 PyList_Append(pylist, s);
1117 i += PyString_Size(s);
1118 wxPyEndBlockThreads();
1119 }
1120
1121 // error check
1122 wxStreamError err = m_wxis->GetLastError();
1123 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1124 wxPyBeginBlockThreads();
1125 Py_DECREF(pylist);
1126 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1127 wxPyEndBlockThreads();
1128 return NULL;
1129 }
1130
1131 return pylist;
1132 }
1133
1134
1135 void wxPyInputStream::seek(int offset, int whence) {
1136 if (m_wxis)
1137 m_wxis->SeekI(offset, wxSeekMode(whence));
1138 }
1139
1140 int wxPyInputStream::tell(){
1141 if (m_wxis)
1142 return m_wxis->TellI();
1143 else return 0;
1144 }
1145
1146
1147
1148
1149 wxPyCBInputStream::wxPyCBInputStream(PyObject *r, PyObject *s, PyObject *t, bool block)
1150 : wxInputStream(), m_read(r), m_seek(s), m_tell(t), m_block(block)
1151 {}
1152
1153
1154 wxPyCBInputStream::~wxPyCBInputStream() {
1155 if (m_block) wxPyBeginBlockThreads();
1156 Py_XDECREF(m_read);
1157 Py_XDECREF(m_seek);
1158 Py_XDECREF(m_tell);
1159 if (m_block) wxPyEndBlockThreads();
1160 }
1161
1162
1163 wxPyCBInputStream* wxPyCBInputStream::create(PyObject *py, bool block) {
1164 if (block) wxPyBeginBlockThreads();
1165
1166 PyObject* read = getMethod(py, "read");
1167 PyObject* seek = getMethod(py, "seek");
1168 PyObject* tell = getMethod(py, "tell");
1169
1170 if (!read) {
1171 PyErr_SetString(PyExc_TypeError, "Not a file-like object");
1172 Py_XDECREF(read);
1173 Py_XDECREF(seek);
1174 Py_XDECREF(tell);
1175 if (block) wxPyEndBlockThreads();
1176 return NULL;
1177 }
1178
1179 if (block) wxPyEndBlockThreads();
1180 return new wxPyCBInputStream(read, seek, tell, block);
1181 }
1182
1183
1184 wxPyCBInputStream* wxPyCBInputStream_create(PyObject *py, bool block) {
1185 return wxPyCBInputStream::create(py, block);
1186 }
1187
1188 PyObject* wxPyCBInputStream::getMethod(PyObject* py, char* name) {
1189 if (!PyObject_HasAttrString(py, name))
1190 return NULL;
1191 PyObject* o = PyObject_GetAttrString(py, name);
1192 if (!PyMethod_Check(o) && !PyCFunction_Check(o)) {
1193 Py_DECREF(o);
1194 return NULL;
1195 }
1196 return o;
1197 }
1198
1199
1200 size_t wxPyCBInputStream::GetSize() const {
1201 wxPyCBInputStream* self = (wxPyCBInputStream*)this; // cast off const
1202 if (m_seek && m_tell) {
1203 off_t temp = self->OnSysTell();
1204 off_t ret = self->OnSysSeek(0, wxFromEnd);
1205 self->OnSysSeek(temp, wxFromStart);
1206 return ret;
1207 }
1208 else
1209 return 0;
1210 }
1211
1212
1213 size_t wxPyCBInputStream::OnSysRead(void *buffer, size_t bufsize) {
1214 if (bufsize == 0)
1215 return 0;
1216
1217 wxPyBeginBlockThreads();
1218 PyObject* arglist = Py_BuildValue("(i)", bufsize);
1219 PyObject* result = PyEval_CallObject(m_read, arglist);
1220 Py_DECREF(arglist);
1221
1222 size_t o = 0;
1223 if ((result != NULL) && PyString_Check(result)) {
1224 o = PyString_Size(result);
1225 if (o == 0)
1226 m_lasterror = wxSTREAM_EOF;
1227 if (o > bufsize)
1228 o = bufsize;
1229 memcpy((char*)buffer, PyString_AsString(result), o); // strings only, not unicode...
1230 Py_DECREF(result);
1231
1232 }
1233 else
1234 m_lasterror = wxSTREAM_READ_ERROR;
1235 wxPyEndBlockThreads();
1236 return o;
1237 }
1238
1239 size_t wxPyCBInputStream::OnSysWrite(const void *buffer, size_t bufsize) {
1240 m_lasterror = wxSTREAM_WRITE_ERROR;
1241 return 0;
1242 }
1243
1244 off_t wxPyCBInputStream::OnSysSeek(off_t off, wxSeekMode mode) {
1245 wxPyBeginBlockThreads();
1246 #ifdef _LARGE_FILES
1247 // off_t is a 64-bit value...
1248 PyObject* arglist = Py_BuildValue("(Li)", off, mode);
1249 #else
1250 PyObject* arglist = Py_BuildValue("(ii)", off, mode);
1251 #endif
1252 PyObject* result = PyEval_CallObject(m_seek, arglist);
1253 Py_DECREF(arglist);
1254 Py_XDECREF(result);
1255 wxPyEndBlockThreads();
1256 return OnSysTell();
1257 }
1258
1259
1260 off_t wxPyCBInputStream::OnSysTell() const {
1261 wxPyBeginBlockThreads();
1262 PyObject* arglist = Py_BuildValue("()");
1263 PyObject* result = PyEval_CallObject(m_tell, arglist);
1264 Py_DECREF(arglist);
1265 off_t o = 0;
1266 if (result != NULL) {
1267 #ifdef _LARGE_FILES
1268 if (PyLong_Check(result))
1269 o = PyLong_AsLongLong(result);
1270 else
1271 #else
1272 o = PyInt_AsLong(result);
1273 #endif
1274 Py_DECREF(result);
1275 };
1276 wxPyEndBlockThreads();
1277 return o;
1278 }
1279
1280 //----------------------------------------------------------------------
1281
1282 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback, wxObject);
1283
1284 wxPyCallback::wxPyCallback(PyObject* func) {
1285 m_func = func;
1286 Py_INCREF(m_func);
1287 }
1288
1289 wxPyCallback::wxPyCallback(const wxPyCallback& other) {
1290 m_func = other.m_func;
1291 Py_INCREF(m_func);
1292 }
1293
1294 wxPyCallback::~wxPyCallback() {
1295 wxPyBeginBlockThreads();
1296 Py_DECREF(m_func);
1297 wxPyEndBlockThreads();
1298 }
1299
1300
1301
1302 // This function is used for all events destined for Python event handlers.
1303 void wxPyCallback::EventThunker(wxEvent& event) {
1304 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
1305 PyObject* func = cb->m_func;
1306 PyObject* result;
1307 PyObject* arg;
1308 PyObject* tuple;
1309 bool checkSkip = FALSE;
1310
1311 wxPyBeginBlockThreads();
1312 wxString className = event.GetClassInfo()->GetClassName();
1313
1314 // If the event is one of these types then pass the original
1315 // event object instead of the one passed to us.
1316 if ( className == wxT("wxPyEvent") ) {
1317 arg = ((wxPyEvent*)&event)->GetSelf();
1318 checkSkip = ((wxPyEvent*)&event)->GetCloned();
1319 }
1320 else if ( className == wxT("wxPyCommandEvent") ) {
1321 arg = ((wxPyCommandEvent*)&event)->GetSelf();
1322 checkSkip = ((wxPyCommandEvent*)&event)->GetCloned();
1323 }
1324 else {
1325 arg = wxPyConstructObject((void*)&event, className);
1326 }
1327
1328 // Call the event handler, passing the event object
1329 tuple = PyTuple_New(1);
1330 PyTuple_SET_ITEM(tuple, 0, arg); // steals ref to arg
1331 result = PyEval_CallObject(func, tuple);
1332 if ( result ) {
1333 Py_DECREF(result); // result is ignored, but we still need to decref it
1334 PyErr_Clear(); // Just in case...
1335 } else {
1336 PyErr_Print();
1337 }
1338
1339 if ( checkSkip ) {
1340 // if the event object was one of our special types and
1341 // it had been cloned, then we need to extract the Skipped
1342 // value from the original and set it in the clone.
1343 result = PyObject_CallMethod(arg, "GetSkipped", "");
1344 if ( result ) {
1345 event.Skip(PyInt_AsLong(result));
1346 Py_DECREF(result);
1347 } else {
1348 PyErr_Print();
1349 }
1350 }
1351
1352 Py_DECREF(tuple);
1353 wxPyEndBlockThreads();
1354 }
1355
1356
1357 //----------------------------------------------------------------------
1358
1359 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper& other) {
1360 m_lastFound = NULL;
1361 m_self = other.m_self;
1362 m_class = other.m_class;
1363 if (m_self) {
1364 Py_INCREF(m_self);
1365 Py_INCREF(m_class);
1366 }
1367 }
1368
1369
1370 void wxPyCallbackHelper::setSelf(PyObject* self, PyObject* klass, int incref) {
1371 m_self = self;
1372 m_class = klass;
1373 m_incRef = incref;
1374 if (incref) {
1375 Py_INCREF(m_self);
1376 Py_INCREF(m_class);
1377 }
1378 }
1379
1380
1381 #if PYTHON_API_VERSION >= 1011
1382
1383 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1384 // in which the method was defined. Starting with 2.2 it returns
1385 // "class that asked for the method" which seems totally bogus to me
1386 // but apprently it fixes some obscure problem waiting to happen in
1387 // Python. Since the API was not documented Guido and the gang felt
1388 // safe in changing it. Needless to say that totally screwed up the
1389 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1390 // code to find the class where the method is actually defined...
1391
1392 static
1393 PyObject* PyFindClassWithAttr(PyObject *klass, PyObject *name)
1394 {
1395 int i, n;
1396
1397 if (PyType_Check(klass)) { // new style classes
1398 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1399 // (TODO: This part is not tested yet, so I'm not sure it is correct...)
1400 PyTypeObject* type = (PyTypeObject*)klass;
1401 PyObject *mro, *res, *base, *dict;
1402 /* Look in tp_dict of types in MRO */
1403 mro = type->tp_mro;
1404 assert(PyTuple_Check(mro));
1405 n = PyTuple_GET_SIZE(mro);
1406 for (i = 0; i < n; i++) {
1407 base = PyTuple_GET_ITEM(mro, i);
1408 if (PyClass_Check(base))
1409 dict = ((PyClassObject *)base)->cl_dict;
1410 else {
1411 assert(PyType_Check(base));
1412 dict = ((PyTypeObject *)base)->tp_dict;
1413 }
1414 assert(dict && PyDict_Check(dict));
1415 res = PyDict_GetItem(dict, name);
1416 if (res != NULL)
1417 return base;
1418 }
1419 return NULL;
1420 }
1421
1422 else if (PyClass_Check(klass)) { // old style classes
1423 // This code is borrowed/adapted from class_lookup in classobject.c
1424 PyClassObject* cp = (PyClassObject*)klass;
1425 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
1426 if (value != NULL) {
1427 return (PyObject*)cp;
1428 }
1429 n = PyTuple_Size(cp->cl_bases);
1430 for (i = 0; i < n; i++) {
1431 PyObject* base = PyTuple_GetItem(cp->cl_bases, i);
1432 PyObject *v = PyFindClassWithAttr(base, name);
1433 if (v != NULL)
1434 return v;
1435 }
1436 return NULL;
1437 }
1438 return NULL;
1439 }
1440 #endif
1441
1442
1443 static
1444 PyObject* PyMethod_GetDefiningClass(PyObject* method, const char* name)
1445 {
1446 PyObject* mgc = PyMethod_GET_CLASS(method);
1447
1448 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1449 return mgc;
1450 #else // 2.2 and after, the hard way...
1451
1452 PyObject* nameo = PyString_FromString(name);
1453 PyObject* klass = PyFindClassWithAttr(mgc, nameo);
1454 Py_DECREF(nameo);
1455 return klass;
1456 #endif
1457 }
1458
1459
1460
1461 bool wxPyCallbackHelper::findCallback(const char* name) const {
1462 wxPyCallbackHelper* self = (wxPyCallbackHelper*)this; // cast away const
1463 self->m_lastFound = NULL;
1464
1465 // If the object (m_self) has an attibute of the given name...
1466 if (m_self && PyObject_HasAttrString(m_self, (char*)name)) {
1467 PyObject *method, *klass;
1468 method = PyObject_GetAttrString(m_self, (char*)name);
1469
1470 // ...and if that attribute is a method, and if that method's class is
1471 // not from a base class...
1472 if (PyMethod_Check(method) &&
1473 (klass = PyMethod_GetDefiningClass(method, (char*)name)) != NULL &&
1474 ((klass == m_class) || PyClass_IsSubclass(klass, m_class))) {
1475
1476 // ...then we'll save a pointer to the method so callCallback can call it.
1477 self->m_lastFound = method;
1478 }
1479 else {
1480 Py_DECREF(method);
1481 }
1482 }
1483 return m_lastFound != NULL;
1484 }
1485
1486
1487 int wxPyCallbackHelper::callCallback(PyObject* argTuple) const {
1488 PyObject* result;
1489 int retval = FALSE;
1490
1491 result = callCallbackObj(argTuple);
1492 if (result) { // Assumes an integer return type...
1493 retval = PyInt_AsLong(result);
1494 Py_DECREF(result);
1495 PyErr_Clear(); // forget about it if it's not...
1496 }
1497 return retval;
1498 }
1499
1500 // Invoke the Python callable object, returning the raw PyObject return
1501 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
1502 PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) const {
1503 PyObject* result;
1504
1505 // Save a copy of the pointer in case the callback generates another
1506 // callback. In that case m_lastFound will have a different value when
1507 // it gets back here...
1508 PyObject* method = m_lastFound;
1509
1510 result = PyEval_CallObject(method, argTuple);
1511 Py_DECREF(argTuple);
1512 Py_DECREF(method);
1513 if (!result) {
1514 PyErr_Print();
1515 }
1516 return result;
1517 }
1518
1519
1520 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper& cbh, PyObject* self, PyObject* klass, int incref) {
1521 cbh.setSelf(self, klass, incref);
1522 }
1523
1524 bool wxPyCBH_findCallback(const wxPyCallbackHelper& cbh, const char* name) {
1525 return cbh.findCallback(name);
1526 }
1527
1528 int wxPyCBH_callCallback(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1529 return cbh.callCallback(argTuple);
1530 }
1531
1532 PyObject* wxPyCBH_callCallbackObj(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1533 return cbh.callCallbackObj(argTuple);
1534 }
1535
1536
1537 void wxPyCBH_delete(wxPyCallbackHelper* cbh) {
1538 if (cbh->m_incRef) {
1539 wxPyBeginBlockThreads();
1540 Py_XDECREF(cbh->m_self);
1541 Py_XDECREF(cbh->m_class);
1542 wxPyEndBlockThreads();
1543 }
1544 }
1545
1546 //---------------------------------------------------------------------------
1547 //---------------------------------------------------------------------------
1548 // These event classes can be derived from in Python and passed through the event
1549 // system without losing anything. They do this by keeping a reference to
1550 // themselves and some special case handling in wxPyCallback::EventThunker.
1551
1552
1553 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1554 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1555 //Py_INCREF(m_self); // circular loops...
1556 m_cloned = FALSE;
1557 }
1558
1559 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1560 wxPyBeginBlockThreads();
1561 if (m_cloned)
1562 Py_DECREF(m_self);
1563 wxPyEndBlockThreads();
1564 }
1565
1566 void wxPyEvtSelfRef::SetSelf(PyObject* self, bool clone) {
1567 wxPyBeginBlockThreads();
1568 if (m_cloned)
1569 Py_DECREF(m_self);
1570 m_self = self;
1571 if (clone) {
1572 Py_INCREF(m_self);
1573 m_cloned = TRUE;
1574 }
1575 wxPyEndBlockThreads();
1576 }
1577
1578 PyObject* wxPyEvtSelfRef::GetSelf() const {
1579 Py_INCREF(m_self);
1580 return m_self;
1581 }
1582
1583
1584 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent, wxEvent);
1585 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent, wxCommandEvent);
1586
1587
1588 wxPyEvent::wxPyEvent(int winid, wxEventType commandType)
1589 : wxEvent(winid, commandType) {
1590 }
1591
1592
1593 wxPyEvent::wxPyEvent(const wxPyEvent& evt)
1594 : wxEvent(evt)
1595 {
1596 SetSelf(evt.m_self, TRUE);
1597 }
1598
1599
1600 wxPyEvent::~wxPyEvent() {
1601 }
1602
1603
1604 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType, int id)
1605 : wxCommandEvent(commandType, id) {
1606 }
1607
1608
1609 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent& evt)
1610 : wxCommandEvent(evt)
1611 {
1612 SetSelf(evt.m_self, TRUE);
1613 }
1614
1615
1616 wxPyCommandEvent::~wxPyCommandEvent() {
1617 }
1618
1619
1620
1621
1622 //---------------------------------------------------------------------------
1623 //---------------------------------------------------------------------------
1624
1625
1626 wxPyTimer::wxPyTimer(PyObject* callback) {
1627 func = callback;
1628 Py_INCREF(func);
1629 }
1630
1631 wxPyTimer::~wxPyTimer() {
1632 wxPyBeginBlockThreads();
1633 Py_DECREF(func);
1634 wxPyEndBlockThreads();
1635 }
1636
1637 void wxPyTimer::Notify() {
1638 if (!func || func == Py_None) {
1639 wxTimer::Notify();
1640 }
1641 else {
1642 wxPyBeginBlockThreads();
1643
1644 PyObject* result;
1645 PyObject* args = Py_BuildValue("()");
1646
1647 result = PyEval_CallObject(func, args);
1648 Py_DECREF(args);
1649 if (result) {
1650 Py_DECREF(result);
1651 PyErr_Clear();
1652 } else {
1653 PyErr_Print();
1654 }
1655
1656 wxPyEndBlockThreads();
1657 }
1658 }
1659
1660
1661
1662 //---------------------------------------------------------------------------
1663 //---------------------------------------------------------------------------
1664 // Convert a wxList to a Python List
1665
1666 PyObject* wxPy_ConvertList(wxListBase* listbase, const char* className) {
1667 wxList* list = (wxList*)listbase; // this is probably bad...
1668 PyObject* pyList;
1669 PyObject* pyObj;
1670 wxObject* wxObj;
1671 wxNode* node = list->GetFirst();
1672
1673 wxPyBeginBlockThreads();
1674 pyList = PyList_New(0);
1675 while (node) {
1676 wxObj = node->GetData();
1677 pyObj = wxPyMake_wxObject(wxObj); //wxPyConstructObject(wxObj, className);
1678 PyList_Append(pyList, pyObj);
1679 node = node->GetNext();
1680 }
1681 wxPyEndBlockThreads();
1682 return pyList;
1683 }
1684
1685 //----------------------------------------------------------------------
1686
1687 long wxPyGetWinHandle(wxWindow* win) {
1688 #ifdef __WXMSW__
1689 return (long)win->GetHandle();
1690 #endif
1691
1692 // Find and return the actual X-Window.
1693 #ifdef __WXGTK__
1694 if (win->m_wxwindow) {
1695 #ifdef __WXGTK20__
1696 return (long) GDK_WINDOW_XWINDOW(GTK_PIZZA(win->m_wxwindow)->bin_window);
1697 #else
1698 GdkWindowPrivate* bwin = (GdkWindowPrivate*)GTK_PIZZA(win->m_wxwindow)->bin_window;
1699 if (bwin) {
1700 return (long)bwin->xwindow;
1701 }
1702 #endif
1703 }
1704 #endif
1705 return 0;
1706 }
1707
1708 //----------------------------------------------------------------------
1709 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1710 // included in every file over and over again...
1711
1712 #if PYTHON_API_VERSION >= 1009
1713 static char* wxStringErrorMsg = "String or Unicode type required";
1714 #else
1715 static char* wxStringErrorMsg = "String type required";
1716 #endif
1717
1718
1719 wxString* wxString_in_helper(PyObject* source) {
1720 wxString* target;
1721 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1722 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1723 PyErr_SetString(PyExc_TypeError, wxStringErrorMsg);
1724 return NULL;
1725 }
1726 #if wxUSE_UNICODE
1727 if (PyUnicode_Check(source)) {
1728 target = new wxString();
1729 size_t len = PyUnicode_GET_SIZE(source);
1730 if (len) {
1731 PyUnicode_AsWideChar((PyUnicodeObject*)source, target->GetWriteBuf(len), len);
1732 target->UngetWriteBuf();
1733 }
1734 } else {
1735 // It is a string, get pointers to it and transform to unicode
1736 char* tmpPtr; int tmpSize;
1737 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1738 target = new wxString(tmpPtr, *wxConvCurrent, tmpSize);
1739 }
1740 #else
1741 char* tmpPtr; int tmpSize;
1742 if (PyString_AsStringAndSize(source, &tmpPtr, &tmpSize) == -1) {
1743 PyErr_SetString(PyExc_TypeError, "Unable to convert string");
1744 return NULL;
1745 }
1746 target = new wxString(tmpPtr, tmpSize);
1747 #endif // wxUSE_UNICODE
1748
1749 #else // No Python unicode API (1.5.2)
1750 if (!PyString_Check(source)) {
1751 PyErr_SetString(PyExc_TypeError, wxStringErrorMsg);
1752 return NULL;
1753 }
1754 target = new wxString(PyString_AS_STRING(source), PyString_GET_SIZE(source));
1755 #endif
1756 return target;
1757 }
1758
1759
1760 // Similar to above except doesn't use "new" and doesn't set an exception
1761 wxString Py2wxString(PyObject* source)
1762 {
1763 wxString target;
1764 bool doDecRef = FALSE;
1765
1766 #if PYTHON_API_VERSION >= 1009 // Have Python unicode API
1767 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1768 // Convert to String if not one already... (TODO: Unicode too?)
1769 source = PyObject_Str(source);
1770 doDecRef = TRUE;
1771 }
1772
1773 #if wxUSE_UNICODE
1774 if (PyUnicode_Check(source)) {
1775 size_t len = PyUnicode_GET_SIZE(source);
1776 if (len) {
1777 PyUnicode_AsWideChar((PyUnicodeObject*)source, target.GetWriteBuf(len), len);
1778 target.UngetWriteBuf();
1779 }
1780 } else {
1781 // It is a string, get pointers to it and transform to unicode
1782 char* tmpPtr; int tmpSize;
1783 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1784 target = wxString(tmpPtr, *wxConvCurrent, tmpSize);
1785 }
1786 #else
1787 char* tmpPtr; int tmpSize;
1788 PyString_AsStringAndSize(source, &tmpPtr, &tmpSize);
1789 target = wxString(tmpPtr, tmpSize);
1790 #endif // wxUSE_UNICODE
1791
1792 #else // No Python unicode API (1.5.2)
1793 if (!PyString_Check(source)) {
1794 // Convert to String if not one already...
1795 source = PyObject_Str(source);
1796 doDecRef = TRUE;
1797 }
1798 target = wxString(PyString_AS_STRING(source), PyString_GET_SIZE(source));
1799 #endif
1800
1801 if (doDecRef)
1802 Py_DECREF(source);
1803 return target;
1804 }
1805
1806
1807 // Make either a Python String or Unicode object, depending on build mode
1808 PyObject* wx2PyString(const wxString& src)
1809 {
1810 PyObject* str;
1811 #if wxUSE_UNICODE
1812 str = PyUnicode_FromWideChar(src.c_str(), src.Len());
1813 #else
1814 str = PyString_FromStringAndSize(src.c_str(), src.Len());
1815 #endif
1816 return str;
1817 }
1818
1819
1820 //----------------------------------------------------------------------
1821
1822
1823 byte* byte_LIST_helper(PyObject* source) {
1824 if (!PyList_Check(source)) {
1825 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1826 return NULL;
1827 }
1828 int count = PyList_Size(source);
1829 byte* temp = new byte[count];
1830 if (! temp) {
1831 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1832 return NULL;
1833 }
1834 for (int x=0; x<count; x++) {
1835 PyObject* o = PyList_GetItem(source, x);
1836 if (! PyInt_Check(o)) {
1837 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1838 return NULL;
1839 }
1840 temp[x] = (byte)PyInt_AsLong(o);
1841 }
1842 return temp;
1843 }
1844
1845
1846 int* int_LIST_helper(PyObject* source) {
1847 if (!PyList_Check(source)) {
1848 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1849 return NULL;
1850 }
1851 int count = PyList_Size(source);
1852 int* temp = new int[count];
1853 if (! temp) {
1854 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1855 return NULL;
1856 }
1857 for (int x=0; x<count; x++) {
1858 PyObject* o = PyList_GetItem(source, x);
1859 if (! PyInt_Check(o)) {
1860 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1861 return NULL;
1862 }
1863 temp[x] = PyInt_AsLong(o);
1864 }
1865 return temp;
1866 }
1867
1868
1869 long* long_LIST_helper(PyObject* source) {
1870 if (!PyList_Check(source)) {
1871 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1872 return NULL;
1873 }
1874 int count = PyList_Size(source);
1875 long* temp = new long[count];
1876 if (! temp) {
1877 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1878 return NULL;
1879 }
1880 for (int x=0; x<count; x++) {
1881 PyObject* o = PyList_GetItem(source, x);
1882 if (! PyInt_Check(o)) {
1883 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1884 return NULL;
1885 }
1886 temp[x] = PyInt_AsLong(o);
1887 }
1888 return temp;
1889 }
1890
1891
1892 char** string_LIST_helper(PyObject* source) {
1893 if (!PyList_Check(source)) {
1894 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1895 return NULL;
1896 }
1897 int count = PyList_Size(source);
1898 char** temp = new char*[count];
1899 if (! temp) {
1900 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1901 return NULL;
1902 }
1903 for (int x=0; x<count; x++) {
1904 PyObject* o = PyList_GetItem(source, x);
1905 if (! PyString_Check(o)) {
1906 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
1907 return NULL;
1908 }
1909 temp[x] = PyString_AsString(o);
1910 }
1911 return temp;
1912 }
1913
1914 //--------------------------------
1915 // Part of patch from Tim Hochberg
1916 static inline bool wxPointFromObjects(PyObject* o1, PyObject* o2, wxPoint* point) {
1917 if (PyInt_Check(o1) && PyInt_Check(o2)) {
1918 point->x = PyInt_AS_LONG(o1);
1919 point->y = PyInt_AS_LONG(o2);
1920 return true;
1921 }
1922 if (PyFloat_Check(o1) && PyFloat_Check(o2)) {
1923 point->x = (int)PyFloat_AS_DOUBLE(o1);
1924 point->y = (int)PyFloat_AS_DOUBLE(o2);
1925 return true;
1926 }
1927 if (PyInstance_Check(o1) || PyInstance_Check(o2)) {
1928 // Disallow instances because they can cause havok
1929 return false;
1930 }
1931 if (PyNumber_Check(o1) && PyNumber_Check(o2)) {
1932 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
1933 point->x = PyInt_AsLong(o1);
1934 point->y = PyInt_AsLong(o2);
1935 return true;
1936 }
1937 return false;
1938 }
1939
1940
1941 wxPoint* wxPoint_LIST_helper(PyObject* source, int *count) {
1942 // Putting all of the declarations here allows
1943 // us to put the error handling all in one place.
1944 int x;
1945 wxPoint* temp;
1946 PyObject *o, *o1, *o2;
1947 bool isFast = PyList_Check(source) || PyTuple_Check(source);
1948
1949 if (!PySequence_Check(source)) {
1950 goto error0;
1951 }
1952
1953 // The length of the sequence is returned in count.
1954 *count = PySequence_Length(source);
1955 if (*count < 0) {
1956 goto error0;
1957 }
1958
1959 temp = new wxPoint[*count];
1960 if (!temp) {
1961 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1962 return NULL;
1963 }
1964 for (x=0; x<*count; x++) {
1965 // Get an item: try fast way first.
1966 if (isFast) {
1967 o = PySequence_Fast_GET_ITEM(source, x);
1968 }
1969 else {
1970 o = PySequence_GetItem(source, x);
1971 if (o == NULL) {
1972 goto error1;
1973 }
1974 }
1975
1976 // Convert o to wxPoint.
1977 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
1978 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
1979 o1 = PySequence_Fast_GET_ITEM(o, 0);
1980 o2 = PySequence_Fast_GET_ITEM(o, 1);
1981 if (!wxPointFromObjects(o1, o2, &temp[x])) {
1982 goto error2;
1983 }
1984 }
1985 else if (PyInstance_Check(o)) {
1986 wxPoint* pt;
1987 if (SWIG_GetPtrObj(o, (void **)&pt, "_wxPoint_p")) {
1988 goto error2;
1989 }
1990 temp[x] = *pt;
1991 }
1992 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
1993 o1 = PySequence_GetItem(o, 0);
1994 o2 = PySequence_GetItem(o, 1);
1995 if (!wxPointFromObjects(o1, o2, &temp[x])) {
1996 goto error3;
1997 }
1998 Py_DECREF(o1);
1999 Py_DECREF(o2);
2000 }
2001 else {
2002 goto error2;
2003 }
2004 // Clean up.
2005 if (!isFast)
2006 Py_DECREF(o);
2007 }
2008 return temp;
2009
2010 error3:
2011 Py_DECREF(o1);
2012 Py_DECREF(o2);
2013 error2:
2014 if (!isFast)
2015 Py_DECREF(o);
2016 error1:
2017 delete [] temp;
2018 error0:
2019 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoints.");
2020 return NULL;
2021 }
2022 // end of patch
2023 //------------------------------
2024
2025
2026 wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
2027 if (!PyList_Check(source)) {
2028 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2029 return NULL;
2030 }
2031 int count = PyList_Size(source);
2032 wxBitmap** temp = new wxBitmap*[count];
2033 if (! temp) {
2034 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2035 return NULL;
2036 }
2037 for (int x=0; x<count; x++) {
2038 PyObject* o = PyList_GetItem(source, x);
2039 if (PyInstance_Check(o)) {
2040 wxBitmap* pt;
2041 if (SWIG_GetPtrObj(o, (void **) &pt,"_wxBitmap_p")) {
2042 PyErr_SetString(PyExc_TypeError,"Expected _wxBitmap_p.");
2043 return NULL;
2044 }
2045 temp[x] = pt;
2046 }
2047 else {
2048 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
2049 return NULL;
2050 }
2051 }
2052 return temp;
2053 }
2054
2055
2056
2057 wxString* wxString_LIST_helper(PyObject* source) {
2058 if (!PyList_Check(source)) {
2059 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2060 return NULL;
2061 }
2062 int count = PyList_Size(source);
2063 wxString* temp = new wxString[count];
2064 if (! temp) {
2065 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2066 return NULL;
2067 }
2068 for (int x=0; x<count; x++) {
2069 PyObject* o = PyList_GetItem(source, x);
2070 #if PYTHON_API_VERSION >= 1009
2071 if (! PyString_Check(o) && ! PyUnicode_Check(o)) {
2072 PyErr_SetString(PyExc_TypeError, "Expected a list of string or unicode objects.");
2073 return NULL;
2074 }
2075 #else
2076 if (! PyString_Check(o)) {
2077 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2078 return NULL;
2079 }
2080 #endif
2081
2082 wxString* pStr = wxString_in_helper(o);
2083 temp[x] = *pStr;
2084 delete pStr;
2085 }
2086 return temp;
2087 }
2088
2089
2090 wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
2091 if (!PyList_Check(source)) {
2092 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2093 return NULL;
2094 }
2095 int count = PyList_Size(source);
2096 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
2097 if (! temp) {
2098 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2099 return NULL;
2100 }
2101 for (int x=0; x<count; x++) {
2102 PyObject* o = PyList_GetItem(source, x);
2103 if (PyInstance_Check(o)) {
2104 wxAcceleratorEntry* ae;
2105 if (SWIG_GetPtrObj(o, (void **) &ae,"_wxAcceleratorEntry_p")) {
2106 PyErr_SetString(PyExc_TypeError,"Expected _wxAcceleratorEntry_p.");
2107 return NULL;
2108 }
2109 temp[x] = *ae;
2110 }
2111 else if (PyTuple_Check(o)) {
2112 PyObject* o1 = PyTuple_GetItem(o, 0);
2113 PyObject* o2 = PyTuple_GetItem(o, 1);
2114 PyObject* o3 = PyTuple_GetItem(o, 2);
2115 temp[x].Set(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2116 }
2117 else {
2118 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2119 return NULL;
2120 }
2121 }
2122 return temp;
2123 }
2124
2125
2126 wxPen** wxPen_LIST_helper(PyObject* source) {
2127 if (!PyList_Check(source)) {
2128 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2129 return NULL;
2130 }
2131 int count = PyList_Size(source);
2132 wxPen** temp = new wxPen*[count];
2133 if (!temp) {
2134 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2135 return NULL;
2136 }
2137 for (int x=0; x<count; x++) {
2138 PyObject* o = PyList_GetItem(source, x);
2139 if (PyInstance_Check(o)) {
2140 wxPen* pt;
2141 if (SWIG_GetPtrObj(o, (void **) &pt,"_wxPen_p")) {
2142 delete temp;
2143 PyErr_SetString(PyExc_TypeError,"Expected _wxPen_p.");
2144 return NULL;
2145 }
2146 temp[x] = pt;
2147 }
2148 else {
2149 delete temp;
2150 PyErr_SetString(PyExc_TypeError, "Expected a list of wxPens.");
2151 return NULL;
2152 }
2153 }
2154 return temp;
2155 }
2156
2157
2158 bool wxPy2int_seq_helper(PyObject* source, int* i1, int* i2) {
2159 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2160 PyObject *o1, *o2;
2161
2162 if (!PySequence_Check(source) || PySequence_Length(source) != 2)
2163 return FALSE;
2164
2165 if (isFast) {
2166 o1 = PySequence_Fast_GET_ITEM(source, 0);
2167 o2 = PySequence_Fast_GET_ITEM(source, 1);
2168 }
2169 else {
2170 o1 = PySequence_GetItem(source, 0);
2171 o2 = PySequence_GetItem(source, 1);
2172 }
2173
2174 *i1 = PyInt_AsLong(o1);
2175 *i2 = PyInt_AsLong(o2);
2176
2177 if (! isFast) {
2178 Py_DECREF(o1);
2179 Py_DECREF(o2);
2180 }
2181 return TRUE;
2182 }
2183
2184
2185 bool wxPy4int_seq_helper(PyObject* source, int* i1, int* i2, int* i3, int* i4) {
2186 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2187 PyObject *o1, *o2, *o3, *o4;
2188
2189 if (!PySequence_Check(source) || PySequence_Length(source) != 4)
2190 return FALSE;
2191
2192 if (isFast) {
2193 o1 = PySequence_Fast_GET_ITEM(source, 0);
2194 o2 = PySequence_Fast_GET_ITEM(source, 1);
2195 o3 = PySequence_Fast_GET_ITEM(source, 2);
2196 o4 = PySequence_Fast_GET_ITEM(source, 3);
2197 }
2198 else {
2199 o1 = PySequence_GetItem(source, 0);
2200 o2 = PySequence_GetItem(source, 1);
2201 o3 = PySequence_GetItem(source, 2);
2202 o4 = PySequence_GetItem(source, 3);
2203 }
2204
2205 *i1 = PyInt_AsLong(o1);
2206 *i2 = PyInt_AsLong(o2);
2207 *i3 = PyInt_AsLong(o3);
2208 *i4 = PyInt_AsLong(o4);
2209
2210 if (! isFast) {
2211 Py_DECREF(o1);
2212 Py_DECREF(o2);
2213 Py_DECREF(o3);
2214 Py_DECREF(o4);
2215 }
2216 return TRUE;
2217 }
2218
2219
2220 //----------------------------------------------------------------------
2221
2222 bool wxSize_helper(PyObject* source, wxSize** obj) {
2223
2224 // If source is an object instance then it may already be the right type
2225 if (PyInstance_Check(source)) {
2226 wxSize* ptr;
2227 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxSize_p"))
2228 goto error;
2229 *obj = ptr;
2230 return TRUE;
2231 }
2232 // otherwise a 2-tuple of integers is expected
2233 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
2234 PyObject* o1 = PySequence_GetItem(source, 0);
2235 PyObject* o2 = PySequence_GetItem(source, 1);
2236 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2237 Py_DECREF(o1);
2238 Py_DECREF(o2);
2239 goto error;
2240 }
2241 **obj = wxSize(PyInt_AsLong(o1), PyInt_AsLong(o2));
2242 Py_DECREF(o1);
2243 Py_DECREF(o2);
2244 return TRUE;
2245 }
2246
2247 error:
2248 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of integers or a wxSize object.");
2249 return FALSE;
2250 }
2251
2252
2253 bool wxPoint_helper(PyObject* source, wxPoint** obj) {
2254
2255 // If source is an object instance then it may already be the right type
2256 if (PyInstance_Check(source)) {
2257 wxPoint* ptr;
2258 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxPoint_p"))
2259 goto error;
2260 *obj = ptr;
2261 return TRUE;
2262 }
2263 // otherwise a length-2 sequence of integers is expected
2264 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
2265 PyObject* o1 = PySequence_GetItem(source, 0);
2266 PyObject* o2 = PySequence_GetItem(source, 1);
2267 // This should really check for integers, not numbers -- but that would break code.
2268 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2269 Py_DECREF(o1);
2270 Py_DECREF(o2);
2271 goto error;
2272 }
2273 **obj = wxPoint(PyInt_AsLong(o1), PyInt_AsLong(o2));
2274 Py_DECREF(o1);
2275 Py_DECREF(o2);
2276 return TRUE;
2277 }
2278 error:
2279 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of integers or a wxPoint object.");
2280 return FALSE;
2281 }
2282
2283
2284
2285 bool wxRealPoint_helper(PyObject* source, wxRealPoint** obj) {
2286
2287 // If source is an object instance then it may already be the right type
2288 if (PyInstance_Check(source)) {
2289 wxRealPoint* ptr;
2290 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxRealPoint_p"))
2291 goto error;
2292 *obj = ptr;
2293 return TRUE;
2294 }
2295 // otherwise a 2-tuple of floats is expected
2296 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
2297 PyObject* o1 = PySequence_GetItem(source, 0);
2298 PyObject* o2 = PySequence_GetItem(source, 1);
2299 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2300 Py_DECREF(o1);
2301 Py_DECREF(o2);
2302 goto error;
2303 }
2304 **obj = wxRealPoint(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2305 Py_DECREF(o1);
2306 Py_DECREF(o2);
2307 return TRUE;
2308 }
2309
2310 error:
2311 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxRealPoint object.");
2312 return FALSE;
2313 }
2314
2315
2316
2317
2318 bool wxRect_helper(PyObject* source, wxRect** obj) {
2319
2320 // If source is an object instance then it may already be the right type
2321 if (PyInstance_Check(source)) {
2322 wxRect* ptr;
2323 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxRect_p"))
2324 goto error;
2325 *obj = ptr;
2326 return TRUE;
2327 }
2328 // otherwise a 4-tuple of integers is expected
2329 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2330 PyObject* o1 = PySequence_GetItem(source, 0);
2331 PyObject* o2 = PySequence_GetItem(source, 1);
2332 PyObject* o3 = PySequence_GetItem(source, 2);
2333 PyObject* o4 = PySequence_GetItem(source, 3);
2334 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2335 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2336 Py_DECREF(o1);
2337 Py_DECREF(o2);
2338 Py_DECREF(o3);
2339 Py_DECREF(o4);
2340 goto error;
2341 }
2342 **obj = wxRect(PyInt_AsLong(o1), PyInt_AsLong(o2),
2343 PyInt_AsLong(o3), PyInt_AsLong(o4));
2344 Py_DECREF(o1);
2345 Py_DECREF(o2);
2346 Py_DECREF(o3);
2347 Py_DECREF(o4);
2348 return TRUE;
2349 }
2350
2351 error:
2352 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of integers or a wxRect object.");
2353 return FALSE;
2354 }
2355
2356
2357
2358 bool wxColour_helper(PyObject* source, wxColour** obj) {
2359
2360 // If source is an object instance then it may already be the right type
2361 if (PyInstance_Check(source)) {
2362 wxColour* ptr;
2363 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxColour_p"))
2364 goto error;
2365 *obj = ptr;
2366 return TRUE;
2367 }
2368 // otherwise check for a string
2369 else if (PyString_Check(source) || PyUnicode_Check(source)) {
2370 wxString spec = Py2wxString(source);
2371 if (spec.GetChar(0) == '#' && spec.Length() == 7) { // It's #RRGGBB
2372 long red, green, blue;
2373 red = green = blue = 0;
2374 spec.Mid(1,2).ToLong(&red, 16);
2375 spec.Mid(3,2).ToLong(&green, 16);
2376 spec.Mid(5,2).ToLong(&blue, 16);
2377
2378 **obj = wxColour(red, green, blue);
2379 return TRUE;
2380 }
2381 else { // it's a colour name
2382 **obj = wxColour(spec);
2383 return TRUE;
2384 }
2385 }
2386 // last chance: 3-tuple of integers is expected
2387 else if (PySequence_Check(source) && PyObject_Length(source) == 3) {
2388 PyObject* o1 = PySequence_GetItem(source, 0);
2389 PyObject* o2 = PySequence_GetItem(source, 1);
2390 PyObject* o3 = PySequence_GetItem(source, 2);
2391 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3)) {
2392 Py_DECREF(o1);
2393 Py_DECREF(o2);
2394 Py_DECREF(o3);
2395 goto error;
2396 }
2397 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2398 Py_DECREF(o1);
2399 Py_DECREF(o2);
2400 Py_DECREF(o3);
2401 return TRUE;
2402 }
2403
2404 error:
2405 PyErr_SetString(PyExc_TypeError,
2406 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2407 return FALSE;
2408 }
2409
2410
2411
2412 bool wxPoint2DDouble_helper(PyObject* source, wxPoint2DDouble** obj) {
2413 // If source is an object instance then it may already be the right type
2414 if (PyInstance_Check(source)) {
2415 wxPoint2DDouble* ptr;
2416 if (SWIG_GetPtrObj(source, (void **)&ptr, "_wxPoint2DDouble_p"))
2417 goto error;
2418 *obj = ptr;
2419 return TRUE;
2420 }
2421 // otherwise a length-2 sequence of floats is expected
2422 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
2423 PyObject* o1 = PySequence_GetItem(source, 0);
2424 PyObject* o2 = PySequence_GetItem(source, 1);
2425 // This should really check for integers, not numbers -- but that would break code.
2426 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2427 Py_DECREF(o1);
2428 Py_DECREF(o2);
2429 goto error;
2430 }
2431 **obj = wxPoint2DDouble(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2432 Py_DECREF(o1);
2433 Py_DECREF(o2);
2434 return TRUE;
2435 }
2436 error:
2437 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxPoint2DDouble object.");
2438 return FALSE;
2439 }
2440
2441
2442
2443 //----------------------------------------------------------------------
2444
2445 PyObject* wxArrayString2PyList_helper(const wxArrayString& arr) {
2446
2447 PyObject* list = PyList_New(0);
2448 for (size_t i=0; i < arr.GetCount(); i++) {
2449 #if wxUSE_UNICODE
2450 PyObject* str = PyUnicode_FromWideChar(arr[i].c_str(), arr[i].Len());
2451 #else
2452 PyObject* str = PyString_FromStringAndSize(arr[i].c_str(), arr[i].Len());
2453 #endif
2454 PyList_Append(list, str);
2455 Py_DECREF(str);
2456 }
2457 return list;
2458 }
2459
2460
2461 PyObject* wxArrayInt2PyList_helper(const wxArrayInt& arr) {
2462
2463 PyObject* list = PyList_New(0);
2464 for (size_t i=0; i < arr.GetCount(); i++) {
2465 PyObject* number = PyInt_FromLong(arr[i]);
2466 PyList_Append(list, number);
2467 Py_DECREF(number);
2468 }
2469 return list;
2470 }
2471
2472
2473 //----------------------------------------------------------------------
2474 //----------------------------------------------------------------------
2475
2476
2477
2478