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