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