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