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