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