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