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