]> git.saurik.com Git - wxWidgets.git/blob - wxPython/src/helpers.cpp
compilation fix for gcc-3.4
[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 wx._core_ module is imported to do some
515 // initial 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 wx._core_ module is
669 // imported, 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 SWIG 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 BootstrapApp patch things up so the stock objects
681 // can 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 // If there is already an App object then wxPython is probably embedded in
739 // a wx C++ application, so there is no need to do all this.
740 static bool embedded = false;
741 if ((pass == 1 || pass == 2) && wxTheApp) {
742 embedded = true;
743 return;
744 }
745 if (pass == 3 && embedded)
746 return;
747
748
749 #define REINITOBJ(name, classname) \
750 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
751 else if (pass == 2) { rsoPass2(#name); } \
752 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
753
754
755 #define REINITOBJ2(name, classname) \
756 if (pass == 1) { } \
757 else if (pass == 2) { rsoPass2(#name); } \
758 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
759
760
761 REINITOBJ(wxNORMAL_FONT, wxFont);
762 REINITOBJ(wxSMALL_FONT, wxFont);
763 REINITOBJ(wxITALIC_FONT, wxFont);
764 REINITOBJ(wxSWISS_FONT, wxFont);
765
766 REINITOBJ(wxRED_PEN, wxPen);
767 REINITOBJ(wxCYAN_PEN, wxPen);
768 REINITOBJ(wxGREEN_PEN, wxPen);
769 REINITOBJ(wxBLACK_PEN, wxPen);
770 REINITOBJ(wxWHITE_PEN, wxPen);
771 REINITOBJ(wxTRANSPARENT_PEN, wxPen);
772 REINITOBJ(wxBLACK_DASHED_PEN, wxPen);
773 REINITOBJ(wxGREY_PEN, wxPen);
774 REINITOBJ(wxMEDIUM_GREY_PEN, wxPen);
775 REINITOBJ(wxLIGHT_GREY_PEN, wxPen);
776
777 REINITOBJ(wxBLUE_BRUSH, wxBrush);
778 REINITOBJ(wxGREEN_BRUSH, wxBrush);
779 REINITOBJ(wxWHITE_BRUSH, wxBrush);
780 REINITOBJ(wxBLACK_BRUSH, wxBrush);
781 REINITOBJ(wxTRANSPARENT_BRUSH, wxBrush);
782 REINITOBJ(wxCYAN_BRUSH, wxBrush);
783 REINITOBJ(wxRED_BRUSH, wxBrush);
784 REINITOBJ(wxGREY_BRUSH, wxBrush);
785 REINITOBJ(wxMEDIUM_GREY_BRUSH, wxBrush);
786 REINITOBJ(wxLIGHT_GREY_BRUSH, wxBrush);
787
788 REINITOBJ(wxBLACK, wxColour);
789 REINITOBJ(wxWHITE, wxColour);
790 REINITOBJ(wxRED, wxColour);
791 REINITOBJ(wxBLUE, wxColour);
792 REINITOBJ(wxGREEN, wxColour);
793 REINITOBJ(wxCYAN, wxColour);
794 REINITOBJ(wxLIGHT_GREY, wxColour);
795
796 REINITOBJ(wxSTANDARD_CURSOR, wxCursor);
797 REINITOBJ(wxHOURGLASS_CURSOR, wxCursor);
798 REINITOBJ(wxCROSS_CURSOR, wxCursor);
799
800 REINITOBJ2(wxNullBitmap, wxBitmap);
801 REINITOBJ2(wxNullIcon, wxIcon);
802 REINITOBJ2(wxNullCursor, wxCursor);
803 REINITOBJ2(wxNullPen, wxPen);
804 REINITOBJ2(wxNullBrush, wxBrush);
805 REINITOBJ2(wxNullPalette, wxPalette);
806 REINITOBJ2(wxNullFont, wxFont);
807 REINITOBJ2(wxNullColour, wxColour);
808
809 REINITOBJ(wxTheFontList, wxFontList);
810 REINITOBJ(wxThePenList, wxPenList);
811 REINITOBJ(wxTheBrushList, wxBrushList);
812 REINITOBJ(wxTheColourDatabase, wxColourDatabase);
813
814
815 REINITOBJ(wxTheClipboard, wxClipboard);
816 REINITOBJ2(wxDefaultValidator, wxValidator);
817 REINITOBJ2(wxNullImage, wxImage);
818 REINITOBJ2(wxNullAcceleratorTable, wxAcceleratorTable);
819
820 #undef REINITOBJ
821 #undef REINITOBJ2
822 }
823
824 //---------------------------------------------------------------------------
825
826 void wxPyClientData_dtor(wxPyClientData* self) {
827 if (! wxPyDoingCleanup) { // Don't do it during cleanup as Python
828 // may have already garbage collected the object...
829 bool blocked = wxPyBeginBlockThreads();
830 Py_DECREF(self->m_obj);
831 self->m_obj = NULL;
832 wxPyEndBlockThreads(blocked);
833 }
834 }
835
836 void wxPyUserData_dtor(wxPyUserData* self) {
837 if (! wxPyDoingCleanup) {
838 bool blocked = wxPyBeginBlockThreads();
839 Py_DECREF(self->m_obj);
840 self->m_obj = NULL;
841 wxPyEndBlockThreads(blocked);
842 }
843 }
844
845
846 // This is called when an OOR controled object is being destroyed. Although
847 // the C++ object is going away there is no way to force the Python object
848 // (and all references to it) to die too. This causes problems (crashes) in
849 // wxPython when a python shadow object attempts to call a C++ method using
850 // the now bogus pointer... So to try and prevent this we'll do a little black
851 // magic and change the class of the python instance to a class that will
852 // raise an exception for any attempt to call methods with it. See
853 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
854 void wxPyOORClientData_dtor(wxPyOORClientData* self) {
855
856 static PyObject* deadObjectClass = NULL;
857
858 bool blocked = wxPyBeginBlockThreads();
859 if (deadObjectClass == NULL) {
860 deadObjectClass = PyDict_GetItemString(wxPython_dict, "_wxPyDeadObject");
861 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
862 // will lead to a deadlock when it tries to aquire the GIL again.
863 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
864 Py_INCREF(deadObjectClass);
865 }
866
867
868 // Only if there is more than one reference to the object
869 if ( !wxPyDoingCleanup && self->m_obj->ob_refcnt > 1 ) {
870 // bool isInstance = wxPyInstance_Check(self->m_obj);
871 // TODO same here
872 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
873
874 // Call __del__, if there is one.
875 PyObject* func = PyObject_GetAttrString(self->m_obj, "__del__");
876 if (func) {
877 PyObject* rv = PyObject_CallMethod(self->m_obj, "__del__", NULL);
878 Py_XDECREF(rv);
879 Py_DECREF(func);
880 }
881 if (PyErr_Occurred())
882 PyErr_Clear(); // just ignore it for now
883
884
885 PyObject* dict = PyObject_GetAttrString(self->m_obj, "__dict__");
886 if (dict) {
887 // Clear the instance's dictionary
888 PyDict_Clear(dict);
889
890 // put the name of the old class into the instance, and then reset the
891 // class to be the dead class.
892 PyObject* klass = PyObject_GetAttrString(self->m_obj, "__class__");
893 PyObject* name = PyObject_GetAttrString(klass, "__name__");
894 PyDict_SetItemString(dict, "_name", name);
895 PyObject_SetAttrString(self->m_obj, "__class__", deadObjectClass);
896 //Py_INCREF(deadObjectClass);
897 Py_DECREF(klass);
898 Py_DECREF(name);
899 }
900 }
901
902 // m_obj is DECREF'd in the base class dtor...
903 wxPyEndBlockThreads(blocked);
904 }
905
906
907 //---------------------------------------------------------------------------
908 // Stuff used by OOR to find the right wxPython class type to return and to
909 // build it.
910
911
912 // The pointer type map is used when the "pointer" type name generated by SWIG
913 // is not the same as the shadow class name, for example wxPyTreeCtrl
914 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
915 // so we'll just make it a Python dictionary in the wx module's namespace.
916 // (See __wxSetDictionary)
917 void wxPyPtrTypeMap_Add(const char* commonName, const char* ptrName) {
918 if (! wxPyPtrTypeMap)
919 wxPyPtrTypeMap = PyDict_New();
920 PyDict_SetItemString(wxPyPtrTypeMap,
921 (char*)commonName,
922 PyString_FromString((char*)ptrName));
923 }
924
925
926
927
928 PyObject* wxPyMake_wxObject(wxObject* source, bool checkEvtHandler) {
929 PyObject* target = NULL;
930 bool isEvtHandler = False;
931
932 if (source) {
933 // If it's derived from wxEvtHandler then there may
934 // already be a pointer to a Python object that we can use
935 // in the OOR data.
936 if (checkEvtHandler && wxIsKindOf(source, wxEvtHandler)) {
937 isEvtHandler = True;
938 wxEvtHandler* eh = (wxEvtHandler*)source;
939 wxPyOORClientData* data = (wxPyOORClientData*)eh->GetClientObject();
940 if (data) {
941 target = data->m_obj;
942 if (target)
943 Py_INCREF(target);
944 }
945 }
946
947 if (! target) {
948 // Otherwise make it the old fashioned way by making a new shadow
949 // object and putting this pointer in it. Look up the class
950 // heirarchy until we find a class name that is located in the
951 // python module.
952 const wxClassInfo* info = source->GetClassInfo();
953 wxString name = info->GetClassName();
954 bool exists = wxPyCheckSwigType(name);
955 while (info && !exists) {
956 info = info->GetBaseClass1();
957 name = info->GetClassName();
958 exists = wxPyCheckSwigType(name);
959 }
960 if (info) {
961 target = wxPyConstructObject((void*)source, name, False);
962 if (target && isEvtHandler)
963 ((wxEvtHandler*)source)->SetClientObject(new wxPyOORClientData(target));
964 } else {
965 wxString msg(wxT("wxPython class not found for "));
966 msg += source->GetClassInfo()->GetClassName();
967 PyErr_SetString(PyExc_NameError, msg.mbc_str());
968 target = NULL;
969 }
970 }
971 } else { // source was NULL so return None.
972 Py_INCREF(Py_None); target = Py_None;
973 }
974 return target;
975 }
976
977
978 PyObject* wxPyMake_wxSizer(wxSizer* source) {
979 PyObject* target = NULL;
980
981 if (source && wxIsKindOf(source, wxSizer)) {
982 // If it's derived from wxSizer then there may already be a pointer to
983 // a Python object that we can use in the OOR data.
984 wxSizer* sz = (wxSizer*)source;
985 wxPyOORClientData* data = (wxPyOORClientData*)sz->GetClientObject();
986 if (data) {
987 target = data->m_obj;
988 if (target)
989 Py_INCREF(target);
990 }
991 }
992 if (! target) {
993 target = wxPyMake_wxObject(source, False);
994 if (target != Py_None)
995 ((wxSizer*)source)->SetClientObject(new wxPyOORClientData(target));
996 }
997 return target;
998 }
999
1000
1001 //---------------------------------------------------------------------------
1002
1003
1004 #ifdef WXP_WITH_THREAD
1005 inline
1006 unsigned long wxPyGetCurrentThreadId() {
1007 return wxThread::GetCurrentId();
1008 }
1009
1010 static wxPyThreadState gs_shutdownTState;
1011
1012 static
1013 wxPyThreadState* wxPyGetThreadState() {
1014 if (wxPyTMutex == NULL) // Python is shutting down...
1015 return &gs_shutdownTState;
1016
1017 unsigned long ctid = wxPyGetCurrentThreadId();
1018 wxPyThreadState* tstate = NULL;
1019
1020 wxPyTMutex->Lock();
1021 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
1022 wxPyThreadState& info = wxPyTStates->Item(i);
1023 if (info.tid == ctid) {
1024 tstate = &info;
1025 break;
1026 }
1027 }
1028 wxPyTMutex->Unlock();
1029 wxASSERT_MSG(tstate, wxT("PyThreadState should not be NULL!"));
1030 return tstate;
1031 }
1032
1033
1034 static
1035 void wxPySaveThreadState(PyThreadState* tstate) {
1036 if (wxPyTMutex == NULL) { // Python is shutting down, assume a single thread...
1037 gs_shutdownTState.tstate = tstate;
1038 return;
1039 }
1040 unsigned long ctid = wxPyGetCurrentThreadId();
1041 wxPyTMutex->Lock();
1042 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
1043 wxPyThreadState& info = wxPyTStates->Item(i);
1044 if (info.tid == ctid) {
1045 #if 0
1046 if (info.tstate != tstate)
1047 wxLogMessage("*** tstate mismatch!???");
1048 #endif
1049 // info.tstate = tstate; *** DO NOT update existing ones???
1050 // Normally it will never change, but apparently COM callbacks
1051 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1052 // tstate which will then be garbage the next time we try to use
1053 // it...
1054 wxPyTMutex->Unlock();
1055 return;
1056 }
1057 }
1058 // not found, so add it...
1059 wxPyTStates->Add(new wxPyThreadState(ctid, tstate));
1060 wxPyTMutex->Unlock();
1061 }
1062
1063 #endif
1064
1065
1066
1067 // Calls from Python to wxWindows code are wrapped in calls to these
1068 // functions:
1069
1070 PyThreadState* wxPyBeginAllowThreads() {
1071 #ifdef WXP_WITH_THREAD
1072 PyThreadState* saved = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1073 wxPySaveThreadState(saved);
1074 return saved;
1075 #else
1076 return NULL;
1077 #endif
1078 }
1079
1080 void wxPyEndAllowThreads(PyThreadState* saved) {
1081 #ifdef WXP_WITH_THREAD
1082 PyEval_RestoreThread(saved); // Py_END_ALLOW_THREADS;
1083 #endif
1084 }
1085
1086
1087
1088 // Calls from wxWindows back to Python code, or even any PyObject
1089 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1090
1091 bool wxPyBeginBlockThreads() {
1092 #ifdef WXP_WITH_THREAD
1093 // This works in for 2.3, maybe a good alternative to find the needed tstate?
1094 // PyThreadState *check = PyGILState_GetThisThreadState();
1095
1096 PyThreadState *current = _PyThreadState_Current;
1097
1098 // Only block if there wasn't already a tstate, or if the current one is
1099 // not the one we are wanting to change to. This should prevent deadlock
1100 // if there are nested calls to wxPyBeginBlockThreads
1101 bool blocked = false;
1102 wxPyThreadState* tstate = wxPyGetThreadState();
1103 if (current != tstate->tstate) {
1104 PyEval_RestoreThread(tstate->tstate);
1105 blocked = true;
1106 }
1107 return blocked;
1108 #endif
1109 }
1110
1111
1112 void wxPyEndBlockThreads(bool blocked) {
1113 #ifdef WXP_WITH_THREAD
1114 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1115 // The value of blocked passed in needs to be the same as that returned
1116 // from wxPyBeginBlockThreads at the same nesting level.
1117 if ( blocked ) {
1118 PyEval_SaveThread();
1119 }
1120 #endif
1121 }
1122
1123
1124 //---------------------------------------------------------------------------
1125 // wxPyInputStream and wxPyCBInputStream methods
1126
1127
1128 void wxPyInputStream::close() {
1129 /* do nothing for now */
1130 }
1131
1132 void wxPyInputStream::flush() {
1133 /* do nothing for now */
1134 }
1135
1136 bool wxPyInputStream::eof() {
1137 if (m_wxis)
1138 return m_wxis->Eof();
1139 else
1140 return True;
1141 }
1142
1143 wxPyInputStream::~wxPyInputStream() {
1144 /* do nothing */
1145 }
1146
1147
1148
1149
1150 PyObject* wxPyInputStream::read(int size) {
1151 PyObject* obj = NULL;
1152 wxMemoryBuffer buf;
1153 const int BUFSIZE = 1024;
1154
1155 // check if we have a real wxInputStream to work with
1156 if (!m_wxis) {
1157 bool blocked = wxPyBeginBlockThreads();
1158 PyErr_SetString(PyExc_IOError, "no valid C-wxInputStream");
1159 wxPyEndBlockThreads(blocked);
1160 return NULL;
1161 }
1162
1163 if (size < 0) {
1164 // read while bytes are available on the stream
1165 while ( m_wxis->CanRead() ) {
1166 m_wxis->Read(buf.GetAppendBuf(BUFSIZE), BUFSIZE);
1167 buf.UngetAppendBuf(m_wxis->LastRead());
1168 }
1169
1170 } else { // Read only size number of characters
1171 m_wxis->Read(buf.GetWriteBuf(size), size);
1172 buf.UngetWriteBuf(m_wxis->LastRead());
1173 }
1174
1175 // error check
1176 bool blocked = wxPyBeginBlockThreads();
1177 wxStreamError err = m_wxis->GetLastError();
1178 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1179 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1180 }
1181 else {
1182 // We use only strings for the streams, not unicode
1183 obj = PyString_FromStringAndSize(buf, buf.GetDataLen());
1184 }
1185 wxPyEndBlockThreads(blocked);
1186 return obj;
1187 }
1188
1189
1190 PyObject* wxPyInputStream::readline(int size) {
1191 PyObject* obj = NULL;
1192 wxMemoryBuffer buf;
1193 int i;
1194 char ch;
1195
1196 // check if we have a real wxInputStream to work with
1197 if (!m_wxis) {
1198 bool blocked = wxPyBeginBlockThreads();
1199 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1200 wxPyEndBlockThreads(blocked);
1201 return NULL;
1202 }
1203
1204 // read until \n or byte limit reached
1205 for (i=ch=0; (ch != '\n') && (m_wxis->CanRead()) && ((size < 0) || (i < size)); i++) {
1206 ch = m_wxis->GetC();
1207 buf.AppendByte(ch);
1208 }
1209
1210 // errorcheck
1211 bool blocked = wxPyBeginBlockThreads();
1212 wxStreamError err = m_wxis->GetLastError();
1213 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1214 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1215 }
1216 else {
1217 // We use only strings for the streams, not unicode
1218 obj = PyString_FromStringAndSize((char*)buf.GetData(), buf.GetDataLen());
1219 }
1220 wxPyEndBlockThreads(blocked);
1221 return obj;
1222 }
1223
1224
1225 PyObject* wxPyInputStream::readlines(int sizehint) {
1226 PyObject* pylist;
1227
1228 // check if we have a real wxInputStream to work with
1229 if (!m_wxis) {
1230 bool blocked = wxPyBeginBlockThreads();
1231 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1232 wxPyEndBlockThreads(blocked);
1233 return NULL;
1234 }
1235
1236 // init list
1237 bool blocked = wxPyBeginBlockThreads();
1238 pylist = PyList_New(0);
1239 wxPyEndBlockThreads(blocked);
1240
1241 if (!pylist) {
1242 bool blocked = wxPyBeginBlockThreads();
1243 PyErr_NoMemory();
1244 wxPyEndBlockThreads(blocked);
1245 return NULL;
1246 }
1247
1248 // read sizehint bytes or until EOF
1249 int i;
1250 for (i=0; (m_wxis->CanRead()) && ((sizehint < 0) || (i < sizehint));) {
1251 PyObject* s = this->readline();
1252 if (s == NULL) {
1253 bool blocked = wxPyBeginBlockThreads();
1254 Py_DECREF(pylist);
1255 wxPyEndBlockThreads(blocked);
1256 return NULL;
1257 }
1258 bool blocked = wxPyBeginBlockThreads();
1259 PyList_Append(pylist, s);
1260 i += PyString_Size(s);
1261 wxPyEndBlockThreads(blocked);
1262 }
1263
1264 // error check
1265 wxStreamError err = m_wxis->GetLastError();
1266 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1267 bool blocked = wxPyBeginBlockThreads();
1268 Py_DECREF(pylist);
1269 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1270 wxPyEndBlockThreads(blocked);
1271 return NULL;
1272 }
1273
1274 return pylist;
1275 }
1276
1277
1278 void wxPyInputStream::seek(int offset, int whence) {
1279 if (m_wxis)
1280 m_wxis->SeekI(offset, wxSeekMode(whence));
1281 }
1282
1283 int wxPyInputStream::tell(){
1284 if (m_wxis)
1285 return m_wxis->TellI();
1286 else return 0;
1287 }
1288
1289
1290
1291
1292 wxPyCBInputStream::wxPyCBInputStream(PyObject *r, PyObject *s, PyObject *t, bool block)
1293 : wxInputStream(), m_read(r), m_seek(s), m_tell(t), m_block(block)
1294 {}
1295
1296
1297 wxPyCBInputStream::~wxPyCBInputStream() {
1298 bool blocked;
1299 if (m_block) blocked = wxPyBeginBlockThreads();
1300 Py_XDECREF(m_read);
1301 Py_XDECREF(m_seek);
1302 Py_XDECREF(m_tell);
1303 if (m_block) wxPyEndBlockThreads(blocked);
1304 }
1305
1306
1307 wxPyCBInputStream* wxPyCBInputStream::create(PyObject *py, bool block) {
1308 bool blocked;
1309 if (block) blocked = wxPyBeginBlockThreads();
1310
1311 PyObject* read = getMethod(py, "read");
1312 PyObject* seek = getMethod(py, "seek");
1313 PyObject* tell = getMethod(py, "tell");
1314
1315 if (!read) {
1316 PyErr_SetString(PyExc_TypeError, "Not a file-like object");
1317 Py_XDECREF(read);
1318 Py_XDECREF(seek);
1319 Py_XDECREF(tell);
1320 if (block) wxPyEndBlockThreads(blocked);
1321 return NULL;
1322 }
1323
1324 if (block) wxPyEndBlockThreads(blocked);
1325 return new wxPyCBInputStream(read, seek, tell, block);
1326 }
1327
1328
1329 wxPyCBInputStream* wxPyCBInputStream_create(PyObject *py, bool block) {
1330 return wxPyCBInputStream::create(py, block);
1331 }
1332
1333 PyObject* wxPyCBInputStream::getMethod(PyObject* py, char* name) {
1334 if (!PyObject_HasAttrString(py, name))
1335 return NULL;
1336 PyObject* o = PyObject_GetAttrString(py, name);
1337 if (!PyMethod_Check(o) && !PyCFunction_Check(o)) {
1338 Py_DECREF(o);
1339 return NULL;
1340 }
1341 return o;
1342 }
1343
1344
1345 size_t wxPyCBInputStream::GetSize() const {
1346 wxPyCBInputStream* self = (wxPyCBInputStream*)this; // cast off const
1347 if (m_seek && m_tell) {
1348 off_t temp = self->OnSysTell();
1349 off_t ret = self->OnSysSeek(0, wxFromEnd);
1350 self->OnSysSeek(temp, wxFromStart);
1351 return ret;
1352 }
1353 else
1354 return 0;
1355 }
1356
1357
1358 size_t wxPyCBInputStream::OnSysRead(void *buffer, size_t bufsize) {
1359 if (bufsize == 0)
1360 return 0;
1361
1362 bool blocked = wxPyBeginBlockThreads();
1363 PyObject* arglist = Py_BuildValue("(i)", bufsize);
1364 PyObject* result = PyEval_CallObject(m_read, arglist);
1365 Py_DECREF(arglist);
1366
1367 size_t o = 0;
1368 if ((result != NULL) && PyString_Check(result)) {
1369 o = PyString_Size(result);
1370 if (o == 0)
1371 m_lasterror = wxSTREAM_EOF;
1372 if (o > bufsize)
1373 o = bufsize;
1374 memcpy((char*)buffer, PyString_AsString(result), o); // strings only, not unicode...
1375 Py_DECREF(result);
1376
1377 }
1378 else
1379 m_lasterror = wxSTREAM_READ_ERROR;
1380 wxPyEndBlockThreads(blocked);
1381 return o;
1382 }
1383
1384 size_t wxPyCBInputStream::OnSysWrite(const void *buffer, size_t bufsize) {
1385 m_lasterror = wxSTREAM_WRITE_ERROR;
1386 return 0;
1387 }
1388
1389 off_t wxPyCBInputStream::OnSysSeek(off_t off, wxSeekMode mode) {
1390 bool blocked = wxPyBeginBlockThreads();
1391 #ifdef _LARGE_FILES
1392 // off_t is a 64-bit value...
1393 PyObject* arglist = Py_BuildValue("(Li)", off, mode);
1394 #else
1395 PyObject* arglist = Py_BuildValue("(ii)", off, mode);
1396 #endif
1397 PyObject* result = PyEval_CallObject(m_seek, arglist);
1398 Py_DECREF(arglist);
1399 Py_XDECREF(result);
1400 wxPyEndBlockThreads(blocked);
1401 return OnSysTell();
1402 }
1403
1404
1405 off_t wxPyCBInputStream::OnSysTell() const {
1406 bool blocked = wxPyBeginBlockThreads();
1407 PyObject* arglist = Py_BuildValue("()");
1408 PyObject* result = PyEval_CallObject(m_tell, arglist);
1409 Py_DECREF(arglist);
1410 off_t o = 0;
1411 if (result != NULL) {
1412 #ifdef _LARGE_FILES
1413 if (PyLong_Check(result))
1414 o = PyLong_AsLongLong(result);
1415 else
1416 #endif
1417 o = PyInt_AsLong(result);
1418 Py_DECREF(result);
1419 };
1420 wxPyEndBlockThreads(blocked);
1421 return o;
1422 }
1423
1424 //----------------------------------------------------------------------
1425
1426 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback, wxObject);
1427
1428 wxPyCallback::wxPyCallback(PyObject* func) {
1429 m_func = func;
1430 Py_INCREF(m_func);
1431 }
1432
1433 wxPyCallback::wxPyCallback(const wxPyCallback& other) {
1434 m_func = other.m_func;
1435 Py_INCREF(m_func);
1436 }
1437
1438 wxPyCallback::~wxPyCallback() {
1439 bool blocked = wxPyBeginBlockThreads();
1440 Py_DECREF(m_func);
1441 wxPyEndBlockThreads(blocked);
1442 }
1443
1444
1445 #define wxPy_PRECALLINIT "_preCallInit"
1446 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1447
1448 // This function is used for all events destined for Python event handlers.
1449 void wxPyCallback::EventThunker(wxEvent& event) {
1450 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
1451 PyObject* func = cb->m_func;
1452 PyObject* result;
1453 PyObject* arg;
1454 PyObject* tuple;
1455 bool checkSkip = False;
1456
1457 bool blocked = wxPyBeginBlockThreads();
1458 wxString className = event.GetClassInfo()->GetClassName();
1459
1460 // If the event is one of these types then pass the original
1461 // event object instead of the one passed to us.
1462 if ( className == wxT("wxPyEvent") ) {
1463 arg = ((wxPyEvent*)&event)->GetSelf();
1464 checkSkip = ((wxPyEvent*)&event)->GetCloned();
1465 }
1466 else if ( className == wxT("wxPyCommandEvent") ) {
1467 arg = ((wxPyCommandEvent*)&event)->GetSelf();
1468 checkSkip = ((wxPyCommandEvent*)&event)->GetCloned();
1469 }
1470 else {
1471 arg = wxPyConstructObject((void*)&event, className);
1472 }
1473
1474 if (!arg) {
1475 PyErr_Print();
1476 } else {
1477 // "intern" the pre/post method names to speed up the HasAttr
1478 static PyObject* s_preName = NULL;
1479 static PyObject* s_postName = NULL;
1480 if (s_preName == NULL) {
1481 s_preName = PyString_FromString(wxPy_PRECALLINIT);
1482 s_postName = PyString_FromString(wxPy_POSTCALLCLEANUP);
1483 }
1484
1485 // Check if the event object needs some preinitialization
1486 if (PyObject_HasAttr(arg, s_preName)) {
1487 result = PyObject_CallMethodObjArgs(arg, s_preName, arg, NULL);
1488 if ( result ) {
1489 Py_DECREF(result); // result is ignored, but we still need to decref it
1490 PyErr_Clear(); // Just in case...
1491 } else {
1492 PyErr_Print();
1493 }
1494 }
1495
1496 // Call the event handler, passing the event object
1497 tuple = PyTuple_New(1);
1498 PyTuple_SET_ITEM(tuple, 0, arg); // steals ref to arg
1499 result = PyEval_CallObject(func, tuple);
1500 if ( result ) {
1501 Py_DECREF(result); // result is ignored, but we still need to decref it
1502 PyErr_Clear(); // Just in case...
1503 } else {
1504 PyErr_Print();
1505 }
1506
1507 // Check if the event object needs some post cleanup
1508 if (PyObject_HasAttr(arg, s_postName)) {
1509 result = PyObject_CallMethodObjArgs(arg, s_postName, arg, NULL);
1510 if ( result ) {
1511 Py_DECREF(result); // result is ignored, but we still need to decref it
1512 PyErr_Clear(); // Just in case...
1513 } else {
1514 PyErr_Print();
1515 }
1516 }
1517
1518 if ( checkSkip ) {
1519 // if the event object was one of our special types and
1520 // it had been cloned, then we need to extract the Skipped
1521 // value from the original and set it in the clone.
1522 result = PyObject_CallMethod(arg, "GetSkipped", "");
1523 if ( result ) {
1524 event.Skip(PyInt_AsLong(result));
1525 Py_DECREF(result);
1526 } else {
1527 PyErr_Print();
1528 }
1529 }
1530 Py_DECREF(tuple);
1531 }
1532 wxPyEndBlockThreads(blocked);
1533 }
1534
1535
1536 //----------------------------------------------------------------------
1537
1538 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper& other) {
1539 m_lastFound = NULL;
1540 m_self = other.m_self;
1541 m_class = other.m_class;
1542 if (m_self) {
1543 Py_INCREF(m_self);
1544 Py_INCREF(m_class);
1545 }
1546 }
1547
1548
1549 void wxPyCallbackHelper::setSelf(PyObject* self, PyObject* klass, int incref) {
1550 m_self = self;
1551 m_class = klass;
1552 m_incRef = incref;
1553 if (incref) {
1554 Py_INCREF(m_self);
1555 Py_INCREF(m_class);
1556 }
1557 }
1558
1559
1560 #if PYTHON_API_VERSION >= 1011
1561
1562 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1563 // in which the method was defined. Starting with 2.2 it returns
1564 // "class that asked for the method" which seems totally bogus to me
1565 // but apprently it fixes some obscure problem waiting to happen in
1566 // Python. Since the API was not documented Guido and the gang felt
1567 // safe in changing it. Needless to say that totally screwed up the
1568 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1569 // code to find the class where the method is actually defined...
1570
1571 static
1572 PyObject* PyFindClassWithAttr(PyObject *klass, PyObject *name)
1573 {
1574 int i, n;
1575
1576 if (PyType_Check(klass)) { // new style classes
1577 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1578 PyTypeObject* type = (PyTypeObject*)klass;
1579 PyObject *mro, *res, *base, *dict;
1580 /* Look in tp_dict of types in MRO */
1581 mro = type->tp_mro;
1582 assert(PyTuple_Check(mro));
1583 n = PyTuple_GET_SIZE(mro);
1584 for (i = 0; i < n; i++) {
1585 base = PyTuple_GET_ITEM(mro, i);
1586 if (PyClass_Check(base))
1587 dict = ((PyClassObject *)base)->cl_dict;
1588 else {
1589 assert(PyType_Check(base));
1590 dict = ((PyTypeObject *)base)->tp_dict;
1591 }
1592 assert(dict && PyDict_Check(dict));
1593 res = PyDict_GetItem(dict, name);
1594 if (res != NULL)
1595 return base;
1596 }
1597 return NULL;
1598 }
1599
1600 else if (PyClass_Check(klass)) { // old style classes
1601 // This code is borrowed/adapted from class_lookup in classobject.c
1602 PyClassObject* cp = (PyClassObject*)klass;
1603 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
1604 if (value != NULL) {
1605 return (PyObject*)cp;
1606 }
1607 n = PyTuple_Size(cp->cl_bases);
1608 for (i = 0; i < n; i++) {
1609 PyObject* base = PyTuple_GetItem(cp->cl_bases, i);
1610 PyObject *v = PyFindClassWithAttr(base, name);
1611 if (v != NULL)
1612 return v;
1613 }
1614 return NULL;
1615 }
1616 return NULL;
1617 }
1618 #endif
1619
1620
1621 static
1622 PyObject* PyMethod_GetDefiningClass(PyObject* method, const char* name)
1623 {
1624 PyObject* mgc = PyMethod_GET_CLASS(method);
1625
1626 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1627 return mgc;
1628 #else // 2.2 and after, the hard way...
1629
1630 PyObject* nameo = PyString_FromString(name);
1631 PyObject* klass = PyFindClassWithAttr(mgc, nameo);
1632 Py_DECREF(nameo);
1633 return klass;
1634 #endif
1635 }
1636
1637
1638
1639 bool wxPyCallbackHelper::findCallback(const char* name) const {
1640 wxPyCallbackHelper* self = (wxPyCallbackHelper*)this; // cast away const
1641 self->m_lastFound = NULL;
1642
1643 // If the object (m_self) has an attibute of the given name...
1644 if (m_self && PyObject_HasAttrString(m_self, (char*)name)) {
1645 PyObject *method, *klass;
1646 method = PyObject_GetAttrString(m_self, (char*)name);
1647
1648 // ...and if that attribute is a method, and if that method's class is
1649 // not from a base class...
1650 if (PyMethod_Check(method) &&
1651 (klass = PyMethod_GetDefiningClass(method, (char*)name)) != NULL &&
1652 ((klass == m_class) || PyObject_IsSubclass(klass, m_class))) {
1653
1654 // ...then we'll save a pointer to the method so callCallback can call it.
1655 self->m_lastFound = method;
1656 }
1657 else {
1658 Py_DECREF(method);
1659 }
1660 }
1661 return m_lastFound != NULL;
1662 }
1663
1664
1665 int wxPyCallbackHelper::callCallback(PyObject* argTuple) const {
1666 PyObject* result;
1667 int retval = False;
1668
1669 result = callCallbackObj(argTuple);
1670 if (result) { // Assumes an integer return type...
1671 retval = PyInt_AsLong(result);
1672 Py_DECREF(result);
1673 PyErr_Clear(); // forget about it if it's not...
1674 }
1675 return retval;
1676 }
1677
1678 // Invoke the Python callable object, returning the raw PyObject return
1679 // value. Caller should DECREF the return value and also manage the GIL.
1680 PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) const {
1681 PyObject* result;
1682
1683 // Save a copy of the pointer in case the callback generates another
1684 // callback. In that case m_lastFound will have a different value when
1685 // it gets back here...
1686 PyObject* method = m_lastFound;
1687
1688 result = PyEval_CallObject(method, argTuple);
1689 Py_DECREF(argTuple);
1690 Py_DECREF(method);
1691 if (!result) {
1692 PyErr_Print();
1693 }
1694 return result;
1695 }
1696
1697
1698 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper& cbh, PyObject* self, PyObject* klass, int incref) {
1699 cbh.setSelf(self, klass, incref);
1700 }
1701
1702 bool wxPyCBH_findCallback(const wxPyCallbackHelper& cbh, const char* name) {
1703 return cbh.findCallback(name);
1704 }
1705
1706 int wxPyCBH_callCallback(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1707 return cbh.callCallback(argTuple);
1708 }
1709
1710 PyObject* wxPyCBH_callCallbackObj(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1711 return cbh.callCallbackObj(argTuple);
1712 }
1713
1714
1715 void wxPyCBH_delete(wxPyCallbackHelper* cbh) {
1716 if (cbh->m_incRef) {
1717 bool blocked = wxPyBeginBlockThreads();
1718 Py_XDECREF(cbh->m_self);
1719 Py_XDECREF(cbh->m_class);
1720 wxPyEndBlockThreads(blocked);
1721 }
1722 }
1723
1724 //---------------------------------------------------------------------------
1725 //---------------------------------------------------------------------------
1726 // These event classes can be derived from in Python and passed through the event
1727 // system without losing anything. They do this by keeping a reference to
1728 // themselves and some special case handling in wxPyCallback::EventThunker.
1729
1730
1731 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1732 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1733 //Py_INCREF(m_self); // circular loops...
1734 m_cloned = False;
1735 }
1736
1737 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1738 bool blocked = wxPyBeginBlockThreads();
1739 if (m_cloned)
1740 Py_DECREF(m_self);
1741 wxPyEndBlockThreads(blocked);
1742 }
1743
1744 void wxPyEvtSelfRef::SetSelf(PyObject* self, bool clone) {
1745 bool blocked = wxPyBeginBlockThreads();
1746 if (m_cloned)
1747 Py_DECREF(m_self);
1748 m_self = self;
1749 if (clone) {
1750 Py_INCREF(m_self);
1751 m_cloned = True;
1752 }
1753 wxPyEndBlockThreads(blocked);
1754 }
1755
1756 PyObject* wxPyEvtSelfRef::GetSelf() const {
1757 Py_INCREF(m_self);
1758 return m_self;
1759 }
1760
1761
1762 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent, wxEvent);
1763 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent, wxCommandEvent);
1764
1765
1766 wxPyEvent::wxPyEvent(int winid, wxEventType commandType)
1767 : wxEvent(winid, commandType) {
1768 }
1769
1770
1771 wxPyEvent::wxPyEvent(const wxPyEvent& evt)
1772 : wxEvent(evt)
1773 {
1774 SetSelf(evt.m_self, True);
1775 }
1776
1777
1778 wxPyEvent::~wxPyEvent() {
1779 }
1780
1781
1782 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType, int id)
1783 : wxCommandEvent(commandType, id) {
1784 }
1785
1786
1787 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent& evt)
1788 : wxCommandEvent(evt)
1789 {
1790 SetSelf(evt.m_self, True);
1791 }
1792
1793
1794 wxPyCommandEvent::~wxPyCommandEvent() {
1795 }
1796
1797
1798
1799
1800
1801 //---------------------------------------------------------------------------
1802 //---------------------------------------------------------------------------
1803 // Convert a wxList to a Python List, only works for lists of wxObjects
1804
1805 PyObject* wxPy_ConvertList(wxListBase* listbase) {
1806 wxList* list = (wxList*)listbase; // this is probably bad...
1807 PyObject* pyList;
1808 PyObject* pyObj;
1809 wxObject* wxObj;
1810 wxNode* node = list->GetFirst();
1811
1812 bool blocked = wxPyBeginBlockThreads();
1813 pyList = PyList_New(0);
1814 while (node) {
1815 wxObj = node->GetData();
1816 pyObj = wxPyMake_wxObject(wxObj);
1817 PyList_Append(pyList, pyObj);
1818 node = node->GetNext();
1819 }
1820 wxPyEndBlockThreads(blocked);
1821 return pyList;
1822 }
1823
1824 //----------------------------------------------------------------------
1825
1826 long wxPyGetWinHandle(wxWindow* win) {
1827
1828 #ifdef __WXMSW__
1829 return (long)win->GetHandle();
1830 #endif
1831
1832 #if defined(__WXGTK__) || defined(__WXX11)
1833 return (long)GetXWindow(win);
1834 #endif
1835
1836 #ifdef __WXMAC__
1837 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1838 return (long)win->GetHandle();
1839 #endif
1840
1841 return 0;
1842 }
1843
1844 //----------------------------------------------------------------------
1845 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1846 // included in every file over and over again...
1847
1848 wxString* wxString_in_helper(PyObject* source) {
1849 wxString* target = NULL;
1850
1851 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1852 PyErr_SetString(PyExc_TypeError, "String or Unicode type required");
1853 return NULL;
1854 }
1855 #if wxUSE_UNICODE
1856 PyObject* uni = source;
1857 if (PyString_Check(source)) {
1858 uni = PyUnicode_FromObject(source);
1859 if (PyErr_Occurred()) return NULL;
1860 }
1861 target = new wxString();
1862 size_t len = PyUnicode_GET_SIZE(uni);
1863 if (len) {
1864 PyUnicode_AsWideChar((PyUnicodeObject*)uni, target->GetWriteBuf(len), len);
1865 target->UngetWriteBuf();
1866 }
1867
1868 if (PyString_Check(source))
1869 Py_DECREF(uni);
1870 #else
1871 char* tmpPtr; int tmpSize;
1872 if (PyString_AsStringAndSize(source, &tmpPtr, &tmpSize) == -1) {
1873 PyErr_SetString(PyExc_TypeError, "Unable to convert string");
1874 return NULL;
1875 }
1876 target = new wxString(tmpPtr, tmpSize);
1877 #endif // wxUSE_UNICODE
1878
1879 return target;
1880 }
1881
1882
1883 // Similar to above except doesn't use "new" and doesn't set an exception
1884 wxString Py2wxString(PyObject* source)
1885 {
1886 wxString target;
1887
1888 #if wxUSE_UNICODE
1889 // Convert to a unicode object, if not already, then to a wxString
1890 PyObject* uni = source;
1891 if (!PyUnicode_Check(source)) {
1892 uni = PyUnicode_FromObject(source);
1893 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1894 }
1895 size_t len = PyUnicode_GET_SIZE(uni);
1896 if (len) {
1897 PyUnicode_AsWideChar((PyUnicodeObject*)uni, target.GetWriteBuf(len), len);
1898 target.UngetWriteBuf();
1899 }
1900
1901 if (!PyUnicode_Check(source))
1902 Py_DECREF(uni);
1903 #else
1904 // Convert to a string object if it isn't already, then to wxString
1905 PyObject* str = source;
1906 if (!PyString_Check(source)) {
1907 str = PyObject_Str(source);
1908 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1909 }
1910 char* tmpPtr; int tmpSize;
1911 PyString_AsStringAndSize(str, &tmpPtr, &tmpSize);
1912 target = wxString(tmpPtr, tmpSize);
1913
1914 if (!PyString_Check(source))
1915 Py_DECREF(str);
1916 #endif // wxUSE_UNICODE
1917
1918 return target;
1919 }
1920
1921
1922 // Make either a Python String or Unicode object, depending on build mode
1923 PyObject* wx2PyString(const wxString& src)
1924 {
1925 PyObject* str;
1926 #if wxUSE_UNICODE
1927 str = PyUnicode_FromWideChar(src.c_str(), src.Len());
1928 #else
1929 str = PyString_FromStringAndSize(src.c_str(), src.Len());
1930 #endif
1931 return str;
1932 }
1933
1934
1935 //----------------------------------------------------------------------
1936
1937
1938 byte* byte_LIST_helper(PyObject* source) {
1939 if (!PyList_Check(source)) {
1940 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1941 return NULL;
1942 }
1943 int count = PyList_Size(source);
1944 byte* temp = new byte[count];
1945 if (! temp) {
1946 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1947 return NULL;
1948 }
1949 for (int x=0; x<count; x++) {
1950 PyObject* o = PyList_GetItem(source, x);
1951 if (! PyInt_Check(o)) {
1952 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1953 return NULL;
1954 }
1955 temp[x] = (byte)PyInt_AsLong(o);
1956 }
1957 return temp;
1958 }
1959
1960
1961 int* int_LIST_helper(PyObject* source) {
1962 if (!PyList_Check(source)) {
1963 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1964 return NULL;
1965 }
1966 int count = PyList_Size(source);
1967 int* temp = new int[count];
1968 if (! temp) {
1969 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1970 return NULL;
1971 }
1972 for (int x=0; x<count; x++) {
1973 PyObject* o = PyList_GetItem(source, x);
1974 if (! PyInt_Check(o)) {
1975 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1976 return NULL;
1977 }
1978 temp[x] = PyInt_AsLong(o);
1979 }
1980 return temp;
1981 }
1982
1983
1984 long* long_LIST_helper(PyObject* source) {
1985 if (!PyList_Check(source)) {
1986 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1987 return NULL;
1988 }
1989 int count = PyList_Size(source);
1990 long* temp = new long[count];
1991 if (! temp) {
1992 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1993 return NULL;
1994 }
1995 for (int x=0; x<count; x++) {
1996 PyObject* o = PyList_GetItem(source, x);
1997 if (! PyInt_Check(o)) {
1998 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1999 return NULL;
2000 }
2001 temp[x] = PyInt_AsLong(o);
2002 }
2003 return temp;
2004 }
2005
2006
2007 char** string_LIST_helper(PyObject* source) {
2008 if (!PyList_Check(source)) {
2009 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2010 return NULL;
2011 }
2012 int count = PyList_Size(source);
2013 char** temp = new char*[count];
2014 if (! temp) {
2015 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2016 return NULL;
2017 }
2018 for (int x=0; x<count; x++) {
2019 PyObject* o = PyList_GetItem(source, x);
2020 if (! PyString_Check(o)) {
2021 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2022 return NULL;
2023 }
2024 temp[x] = PyString_AsString(o);
2025 }
2026 return temp;
2027 }
2028
2029 //--------------------------------
2030 // Part of patch from Tim Hochberg
2031 static inline bool wxPointFromObjects(PyObject* o1, PyObject* o2, wxPoint* point) {
2032 if (PyInt_Check(o1) && PyInt_Check(o2)) {
2033 point->x = PyInt_AS_LONG(o1);
2034 point->y = PyInt_AS_LONG(o2);
2035 return True;
2036 }
2037 if (PyFloat_Check(o1) && PyFloat_Check(o2)) {
2038 point->x = (int)PyFloat_AS_DOUBLE(o1);
2039 point->y = (int)PyFloat_AS_DOUBLE(o2);
2040 return True;
2041 }
2042 if (wxPySwigInstance_Check(o1) || wxPySwigInstance_Check(o2)) { // TODO: Why???
2043 // Disallow instances because they can cause havok
2044 return False;
2045 }
2046 if (PyNumber_Check(o1) && PyNumber_Check(o2)) {
2047 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2048 point->x = PyInt_AsLong(o1);
2049 point->y = PyInt_AsLong(o2);
2050 return True;
2051 }
2052 return False;
2053 }
2054
2055
2056 wxPoint* wxPoint_LIST_helper(PyObject* source, int *count) {
2057 // Putting all of the declarations here allows
2058 // us to put the error handling all in one place.
2059 int x;
2060 wxPoint* temp;
2061 PyObject *o, *o1, *o2;
2062 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2063
2064 if (!PySequence_Check(source)) {
2065 goto error0;
2066 }
2067
2068 // The length of the sequence is returned in count.
2069 *count = PySequence_Length(source);
2070 if (*count < 0) {
2071 goto error0;
2072 }
2073
2074 temp = new wxPoint[*count];
2075 if (!temp) {
2076 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2077 return NULL;
2078 }
2079 for (x=0; x<*count; x++) {
2080 // Get an item: try fast way first.
2081 if (isFast) {
2082 o = PySequence_Fast_GET_ITEM(source, x);
2083 }
2084 else {
2085 o = PySequence_GetItem(source, x);
2086 if (o == NULL) {
2087 goto error1;
2088 }
2089 }
2090
2091 // Convert o to wxPoint.
2092 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
2093 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
2094 o1 = PySequence_Fast_GET_ITEM(o, 0);
2095 o2 = PySequence_Fast_GET_ITEM(o, 1);
2096 if (!wxPointFromObjects(o1, o2, &temp[x])) {
2097 goto error2;
2098 }
2099 }
2100 else if (wxPySwigInstance_Check(o)) {
2101 wxPoint* pt;
2102 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPoint"))) {
2103 goto error2;
2104 }
2105 temp[x] = *pt;
2106 }
2107 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
2108 o1 = PySequence_GetItem(o, 0);
2109 o2 = PySequence_GetItem(o, 1);
2110 if (!wxPointFromObjects(o1, o2, &temp[x])) {
2111 goto error3;
2112 }
2113 Py_DECREF(o1);
2114 Py_DECREF(o2);
2115 }
2116 else {
2117 goto error2;
2118 }
2119 // Clean up.
2120 if (!isFast)
2121 Py_DECREF(o);
2122 }
2123 return temp;
2124
2125 error3:
2126 Py_DECREF(o1);
2127 Py_DECREF(o2);
2128 error2:
2129 if (!isFast)
2130 Py_DECREF(o);
2131 error1:
2132 delete [] temp;
2133 error0:
2134 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoints.");
2135 return NULL;
2136 }
2137 // end of patch
2138 //------------------------------
2139
2140
2141 wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
2142 if (!PyList_Check(source)) {
2143 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2144 return NULL;
2145 }
2146 int count = PyList_Size(source);
2147 wxBitmap** temp = new wxBitmap*[count];
2148 if (! temp) {
2149 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2150 return NULL;
2151 }
2152 for (int x=0; x<count; x++) {
2153 PyObject* o = PyList_GetItem(source, x);
2154 if (wxPySwigInstance_Check(o)) {
2155 wxBitmap* pt;
2156 if (! wxPyConvertSwigPtr(o, (void **) &pt, wxT("wxBitmap"))) {
2157 PyErr_SetString(PyExc_TypeError,"Expected wxBitmap.");
2158 return NULL;
2159 }
2160 temp[x] = pt;
2161 }
2162 else {
2163 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
2164 return NULL;
2165 }
2166 }
2167 return temp;
2168 }
2169
2170
2171
2172 wxString* wxString_LIST_helper(PyObject* source) {
2173 if (!PyList_Check(source)) {
2174 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2175 return NULL;
2176 }
2177 int count = PyList_Size(source);
2178 wxString* temp = new wxString[count];
2179 if (! temp) {
2180 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2181 return NULL;
2182 }
2183 for (int x=0; x<count; x++) {
2184 PyObject* o = PyList_GetItem(source, x);
2185 #if PYTHON_API_VERSION >= 1009
2186 if (! PyString_Check(o) && ! PyUnicode_Check(o)) {
2187 PyErr_SetString(PyExc_TypeError, "Expected a list of string or unicode objects.");
2188 return NULL;
2189 }
2190 #else
2191 if (! PyString_Check(o)) {
2192 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2193 return NULL;
2194 }
2195 #endif
2196
2197 wxString* pStr = wxString_in_helper(o);
2198 temp[x] = *pStr;
2199 delete pStr;
2200 }
2201 return temp;
2202 }
2203
2204
2205 wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
2206 if (!PyList_Check(source)) {
2207 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2208 return NULL;
2209 }
2210 int count = PyList_Size(source);
2211 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
2212 if (! temp) {
2213 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2214 return NULL;
2215 }
2216 for (int x=0; x<count; x++) {
2217 PyObject* o = PyList_GetItem(source, x);
2218 if (wxPySwigInstance_Check(o)) {
2219 wxAcceleratorEntry* ae;
2220 if (! wxPyConvertSwigPtr(o, (void **) &ae, wxT("wxAcceleratorEntry"))) {
2221 PyErr_SetString(PyExc_TypeError,"Expected wxAcceleratorEntry.");
2222 return NULL;
2223 }
2224 temp[x] = *ae;
2225 }
2226 else if (PyTuple_Check(o)) {
2227 PyObject* o1 = PyTuple_GetItem(o, 0);
2228 PyObject* o2 = PyTuple_GetItem(o, 1);
2229 PyObject* o3 = PyTuple_GetItem(o, 2);
2230 temp[x].Set(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2231 }
2232 else {
2233 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2234 return NULL;
2235 }
2236 }
2237 return temp;
2238 }
2239
2240
2241 wxPen** wxPen_LIST_helper(PyObject* source) {
2242 if (!PyList_Check(source)) {
2243 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2244 return NULL;
2245 }
2246 int count = PyList_Size(source);
2247 wxPen** temp = new wxPen*[count];
2248 if (!temp) {
2249 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2250 return NULL;
2251 }
2252 for (int x=0; x<count; x++) {
2253 PyObject* o = PyList_GetItem(source, x);
2254 if (wxPySwigInstance_Check(o)) {
2255 wxPen* pt;
2256 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPen"))) {
2257 delete temp;
2258 PyErr_SetString(PyExc_TypeError,"Expected wxPen.");
2259 return NULL;
2260 }
2261 temp[x] = pt;
2262 }
2263 else {
2264 delete temp;
2265 PyErr_SetString(PyExc_TypeError, "Expected a list of wxPens.");
2266 return NULL;
2267 }
2268 }
2269 return temp;
2270 }
2271
2272
2273 bool wxPy2int_seq_helper(PyObject* source, int* i1, int* i2) {
2274 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2275 PyObject *o1, *o2;
2276
2277 if (!PySequence_Check(source) || PySequence_Length(source) != 2)
2278 return False;
2279
2280 if (isFast) {
2281 o1 = PySequence_Fast_GET_ITEM(source, 0);
2282 o2 = PySequence_Fast_GET_ITEM(source, 1);
2283 }
2284 else {
2285 o1 = PySequence_GetItem(source, 0);
2286 o2 = PySequence_GetItem(source, 1);
2287 }
2288
2289 *i1 = PyInt_AsLong(o1);
2290 *i2 = PyInt_AsLong(o2);
2291
2292 if (! isFast) {
2293 Py_DECREF(o1);
2294 Py_DECREF(o2);
2295 }
2296 return True;
2297 }
2298
2299
2300 bool wxPy4int_seq_helper(PyObject* source, int* i1, int* i2, int* i3, int* i4) {
2301 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2302 PyObject *o1, *o2, *o3, *o4;
2303
2304 if (!PySequence_Check(source) || PySequence_Length(source) != 4)
2305 return False;
2306
2307 if (isFast) {
2308 o1 = PySequence_Fast_GET_ITEM(source, 0);
2309 o2 = PySequence_Fast_GET_ITEM(source, 1);
2310 o3 = PySequence_Fast_GET_ITEM(source, 2);
2311 o4 = PySequence_Fast_GET_ITEM(source, 3);
2312 }
2313 else {
2314 o1 = PySequence_GetItem(source, 0);
2315 o2 = PySequence_GetItem(source, 1);
2316 o3 = PySequence_GetItem(source, 2);
2317 o4 = PySequence_GetItem(source, 3);
2318 }
2319
2320 *i1 = PyInt_AsLong(o1);
2321 *i2 = PyInt_AsLong(o2);
2322 *i3 = PyInt_AsLong(o3);
2323 *i4 = PyInt_AsLong(o4);
2324
2325 if (! isFast) {
2326 Py_DECREF(o1);
2327 Py_DECREF(o2);
2328 Py_DECREF(o3);
2329 Py_DECREF(o4);
2330 }
2331 return True;
2332 }
2333
2334
2335 //----------------------------------------------------------------------
2336
2337 bool wxPySimple_typecheck(PyObject* source, const wxChar* classname, int seqLen)
2338 {
2339 void* ptr;
2340
2341 if (wxPySwigInstance_Check(source) &&
2342 wxPyConvertSwigPtr(source, (void **)&ptr, classname))
2343 return True;
2344
2345 PyErr_Clear();
2346 if (PySequence_Check(source) && PySequence_Length(source) == seqLen)
2347 return True;
2348
2349 return False;
2350 }
2351
2352 bool wxSize_helper(PyObject* source, wxSize** obj)
2353 {
2354 if (source == Py_None) {
2355 **obj = wxSize(-1,-1);
2356 return True;
2357 }
2358 return wxPyTwoIntItem_helper(source, obj, wxT("wxSize"));
2359 }
2360
2361
2362 bool wxPoint_helper(PyObject* source, wxPoint** obj)
2363 {
2364 if (source == Py_None) {
2365 **obj = wxPoint(-1,-1);
2366 return True;
2367 }
2368 return wxPyTwoIntItem_helper(source, obj, wxT("wxPoint"));
2369 }
2370
2371
2372
2373 bool wxRealPoint_helper(PyObject* source, wxRealPoint** obj) {
2374
2375 if (source == Py_None) {
2376 **obj = wxRealPoint(-1,-1);
2377 return True;
2378 }
2379
2380 // If source is an object instance then it may already be the right type
2381 if (wxPySwigInstance_Check(source)) {
2382 wxRealPoint* ptr;
2383 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRealPoint")))
2384 goto error;
2385 *obj = ptr;
2386 return True;
2387 }
2388 // otherwise a 2-tuple of floats is expected
2389 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
2390 PyObject* o1 = PySequence_GetItem(source, 0);
2391 PyObject* o2 = PySequence_GetItem(source, 1);
2392 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2393 Py_DECREF(o1);
2394 Py_DECREF(o2);
2395 goto error;
2396 }
2397 **obj = wxRealPoint(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2398 Py_DECREF(o1);
2399 Py_DECREF(o2);
2400 return True;
2401 }
2402
2403 error:
2404 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxRealPoint object.");
2405 return False;
2406 }
2407
2408
2409
2410 bool wxRect_helper(PyObject* source, wxRect** obj) {
2411
2412 if (source == Py_None) {
2413 **obj = wxRect(-1,-1,-1,-1);
2414 return True;
2415 }
2416
2417 // If source is an object instance then it may already be the right type
2418 if (wxPySwigInstance_Check(source)) {
2419 wxRect* ptr;
2420 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRect")))
2421 goto error;
2422 *obj = ptr;
2423 return True;
2424 }
2425 // otherwise a 4-tuple of integers is expected
2426 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2427 PyObject* o1 = PySequence_GetItem(source, 0);
2428 PyObject* o2 = PySequence_GetItem(source, 1);
2429 PyObject* o3 = PySequence_GetItem(source, 2);
2430 PyObject* o4 = PySequence_GetItem(source, 3);
2431 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2432 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2433 Py_DECREF(o1);
2434 Py_DECREF(o2);
2435 Py_DECREF(o3);
2436 Py_DECREF(o4);
2437 goto error;
2438 }
2439 **obj = wxRect(PyInt_AsLong(o1), PyInt_AsLong(o2),
2440 PyInt_AsLong(o3), PyInt_AsLong(o4));
2441 Py_DECREF(o1);
2442 Py_DECREF(o2);
2443 Py_DECREF(o3);
2444 Py_DECREF(o4);
2445 return True;
2446 }
2447
2448 error:
2449 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of integers or a wxRect object.");
2450 return False;
2451 }
2452
2453
2454
2455 bool wxColour_helper(PyObject* source, wxColour** obj) {
2456
2457 if (source == Py_None) {
2458 **obj = wxNullColour;
2459 return True;
2460 }
2461
2462 // If source is an object instance then it may already be the right type
2463 if (wxPySwigInstance_Check(source)) {
2464 wxColour* ptr;
2465 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxColour")))
2466 goto error;
2467 *obj = ptr;
2468 return True;
2469 }
2470 // otherwise check for a string
2471 else if (PyString_Check(source) || PyUnicode_Check(source)) {
2472 wxString spec = Py2wxString(source);
2473 if (spec.GetChar(0) == '#' && spec.Length() == 7) { // It's #RRGGBB
2474 long red, green, blue;
2475 red = green = blue = 0;
2476 spec.Mid(1,2).ToLong(&red, 16);
2477 spec.Mid(3,2).ToLong(&green, 16);
2478 spec.Mid(5,2).ToLong(&blue, 16);
2479
2480 **obj = wxColour(red, green, blue);
2481 return True;
2482 }
2483 else { // it's a colour name
2484 **obj = wxColour(spec);
2485 return True;
2486 }
2487 }
2488 // last chance: 3-tuple of integers is expected
2489 else if (PySequence_Check(source) && PyObject_Length(source) == 3) {
2490 PyObject* o1 = PySequence_GetItem(source, 0);
2491 PyObject* o2 = PySequence_GetItem(source, 1);
2492 PyObject* o3 = PySequence_GetItem(source, 2);
2493 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3)) {
2494 Py_DECREF(o1);
2495 Py_DECREF(o2);
2496 Py_DECREF(o3);
2497 goto error;
2498 }
2499 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2500 Py_DECREF(o1);
2501 Py_DECREF(o2);
2502 Py_DECREF(o3);
2503 return True;
2504 }
2505
2506 error:
2507 PyErr_SetString(PyExc_TypeError,
2508 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2509 return False;
2510 }
2511
2512
2513 bool wxColour_typecheck(PyObject* source) {
2514
2515 if (wxPySimple_typecheck(source, wxT("wxColour"), 3))
2516 return True;
2517
2518 if (PyString_Check(source) || PyUnicode_Check(source))
2519 return True;
2520
2521 return False;
2522 }
2523
2524
2525
2526 bool wxPoint2D_helper(PyObject* source, wxPoint2D** obj) {
2527
2528 if (source == Py_None) {
2529 **obj = wxPoint2D(-1,-1);
2530 return True;
2531 }
2532
2533 // If source is an object instance then it may already be the right type
2534 if (wxPySwigInstance_Check(source)) {
2535 wxPoint2D* ptr;
2536 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxPoint2D")))
2537 goto error;
2538 *obj = ptr;
2539 return True;
2540 }
2541 // otherwise a length-2 sequence of floats is expected
2542 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
2543 PyObject* o1 = PySequence_GetItem(source, 0);
2544 PyObject* o2 = PySequence_GetItem(source, 1);
2545 // This should really check for floats, not numbers -- but that would break code.
2546 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2547 Py_DECREF(o1);
2548 Py_DECREF(o2);
2549 goto error;
2550 }
2551 **obj = wxPoint2D(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2552 Py_DECREF(o1);
2553 Py_DECREF(o2);
2554 return True;
2555 }
2556 error:
2557 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxPoint2D object.");
2558 return False;
2559 }
2560
2561
2562 //----------------------------------------------------------------------
2563
2564 PyObject* wxArrayString2PyList_helper(const wxArrayString& arr) {
2565
2566 PyObject* list = PyList_New(0);
2567 for (size_t i=0; i < arr.GetCount(); i++) {
2568 #if wxUSE_UNICODE
2569 PyObject* str = PyUnicode_FromWideChar(arr[i].c_str(), arr[i].Len());
2570 #else
2571 PyObject* str = PyString_FromStringAndSize(arr[i].c_str(), arr[i].Len());
2572 #endif
2573 PyList_Append(list, str);
2574 Py_DECREF(str);
2575 }
2576 return list;
2577 }
2578
2579
2580 PyObject* wxArrayInt2PyList_helper(const wxArrayInt& arr) {
2581
2582 PyObject* list = PyList_New(0);
2583 for (size_t i=0; i < arr.GetCount(); i++) {
2584 PyObject* number = PyInt_FromLong(arr[i]);
2585 PyList_Append(list, number);
2586 Py_DECREF(number);
2587 }
2588 return list;
2589 }
2590
2591
2592 //----------------------------------------------------------------------
2593 //----------------------------------------------------------------------
2594
2595
2596
2597