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