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