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