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