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