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