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