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