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