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