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