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