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