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