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