1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Helper functions/classes for the wxPython extension module
7 // Created: 1-July-1997
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
16 #include "wx/wxPython/wxPython_int.h"
17 #include "wx/wxPython/pyistream.h"
20 #include <wx/msw/private.h>
21 #include <wx/msw/winundef.h>
22 #include <wx/msw/msvcrt.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)
38 #include "wx/x11/privx.h"
39 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
43 #include <wx/mac/private.h>
46 #include <wx/clipbrd.h>
47 #include <wx/mimetype.h>
50 //----------------------------------------------------------------------
52 #if PYTHON_API_VERSION < 1009 && wxUSE_UNICODE
53 #error Python must support Unicode to use wxWindows Unicode
56 //----------------------------------------------------------------------
58 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
59 bool wxPyDoCleanup
= false;
60 bool wxPyDoingCleanup
= false;
63 #ifdef WXP_WITH_THREAD
64 #if !wxPyUSE_GIL_STATE
65 struct wxPyThreadState
{
67 PyThreadState
* tstate
;
69 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
70 : tid(_tid
), tstate(_tstate
) {}
73 #include <wx/dynarray.h>
74 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
75 #include <wx/arrimpl.cpp>
76 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
78 wxPyThreadStateArray
* wxPyTStates
= NULL
;
79 wxMutex
* wxPyTMutex
= NULL
;
85 #define DEFAULTENCODING_SIZE 64
86 static char wxPyDefaultEncoding
[DEFAULTENCODING_SIZE
] = "ascii";
88 static PyObject
* wxPython_dict
= NULL
;
89 static PyObject
* wxPyAssertionError
= NULL
;
90 static PyObject
* wxPyNoAppError
= NULL
;
92 PyObject
* wxPyPtrTypeMap
= NULL
;
95 #ifdef __WXMSW__ // If building for win32...
96 //----------------------------------------------------------------------
97 // This gets run when the DLL is loaded. We just need to save a handle.
98 //----------------------------------------------------------------------
102 HINSTANCE hinstDLL
, // handle to DLL module
103 DWORD fdwReason
, // reason for calling function
104 LPVOID lpvReserved
// reserved
107 // If wxPython is embedded in another wxWidgets app then
108 // the instance has already been set.
109 if (! wxGetInstance())
110 wxSetInstance(hinstDLL
);
115 //----------------------------------------------------------------------
116 // Classes for implementing the wxp main application shell.
117 //----------------------------------------------------------------------
119 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
123 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
124 m_startupComplete
= false;
128 wxPyApp::~wxPyApp() {
130 wxApp::SetInstance(NULL
);
134 // This one isn't acutally called... We fake it with _BootstrapApp
135 bool wxPyApp::OnInit() {
140 int wxPyApp::MainLoop() {
143 DeletePendingObjects();
144 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
146 if ( m_exitOnFrameDelete
== Later
) {
147 m_exitOnFrameDelete
= Yes
;
150 retval
= wxApp::MainLoop();
157 bool wxPyApp::OnInitGui() {
159 wxApp::OnInitGui(); // in this case always call the base class version
160 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
161 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
162 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
163 wxPyEndBlockThreads(blocked
);
168 int wxPyApp::OnExit() {
170 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
171 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
172 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
173 wxPyEndBlockThreads(blocked
);
174 wxApp::OnExit(); // in this case always call the base class version
180 void wxPyApp::OnAssert(const wxChar
*file
,
185 // if we're not fully initialized then just log the error
186 if (! m_startupComplete
) {
189 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
199 // If the OnAssert is overloaded in the Python class then call it...
201 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
202 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
203 PyObject
* fso
= wx2PyString(file
);
204 PyObject
* cso
= wx2PyString(file
);
207 mso
= wx2PyString(file
);
209 mso
= Py_None
; Py_INCREF(Py_None
);
211 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
216 wxPyEndBlockThreads(blocked
);
218 // ...otherwise do our own thing with it
221 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
224 // turn it into a Python exception?
225 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
228 buf
.Printf(wxT("C++ assertion \"%s\" failed in %s(%d)"), cond
, file
, line
);
235 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
236 PyObject
* s
= wx2PyString(buf
);
237 PyErr_SetObject(wxPyAssertionError
, s
);
239 wxPyEndBlockThreads(blocked
);
241 // Now when control returns to whatever API wrapper was called from
242 // Python it should detect that an exception is set and will return
243 // NULL, signalling the exception to Python.
246 // Send it to the normal log destination, but only if
247 // not _DIALOG because it will call this too
248 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
251 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
260 // do the normal wx assert dialog?
261 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
262 wxApp::OnAssert(file
, line
, cond
, msg
);
267 // For catching Apple Events
268 void wxPyApp::MacOpenFile(const wxString
&fileName
)
270 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
271 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
272 PyObject
* s
= wx2PyString(fileName
);
273 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
276 wxPyEndBlockThreads(blocked
);
279 void wxPyApp::MacPrintFile(const wxString
&fileName
)
281 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
282 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
283 PyObject
* s
= wx2PyString(fileName
);
284 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
287 wxPyEndBlockThreads(blocked
);
290 void wxPyApp::MacNewFile()
292 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
293 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
294 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
295 wxPyEndBlockThreads(blocked
);
298 void wxPyApp::MacReopenApp()
300 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
301 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
302 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
303 wxPyEndBlockThreads(blocked
);
308 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
310 return s_macSupportPCMenuShortcuts
;
317 long wxPyApp::GetMacAboutMenuItemId() {
319 return s_macAboutMenuItemId
;
326 long wxPyApp::GetMacPreferencesMenuItemId() {
328 return s_macPreferencesMenuItemId
;
335 long wxPyApp::GetMacExitMenuItemId() {
337 return s_macExitMenuItemId
;
344 wxString
wxPyApp::GetMacHelpMenuTitleName() {
346 return s_macHelpMenuTitleName
;
348 return wxEmptyString
;
353 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
355 s_macSupportPCMenuShortcuts
= val
;
360 void wxPyApp::SetMacAboutMenuItemId(long val
) {
362 s_macAboutMenuItemId
= val
;
367 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
369 s_macPreferencesMenuItemId
= val
;
374 void wxPyApp::SetMacExitMenuItemId(long val
) {
376 s_macExitMenuItemId
= val
;
381 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
383 s_macHelpMenuTitleName
= val
;
388 // This finishes the initialization of wxWindows and then calls the OnInit
389 // that should be present in the derived (Python) class.
390 void wxPyApp::_BootstrapApp()
392 static bool haveInitialized
= false;
395 PyObject
* retval
= NULL
;
396 PyObject
* pyint
= NULL
;
399 // Only initialize wxWidgets once
400 if (! haveInitialized
) {
402 // Get any command-line args passed to this program from the sys module
405 blocked
= wxPyBeginBlockThreads();
407 PyObject
* sysargv
= PySys_GetObject("argv");
408 PyObject
* executable
= PySys_GetObject("executable");
410 if (sysargv
!= NULL
&& executable
!= NULL
) {
411 argc
= PyList_Size(sysargv
) + 1;
412 argv
= new char*[argc
+1];
413 argv
[0] = strdup(PyString_AsString(executable
));
415 for(x
=1; x
<argc
; x
++) {
416 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
417 argv
[x
] = strdup(PyString_AsString(pyArg
));
421 wxPyEndBlockThreads(blocked
);
423 // Initialize wxWidgets
424 result
= wxEntryStart(argc
, argv
);
425 // wxApp takes ownership of the argv array, don't delete it here
427 blocked
= wxPyBeginBlockThreads();
429 PyErr_SetString(PyExc_SystemError
,
430 "wxEntryStart failed, unable to initialize wxWidgets!"
432 " (Is DISPLAY set properly?)"
438 // On wxGTK the locale will be changed to match the system settings,
439 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
440 // for the floating point conversions and such to work right.
441 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
442 setlocale(LC_NUMERIC
, "C");
445 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
447 // The stock objects were all NULL when they were loaded into
448 // SWIG generated proxies, so re-init those now...
449 wxPy_ReinitStockObjects(3);
451 wxPyEndBlockThreads(blocked
);
452 haveInitialized
= true;
460 // It's now ok to generate exceptions for assertion errors.
461 wxPythonApp
->SetStartupComplete(true);
463 // Call the Python wxApp's OnInit function
464 blocked
= wxPyBeginBlockThreads();
465 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
467 PyObject
* method
= m_myInst
.GetLastFound();
468 PyObject
* argTuple
= PyTuple_New(0);
469 retval
= PyEval_CallObject(method
, argTuple
);
475 pyint
= PyNumber_Int(retval
);
477 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
480 result
= PyInt_AS_LONG(pyint
);
483 // Is it okay if there is no OnInit? Probably so...
488 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
495 wxPyEndBlockThreads(blocked
);
498 //---------------------------------------------------------------------
499 //----------------------------------------------------------------------
503 static char* wxPyCopyCString(const wxChar
* src
)
505 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
506 size_t len
= strlen(buff
);
507 char* dest
= new char[len
+1];
513 static char* wxPyCopyCString(const char* src
) // we need a char version too
515 size_t len
= strlen(src
);
516 char* dest
= new char[len
+1];
522 static wxChar
* wxPyCopyWString(const char *src
)
524 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
525 wxString
str(src
, *wxConvCurrent
);
526 return copystring(str
);
530 static wxChar
* wxPyCopyWString(const wxChar
*src
)
532 return copystring(src
);
538 inline const char* dropwx(const char* name
) {
539 if (name
[0] == 'w' && name
[1] == 'x')
545 //----------------------------------------------------------------------
547 // This function is called when the wx._core_ module is imported to do some
548 // initial setup. (Before there is a wxApp object.) The rest happens in
549 // wxPyApp::_BootstrapApp
550 void __wxPyPreStart(PyObject
* moduleDict
)
554 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
555 // | _CRTDBG_CHECK_ALWAYS_DF
556 // | _CRTDBG_DELAY_FREE_MEM_DF
560 #ifdef WXP_WITH_THREAD
561 #if wxPyUSE_GIL_STATE
562 PyEval_InitThreads();
564 PyEval_InitThreads();
565 wxPyTStates
= new wxPyThreadStateArray
;
566 wxPyTMutex
= new wxMutex
;
568 // Save the current (main) thread state in our array
569 PyThreadState
* tstate
= wxPyBeginAllowThreads();
570 wxPyEndAllowThreads(tstate
);
574 // Ensure that the build options in the DLL (or whatever) match this build
575 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
577 // Init the stock objects to a non-NULL value so SWIG doesn't create them as None
578 wxPy_ReinitStockObjects(1);
580 wxInitAllImageHandlers();
585 void __wxPyCleanup() {
586 wxPyDoingCleanup
= true;
588 wxPyDoCleanup
= false;
591 #ifdef WXP_WITH_THREAD
592 #if !wxPyUSE_GIL_STATE
595 wxPyTStates
->Empty();
603 // Save a reference to the dictionary of the wx._core module, and inject
604 // a few more things into it.
605 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
608 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
611 if (!PyDict_Check(wxPython_dict
)) {
612 PyErr_SetString(PyExc_TypeError
,
613 "_wxPySetDictionary must have dictionary object!");
617 if (! wxPyPtrTypeMap
)
618 wxPyPtrTypeMap
= PyDict_New();
619 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
621 // Create an exception object to use for wxASSERTions
622 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
623 PyExc_AssertionError
, NULL
);
624 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
626 // Create an exception object to use when the app object hasn't been created yet
627 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
628 PyExc_RuntimeError
, NULL
);
629 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
634 #define wxPlatform "__WXMOTIF__"
635 #define wxPlatName "wxMotif"
638 #define wxPlatform "__WXX11__"
639 #define wxPlatName "wxX11"
642 #define wxPlatform "__WXGTK__"
643 #define wxPlatName "wxGTK"
646 #define wxPlatform "__WXMSW__"
647 #define wxPlatName "wxMSW"
650 #define wxPlatform "__WXMAC__"
651 #define wxPlatName "wxMac"
660 // These should be deprecated in favor of the PlatformInfo tuple built below...
661 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
662 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
663 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
665 // Make a tuple of strings that gives more info about the platform.
666 PyObject
* PlatInfo
= PyList_New(0);
669 #define _AddInfoString(st) \
670 obj = PyString_FromString(st); \
671 PyList_Append(PlatInfo, obj); \
674 _AddInfoString(wxPlatform
);
675 _AddInfoString(wxPlatName
);
677 _AddInfoString("unicode");
679 _AddInfoString("ansi");
683 _AddInfoString("gtk2");
685 _AddInfoString("gtk1");
689 _AddInfoString("wx-assertions-on");
691 _AddInfoString("wx-assertions-off");
694 #undef _AddInfoString
696 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
698 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
705 //---------------------------------------------------------------------------
707 // The stock objects are no longer created when the wx._core_ module is
708 // imported, but only after the app object has been created. The
709 // wxPy_ReinitStockObjects function will be called 3 times to pass the stock
710 // objects though various stages of evolution:
712 // pass 1: Set all the pointers to a non-NULL value so the Python proxy
713 // object will be created (otherwise SWIG will just use None.)
715 // pass 2: After the module has been imported and the python proxys have
716 // been created, then set the __class__ to be _wxPyUnbornObject so
717 // it will catch any access to the object and will raise an exception.
719 // pass 3: Finally, from BootstrapApp patch things up so the stock objects
723 PyObject
* __wxPyFixStockObjects(PyObject
* /* self */, PyObject
* args
)
725 wxPy_ReinitStockObjects(2);
730 static void rsoPass2(const char* name
)
732 static PyObject
* unbornObjectClass
= NULL
;
735 if (unbornObjectClass
== NULL
) {
736 unbornObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyUnbornObject");
737 Py_INCREF(unbornObjectClass
);
740 // Find the object instance
741 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
742 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
743 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
746 PyObject_SetAttrString(obj
, "__class__", unbornObjectClass
);
750 static void rsoPass3(const char* name
, const char* classname
, void* ptr
)
756 // Find the object instance
757 obj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(name
));
758 wxCHECK_RET(obj
!= NULL
, wxT("Unable to find stock object"));
759 wxCHECK_RET(wxPySwigInstance_Check(obj
), wxT("Not a swig instance"));
761 // Find the class object and put it back in the instance
762 classobj
= PyDict_GetItemString(wxPython_dict
, (char*)dropwx(classname
));
763 wxCHECK_RET(classobj
!= NULL
, wxT("Unable to find stock class object"));
764 PyObject_SetAttrString(obj
, "__class__", classobj
);
766 // Rebuild the .this swigified pointer with the new value of the C++ pointer
767 ptrobj
= wxPyMakeSwigPtr(ptr
, wxString(classname
, *wxConvCurrent
));
768 PyObject_SetAttrString(obj
, "this", ptrobj
);
774 void wxPy_ReinitStockObjects(int pass
)
777 // If there is already an App object then wxPython is probably embedded in
778 // a wx C++ application, so there is no need to do all this.
779 static bool embedded
= false;
780 if ((pass
== 1 || pass
== 2) && wxTheApp
) {
784 if (pass
== 3 && embedded
)
788 #define REINITOBJ(name, classname) \
789 if (pass == 1) { name = (classname*)0xC0C0C0C0; } \
790 else if (pass == 2) { rsoPass2(#name); } \
791 else if (pass == 3) { rsoPass3(#name, #classname, (void*)name); }
794 #define REINITOBJ2(name, classname) \
796 else if (pass == 2) { rsoPass2(#name); } \
797 else if (pass == 3) { rsoPass3(#name, #classname, (void*)&name); }
800 REINITOBJ(wxNORMAL_FONT
, wxFont
);
801 REINITOBJ(wxSMALL_FONT
, wxFont
);
802 REINITOBJ(wxITALIC_FONT
, wxFont
);
803 REINITOBJ(wxSWISS_FONT
, wxFont
);
805 REINITOBJ(wxRED_PEN
, wxPen
);
806 REINITOBJ(wxCYAN_PEN
, wxPen
);
807 REINITOBJ(wxGREEN_PEN
, wxPen
);
808 REINITOBJ(wxBLACK_PEN
, wxPen
);
809 REINITOBJ(wxWHITE_PEN
, wxPen
);
810 REINITOBJ(wxTRANSPARENT_PEN
, wxPen
);
811 REINITOBJ(wxBLACK_DASHED_PEN
, wxPen
);
812 REINITOBJ(wxGREY_PEN
, wxPen
);
813 REINITOBJ(wxMEDIUM_GREY_PEN
, wxPen
);
814 REINITOBJ(wxLIGHT_GREY_PEN
, wxPen
);
816 REINITOBJ(wxBLUE_BRUSH
, wxBrush
);
817 REINITOBJ(wxGREEN_BRUSH
, wxBrush
);
818 REINITOBJ(wxWHITE_BRUSH
, wxBrush
);
819 REINITOBJ(wxBLACK_BRUSH
, wxBrush
);
820 REINITOBJ(wxTRANSPARENT_BRUSH
, wxBrush
);
821 REINITOBJ(wxCYAN_BRUSH
, wxBrush
);
822 REINITOBJ(wxRED_BRUSH
, wxBrush
);
823 REINITOBJ(wxGREY_BRUSH
, wxBrush
);
824 REINITOBJ(wxMEDIUM_GREY_BRUSH
, wxBrush
);
825 REINITOBJ(wxLIGHT_GREY_BRUSH
, wxBrush
);
827 REINITOBJ(wxBLACK
, wxColour
);
828 REINITOBJ(wxWHITE
, wxColour
);
829 REINITOBJ(wxRED
, wxColour
);
830 REINITOBJ(wxBLUE
, wxColour
);
831 REINITOBJ(wxGREEN
, wxColour
);
832 REINITOBJ(wxCYAN
, wxColour
);
833 REINITOBJ(wxLIGHT_GREY
, wxColour
);
835 REINITOBJ(wxSTANDARD_CURSOR
, wxCursor
);
836 REINITOBJ(wxHOURGLASS_CURSOR
, wxCursor
);
837 REINITOBJ(wxCROSS_CURSOR
, wxCursor
);
839 REINITOBJ2(wxNullBitmap
, wxBitmap
);
840 REINITOBJ2(wxNullIcon
, wxIcon
);
841 REINITOBJ2(wxNullCursor
, wxCursor
);
842 REINITOBJ2(wxNullPen
, wxPen
);
843 REINITOBJ2(wxNullBrush
, wxBrush
);
844 REINITOBJ2(wxNullPalette
, wxPalette
);
845 REINITOBJ2(wxNullFont
, wxFont
);
846 REINITOBJ2(wxNullColour
, wxColour
);
848 REINITOBJ(wxTheFontList
, wxFontList
);
849 REINITOBJ(wxThePenList
, wxPenList
);
850 REINITOBJ(wxTheBrushList
, wxBrushList
);
851 REINITOBJ(wxTheColourDatabase
, wxColourDatabase
);
854 REINITOBJ2(wxDefaultValidator
, wxValidator
);
855 REINITOBJ2(wxNullImage
, wxImage
);
856 REINITOBJ2(wxNullAcceleratorTable
, wxAcceleratorTable
);
862 //---------------------------------------------------------------------------
864 // Check for existence of a wxApp, setting an exception if there isn't one.
865 // This doesn't need to aquire the GIL because it should only be called from
866 // an %exception before the lock is released.
868 bool wxPyCheckForApp() {
869 if (wxTheApp
!= NULL
)
872 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
877 //---------------------------------------------------------------------------
879 void wxPyUserData_dtor(wxPyUserData
* self
) {
880 if (! wxPyDoingCleanup
) {
881 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
882 Py_DECREF(self
->m_obj
);
884 wxPyEndBlockThreads(blocked
);
889 void wxPyClientData_dtor(wxPyClientData
* self
) {
890 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
891 // may have already garbage collected the object...
892 if (self
->m_incRef
) {
893 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
894 Py_DECREF(self
->m_obj
);
895 wxPyEndBlockThreads(blocked
);
903 // This is called when an OOR controled object is being destroyed. Although
904 // the C++ object is going away there is no way to force the Python object
905 // (and all references to it) to die too. This causes problems (crashes) in
906 // wxPython when a python shadow object attempts to call a C++ method using
907 // the now bogus pointer... So to try and prevent this we'll do a little black
908 // magic and change the class of the python instance to a class that will
909 // raise an exception for any attempt to call methods with it. See
910 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
911 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
913 static PyObject
* deadObjectClass
= NULL
;
915 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
916 if (deadObjectClass
== NULL
) {
917 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
918 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
919 // will lead to a deadlock when it tries to aquire the GIL again.
920 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
921 Py_INCREF(deadObjectClass
);
925 // Only if there is more than one reference to the object and we are
926 // holding the OOR reference:
927 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
928 // bool isInstance = wxPyInstance_Check(self->m_obj);
930 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
932 // Call __del__, if there is one.
933 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
935 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
939 if (PyErr_Occurred())
940 PyErr_Clear(); // just ignore it for now
943 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
945 // Clear the instance's dictionary
948 // put the name of the old class into the instance, and then reset the
949 // class to be the dead class.
950 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
951 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
952 PyDict_SetItemString(dict
, "_name", name
);
953 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
954 //Py_INCREF(deadObjectClass);
960 // m_obj is DECREF'd in the base class dtor...
961 wxPyEndBlockThreads(blocked
);
965 //---------------------------------------------------------------------------
966 // Stuff used by OOR to find the right wxPython class type to return and to
970 // The pointer type map is used when the "pointer" type name generated by SWIG
971 // is not the same as the shadow class name, for example wxPyTreeCtrl
972 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
973 // so we'll just make it a Python dictionary in the wx module's namespace.
974 // (See __wxSetDictionary)
975 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
976 if (! wxPyPtrTypeMap
)
977 wxPyPtrTypeMap
= PyDict_New();
978 PyDict_SetItemString(wxPyPtrTypeMap
,
980 PyString_FromString((char*)ptrName
));
986 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
987 PyObject
* target
= NULL
;
988 bool isEvtHandler
= false;
989 bool isSizer
= false;
992 // If it's derived from wxEvtHandler then there may
993 // already be a pointer to a Python object that we can use
995 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
997 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
998 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
1000 target
= data
->m_obj
;
1006 // Also check for wxSizer
1007 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
1009 wxSizer
* sz
= (wxSizer
*)source
;
1010 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
1012 target
= data
->m_obj
;
1019 // Otherwise make it the old fashioned way by making a new shadow
1020 // object and putting this pointer in it. Look up the class
1021 // heirarchy until we find a class name that is located in the
1023 const wxClassInfo
* info
= source
->GetClassInfo();
1024 wxString name
= info
->GetClassName();
1025 bool exists
= wxPyCheckSwigType(name
);
1026 while (info
&& !exists
) {
1027 info
= info
->GetBaseClass1();
1028 name
= info
->GetClassName();
1029 exists
= wxPyCheckSwigType(name
);
1032 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
1033 if (target
&& isEvtHandler
)
1034 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1035 if (target
&& isSizer
)
1036 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
1038 wxString
msg(wxT("wxPython class not found for "));
1039 msg
+= source
->GetClassInfo()->GetClassName();
1040 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
1044 } else { // source was NULL so return None.
1045 Py_INCREF(Py_None
); target
= Py_None
;
1051 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
1053 return wxPyMake_wxObject(source
, setThisOwn
);
1057 //---------------------------------------------------------------------------
1060 #ifdef WXP_WITH_THREAD
1061 #if !wxPyUSE_GIL_STATE
1064 unsigned long wxPyGetCurrentThreadId() {
1065 return wxThread::GetCurrentId();
1068 static wxPyThreadState gs_shutdownTState
;
1071 wxPyThreadState
* wxPyGetThreadState() {
1072 if (wxPyTMutex
== NULL
) // Python is shutting down...
1073 return &gs_shutdownTState
;
1075 unsigned long ctid
= wxPyGetCurrentThreadId();
1076 wxPyThreadState
* tstate
= NULL
;
1079 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1080 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1081 if (info
.tid
== ctid
) {
1086 wxPyTMutex
->Unlock();
1087 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
1093 void wxPySaveThreadState(PyThreadState
* tstate
) {
1094 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
1095 gs_shutdownTState
.tstate
= tstate
;
1098 unsigned long ctid
= wxPyGetCurrentThreadId();
1100 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
1101 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
1102 if (info
.tid
== ctid
) {
1104 if (info
.tstate
!= tstate
)
1105 wxLogMessage("*** tstate mismatch!???");
1107 info
.tstate
= tstate
; // allow for transient tstates
1108 // Normally it will never change, but apparently COM callbacks
1109 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
1110 // tstate which will then be garbage the next time we try to use
1113 wxPyTMutex
->Unlock();
1117 // not found, so add it...
1118 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
1119 wxPyTMutex
->Unlock();
1127 // Calls from Python to wxWindows code are wrapped in calls to these
1130 PyThreadState
* wxPyBeginAllowThreads() {
1131 #ifdef WXP_WITH_THREAD
1132 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1133 #if !wxPyUSE_GIL_STATE
1134 wxPySaveThreadState(saved
);
1142 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1143 #ifdef WXP_WITH_THREAD
1144 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1150 // Calls from wxWindows back to Python code, or even any PyObject
1151 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1153 wxPyBlock_t
wxPyBeginBlockThreads() {
1154 #ifdef WXP_WITH_THREAD
1155 if (! Py_IsInitialized()) {
1156 return (wxPyBlock_t
)0;
1158 #if wxPyUSE_GIL_STATE
1159 PyGILState_STATE state
= PyGILState_Ensure();
1162 PyThreadState
*current
= _PyThreadState_Current
;
1164 // Only block if there wasn't already a tstate, or if the current one is
1165 // not the one we are wanting to change to. This should prevent deadlock
1166 // if there are nested calls to wxPyBeginBlockThreads
1167 wxPyBlock_t blocked
= false;
1168 wxPyThreadState
* tstate
= wxPyGetThreadState();
1169 if (current
!= tstate
->tstate
) {
1170 PyEval_RestoreThread(tstate
->tstate
);
1176 return (wxPyBlock_t
)0;
1181 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1182 #ifdef WXP_WITH_THREAD
1183 if (! Py_IsInitialized()) {
1186 #if wxPyUSE_GIL_STATE
1187 PyGILState_Release(blocked
);
1189 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1190 // The value of blocked passed in needs to be the same as that returned
1191 // from wxPyBeginBlockThreads at the same nesting level.
1193 PyEval_SaveThread();
1200 //---------------------------------------------------------------------------
1201 // wxPyInputStream and wxPyCBInputStream methods
1204 void wxPyInputStream::close() {
1205 /* do nothing for now */
1208 void wxPyInputStream::flush() {
1209 /* do nothing for now */
1212 bool wxPyInputStream::eof() {
1214 return m_wxis
->Eof();
1219 wxPyInputStream::~wxPyInputStream() {
1227 PyObject
* wxPyInputStream::read(int size
) {
1228 PyObject
* obj
= NULL
;
1230 const int BUFSIZE
= 1024;
1232 // check if we have a real wxInputStream to work with
1234 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1235 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1236 wxPyEndBlockThreads(blocked
);
1241 // read while bytes are available on the stream
1242 while ( m_wxis
->CanRead() ) {
1243 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1244 buf
.UngetAppendBuf(m_wxis
->LastRead());
1247 } else { // Read only size number of characters
1248 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1249 buf
.UngetWriteBuf(m_wxis
->LastRead());
1253 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1254 wxStreamError err
= m_wxis
->GetLastError();
1255 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1256 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1259 // We use only strings for the streams, not unicode
1260 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1262 wxPyEndBlockThreads(blocked
);
1267 PyObject
* wxPyInputStream::readline(int size
) {
1268 PyObject
* obj
= NULL
;
1273 // check if we have a real wxInputStream to work with
1275 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1276 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1277 wxPyEndBlockThreads(blocked
);
1281 // read until \n or byte limit reached
1282 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1283 ch
= m_wxis
->GetC();
1288 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1289 wxStreamError err
= m_wxis
->GetLastError();
1290 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1291 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1294 // We use only strings for the streams, not unicode
1295 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1297 wxPyEndBlockThreads(blocked
);
1302 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1305 // check if we have a real wxInputStream to work with
1307 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1308 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1309 wxPyEndBlockThreads(blocked
);
1314 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1315 pylist
= PyList_New(0);
1316 wxPyEndBlockThreads(blocked
);
1319 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1321 wxPyEndBlockThreads(blocked
);
1325 // read sizehint bytes or until EOF
1327 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1328 PyObject
* s
= this->readline();
1330 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1332 wxPyEndBlockThreads(blocked
);
1335 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1336 PyList_Append(pylist
, s
);
1337 i
+= PyString_Size(s
);
1338 wxPyEndBlockThreads(blocked
);
1342 wxStreamError err
= m_wxis
->GetLastError();
1343 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1344 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1346 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1347 wxPyEndBlockThreads(blocked
);
1355 void wxPyInputStream::seek(int offset
, int whence
) {
1357 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1360 int wxPyInputStream::tell(){
1362 return m_wxis
->TellI();
1369 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1370 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1373 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1375 m_read
= other
.m_read
;
1376 m_seek
= other
.m_seek
;
1377 m_tell
= other
.m_tell
;
1378 m_block
= other
.m_block
;
1385 wxPyCBInputStream::~wxPyCBInputStream() {
1386 wxPyBlock_t blocked
;
1387 if (m_block
) blocked
= wxPyBeginBlockThreads();
1391 if (m_block
) wxPyEndBlockThreads(blocked
);
1395 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1396 wxPyBlock_t blocked
;
1397 if (block
) blocked
= wxPyBeginBlockThreads();
1399 PyObject
* read
= getMethod(py
, "read");
1400 PyObject
* seek
= getMethod(py
, "seek");
1401 PyObject
* tell
= getMethod(py
, "tell");
1404 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1408 if (block
) wxPyEndBlockThreads(blocked
);
1412 if (block
) wxPyEndBlockThreads(blocked
);
1413 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1417 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1418 return wxPyCBInputStream::create(py
, block
);
1421 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1422 return new wxPyCBInputStream(*other
);
1425 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1426 if (!PyObject_HasAttrString(py
, name
))
1428 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1429 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1437 wxFileOffset
wxPyCBInputStream::GetLength() const {
1438 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1439 if (m_seek
&& m_tell
) {
1440 wxFileOffset temp
= self
->OnSysTell();
1441 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1442 self
->OnSysSeek(temp
, wxFromStart
);
1446 return wxInvalidOffset
;
1450 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1454 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1455 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1456 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1460 if ((result
!= NULL
) && PyString_Check(result
)) {
1461 o
= PyString_Size(result
);
1463 m_lasterror
= wxSTREAM_EOF
;
1466 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1471 m_lasterror
= wxSTREAM_READ_ERROR
;
1472 wxPyEndBlockThreads(blocked
);
1476 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1477 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1482 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1483 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1484 PyObject
* arglist
= PyTuple_New(2);
1486 if (sizeof(wxFileOffset
) > sizeof(long))
1487 // wxFileOffset is a 64-bit value...
1488 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1490 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1492 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1495 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1498 wxPyEndBlockThreads(blocked
);
1503 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1504 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1505 PyObject
* arglist
= Py_BuildValue("()");
1506 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1509 if (result
!= NULL
) {
1510 if (PyLong_Check(result
))
1511 o
= PyLong_AsLongLong(result
);
1513 o
= PyInt_AsLong(result
);
1516 wxPyEndBlockThreads(blocked
);
1520 //----------------------------------------------------------------------
1522 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1524 wxPyCallback::wxPyCallback(PyObject
* func
) {
1529 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1530 m_func
= other
.m_func
;
1534 wxPyCallback::~wxPyCallback() {
1535 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1537 wxPyEndBlockThreads(blocked
);
1541 #define wxPy_PRECALLINIT "_preCallInit"
1542 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1544 // This function is used for all events destined for Python event handlers.
1545 void wxPyCallback::EventThunker(wxEvent
& event
) {
1546 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1547 PyObject
* func
= cb
->m_func
;
1551 bool checkSkip
= false;
1553 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1554 wxString className
= event
.GetClassInfo()->GetClassName();
1556 // If the event is one of these types then pass the original
1557 // event object instead of the one passed to us.
1558 if ( className
== wxT("wxPyEvent") ) {
1559 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1560 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1562 else if ( className
== wxT("wxPyCommandEvent") ) {
1563 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1564 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1567 arg
= wxPyConstructObject((void*)&event
, className
);
1573 // "intern" the pre/post method names to speed up the HasAttr
1574 static PyObject
* s_preName
= NULL
;
1575 static PyObject
* s_postName
= NULL
;
1576 if (s_preName
== NULL
) {
1577 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1578 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1581 // Check if the event object needs some preinitialization
1582 if (PyObject_HasAttr(arg
, s_preName
)) {
1583 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1585 Py_DECREF(result
); // result is ignored, but we still need to decref it
1586 PyErr_Clear(); // Just in case...
1592 // Call the event handler, passing the event object
1593 tuple
= PyTuple_New(1);
1594 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1595 result
= PyEval_CallObject(func
, tuple
);
1597 Py_DECREF(result
); // result is ignored, but we still need to decref it
1598 PyErr_Clear(); // Just in case...
1603 // Check if the event object needs some post cleanup
1604 if (PyObject_HasAttr(arg
, s_postName
)) {
1605 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1607 Py_DECREF(result
); // result is ignored, but we still need to decref it
1608 PyErr_Clear(); // Just in case...
1615 // if the event object was one of our special types and
1616 // it had been cloned, then we need to extract the Skipped
1617 // value from the original and set it in the clone.
1618 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1620 event
.Skip(PyInt_AsLong(result
));
1628 wxPyEndBlockThreads(blocked
);
1632 //----------------------------------------------------------------------
1634 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1636 m_self
= other
.m_self
;
1637 m_class
= other
.m_class
;
1645 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1656 #if PYTHON_API_VERSION >= 1011
1658 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1659 // in which the method was defined. Starting with 2.2 it returns
1660 // "class that asked for the method" which seems totally bogus to me
1661 // but apprently it fixes some obscure problem waiting to happen in
1662 // Python. Since the API was not documented Guido and the gang felt
1663 // safe in changing it. Needless to say that totally screwed up the
1664 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1665 // code to find the class where the method is actually defined...
1668 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1672 if (PyType_Check(klass
)) { // new style classes
1673 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1674 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1675 PyObject
*mro
, *res
, *base
, *dict
;
1676 /* Look in tp_dict of types in MRO */
1678 assert(PyTuple_Check(mro
));
1679 n
= PyTuple_GET_SIZE(mro
);
1680 for (i
= 0; i
< n
; i
++) {
1681 base
= PyTuple_GET_ITEM(mro
, i
);
1682 if (PyClass_Check(base
))
1683 dict
= ((PyClassObject
*)base
)->cl_dict
;
1685 assert(PyType_Check(base
));
1686 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1688 assert(dict
&& PyDict_Check(dict
));
1689 res
= PyDict_GetItem(dict
, name
);
1696 else if (PyClass_Check(klass
)) { // old style classes
1697 // This code is borrowed/adapted from class_lookup in classobject.c
1698 PyClassObject
* cp
= (PyClassObject
*)klass
;
1699 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1700 if (value
!= NULL
) {
1701 return (PyObject
*)cp
;
1703 n
= PyTuple_Size(cp
->cl_bases
);
1704 for (i
= 0; i
< n
; i
++) {
1705 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1706 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1718 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, const char* name
)
1720 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1722 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1724 #else // 2.2 and after, the hard way...
1726 PyObject
* nameo
= PyString_FromString(name
);
1727 PyObject
* klass
= PyFindClassWithAttr(mgc
, nameo
);
1735 bool wxPyCallbackHelper::findCallback(const char* name
) const {
1736 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1737 self
->m_lastFound
= NULL
;
1739 // If the object (m_self) has an attibute of the given name...
1740 if (m_self
&& PyObject_HasAttrString(m_self
, (char*)name
)) {
1741 PyObject
*method
, *klass
;
1742 method
= PyObject_GetAttrString(m_self
, (char*)name
);
1744 // ...and if that attribute is a method, and if that method's class is
1745 // not from a base class...
1746 if (PyMethod_Check(method
) &&
1747 (klass
= PyMethod_GetDefiningClass(method
, (char*)name
)) != NULL
&&
1748 ((klass
== m_class
) || PyObject_IsSubclass(klass
, m_class
))) {
1750 // ...then we'll save a pointer to the method so callCallback can call it.
1751 self
->m_lastFound
= method
;
1757 return m_lastFound
!= NULL
;
1761 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1765 result
= callCallbackObj(argTuple
);
1766 if (result
) { // Assumes an integer return type...
1767 retval
= PyInt_AsLong(result
);
1769 PyErr_Clear(); // forget about it if it's not...
1774 // Invoke the Python callable object, returning the raw PyObject return
1775 // value. Caller should DECREF the return value and also manage the GIL.
1776 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1779 // Save a copy of the pointer in case the callback generates another
1780 // callback. In that case m_lastFound will have a different value when
1781 // it gets back here...
1782 PyObject
* method
= m_lastFound
;
1784 result
= PyEval_CallObject(method
, argTuple
);
1785 Py_DECREF(argTuple
);
1794 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1795 cbh
.setSelf(self
, klass
, incref
);
1798 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
) {
1799 return cbh
.findCallback(name
);
1802 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1803 return cbh
.callCallback(argTuple
);
1806 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1807 return cbh
.callCallbackObj(argTuple
);
1811 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1812 if (cbh
->m_incRef
) {
1813 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1814 Py_XDECREF(cbh
->m_self
);
1815 Py_XDECREF(cbh
->m_class
);
1816 wxPyEndBlockThreads(blocked
);
1820 //---------------------------------------------------------------------------
1821 //---------------------------------------------------------------------------
1822 // These event classes can be derived from in Python and passed through the event
1823 // system without losing anything. They do this by keeping a reference to
1824 // themselves and some special case handling in wxPyCallback::EventThunker.
1827 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1828 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1829 //Py_INCREF(m_self); // circular loops...
1833 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1834 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1837 wxPyEndBlockThreads(blocked
);
1840 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1841 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1849 wxPyEndBlockThreads(blocked
);
1852 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1858 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1859 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1862 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1863 : wxEvent(winid
, commandType
) {
1867 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1870 SetSelf(evt
.m_self
, true);
1874 wxPyEvent::~wxPyEvent() {
1878 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1879 : wxCommandEvent(commandType
, id
) {
1883 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1884 : wxCommandEvent(evt
)
1886 SetSelf(evt
.m_self
, true);
1890 wxPyCommandEvent::~wxPyCommandEvent() {
1897 //---------------------------------------------------------------------------
1898 //---------------------------------------------------------------------------
1899 // Convert a wxList to a Python List, only works for lists of wxObjects
1901 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1902 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1906 wxNode
* node
= list
->GetFirst();
1908 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1909 pyList
= PyList_New(0);
1911 wxObj
= node
->GetData();
1912 pyObj
= wxPyMake_wxObject(wxObj
,false);
1913 PyList_Append(pyList
, pyObj
);
1914 node
= node
->GetNext();
1916 wxPyEndBlockThreads(blocked
);
1920 //----------------------------------------------------------------------
1922 long wxPyGetWinHandle(wxWindow
* win
) {
1925 return (long)win
->GetHandle();
1928 #if defined(__WXGTK__) || defined(__WXX11)
1929 return (long)GetXWindow(win
);
1933 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1934 return (long)win
->GetHandle();
1940 //----------------------------------------------------------------------
1941 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1942 // included in every file over and over again...
1944 wxString
* wxString_in_helper(PyObject
* source
) {
1945 wxString
* target
= NULL
;
1947 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1948 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1952 PyObject
* uni
= source
;
1953 if (PyString_Check(source
)) {
1954 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1955 if (PyErr_Occurred()) return NULL
;
1957 target
= new wxString();
1958 size_t len
= PyUnicode_GET_SIZE(uni
);
1960 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1961 target
->UngetWriteBuf(len
);
1964 if (PyString_Check(source
))
1967 // Convert to a string object if it isn't already, then to wxString
1968 PyObject
* str
= source
;
1969 if (PyUnicode_Check(source
)) {
1970 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1971 if (PyErr_Occurred()) return NULL
;
1973 else if (!PyString_Check(source
)) {
1974 str
= PyObject_Str(source
);
1975 if (PyErr_Occurred()) return NULL
;
1977 char* tmpPtr
; int tmpSize
;
1978 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1979 target
= new wxString(tmpPtr
, tmpSize
);
1981 if (!PyString_Check(source
))
1983 #endif // wxUSE_UNICODE
1989 // Similar to above except doesn't use "new" and doesn't set an exception
1990 wxString
Py2wxString(PyObject
* source
)
1995 // Convert to a unicode object, if not already, then to a wxString
1996 PyObject
* uni
= source
;
1997 if (!PyUnicode_Check(source
)) {
1998 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1999 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2001 size_t len
= PyUnicode_GET_SIZE(uni
);
2003 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
2004 target
.UngetWriteBuf();
2007 if (!PyUnicode_Check(source
))
2010 // Convert to a string object if it isn't already, then to wxString
2011 PyObject
* str
= source
;
2012 if (PyUnicode_Check(source
)) {
2013 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
2014 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2016 else if (!PyString_Check(source
)) {
2017 str
= PyObject_Str(source
);
2018 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
2020 char* tmpPtr
; int tmpSize
;
2021 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
2022 target
= wxString(tmpPtr
, tmpSize
);
2024 if (!PyString_Check(source
))
2026 #endif // wxUSE_UNICODE
2032 // Make either a Python String or Unicode object, depending on build mode
2033 PyObject
* wx2PyString(const wxString
& src
)
2037 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
2039 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
2046 void wxSetDefaultPyEncoding(const char* encoding
)
2048 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
2051 const char* wxGetDefaultPyEncoding()
2053 return wxPyDefaultEncoding
;
2056 //----------------------------------------------------------------------
2059 byte
* byte_LIST_helper(PyObject
* source
) {
2060 if (!PyList_Check(source
)) {
2061 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2064 int count
= PyList_Size(source
);
2065 byte
* temp
= new byte
[count
];
2067 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2070 for (int x
=0; x
<count
; x
++) {
2071 PyObject
* o
= PyList_GetItem(source
, x
);
2072 if (! PyInt_Check(o
)) {
2073 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2076 temp
[x
] = (byte
)PyInt_AsLong(o
);
2082 int* int_LIST_helper(PyObject
* source
) {
2083 if (!PyList_Check(source
)) {
2084 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2087 int count
= PyList_Size(source
);
2088 int* temp
= new int[count
];
2090 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2093 for (int x
=0; x
<count
; x
++) {
2094 PyObject
* o
= PyList_GetItem(source
, x
);
2095 if (! PyInt_Check(o
)) {
2096 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2099 temp
[x
] = PyInt_AsLong(o
);
2105 long* long_LIST_helper(PyObject
* source
) {
2106 if (!PyList_Check(source
)) {
2107 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2110 int count
= PyList_Size(source
);
2111 long* temp
= new long[count
];
2113 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2116 for (int x
=0; x
<count
; x
++) {
2117 PyObject
* o
= PyList_GetItem(source
, x
);
2118 if (! PyInt_Check(o
)) {
2119 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2122 temp
[x
] = PyInt_AsLong(o
);
2128 char** string_LIST_helper(PyObject
* source
) {
2129 if (!PyList_Check(source
)) {
2130 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2133 int count
= PyList_Size(source
);
2134 char** temp
= new char*[count
];
2136 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2139 for (int x
=0; x
<count
; x
++) {
2140 PyObject
* o
= PyList_GetItem(source
, x
);
2141 if (! PyString_Check(o
)) {
2142 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2145 temp
[x
] = PyString_AsString(o
);
2150 //--------------------------------
2151 // Part of patch from Tim Hochberg
2152 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2153 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2154 point
->x
= PyInt_AS_LONG(o1
);
2155 point
->y
= PyInt_AS_LONG(o2
);
2158 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2159 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2160 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2163 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2164 // Disallow instances because they can cause havok
2167 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2168 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2169 point
->x
= PyInt_AsLong(o1
);
2170 point
->y
= PyInt_AsLong(o2
);
2177 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2178 // Putting all of the declarations here allows
2179 // us to put the error handling all in one place.
2182 PyObject
*o
, *o1
, *o2
;
2183 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2185 if (!PySequence_Check(source
)) {
2189 // The length of the sequence is returned in count.
2190 *count
= PySequence_Length(source
);
2195 temp
= new wxPoint
[*count
];
2197 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2200 for (x
=0; x
<*count
; x
++) {
2201 // Get an item: try fast way first.
2203 o
= PySequence_Fast_GET_ITEM(source
, x
);
2206 o
= PySequence_GetItem(source
, x
);
2212 // Convert o to wxPoint.
2213 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2214 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2215 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2216 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2217 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2221 else if (wxPySwigInstance_Check(o
)) {
2223 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2228 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2229 o1
= PySequence_GetItem(o
, 0);
2230 o2
= PySequence_GetItem(o
, 1);
2231 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2255 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2259 //------------------------------
2262 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2263 if (!PyList_Check(source
)) {
2264 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2267 int count
= PyList_Size(source
);
2268 wxBitmap
** temp
= new wxBitmap
*[count
];
2270 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2273 for (int x
=0; x
<count
; x
++) {
2274 PyObject
* o
= PyList_GetItem(source
, x
);
2275 if (wxPySwigInstance_Check(o
)) {
2277 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2278 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2284 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2293 wxString
* wxString_LIST_helper(PyObject
* source
) {
2294 if (!PyList_Check(source
)) {
2295 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2298 int count
= PyList_Size(source
);
2299 wxString
* temp
= new wxString
[count
];
2301 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2304 for (int x
=0; x
<count
; x
++) {
2305 PyObject
* o
= PyList_GetItem(source
, x
);
2306 #if PYTHON_API_VERSION >= 1009
2307 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2308 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2312 if (! PyString_Check(o
)) {
2313 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2318 wxString
* pStr
= wxString_in_helper(o
);
2326 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2327 if (!PyList_Check(source
)) {
2328 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2331 int count
= PyList_Size(source
);
2332 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2334 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2337 for (int x
=0; x
<count
; x
++) {
2338 PyObject
* o
= PyList_GetItem(source
, x
);
2339 if (wxPySwigInstance_Check(o
)) {
2340 wxAcceleratorEntry
* ae
;
2341 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2342 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2347 else if (PyTuple_Check(o
)) {
2348 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2349 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2350 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2351 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2354 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2362 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2363 if (!PyList_Check(source
)) {
2364 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2367 int count
= PyList_Size(source
);
2368 wxPen
** temp
= new wxPen
*[count
];
2370 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2373 for (int x
=0; x
<count
; x
++) {
2374 PyObject
* o
= PyList_GetItem(source
, x
);
2375 if (wxPySwigInstance_Check(o
)) {
2377 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2379 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2386 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2394 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2395 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2398 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2402 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2403 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2406 o1
= PySequence_GetItem(source
, 0);
2407 o2
= PySequence_GetItem(source
, 1);
2410 *i1
= PyInt_AsLong(o1
);
2411 *i2
= PyInt_AsLong(o2
);
2421 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2422 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2423 PyObject
*o1
, *o2
, *o3
, *o4
;
2425 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2429 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2430 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2431 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2432 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2435 o1
= PySequence_GetItem(source
, 0);
2436 o2
= PySequence_GetItem(source
, 1);
2437 o3
= PySequence_GetItem(source
, 2);
2438 o4
= PySequence_GetItem(source
, 3);
2441 *i1
= PyInt_AsLong(o1
);
2442 *i2
= PyInt_AsLong(o2
);
2443 *i3
= PyInt_AsLong(o3
);
2444 *i4
= PyInt_AsLong(o4
);
2456 //----------------------------------------------------------------------
2458 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2462 if (wxPySwigInstance_Check(source
) &&
2463 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2467 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2473 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2475 if (source
== Py_None
) {
2476 **obj
= wxSize(-1,-1);
2479 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2483 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2485 if (source
== Py_None
) {
2486 **obj
= wxPoint(-1,-1);
2489 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2494 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2496 if (source
== Py_None
) {
2497 **obj
= wxRealPoint(-1,-1);
2501 // If source is an object instance then it may already be the right type
2502 if (wxPySwigInstance_Check(source
)) {
2504 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2509 // otherwise a 2-tuple of floats is expected
2510 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2511 PyObject
* o1
= PySequence_GetItem(source
, 0);
2512 PyObject
* o2
= PySequence_GetItem(source
, 1);
2513 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2518 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2525 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2531 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2533 if (source
== Py_None
) {
2534 **obj
= wxRect(-1,-1,-1,-1);
2538 // If source is an object instance then it may already be the right type
2539 if (wxPySwigInstance_Check(source
)) {
2541 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2546 // otherwise a 4-tuple of integers is expected
2547 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2548 PyObject
* o1
= PySequence_GetItem(source
, 0);
2549 PyObject
* o2
= PySequence_GetItem(source
, 1);
2550 PyObject
* o3
= PySequence_GetItem(source
, 2);
2551 PyObject
* o4
= PySequence_GetItem(source
, 3);
2552 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2553 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2560 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2561 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2570 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2576 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2578 if (source
== Py_None
) {
2579 **obj
= wxNullColour
;
2583 // If source is an object instance then it may already be the right type
2584 if (wxPySwigInstance_Check(source
)) {
2586 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxColour")))
2591 // otherwise check for a string
2592 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2593 wxString spec
= Py2wxString(source
);
2594 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2595 long red
, green
, blue
;
2596 red
= green
= blue
= 0;
2597 spec
.Mid(1,2).ToLong(&red
, 16);
2598 spec
.Mid(3,2).ToLong(&green
, 16);
2599 spec
.Mid(5,2).ToLong(&blue
, 16);
2601 **obj
= wxColour(red
, green
, blue
);
2604 else { // it's a colour name
2605 **obj
= wxColour(spec
);
2609 // last chance: 3-tuple of integers is expected
2610 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2611 PyObject
* o1
= PySequence_GetItem(source
, 0);
2612 PyObject
* o2
= PySequence_GetItem(source
, 1);
2613 PyObject
* o3
= PySequence_GetItem(source
, 2);
2614 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2620 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2628 PyErr_SetString(PyExc_TypeError
,
2629 "Expected a wxColour object or a string containing a colour name or '#RRGGBB'.");
2634 bool wxColour_typecheck(PyObject
* source
) {
2636 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2639 if (PyString_Check(source
) || PyUnicode_Check(source
))
2647 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2649 if (source
== Py_None
) {
2650 **obj
= wxPoint2D(-1,-1);
2654 // If source is an object instance then it may already be the right type
2655 if (wxPySwigInstance_Check(source
)) {
2657 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2662 // otherwise a length-2 sequence of floats is expected
2663 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2664 PyObject
* o1
= PySequence_GetItem(source
, 0);
2665 PyObject
* o2
= PySequence_GetItem(source
, 1);
2666 // This should really check for floats, not numbers -- but that would break code.
2667 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2672 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2678 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2683 //----------------------------------------------------------------------
2685 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2687 PyObject
* list
= PyList_New(0);
2688 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2690 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2692 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2694 PyList_Append(list
, str
);
2701 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2703 PyObject
* list
= PyList_New(0);
2704 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2705 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2706 PyList_Append(list
, number
);
2713 //----------------------------------------------------------------------
2714 // wxPyImageHandler methods
2716 // TODO: Switch these to use wxPython's standard macros and helper classes
2717 // for calling callbacks.
2719 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2720 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2721 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2722 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2724 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2725 return wxPyConstructObject(new wxPyInputStream(stream
),
2726 wxT("wxPyInputStream"), 0);
2729 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2730 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2733 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2734 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2737 wxPyImageHandler::wxPyImageHandler():
2740 if (!m_DoCanRead_Name
) {
2741 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2742 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2743 m_LoadFile_Name
= PyString_FromString("LoadFile");
2744 m_SaveFile_Name
= PyString_FromString("SaveFile");
2748 wxPyImageHandler::~wxPyImageHandler() {
2755 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2756 // should check here for isinstance(PyImageHandler) ??
2761 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2762 // check if our object has this method
2763 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2764 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2765 wxPyEndBlockThreads(blocked
);
2769 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2770 py_InputStream(&stream
), NULL
);
2771 bool retval
= false;
2773 retval
= PyInt_AsLong(res
);
2779 wxPyEndBlockThreads(blocked
);
2783 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2784 bool verbose
, int index
) {
2785 // check if our object has this method
2786 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2787 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2788 wxPyEndBlockThreads(blocked
);
2791 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2793 py_InputStream(&stream
),
2794 PyInt_FromLong(verbose
),
2795 PyInt_FromLong(index
),
2797 bool retval
= false;
2799 retval
= PyInt_AsLong(res
);
2804 wxPyEndBlockThreads(blocked
);
2808 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2810 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2811 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2812 wxPyEndBlockThreads(blocked
);
2815 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2817 py_OutputStream(&stream
),
2818 PyInt_FromLong(verbose
),
2820 bool retval
= false;
2822 retval
=PyInt_AsLong(res
);
2827 wxPyEndBlockThreads(blocked
);
2831 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2832 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2833 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2834 wxPyEndBlockThreads(blocked
);
2837 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2838 py_InputStream(&stream
),
2842 retval
=PyInt_AsLong(res
);
2847 wxPyEndBlockThreads(blocked
);
2852 //----------------------------------------------------------------------
2853 //----------------------------------------------------------------------