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