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