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