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