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