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