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