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