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