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