]> git.saurik.com Git - wxWidgets.git/blob - wxPython/src/helpers.cpp
SetCanFocus
[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 }
846 }
847
848 // m_obj is DECREF'd in the base class dtor...
849 wxPyEndBlockThreads(blocked);
850 }
851
852
853 //---------------------------------------------------------------------------
854 // Stuff used by OOR to find the right wxPython class type to return and to
855 // build it.
856
857
858 // The pointer type map is used when the "pointer" type name generated by SWIG
859 // is not the same as the shadow class name, for example wxPyTreeCtrl
860 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
861 // so we'll just make it a Python dictionary in the wx module's namespace.
862 // (See __wxSetDictionary)
863 void wxPyPtrTypeMap_Add(const char* commonName, const char* ptrName) {
864 if (! wxPyPtrTypeMap)
865 wxPyPtrTypeMap = PyDict_New();
866 PyDict_SetItemString(wxPyPtrTypeMap,
867 (char*)commonName,
868 PyString_FromString((char*)ptrName));
869 }
870
871
872
873
874 PyObject* wxPyMake_wxObject(wxObject* source, bool setThisOwn, bool checkEvtHandler) {
875 PyObject* target = NULL;
876 bool isEvtHandler = false;
877 bool isSizer = false;
878
879 if (source) {
880 // If it's derived from wxEvtHandler then there may
881 // already be a pointer to a Python object that we can use
882 // in the OOR data.
883 if (checkEvtHandler && wxIsKindOf(source, wxEvtHandler)) {
884 isEvtHandler = true;
885 wxEvtHandler* eh = (wxEvtHandler*)source;
886 wxPyOORClientData* data = (wxPyOORClientData*)eh->GetClientObject();
887 if (data) {
888 target = data->m_obj;
889 if (target)
890 Py_INCREF(target);
891 }
892 }
893
894 // Also check for wxSizer
895 if (!target && wxIsKindOf(source, wxSizer)) {
896 isSizer = true;
897 wxSizer* sz = (wxSizer*)source;
898 wxPyOORClientData* data = (wxPyOORClientData*)sz->GetClientObject();
899 if (data) {
900 target = data->m_obj;
901 if (target)
902 Py_INCREF(target);
903 }
904 }
905
906 if (! target) {
907 // Otherwise make it the old fashioned way by making a new shadow
908 // object and putting this pointer in it. Look up the class
909 // heirarchy until we find a class name that is located in the
910 // python module.
911 const wxClassInfo* info = source->GetClassInfo();
912 wxString name = info->GetClassName();
913 bool exists = wxPyCheckSwigType(name);
914 while (info && !exists) {
915 info = info->GetBaseClass1();
916 name = info->GetClassName();
917 exists = wxPyCheckSwigType(name);
918 }
919 if (info) {
920 target = wxPyConstructObject((void*)source, name, setThisOwn);
921 if (target && isEvtHandler)
922 ((wxEvtHandler*)source)->SetClientObject(new wxPyOORClientData(target));
923 if (target && isSizer)
924 ((wxSizer*)source)->SetClientObject(new wxPyOORClientData(target));
925 } else {
926 wxString msg(wxT("wxPython class not found for "));
927 msg += source->GetClassInfo()->GetClassName();
928 PyErr_SetString(PyExc_NameError, msg.mbc_str());
929 target = NULL;
930 }
931 }
932 } else { // source was NULL so return None.
933 Py_INCREF(Py_None); target = Py_None;
934 }
935 return target;
936 }
937
938
939 PyObject* wxPyMake_wxSizer(wxSizer* source, bool setThisOwn) {
940
941 return wxPyMake_wxObject(source, setThisOwn);
942 }
943
944
945 //---------------------------------------------------------------------------
946
947
948 #ifdef WXP_WITH_THREAD
949 #if !wxPyUSE_GIL_STATE
950
951 inline
952 unsigned long wxPyGetCurrentThreadId() {
953 return wxThread::GetCurrentId();
954 }
955
956 static wxPyThreadState gs_shutdownTState;
957
958 static
959 wxPyThreadState* wxPyGetThreadState() {
960 if (wxPyTMutex == NULL) // Python is shutting down...
961 return &gs_shutdownTState;
962
963 unsigned long ctid = wxPyGetCurrentThreadId();
964 wxPyThreadState* tstate = NULL;
965
966 wxPyTMutex->Lock();
967 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
968 wxPyThreadState& info = wxPyTStates->Item(i);
969 if (info.tid == ctid) {
970 tstate = &info;
971 break;
972 }
973 }
974 wxPyTMutex->Unlock();
975 wxASSERT_MSG(tstate, wxT("PyThreadState should not be NULL!"));
976 return tstate;
977 }
978
979
980 static
981 void wxPySaveThreadState(PyThreadState* tstate) {
982 if (wxPyTMutex == NULL) { // Python is shutting down, assume a single thread...
983 gs_shutdownTState.tstate = tstate;
984 return;
985 }
986 unsigned long ctid = wxPyGetCurrentThreadId();
987 wxPyTMutex->Lock();
988 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
989 wxPyThreadState& info = wxPyTStates->Item(i);
990 if (info.tid == ctid) {
991 #if 0
992 if (info.tstate != tstate)
993 wxLogMessage("*** tstate mismatch!???");
994 #endif
995 info.tstate = tstate; // allow for transient tstates
996 // Normally it will never change, but apparently COM callbacks
997 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
998 // tstate which will then be garbage the next time we try to use
999 // it...
1000
1001 wxPyTMutex->Unlock();
1002 return;
1003 }
1004 }
1005 // not found, so add it...
1006 wxPyTStates->Add(new wxPyThreadState(ctid, tstate));
1007 wxPyTMutex->Unlock();
1008 }
1009
1010 #endif
1011 #endif
1012
1013
1014
1015 // Calls from Python to wxWindows code are wrapped in calls to these
1016 // functions:
1017
1018 PyThreadState* wxPyBeginAllowThreads() {
1019 #ifdef WXP_WITH_THREAD
1020 PyThreadState* saved = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1021 #if !wxPyUSE_GIL_STATE
1022 wxPySaveThreadState(saved);
1023 #endif
1024 return saved;
1025 #else
1026 return NULL;
1027 #endif
1028 }
1029
1030 void wxPyEndAllowThreads(PyThreadState* saved) {
1031 #ifdef WXP_WITH_THREAD
1032 PyEval_RestoreThread(saved); // Py_END_ALLOW_THREADS;
1033 #endif
1034 }
1035
1036
1037
1038 // Calls from wxWindows back to Python code, or even any PyObject
1039 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1040
1041 wxPyBlock_t wxPyBeginBlockThreads() {
1042 #ifdef WXP_WITH_THREAD
1043 if (! Py_IsInitialized()) {
1044 return (wxPyBlock_t)0;
1045 }
1046 #if wxPyUSE_GIL_STATE
1047 PyGILState_STATE state = PyGILState_Ensure();
1048 return state;
1049 #else
1050 PyThreadState *current = _PyThreadState_Current;
1051
1052 // Only block if there wasn't already a tstate, or if the current one is
1053 // not the one we are wanting to change to. This should prevent deadlock
1054 // if there are nested calls to wxPyBeginBlockThreads
1055 wxPyBlock_t blocked = false;
1056 wxPyThreadState* tstate = wxPyGetThreadState();
1057 if (current != tstate->tstate) {
1058 PyEval_RestoreThread(tstate->tstate);
1059 blocked = true;
1060 }
1061 return blocked;
1062 #endif
1063 #else
1064 return (wxPyBlock_t)0;
1065 #endif
1066 }
1067
1068
1069 void wxPyEndBlockThreads(wxPyBlock_t blocked) {
1070 #ifdef WXP_WITH_THREAD
1071 if (! Py_IsInitialized()) {
1072 return;
1073 }
1074 #if wxPyUSE_GIL_STATE
1075 PyGILState_Release(blocked);
1076 #else
1077 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1078 // The value of blocked passed in needs to be the same as that returned
1079 // from wxPyBeginBlockThreads at the same nesting level.
1080 if ( blocked ) {
1081 PyEval_SaveThread();
1082 }
1083 #endif
1084 #endif
1085 }
1086
1087
1088 //---------------------------------------------------------------------------
1089 // wxPyInputStream and wxPyCBInputStream methods
1090
1091
1092 void wxPyInputStream::close() {
1093 /* do nothing for now */
1094 }
1095
1096 void wxPyInputStream::flush() {
1097 /* do nothing for now */
1098 }
1099
1100 bool wxPyInputStream::eof() {
1101 if (m_wxis)
1102 return m_wxis->Eof();
1103 else
1104 return true;
1105 }
1106
1107 wxPyInputStream::~wxPyInputStream() {
1108 if (m_wxis)
1109 delete m_wxis;
1110 }
1111
1112
1113
1114
1115 PyObject* wxPyInputStream::read(int size) {
1116 PyObject* obj = NULL;
1117 wxMemoryBuffer buf;
1118 const int BUFSIZE = 1024;
1119
1120 // check if we have a real wxInputStream to work with
1121 if (!m_wxis) {
1122 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1123 PyErr_SetString(PyExc_IOError, "no valid C-wxInputStream");
1124 wxPyEndBlockThreads(blocked);
1125 return NULL;
1126 }
1127
1128 if (size < 0) {
1129 // read while bytes are available on the stream
1130 while ( m_wxis->CanRead() ) {
1131 m_wxis->Read(buf.GetAppendBuf(BUFSIZE), BUFSIZE);
1132 buf.UngetAppendBuf(m_wxis->LastRead());
1133 }
1134
1135 } else { // Read only size number of characters
1136 m_wxis->Read(buf.GetWriteBuf(size), size);
1137 buf.UngetWriteBuf(m_wxis->LastRead());
1138 }
1139
1140 // error check
1141 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1142 wxStreamError err = m_wxis->GetLastError();
1143 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1144 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1145 }
1146 else {
1147 // We use only strings for the streams, not unicode
1148 obj = PyString_FromStringAndSize(buf, buf.GetDataLen());
1149 }
1150 wxPyEndBlockThreads(blocked);
1151 return obj;
1152 }
1153
1154
1155 PyObject* wxPyInputStream::readline(int size) {
1156 PyObject* obj = NULL;
1157 wxMemoryBuffer buf;
1158 int i;
1159 char ch;
1160
1161 // check if we have a real wxInputStream to work with
1162 if (!m_wxis) {
1163 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1164 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1165 wxPyEndBlockThreads(blocked);
1166 return NULL;
1167 }
1168
1169 // read until \n or byte limit reached
1170 for (i=ch=0; (ch != '\n') && (m_wxis->CanRead()) && ((size < 0) || (i < size)); i++) {
1171 ch = m_wxis->GetC();
1172 buf.AppendByte(ch);
1173 }
1174
1175 // errorcheck
1176 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1177 wxStreamError err = m_wxis->GetLastError();
1178 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1179 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1180 }
1181 else {
1182 // We use only strings for the streams, not unicode
1183 obj = PyString_FromStringAndSize((char*)buf.GetData(), buf.GetDataLen());
1184 }
1185 wxPyEndBlockThreads(blocked);
1186 return obj;
1187 }
1188
1189
1190 PyObject* wxPyInputStream::readlines(int sizehint) {
1191 PyObject* pylist;
1192
1193 // check if we have a real wxInputStream to work with
1194 if (!m_wxis) {
1195 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1196 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
1197 wxPyEndBlockThreads(blocked);
1198 return NULL;
1199 }
1200
1201 // init list
1202 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1203 pylist = PyList_New(0);
1204 wxPyEndBlockThreads(blocked);
1205
1206 if (!pylist) {
1207 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1208 PyErr_NoMemory();
1209 wxPyEndBlockThreads(blocked);
1210 return NULL;
1211 }
1212
1213 // read sizehint bytes or until EOF
1214 int i;
1215 for (i=0; (m_wxis->CanRead()) && ((sizehint < 0) || (i < sizehint));) {
1216 PyObject* s = this->readline();
1217 if (s == NULL) {
1218 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1219 Py_DECREF(pylist);
1220 wxPyEndBlockThreads(blocked);
1221 return NULL;
1222 }
1223 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1224 PyList_Append(pylist, s);
1225 i += PyString_Size(s);
1226 wxPyEndBlockThreads(blocked);
1227 }
1228
1229 // error check
1230 wxStreamError err = m_wxis->GetLastError();
1231 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
1232 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1233 Py_DECREF(pylist);
1234 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1235 wxPyEndBlockThreads(blocked);
1236 return NULL;
1237 }
1238
1239 return pylist;
1240 }
1241
1242
1243 void wxPyInputStream::seek(int offset, int whence) {
1244 if (m_wxis)
1245 m_wxis->SeekI(offset, wxSeekMode(whence));
1246 }
1247
1248 int wxPyInputStream::tell(){
1249 if (m_wxis)
1250 return m_wxis->TellI();
1251 else return 0;
1252 }
1253
1254
1255
1256
1257 wxPyCBInputStream::wxPyCBInputStream(PyObject *r, PyObject *s, PyObject *t, bool block)
1258 : wxInputStream(), m_read(r), m_seek(s), m_tell(t), m_block(block)
1259 {}
1260
1261 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream& other)
1262 {
1263 m_read = other.m_read;
1264 m_seek = other.m_seek;
1265 m_tell = other.m_tell;
1266 m_block = other.m_block;
1267 Py_INCREF(m_read);
1268 Py_INCREF(m_seek);
1269 Py_INCREF(m_tell);
1270 }
1271
1272
1273 wxPyCBInputStream::~wxPyCBInputStream() {
1274 wxPyBlock_t blocked = wxPyBlock_t_default;
1275 if (m_block) blocked = wxPyBeginBlockThreads();
1276 Py_XDECREF(m_read);
1277 Py_XDECREF(m_seek);
1278 Py_XDECREF(m_tell);
1279 if (m_block) wxPyEndBlockThreads(blocked);
1280 }
1281
1282
1283 wxPyCBInputStream* wxPyCBInputStream::create(PyObject *py, bool block) {
1284 wxPyBlock_t blocked = wxPyBlock_t_default;
1285 if (block) blocked = wxPyBeginBlockThreads();
1286
1287 PyObject* read = getMethod(py, "read");
1288 PyObject* seek = getMethod(py, "seek");
1289 PyObject* tell = getMethod(py, "tell");
1290
1291 if (!read) {
1292 PyErr_SetString(PyExc_TypeError, "Not a file-like object");
1293 Py_XDECREF(read);
1294 Py_XDECREF(seek);
1295 Py_XDECREF(tell);
1296 if (block) wxPyEndBlockThreads(blocked);
1297 return NULL;
1298 }
1299
1300 if (block) wxPyEndBlockThreads(blocked);
1301 return new wxPyCBInputStream(read, seek, tell, block);
1302 }
1303
1304
1305 wxPyCBInputStream* wxPyCBInputStream_create(PyObject *py, bool block) {
1306 return wxPyCBInputStream::create(py, block);
1307 }
1308
1309 wxPyCBInputStream* wxPyCBInputStream_copy(wxPyCBInputStream* other) {
1310 return new wxPyCBInputStream(*other);
1311 }
1312
1313 PyObject* wxPyCBInputStream::getMethod(PyObject* py, char* name) {
1314 if (!PyObject_HasAttrString(py, name))
1315 return NULL;
1316 PyObject* o = PyObject_GetAttrString(py, name);
1317 if (!PyMethod_Check(o) && !PyCFunction_Check(o)) {
1318 Py_DECREF(o);
1319 return NULL;
1320 }
1321 return o;
1322 }
1323
1324
1325 wxFileOffset wxPyCBInputStream::GetLength() const {
1326 wxPyCBInputStream* self = (wxPyCBInputStream*)this; // cast off const
1327 if (m_seek && m_tell) {
1328 wxFileOffset temp = self->OnSysTell();
1329 wxFileOffset ret = self->OnSysSeek(0, wxFromEnd);
1330 self->OnSysSeek(temp, wxFromStart);
1331 return ret;
1332 }
1333 else
1334 return wxInvalidOffset;
1335 }
1336
1337
1338 size_t wxPyCBInputStream::OnSysRead(void *buffer, size_t bufsize) {
1339 if (bufsize == 0)
1340 return 0;
1341
1342 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1343 PyObject* arglist = Py_BuildValue("(i)", bufsize);
1344 PyObject* result = PyEval_CallObject(m_read, arglist);
1345 Py_DECREF(arglist);
1346
1347 size_t o = 0;
1348 if ((result != NULL) && PyString_Check(result)) {
1349 o = PyString_Size(result);
1350 if (o == 0)
1351 m_lasterror = wxSTREAM_EOF;
1352 if (o > bufsize)
1353 o = bufsize;
1354 memcpy((char*)buffer, PyString_AsString(result), o); // strings only, not unicode...
1355 Py_DECREF(result);
1356
1357 }
1358 else
1359 m_lasterror = wxSTREAM_READ_ERROR;
1360 wxPyEndBlockThreads(blocked);
1361 return o;
1362 }
1363
1364 size_t wxPyCBInputStream::OnSysWrite(const void *buffer, size_t bufsize) {
1365 m_lasterror = wxSTREAM_WRITE_ERROR;
1366 return 0;
1367 }
1368
1369
1370 wxFileOffset wxPyCBInputStream::OnSysSeek(wxFileOffset off, wxSeekMode mode) {
1371 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1372 PyObject* arglist = PyTuple_New(2);
1373
1374 if (sizeof(wxFileOffset) > sizeof(long))
1375 // wxFileOffset is a 64-bit value...
1376 PyTuple_SET_ITEM(arglist, 0, PyLong_FromLongLong(off));
1377 else
1378 PyTuple_SET_ITEM(arglist, 0, PyInt_FromLong(off));
1379
1380 PyTuple_SET_ITEM(arglist, 1, PyInt_FromLong(mode));
1381
1382
1383 PyObject* result = PyEval_CallObject(m_seek, arglist);
1384 Py_DECREF(arglist);
1385 Py_XDECREF(result);
1386 wxPyEndBlockThreads(blocked);
1387 return OnSysTell();
1388 }
1389
1390
1391 wxFileOffset wxPyCBInputStream::OnSysTell() const {
1392 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1393 PyObject* arglist = Py_BuildValue("()");
1394 PyObject* result = PyEval_CallObject(m_tell, arglist);
1395 Py_DECREF(arglist);
1396 wxFileOffset o = 0;
1397 if (result != NULL) {
1398 if (PyLong_Check(result))
1399 o = PyLong_AsLongLong(result);
1400 else
1401 o = PyInt_AsLong(result);
1402 Py_DECREF(result);
1403 };
1404 wxPyEndBlockThreads(blocked);
1405 return o;
1406 }
1407
1408 //----------------------------------------------------------------------
1409
1410 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback, wxObject);
1411
1412 wxPyCallback::wxPyCallback(PyObject* func) {
1413 m_func = func;
1414 Py_INCREF(m_func);
1415 }
1416
1417 wxPyCallback::wxPyCallback(const wxPyCallback& other) {
1418 m_func = other.m_func;
1419 Py_INCREF(m_func);
1420 }
1421
1422 wxPyCallback::~wxPyCallback() {
1423 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1424 Py_DECREF(m_func);
1425 wxPyEndBlockThreads(blocked);
1426 }
1427
1428
1429 #define wxPy_PRECALLINIT "_preCallInit"
1430 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1431
1432 // This function is used for all events destined for Python event handlers.
1433 void wxPyCallback::EventThunker(wxEvent& event) {
1434 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
1435 PyObject* func = cb->m_func;
1436 PyObject* result;
1437 PyObject* arg;
1438 PyObject* tuple;
1439 bool checkSkip = false;
1440
1441 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1442 wxString className = event.GetClassInfo()->GetClassName();
1443
1444 // If the event is one of these types then pass the original
1445 // event object instead of the one passed to us.
1446 if ( className == wxT("wxPyEvent") ) {
1447 arg = ((wxPyEvent*)&event)->GetSelf();
1448 checkSkip = ((wxPyEvent*)&event)->GetCloned();
1449 }
1450 else if ( className == wxT("wxPyCommandEvent") ) {
1451 arg = ((wxPyCommandEvent*)&event)->GetSelf();
1452 checkSkip = ((wxPyCommandEvent*)&event)->GetCloned();
1453 }
1454 else {
1455 arg = wxPyConstructObject((void*)&event, className);
1456 }
1457
1458 if (!arg) {
1459 PyErr_Print();
1460 } else {
1461 // "intern" the pre/post method names to speed up the HasAttr
1462 static PyObject* s_preName = NULL;
1463 static PyObject* s_postName = NULL;
1464 if (s_preName == NULL) {
1465 s_preName = PyString_FromString(wxPy_PRECALLINIT);
1466 s_postName = PyString_FromString(wxPy_POSTCALLCLEANUP);
1467 }
1468
1469 // Check if the event object needs some preinitialization
1470 if (PyObject_HasAttr(arg, s_preName)) {
1471 result = PyObject_CallMethodObjArgs(arg, s_preName, arg, NULL);
1472 if ( result ) {
1473 Py_DECREF(result); // result is ignored, but we still need to decref it
1474 PyErr_Clear(); // Just in case...
1475 } else {
1476 PyErr_Print();
1477 }
1478 }
1479
1480 // Call the event handler, passing the event object
1481 tuple = PyTuple_New(1);
1482 PyTuple_SET_ITEM(tuple, 0, arg); // steals ref to arg
1483 result = PyEval_CallObject(func, tuple);
1484 if ( result ) {
1485 Py_DECREF(result); // result is ignored, but we still need to decref it
1486 PyErr_Clear(); // Just in case...
1487 } else {
1488 PyErr_Print();
1489 }
1490
1491 // Check if the event object needs some post cleanup
1492 if (PyObject_HasAttr(arg, s_postName)) {
1493 result = PyObject_CallMethodObjArgs(arg, s_postName, arg, NULL);
1494 if ( result ) {
1495 Py_DECREF(result); // result is ignored, but we still need to decref it
1496 PyErr_Clear(); // Just in case...
1497 } else {
1498 PyErr_Print();
1499 }
1500 }
1501
1502 if ( checkSkip ) {
1503 // if the event object was one of our special types and
1504 // it had been cloned, then we need to extract the Skipped
1505 // value from the original and set it in the clone.
1506 result = PyObject_CallMethod(arg, "GetSkipped", "");
1507 if ( result ) {
1508 event.Skip(PyInt_AsLong(result));
1509 Py_DECREF(result);
1510 } else {
1511 PyErr_Print();
1512 }
1513 }
1514 Py_DECREF(tuple);
1515 }
1516 wxPyEndBlockThreads(blocked);
1517 }
1518
1519
1520 //----------------------------------------------------------------------
1521
1522 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper& other) {
1523 m_lastFound = NULL;
1524 m_self = other.m_self;
1525 m_class = other.m_class;
1526 if (m_self) {
1527 Py_INCREF(m_self);
1528 Py_INCREF(m_class);
1529 }
1530 }
1531
1532
1533 void wxPyCallbackHelper::setSelf(PyObject* self, PyObject* klass, int incref) {
1534 m_self = self;
1535 m_class = klass;
1536 m_incRef = incref;
1537 if (incref) {
1538 Py_INCREF(m_self);
1539 Py_INCREF(m_class);
1540 }
1541 }
1542
1543
1544 #if PYTHON_API_VERSION >= 1011
1545
1546 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1547 // in which the method was defined. Starting with 2.2 it returns
1548 // "class that asked for the method" which seems totally bogus to me
1549 // but apprently it fixes some obscure problem waiting to happen in
1550 // Python. Since the API was not documented Guido and the gang felt
1551 // safe in changing it. Needless to say that totally screwed up the
1552 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1553 // code to find the class where the method is actually defined...
1554
1555 static
1556 PyObject* PyFindClassWithAttr(PyObject *klass, PyObject *name)
1557 {
1558 int i, n;
1559
1560 if (PyType_Check(klass)) { // new style classes
1561 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1562 PyTypeObject* type = (PyTypeObject*)klass;
1563 PyObject *mro, *res, *base, *dict;
1564 /* Look in tp_dict of types in MRO */
1565 mro = type->tp_mro;
1566 assert(PyTuple_Check(mro));
1567 n = PyTuple_GET_SIZE(mro);
1568 for (i = 0; i < n; i++) {
1569 base = PyTuple_GET_ITEM(mro, i);
1570 if (PyClass_Check(base))
1571 dict = ((PyClassObject *)base)->cl_dict;
1572 else {
1573 assert(PyType_Check(base));
1574 dict = ((PyTypeObject *)base)->tp_dict;
1575 }
1576 assert(dict && PyDict_Check(dict));
1577 res = PyDict_GetItem(dict, name);
1578 if (res != NULL)
1579 return base;
1580 }
1581 return NULL;
1582 }
1583
1584 else if (PyClass_Check(klass)) { // old style classes
1585 // This code is borrowed/adapted from class_lookup in classobject.c
1586 PyClassObject* cp = (PyClassObject*)klass;
1587 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
1588 if (value != NULL) {
1589 return (PyObject*)cp;
1590 }
1591 n = PyTuple_Size(cp->cl_bases);
1592 for (i = 0; i < n; i++) {
1593 PyObject* base = PyTuple_GetItem(cp->cl_bases, i);
1594 PyObject *v = PyFindClassWithAttr(base, name);
1595 if (v != NULL)
1596 return v;
1597 }
1598 return NULL;
1599 }
1600 return NULL;
1601 }
1602 #endif
1603
1604
1605 static
1606 PyObject* PyMethod_GetDefiningClass(PyObject* method, PyObject* nameo)
1607 {
1608 PyObject* mgc = PyMethod_GET_CLASS(method);
1609
1610 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1611 return mgc;
1612 #else // 2.2 and after, the hard way...
1613 return PyFindClassWithAttr(mgc, nameo);
1614 #endif
1615 }
1616
1617
1618
1619 // To avoid recursion when an overridden virtual method wants to call the base
1620 // class version, temporarily set an attribute in the instance with the same
1621 // name as the method. Then the PyObject_GetAttr in the next findCallback
1622 // will return this attribute and the PyMethod_Check will fail.
1623
1624 void wxPyCallbackHelper::setRecursionGuard(PyObject* method) const
1625 {
1626 PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1627 PyObject_SetAttr(m_self, func->func_name, Py_None);
1628 }
1629
1630 void wxPyCallbackHelper::clearRecursionGuard(PyObject* method) const
1631 {
1632 PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1633 if (PyObject_HasAttr(m_self, func->func_name)) {
1634 PyObject_DelAttr(m_self, func->func_name);
1635 }
1636 }
1637
1638 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1639 // {
1640 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1641 // if (PyObject_HasAttr(m_self, func->func_name)) {
1642 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1643 // bool retval = (attr == Py_None);
1644 // Py_DECREF(attr);
1645 // return retval;
1646 // }
1647 // return false;
1648 // }
1649
1650
1651 bool wxPyCallbackHelper::findCallback(const char* name, bool setGuard) const {
1652 wxPyCallbackHelper* self = (wxPyCallbackHelper*)this; // cast away const
1653 PyObject *method, *klass;
1654 PyObject* nameo = PyString_FromString(name);
1655 self->m_lastFound = NULL;
1656
1657 // If the object (m_self) has an attibute of the given name...
1658 if (m_self && PyObject_HasAttr(m_self, nameo)) {
1659 method = PyObject_GetAttr(m_self, nameo);
1660
1661 // ...and if that attribute is a method, and if that method's class is
1662 // not from the registered class or a base class...
1663 if (PyMethod_Check(method) &&
1664 (klass = PyMethod_GetDefiningClass(method, nameo)) != NULL &&
1665 (klass != m_class) &&
1666 PyObject_IsSubclass(klass, m_class)) {
1667
1668 // ...then we'll save a pointer to the method so callCallback can
1669 // call it. But first, set a recursion guard in case the
1670 // overridden method wants to call the base class version.
1671 if (setGuard)
1672 setRecursionGuard(method);
1673 self->m_lastFound = method;
1674 }
1675 else {
1676 Py_DECREF(method);
1677 }
1678 }
1679
1680 Py_DECREF(nameo);
1681 return m_lastFound != NULL;
1682 }
1683
1684
1685 int wxPyCallbackHelper::callCallback(PyObject* argTuple) const {
1686 PyObject* result;
1687 int retval = false;
1688
1689 result = callCallbackObj(argTuple);
1690 if (result) { // Assumes an integer return type...
1691 retval = PyInt_AsLong(result);
1692 Py_DECREF(result);
1693 PyErr_Clear(); // forget about it if it's not...
1694 }
1695 return retval;
1696 }
1697
1698 // Invoke the Python callable object, returning the raw PyObject return
1699 // value. Caller should DECREF the return value and also manage the GIL.
1700 PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) const {
1701 PyObject* result;
1702
1703 // Save a copy of the pointer in case the callback generates another
1704 // callback. In that case m_lastFound will have a different value when
1705 // it gets back here...
1706 PyObject* method = m_lastFound;
1707
1708 result = PyEval_CallObject(method, argTuple);
1709 clearRecursionGuard(method);
1710
1711 Py_DECREF(argTuple);
1712 Py_DECREF(method);
1713 if (!result) {
1714 PyErr_Print();
1715 }
1716 return result;
1717 }
1718
1719
1720 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper& cbh, PyObject* self, PyObject* klass, int incref) {
1721 cbh.setSelf(self, klass, incref);
1722 }
1723
1724 bool wxPyCBH_findCallback(const wxPyCallbackHelper& cbh, const char* name, bool setGuard) {
1725 return cbh.findCallback(name, setGuard);
1726 }
1727
1728 int wxPyCBH_callCallback(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1729 return cbh.callCallback(argTuple);
1730 }
1731
1732 PyObject* wxPyCBH_callCallbackObj(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1733 return cbh.callCallbackObj(argTuple);
1734 }
1735
1736
1737 void wxPyCBH_delete(wxPyCallbackHelper* cbh) {
1738 if (cbh->m_incRef && Py_IsInitialized()) {
1739 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1740 Py_XDECREF(cbh->m_self);
1741 Py_XDECREF(cbh->m_class);
1742 wxPyEndBlockThreads(blocked);
1743 }
1744 }
1745
1746 //---------------------------------------------------------------------------
1747 //---------------------------------------------------------------------------
1748 // These event classes can be derived from in Python and passed through the event
1749 // system without losing anything. They do this by keeping a reference to
1750 // themselves and some special case handling in wxPyCallback::EventThunker.
1751
1752
1753 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1754 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1755 //Py_INCREF(m_self); // circular loops...
1756 m_cloned = false;
1757 }
1758
1759 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1760 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1761 if (m_cloned)
1762 Py_DECREF(m_self);
1763 wxPyEndBlockThreads(blocked);
1764 }
1765
1766 void wxPyEvtSelfRef::SetSelf(PyObject* self, bool clone) {
1767 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1768 if (m_cloned)
1769 Py_DECREF(m_self);
1770 m_self = self;
1771 if (clone) {
1772 Py_INCREF(m_self);
1773 m_cloned = true;
1774 }
1775 wxPyEndBlockThreads(blocked);
1776 }
1777
1778 PyObject* wxPyEvtSelfRef::GetSelf() const {
1779 Py_INCREF(m_self);
1780 return m_self;
1781 }
1782
1783
1784 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent, wxEvent);
1785 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent, wxCommandEvent);
1786
1787
1788 wxPyEvent::wxPyEvent(int winid, wxEventType commandType)
1789 : wxEvent(winid, commandType) {
1790 }
1791
1792
1793 wxPyEvent::wxPyEvent(const wxPyEvent& evt)
1794 : wxEvent(evt)
1795 {
1796 SetSelf(evt.m_self, true);
1797 }
1798
1799
1800 wxPyEvent::~wxPyEvent() {
1801 }
1802
1803
1804 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType, int id)
1805 : wxCommandEvent(commandType, id) {
1806 }
1807
1808
1809 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent& evt)
1810 : wxCommandEvent(evt)
1811 {
1812 SetSelf(evt.m_self, true);
1813 }
1814
1815
1816 wxPyCommandEvent::~wxPyCommandEvent() {
1817 }
1818
1819
1820
1821
1822
1823 //---------------------------------------------------------------------------
1824 //---------------------------------------------------------------------------
1825 // Convert a wxList to a Python List, only works for lists of wxObjects
1826
1827 PyObject* wxPy_ConvertList(wxListBase* listbase) {
1828 wxList* list = (wxList*)listbase; // this is probably bad...
1829 PyObject* pyList;
1830 PyObject* pyObj;
1831 wxObject* wxObj;
1832 wxNode* node = list->GetFirst();
1833
1834 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1835 pyList = PyList_New(0);
1836 while (node) {
1837 wxObj = node->GetData();
1838 pyObj = wxPyMake_wxObject(wxObj,false);
1839 PyList_Append(pyList, pyObj);
1840 Py_DECREF(pyObj); // the Append also does an INCREF, that's one more than we need.
1841 node = node->GetNext();
1842 }
1843 wxPyEndBlockThreads(blocked);
1844 return pyList;
1845 }
1846
1847 //----------------------------------------------------------------------
1848
1849 long wxPyGetWinHandle(wxWindow* win) {
1850
1851 #ifdef __WXMSW__
1852 return (long)win->GetHandle();
1853 #endif
1854
1855 #if defined(__WXGTK__) || defined(__WXX11)
1856 return (long)GetXWindow(win);
1857 #endif
1858
1859 #ifdef __WXMAC__
1860 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1861 return (long)win->GetHandle();
1862 #endif
1863
1864 return 0;
1865 }
1866
1867 //----------------------------------------------------------------------
1868 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1869 // included in every file over and over again...
1870
1871 wxString* wxString_in_helper(PyObject* source) {
1872 wxString* target = NULL;
1873
1874 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
1875 PyErr_SetString(PyExc_TypeError, "String or Unicode type required");
1876 return NULL;
1877 }
1878 #if wxUSE_UNICODE
1879 PyObject* uni = source;
1880 if (PyString_Check(source)) {
1881 uni = PyUnicode_FromEncodedObject(source, wxPyDefaultEncoding, "strict");
1882 if (PyErr_Occurred()) return NULL;
1883 }
1884 target = new wxString();
1885 size_t len = PyUnicode_GET_SIZE(uni);
1886 if (len) {
1887 PyUnicode_AsWideChar((PyUnicodeObject*)uni, wxStringBuffer(*target, len), len);
1888 }
1889
1890 if (PyString_Check(source))
1891 Py_DECREF(uni);
1892 #else
1893 // Convert to a string object if it isn't already, then to wxString
1894 PyObject* str = source;
1895 if (PyUnicode_Check(source)) {
1896 str = PyUnicode_AsEncodedString(source, wxPyDefaultEncoding, "strict");
1897 if (PyErr_Occurred()) return NULL;
1898 }
1899 else if (!PyString_Check(source)) {
1900 str = PyObject_Str(source);
1901 if (PyErr_Occurred()) return NULL;
1902 }
1903 char* tmpPtr; Py_ssize_t tmpSize;
1904 PyString_AsStringAndSize(str, &tmpPtr, &tmpSize);
1905 target = new wxString(tmpPtr, tmpSize);
1906
1907 if (!PyString_Check(source))
1908 Py_DECREF(str);
1909 #endif // wxUSE_UNICODE
1910
1911 return target;
1912 }
1913
1914
1915 // Similar to above except doesn't use "new" and doesn't set an exception
1916 wxString Py2wxString(PyObject* source)
1917 {
1918 wxString target;
1919
1920 #if wxUSE_UNICODE
1921 // Convert to a unicode object, if not already, then to a wxString
1922 PyObject* uni = source;
1923 if (!PyUnicode_Check(source)) {
1924 uni = PyUnicode_FromEncodedObject(source, wxPyDefaultEncoding, "strict");
1925 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1926 }
1927 size_t len = PyUnicode_GET_SIZE(uni);
1928 if (len) {
1929 PyUnicode_AsWideChar((PyUnicodeObject*)uni, wxStringBuffer(target, len), len);
1930 }
1931
1932 if (!PyUnicode_Check(source))
1933 Py_DECREF(uni);
1934 #else
1935 // Convert to a string object if it isn't already, then to wxString
1936 PyObject* str = source;
1937 if (PyUnicode_Check(source)) {
1938 str = PyUnicode_AsEncodedString(source, wxPyDefaultEncoding, "strict");
1939 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1940 }
1941 else if (!PyString_Check(source)) {
1942 str = PyObject_Str(source);
1943 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1944 }
1945 char* tmpPtr; Py_ssize_t tmpSize;
1946 PyString_AsStringAndSize(str, &tmpPtr, &tmpSize);
1947 target = wxString(tmpPtr, tmpSize);
1948
1949 if (!PyString_Check(source))
1950 Py_DECREF(str);
1951 #endif // wxUSE_UNICODE
1952
1953 return target;
1954 }
1955
1956
1957 // Make either a Python String or Unicode object, depending on build mode
1958 PyObject* wx2PyString(const wxString& src)
1959 {
1960 PyObject* str;
1961 #if wxUSE_UNICODE
1962 str = PyUnicode_FromWideChar(src.c_str(), src.Len());
1963 #else
1964 str = PyString_FromStringAndSize(src.c_str(), src.Len());
1965 #endif
1966 return str;
1967 }
1968
1969
1970
1971 void wxSetDefaultPyEncoding(const char* encoding)
1972 {
1973 strncpy(wxPyDefaultEncoding, encoding, DEFAULTENCODING_SIZE);
1974 }
1975
1976 const char* wxGetDefaultPyEncoding()
1977 {
1978 return wxPyDefaultEncoding;
1979 }
1980
1981 //----------------------------------------------------------------------
1982
1983
1984 byte* byte_LIST_helper(PyObject* source) {
1985 if (!PyList_Check(source)) {
1986 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1987 return NULL;
1988 }
1989 int count = PyList_Size(source);
1990 byte* temp = new byte[count];
1991 if (! temp) {
1992 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1993 return NULL;
1994 }
1995 for (int x=0; x<count; x++) {
1996 PyObject* o = PyList_GetItem(source, x);
1997 if (! PyInt_Check(o)) {
1998 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1999 return NULL;
2000 }
2001 temp[x] = (byte)PyInt_AsLong(o);
2002 }
2003 return temp;
2004 }
2005
2006
2007 int* int_LIST_helper(PyObject* source) {
2008 if (!PyList_Check(source)) {
2009 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2010 return NULL;
2011 }
2012 int count = PyList_Size(source);
2013 int* temp = new int[count];
2014 if (! temp) {
2015 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2016 return NULL;
2017 }
2018 for (int x=0; x<count; x++) {
2019 PyObject* o = PyList_GetItem(source, x);
2020 if (! PyInt_Check(o)) {
2021 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
2022 return NULL;
2023 }
2024 temp[x] = PyInt_AsLong(o);
2025 }
2026 return temp;
2027 }
2028
2029
2030 long* long_LIST_helper(PyObject* source) {
2031 if (!PyList_Check(source)) {
2032 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2033 return NULL;
2034 }
2035 int count = PyList_Size(source);
2036 long* temp = new long[count];
2037 if (! temp) {
2038 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2039 return NULL;
2040 }
2041 for (int x=0; x<count; x++) {
2042 PyObject* o = PyList_GetItem(source, x);
2043 if (! PyInt_Check(o)) {
2044 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
2045 return NULL;
2046 }
2047 temp[x] = PyInt_AsLong(o);
2048 }
2049 return temp;
2050 }
2051
2052
2053 char** string_LIST_helper(PyObject* source) {
2054 if (!PyList_Check(source)) {
2055 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2056 return NULL;
2057 }
2058 int count = PyList_Size(source);
2059 char** temp = new char*[count];
2060 if (! temp) {
2061 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2062 return NULL;
2063 }
2064 for (int x=0; x<count; x++) {
2065 PyObject* o = PyList_GetItem(source, x);
2066 if (! PyString_Check(o)) {
2067 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2068 return NULL;
2069 }
2070 temp[x] = PyString_AsString(o);
2071 }
2072 return temp;
2073 }
2074
2075 //---------------------------------------------------------------------------
2076 // NOTE: The following functions could really use some refactoring using
2077 // templates to make things somewhat simpler...
2078
2079 inline bool wxPointFromObjects(PyObject* o1, PyObject* o2, wxPoint* point)
2080 {
2081 // get the x value
2082 if (PyInt_Check(o1))
2083 point->x = (int)PyInt_AS_LONG(o1);
2084 else if (PyFloat_Check(o1))
2085 point->x = (int)PyFloat_AS_DOUBLE(o1);
2086 else if (PyNumber_Check(o1))
2087 point->x = (int)PyInt_AsLong(o1);
2088 else
2089 return false;
2090
2091 // get the y value
2092 if (PyInt_Check(o2))
2093 point->y = (int)PyInt_AS_LONG(o2);
2094 else if (PyFloat_Check(o2))
2095 point->y = (int)PyFloat_AS_DOUBLE(o2);
2096 else if (PyNumber_Check(o2))
2097 point->y = (int)PyInt_AsLong(o2);
2098 else
2099 return false;
2100
2101 return true;
2102
2103 // NOTE: This function used to have this code in it, but I don't know why it
2104 // is a problem nor what havok it will cause, so removing for now...
2105 // if (wxPySwigInstance_Check(o1) || wxPySwigInstance_Check(o2)) {
2106 // // Disallow instances because they can cause havok
2107 // return false;
2108 // }
2109 }
2110
2111
2112 inline bool wxPoint2DFromObjects(PyObject* o1, PyObject* o2, wxPoint2D* point)
2113 {
2114 // get the x value
2115 if (PyInt_Check(o1))
2116 point->m_x = (double)PyInt_AS_LONG(o1);
2117 else if (PyFloat_Check(o1))
2118 point->m_x = (double)PyFloat_AS_DOUBLE(o1);
2119 else if (PyNumber_Check(o1))
2120 point->m_x = (double)PyFloat_AsDouble(o1);
2121 else
2122 return false;
2123
2124 // get the y value
2125 if (PyInt_Check(o2))
2126 point->m_y = (double)PyInt_AS_LONG(o2);
2127 else if (PyFloat_Check(o2))
2128 point->m_y = (double)PyFloat_AS_DOUBLE(o2);
2129 else if (PyNumber_Check(o2))
2130 point->m_y = (double)PyFloat_AsDouble(o2);
2131 else
2132 return false;
2133
2134 return true;
2135 }
2136
2137
2138
2139 wxPoint* wxPoint_LIST_helper(PyObject* source, int *count)
2140 {
2141 int idx;
2142 wxPoint* temp;
2143 PyObject *o, *o1, *o2;
2144 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2145
2146 if (!PySequence_Check(source)) {
2147 goto error0;
2148 }
2149
2150 // The length of the sequence is returned in count.
2151 *count = PySequence_Length(source);
2152 if (*count < 0) {
2153 goto error0;
2154 }
2155
2156 temp = new wxPoint[*count];
2157 if (!temp) {
2158 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2159 return NULL;
2160 }
2161 for (idx=0; idx<*count; idx++) {
2162 // Get an item: try fast way first.
2163 if (isFast) {
2164 o = PySequence_Fast_GET_ITEM(source, idx);
2165 }
2166 else {
2167 o = PySequence_GetItem(source, idx);
2168 if (o == NULL) {
2169 goto error1;
2170 }
2171 }
2172
2173 // Convert o to wxPoint.
2174 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
2175 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
2176 o1 = PySequence_Fast_GET_ITEM(o, 0);
2177 o2 = PySequence_Fast_GET_ITEM(o, 1);
2178 if (!wxPointFromObjects(o1, o2, &temp[idx])) {
2179 goto error2;
2180 }
2181 }
2182 else if (wxPySwigInstance_Check(o)) {
2183 wxPoint* pt;
2184 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPoint"))) {
2185 goto error2;
2186 }
2187 temp[idx] = *pt;
2188 }
2189 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
2190 o1 = PySequence_GetItem(o, 0);
2191 o2 = PySequence_GetItem(o, 1);
2192 if (!wxPointFromObjects(o1, o2, &temp[idx])) {
2193 goto error3;
2194 }
2195 Py_DECREF(o1);
2196 Py_DECREF(o2);
2197 }
2198 else {
2199 goto error2;
2200 }
2201 // Clean up.
2202 if (!isFast)
2203 Py_DECREF(o);
2204 }
2205 return temp;
2206
2207 error3:
2208 Py_DECREF(o1);
2209 Py_DECREF(o2);
2210 error2:
2211 if (!isFast)
2212 Py_DECREF(o);
2213 error1:
2214 delete [] temp;
2215 error0:
2216 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoints.");
2217 return NULL;
2218 }
2219
2220
2221
2222 wxPoint2D* wxPoint2D_LIST_helper(PyObject* source, size_t *count)
2223 {
2224 size_t idx;
2225 wxPoint2D* temp;
2226 PyObject *o, *o1, *o2;
2227 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2228
2229 if (!PySequence_Check(source)) {
2230 goto error0;
2231 }
2232
2233 // The length of the sequence is returned in count.
2234 *count = PySequence_Length(source);
2235 if (*count < 0) {
2236 goto error0;
2237 }
2238
2239 temp = new wxPoint2D[*count];
2240 if (!temp) {
2241 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2242 return NULL;
2243 }
2244 for (idx=0; idx<*count; idx++) {
2245 // Get an item: try fast way first.
2246 if (isFast) {
2247 o = PySequence_Fast_GET_ITEM(source, idx);
2248 }
2249 else {
2250 o = PySequence_GetItem(source, idx);
2251 if (o == NULL) {
2252 goto error1;
2253 }
2254 }
2255
2256 // Convert o to wxPoint.
2257 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
2258 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
2259 o1 = PySequence_Fast_GET_ITEM(o, 0);
2260 o2 = PySequence_Fast_GET_ITEM(o, 1);
2261 if (!wxPoint2DFromObjects(o1, o2, &temp[idx])) {
2262 goto error2;
2263 }
2264 }
2265 else if (wxPySwigInstance_Check(o)) {
2266 wxPoint2D* pt;
2267 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPoint2D"))) {
2268 goto error2;
2269 }
2270 temp[idx] = *pt;
2271 }
2272 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
2273 o1 = PySequence_GetItem(o, 0);
2274 o2 = PySequence_GetItem(o, 1);
2275 if (!wxPoint2DFromObjects(o1, o2, &temp[idx])) {
2276 goto error3;
2277 }
2278 Py_DECREF(o1);
2279 Py_DECREF(o2);
2280 }
2281 else {
2282 goto error2;
2283 }
2284 // Clean up.
2285 if (!isFast)
2286 Py_DECREF(o);
2287 }
2288 return temp;
2289
2290 error3:
2291 Py_DECREF(o1);
2292 Py_DECREF(o2);
2293 error2:
2294 if (!isFast)
2295 Py_DECREF(o);
2296 error1:
2297 delete [] temp;
2298 error0:
2299 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoint2Ds.");
2300 return NULL;
2301 }
2302
2303 //---------------------------------------------------------------------------
2304
2305
2306 wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
2307 if (!PyList_Check(source)) {
2308 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2309 return NULL;
2310 }
2311 int count = PyList_Size(source);
2312 wxBitmap** temp = new wxBitmap*[count];
2313 if (! temp) {
2314 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2315 return NULL;
2316 }
2317 for (int x=0; x<count; x++) {
2318 PyObject* o = PyList_GetItem(source, x);
2319 if (wxPySwigInstance_Check(o)) {
2320 wxBitmap* pt;
2321 if (! wxPyConvertSwigPtr(o, (void **) &pt, wxT("wxBitmap"))) {
2322 PyErr_SetString(PyExc_TypeError,"Expected wxBitmap.");
2323 return NULL;
2324 }
2325 temp[x] = pt;
2326 }
2327 else {
2328 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
2329 return NULL;
2330 }
2331 }
2332 return temp;
2333 }
2334
2335
2336
2337 wxString* wxString_LIST_helper(PyObject* source) {
2338 if (!PyList_Check(source)) {
2339 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2340 return NULL;
2341 }
2342 int count = PyList_Size(source);
2343 wxString* temp = new wxString[count];
2344 if (! temp) {
2345 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2346 return NULL;
2347 }
2348 for (int x=0; x<count; x++) {
2349 PyObject* o = PyList_GetItem(source, x);
2350 #if PYTHON_API_VERSION >= 1009
2351 if (! PyString_Check(o) && ! PyUnicode_Check(o)) {
2352 PyErr_SetString(PyExc_TypeError, "Expected a list of string or unicode objects.");
2353 return NULL;
2354 }
2355 #else
2356 if (! PyString_Check(o)) {
2357 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2358 return NULL;
2359 }
2360 #endif
2361
2362 wxString* pStr = wxString_in_helper(o);
2363 temp[x] = *pStr;
2364 delete pStr;
2365 }
2366 return temp;
2367 }
2368
2369
2370 wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
2371 if (!PyList_Check(source)) {
2372 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2373 return NULL;
2374 }
2375 int count = PyList_Size(source);
2376 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
2377 if (! temp) {
2378 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2379 return NULL;
2380 }
2381 for (int x=0; x<count; x++) {
2382 PyObject* o = PyList_GetItem(source, x);
2383 if (wxPySwigInstance_Check(o)) {
2384 wxAcceleratorEntry* ae;
2385 if (! wxPyConvertSwigPtr(o, (void **) &ae, wxT("wxAcceleratorEntry"))) {
2386 PyErr_SetString(PyExc_TypeError,"Expected wxAcceleratorEntry.");
2387 return NULL;
2388 }
2389 temp[x] = *ae;
2390 }
2391 else if (PyTuple_Check(o)) {
2392 PyObject* o1 = PyTuple_GetItem(o, 0);
2393 PyObject* o2 = PyTuple_GetItem(o, 1);
2394 PyObject* o3 = PyTuple_GetItem(o, 2);
2395 temp[x].Set(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2396 }
2397 else {
2398 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2399 return NULL;
2400 }
2401 }
2402 return temp;
2403 }
2404
2405
2406 wxPen** wxPen_LIST_helper(PyObject* source) {
2407 if (!PyList_Check(source)) {
2408 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2409 return NULL;
2410 }
2411 int count = PyList_Size(source);
2412 wxPen** temp = new wxPen*[count];
2413 if (!temp) {
2414 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2415 return NULL;
2416 }
2417 for (int x=0; x<count; x++) {
2418 PyObject* o = PyList_GetItem(source, x);
2419 if (wxPySwigInstance_Check(o)) {
2420 wxPen* pt;
2421 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPen"))) {
2422 delete temp;
2423 PyErr_SetString(PyExc_TypeError,"Expected wxPen.");
2424 return NULL;
2425 }
2426 temp[x] = pt;
2427 }
2428 else {
2429 delete temp;
2430 PyErr_SetString(PyExc_TypeError, "Expected a list of wxPens.");
2431 return NULL;
2432 }
2433 }
2434 return temp;
2435 }
2436
2437
2438 bool wxPy2int_seq_helper(PyObject* source, int* i1, int* i2) {
2439 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2440 PyObject *o1, *o2;
2441
2442 if (!PySequence_Check(source) || PySequence_Length(source) != 2)
2443 return false;
2444
2445 if (isFast) {
2446 o1 = PySequence_Fast_GET_ITEM(source, 0);
2447 o2 = PySequence_Fast_GET_ITEM(source, 1);
2448 }
2449 else {
2450 o1 = PySequence_GetItem(source, 0);
2451 o2 = PySequence_GetItem(source, 1);
2452 }
2453
2454 *i1 = PyInt_AsLong(o1);
2455 *i2 = PyInt_AsLong(o2);
2456
2457 if (! isFast) {
2458 Py_DECREF(o1);
2459 Py_DECREF(o2);
2460 }
2461 return true;
2462 }
2463
2464
2465 bool wxPy4int_seq_helper(PyObject* source, int* i1, int* i2, int* i3, int* i4) {
2466 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2467 PyObject *o1, *o2, *o3, *o4;
2468
2469 if (!PySequence_Check(source) || PySequence_Length(source) != 4)
2470 return false;
2471
2472 if (isFast) {
2473 o1 = PySequence_Fast_GET_ITEM(source, 0);
2474 o2 = PySequence_Fast_GET_ITEM(source, 1);
2475 o3 = PySequence_Fast_GET_ITEM(source, 2);
2476 o4 = PySequence_Fast_GET_ITEM(source, 3);
2477 }
2478 else {
2479 o1 = PySequence_GetItem(source, 0);
2480 o2 = PySequence_GetItem(source, 1);
2481 o3 = PySequence_GetItem(source, 2);
2482 o4 = PySequence_GetItem(source, 3);
2483 }
2484
2485 *i1 = PyInt_AsLong(o1);
2486 *i2 = PyInt_AsLong(o2);
2487 *i3 = PyInt_AsLong(o3);
2488 *i4 = PyInt_AsLong(o4);
2489
2490 if (! isFast) {
2491 Py_DECREF(o1);
2492 Py_DECREF(o2);
2493 Py_DECREF(o3);
2494 Py_DECREF(o4);
2495 }
2496 return true;
2497 }
2498
2499
2500 //----------------------------------------------------------------------
2501
2502 bool wxPySimple_typecheck(PyObject* source, const wxChar* classname, int seqLen)
2503 {
2504 void* ptr;
2505
2506 if (wxPySwigInstance_Check(source) &&
2507 wxPyConvertSwigPtr(source, (void **)&ptr, classname))
2508 return true;
2509
2510 PyErr_Clear();
2511 if (PySequence_Check(source) && PySequence_Length(source) == seqLen)
2512 return true;
2513
2514 return false;
2515 }
2516
2517 bool wxSize_helper(PyObject* source, wxSize** obj)
2518 {
2519 if (source == Py_None) {
2520 **obj = wxSize(-1,-1);
2521 return true;
2522 }
2523 return wxPyTwoIntItem_helper(source, obj, wxT("wxSize"));
2524 }
2525
2526
2527 bool wxPoint_helper(PyObject* source, wxPoint** obj)
2528 {
2529 if (source == Py_None) {
2530 **obj = wxPoint(-1,-1);
2531 return true;
2532 }
2533 return wxPyTwoIntItem_helper(source, obj, wxT("wxPoint"));
2534 }
2535
2536
2537
2538 bool wxPosition_helper(PyObject* source, wxPosition** obj)
2539 {
2540 if (source == Py_None) {
2541 **obj = wxPosition(-1,-1);
2542 return true;
2543 }
2544 return wxPyTwoIntItem_helper(source, obj, wxT("wxPosition"));
2545 }
2546
2547
2548
2549 bool wxRealPoint_helper(PyObject* source, wxRealPoint** obj) {
2550
2551 if (source == Py_None) {
2552 **obj = wxRealPoint(-1,-1);
2553 return true;
2554 }
2555
2556 // If source is an object instance then it may already be the right type
2557 if (wxPySwigInstance_Check(source)) {
2558 wxRealPoint* ptr;
2559 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRealPoint")))
2560 goto error;
2561 *obj = ptr;
2562 return true;
2563 }
2564 // otherwise a 2-tuple of floats is expected
2565 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
2566 PyObject* o1 = PySequence_GetItem(source, 0);
2567 PyObject* o2 = PySequence_GetItem(source, 1);
2568 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2569 Py_DECREF(o1);
2570 Py_DECREF(o2);
2571 goto error;
2572 }
2573 **obj = wxRealPoint(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2574 Py_DECREF(o1);
2575 Py_DECREF(o2);
2576 return true;
2577 }
2578
2579 error:
2580 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxRealPoint object.");
2581 return false;
2582 }
2583
2584
2585
2586 bool wxRect_helper(PyObject* source, wxRect** obj) {
2587
2588 if (source == Py_None) {
2589 **obj = wxRect(-1,-1,-1,-1);
2590 return true;
2591 }
2592
2593 // If source is an object instance then it may already be the right type
2594 if (wxPySwigInstance_Check(source)) {
2595 wxRect* ptr;
2596 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRect")))
2597 goto error;
2598 *obj = ptr;
2599 return true;
2600 }
2601 // otherwise a 4-tuple of integers is expected
2602 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2603 PyObject* o1 = PySequence_GetItem(source, 0);
2604 PyObject* o2 = PySequence_GetItem(source, 1);
2605 PyObject* o3 = PySequence_GetItem(source, 2);
2606 PyObject* o4 = PySequence_GetItem(source, 3);
2607 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2608 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2609 Py_DECREF(o1);
2610 Py_DECREF(o2);
2611 Py_DECREF(o3);
2612 Py_DECREF(o4);
2613 goto error;
2614 }
2615 **obj = wxRect(PyInt_AsLong(o1), PyInt_AsLong(o2),
2616 PyInt_AsLong(o3), PyInt_AsLong(o4));
2617 Py_DECREF(o1);
2618 Py_DECREF(o2);
2619 Py_DECREF(o3);
2620 Py_DECREF(o4);
2621 return true;
2622 }
2623
2624 error:
2625 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of integers or a wxRect object.");
2626 return false;
2627 }
2628
2629
2630
2631 bool wxColour_helper(PyObject* source, wxColour** obj) {
2632
2633 if (source == Py_None) {
2634 **obj = wxNullColour;
2635 return true;
2636 }
2637
2638 // If source is an object instance then it may already be the right type
2639 if (wxPySwigInstance_Check(source)) {
2640 wxColour* ptr;
2641 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxColour")))
2642 goto error;
2643 *obj = ptr;
2644 return true;
2645 }
2646 // otherwise check for a string
2647 else if (PyString_Check(source) || PyUnicode_Check(source)) {
2648 wxString spec = Py2wxString(source);
2649 if (spec.GetChar(0) == '#' && spec.Length() == 7) { // It's #RRGGBB
2650 long red, green, blue;
2651 red = green = blue = 0;
2652 spec.Mid(1,2).ToLong(&red, 16);
2653 spec.Mid(3,2).ToLong(&green, 16);
2654 spec.Mid(5,2).ToLong(&blue, 16);
2655
2656 **obj = wxColour(red, green, blue);
2657 return true;
2658 }
2659 else { // it's a colour name
2660 **obj = wxColour(spec);
2661 return true;
2662 }
2663 }
2664 // last chance: 3-tuple or 4-tuple of integers is expected
2665 else if (PySequence_Check(source) && PyObject_Length(source) == 3) {
2666 PyObject* o1 = PySequence_GetItem(source, 0);
2667 PyObject* o2 = PySequence_GetItem(source, 1);
2668 PyObject* o3 = PySequence_GetItem(source, 2);
2669 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3)) {
2670 Py_DECREF(o1);
2671 Py_DECREF(o2);
2672 Py_DECREF(o3);
2673 goto error;
2674 }
2675 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2676 Py_DECREF(o1);
2677 Py_DECREF(o2);
2678 Py_DECREF(o3);
2679 return true;
2680 }
2681 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2682 PyObject* o1 = PySequence_GetItem(source, 0);
2683 PyObject* o2 = PySequence_GetItem(source, 1);
2684 PyObject* o3 = PySequence_GetItem(source, 2);
2685 PyObject* o4 = PySequence_GetItem(source, 3);
2686 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2687 Py_DECREF(o1);
2688 Py_DECREF(o2);
2689 Py_DECREF(o3);
2690 Py_DECREF(o4);
2691 goto error;
2692 }
2693 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3), PyInt_AsLong(o4));
2694 Py_DECREF(o1);
2695 Py_DECREF(o2);
2696 Py_DECREF(o3);
2697 Py_DECREF(o4);
2698 return true;
2699 }
2700
2701 error:
2702 PyErr_SetString(PyExc_TypeError,
2703 "Expected a wxColour object, a string containing a colour name or '#RRGGBB', or a 3- or 4-tuple of integers.");
2704 return false;
2705 }
2706
2707
2708 bool wxColour_typecheck(PyObject* source) {
2709
2710 if (wxPySimple_typecheck(source, wxT("wxColour"), 3))
2711 return true;
2712
2713 if (PyString_Check(source) || PyUnicode_Check(source))
2714 return true;
2715
2716 return false;
2717 }
2718
2719
2720
2721 bool wxPoint2D_helper(PyObject* source, wxPoint2D** obj) {
2722
2723 if (source == Py_None) {
2724 **obj = wxPoint2D(-1,-1);
2725 return true;
2726 }
2727
2728 // If source is an object instance then it may already be the right type
2729 if (wxPySwigInstance_Check(source)) {
2730 wxPoint2D* ptr;
2731 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxPoint2D")))
2732 goto error;
2733 *obj = ptr;
2734 return true;
2735 }
2736 // otherwise a length-2 sequence of floats is expected
2737 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
2738 PyObject* o1 = PySequence_GetItem(source, 0);
2739 PyObject* o2 = PySequence_GetItem(source, 1);
2740 // This should really check for floats, not numbers -- but that would break code.
2741 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2742 Py_DECREF(o1);
2743 Py_DECREF(o2);
2744 goto error;
2745 }
2746 **obj = wxPoint2D(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
2747 Py_DECREF(o1);
2748 Py_DECREF(o2);
2749 return true;
2750 }
2751 error:
2752 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wx.Point2D object.");
2753 return false;
2754 }
2755
2756
2757
2758 bool wxRect2D_helper(PyObject* source, wxRect2D** obj) {
2759
2760 if (source == Py_None) {
2761 **obj = wxRect2D(-1,-1,-1,-1);
2762 return true;
2763 }
2764
2765 // If source is an object instance then it may already be the right type
2766 if (wxPySwigInstance_Check(source)) {
2767 wxRect2D* ptr;
2768 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRect2D")))
2769 goto error;
2770 *obj = ptr;
2771 return true;
2772 }
2773 // otherwise a length-4 sequence of floats is expected
2774 if (PySequence_Check(source) && PySequence_Length(source) == 4) {
2775 PyObject* o1 = PySequence_GetItem(source, 0);
2776 PyObject* o2 = PySequence_GetItem(source, 1);
2777 PyObject* o3 = PySequence_GetItem(source, 2);
2778 PyObject* o4 = PySequence_GetItem(source, 3);
2779 // This should really check for floats, not numbers -- but that would break code.
2780 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2781 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2782 Py_DECREF(o1);
2783 Py_DECREF(o2);
2784 Py_DECREF(o3);
2785 Py_DECREF(o4);
2786 goto error;
2787 }
2788 **obj = wxRect2D(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2),
2789 PyFloat_AsDouble(o3), PyFloat_AsDouble(o4));
2790 Py_DECREF(o1);
2791 Py_DECREF(o2);
2792 Py_DECREF(o3);
2793 Py_DECREF(o4);
2794 return true;
2795 }
2796 error:
2797 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of floats or a wx.Rect2D object.");
2798 return false;
2799 }
2800
2801
2802 //----------------------------------------------------------------------
2803
2804 PyObject* wxArrayString2PyList_helper(const wxArrayString& arr)
2805 {
2806 PyObject* list = PyList_New(0);
2807 for (size_t i=0; i < arr.GetCount(); i++) {
2808 #if wxUSE_UNICODE
2809 PyObject* str = PyUnicode_FromWideChar(arr[i].c_str(), arr[i].Len());
2810 #else
2811 PyObject* str = PyString_FromStringAndSize(arr[i].c_str(), arr[i].Len());
2812 #endif
2813 PyList_Append(list, str);
2814 Py_DECREF(str);
2815 }
2816 return list;
2817 }
2818
2819
2820 PyObject* wxArrayInt2PyList_helper(const wxArrayInt& arr)
2821 {
2822 PyObject* list = PyList_New(0);
2823 for (size_t i=0; i < arr.GetCount(); i++) {
2824 PyObject* number = PyInt_FromLong(arr[i]);
2825 PyList_Append(list, number);
2826 Py_DECREF(number);
2827 }
2828 return list;
2829 }
2830
2831
2832 PyObject* wxArrayDouble2PyList_helper(const wxArrayDouble& arr)
2833 {
2834 PyObject* list = PyList_New(0);
2835 for (size_t i=0; i < arr.GetCount(); i++) {
2836 PyObject* number = PyFloat_FromDouble(arr[i]);
2837 PyList_Append(list, number);
2838 Py_DECREF(number);
2839 }
2840 return list;
2841 }
2842
2843
2844 //----------------------------------------------------------------------
2845 // wxPyImageHandler methods
2846 //
2847 // TODO: Switch these to use wxPython's standard macros and helper classes
2848 // for calling callbacks.
2849
2850 PyObject* wxPyImageHandler::m_DoCanRead_Name = NULL;
2851 PyObject* wxPyImageHandler::m_GetImageCount_Name = NULL;
2852 PyObject* wxPyImageHandler::m_LoadFile_Name = NULL;
2853 PyObject* wxPyImageHandler::m_SaveFile_Name = NULL;
2854
2855 PyObject* wxPyImageHandler::py_InputStream(wxInputStream* stream) {
2856 return wxPyConstructObject(new wxPyInputStream(stream),
2857 wxT("wxPyInputStream"), 0);
2858 }
2859
2860 PyObject* wxPyImageHandler::py_Image(wxImage* image) {
2861 return wxPyConstructObject(image, wxT("wxImage"), 0);
2862 }
2863
2864 PyObject* wxPyImageHandler::py_OutputStream(wxOutputStream* stream) {
2865 return wxPyConstructObject(stream, wxT("wxOutputStream"), 0);
2866 }
2867
2868 wxPyImageHandler::wxPyImageHandler():
2869 m_self(NULL)
2870 {
2871 if (!m_DoCanRead_Name) {
2872 m_DoCanRead_Name = PyString_FromString("DoCanRead");
2873 m_GetImageCount_Name = PyString_FromString("GetImageCount");
2874 m_LoadFile_Name = PyString_FromString("LoadFile");
2875 m_SaveFile_Name = PyString_FromString("SaveFile");
2876 }
2877 }
2878
2879 wxPyImageHandler::~wxPyImageHandler() {
2880 if (m_self) {
2881 Py_DECREF(m_self);
2882 m_self = NULL;
2883 }
2884 }
2885
2886 void wxPyImageHandler::_SetSelf(PyObject *self) {
2887 // should check here for isinstance(PyImageHandler) ??
2888 m_self = self;
2889 Py_INCREF(m_self);
2890 }
2891
2892 bool wxPyImageHandler::DoCanRead(wxInputStream& stream) {
2893 // check if our object has this method
2894 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2895 if (!m_self || !PyObject_HasAttr(m_self, m_DoCanRead_Name)) {
2896 wxPyEndBlockThreads(blocked);
2897 return false;
2898 }
2899
2900 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_DoCanRead_Name,
2901 py_InputStream(&stream), NULL);
2902 bool retval = false;
2903 if (res) {
2904 retval = PyInt_AsLong(res);
2905 Py_DECREF(res);
2906 PyErr_Clear();
2907 }
2908 else
2909 PyErr_Print();
2910 wxPyEndBlockThreads(blocked);
2911 return retval;
2912 }
2913
2914 bool wxPyImageHandler::LoadFile( wxImage* image, wxInputStream& stream,
2915 bool verbose, int index ) {
2916 // check if our object has this method
2917 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2918 if (!m_self || !PyObject_HasAttr(m_self, m_LoadFile_Name)) {
2919 wxPyEndBlockThreads(blocked);
2920 return false;
2921 }
2922 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_LoadFile_Name,
2923 py_Image(image),
2924 py_InputStream(&stream),
2925 PyInt_FromLong(verbose),
2926 PyInt_FromLong(index),
2927 NULL);
2928 bool retval = false;
2929 if (res) {
2930 retval = PyInt_AsLong(res);
2931 Py_DECREF(res);
2932 PyErr_Clear();
2933 } else
2934 PyErr_Print();
2935 wxPyEndBlockThreads(blocked);
2936 return retval;
2937 }
2938
2939 bool wxPyImageHandler::SaveFile( wxImage* image, wxOutputStream& stream,
2940 bool verbose ) {
2941 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2942 if (!m_self || !PyObject_HasAttr(m_self, m_SaveFile_Name)) {
2943 wxPyEndBlockThreads(blocked);
2944 return false;
2945 }
2946 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_SaveFile_Name,
2947 py_Image(image),
2948 py_OutputStream(&stream),
2949 PyInt_FromLong(verbose),
2950 NULL);
2951 bool retval = false;
2952 if(res) {
2953 retval=PyInt_AsLong(res);
2954 Py_DECREF(res);
2955 PyErr_Clear();
2956 } else
2957 PyErr_Print();
2958 wxPyEndBlockThreads(blocked);
2959 return retval;
2960 }
2961
2962 int wxPyImageHandler::GetImageCount( wxInputStream& stream ) {
2963 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2964 if (!m_self || !PyObject_HasAttr(m_self, m_GetImageCount_Name)) {
2965 wxPyEndBlockThreads(blocked);
2966 return 1;
2967 }
2968 PyObject *res=PyObject_CallMethodObjArgs(m_self, m_GetImageCount_Name,
2969 py_InputStream(&stream),
2970 NULL);
2971 int retval = 1;
2972 if(res) {
2973 retval=PyInt_AsLong(res);
2974 Py_DECREF(res);
2975 PyErr_Clear();
2976 } else
2977 PyErr_Print();
2978 wxPyEndBlockThreads(blocked);
2979 return retval;
2980 }
2981
2982
2983 //----------------------------------------------------------------------
2984 // Function to test if the Display (or whatever is the platform equivallent)
2985 // can be connected to. This is accessable from wxPython as a staticmethod of
2986 // wx.App called DisplayAvailable().
2987
2988
2989 bool wxPyTestDisplayAvailable()
2990 {
2991 #ifdef __WXGTK__
2992 Display* display;
2993 display = XOpenDisplay(NULL);
2994 if (display == NULL)
2995 return false;
2996 XCloseDisplay(display);
2997 return true;
2998 #endif
2999
3000 #ifdef __WXMAC__
3001 // This is adapted from Python's Mac/Modules/MacOS.c in the
3002 // MacOS_WMAvailable function.
3003 bool rv;
3004 ProcessSerialNumber psn;
3005
3006 /*
3007 ** This is a fairly innocuous call to make if we don't have a window
3008 ** manager, or if we have no permission to talk to it. It will print
3009 ** a message on stderr, but at least it won't abort the process.
3010 ** It appears the function caches the result itself, and it's cheap, so
3011 ** no need for us to cache.
3012 */
3013 #ifdef kCGNullDirectDisplay
3014 /* On 10.1 CGMainDisplayID() isn't available, and
3015 ** kCGNullDirectDisplay isn't defined.
3016 */
3017 if (CGMainDisplayID() == 0) {
3018 rv = false;
3019 } else
3020 #endif
3021 {
3022 // Also foreground the application on the first call as a side-effect.
3023 if (GetCurrentProcess(&psn) < 0 || SetFrontProcess(&psn) < 0) {
3024 rv = false;
3025 } else {
3026 rv = true;
3027 }
3028 }
3029 return rv;
3030 #endif
3031
3032 #ifdef __WXMSW__
3033 // TODO...
3034 return true;
3035 #endif
3036 }
3037
3038
3039 //----------------------------------------------------------------------
3040 //----------------------------------------------------------------------
3041
3042
3043
3044