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