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