]> git.saurik.com Git - wxWidgets.git/blame - wxPython/src/helpers.cpp
added inline plural form of wxGetTranslation to wxUSE_INTL=0 case for use with non...
[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);
845 }
4acff284 846 }
1fded56b 847
d14a1e28 848 // m_obj is DECREF'd in the base class dtor...
da32eb53 849 wxPyEndBlockThreads(blocked);
4acff284 850}
7bf85405 851
1fded56b 852
9416aa89
RD
853//---------------------------------------------------------------------------
854// Stuff used by OOR to find the right wxPython class type to return and to
855// build it.
856
857
858// The pointer type map is used when the "pointer" type name generated by SWIG
859// is not the same as the shadow class name, for example wxPyTreeCtrl
860// vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
861// so we'll just make it a Python dictionary in the wx module's namespace.
4acff284 862// (See __wxSetDictionary)
9416aa89
RD
863void wxPyPtrTypeMap_Add(const char* commonName, const char* ptrName) {
864 if (! wxPyPtrTypeMap)
865 wxPyPtrTypeMap = PyDict_New();
9416aa89
RD
866 PyDict_SetItemString(wxPyPtrTypeMap,
867 (char*)commonName,
868 PyString_FromString((char*)ptrName));
869}
870
871
872
9416aa89 873
6d450e1a 874PyObject* wxPyMake_wxObject(wxObject* source, bool setThisOwn, bool checkEvtHandler) {
0122b7e3 875 PyObject* target = NULL;
4519a2d9 876 bool isEvtHandler = false;
f3c2a60b 877 bool isSizer = false;
9416aa89
RD
878
879 if (source) {
2aab8f16 880 // If it's derived from wxEvtHandler then there may
2f4e9287
RD
881 // already be a pointer to a Python object that we can use
882 // in the OOR data.
883 if (checkEvtHandler && wxIsKindOf(source, wxEvtHandler)) {
4519a2d9 884 isEvtHandler = true;
0122b7e3 885 wxEvtHandler* eh = (wxEvtHandler*)source;
4acff284 886 wxPyOORClientData* data = (wxPyOORClientData*)eh->GetClientObject();
0122b7e3
RD
887 if (data) {
888 target = data->m_obj;
d14a1e28
RD
889 if (target)
890 Py_INCREF(target);
0122b7e3 891 }
9416aa89 892 }
0122b7e3 893
f3c2a60b
RD
894 // Also check for wxSizer
895 if (!target && wxIsKindOf(source, wxSizer)) {
896 isSizer = true;
897 wxSizer* sz = (wxSizer*)source;
898 wxPyOORClientData* data = (wxPyOORClientData*)sz->GetClientObject();
899 if (data) {
900 target = data->m_obj;
901 if (target)
902 Py_INCREF(target);
903 }
904 }
905
0122b7e3 906 if (! target) {
d14a1e28
RD
907 // Otherwise make it the old fashioned way by making a new shadow
908 // object and putting this pointer in it. Look up the class
909 // heirarchy until we find a class name that is located in the
910 // python module.
911 const wxClassInfo* info = source->GetClassInfo();
912 wxString name = info->GetClassName();
913 bool exists = wxPyCheckSwigType(name);
914 while (info && !exists) {
915 info = info->GetBaseClass1();
916 name = info->GetClassName();
917 exists = wxPyCheckSwigType(name);
0122b7e3
RD
918 }
919 if (info) {
6d450e1a 920 target = wxPyConstructObject((void*)source, name, setThisOwn);
0122b7e3 921 if (target && isEvtHandler)
4acff284 922 ((wxEvtHandler*)source)->SetClientObject(new wxPyOORClientData(target));
f3c2a60b
RD
923 if (target && isSizer)
924 ((wxSizer*)source)->SetClientObject(new wxPyOORClientData(target));
0122b7e3 925 } else {
4acff284 926 wxString msg(wxT("wxPython class not found for "));
0122b7e3 927 msg += source->GetClassInfo()->GetClassName();
a541c325 928 PyErr_SetString(PyExc_NameError, msg.mbc_str());
0122b7e3
RD
929 target = NULL;
930 }
9416aa89
RD
931 }
932 } else { // source was NULL so return None.
933 Py_INCREF(Py_None); target = Py_None;
934 }
935 return target;
936}
937
0122b7e3 938
6d450e1a 939PyObject* wxPyMake_wxSizer(wxSizer* source, bool setThisOwn) {
2f4e9287 940
f3c2a60b 941 return wxPyMake_wxObject(source, setThisOwn);
2f4e9287
RD
942}
943
944
d559219f 945//---------------------------------------------------------------------------
7bf85405 946
4958ea8f 947
cf694132 948#ifdef WXP_WITH_THREAD
6e6b3557
RD
949#if !wxPyUSE_GIL_STATE
950
4268f798
RD
951inline
952unsigned long wxPyGetCurrentThreadId() {
4958ea8f 953 return wxThread::GetCurrentId();
4268f798
RD
954}
955
b856768b 956static wxPyThreadState gs_shutdownTState;
d14a1e28 957
4268f798 958static
b856768b 959wxPyThreadState* wxPyGetThreadState() {
be43cc44 960 if (wxPyTMutex == NULL) // Python is shutting down...
b856768b 961 return &gs_shutdownTState;
be43cc44 962
4268f798 963 unsigned long ctid = wxPyGetCurrentThreadId();
b856768b 964 wxPyThreadState* tstate = NULL;
4268f798
RD
965
966 wxPyTMutex->Lock();
967 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
968 wxPyThreadState& info = wxPyTStates->Item(i);
969 if (info.tid == ctid) {
b856768b 970 tstate = &info;
4268f798
RD
971 break;
972 }
973 }
974 wxPyTMutex->Unlock();
a541c325 975 wxASSERT_MSG(tstate, wxT("PyThreadState should not be NULL!"));
4268f798
RD
976 return tstate;
977}
978
b856768b 979
4268f798
RD
980static
981void wxPySaveThreadState(PyThreadState* tstate) {
be43cc44 982 if (wxPyTMutex == NULL) { // Python is shutting down, assume a single thread...
b856768b 983 gs_shutdownTState.tstate = tstate;
be43cc44
RD
984 return;
985 }
4268f798
RD
986 unsigned long ctid = wxPyGetCurrentThreadId();
987 wxPyTMutex->Lock();
988 for(size_t i=0; i < wxPyTStates->GetCount(); i++) {
989 wxPyThreadState& info = wxPyTStates->Item(i);
990 if (info.tid == ctid) {
763d71e4
RD
991#if 0
992 if (info.tstate != tstate)
993 wxLogMessage("*** tstate mismatch!???");
994#endif
ae13f292 995 info.tstate = tstate; // allow for transient tstates
763d71e4
RD
996 // Normally it will never change, but apparently COM callbacks
997 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
46e10fde 998 // tstate which will then be garbage the next time we try to use
763d71e4 999 // it...
d02ea46c 1000
4268f798
RD
1001 wxPyTMutex->Unlock();
1002 return;
1003 }
1112b0c6 1004 }
4268f798
RD
1005 // not found, so add it...
1006 wxPyTStates->Add(new wxPyThreadState(ctid, tstate));
1007 wxPyTMutex->Unlock();
1008}
1009
1010#endif
6e6b3557 1011#endif
4268f798
RD
1012
1013
b856768b 1014
4268f798
RD
1015// Calls from Python to wxWindows code are wrapped in calls to these
1016// functions:
1017
1018PyThreadState* wxPyBeginAllowThreads() {
1019#ifdef WXP_WITH_THREAD
1020 PyThreadState* saved = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
6e6b3557 1021#if !wxPyUSE_GIL_STATE
4268f798 1022 wxPySaveThreadState(saved);
6e6b3557 1023#endif
4268f798
RD
1024 return saved;
1025#else
1026 return NULL;
1027#endif
1028}
1029
1030void wxPyEndAllowThreads(PyThreadState* saved) {
1031#ifdef WXP_WITH_THREAD
1032 PyEval_RestoreThread(saved); // Py_END_ALLOW_THREADS;
cf694132 1033#endif
d559219f 1034}
cf694132 1035
cf694132 1036
4268f798
RD
1037
1038// Calls from wxWindows back to Python code, or even any PyObject
1039// manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1040
6e6b3557 1041wxPyBlock_t wxPyBeginBlockThreads() {
cf694132 1042#ifdef WXP_WITH_THREAD
ea19c9a8
RD
1043 if (! Py_IsInitialized()) {
1044 return (wxPyBlock_t)0;
1045 }
6e6b3557
RD
1046#if wxPyUSE_GIL_STATE
1047 PyGILState_STATE state = PyGILState_Ensure();
1048 return state;
1049#else
27b60faf 1050 PyThreadState *current = _PyThreadState_Current;
da32eb53 1051
27b60faf
RD
1052 // Only block if there wasn't already a tstate, or if the current one is
1053 // not the one we are wanting to change to. This should prevent deadlock
1054 // if there are nested calls to wxPyBeginBlockThreads
6e6b3557 1055 wxPyBlock_t blocked = false;
27b60faf
RD
1056 wxPyThreadState* tstate = wxPyGetThreadState();
1057 if (current != tstate->tstate) {
b856768b 1058 PyEval_RestoreThread(tstate->tstate);
da32eb53 1059 blocked = true;
b856768b 1060 }
da32eb53 1061 return blocked;
4268f798 1062#endif
6e6b3557 1063#else
f3c2a60b 1064 return (wxPyBlock_t)0;
6e6b3557 1065#endif
4268f798
RD
1066}
1067
1068
6e6b3557 1069void wxPyEndBlockThreads(wxPyBlock_t blocked) {
4268f798 1070#ifdef WXP_WITH_THREAD
ea19c9a8
RD
1071 if (! Py_IsInitialized()) {
1072 return;
1073 }
6e6b3557
RD
1074#if wxPyUSE_GIL_STATE
1075 PyGILState_Release(blocked);
1076#else
da32eb53
RD
1077 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1078 // The value of blocked passed in needs to be the same as that returned
1079 // from wxPyBeginBlockThreads at the same nesting level.
1080 if ( blocked ) {
b856768b
RD
1081 PyEval_SaveThread();
1082 }
1112b0c6 1083#endif
6e6b3557 1084#endif
cf694132
RD
1085}
1086
19a97bd6 1087
d559219f 1088//---------------------------------------------------------------------------
f74ff5ef
RD
1089// wxPyInputStream and wxPyCBInputStream methods
1090
f74ff5ef
RD
1091
1092void wxPyInputStream::close() {
a541c325 1093 /* do nothing for now */
f74ff5ef
RD
1094}
1095
1096void wxPyInputStream::flush() {
a541c325 1097 /* do nothing for now */
f74ff5ef
RD
1098}
1099
1100bool wxPyInputStream::eof() {
1101 if (m_wxis)
1102 return m_wxis->Eof();
1103 else
4519a2d9 1104 return true;
f74ff5ef
RD
1105}
1106
1107wxPyInputStream::~wxPyInputStream() {
f464a4f2
RD
1108 if (m_wxis)
1109 delete m_wxis;
f74ff5ef
RD
1110}
1111
a541c325
RD
1112
1113
1114
1115PyObject* wxPyInputStream::read(int size) {
1116 PyObject* obj = NULL;
1117 wxMemoryBuffer buf;
f74ff5ef
RD
1118 const int BUFSIZE = 1024;
1119
1120 // check if we have a real wxInputStream to work with
1121 if (!m_wxis) {
6e6b3557 1122 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f74ff5ef 1123 PyErr_SetString(PyExc_IOError, "no valid C-wxInputStream");
da32eb53 1124 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1125 return NULL;
1126 }
1127
1128 if (size < 0) {
1e4a197e
RD
1129 // read while bytes are available on the stream
1130 while ( m_wxis->CanRead() ) {
a541c325
RD
1131 m_wxis->Read(buf.GetAppendBuf(BUFSIZE), BUFSIZE);
1132 buf.UngetAppendBuf(m_wxis->LastRead());
f74ff5ef
RD
1133 }
1134
1135 } else { // Read only size number of characters
a541c325
RD
1136 m_wxis->Read(buf.GetWriteBuf(size), size);
1137 buf.UngetWriteBuf(m_wxis->LastRead());
1138 }
f74ff5ef 1139
a541c325 1140 // error check
6e6b3557 1141 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1e4a197e
RD
1142 wxStreamError err = m_wxis->GetLastError();
1143 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
a541c325
RD
1144 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
1145 }
1146 else {
1147 // We use only strings for the streams, not unicode
1148 obj = PyString_FromStringAndSize(buf, buf.GetDataLen());
f74ff5ef 1149 }
da32eb53 1150 wxPyEndBlockThreads(blocked);
a541c325 1151 return obj;
f74ff5ef
RD
1152}
1153
1154
a541c325
RD
1155PyObject* wxPyInputStream::readline(int size) {
1156 PyObject* obj = NULL;
1157 wxMemoryBuffer buf;
1158 int i;
1159 char ch;
1160
f74ff5ef
RD
1161 // check if we have a real wxInputStream to work with
1162 if (!m_wxis) {
6e6b3557 1163 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f74ff5ef 1164 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
da32eb53 1165 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1166 return NULL;
1167 }
1168
f74ff5ef 1169 // read until \n or byte limit reached
1e4a197e 1170 for (i=ch=0; (ch != '\n') && (m_wxis->CanRead()) && ((size < 0) || (i < size)); i++) {
a541c325
RD
1171 ch = m_wxis->GetC();
1172 buf.AppendByte(ch);
f74ff5ef
RD
1173 }
1174
1175 // errorcheck
6e6b3557 1176 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1e4a197e
RD
1177 wxStreamError err = m_wxis->GetLastError();
1178 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
f74ff5ef 1179 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
f74ff5ef 1180 }
a541c325
RD
1181 else {
1182 // We use only strings for the streams, not unicode
1183 obj = PyString_FromStringAndSize((char*)buf.GetData(), buf.GetDataLen());
1184 }
da32eb53 1185 wxPyEndBlockThreads(blocked);
a541c325 1186 return obj;
f74ff5ef
RD
1187}
1188
1189
a541c325
RD
1190PyObject* wxPyInputStream::readlines(int sizehint) {
1191 PyObject* pylist;
1192
f74ff5ef
RD
1193 // check if we have a real wxInputStream to work with
1194 if (!m_wxis) {
6e6b3557 1195 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1e4a197e 1196 PyErr_SetString(PyExc_IOError,"no valid C-wxInputStream");
da32eb53 1197 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1198 return NULL;
1199 }
1200
1201 // init list
6e6b3557 1202 wxPyBlock_t blocked = wxPyBeginBlockThreads();
a541c325 1203 pylist = PyList_New(0);
da32eb53 1204 wxPyEndBlockThreads(blocked);
d02ea46c 1205
a541c325 1206 if (!pylist) {
6e6b3557 1207 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f74ff5ef 1208 PyErr_NoMemory();
da32eb53 1209 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1210 return NULL;
1211 }
1212
1213 // read sizehint bytes or until EOF
1214 int i;
1e4a197e 1215 for (i=0; (m_wxis->CanRead()) && ((sizehint < 0) || (i < sizehint));) {
a541c325 1216 PyObject* s = this->readline();
f74ff5ef 1217 if (s == NULL) {
6e6b3557 1218 wxPyBlock_t blocked = wxPyBeginBlockThreads();
a541c325 1219 Py_DECREF(pylist);
da32eb53 1220 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1221 return NULL;
1222 }
6e6b3557 1223 wxPyBlock_t blocked = wxPyBeginBlockThreads();
a541c325
RD
1224 PyList_Append(pylist, s);
1225 i += PyString_Size(s);
da32eb53 1226 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1227 }
1228
1229 // error check
1e4a197e
RD
1230 wxStreamError err = m_wxis->GetLastError();
1231 if (err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF) {
6e6b3557 1232 wxPyBlock_t blocked = wxPyBeginBlockThreads();
a541c325 1233 Py_DECREF(pylist);
f74ff5ef 1234 PyErr_SetString(PyExc_IOError,"IOError in wxInputStream");
da32eb53 1235 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1236 return NULL;
1237 }
a541c325
RD
1238
1239 return pylist;
f74ff5ef
RD
1240}
1241
1242
1243void wxPyInputStream::seek(int offset, int whence) {
1244 if (m_wxis)
1245 m_wxis->SeekI(offset, wxSeekMode(whence));
1246}
1247
1248int wxPyInputStream::tell(){
1249 if (m_wxis)
1250 return m_wxis->TellI();
1251 else return 0;
1252}
1253
1254
1255
1256
1257wxPyCBInputStream::wxPyCBInputStream(PyObject *r, PyObject *s, PyObject *t, bool block)
1258 : wxInputStream(), m_read(r), m_seek(s), m_tell(t), m_block(block)
1259{}
1260
d02ea46c
RD
1261wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream& other)
1262{
1263 m_read = other.m_read;
1264 m_seek = other.m_seek;
1265 m_tell = other.m_tell;
1266 m_block = other.m_block;
1267 Py_INCREF(m_read);
1268 Py_INCREF(m_seek);
1269 Py_INCREF(m_tell);
1270}
1271
f74ff5ef
RD
1272
1273wxPyCBInputStream::~wxPyCBInputStream() {
9e1729e5 1274 wxPyBlock_t blocked = wxPyBlock_t_default;
da32eb53 1275 if (m_block) blocked = wxPyBeginBlockThreads();
f74ff5ef
RD
1276 Py_XDECREF(m_read);
1277 Py_XDECREF(m_seek);
1278 Py_XDECREF(m_tell);
da32eb53 1279 if (m_block) wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1280}
1281
1282
1283wxPyCBInputStream* wxPyCBInputStream::create(PyObject *py, bool block) {
9e1729e5 1284 wxPyBlock_t blocked = wxPyBlock_t_default;
da32eb53 1285 if (block) blocked = wxPyBeginBlockThreads();
f74ff5ef
RD
1286
1287 PyObject* read = getMethod(py, "read");
1288 PyObject* seek = getMethod(py, "seek");
1289 PyObject* tell = getMethod(py, "tell");
1290
1291 if (!read) {
1292 PyErr_SetString(PyExc_TypeError, "Not a file-like object");
1293 Py_XDECREF(read);
1294 Py_XDECREF(seek);
1295 Py_XDECREF(tell);
da32eb53 1296 if (block) wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1297 return NULL;
1298 }
1299
da32eb53 1300 if (block) wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1301 return new wxPyCBInputStream(read, seek, tell, block);
1302}
1303
249a57f4
RD
1304
1305wxPyCBInputStream* wxPyCBInputStream_create(PyObject *py, bool block) {
1306 return wxPyCBInputStream::create(py, block);
1307}
1308
d02ea46c
RD
1309wxPyCBInputStream* wxPyCBInputStream_copy(wxPyCBInputStream* other) {
1310 return new wxPyCBInputStream(*other);
1311}
1312
f74ff5ef
RD
1313PyObject* wxPyCBInputStream::getMethod(PyObject* py, char* name) {
1314 if (!PyObject_HasAttrString(py, name))
1315 return NULL;
1316 PyObject* o = PyObject_GetAttrString(py, name);
1317 if (!PyMethod_Check(o) && !PyCFunction_Check(o)) {
1318 Py_DECREF(o);
1319 return NULL;
1320 }
1321 return o;
1322}
1323
1324
588066b7 1325wxFileOffset wxPyCBInputStream::GetLength() const {
f74ff5ef
RD
1326 wxPyCBInputStream* self = (wxPyCBInputStream*)this; // cast off const
1327 if (m_seek && m_tell) {
3bc06221
RD
1328 wxFileOffset temp = self->OnSysTell();
1329 wxFileOffset ret = self->OnSysSeek(0, wxFromEnd);
f74ff5ef
RD
1330 self->OnSysSeek(temp, wxFromStart);
1331 return ret;
1332 }
1333 else
588066b7 1334 return wxInvalidOffset;
f74ff5ef
RD
1335}
1336
1337
1338size_t wxPyCBInputStream::OnSysRead(void *buffer, size_t bufsize) {
1339 if (bufsize == 0)
1340 return 0;
1341
6e6b3557 1342 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f74ff5ef
RD
1343 PyObject* arglist = Py_BuildValue("(i)", bufsize);
1344 PyObject* result = PyEval_CallObject(m_read, arglist);
1345 Py_DECREF(arglist);
1346
1347 size_t o = 0;
a541c325 1348 if ((result != NULL) && PyString_Check(result)) {
f74ff5ef
RD
1349 o = PyString_Size(result);
1350 if (o == 0)
1351 m_lasterror = wxSTREAM_EOF;
1352 if (o > bufsize)
1353 o = bufsize;
a541c325 1354 memcpy((char*)buffer, PyString_AsString(result), o); // strings only, not unicode...
f74ff5ef
RD
1355 Py_DECREF(result);
1356
1357 }
1358 else
1359 m_lasterror = wxSTREAM_READ_ERROR;
da32eb53 1360 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1361 return o;
1362}
1363
1364size_t wxPyCBInputStream::OnSysWrite(const void *buffer, size_t bufsize) {
1365 m_lasterror = wxSTREAM_WRITE_ERROR;
1366 return 0;
1367}
1368
f464a4f2 1369
3bc06221 1370wxFileOffset wxPyCBInputStream::OnSysSeek(wxFileOffset off, wxSeekMode mode) {
6e6b3557 1371 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f464a4f2
RD
1372 PyObject* arglist = PyTuple_New(2);
1373
1374 if (sizeof(wxFileOffset) > sizeof(long))
1375 // wxFileOffset is a 64-bit value...
1376 PyTuple_SET_ITEM(arglist, 0, PyLong_FromLongLong(off));
1377 else
1378 PyTuple_SET_ITEM(arglist, 0, PyInt_FromLong(off));
1379
1380 PyTuple_SET_ITEM(arglist, 1, PyInt_FromLong(mode));
1381
d02ea46c 1382
f74ff5ef
RD
1383 PyObject* result = PyEval_CallObject(m_seek, arglist);
1384 Py_DECREF(arglist);
1385 Py_XDECREF(result);
da32eb53 1386 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1387 return OnSysTell();
1388}
1389
1fded56b 1390
3bc06221 1391wxFileOffset wxPyCBInputStream::OnSysTell() const {
6e6b3557 1392 wxPyBlock_t blocked = wxPyBeginBlockThreads();
f74ff5ef
RD
1393 PyObject* arglist = Py_BuildValue("()");
1394 PyObject* result = PyEval_CallObject(m_tell, arglist);
1395 Py_DECREF(arglist);
3bc06221 1396 wxFileOffset o = 0;
f74ff5ef 1397 if (result != NULL) {
1fded56b
RD
1398 if (PyLong_Check(result))
1399 o = PyLong_AsLongLong(result);
1400 else
93b663b8 1401 o = PyInt_AsLong(result);
f74ff5ef
RD
1402 Py_DECREF(result);
1403 };
da32eb53 1404 wxPyEndBlockThreads(blocked);
f74ff5ef
RD
1405 return o;
1406}
1407
1408//----------------------------------------------------------------------
d559219f 1409
43d6e3ca 1410IMPLEMENT_ABSTRACT_CLASS(wxPyCallback, wxObject);
2f90df85 1411
d559219f
RD
1412wxPyCallback::wxPyCallback(PyObject* func) {
1413 m_func = func;
1414 Py_INCREF(m_func);
1415}
1416
2f90df85
RD
1417wxPyCallback::wxPyCallback(const wxPyCallback& other) {
1418 m_func = other.m_func;
1419 Py_INCREF(m_func);
1420}
1421
d559219f 1422wxPyCallback::~wxPyCallback() {
6e6b3557 1423 wxPyBlock_t blocked = wxPyBeginBlockThreads();
d559219f 1424 Py_DECREF(m_func);
da32eb53 1425 wxPyEndBlockThreads(blocked);
d559219f
RD
1426}
1427
cf694132 1428
da32eb53
RD
1429#define wxPy_PRECALLINIT "_preCallInit"
1430#define wxPy_POSTCALLCLEANUP "_postCallCleanup"
cf694132 1431
7bf85405
RD
1432// This function is used for all events destined for Python event handlers.
1433void wxPyCallback::EventThunker(wxEvent& event) {
1434 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
1435 PyObject* func = cb->m_func;
1436 PyObject* result;
1437 PyObject* arg;
1438 PyObject* tuple;
4519a2d9 1439 bool checkSkip = false;
cf694132 1440
6e6b3557 1441 wxPyBlock_t blocked = wxPyBeginBlockThreads();
65dd82cb
RD
1442 wxString className = event.GetClassInfo()->GetClassName();
1443
3734a866
RD
1444 // If the event is one of these types then pass the original
1445 // event object instead of the one passed to us.
1446 if ( className == wxT("wxPyEvent") ) {
1447 arg = ((wxPyEvent*)&event)->GetSelf();
1448 checkSkip = ((wxPyEvent*)&event)->GetCloned();
1449 }
1450 else if ( className == wxT("wxPyCommandEvent") ) {
1451 arg = ((wxPyCommandEvent*)&event)->GetSelf();
1452 checkSkip = ((wxPyCommandEvent*)&event)->GetCloned();
1453 }
c8bc7bb8 1454 else {
a541c325 1455 arg = wxPyConstructObject((void*)&event, className);
c8bc7bb8 1456 }
7bf85405 1457
b856768b 1458 if (!arg) {
7bf85405 1459 PyErr_Print();
b856768b 1460 } else {
da32eb53
RD
1461 // "intern" the pre/post method names to speed up the HasAttr
1462 static PyObject* s_preName = NULL;
1463 static PyObject* s_postName = NULL;
1464 if (s_preName == NULL) {
1465 s_preName = PyString_FromString(wxPy_PRECALLINIT);
1466 s_postName = PyString_FromString(wxPy_POSTCALLCLEANUP);
1467 }
d02ea46c 1468
b7c75283 1469 // Check if the event object needs some preinitialization
da32eb53
RD
1470 if (PyObject_HasAttr(arg, s_preName)) {
1471 result = PyObject_CallMethodObjArgs(arg, s_preName, arg, NULL);
b7c75283
RD
1472 if ( result ) {
1473 Py_DECREF(result); // result is ignored, but we still need to decref it
1474 PyErr_Clear(); // Just in case...
1475 } else {
1476 PyErr_Print();
d02ea46c 1477 }
b7c75283 1478 }
d02ea46c 1479
b856768b
RD
1480 // Call the event handler, passing the event object
1481 tuple = PyTuple_New(1);
1482 PyTuple_SET_ITEM(tuple, 0, arg); // steals ref to arg
1483 result = PyEval_CallObject(func, tuple);
3734a866 1484 if ( result ) {
b856768b
RD
1485 Py_DECREF(result); // result is ignored, but we still need to decref it
1486 PyErr_Clear(); // Just in case...
3734a866
RD
1487 } else {
1488 PyErr_Print();
1489 }
3734a866 1490
da32eb53
RD
1491 // Check if the event object needs some post cleanup
1492 if (PyObject_HasAttr(arg, s_postName)) {
1493 result = PyObject_CallMethodObjArgs(arg, s_postName, arg, NULL);
1494 if ( result ) {
1495 Py_DECREF(result); // result is ignored, but we still need to decref it
1496 PyErr_Clear(); // Just in case...
1497 } else {
1498 PyErr_Print();
d02ea46c 1499 }
da32eb53
RD
1500 }
1501
b856768b
RD
1502 if ( checkSkip ) {
1503 // if the event object was one of our special types and
1504 // it had been cloned, then we need to extract the Skipped
1505 // value from the original and set it in the clone.
1506 result = PyObject_CallMethod(arg, "GetSkipped", "");
1507 if ( result ) {
1508 event.Skip(PyInt_AsLong(result));
1509 Py_DECREF(result);
1510 } else {
1511 PyErr_Print();
1512 }
1513 }
1514 Py_DECREF(tuple);
1515 }
da32eb53 1516 wxPyEndBlockThreads(blocked);
7bf85405
RD
1517}
1518
1519
d559219f 1520//----------------------------------------------------------------------
7bf85405 1521
2f90df85
RD
1522wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper& other) {
1523 m_lastFound = NULL;
1524 m_self = other.m_self;
f6bcfd97
BP
1525 m_class = other.m_class;
1526 if (m_self) {
2f90df85 1527 Py_INCREF(m_self);
f6bcfd97
BP
1528 Py_INCREF(m_class);
1529 }
2f90df85
RD
1530}
1531
1532
33510773 1533void wxPyCallbackHelper::setSelf(PyObject* self, PyObject* klass, int incref) {
d559219f 1534 m_self = self;
33510773 1535 m_class = klass;
b7312675 1536 m_incRef = incref;
f6bcfd97 1537 if (incref) {
2f90df85 1538 Py_INCREF(m_self);
f6bcfd97
BP
1539 Py_INCREF(m_class);
1540 }
d559219f 1541}
8bf5d46e 1542
8bf5d46e 1543
78b57918
RD
1544#if PYTHON_API_VERSION >= 1011
1545
1546// Prior to Python 2.2 PyMethod_GetClass returned the class object
1547// in which the method was defined. Starting with 2.2 it returns
1548// "class that asked for the method" which seems totally bogus to me
4152e8b9 1549// but apprently it fixes some obscure problem waiting to happen in
78b57918
RD
1550// Python. Since the API was not documented Guido and the gang felt
1551// safe in changing it. Needless to say that totally screwed up the
1552// logic below in wxPyCallbackHelper::findCallback, hence this icky
4152e8b9 1553// code to find the class where the method is actually defined...
78b57918
RD
1554
1555static
1556PyObject* PyFindClassWithAttr(PyObject *klass, PyObject *name)
1557{
1558 int i, n;
1559
1560 if (PyType_Check(klass)) { // new style classes
1561 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1562 PyTypeObject* type = (PyTypeObject*)klass;
1563 PyObject *mro, *res, *base, *dict;
1564 /* Look in tp_dict of types in MRO */
1565 mro = type->tp_mro;
1566 assert(PyTuple_Check(mro));
1567 n = PyTuple_GET_SIZE(mro);
1568 for (i = 0; i < n; i++) {
1569 base = PyTuple_GET_ITEM(mro, i);
1570 if (PyClass_Check(base))
1571 dict = ((PyClassObject *)base)->cl_dict;
1572 else {
1573 assert(PyType_Check(base));
1574 dict = ((PyTypeObject *)base)->tp_dict;
1575 }
1576 assert(dict && PyDict_Check(dict));
1577 res = PyDict_GetItem(dict, name);
1578 if (res != NULL)
4a98c806 1579 return base;
78b57918
RD
1580 }
1581 return NULL;
1582 }
1583
1584 else if (PyClass_Check(klass)) { // old style classes
1585 // This code is borrowed/adapted from class_lookup in classobject.c
1586 PyClassObject* cp = (PyClassObject*)klass;
1587 PyObject *value = PyDict_GetItem(cp->cl_dict, name);
1588 if (value != NULL) {
1589 return (PyObject*)cp;
1590 }
1591 n = PyTuple_Size(cp->cl_bases);
1592 for (i = 0; i < n; i++) {
1593 PyObject* base = PyTuple_GetItem(cp->cl_bases, i);
1594 PyObject *v = PyFindClassWithAttr(base, name);
1595 if (v != NULL)
1596 return v;
1597 }
1598 return NULL;
1599 }
4152e8b9 1600 return NULL;
78b57918
RD
1601}
1602#endif
1603
1604
1605static
a7a01418 1606PyObject* PyMethod_GetDefiningClass(PyObject* method, PyObject* nameo)
78b57918
RD
1607{
1608 PyObject* mgc = PyMethod_GET_CLASS(method);
1609
1610#if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1611 return mgc;
1612#else // 2.2 and after, the hard way...
a7a01418 1613 return PyFindClassWithAttr(mgc, nameo);
78b57918
RD
1614#endif
1615}
1616
1617
1618
a7a01418
RD
1619// To avoid recursion when an overridden virtual method wants to call the base
1620// class version, temporarily set an attribute in the instance with the same
1621// name as the method. Then the PyObject_GetAttr in the next findCallback
1622// will return this attribute and the PyMethod_Check will fail.
1623
1624void wxPyCallbackHelper::setRecursionGuard(PyObject* method) const
1625{
1626 PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1627 PyObject_SetAttr(m_self, func->func_name, Py_None);
1628}
1629
1630void wxPyCallbackHelper::clearRecursionGuard(PyObject* method) const
1631{
1632 PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1633 if (PyObject_HasAttr(m_self, func->func_name)) {
1634 PyObject_DelAttr(m_self, func->func_name);
1635 }
1636}
1637
1638// bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1639// {
1640// PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1641// if (PyObject_HasAttr(m_self, func->func_name)) {
1642// PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1643// bool retval = (attr == Py_None);
1644// Py_DECREF(attr);
1645// return retval;
1646// }
1647// return false;
1648// }
1649
1650
369ac260 1651bool wxPyCallbackHelper::findCallback(const char* name, bool setGuard) const {
f6bcfd97 1652 wxPyCallbackHelper* self = (wxPyCallbackHelper*)this; // cast away const
a7a01418
RD
1653 PyObject *method, *klass;
1654 PyObject* nameo = PyString_FromString(name);
f6bcfd97 1655 self->m_lastFound = NULL;
78b57918
RD
1656
1657 // If the object (m_self) has an attibute of the given name...
a7a01418
RD
1658 if (m_self && PyObject_HasAttr(m_self, nameo)) {
1659 method = PyObject_GetAttr(m_self, nameo);
f6bcfd97 1660
78b57918 1661 // ...and if that attribute is a method, and if that method's class is
a7a01418 1662 // not from the registered class or a base class...
f6bcfd97 1663 if (PyMethod_Check(method) &&
a7a01418
RD
1664 (klass = PyMethod_GetDefiningClass(method, nameo)) != NULL &&
1665 (klass != m_class) &&
1666 PyObject_IsSubclass(klass, m_class)) {
1667
1668 // ...then we'll save a pointer to the method so callCallback can
1669 // call it. But first, set a recursion guard in case the
1670 // overridden method wants to call the base class version.
369ac260
RD
1671 if (setGuard)
1672 setRecursionGuard(method);
f6bcfd97
BP
1673 self->m_lastFound = method;
1674 }
de20db99
RD
1675 else {
1676 Py_DECREF(method);
1677 }
f6bcfd97 1678 }
a7a01418
RD
1679
1680 Py_DECREF(nameo);
d559219f
RD
1681 return m_lastFound != NULL;
1682}
8bf5d46e 1683
d559219f 1684
f6bcfd97 1685int wxPyCallbackHelper::callCallback(PyObject* argTuple) const {
d559219f 1686 PyObject* result;
4519a2d9 1687 int retval = false;
d559219f
RD
1688
1689 result = callCallbackObj(argTuple);
1690 if (result) { // Assumes an integer return type...
1691 retval = PyInt_AsLong(result);
1692 Py_DECREF(result);
1693 PyErr_Clear(); // forget about it if it's not...
1694 }
1695 return retval;
1696}
1697
1698// Invoke the Python callable object, returning the raw PyObject return
f048f829 1699// value. Caller should DECREF the return value and also manage the GIL.
f6bcfd97 1700PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) const {
de20db99 1701 PyObject* result;
d559219f 1702
de20db99
RD
1703 // Save a copy of the pointer in case the callback generates another
1704 // callback. In that case m_lastFound will have a different value when
1705 // it gets back here...
1706 PyObject* method = m_lastFound;
1707
1708 result = PyEval_CallObject(method, argTuple);
a7a01418
RD
1709 clearRecursionGuard(method);
1710
d559219f 1711 Py_DECREF(argTuple);
de20db99 1712 Py_DECREF(method);
d559219f
RD
1713 if (!result) {
1714 PyErr_Print();
1715 }
1716 return result;
1717}
714e6a9e 1718
7bf85405 1719
0122b7e3 1720void wxPyCBH_setCallbackInfo(wxPyCallbackHelper& cbh, PyObject* self, PyObject* klass, int incref) {
1e7ecb7b
RD
1721 cbh.setSelf(self, klass, incref);
1722}
1723
369ac260
RD
1724bool wxPyCBH_findCallback(const wxPyCallbackHelper& cbh, const char* name, bool setGuard) {
1725 return cbh.findCallback(name, setGuard);
1e7ecb7b
RD
1726}
1727
1728int wxPyCBH_callCallback(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1729 return cbh.callCallback(argTuple);
1730}
1731
1732PyObject* wxPyCBH_callCallbackObj(const wxPyCallbackHelper& cbh, PyObject* argTuple) {
1733 return cbh.callCallbackObj(argTuple);
1734}
1735
1736
1737void wxPyCBH_delete(wxPyCallbackHelper* cbh) {
9f4a1fed 1738 if (cbh->m_incRef && Py_IsInitialized()) {
6e6b3557 1739 wxPyBlock_t blocked = wxPyBeginBlockThreads();
1e7ecb7b
RD
1740 Py_XDECREF(cbh->m_self);
1741 Py_XDECREF(cbh->m_class);
da32eb53 1742 wxPyEndBlockThreads(blocked);
1e7ecb7b 1743 }
1e7ecb7b 1744}
d559219f 1745
65dd82cb
RD
1746//---------------------------------------------------------------------------
1747//---------------------------------------------------------------------------
2aab8f16 1748// These event classes can be derived from in Python and passed through the event
c368d904 1749// system without losing anything. They do this by keeping a reference to
65dd82cb
RD
1750// themselves and some special case handling in wxPyCallback::EventThunker.
1751
1752
e19b7164 1753wxPyEvtSelfRef::wxPyEvtSelfRef() {
65dd82cb
RD
1754 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1755 //Py_INCREF(m_self); // circular loops...
4519a2d9 1756 m_cloned = false;
65dd82cb
RD
1757}
1758
e19b7164 1759wxPyEvtSelfRef::~wxPyEvtSelfRef() {
6e6b3557 1760 wxPyBlock_t blocked = wxPyBeginBlockThreads();
65dd82cb
RD
1761 if (m_cloned)
1762 Py_DECREF(m_self);
da32eb53 1763 wxPyEndBlockThreads(blocked);
65dd82cb
RD
1764}
1765
e19b7164 1766void wxPyEvtSelfRef::SetSelf(PyObject* self, bool clone) {
6e6b3557 1767 wxPyBlock_t blocked = wxPyBeginBlockThreads();
65dd82cb
RD
1768 if (m_cloned)
1769 Py_DECREF(m_self);
1770 m_self = self;
1771 if (clone) {
1772 Py_INCREF(m_self);
4519a2d9 1773 m_cloned = true;
65dd82cb 1774 }
da32eb53 1775 wxPyEndBlockThreads(blocked);
65dd82cb
RD
1776}
1777
e19b7164 1778PyObject* wxPyEvtSelfRef::GetSelf() const {
65dd82cb
RD
1779 Py_INCREF(m_self);
1780 return m_self;
1781}
1782
1783
07b2e1cd
RD
1784IMPLEMENT_ABSTRACT_CLASS(wxPyEvent, wxEvent);
1785IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent, wxCommandEvent);
1786
1787
3ef86e32
RD
1788wxPyEvent::wxPyEvent(int winid, wxEventType commandType)
1789 : wxEvent(winid, commandType) {
65dd82cb
RD
1790}
1791
65dd82cb 1792
07b2e1cd
RD
1793wxPyEvent::wxPyEvent(const wxPyEvent& evt)
1794 : wxEvent(evt)
1795{
4519a2d9 1796 SetSelf(evt.m_self, true);
65dd82cb
RD
1797}
1798
1799
07b2e1cd
RD
1800wxPyEvent::~wxPyEvent() {
1801}
65dd82cb
RD
1802
1803
1804wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType, int id)
1805 : wxCommandEvent(commandType, id) {
1806}
1807
65dd82cb 1808
07b2e1cd
RD
1809wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent& evt)
1810 : wxCommandEvent(evt)
1811{
4519a2d9 1812 SetSelf(evt.m_self, true);
65dd82cb
RD
1813}
1814
1815
07b2e1cd
RD
1816wxPyCommandEvent::~wxPyCommandEvent() {
1817}
1818
65dd82cb
RD
1819
1820
1821
cf694132 1822
2f90df85 1823//---------------------------------------------------------------------------
389c5527 1824//---------------------------------------------------------------------------
d14a1e28 1825// Convert a wxList to a Python List, only works for lists of wxObjects
389c5527 1826
d14a1e28 1827PyObject* wxPy_ConvertList(wxListBase* listbase) {
1e4a197e 1828 wxList* list = (wxList*)listbase; // this is probably bad...
389c5527
RD
1829 PyObject* pyList;
1830 PyObject* pyObj;
1831 wxObject* wxObj;
1e4a197e 1832 wxNode* node = list->GetFirst();
389c5527 1833
6e6b3557 1834 wxPyBlock_t blocked = wxPyBeginBlockThreads();
389c5527
RD
1835 pyList = PyList_New(0);
1836 while (node) {
1e4a197e 1837 wxObj = node->GetData();
6d450e1a 1838 pyObj = wxPyMake_wxObject(wxObj,false);
389c5527 1839 PyList_Append(pyList, pyObj);
cd0a59fb 1840 Py_DECREF(pyObj); // the Append also does an INCREF, that's one more than we need.
1e4a197e 1841 node = node->GetNext();
389c5527 1842 }
da32eb53 1843 wxPyEndBlockThreads(blocked);
389c5527
RD
1844 return pyList;
1845}
1846
54b96882
RD
1847//----------------------------------------------------------------------
1848
1849long wxPyGetWinHandle(wxWindow* win) {
1b35fec7 1850
54b96882
RD
1851#ifdef __WXMSW__
1852 return (long)win->GetHandle();
1853#endif
26eac43e 1854
98bc3dcf
RD
1855#if defined(__WXGTK__) || defined(__WXX11)
1856 return (long)GetXWindow(win);
54b96882 1857#endif
d02ea46c 1858
1b35fec7 1859#ifdef __WXMAC__
9c605df7
RD
1860 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1861 return (long)win->GetHandle();
1b35fec7 1862#endif
26eac43e 1863
54b96882
RD
1864 return 0;
1865}
1866
7bf85405
RD
1867//----------------------------------------------------------------------
1868// Some helper functions for typemaps in my_typemaps.i, so they won't be
c8bc7bb8
RD
1869// included in every file over and over again...
1870
c8bc7bb8 1871wxString* wxString_in_helper(PyObject* source) {
3eb1aad7
RD
1872 wxString* target = NULL;
1873
c8bc7bb8 1874 if (!PyString_Check(source) && !PyUnicode_Check(source)) {
3eb1aad7 1875 PyErr_SetString(PyExc_TypeError, "String or Unicode type required");
c8bc7bb8
RD
1876 return NULL;
1877 }
1878#if wxUSE_UNICODE
3eb1aad7
RD
1879 PyObject* uni = source;
1880 if (PyString_Check(source)) {
27c9e43c 1881 uni = PyUnicode_FromEncodedObject(source, wxPyDefaultEncoding, "strict");
3eb1aad7 1882 if (PyErr_Occurred()) return NULL;
c8bc7bb8 1883 }
3eb1aad7
RD
1884 target = new wxString();
1885 size_t len = PyUnicode_GET_SIZE(uni);
1886 if (len) {
5647b95a 1887 PyUnicode_AsWideChar((PyUnicodeObject*)uni, wxStringBuffer(*target, len), len);
3eb1aad7
RD
1888 }
1889
1890 if (PyString_Check(source))
1891 Py_DECREF(uni);
c8bc7bb8 1892#else
db301e68
RD
1893 // Convert to a string object if it isn't already, then to wxString
1894 PyObject* str = source;
27c9e43c
RD
1895 if (PyUnicode_Check(source)) {
1896 str = PyUnicode_AsEncodedString(source, wxPyDefaultEncoding, "strict");
1897 if (PyErr_Occurred()) return NULL;
d02ea46c 1898 }
27c9e43c 1899 else if (!PyString_Check(source)) {
db301e68
RD
1900 str = PyObject_Str(source);
1901 if (PyErr_Occurred()) return NULL;
c8bc7bb8 1902 }
a608c09d 1903 char* tmpPtr; Py_ssize_t tmpSize;
db301e68 1904 PyString_AsStringAndSize(str, &tmpPtr, &tmpSize);
c8bc7bb8 1905 target = new wxString(tmpPtr, tmpSize);
d02ea46c 1906
db301e68
RD
1907 if (!PyString_Check(source))
1908 Py_DECREF(str);
c8bc7bb8 1909#endif // wxUSE_UNICODE
d02ea46c 1910
c8bc7bb8
RD
1911 return target;
1912}
1913
7bf85405 1914
a541c325
RD
1915// Similar to above except doesn't use "new" and doesn't set an exception
1916wxString Py2wxString(PyObject* source)
1917{
1918 wxString target;
a541c325
RD
1919
1920#if wxUSE_UNICODE
3eb1aad7
RD
1921 // Convert to a unicode object, if not already, then to a wxString
1922 PyObject* uni = source;
1923 if (!PyUnicode_Check(source)) {
27c9e43c 1924 uni = PyUnicode_FromEncodedObject(source, wxPyDefaultEncoding, "strict");
3eb1aad7 1925 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
d02ea46c 1926 }
3eb1aad7
RD
1927 size_t len = PyUnicode_GET_SIZE(uni);
1928 if (len) {
5647b95a 1929 PyUnicode_AsWideChar((PyUnicodeObject*)uni, wxStringBuffer(target, len), len);
a541c325 1930 }
d02ea46c 1931
3eb1aad7
RD
1932 if (!PyUnicode_Check(source))
1933 Py_DECREF(uni);
a541c325 1934#else
3eb1aad7
RD
1935 // Convert to a string object if it isn't already, then to wxString
1936 PyObject* str = source;
27c9e43c
RD
1937 if (PyUnicode_Check(source)) {
1938 str = PyUnicode_AsEncodedString(source, wxPyDefaultEncoding, "strict");
1939 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
d02ea46c 1940 }
27c9e43c 1941 else if (!PyString_Check(source)) {
3eb1aad7
RD
1942 str = PyObject_Str(source);
1943 if (PyErr_Occurred()) return wxEmptyString; // TODO: should we PyErr_Clear?
1944 }
a608c09d 1945 char* tmpPtr; Py_ssize_t tmpSize;
3eb1aad7 1946 PyString_AsStringAndSize(str, &tmpPtr, &tmpSize);
a541c325 1947 target = wxString(tmpPtr, tmpSize);
d02ea46c 1948
3eb1aad7
RD
1949 if (!PyString_Check(source))
1950 Py_DECREF(str);
a541c325
RD
1951#endif // wxUSE_UNICODE
1952
a541c325
RD
1953 return target;
1954}
1955
1956
1957// Make either a Python String or Unicode object, depending on build mode
1958PyObject* wx2PyString(const wxString& src)
1959{
1960 PyObject* str;
1961#if wxUSE_UNICODE
1e4a197e 1962 str = PyUnicode_FromWideChar(src.c_str(), src.Len());
a541c325
RD
1963#else
1964 str = PyString_FromStringAndSize(src.c_str(), src.Len());
1965#endif
1966 return str;
1967}
1968
1969
27c9e43c
RD
1970
1971void wxSetDefaultPyEncoding(const char* encoding)
1972{
1973 strncpy(wxPyDefaultEncoding, encoding, DEFAULTENCODING_SIZE);
1974}
1975
1976const char* wxGetDefaultPyEncoding()
1977{
1978 return wxPyDefaultEncoding;
1979}
1980
a541c325
RD
1981//----------------------------------------------------------------------
1982
7bf85405 1983
2f90df85 1984byte* byte_LIST_helper(PyObject* source) {
b639c3c5
RD
1985 if (!PyList_Check(source)) {
1986 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
1987 return NULL;
1988 }
1989 int count = PyList_Size(source);
1990 byte* temp = new byte[count];
1991 if (! temp) {
1992 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
1993 return NULL;
1994 }
1995 for (int x=0; x<count; x++) {
1996 PyObject* o = PyList_GetItem(source, x);
1997 if (! PyInt_Check(o)) {
1998 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
1999 return NULL;
2000 }
2001 temp[x] = (byte)PyInt_AsLong(o);
2002 }
2003 return temp;
2004}
2005
2006
2f90df85 2007int* int_LIST_helper(PyObject* source) {
7bf85405
RD
2008 if (!PyList_Check(source)) {
2009 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2010 return NULL;
2011 }
2012 int count = PyList_Size(source);
2013 int* temp = new int[count];
2014 if (! temp) {
2015 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2016 return NULL;
2017 }
2018 for (int x=0; x<count; x++) {
2019 PyObject* o = PyList_GetItem(source, x);
2020 if (! PyInt_Check(o)) {
2021 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
2022 return NULL;
2023 }
2024 temp[x] = PyInt_AsLong(o);
2025 }
2026 return temp;
2027}
2028
2029
2f90df85 2030long* long_LIST_helper(PyObject* source) {
7bf85405
RD
2031 if (!PyList_Check(source)) {
2032 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2033 return NULL;
2034 }
2035 int count = PyList_Size(source);
2036 long* temp = new long[count];
2037 if (! temp) {
2038 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2039 return NULL;
2040 }
2041 for (int x=0; x<count; x++) {
2042 PyObject* o = PyList_GetItem(source, x);
2043 if (! PyInt_Check(o)) {
2044 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
2045 return NULL;
2046 }
2047 temp[x] = PyInt_AsLong(o);
2048 }
2049 return temp;
2050}
2051
2052
2f90df85 2053char** string_LIST_helper(PyObject* source) {
7bf85405
RD
2054 if (!PyList_Check(source)) {
2055 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2056 return NULL;
2057 }
2058 int count = PyList_Size(source);
2059 char** temp = new char*[count];
2060 if (! temp) {
2061 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2062 return NULL;
2063 }
2064 for (int x=0; x<count; x++) {
2065 PyObject* o = PyList_GetItem(source, x);
2066 if (! PyString_Check(o)) {
2067 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2068 return NULL;
2069 }
2070 temp[x] = PyString_AsString(o);
2071 }
2072 return temp;
2073}
2074
281c54cc
RD
2075//---------------------------------------------------------------------------
2076// NOTE: The following functions could really use some refactoring using
2077// templates to make things somewhat simpler...
2078
2079inline bool wxPointFromObjects(PyObject* o1, PyObject* o2, wxPoint* point)
2080{
2081 // get the x value
2082 if (PyInt_Check(o1))
2083 point->x = (int)PyInt_AS_LONG(o1);
2084 else if (PyFloat_Check(o1))
e0672e2f 2085 point->x = (int)PyFloat_AS_DOUBLE(o1);
281c54cc
RD
2086 else if (PyNumber_Check(o1))
2087 point->x = (int)PyInt_AsLong(o1);
2088 else
2089 return false;
2090
2091 // get the y value
2092 if (PyInt_Check(o2))
2093 point->y = (int)PyInt_AS_LONG(o2);
2094 else if (PyFloat_Check(o2))
e0672e2f 2095 point->y = (int)PyFloat_AS_DOUBLE(o2);
281c54cc
RD
2096 else if (PyNumber_Check(o2))
2097 point->y = (int)PyInt_AsLong(o2);
2098 else
4519a2d9 2099 return false;
281c54cc
RD
2100
2101 return true;
2102
2103// NOTE: This function used to have this code in it, but I don't know why it
2104// is a problem nor what havok it will cause, so removing for now...
2105// if (wxPySwigInstance_Check(o1) || wxPySwigInstance_Check(o2)) {
2106// // Disallow instances because they can cause havok
2107// return false;
2108// }
2109}
2110
2111
2112inline bool wxPoint2DFromObjects(PyObject* o1, PyObject* o2, wxPoint2D* point)
2113{
2114 // get the x value
2115 if (PyInt_Check(o1))
2116 point->m_x = (double)PyInt_AS_LONG(o1);
2117 else if (PyFloat_Check(o1))
2118 point->m_x = (double)PyFloat_AS_DOUBLE(o1);
2119 else if (PyNumber_Check(o1))
2120 point->m_x = (double)PyFloat_AsDouble(o1);
2121 else
2122 return false;
2123
2124 // get the y value
2125 if (PyInt_Check(o2))
2126 point->m_y = (double)PyInt_AS_LONG(o2);
2127 else if (PyFloat_Check(o2))
2128 point->m_y = (double)PyFloat_AS_DOUBLE(o2);
2129 else if (PyNumber_Check(o2))
2130 point->m_y = (double)PyFloat_AsDouble(o2);
2131 else
2132 return false;
2133
2134 return true;
e0672e2f 2135}
7bf85405
RD
2136
2137
281c54cc
RD
2138
2139wxPoint* wxPoint_LIST_helper(PyObject* source, int *count)
2140{
2141 int idx;
e0672e2f
RD
2142 wxPoint* temp;
2143 PyObject *o, *o1, *o2;
9d37f964 2144 bool isFast = PyList_Check(source) || PyTuple_Check(source);
e0672e2f 2145
e0672e2f
RD
2146 if (!PySequence_Check(source)) {
2147 goto error0;
7bf85405 2148 }
9d37f964
RD
2149
2150 // The length of the sequence is returned in count.
e0672e2f
RD
2151 *count = PySequence_Length(source);
2152 if (*count < 0) {
2153 goto error0;
2154 }
2155
2156 temp = new wxPoint[*count];
2157 if (!temp) {
7bf85405
RD
2158 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2159 return NULL;
2160 }
281c54cc 2161 for (idx=0; idx<*count; idx++) {
e0672e2f
RD
2162 // Get an item: try fast way first.
2163 if (isFast) {
281c54cc 2164 o = PySequence_Fast_GET_ITEM(source, idx);
e0672e2f
RD
2165 }
2166 else {
281c54cc 2167 o = PySequence_GetItem(source, idx);
e0672e2f
RD
2168 if (o == NULL) {
2169 goto error1;
2170 }
2171 }
7bf85405 2172
e0672e2f
RD
2173 // Convert o to wxPoint.
2174 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
2175 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
2176 o1 = PySequence_Fast_GET_ITEM(o, 0);
2177 o2 = PySequence_Fast_GET_ITEM(o, 1);
281c54cc 2178 if (!wxPointFromObjects(o1, o2, &temp[idx])) {
e0672e2f
RD
2179 goto error2;
2180 }
7bf85405 2181 }
d14a1e28 2182 else if (wxPySwigInstance_Check(o)) {
d559219f 2183 wxPoint* pt;
d14a1e28 2184 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPoint"))) {
e0672e2f 2185 goto error2;
d559219f 2186 }
281c54cc 2187 temp[idx] = *pt;
d559219f 2188 }
e0672e2f
RD
2189 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
2190 o1 = PySequence_GetItem(o, 0);
2191 o2 = PySequence_GetItem(o, 1);
281c54cc 2192 if (!wxPointFromObjects(o1, o2, &temp[idx])) {
e0672e2f
RD
2193 goto error3;
2194 }
2195 Py_DECREF(o1);
2196 Py_DECREF(o2);
2197 }
7bf85405 2198 else {
e0672e2f 2199 goto error2;
7bf85405 2200 }
e0672e2f
RD
2201 // Clean up.
2202 if (!isFast)
2203 Py_DECREF(o);
7bf85405
RD
2204 }
2205 return temp;
e0672e2f
RD
2206
2207error3:
2208 Py_DECREF(o1);
2209 Py_DECREF(o2);
2210error2:
2211 if (!isFast)
2212 Py_DECREF(o);
2213error1:
1e4a197e 2214 delete [] temp;
e0672e2f
RD
2215error0:
2216 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoints.");
2217 return NULL;
7bf85405 2218}
281c54cc
RD
2219
2220
2221
2222wxPoint2D* wxPoint2D_LIST_helper(PyObject* source, size_t *count)
2223{
2224 size_t idx;
2225 wxPoint2D* temp;
2226 PyObject *o, *o1, *o2;
2227 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2228
2229 if (!PySequence_Check(source)) {
2230 goto error0;
2231 }
2232
2233 // The length of the sequence is returned in count.
2234 *count = PySequence_Length(source);
2235 if (*count < 0) {
2236 goto error0;
2237 }
2238
2239 temp = new wxPoint2D[*count];
2240 if (!temp) {
2241 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2242 return NULL;
2243 }
2244 for (idx=0; idx<*count; idx++) {
2245 // Get an item: try fast way first.
2246 if (isFast) {
2247 o = PySequence_Fast_GET_ITEM(source, idx);
2248 }
2249 else {
2250 o = PySequence_GetItem(source, idx);
2251 if (o == NULL) {
2252 goto error1;
2253 }
2254 }
2255
2256 // Convert o to wxPoint.
2257 if ((PyTuple_Check(o) && PyTuple_GET_SIZE(o) == 2) ||
2258 (PyList_Check(o) && PyList_GET_SIZE(o) == 2)) {
2259 o1 = PySequence_Fast_GET_ITEM(o, 0);
2260 o2 = PySequence_Fast_GET_ITEM(o, 1);
2261 if (!wxPoint2DFromObjects(o1, o2, &temp[idx])) {
2262 goto error2;
2263 }
2264 }
2265 else if (wxPySwigInstance_Check(o)) {
2266 wxPoint2D* pt;
2267 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPoint2D"))) {
2268 goto error2;
2269 }
2270 temp[idx] = *pt;
2271 }
2272 else if (PySequence_Check(o) && PySequence_Length(o) == 2) {
2273 o1 = PySequence_GetItem(o, 0);
2274 o2 = PySequence_GetItem(o, 1);
2275 if (!wxPoint2DFromObjects(o1, o2, &temp[idx])) {
2276 goto error3;
2277 }
2278 Py_DECREF(o1);
2279 Py_DECREF(o2);
2280 }
2281 else {
2282 goto error2;
2283 }
2284 // Clean up.
2285 if (!isFast)
2286 Py_DECREF(o);
2287 }
2288 return temp;
2289
2290error3:
2291 Py_DECREF(o1);
2292 Py_DECREF(o2);
2293error2:
2294 if (!isFast)
2295 Py_DECREF(o);
2296error1:
2297 delete [] temp;
2298error0:
2299 PyErr_SetString(PyExc_TypeError, "Expected a sequence of length-2 sequences or wxPoint2Ds.");
2300 return NULL;
2301}
2302
2303//---------------------------------------------------------------------------
7bf85405
RD
2304
2305
2f90df85 2306wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
7bf85405
RD
2307 if (!PyList_Check(source)) {
2308 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2309 return NULL;
2310 }
2311 int count = PyList_Size(source);
2312 wxBitmap** temp = new wxBitmap*[count];
2313 if (! temp) {
2314 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2315 return NULL;
2316 }
2317 for (int x=0; x<count; x++) {
2318 PyObject* o = PyList_GetItem(source, x);
d14a1e28 2319 if (wxPySwigInstance_Check(o)) {
7bf85405 2320 wxBitmap* pt;
d14a1e28
RD
2321 if (! wxPyConvertSwigPtr(o, (void **) &pt, wxT("wxBitmap"))) {
2322 PyErr_SetString(PyExc_TypeError,"Expected wxBitmap.");
7bf85405
RD
2323 return NULL;
2324 }
2325 temp[x] = pt;
2326 }
2327 else {
2328 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
2329 return NULL;
2330 }
2331 }
2332 return temp;
2333}
2334
2335
2336
2f90df85 2337wxString* wxString_LIST_helper(PyObject* source) {
7bf85405
RD
2338 if (!PyList_Check(source)) {
2339 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2340 return NULL;
2341 }
2342 int count = PyList_Size(source);
2343 wxString* temp = new wxString[count];
2344 if (! temp) {
2345 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2346 return NULL;
2347 }
2348 for (int x=0; x<count; x++) {
2349 PyObject* o = PyList_GetItem(source, x);
ecc08ead
RD
2350#if PYTHON_API_VERSION >= 1009
2351 if (! PyString_Check(o) && ! PyUnicode_Check(o)) {
2352 PyErr_SetString(PyExc_TypeError, "Expected a list of string or unicode objects.");
2353 return NULL;
2354 }
ecc08ead 2355#else
7bf85405
RD
2356 if (! PyString_Check(o)) {
2357 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
2358 return NULL;
2359 }
ecc08ead 2360#endif
a541c325
RD
2361
2362 wxString* pStr = wxString_in_helper(o);
2363 temp[x] = *pStr;
2364 delete pStr;
7bf85405
RD
2365 }
2366 return temp;
2367}
2368
2369
2f90df85 2370wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
7bf85405
RD
2371 if (!PyList_Check(source)) {
2372 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2373 return NULL;
2374 }
2375 int count = PyList_Size(source);
2376 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
2377 if (! temp) {
2378 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2379 return NULL;
2380 }
2381 for (int x=0; x<count; x++) {
2382 PyObject* o = PyList_GetItem(source, x);
d14a1e28 2383 if (wxPySwigInstance_Check(o)) {
7bf85405 2384 wxAcceleratorEntry* ae;
d14a1e28
RD
2385 if (! wxPyConvertSwigPtr(o, (void **) &ae, wxT("wxAcceleratorEntry"))) {
2386 PyErr_SetString(PyExc_TypeError,"Expected wxAcceleratorEntry.");
7bf85405
RD
2387 return NULL;
2388 }
2389 temp[x] = *ae;
2390 }
2391 else if (PyTuple_Check(o)) {
2392 PyObject* o1 = PyTuple_GetItem(o, 0);
2393 PyObject* o2 = PyTuple_GetItem(o, 1);
2394 PyObject* o3 = PyTuple_GetItem(o, 2);
0adbc166 2395 temp[x].Set(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
7bf85405
RD
2396 }
2397 else {
2398 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2399 return NULL;
2400 }
2401 }
2402 return temp;
2403}
2404
bb0054cd 2405
9d37f964
RD
2406wxPen** wxPen_LIST_helper(PyObject* source) {
2407 if (!PyList_Check(source)) {
2408 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
2409 return NULL;
2410 }
2411 int count = PyList_Size(source);
2412 wxPen** temp = new wxPen*[count];
2413 if (!temp) {
2414 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
2415 return NULL;
2416 }
2417 for (int x=0; x<count; x++) {
2418 PyObject* o = PyList_GetItem(source, x);
d14a1e28 2419 if (wxPySwigInstance_Check(o)) {
9d37f964 2420 wxPen* pt;
d14a1e28 2421 if (! wxPyConvertSwigPtr(o, (void **)&pt, wxT("wxPen"))) {
9d37f964 2422 delete temp;
d14a1e28 2423 PyErr_SetString(PyExc_TypeError,"Expected wxPen.");
9d37f964
RD
2424 return NULL;
2425 }
2426 temp[x] = pt;
2427 }
2428 else {
2429 delete temp;
2430 PyErr_SetString(PyExc_TypeError, "Expected a list of wxPens.");
2431 return NULL;
2432 }
2433 }
2434 return temp;
2435}
2436
2437
1e4a197e 2438bool wxPy2int_seq_helper(PyObject* source, int* i1, int* i2) {
9d37f964
RD
2439 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2440 PyObject *o1, *o2;
2441
2442 if (!PySequence_Check(source) || PySequence_Length(source) != 2)
4519a2d9 2443 return false;
9d37f964
RD
2444
2445 if (isFast) {
2446 o1 = PySequence_Fast_GET_ITEM(source, 0);
2447 o2 = PySequence_Fast_GET_ITEM(source, 1);
2448 }
2449 else {
2450 o1 = PySequence_GetItem(source, 0);
2451 o2 = PySequence_GetItem(source, 1);
2452 }
2453
2454 *i1 = PyInt_AsLong(o1);
2455 *i2 = PyInt_AsLong(o2);
2456
2457 if (! isFast) {
2458 Py_DECREF(o1);
2459 Py_DECREF(o2);
2460 }
4519a2d9 2461 return true;
9d37f964
RD
2462}
2463
2464
1e4a197e 2465bool wxPy4int_seq_helper(PyObject* source, int* i1, int* i2, int* i3, int* i4) {
9d37f964
RD
2466 bool isFast = PyList_Check(source) || PyTuple_Check(source);
2467 PyObject *o1, *o2, *o3, *o4;
2468
2469 if (!PySequence_Check(source) || PySequence_Length(source) != 4)
4519a2d9 2470 return false;
9d37f964
RD
2471
2472 if (isFast) {
2473 o1 = PySequence_Fast_GET_ITEM(source, 0);
2474 o2 = PySequence_Fast_GET_ITEM(source, 1);
2475 o3 = PySequence_Fast_GET_ITEM(source, 2);
2476 o4 = PySequence_Fast_GET_ITEM(source, 3);
2477 }
2478 else {
2479 o1 = PySequence_GetItem(source, 0);
2480 o2 = PySequence_GetItem(source, 1);
2481 o3 = PySequence_GetItem(source, 2);
2482 o4 = PySequence_GetItem(source, 3);
2483 }
2484
2485 *i1 = PyInt_AsLong(o1);
2486 *i2 = PyInt_AsLong(o2);
2487 *i3 = PyInt_AsLong(o3);
2488 *i4 = PyInt_AsLong(o4);
2489
2490 if (! isFast) {
2491 Py_DECREF(o1);
2492 Py_DECREF(o2);
2493 Py_DECREF(o3);
2494 Py_DECREF(o4);
2495 }
4519a2d9 2496 return true;
9d37f964
RD
2497}
2498
bb0054cd
RD
2499
2500//----------------------------------------------------------------------
bb0054cd 2501
d14a1e28
RD
2502bool wxPySimple_typecheck(PyObject* source, const wxChar* classname, int seqLen)
2503{
2504 void* ptr;
26eac43e 2505
d14a1e28
RD
2506 if (wxPySwigInstance_Check(source) &&
2507 wxPyConvertSwigPtr(source, (void **)&ptr, classname))
4519a2d9 2508 return true;
2f90df85 2509
d14a1e28
RD
2510 PyErr_Clear();
2511 if (PySequence_Check(source) && PySequence_Length(source) == seqLen)
4519a2d9 2512 return true;
26eac43e 2513
4519a2d9 2514 return false;
26eac43e 2515}
2f90df85 2516
d14a1e28
RD
2517bool wxSize_helper(PyObject* source, wxSize** obj)
2518{
22faec7d
RD
2519 if (source == Py_None) {
2520 **obj = wxSize(-1,-1);
4519a2d9 2521 return true;
22faec7d 2522 }
d14a1e28 2523 return wxPyTwoIntItem_helper(source, obj, wxT("wxSize"));
2f90df85
RD
2524}
2525
1e4a197e 2526
d14a1e28
RD
2527bool wxPoint_helper(PyObject* source, wxPoint** obj)
2528{
22faec7d
RD
2529 if (source == Py_None) {
2530 **obj = wxPoint(-1,-1);
4519a2d9 2531 return true;
22faec7d 2532 }
d14a1e28 2533 return wxPyTwoIntItem_helper(source, obj, wxT("wxPoint"));
2f90df85
RD
2534}
2535
2536
2537
91d6301a
RD
2538bool wxPosition_helper(PyObject* source, wxPosition** obj)
2539{
2540 if (source == Py_None) {
2541 **obj = wxPosition(-1,-1);
2542 return true;
2543 }
2544 return wxPyTwoIntItem_helper(source, obj, wxT("wxPosition"));
2545}
2546
2547
2548
2f90df85
RD
2549bool wxRealPoint_helper(PyObject* source, wxRealPoint** obj) {
2550
22faec7d
RD
2551 if (source == Py_None) {
2552 **obj = wxRealPoint(-1,-1);
4519a2d9 2553 return true;
22faec7d 2554 }
26eac43e 2555
2f90df85 2556 // If source is an object instance then it may already be the right type
d14a1e28 2557 if (wxPySwigInstance_Check(source)) {
2f90df85 2558 wxRealPoint* ptr;
d14a1e28 2559 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRealPoint")))
2f90df85
RD
2560 goto error;
2561 *obj = ptr;
4519a2d9 2562 return true;
2f90df85
RD
2563 }
2564 // otherwise a 2-tuple of floats is expected
2565 else if (PySequence_Check(source) && PyObject_Length(source) == 2) {
2566 PyObject* o1 = PySequence_GetItem(source, 0);
2567 PyObject* o2 = PySequence_GetItem(source, 1);
db0ff83e
RD
2568 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2569 Py_DECREF(o1);
2570 Py_DECREF(o2);
2571 goto error;
2572 }
2f90df85 2573 **obj = wxRealPoint(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
db0ff83e
RD
2574 Py_DECREF(o1);
2575 Py_DECREF(o2);
4519a2d9 2576 return true;
2f90df85
RD
2577 }
2578
2579 error:
2580 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wxRealPoint object.");
4519a2d9 2581 return false;
2f90df85
RD
2582}
2583
2584
2585
2f90df85
RD
2586bool wxRect_helper(PyObject* source, wxRect** obj) {
2587
22faec7d
RD
2588 if (source == Py_None) {
2589 **obj = wxRect(-1,-1,-1,-1);
4519a2d9 2590 return true;
22faec7d
RD
2591 }
2592
2f90df85 2593 // If source is an object instance then it may already be the right type
d14a1e28 2594 if (wxPySwigInstance_Check(source)) {
2f90df85 2595 wxRect* ptr;
d14a1e28 2596 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRect")))
2f90df85
RD
2597 goto error;
2598 *obj = ptr;
4519a2d9 2599 return true;
2f90df85
RD
2600 }
2601 // otherwise a 4-tuple of integers is expected
2602 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2603 PyObject* o1 = PySequence_GetItem(source, 0);
2604 PyObject* o2 = PySequence_GetItem(source, 1);
2605 PyObject* o3 = PySequence_GetItem(source, 2);
2606 PyObject* o4 = PySequence_GetItem(source, 3);
db0ff83e
RD
2607 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2608 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2609 Py_DECREF(o1);
2610 Py_DECREF(o2);
2611 Py_DECREF(o3);
2612 Py_DECREF(o4);
2613 goto error;
2614 }
2f90df85 2615 **obj = wxRect(PyInt_AsLong(o1), PyInt_AsLong(o2),
db0ff83e
RD
2616 PyInt_AsLong(o3), PyInt_AsLong(o4));
2617 Py_DECREF(o1);
2618 Py_DECREF(o2);
2619 Py_DECREF(o3);
2620 Py_DECREF(o4);
4519a2d9 2621 return true;
2f90df85
RD
2622 }
2623
2624 error:
2625 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of integers or a wxRect object.");
4519a2d9 2626 return false;
2f90df85
RD
2627}
2628
2629
2630
f6bcfd97
BP
2631bool wxColour_helper(PyObject* source, wxColour** obj) {
2632
22faec7d
RD
2633 if (source == Py_None) {
2634 **obj = wxNullColour;
4519a2d9 2635 return true;
22faec7d
RD
2636 }
2637
f6bcfd97 2638 // If source is an object instance then it may already be the right type
d14a1e28 2639 if (wxPySwigInstance_Check(source)) {
f6bcfd97 2640 wxColour* ptr;
d14a1e28 2641 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxColour")))
f6bcfd97
BP
2642 goto error;
2643 *obj = ptr;
4519a2d9 2644 return true;
f6bcfd97 2645 }
1e4a197e
RD
2646 // otherwise check for a string
2647 else if (PyString_Check(source) || PyUnicode_Check(source)) {
2648 wxString spec = Py2wxString(source);
a541c325
RD
2649 if (spec.GetChar(0) == '#' && spec.Length() == 7) { // It's #RRGGBB
2650 long red, green, blue;
2651 red = green = blue = 0;
a541c325
RD
2652 spec.Mid(1,2).ToLong(&red, 16);
2653 spec.Mid(3,2).ToLong(&green, 16);
2654 spec.Mid(5,2).ToLong(&blue, 16);
2655
f6bcfd97 2656 **obj = wxColour(red, green, blue);
4519a2d9 2657 return true;
f6bcfd97
BP
2658 }
2659 else { // it's a colour name
2660 **obj = wxColour(spec);
4519a2d9 2661 return true;
f6bcfd97
BP
2662 }
2663 }
28cc717d 2664 // last chance: 3-tuple or 4-tuple of integers is expected
1e4a197e
RD
2665 else if (PySequence_Check(source) && PyObject_Length(source) == 3) {
2666 PyObject* o1 = PySequence_GetItem(source, 0);
2667 PyObject* o2 = PySequence_GetItem(source, 1);
2668 PyObject* o3 = PySequence_GetItem(source, 2);
2669 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3)) {
2670 Py_DECREF(o1);
2671 Py_DECREF(o2);
2672 Py_DECREF(o3);
2673 goto error;
2674 }
2675 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3));
2676 Py_DECREF(o1);
2677 Py_DECREF(o2);
2678 Py_DECREF(o3);
4519a2d9 2679 return true;
1e4a197e 2680 }
28cc717d
RD
2681 else if (PySequence_Check(source) && PyObject_Length(source) == 4) {
2682 PyObject* o1 = PySequence_GetItem(source, 0);
2683 PyObject* o2 = PySequence_GetItem(source, 1);
2684 PyObject* o3 = PySequence_GetItem(source, 2);
2685 PyObject* o4 = PySequence_GetItem(source, 3);
2686 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) || !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2687 Py_DECREF(o1);
2688 Py_DECREF(o2);
2689 Py_DECREF(o3);
2690 Py_DECREF(o4);
2691 goto error;
2692 }
2693 **obj = wxColour(PyInt_AsLong(o1), PyInt_AsLong(o2), PyInt_AsLong(o3), PyInt_AsLong(o4));
2694 Py_DECREF(o1);
2695 Py_DECREF(o2);
2696 Py_DECREF(o3);
2697 Py_DECREF(o4);
2698 return true;
2699 }
f6bcfd97
BP
2700
2701 error:
a541c325 2702 PyErr_SetString(PyExc_TypeError,
28cc717d 2703 "Expected a wxColour object, a string containing a colour name or '#RRGGBB', or a 3- or 4-tuple of integers.");
4519a2d9 2704 return false;
1e4a197e
RD
2705}
2706
2707
d14a1e28
RD
2708bool wxColour_typecheck(PyObject* source) {
2709
2710 if (wxPySimple_typecheck(source, wxT("wxColour"), 3))
4519a2d9 2711 return true;
d14a1e28
RD
2712
2713 if (PyString_Check(source) || PyUnicode_Check(source))
4519a2d9 2714 return true;
26eac43e 2715
4519a2d9 2716 return false;
d14a1e28
RD
2717}
2718
2719
1e4a197e 2720
d14a1e28 2721bool wxPoint2D_helper(PyObject* source, wxPoint2D** obj) {
22faec7d
RD
2722
2723 if (source == Py_None) {
2724 **obj = wxPoint2D(-1,-1);
4519a2d9 2725 return true;
22faec7d 2726 }
26eac43e 2727
1e4a197e 2728 // If source is an object instance then it may already be the right type
d14a1e28
RD
2729 if (wxPySwigInstance_Check(source)) {
2730 wxPoint2D* ptr;
2731 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxPoint2D")))
1e4a197e
RD
2732 goto error;
2733 *obj = ptr;
4519a2d9 2734 return true;
1e4a197e
RD
2735 }
2736 // otherwise a length-2 sequence of floats is expected
2737 if (PySequence_Check(source) && PySequence_Length(source) == 2) {
2738 PyObject* o1 = PySequence_GetItem(source, 0);
2739 PyObject* o2 = PySequence_GetItem(source, 1);
d14a1e28 2740 // This should really check for floats, not numbers -- but that would break code.
1e4a197e
RD
2741 if (!PyNumber_Check(o1) || !PyNumber_Check(o2)) {
2742 Py_DECREF(o1);
2743 Py_DECREF(o2);
2744 goto error;
2745 }
d14a1e28 2746 **obj = wxPoint2D(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2));
1e4a197e
RD
2747 Py_DECREF(o1);
2748 Py_DECREF(o2);
4519a2d9 2749 return true;
1e4a197e
RD
2750 }
2751 error:
debe38c9
RD
2752 PyErr_SetString(PyExc_TypeError, "Expected a 2-tuple of floats or a wx.Point2D object.");
2753 return false;
2754}
2755
2756
2757
2758bool wxRect2D_helper(PyObject* source, wxRect2D** obj) {
2759
2760 if (source == Py_None) {
2761 **obj = wxRect2D(-1,-1,-1,-1);
2762 return true;
2763 }
2764
2765 // If source is an object instance then it may already be the right type
2766 if (wxPySwigInstance_Check(source)) {
2767 wxRect2D* ptr;
2768 if (! wxPyConvertSwigPtr(source, (void **)&ptr, wxT("wxRect2D")))
2769 goto error;
2770 *obj = ptr;
2771 return true;
2772 }
2773 // otherwise a length-4 sequence of floats is expected
2774 if (PySequence_Check(source) && PySequence_Length(source) == 4) {
2775 PyObject* o1 = PySequence_GetItem(source, 0);
2776 PyObject* o2 = PySequence_GetItem(source, 1);
2777 PyObject* o3 = PySequence_GetItem(source, 2);
2778 PyObject* o4 = PySequence_GetItem(source, 3);
2779 // This should really check for floats, not numbers -- but that would break code.
2780 if (!PyNumber_Check(o1) || !PyNumber_Check(o2) ||
2781 !PyNumber_Check(o3) || !PyNumber_Check(o4)) {
2782 Py_DECREF(o1);
2783 Py_DECREF(o2);
2784 Py_DECREF(o3);
2785 Py_DECREF(o4);
2786 goto error;
2787 }
2788 **obj = wxRect2D(PyFloat_AsDouble(o1), PyFloat_AsDouble(o2),
2789 PyFloat_AsDouble(o3), PyFloat_AsDouble(o4));
2790 Py_DECREF(o1);
2791 Py_DECREF(o2);
2792 Py_DECREF(o3);
2793 Py_DECREF(o4);
2794 return true;
2795 }
2796 error:
2797 PyErr_SetString(PyExc_TypeError, "Expected a 4-tuple of floats or a wx.Rect2D object.");
4519a2d9 2798 return false;
f6bcfd97
BP
2799}
2800
2801
bb0054cd 2802//----------------------------------------------------------------------
b37c7e1d 2803
281c54cc
RD
2804PyObject* wxArrayString2PyList_helper(const wxArrayString& arr)
2805{
b37c7e1d
RD
2806 PyObject* list = PyList_New(0);
2807 for (size_t i=0; i < arr.GetCount(); i++) {
c8bc7bb8 2808#if wxUSE_UNICODE
1e4a197e 2809 PyObject* str = PyUnicode_FromWideChar(arr[i].c_str(), arr[i].Len());
c8bc7bb8
RD
2810#else
2811 PyObject* str = PyString_FromStringAndSize(arr[i].c_str(), arr[i].Len());
2812#endif
b37c7e1d 2813 PyList_Append(list, str);
8af26133 2814 Py_DECREF(str);
b37c7e1d
RD
2815 }
2816 return list;
2817}
2818
2819
281c54cc
RD
2820PyObject* wxArrayInt2PyList_helper(const wxArrayInt& arr)
2821{
293a0a86
RD
2822 PyObject* list = PyList_New(0);
2823 for (size_t i=0; i < arr.GetCount(); i++) {
2824 PyObject* number = PyInt_FromLong(arr[i]);
2825 PyList_Append(list, number);
2826 Py_DECREF(number);
2827 }
2828 return list;
2829}
2830
2831
281c54cc
RD
2832PyObject* wxArrayDouble2PyList_helper(const wxArrayDouble& arr)
2833{
2834 PyObject* list = PyList_New(0);
2835 for (size_t i=0; i < arr.GetCount(); i++) {
2836 PyObject* number = PyFloat_FromDouble(arr[i]);
2837 PyList_Append(list, number);
2838 Py_DECREF(number);
2839 }
2840 return list;
2841}
2842
2843
02b800ce
RD
2844//----------------------------------------------------------------------
2845// wxPyImageHandler methods
2846//
2847// TODO: Switch these to use wxPython's standard macros and helper classes
2848// for calling callbacks.
2849
2850PyObject* wxPyImageHandler::m_DoCanRead_Name = NULL;
2851PyObject* wxPyImageHandler::m_GetImageCount_Name = NULL;
2852PyObject* wxPyImageHandler::m_LoadFile_Name = NULL;
2853PyObject* wxPyImageHandler::m_SaveFile_Name = NULL;
2854
2855PyObject* wxPyImageHandler::py_InputStream(wxInputStream* stream) {
2856 return wxPyConstructObject(new wxPyInputStream(stream),
2857 wxT("wxPyInputStream"), 0);
2858}
2859
2860PyObject* wxPyImageHandler::py_Image(wxImage* image) {
2861 return wxPyConstructObject(image, wxT("wxImage"), 0);
2862}
2863
2864PyObject* wxPyImageHandler::py_OutputStream(wxOutputStream* stream) {
2865 return wxPyConstructObject(stream, wxT("wxOutputStream"), 0);
2866}
2867
2868wxPyImageHandler::wxPyImageHandler():
2869 m_self(NULL)
2870{
2871 if (!m_DoCanRead_Name) {
2872 m_DoCanRead_Name = PyString_FromString("DoCanRead");
2873 m_GetImageCount_Name = PyString_FromString("GetImageCount");
2874 m_LoadFile_Name = PyString_FromString("LoadFile");
2875 m_SaveFile_Name = PyString_FromString("SaveFile");
2876 }
2877}
2878
2879wxPyImageHandler::~wxPyImageHandler() {
2880 if (m_self) {
2881 Py_DECREF(m_self);
2882 m_self = NULL;
2883 }
2884}
2885
2886void wxPyImageHandler::_SetSelf(PyObject *self) {
2887 // should check here for isinstance(PyImageHandler) ??
2888 m_self = self;
2889 Py_INCREF(m_self);
2890}
2891
2892bool wxPyImageHandler::DoCanRead(wxInputStream& stream) {
2893 // check if our object has this method
2894 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2895 if (!m_self || !PyObject_HasAttr(m_self, m_DoCanRead_Name)) {
2896 wxPyEndBlockThreads(blocked);
2897 return false;
2898 }
2899
2900 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_DoCanRead_Name,
2901 py_InputStream(&stream), NULL);
2902 bool retval = false;
2903 if (res) {
2904 retval = PyInt_AsLong(res);
2905 Py_DECREF(res);
2906 PyErr_Clear();
2907 }
2908 else
2909 PyErr_Print();
2910 wxPyEndBlockThreads(blocked);
2911 return retval;
2912}
2913
2914bool wxPyImageHandler::LoadFile( wxImage* image, wxInputStream& stream,
2915 bool verbose, int index ) {
2916 // check if our object has this method
2917 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2918 if (!m_self || !PyObject_HasAttr(m_self, m_LoadFile_Name)) {
2919 wxPyEndBlockThreads(blocked);
2920 return false;
2921 }
2922 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_LoadFile_Name,
2923 py_Image(image),
2924 py_InputStream(&stream),
2925 PyInt_FromLong(verbose),
2926 PyInt_FromLong(index),
2927 NULL);
2928 bool retval = false;
2929 if (res) {
2930 retval = PyInt_AsLong(res);
2931 Py_DECREF(res);
2932 PyErr_Clear();
2933 } else
2934 PyErr_Print();
2935 wxPyEndBlockThreads(blocked);
2936 return retval;
2937}
2938
2939bool wxPyImageHandler::SaveFile( wxImage* image, wxOutputStream& stream,
2940 bool verbose ) {
2941 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2942 if (!m_self || !PyObject_HasAttr(m_self, m_SaveFile_Name)) {
2943 wxPyEndBlockThreads(blocked);
2944 return false;
2945 }
2946 PyObject* res = PyObject_CallMethodObjArgs(m_self, m_SaveFile_Name,
2947 py_Image(image),
2948 py_OutputStream(&stream),
2949 PyInt_FromLong(verbose),
2950 NULL);
2951 bool retval = false;
2952 if(res) {
2953 retval=PyInt_AsLong(res);
2954 Py_DECREF(res);
2955 PyErr_Clear();
2956 } else
2957 PyErr_Print();
2958 wxPyEndBlockThreads(blocked);
2959 return retval;
2960}
2961
2962int wxPyImageHandler::GetImageCount( wxInputStream& stream ) {
2963 wxPyBlock_t blocked = wxPyBeginBlockThreads();
2964 if (!m_self || !PyObject_HasAttr(m_self, m_GetImageCount_Name)) {
2965 wxPyEndBlockThreads(blocked);
2966 return 1;
2967 }
2968 PyObject *res=PyObject_CallMethodObjArgs(m_self, m_GetImageCount_Name,
2969 py_InputStream(&stream),
2970 NULL);
2971 int retval = 1;
2972 if(res) {
2973 retval=PyInt_AsLong(res);
2974 Py_DECREF(res);
2975 PyErr_Clear();
2976 } else
2977 PyErr_Print();
2978 wxPyEndBlockThreads(blocked);
2979 return retval;
2980}
2981
2982
4d9de110
RD
2983//----------------------------------------------------------------------
2984// Function to test if the Display (or whatever is the platform equivallent)
2985// can be connected to. This is accessable from wxPython as a staticmethod of
2986// wx.App called DisplayAvailable().
2987
2988
2989bool wxPyTestDisplayAvailable()
2990{
2991#ifdef __WXGTK__
2992 Display* display;
2993 display = XOpenDisplay(NULL);
2994 if (display == NULL)
2995 return false;
2996 XCloseDisplay(display);
2997 return true;
2998#endif
2999
3000#ifdef __WXMAC__
3001 // This is adapted from Python's Mac/Modules/MacOS.c in the
3002 // MacOS_WMAvailable function.
3003 bool rv;
3004 ProcessSerialNumber psn;
3005
3006 /*
3007 ** This is a fairly innocuous call to make if we don't have a window
3008 ** manager, or if we have no permission to talk to it. It will print
3009 ** a message on stderr, but at least it won't abort the process.
3010 ** It appears the function caches the result itself, and it's cheap, so
3011 ** no need for us to cache.
3012 */
3013#ifdef kCGNullDirectDisplay
3014 /* On 10.1 CGMainDisplayID() isn't available, and
3015 ** kCGNullDirectDisplay isn't defined.
3016 */
3017 if (CGMainDisplayID() == 0) {
3018 rv = false;
3019 } else
3020#endif
3021 {
3022 // Also foreground the application on the first call as a side-effect.
3023 if (GetCurrentProcess(&psn) < 0 || SetFrontProcess(&psn) < 0) {
3024 rv = false;
3025 } else {
3026 rv = true;
3027 }
3028 }
3029 return rv;
3030#endif
3031
3032#ifdef __WXMSW__
3033 // TODO...
3034 return true;
3035#endif
3036}
3037
3038
bb0054cd 3039//----------------------------------------------------------------------
7bf85405 3040//----------------------------------------------------------------------
7bf85405 3041
7bf85405 3042
7bf85405 3043
de20db99 3044