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