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