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