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