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