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