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