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