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