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