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