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"
18 #include "wx/wxPython/swigver.h"
19 #include "wx/wxPython/twoitem.h"
22 #include <wx/msw/private.h>
23 #include <wx/msw/winundef.h>
24 #include <wx/msw/msvcrt.h>
31 #include <gdk/gdkprivate.h>
32 #include <wx/gtk/win_gtk.h>
33 #define GetXWindow(wxwin) (wxwin)->m_wxwindow ? \
34 GDK_WINDOW_XWINDOW(GTK_PIZZA((wxwin)->m_wxwindow)->bin_window) : \
35 GDK_WINDOW_XWINDOW((wxwin)->m_widget->window)
40 #include "wx/x11/privx.h"
41 #define GetXWindow(wxwin) ((Window)(wxwin)->GetHandle())
45 #include <wx/mac/private.h>
48 #include <wx/clipbrd.h>
49 #include <wx/mimetype.h>
52 //----------------------------------------------------------------------
54 #if PYTHON_API_VERSION < 1009 && wxUSE_UNICODE
55 #error Python must support Unicode to use wxWindows Unicode
58 //----------------------------------------------------------------------
60 wxPyApp
* wxPythonApp
= NULL
; // Global instance of application object
61 bool wxPyDoCleanup
= false;
62 bool wxPyDoingCleanup
= false;
65 #ifdef WXP_WITH_THREAD
66 #if !wxPyUSE_GIL_STATE
67 struct wxPyThreadState
{
69 PyThreadState
* tstate
;
71 wxPyThreadState(unsigned long _tid
=0, PyThreadState
* _tstate
=NULL
)
72 : tid(_tid
), tstate(_tstate
) {}
75 #include <wx/dynarray.h>
76 WX_DECLARE_OBJARRAY(wxPyThreadState
, wxPyThreadStateArray
);
77 #include <wx/arrimpl.cpp>
78 WX_DEFINE_OBJARRAY(wxPyThreadStateArray
);
80 wxPyThreadStateArray
* wxPyTStates
= NULL
;
81 wxMutex
* wxPyTMutex
= NULL
;
87 #define DEFAULTENCODING_SIZE 64
88 static char wxPyDefaultEncoding
[DEFAULTENCODING_SIZE
] = "ascii";
90 static PyObject
* wxPython_dict
= NULL
;
91 static PyObject
* wxPyAssertionError
= NULL
;
92 static PyObject
* wxPyNoAppError
= NULL
;
94 PyObject
* wxPyPtrTypeMap
= NULL
;
97 #ifdef __WXMSW__ // If building for win32...
98 //----------------------------------------------------------------------
99 // This gets run when the DLL is loaded. We just need to save a handle.
100 //----------------------------------------------------------------------
104 HINSTANCE hinstDLL
, // handle to DLL module
105 DWORD fdwReason
, // reason for calling function
106 LPVOID lpvReserved
// reserved
109 // If wxPython is embedded in another wxWidgets app then
110 // the instance has already been set.
111 if (! wxGetInstance())
112 wxSetInstance(hinstDLL
);
117 //----------------------------------------------------------------------
118 // Classes for implementing the wxp main application shell.
119 //----------------------------------------------------------------------
121 IMPLEMENT_ABSTRACT_CLASS(wxPyApp
, wxApp
);
125 m_assertMode
= wxPYAPP_ASSERT_EXCEPTION
;
126 m_startupComplete
= false;
130 wxPyApp::~wxPyApp() {
132 wxApp::SetInstance(NULL
);
136 // This one isn't acutally called... We fake it with _BootstrapApp
137 bool wxPyApp::OnInit() {
142 int wxPyApp::MainLoop() {
145 DeletePendingObjects();
146 bool initialized
= wxTopLevelWindows
.GetCount() != 0;
148 if ( m_exitOnFrameDelete
== Later
) {
149 m_exitOnFrameDelete
= Yes
;
152 retval
= wxApp::MainLoop();
159 bool wxPyApp::OnInitGui() {
161 wxApp::OnInitGui(); // in this case always call the base class version
162 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
163 if (wxPyCBH_findCallback(m_myInst
, "OnInitGui"))
164 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
165 wxPyEndBlockThreads(blocked
);
170 int wxPyApp::OnExit() {
172 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
173 if (wxPyCBH_findCallback(m_myInst
, "OnExit"))
174 rval
= wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
175 wxPyEndBlockThreads(blocked
);
176 wxApp::OnExit(); // in this case always call the base class version
182 void wxPyApp::ExitMainLoop() {
184 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
185 if ((found
= wxPyCBH_findCallback(m_myInst
, "ExitMainLoop")))
186 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
187 wxPyEndBlockThreads(blocked
);
189 wxApp::ExitMainLoop();
194 void wxPyApp::OnAssertFailure(const wxChar
*file
,
200 // if we're not fully initialized then just log the error
201 if (! m_startupComplete
) {
204 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
207 buf
<< wxT(" in ") << func
<< wxT("()");
209 buf
<< wxT(": ") << msg
;
215 // If the OnAssert is overloaded in the Python class then call it...
217 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
218 if ((found
= wxPyCBH_findCallback(m_myInst
, "OnAssert"))) {
219 PyObject
* fso
= wx2PyString(file
);
220 PyObject
* cso
= wx2PyString(file
);
223 mso
= wx2PyString(file
);
225 mso
= Py_None
; Py_INCREF(Py_None
);
227 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(OiOO)", fso
, line
, cso
, mso
));
232 wxPyEndBlockThreads(blocked
);
234 // ...otherwise do our own thing with it
237 if (m_assertMode
& wxPYAPP_ASSERT_SUPPRESS
)
240 // turn it into a Python exception?
241 if (m_assertMode
& wxPYAPP_ASSERT_EXCEPTION
) {
244 buf
.Printf(wxT("C++ assertion \"%s\" failed at %s(%d)"), cond
, file
, line
);
246 buf
<< wxT(" in ") << func
<< wxT("()");
248 buf
<< wxT(": ") << msg
;
252 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
253 PyObject
* s
= wx2PyString(buf
);
254 PyErr_SetObject(wxPyAssertionError
, s
);
256 wxPyEndBlockThreads(blocked
);
258 // Now when control returns to whatever API wrapper was called from
259 // Python it should detect that an exception is set and will return
260 // NULL, signalling the exception to Python.
263 // Send it to the normal log destination, but only if
264 // not _DIALOG because it will call this too
265 if ( (m_assertMode
& wxPYAPP_ASSERT_LOG
) && !(m_assertMode
& wxPYAPP_ASSERT_DIALOG
)) {
268 buf
.Printf(wxT("%s(%d): assert \"%s\" failed"),
271 buf
<< wxT(" in ") << func
<< wxT("()");
273 buf
<< wxT(": ") << msg
;
277 // do the normal wx assert dialog?
278 if (m_assertMode
& wxPYAPP_ASSERT_DIALOG
)
279 wxApp::OnAssertFailure(file
, line
, func
, cond
, msg
);
284 // For catching Apple Events
285 void wxPyApp::MacOpenFile(const wxString
&fileName
)
287 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
288 if (wxPyCBH_findCallback(m_myInst
, "MacOpenFile")) {
289 PyObject
* s
= wx2PyString(fileName
);
290 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
293 wxPyEndBlockThreads(blocked
);
296 void wxPyApp::MacPrintFile(const wxString
&fileName
)
298 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
299 if (wxPyCBH_findCallback(m_myInst
, "MacPrintFile")) {
300 PyObject
* s
= wx2PyString(fileName
);
301 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("(O)", s
));
304 wxPyEndBlockThreads(blocked
);
307 void wxPyApp::MacNewFile()
309 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
310 if (wxPyCBH_findCallback(m_myInst
, "MacNewFile"))
311 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
312 wxPyEndBlockThreads(blocked
);
315 void wxPyApp::MacReopenApp()
317 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
318 if (wxPyCBH_findCallback(m_myInst
, "MacReopenApp"))
319 wxPyCBH_callCallback(m_myInst
, Py_BuildValue("()"));
320 wxPyEndBlockThreads(blocked
);
325 bool wxPyApp::GetMacSupportPCMenuShortcuts() {
327 return s_macSupportPCMenuShortcuts
;
334 long wxPyApp::GetMacAboutMenuItemId() {
336 return s_macAboutMenuItemId
;
343 long wxPyApp::GetMacPreferencesMenuItemId() {
345 return s_macPreferencesMenuItemId
;
352 long wxPyApp::GetMacExitMenuItemId() {
354 return s_macExitMenuItemId
;
361 wxString
wxPyApp::GetMacHelpMenuTitleName() {
363 return s_macHelpMenuTitleName
;
365 return wxEmptyString
;
370 void wxPyApp::SetMacSupportPCMenuShortcuts(bool val
) {
372 s_macSupportPCMenuShortcuts
= val
;
377 void wxPyApp::SetMacAboutMenuItemId(long val
) {
379 s_macAboutMenuItemId
= val
;
384 void wxPyApp::SetMacPreferencesMenuItemId(long val
) {
386 s_macPreferencesMenuItemId
= val
;
391 void wxPyApp::SetMacExitMenuItemId(long val
) {
393 s_macExitMenuItemId
= val
;
398 void wxPyApp::SetMacHelpMenuTitleName(const wxString
& val
) {
400 s_macHelpMenuTitleName
= val
;
405 // This finishes the initialization of wxWindows and then calls the OnInit
406 // that should be present in the derived (Python) class.
407 void wxPyApp::_BootstrapApp()
409 static bool haveInitialized
= false;
412 PyObject
* retval
= NULL
;
413 PyObject
* pyint
= NULL
;
416 // Only initialize wxWidgets once
417 if (! haveInitialized
) {
419 // Get any command-line args passed to this program from the sys module
422 blocked
= wxPyBeginBlockThreads();
424 PyObject
* sysargv
= PySys_GetObject("argv");
425 PyObject
* executable
= PySys_GetObject("executable");
427 if (sysargv
!= NULL
&& executable
!= NULL
) {
428 argc
= PyList_Size(sysargv
) + 1;
429 argv
= new char*[argc
+1];
430 argv
[0] = strdup(PyString_AsString(executable
));
432 for(x
=1; x
<argc
; x
++) {
433 PyObject
*pyArg
= PyList_GetItem(sysargv
, x
-1);
434 argv
[x
] = strdup(PyString_AsString(pyArg
));
438 wxPyEndBlockThreads(blocked
);
440 // Initialize wxWidgets
441 result
= wxEntryStart(argc
, argv
);
442 // wxApp takes ownership of the argv array, don't delete it here
444 blocked
= wxPyBeginBlockThreads();
446 PyErr_SetString(PyExc_SystemError
,
447 "wxEntryStart failed, unable to initialize wxWidgets!"
449 " (Is DISPLAY set properly?)"
455 // On wxGTK the locale will be changed to match the system settings,
456 // but Python before 2.4 needs to have LC_NUMERIC set to "C" in order
457 // for the floating point conversions and such to work right.
458 #if defined(__WXGTK__) && PY_VERSION_HEX < 0x02040000
459 setlocale(LC_NUMERIC
, "C");
462 // wxSystemOptions::SetOption(wxT("mac.textcontrol-use-mlte"), 1);
464 wxPyEndBlockThreads(blocked
);
465 haveInitialized
= true;
473 // It's now ok to generate exceptions for assertion errors.
474 wxPythonApp
->SetStartupComplete(true);
477 // Call the Python wxApp's OnPreInit and OnInit functions
478 blocked
= wxPyBeginBlockThreads();
479 if (wxPyCBH_findCallback(m_myInst
, "OnPreInit")) {
480 PyObject
* method
= m_myInst
.GetLastFound();
481 PyObject
* argTuple
= PyTuple_New(0);
482 retval
= PyEval_CallObject(method
, argTuple
);
483 m_myInst
.clearRecursionGuard(method
);
489 if (wxPyCBH_findCallback(m_myInst
, "OnInit")) {
491 PyObject
* method
= m_myInst
.GetLastFound();
492 PyObject
* argTuple
= PyTuple_New(0);
493 retval
= PyEval_CallObject(method
, argTuple
);
494 m_myInst
.clearRecursionGuard(method
);
498 // Don't PyErr_Print here, let the exception in this case go back
499 // up to the wx.PyApp.__init__ scope.
502 pyint
= PyNumber_Int(retval
);
504 PyErr_SetString(PyExc_TypeError
, "OnInit should return a boolean value");
507 result
= PyInt_AS_LONG(pyint
);
510 // Is it okay if there is no OnInit? Probably so...
515 PyErr_SetString(PyExc_SystemExit
, "OnInit returned false, exiting...");
522 wxPyEndBlockThreads(blocked
);
525 //---------------------------------------------------------------------
526 //----------------------------------------------------------------------
530 static char* wxPyCopyCString(const wxChar
* src
)
532 wxWX2MBbuf buff
= (wxWX2MBbuf
)wxConvCurrent
->cWX2MB(src
);
533 size_t len
= strlen(buff
);
534 char* dest
= new char[len
+1];
540 static char* wxPyCopyCString(const char* src
) // we need a char version too
542 size_t len
= strlen(src
);
543 char* dest
= new char[len
+1];
549 static wxChar
* wxPyCopyWString(const char *src
)
551 //wxMB2WXbuf buff = wxConvCurrent->cMB2WX(src);
552 wxString
str(src
, *wxConvCurrent
);
553 return copystring(str
);
557 static wxChar
* wxPyCopyWString(const wxChar
*src
)
559 return copystring(src
);
565 inline const char* dropwx(const char* name
) {
566 if (name
[0] == 'w' && name
[1] == 'x')
572 //----------------------------------------------------------------------
574 // This function is called when the wx._core_ module is imported to do some
575 // initial setup. (Before there is a wxApp object.) The rest happens in
576 // wxPyApp::_BootstrapApp
577 void __wxPyPreStart(PyObject
* moduleDict
)
581 // wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
582 // | _CRTDBG_CHECK_ALWAYS_DF
583 // | _CRTDBG_DELAY_FREE_MEM_DF
587 #ifdef WXP_WITH_THREAD
588 #if wxPyUSE_GIL_STATE
589 PyEval_InitThreads();
591 PyEval_InitThreads();
592 wxPyTStates
= new wxPyThreadStateArray
;
593 wxPyTMutex
= new wxMutex
;
595 // Save the current (main) thread state in our array
596 PyThreadState
* tstate
= wxPyBeginAllowThreads();
597 wxPyEndAllowThreads(tstate
);
601 // Ensure that the build options in the DLL (or whatever) match this build
602 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "wxPython");
604 wxInitAllImageHandlers();
609 void __wxPyCleanup() {
610 wxPyDoingCleanup
= true;
612 wxPyDoCleanup
= false;
615 #ifdef WXP_WITH_THREAD
616 #if !wxPyUSE_GIL_STATE
619 wxPyTStates
->Empty();
627 // Save a reference to the dictionary of the wx._core module, and inject
628 // a few more things into it.
629 PyObject
* __wxPySetDictionary(PyObject
* /* self */, PyObject
* args
)
632 if (!PyArg_ParseTuple(args
, "O", &wxPython_dict
))
635 if (!PyDict_Check(wxPython_dict
)) {
636 PyErr_SetString(PyExc_TypeError
,
637 "_wxPySetDictionary must have dictionary object!");
641 if (! wxPyPtrTypeMap
)
642 wxPyPtrTypeMap
= PyDict_New();
643 PyDict_SetItemString(wxPython_dict
, "__wxPyPtrTypeMap", wxPyPtrTypeMap
);
645 // Create an exception object to use for wxASSERTions
646 wxPyAssertionError
= PyErr_NewException("wx._core.PyAssertionError",
647 PyExc_AssertionError
, NULL
);
648 PyDict_SetItemString(wxPython_dict
, "PyAssertionError", wxPyAssertionError
);
650 // Create an exception object to use when the app object hasn't been created yet
651 wxPyNoAppError
= PyErr_NewException("wx._core.PyNoAppError",
652 PyExc_RuntimeError
, NULL
);
653 PyDict_SetItemString(wxPython_dict
, "PyNoAppError", wxPyNoAppError
);
658 #define wxPlatform "__WXMOTIF__"
659 #define wxPlatName "wxMotif"
662 #define wxPlatform "__WXX11__"
663 #define wxPlatName "wxX11"
666 #define wxPlatform "__WXGTK__"
667 #define wxPlatName "wxGTK"
670 #define wxPlatform "__WXMSW__"
671 #define wxPlatName "wxMSW"
674 #define wxPlatform "__WXMAC__"
675 #define wxPlatName "wxMac"
684 // These should be deprecated in favor of the PlatformInfo tuple built below...
685 PyDict_SetItemString(wxPython_dict
, "Platform", PyString_FromString(wxPlatform
));
686 PyDict_SetItemString(wxPython_dict
, "USE_UNICODE", PyInt_FromLong(wxUSE_UNICODE
));
687 PyDict_SetItemString(wxPython_dict
, "__WXDEBUG__", PyInt_FromLong(wxdebug
));
689 // Make a tuple of strings that gives more info about the platform.
690 PyObject
* PlatInfo
= PyList_New(0);
693 #define _AddInfoString(st) \
694 obj = PyString_FromString(st); \
695 PyList_Append(PlatInfo, obj); \
698 _AddInfoString(wxPlatform
);
699 _AddInfoString(wxPlatName
);
701 _AddInfoString("unicode");
703 _AddInfoString("ansi");
707 _AddInfoString("gtk2");
709 _AddInfoString("gtk1");
713 _AddInfoString("wx-assertions-on");
715 _AddInfoString("wx-assertions-off");
717 _AddInfoString(wxPy_SWIG_VERSION
);
719 #if wxMAC_USE_CORE_GRAPHICS
720 _AddInfoString("mac-cg");
722 _AddInfoString("mac-qd");
724 #if wxMAC_USE_NATIVE_TOOLBAR
725 _AddInfoString("mac-native-tb");
727 _AddInfoString("mac-no-native-tb");
731 #undef _AddInfoString
733 PyObject
* PlatInfoTuple
= PyList_AsTuple(PlatInfo
);
735 PyDict_SetItemString(wxPython_dict
, "PlatformInfo", PlatInfoTuple
);
742 //---------------------------------------------------------------------------
744 // Check for existence of a wxApp, setting an exception if there isn't one.
745 // This doesn't need to aquire the GIL because it should only be called from
746 // an %exception before the lock is released.
748 bool wxPyCheckForApp() {
749 if (wxTheApp
!= NULL
)
752 PyErr_SetString(wxPyNoAppError
, "The wx.App object must be created first!");
757 //---------------------------------------------------------------------------
759 void wxPyUserData_dtor(wxPyUserData
* self
) {
760 if (! wxPyDoingCleanup
) {
761 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
762 Py_DECREF(self
->m_obj
);
764 wxPyEndBlockThreads(blocked
);
769 void wxPyClientData_dtor(wxPyClientData
* self
) {
770 if (! wxPyDoingCleanup
) { // Don't do it during cleanup as Python
771 // may have already garbage collected the object...
772 if (self
->m_incRef
) {
773 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
774 Py_DECREF(self
->m_obj
);
775 wxPyEndBlockThreads(blocked
);
783 // This is called when an OOR controled object is being destroyed. Although
784 // the C++ object is going away there is no way to force the Python object
785 // (and all references to it) to die too. This causes problems (crashes) in
786 // wxPython when a python shadow object attempts to call a C++ method using
787 // the now bogus pointer... So to try and prevent this we'll do a little black
788 // magic and change the class of the python instance to a class that will
789 // raise an exception for any attempt to call methods with it. See
790 // _wxPyDeadObject in _core_ex.py for the implementation of this class.
791 void wxPyOORClientData_dtor(wxPyOORClientData
* self
) {
793 static PyObject
* deadObjectClass
= NULL
;
795 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
796 if (deadObjectClass
== NULL
) {
797 deadObjectClass
= PyDict_GetItemString(wxPython_dict
, "_wxPyDeadObject");
798 // TODO: Can not wxASSERT here because inside a wxPyBeginBlock Threads,
799 // will lead to a deadlock when it tries to aquire the GIL again.
800 //wxASSERT_MSG(deadObjectClass != NULL, wxT("Can't get _wxPyDeadObject class!"));
801 Py_INCREF(deadObjectClass
);
805 // Only if there is more than one reference to the object and we are
806 // holding the OOR reference:
807 if ( !wxPyDoingCleanup
&& self
->m_obj
->ob_refcnt
> 1 && self
->m_incRef
) {
808 // bool isInstance = wxPyInstance_Check(self->m_obj);
810 //wxASSERT_MSG(isInstance, wxT("m_obj not an instance!?!?!"));
812 // Call __del__, if there is one.
813 PyObject
* func
= PyObject_GetAttrString(self
->m_obj
, "__del__");
815 PyObject
* rv
= PyObject_CallMethod(self
->m_obj
, "__del__", NULL
);
819 if (PyErr_Occurred())
820 PyErr_Clear(); // just ignore it for now
823 PyObject
* dict
= PyObject_GetAttrString(self
->m_obj
, "__dict__");
825 // Clear the instance's dictionary
828 // put the name of the old class into the instance, and then reset the
829 // class to be the dead class.
830 PyObject
* klass
= PyObject_GetAttrString(self
->m_obj
, "__class__");
831 PyObject
* name
= PyObject_GetAttrString(klass
, "__name__");
832 PyDict_SetItemString(dict
, "_name", name
);
833 PyObject_SetAttrString(self
->m_obj
, "__class__", deadObjectClass
);
834 //Py_INCREF(deadObjectClass);
840 // m_obj is DECREF'd in the base class dtor...
841 wxPyEndBlockThreads(blocked
);
845 //---------------------------------------------------------------------------
846 // Stuff used by OOR to find the right wxPython class type to return and to
850 // The pointer type map is used when the "pointer" type name generated by SWIG
851 // is not the same as the shadow class name, for example wxPyTreeCtrl
852 // vs. wxTreeCtrl. It needs to be referenced in Python as well as from C++,
853 // so we'll just make it a Python dictionary in the wx module's namespace.
854 // (See __wxSetDictionary)
855 void wxPyPtrTypeMap_Add(const char* commonName
, const char* ptrName
) {
856 if (! wxPyPtrTypeMap
)
857 wxPyPtrTypeMap
= PyDict_New();
858 PyDict_SetItemString(wxPyPtrTypeMap
,
860 PyString_FromString((char*)ptrName
));
866 PyObject
* wxPyMake_wxObject(wxObject
* source
, bool setThisOwn
, bool checkEvtHandler
) {
867 PyObject
* target
= NULL
;
868 bool isEvtHandler
= false;
869 bool isSizer
= false;
872 // If it's derived from wxEvtHandler then there may
873 // already be a pointer to a Python object that we can use
875 if (checkEvtHandler
&& wxIsKindOf(source
, wxEvtHandler
)) {
877 wxEvtHandler
* eh
= (wxEvtHandler
*)source
;
878 wxPyOORClientData
* data
= (wxPyOORClientData
*)eh
->GetClientObject();
880 target
= data
->m_obj
;
886 // Also check for wxSizer
887 if (!target
&& wxIsKindOf(source
, wxSizer
)) {
889 wxSizer
* sz
= (wxSizer
*)source
;
890 wxPyOORClientData
* data
= (wxPyOORClientData
*)sz
->GetClientObject();
892 target
= data
->m_obj
;
899 // Otherwise make it the old fashioned way by making a new shadow
900 // object and putting this pointer in it. Look up the class
901 // heirarchy until we find a class name that is located in the
903 const wxClassInfo
* info
= source
->GetClassInfo();
904 wxString name
= info
->GetClassName();
905 bool exists
= wxPyCheckSwigType(name
);
906 while (info
&& !exists
) {
907 info
= info
->GetBaseClass1();
908 name
= info
->GetClassName();
909 exists
= wxPyCheckSwigType(name
);
912 target
= wxPyConstructObject((void*)source
, name
, setThisOwn
);
913 if (target
&& isEvtHandler
)
914 ((wxEvtHandler
*)source
)->SetClientObject(new wxPyOORClientData(target
));
915 if (target
&& isSizer
)
916 ((wxSizer
*)source
)->SetClientObject(new wxPyOORClientData(target
));
918 wxString
msg(wxT("wxPython class not found for "));
919 msg
+= source
->GetClassInfo()->GetClassName();
920 PyErr_SetString(PyExc_NameError
, msg
.mbc_str());
924 } else { // source was NULL so return None.
925 Py_INCREF(Py_None
); target
= Py_None
;
931 PyObject
* wxPyMake_wxSizer(wxSizer
* source
, bool setThisOwn
) {
933 return wxPyMake_wxObject(source
, setThisOwn
);
937 //---------------------------------------------------------------------------
940 #ifdef WXP_WITH_THREAD
941 #if !wxPyUSE_GIL_STATE
944 unsigned long wxPyGetCurrentThreadId() {
945 return wxThread::GetCurrentId();
948 static wxPyThreadState gs_shutdownTState
;
951 wxPyThreadState
* wxPyGetThreadState() {
952 if (wxPyTMutex
== NULL
) // Python is shutting down...
953 return &gs_shutdownTState
;
955 unsigned long ctid
= wxPyGetCurrentThreadId();
956 wxPyThreadState
* tstate
= NULL
;
959 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
960 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
961 if (info
.tid
== ctid
) {
966 wxPyTMutex
->Unlock();
967 wxASSERT_MSG(tstate
, wxT("PyThreadState should not be NULL!"));
973 void wxPySaveThreadState(PyThreadState
* tstate
) {
974 if (wxPyTMutex
== NULL
) { // Python is shutting down, assume a single thread...
975 gs_shutdownTState
.tstate
= tstate
;
978 unsigned long ctid
= wxPyGetCurrentThreadId();
980 for(size_t i
=0; i
< wxPyTStates
->GetCount(); i
++) {
981 wxPyThreadState
& info
= wxPyTStates
->Item(i
);
982 if (info
.tid
== ctid
) {
984 if (info
.tstate
!= tstate
)
985 wxLogMessage("*** tstate mismatch!???");
987 info
.tstate
= tstate
; // allow for transient tstates
988 // Normally it will never change, but apparently COM callbacks
989 // (i.e. ActiveX controls) will (incorrectly IMHO) use a transient
990 // tstate which will then be garbage the next time we try to use
993 wxPyTMutex
->Unlock();
997 // not found, so add it...
998 wxPyTStates
->Add(new wxPyThreadState(ctid
, tstate
));
999 wxPyTMutex
->Unlock();
1007 // Calls from Python to wxWindows code are wrapped in calls to these
1010 PyThreadState
* wxPyBeginAllowThreads() {
1011 #ifdef WXP_WITH_THREAD
1012 PyThreadState
* saved
= PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS;
1013 #if !wxPyUSE_GIL_STATE
1014 wxPySaveThreadState(saved
);
1022 void wxPyEndAllowThreads(PyThreadState
* saved
) {
1023 #ifdef WXP_WITH_THREAD
1024 PyEval_RestoreThread(saved
); // Py_END_ALLOW_THREADS;
1030 // Calls from wxWindows back to Python code, or even any PyObject
1031 // manipulations, PyDECREF's and etc. are wrapped in calls to these functions:
1033 wxPyBlock_t
wxPyBeginBlockThreads() {
1034 #ifdef WXP_WITH_THREAD
1035 if (! Py_IsInitialized()) {
1036 return (wxPyBlock_t
)0;
1038 #if wxPyUSE_GIL_STATE
1039 PyGILState_STATE state
= PyGILState_Ensure();
1042 PyThreadState
*current
= _PyThreadState_Current
;
1044 // Only block if there wasn't already a tstate, or if the current one is
1045 // not the one we are wanting to change to. This should prevent deadlock
1046 // if there are nested calls to wxPyBeginBlockThreads
1047 wxPyBlock_t blocked
= false;
1048 wxPyThreadState
* tstate
= wxPyGetThreadState();
1049 if (current
!= tstate
->tstate
) {
1050 PyEval_RestoreThread(tstate
->tstate
);
1056 return (wxPyBlock_t
)0;
1061 void wxPyEndBlockThreads(wxPyBlock_t blocked
) {
1062 #ifdef WXP_WITH_THREAD
1063 if (! Py_IsInitialized()) {
1066 #if wxPyUSE_GIL_STATE
1067 PyGILState_Release(blocked
);
1069 // Only unblock if we blocked in the last call to wxPyBeginBlockThreads.
1070 // The value of blocked passed in needs to be the same as that returned
1071 // from wxPyBeginBlockThreads at the same nesting level.
1073 PyEval_SaveThread();
1080 //---------------------------------------------------------------------------
1081 // wxPyInputStream and wxPyCBInputStream methods
1084 void wxPyInputStream::close() {
1085 /* do nothing for now */
1088 void wxPyInputStream::flush() {
1089 /* do nothing for now */
1092 bool wxPyInputStream::eof() {
1094 return m_wxis
->Eof();
1099 wxPyInputStream::~wxPyInputStream() {
1107 PyObject
* wxPyInputStream::read(int size
) {
1108 PyObject
* obj
= NULL
;
1110 const int BUFSIZE
= 1024;
1112 // check if we have a real wxInputStream to work with
1114 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1115 PyErr_SetString(PyExc_IOError
, "no valid C-wxInputStream");
1116 wxPyEndBlockThreads(blocked
);
1121 // read while bytes are available on the stream
1122 while ( m_wxis
->CanRead() ) {
1123 m_wxis
->Read(buf
.GetAppendBuf(BUFSIZE
), BUFSIZE
);
1124 buf
.UngetAppendBuf(m_wxis
->LastRead());
1127 } else { // Read only size number of characters
1128 m_wxis
->Read(buf
.GetWriteBuf(size
), size
);
1129 buf
.UngetWriteBuf(m_wxis
->LastRead());
1133 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1134 wxStreamError err
= m_wxis
->GetLastError();
1135 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1136 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1139 // We use only strings for the streams, not unicode
1140 obj
= PyString_FromStringAndSize(buf
, buf
.GetDataLen());
1142 wxPyEndBlockThreads(blocked
);
1147 PyObject
* wxPyInputStream::readline(int size
) {
1148 PyObject
* obj
= NULL
;
1153 // check if we have a real wxInputStream to work with
1155 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1156 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1157 wxPyEndBlockThreads(blocked
);
1161 // read until \n or byte limit reached
1162 for (i
=ch
=0; (ch
!= '\n') && (m_wxis
->CanRead()) && ((size
< 0) || (i
< size
)); i
++) {
1163 ch
= m_wxis
->GetC();
1168 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1169 wxStreamError err
= m_wxis
->GetLastError();
1170 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1171 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1174 // We use only strings for the streams, not unicode
1175 obj
= PyString_FromStringAndSize((char*)buf
.GetData(), buf
.GetDataLen());
1177 wxPyEndBlockThreads(blocked
);
1182 PyObject
* wxPyInputStream::readlines(int sizehint
) {
1185 // check if we have a real wxInputStream to work with
1187 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1188 PyErr_SetString(PyExc_IOError
,"no valid C-wxInputStream");
1189 wxPyEndBlockThreads(blocked
);
1194 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1195 pylist
= PyList_New(0);
1196 wxPyEndBlockThreads(blocked
);
1199 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1201 wxPyEndBlockThreads(blocked
);
1205 // read sizehint bytes or until EOF
1207 for (i
=0; (m_wxis
->CanRead()) && ((sizehint
< 0) || (i
< sizehint
));) {
1208 PyObject
* s
= this->readline();
1210 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1212 wxPyEndBlockThreads(blocked
);
1215 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1216 PyList_Append(pylist
, s
);
1217 i
+= PyString_Size(s
);
1218 wxPyEndBlockThreads(blocked
);
1222 wxStreamError err
= m_wxis
->GetLastError();
1223 if (err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
) {
1224 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1226 PyErr_SetString(PyExc_IOError
,"IOError in wxInputStream");
1227 wxPyEndBlockThreads(blocked
);
1235 void wxPyInputStream::seek(int offset
, int whence
) {
1237 m_wxis
->SeekI(offset
, wxSeekMode(whence
));
1240 int wxPyInputStream::tell(){
1242 return m_wxis
->TellI();
1249 wxPyCBInputStream::wxPyCBInputStream(PyObject
*r
, PyObject
*s
, PyObject
*t
, bool block
)
1250 : wxInputStream(), m_read(r
), m_seek(s
), m_tell(t
), m_block(block
)
1253 wxPyCBInputStream::wxPyCBInputStream(const wxPyCBInputStream
& other
)
1255 m_read
= other
.m_read
;
1256 m_seek
= other
.m_seek
;
1257 m_tell
= other
.m_tell
;
1258 m_block
= other
.m_block
;
1265 wxPyCBInputStream::~wxPyCBInputStream() {
1266 wxPyBlock_t blocked
;
1267 if (m_block
) blocked
= wxPyBeginBlockThreads();
1271 if (m_block
) wxPyEndBlockThreads(blocked
);
1275 wxPyCBInputStream
* wxPyCBInputStream::create(PyObject
*py
, bool block
) {
1276 wxPyBlock_t blocked
;
1277 if (block
) blocked
= wxPyBeginBlockThreads();
1279 PyObject
* read
= getMethod(py
, "read");
1280 PyObject
* seek
= getMethod(py
, "seek");
1281 PyObject
* tell
= getMethod(py
, "tell");
1284 PyErr_SetString(PyExc_TypeError
, "Not a file-like object");
1288 if (block
) wxPyEndBlockThreads(blocked
);
1292 if (block
) wxPyEndBlockThreads(blocked
);
1293 return new wxPyCBInputStream(read
, seek
, tell
, block
);
1297 wxPyCBInputStream
* wxPyCBInputStream_create(PyObject
*py
, bool block
) {
1298 return wxPyCBInputStream::create(py
, block
);
1301 wxPyCBInputStream
* wxPyCBInputStream_copy(wxPyCBInputStream
* other
) {
1302 return new wxPyCBInputStream(*other
);
1305 PyObject
* wxPyCBInputStream::getMethod(PyObject
* py
, char* name
) {
1306 if (!PyObject_HasAttrString(py
, name
))
1308 PyObject
* o
= PyObject_GetAttrString(py
, name
);
1309 if (!PyMethod_Check(o
) && !PyCFunction_Check(o
)) {
1317 wxFileOffset
wxPyCBInputStream::GetLength() const {
1318 wxPyCBInputStream
* self
= (wxPyCBInputStream
*)this; // cast off const
1319 if (m_seek
&& m_tell
) {
1320 wxFileOffset temp
= self
->OnSysTell();
1321 wxFileOffset ret
= self
->OnSysSeek(0, wxFromEnd
);
1322 self
->OnSysSeek(temp
, wxFromStart
);
1326 return wxInvalidOffset
;
1330 size_t wxPyCBInputStream::OnSysRead(void *buffer
, size_t bufsize
) {
1334 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1335 PyObject
* arglist
= Py_BuildValue("(i)", bufsize
);
1336 PyObject
* result
= PyEval_CallObject(m_read
, arglist
);
1340 if ((result
!= NULL
) && PyString_Check(result
)) {
1341 o
= PyString_Size(result
);
1343 m_lasterror
= wxSTREAM_EOF
;
1346 memcpy((char*)buffer
, PyString_AsString(result
), o
); // strings only, not unicode...
1351 m_lasterror
= wxSTREAM_READ_ERROR
;
1352 wxPyEndBlockThreads(blocked
);
1356 size_t wxPyCBInputStream::OnSysWrite(const void *buffer
, size_t bufsize
) {
1357 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1362 wxFileOffset
wxPyCBInputStream::OnSysSeek(wxFileOffset off
, wxSeekMode mode
) {
1363 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1364 PyObject
* arglist
= PyTuple_New(2);
1366 if (sizeof(wxFileOffset
) > sizeof(long))
1367 // wxFileOffset is a 64-bit value...
1368 PyTuple_SET_ITEM(arglist
, 0, PyLong_FromLongLong(off
));
1370 PyTuple_SET_ITEM(arglist
, 0, PyInt_FromLong(off
));
1372 PyTuple_SET_ITEM(arglist
, 1, PyInt_FromLong(mode
));
1375 PyObject
* result
= PyEval_CallObject(m_seek
, arglist
);
1378 wxPyEndBlockThreads(blocked
);
1383 wxFileOffset
wxPyCBInputStream::OnSysTell() const {
1384 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1385 PyObject
* arglist
= Py_BuildValue("()");
1386 PyObject
* result
= PyEval_CallObject(m_tell
, arglist
);
1389 if (result
!= NULL
) {
1390 if (PyLong_Check(result
))
1391 o
= PyLong_AsLongLong(result
);
1393 o
= PyInt_AsLong(result
);
1396 wxPyEndBlockThreads(blocked
);
1400 //----------------------------------------------------------------------
1402 IMPLEMENT_ABSTRACT_CLASS(wxPyCallback
, wxObject
);
1404 wxPyCallback::wxPyCallback(PyObject
* func
) {
1409 wxPyCallback::wxPyCallback(const wxPyCallback
& other
) {
1410 m_func
= other
.m_func
;
1414 wxPyCallback::~wxPyCallback() {
1415 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1417 wxPyEndBlockThreads(blocked
);
1421 #define wxPy_PRECALLINIT "_preCallInit"
1422 #define wxPy_POSTCALLCLEANUP "_postCallCleanup"
1424 // This function is used for all events destined for Python event handlers.
1425 void wxPyCallback::EventThunker(wxEvent
& event
) {
1426 wxPyCallback
* cb
= (wxPyCallback
*)event
.m_callbackUserData
;
1427 PyObject
* func
= cb
->m_func
;
1431 bool checkSkip
= false;
1433 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1434 wxString className
= event
.GetClassInfo()->GetClassName();
1436 // If the event is one of these types then pass the original
1437 // event object instead of the one passed to us.
1438 if ( className
== wxT("wxPyEvent") ) {
1439 arg
= ((wxPyEvent
*)&event
)->GetSelf();
1440 checkSkip
= ((wxPyEvent
*)&event
)->GetCloned();
1442 else if ( className
== wxT("wxPyCommandEvent") ) {
1443 arg
= ((wxPyCommandEvent
*)&event
)->GetSelf();
1444 checkSkip
= ((wxPyCommandEvent
*)&event
)->GetCloned();
1447 arg
= wxPyConstructObject((void*)&event
, className
);
1453 // "intern" the pre/post method names to speed up the HasAttr
1454 static PyObject
* s_preName
= NULL
;
1455 static PyObject
* s_postName
= NULL
;
1456 if (s_preName
== NULL
) {
1457 s_preName
= PyString_FromString(wxPy_PRECALLINIT
);
1458 s_postName
= PyString_FromString(wxPy_POSTCALLCLEANUP
);
1461 // Check if the event object needs some preinitialization
1462 if (PyObject_HasAttr(arg
, s_preName
)) {
1463 result
= PyObject_CallMethodObjArgs(arg
, s_preName
, arg
, NULL
);
1465 Py_DECREF(result
); // result is ignored, but we still need to decref it
1466 PyErr_Clear(); // Just in case...
1472 // Call the event handler, passing the event object
1473 tuple
= PyTuple_New(1);
1474 PyTuple_SET_ITEM(tuple
, 0, arg
); // steals ref to arg
1475 result
= PyEval_CallObject(func
, tuple
);
1477 Py_DECREF(result
); // result is ignored, but we still need to decref it
1478 PyErr_Clear(); // Just in case...
1483 // Check if the event object needs some post cleanup
1484 if (PyObject_HasAttr(arg
, s_postName
)) {
1485 result
= PyObject_CallMethodObjArgs(arg
, s_postName
, arg
, NULL
);
1487 Py_DECREF(result
); // result is ignored, but we still need to decref it
1488 PyErr_Clear(); // Just in case...
1495 // if the event object was one of our special types and
1496 // it had been cloned, then we need to extract the Skipped
1497 // value from the original and set it in the clone.
1498 result
= PyObject_CallMethod(arg
, "GetSkipped", "");
1500 event
.Skip(PyInt_AsLong(result
));
1508 wxPyEndBlockThreads(blocked
);
1512 //----------------------------------------------------------------------
1514 wxPyCallbackHelper::wxPyCallbackHelper(const wxPyCallbackHelper
& other
) {
1516 m_self
= other
.m_self
;
1517 m_class
= other
.m_class
;
1525 void wxPyCallbackHelper::setSelf(PyObject
* self
, PyObject
* klass
, int incref
) {
1536 #if PYTHON_API_VERSION >= 1011
1538 // Prior to Python 2.2 PyMethod_GetClass returned the class object
1539 // in which the method was defined. Starting with 2.2 it returns
1540 // "class that asked for the method" which seems totally bogus to me
1541 // but apprently it fixes some obscure problem waiting to happen in
1542 // Python. Since the API was not documented Guido and the gang felt
1543 // safe in changing it. Needless to say that totally screwed up the
1544 // logic below in wxPyCallbackHelper::findCallback, hence this icky
1545 // code to find the class where the method is actually defined...
1548 PyObject
* PyFindClassWithAttr(PyObject
*klass
, PyObject
*name
)
1552 if (PyType_Check(klass
)) { // new style classes
1553 // This code is borrowed/adapted from _PyType_Lookup in typeobject.c
1554 PyTypeObject
* type
= (PyTypeObject
*)klass
;
1555 PyObject
*mro
, *res
, *base
, *dict
;
1556 /* Look in tp_dict of types in MRO */
1558 assert(PyTuple_Check(mro
));
1559 n
= PyTuple_GET_SIZE(mro
);
1560 for (i
= 0; i
< n
; i
++) {
1561 base
= PyTuple_GET_ITEM(mro
, i
);
1562 if (PyClass_Check(base
))
1563 dict
= ((PyClassObject
*)base
)->cl_dict
;
1565 assert(PyType_Check(base
));
1566 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1568 assert(dict
&& PyDict_Check(dict
));
1569 res
= PyDict_GetItem(dict
, name
);
1576 else if (PyClass_Check(klass
)) { // old style classes
1577 // This code is borrowed/adapted from class_lookup in classobject.c
1578 PyClassObject
* cp
= (PyClassObject
*)klass
;
1579 PyObject
*value
= PyDict_GetItem(cp
->cl_dict
, name
);
1580 if (value
!= NULL
) {
1581 return (PyObject
*)cp
;
1583 n
= PyTuple_Size(cp
->cl_bases
);
1584 for (i
= 0; i
< n
; i
++) {
1585 PyObject
* base
= PyTuple_GetItem(cp
->cl_bases
, i
);
1586 PyObject
*v
= PyFindClassWithAttr(base
, name
);
1598 PyObject
* PyMethod_GetDefiningClass(PyObject
* method
, PyObject
* nameo
)
1600 PyObject
* mgc
= PyMethod_GET_CLASS(method
);
1602 #if PYTHON_API_VERSION <= 1010 // prior to Python 2.2, the easy way
1604 #else // 2.2 and after, the hard way...
1605 return PyFindClassWithAttr(mgc
, nameo
);
1611 // To avoid recursion when an overridden virtual method wants to call the base
1612 // class version, temporarily set an attribute in the instance with the same
1613 // name as the method. Then the PyObject_GetAttr in the next findCallback
1614 // will return this attribute and the PyMethod_Check will fail.
1616 void wxPyCallbackHelper::setRecursionGuard(PyObject
* method
) const
1618 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1619 PyObject_SetAttr(m_self
, func
->func_name
, Py_None
);
1622 void wxPyCallbackHelper::clearRecursionGuard(PyObject
* method
) const
1624 PyFunctionObject
* func
= (PyFunctionObject
*)PyMethod_Function(method
);
1625 if (PyObject_HasAttr(m_self
, func
->func_name
)) {
1626 PyObject_DelAttr(m_self
, func
->func_name
);
1630 // bool wxPyCallbackHelper::hasRecursionGuard(PyObject* method) const
1632 // PyFunctionObject* func = (PyFunctionObject*)PyMethod_Function(method);
1633 // if (PyObject_HasAttr(m_self, func->func_name)) {
1634 // PyObject* attr = PyObject_GetAttr(m_self, func->func_name);
1635 // bool retval = (attr == Py_None);
1643 bool wxPyCallbackHelper::findCallback(const char* name
, bool setGuard
) const {
1644 wxPyCallbackHelper
* self
= (wxPyCallbackHelper
*)this; // cast away const
1645 PyObject
*method
, *klass
;
1646 PyObject
* nameo
= PyString_FromString(name
);
1647 self
->m_lastFound
= NULL
;
1649 // If the object (m_self) has an attibute of the given name...
1650 if (m_self
&& PyObject_HasAttr(m_self
, nameo
)) {
1651 method
= PyObject_GetAttr(m_self
, nameo
);
1653 // ...and if that attribute is a method, and if that method's class is
1654 // not from the registered class or a base class...
1655 if (PyMethod_Check(method
) &&
1656 (klass
= PyMethod_GetDefiningClass(method
, nameo
)) != NULL
&&
1657 (klass
!= m_class
) &&
1658 PyObject_IsSubclass(klass
, m_class
)) {
1660 // ...then we'll save a pointer to the method so callCallback can
1661 // call it. But first, set a recursion guard in case the
1662 // overridden method wants to call the base class version.
1664 setRecursionGuard(method
);
1665 self
->m_lastFound
= method
;
1673 return m_lastFound
!= NULL
;
1677 int wxPyCallbackHelper::callCallback(PyObject
* argTuple
) const {
1681 result
= callCallbackObj(argTuple
);
1682 if (result
) { // Assumes an integer return type...
1683 retval
= PyInt_AsLong(result
);
1685 PyErr_Clear(); // forget about it if it's not...
1690 // Invoke the Python callable object, returning the raw PyObject return
1691 // value. Caller should DECREF the return value and also manage the GIL.
1692 PyObject
* wxPyCallbackHelper::callCallbackObj(PyObject
* argTuple
) const {
1695 // Save a copy of the pointer in case the callback generates another
1696 // callback. In that case m_lastFound will have a different value when
1697 // it gets back here...
1698 PyObject
* method
= m_lastFound
;
1700 result
= PyEval_CallObject(method
, argTuple
);
1701 clearRecursionGuard(method
);
1703 Py_DECREF(argTuple
);
1712 void wxPyCBH_setCallbackInfo(wxPyCallbackHelper
& cbh
, PyObject
* self
, PyObject
* klass
, int incref
) {
1713 cbh
.setSelf(self
, klass
, incref
);
1716 bool wxPyCBH_findCallback(const wxPyCallbackHelper
& cbh
, const char* name
, bool setGuard
) {
1717 return cbh
.findCallback(name
, setGuard
);
1720 int wxPyCBH_callCallback(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1721 return cbh
.callCallback(argTuple
);
1724 PyObject
* wxPyCBH_callCallbackObj(const wxPyCallbackHelper
& cbh
, PyObject
* argTuple
) {
1725 return cbh
.callCallbackObj(argTuple
);
1729 void wxPyCBH_delete(wxPyCallbackHelper
* cbh
) {
1730 if (cbh
->m_incRef
) {
1731 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1732 Py_XDECREF(cbh
->m_self
);
1733 Py_XDECREF(cbh
->m_class
);
1734 wxPyEndBlockThreads(blocked
);
1738 //---------------------------------------------------------------------------
1739 //---------------------------------------------------------------------------
1740 // These event classes can be derived from in Python and passed through the event
1741 // system without losing anything. They do this by keeping a reference to
1742 // themselves and some special case handling in wxPyCallback::EventThunker.
1745 wxPyEvtSelfRef::wxPyEvtSelfRef() {
1746 //m_self = Py_None; // **** We don't do normal ref counting to prevent
1747 //Py_INCREF(m_self); // circular loops...
1751 wxPyEvtSelfRef::~wxPyEvtSelfRef() {
1752 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1755 wxPyEndBlockThreads(blocked
);
1758 void wxPyEvtSelfRef::SetSelf(PyObject
* self
, bool clone
) {
1759 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1767 wxPyEndBlockThreads(blocked
);
1770 PyObject
* wxPyEvtSelfRef::GetSelf() const {
1776 IMPLEMENT_ABSTRACT_CLASS(wxPyEvent
, wxEvent
);
1777 IMPLEMENT_ABSTRACT_CLASS(wxPyCommandEvent
, wxCommandEvent
);
1780 wxPyEvent::wxPyEvent(int winid
, wxEventType commandType
)
1781 : wxEvent(winid
, commandType
) {
1785 wxPyEvent::wxPyEvent(const wxPyEvent
& evt
)
1788 SetSelf(evt
.m_self
, true);
1792 wxPyEvent::~wxPyEvent() {
1796 wxPyCommandEvent::wxPyCommandEvent(wxEventType commandType
, int id
)
1797 : wxCommandEvent(commandType
, id
) {
1801 wxPyCommandEvent::wxPyCommandEvent(const wxPyCommandEvent
& evt
)
1802 : wxCommandEvent(evt
)
1804 SetSelf(evt
.m_self
, true);
1808 wxPyCommandEvent::~wxPyCommandEvent() {
1815 //---------------------------------------------------------------------------
1816 //---------------------------------------------------------------------------
1817 // Convert a wxList to a Python List, only works for lists of wxObjects
1819 PyObject
* wxPy_ConvertList(wxListBase
* listbase
) {
1820 wxList
* list
= (wxList
*)listbase
; // this is probably bad...
1824 wxNode
* node
= list
->GetFirst();
1826 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
1827 pyList
= PyList_New(0);
1829 wxObj
= node
->GetData();
1830 pyObj
= wxPyMake_wxObject(wxObj
,false);
1831 PyList_Append(pyList
, pyObj
);
1832 node
= node
->GetNext();
1834 wxPyEndBlockThreads(blocked
);
1838 //----------------------------------------------------------------------
1840 long wxPyGetWinHandle(wxWindow
* win
) {
1843 return (long)win
->GetHandle();
1846 #if defined(__WXGTK__) || defined(__WXX11)
1847 return (long)GetXWindow(win
);
1851 //return (long)MAC_WXHWND(win->MacGetTopLevelWindowRef());
1852 return (long)win
->GetHandle();
1858 //----------------------------------------------------------------------
1859 // Some helper functions for typemaps in my_typemaps.i, so they won't be
1860 // included in every file over and over again...
1862 wxString
* wxString_in_helper(PyObject
* source
) {
1863 wxString
* target
= NULL
;
1865 if (!PyString_Check(source
) && !PyUnicode_Check(source
)) {
1866 PyErr_SetString(PyExc_TypeError
, "String or Unicode type required");
1870 PyObject
* uni
= source
;
1871 if (PyString_Check(source
)) {
1872 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1873 if (PyErr_Occurred()) return NULL
;
1875 target
= new wxString();
1876 size_t len
= PyUnicode_GET_SIZE(uni
);
1878 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
->GetWriteBuf(len
), len
);
1879 target
->UngetWriteBuf(len
);
1882 if (PyString_Check(source
))
1885 // Convert to a string object if it isn't already, then to wxString
1886 PyObject
* str
= source
;
1887 if (PyUnicode_Check(source
)) {
1888 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1889 if (PyErr_Occurred()) return NULL
;
1891 else if (!PyString_Check(source
)) {
1892 str
= PyObject_Str(source
);
1893 if (PyErr_Occurred()) return NULL
;
1895 char* tmpPtr
; Py_ssize_t tmpSize
;
1896 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1897 target
= new wxString(tmpPtr
, tmpSize
);
1899 if (!PyString_Check(source
))
1901 #endif // wxUSE_UNICODE
1907 // Similar to above except doesn't use "new" and doesn't set an exception
1908 wxString
Py2wxString(PyObject
* source
)
1913 // Convert to a unicode object, if not already, then to a wxString
1914 PyObject
* uni
= source
;
1915 if (!PyUnicode_Check(source
)) {
1916 uni
= PyUnicode_FromEncodedObject(source
, wxPyDefaultEncoding
, "strict");
1917 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1919 size_t len
= PyUnicode_GET_SIZE(uni
);
1921 PyUnicode_AsWideChar((PyUnicodeObject
*)uni
, target
.GetWriteBuf(len
), len
);
1922 target
.UngetWriteBuf();
1925 if (!PyUnicode_Check(source
))
1928 // Convert to a string object if it isn't already, then to wxString
1929 PyObject
* str
= source
;
1930 if (PyUnicode_Check(source
)) {
1931 str
= PyUnicode_AsEncodedString(source
, wxPyDefaultEncoding
, "strict");
1932 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1934 else if (!PyString_Check(source
)) {
1935 str
= PyObject_Str(source
);
1936 if (PyErr_Occurred()) return wxEmptyString
; // TODO: should we PyErr_Clear?
1938 char* tmpPtr
; Py_ssize_t tmpSize
;
1939 PyString_AsStringAndSize(str
, &tmpPtr
, &tmpSize
);
1940 target
= wxString(tmpPtr
, tmpSize
);
1942 if (!PyString_Check(source
))
1944 #endif // wxUSE_UNICODE
1950 // Make either a Python String or Unicode object, depending on build mode
1951 PyObject
* wx2PyString(const wxString
& src
)
1955 str
= PyUnicode_FromWideChar(src
.c_str(), src
.Len());
1957 str
= PyString_FromStringAndSize(src
.c_str(), src
.Len());
1964 void wxSetDefaultPyEncoding(const char* encoding
)
1966 strncpy(wxPyDefaultEncoding
, encoding
, DEFAULTENCODING_SIZE
);
1969 const char* wxGetDefaultPyEncoding()
1971 return wxPyDefaultEncoding
;
1974 //----------------------------------------------------------------------
1977 byte
* byte_LIST_helper(PyObject
* source
) {
1978 if (!PyList_Check(source
)) {
1979 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
1982 int count
= PyList_Size(source
);
1983 byte
* temp
= new byte
[count
];
1985 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
1988 for (int x
=0; x
<count
; x
++) {
1989 PyObject
* o
= PyList_GetItem(source
, x
);
1990 if (! PyInt_Check(o
)) {
1991 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
1994 temp
[x
] = (byte
)PyInt_AsLong(o
);
2000 int* int_LIST_helper(PyObject
* source
) {
2001 if (!PyList_Check(source
)) {
2002 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2005 int count
= PyList_Size(source
);
2006 int* temp
= new int[count
];
2008 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2011 for (int x
=0; x
<count
; x
++) {
2012 PyObject
* o
= PyList_GetItem(source
, x
);
2013 if (! PyInt_Check(o
)) {
2014 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2017 temp
[x
] = PyInt_AsLong(o
);
2023 long* long_LIST_helper(PyObject
* source
) {
2024 if (!PyList_Check(source
)) {
2025 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2028 int count
= PyList_Size(source
);
2029 long* temp
= new long[count
];
2031 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2034 for (int x
=0; x
<count
; x
++) {
2035 PyObject
* o
= PyList_GetItem(source
, x
);
2036 if (! PyInt_Check(o
)) {
2037 PyErr_SetString(PyExc_TypeError
, "Expected a list of integers.");
2040 temp
[x
] = PyInt_AsLong(o
);
2046 char** string_LIST_helper(PyObject
* source
) {
2047 if (!PyList_Check(source
)) {
2048 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2051 int count
= PyList_Size(source
);
2052 char** temp
= new char*[count
];
2054 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2057 for (int x
=0; x
<count
; x
++) {
2058 PyObject
* o
= PyList_GetItem(source
, x
);
2059 if (! PyString_Check(o
)) {
2060 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2063 temp
[x
] = PyString_AsString(o
);
2068 //--------------------------------
2069 // Part of patch from Tim Hochberg
2070 static inline bool wxPointFromObjects(PyObject
* o1
, PyObject
* o2
, wxPoint
* point
) {
2071 if (PyInt_Check(o1
) && PyInt_Check(o2
)) {
2072 point
->x
= PyInt_AS_LONG(o1
);
2073 point
->y
= PyInt_AS_LONG(o2
);
2076 if (PyFloat_Check(o1
) && PyFloat_Check(o2
)) {
2077 point
->x
= (int)PyFloat_AS_DOUBLE(o1
);
2078 point
->y
= (int)PyFloat_AS_DOUBLE(o2
);
2081 if (wxPySwigInstance_Check(o1
) || wxPySwigInstance_Check(o2
)) { // TODO: Why???
2082 // Disallow instances because they can cause havok
2085 if (PyNumber_Check(o1
) && PyNumber_Check(o2
)) {
2086 // I believe this excludes instances, so this should be safe without INCREFFing o1 and o2
2087 point
->x
= PyInt_AsLong(o1
);
2088 point
->y
= PyInt_AsLong(o2
);
2095 wxPoint
* wxPoint_LIST_helper(PyObject
* source
, int *count
) {
2096 // Putting all of the declarations here allows
2097 // us to put the error handling all in one place.
2100 PyObject
*o
, *o1
, *o2
;
2101 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2103 if (!PySequence_Check(source
)) {
2107 // The length of the sequence is returned in count.
2108 *count
= PySequence_Length(source
);
2113 temp
= new wxPoint
[*count
];
2115 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2118 for (x
=0; x
<*count
; x
++) {
2119 // Get an item: try fast way first.
2121 o
= PySequence_Fast_GET_ITEM(source
, x
);
2124 o
= PySequence_GetItem(source
, x
);
2130 // Convert o to wxPoint.
2131 if ((PyTuple_Check(o
) && PyTuple_GET_SIZE(o
) == 2) ||
2132 (PyList_Check(o
) && PyList_GET_SIZE(o
) == 2)) {
2133 o1
= PySequence_Fast_GET_ITEM(o
, 0);
2134 o2
= PySequence_Fast_GET_ITEM(o
, 1);
2135 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2139 else if (wxPySwigInstance_Check(o
)) {
2141 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPoint"))) {
2146 else if (PySequence_Check(o
) && PySequence_Length(o
) == 2) {
2147 o1
= PySequence_GetItem(o
, 0);
2148 o2
= PySequence_GetItem(o
, 1);
2149 if (!wxPointFromObjects(o1
, o2
, &temp
[x
])) {
2173 PyErr_SetString(PyExc_TypeError
, "Expected a sequence of length-2 sequences or wxPoints.");
2177 //------------------------------
2180 wxBitmap
** wxBitmap_LIST_helper(PyObject
* source
) {
2181 if (!PyList_Check(source
)) {
2182 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2185 int count
= PyList_Size(source
);
2186 wxBitmap
** temp
= new wxBitmap
*[count
];
2188 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2191 for (int x
=0; x
<count
; x
++) {
2192 PyObject
* o
= PyList_GetItem(source
, x
);
2193 if (wxPySwigInstance_Check(o
)) {
2195 if (! wxPyConvertSwigPtr(o
, (void **) &pt
, wxT("wxBitmap"))) {
2196 PyErr_SetString(PyExc_TypeError
,"Expected wxBitmap.");
2202 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxBitmaps.");
2211 wxString
* wxString_LIST_helper(PyObject
* source
) {
2212 if (!PyList_Check(source
)) {
2213 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2216 int count
= PyList_Size(source
);
2217 wxString
* temp
= new wxString
[count
];
2219 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2222 for (int x
=0; x
<count
; x
++) {
2223 PyObject
* o
= PyList_GetItem(source
, x
);
2224 #if PYTHON_API_VERSION >= 1009
2225 if (! PyString_Check(o
) && ! PyUnicode_Check(o
)) {
2226 PyErr_SetString(PyExc_TypeError
, "Expected a list of string or unicode objects.");
2230 if (! PyString_Check(o
)) {
2231 PyErr_SetString(PyExc_TypeError
, "Expected a list of strings.");
2236 wxString
* pStr
= wxString_in_helper(o
);
2244 wxAcceleratorEntry
* wxAcceleratorEntry_LIST_helper(PyObject
* source
) {
2245 if (!PyList_Check(source
)) {
2246 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2249 int count
= PyList_Size(source
);
2250 wxAcceleratorEntry
* temp
= new wxAcceleratorEntry
[count
];
2252 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2255 for (int x
=0; x
<count
; x
++) {
2256 PyObject
* o
= PyList_GetItem(source
, x
);
2257 if (wxPySwigInstance_Check(o
)) {
2258 wxAcceleratorEntry
* ae
;
2259 if (! wxPyConvertSwigPtr(o
, (void **) &ae
, wxT("wxAcceleratorEntry"))) {
2260 PyErr_SetString(PyExc_TypeError
,"Expected wxAcceleratorEntry.");
2265 else if (PyTuple_Check(o
)) {
2266 PyObject
* o1
= PyTuple_GetItem(o
, 0);
2267 PyObject
* o2
= PyTuple_GetItem(o
, 1);
2268 PyObject
* o3
= PyTuple_GetItem(o
, 2);
2269 temp
[x
].Set(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2272 PyErr_SetString(PyExc_TypeError
, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
2280 wxPen
** wxPen_LIST_helper(PyObject
* source
) {
2281 if (!PyList_Check(source
)) {
2282 PyErr_SetString(PyExc_TypeError
, "Expected a list object.");
2285 int count
= PyList_Size(source
);
2286 wxPen
** temp
= new wxPen
*[count
];
2288 PyErr_SetString(PyExc_MemoryError
, "Unable to allocate temporary array");
2291 for (int x
=0; x
<count
; x
++) {
2292 PyObject
* o
= PyList_GetItem(source
, x
);
2293 if (wxPySwigInstance_Check(o
)) {
2295 if (! wxPyConvertSwigPtr(o
, (void **)&pt
, wxT("wxPen"))) {
2297 PyErr_SetString(PyExc_TypeError
,"Expected wxPen.");
2304 PyErr_SetString(PyExc_TypeError
, "Expected a list of wxPens.");
2312 bool wxPy2int_seq_helper(PyObject
* source
, int* i1
, int* i2
) {
2313 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2316 if (!PySequence_Check(source
) || PySequence_Length(source
) != 2)
2320 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2321 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2324 o1
= PySequence_GetItem(source
, 0);
2325 o2
= PySequence_GetItem(source
, 1);
2328 *i1
= PyInt_AsLong(o1
);
2329 *i2
= PyInt_AsLong(o2
);
2339 bool wxPy4int_seq_helper(PyObject
* source
, int* i1
, int* i2
, int* i3
, int* i4
) {
2340 bool isFast
= PyList_Check(source
) || PyTuple_Check(source
);
2341 PyObject
*o1
, *o2
, *o3
, *o4
;
2343 if (!PySequence_Check(source
) || PySequence_Length(source
) != 4)
2347 o1
= PySequence_Fast_GET_ITEM(source
, 0);
2348 o2
= PySequence_Fast_GET_ITEM(source
, 1);
2349 o3
= PySequence_Fast_GET_ITEM(source
, 2);
2350 o4
= PySequence_Fast_GET_ITEM(source
, 3);
2353 o1
= PySequence_GetItem(source
, 0);
2354 o2
= PySequence_GetItem(source
, 1);
2355 o3
= PySequence_GetItem(source
, 2);
2356 o4
= PySequence_GetItem(source
, 3);
2359 *i1
= PyInt_AsLong(o1
);
2360 *i2
= PyInt_AsLong(o2
);
2361 *i3
= PyInt_AsLong(o3
);
2362 *i4
= PyInt_AsLong(o4
);
2374 //----------------------------------------------------------------------
2376 bool wxPySimple_typecheck(PyObject
* source
, const wxChar
* classname
, int seqLen
)
2380 if (wxPySwigInstance_Check(source
) &&
2381 wxPyConvertSwigPtr(source
, (void **)&ptr
, classname
))
2385 if (PySequence_Check(source
) && PySequence_Length(source
) == seqLen
)
2391 bool wxSize_helper(PyObject
* source
, wxSize
** obj
)
2393 if (source
== Py_None
) {
2394 **obj
= wxSize(-1,-1);
2397 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxSize"));
2401 bool wxPoint_helper(PyObject
* source
, wxPoint
** obj
)
2403 if (source
== Py_None
) {
2404 **obj
= wxPoint(-1,-1);
2407 return wxPyTwoIntItem_helper(source
, obj
, wxT("wxPoint"));
2412 bool wxRealPoint_helper(PyObject
* source
, wxRealPoint
** obj
) {
2414 if (source
== Py_None
) {
2415 **obj
= wxRealPoint(-1,-1);
2419 // If source is an object instance then it may already be the right type
2420 if (wxPySwigInstance_Check(source
)) {
2422 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRealPoint")))
2427 // otherwise a 2-tuple of floats is expected
2428 else if (PySequence_Check(source
) && PyObject_Length(source
) == 2) {
2429 PyObject
* o1
= PySequence_GetItem(source
, 0);
2430 PyObject
* o2
= PySequence_GetItem(source
, 1);
2431 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2436 **obj
= wxRealPoint(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2443 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxRealPoint object.");
2449 bool wxRect_helper(PyObject
* source
, wxRect
** obj
) {
2451 if (source
== Py_None
) {
2452 **obj
= wxRect(-1,-1,-1,-1);
2456 // If source is an object instance then it may already be the right type
2457 if (wxPySwigInstance_Check(source
)) {
2459 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxRect")))
2464 // otherwise a 4-tuple of integers is expected
2465 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2466 PyObject
* o1
= PySequence_GetItem(source
, 0);
2467 PyObject
* o2
= PySequence_GetItem(source
, 1);
2468 PyObject
* o3
= PySequence_GetItem(source
, 2);
2469 PyObject
* o4
= PySequence_GetItem(source
, 3);
2470 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) ||
2471 !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2478 **obj
= wxRect(PyInt_AsLong(o1
), PyInt_AsLong(o2
),
2479 PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2488 PyErr_SetString(PyExc_TypeError
, "Expected a 4-tuple of integers or a wxRect object.");
2494 bool wxColour_helper(PyObject
* source
, wxColour
** obj
) {
2496 if (source
== Py_None
) {
2497 **obj
= wxNullColour
;
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("wxColour")))
2509 // otherwise check for a string
2510 else if (PyString_Check(source
) || PyUnicode_Check(source
)) {
2511 wxString spec
= Py2wxString(source
);
2512 if (spec
.GetChar(0) == '#' && spec
.Length() == 7) { // It's #RRGGBB
2513 long red
, green
, blue
;
2514 red
= green
= blue
= 0;
2515 spec
.Mid(1,2).ToLong(&red
, 16);
2516 spec
.Mid(3,2).ToLong(&green
, 16);
2517 spec
.Mid(5,2).ToLong(&blue
, 16);
2519 **obj
= wxColour(red
, green
, blue
);
2522 else { // it's a colour name
2523 **obj
= wxColour(spec
);
2527 // last chance: 3-tuple or 4-tuple of integers is expected
2528 else if (PySequence_Check(source
) && PyObject_Length(source
) == 3) {
2529 PyObject
* o1
= PySequence_GetItem(source
, 0);
2530 PyObject
* o2
= PySequence_GetItem(source
, 1);
2531 PyObject
* o3
= PySequence_GetItem(source
, 2);
2532 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
)) {
2538 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
));
2544 else if (PySequence_Check(source
) && PyObject_Length(source
) == 4) {
2545 PyObject
* o1
= PySequence_GetItem(source
, 0);
2546 PyObject
* o2
= PySequence_GetItem(source
, 1);
2547 PyObject
* o3
= PySequence_GetItem(source
, 2);
2548 PyObject
* o4
= PySequence_GetItem(source
, 3);
2549 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
) || !PyNumber_Check(o3
) || !PyNumber_Check(o4
)) {
2556 **obj
= wxColour(PyInt_AsLong(o1
), PyInt_AsLong(o2
), PyInt_AsLong(o3
), PyInt_AsLong(o4
));
2565 PyErr_SetString(PyExc_TypeError
,
2566 "Expected a wxColour object, a string containing a colour name or '#RRGGBB', or a 3- or 4-tuple of integers.");
2571 bool wxColour_typecheck(PyObject
* source
) {
2573 if (wxPySimple_typecheck(source
, wxT("wxColour"), 3))
2576 if (PyString_Check(source
) || PyUnicode_Check(source
))
2584 bool wxPoint2D_helper(PyObject
* source
, wxPoint2D
** obj
) {
2586 if (source
== Py_None
) {
2587 **obj
= wxPoint2D(-1,-1);
2591 // If source is an object instance then it may already be the right type
2592 if (wxPySwigInstance_Check(source
)) {
2594 if (! wxPyConvertSwigPtr(source
, (void **)&ptr
, wxT("wxPoint2D")))
2599 // otherwise a length-2 sequence of floats is expected
2600 if (PySequence_Check(source
) && PySequence_Length(source
) == 2) {
2601 PyObject
* o1
= PySequence_GetItem(source
, 0);
2602 PyObject
* o2
= PySequence_GetItem(source
, 1);
2603 // This should really check for floats, not numbers -- but that would break code.
2604 if (!PyNumber_Check(o1
) || !PyNumber_Check(o2
)) {
2609 **obj
= wxPoint2D(PyFloat_AsDouble(o1
), PyFloat_AsDouble(o2
));
2615 PyErr_SetString(PyExc_TypeError
, "Expected a 2-tuple of floats or a wxPoint2D object.");
2620 //----------------------------------------------------------------------
2622 PyObject
* wxArrayString2PyList_helper(const wxArrayString
& arr
) {
2624 PyObject
* list
= PyList_New(0);
2625 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2627 PyObject
* str
= PyUnicode_FromWideChar(arr
[i
].c_str(), arr
[i
].Len());
2629 PyObject
* str
= PyString_FromStringAndSize(arr
[i
].c_str(), arr
[i
].Len());
2631 PyList_Append(list
, str
);
2638 PyObject
* wxArrayInt2PyList_helper(const wxArrayInt
& arr
) {
2640 PyObject
* list
= PyList_New(0);
2641 for (size_t i
=0; i
< arr
.GetCount(); i
++) {
2642 PyObject
* number
= PyInt_FromLong(arr
[i
]);
2643 PyList_Append(list
, number
);
2650 //----------------------------------------------------------------------
2651 // wxPyImageHandler methods
2653 // TODO: Switch these to use wxPython's standard macros and helper classes
2654 // for calling callbacks.
2656 PyObject
* wxPyImageHandler::m_DoCanRead_Name
= NULL
;
2657 PyObject
* wxPyImageHandler::m_GetImageCount_Name
= NULL
;
2658 PyObject
* wxPyImageHandler::m_LoadFile_Name
= NULL
;
2659 PyObject
* wxPyImageHandler::m_SaveFile_Name
= NULL
;
2661 PyObject
* wxPyImageHandler::py_InputStream(wxInputStream
* stream
) {
2662 return wxPyConstructObject(new wxPyInputStream(stream
),
2663 wxT("wxPyInputStream"), 0);
2666 PyObject
* wxPyImageHandler::py_Image(wxImage
* image
) {
2667 return wxPyConstructObject(image
, wxT("wxImage"), 0);
2670 PyObject
* wxPyImageHandler::py_OutputStream(wxOutputStream
* stream
) {
2671 return wxPyConstructObject(stream
, wxT("wxOutputStream"), 0);
2674 wxPyImageHandler::wxPyImageHandler():
2677 if (!m_DoCanRead_Name
) {
2678 m_DoCanRead_Name
= PyString_FromString("DoCanRead");
2679 m_GetImageCount_Name
= PyString_FromString("GetImageCount");
2680 m_LoadFile_Name
= PyString_FromString("LoadFile");
2681 m_SaveFile_Name
= PyString_FromString("SaveFile");
2685 wxPyImageHandler::~wxPyImageHandler() {
2692 void wxPyImageHandler::_SetSelf(PyObject
*self
) {
2693 // should check here for isinstance(PyImageHandler) ??
2698 bool wxPyImageHandler::DoCanRead(wxInputStream
& stream
) {
2699 // check if our object has this method
2700 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2701 if (!m_self
|| !PyObject_HasAttr(m_self
, m_DoCanRead_Name
)) {
2702 wxPyEndBlockThreads(blocked
);
2706 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_DoCanRead_Name
,
2707 py_InputStream(&stream
), NULL
);
2708 bool retval
= false;
2710 retval
= PyInt_AsLong(res
);
2716 wxPyEndBlockThreads(blocked
);
2720 bool wxPyImageHandler::LoadFile( wxImage
* image
, wxInputStream
& stream
,
2721 bool verbose
, int index
) {
2722 // check if our object has this method
2723 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2724 if (!m_self
|| !PyObject_HasAttr(m_self
, m_LoadFile_Name
)) {
2725 wxPyEndBlockThreads(blocked
);
2728 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_LoadFile_Name
,
2730 py_InputStream(&stream
),
2731 PyInt_FromLong(verbose
),
2732 PyInt_FromLong(index
),
2734 bool retval
= false;
2736 retval
= PyInt_AsLong(res
);
2741 wxPyEndBlockThreads(blocked
);
2745 bool wxPyImageHandler::SaveFile( wxImage
* image
, wxOutputStream
& stream
,
2747 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2748 if (!m_self
|| !PyObject_HasAttr(m_self
, m_SaveFile_Name
)) {
2749 wxPyEndBlockThreads(blocked
);
2752 PyObject
* res
= PyObject_CallMethodObjArgs(m_self
, m_SaveFile_Name
,
2754 py_OutputStream(&stream
),
2755 PyInt_FromLong(verbose
),
2757 bool retval
= false;
2759 retval
=PyInt_AsLong(res
);
2764 wxPyEndBlockThreads(blocked
);
2768 int wxPyImageHandler::GetImageCount( wxInputStream
& stream
) {
2769 wxPyBlock_t blocked
= wxPyBeginBlockThreads();
2770 if (!m_self
|| !PyObject_HasAttr(m_self
, m_GetImageCount_Name
)) {
2771 wxPyEndBlockThreads(blocked
);
2774 PyObject
*res
=PyObject_CallMethodObjArgs(m_self
, m_GetImageCount_Name
,
2775 py_InputStream(&stream
),
2779 retval
=PyInt_AsLong(res
);
2784 wxPyEndBlockThreads(blocked
);
2789 //----------------------------------------------------------------------
2790 // Function to test if the Display (or whatever is the platform equivallent)
2791 // can be connected to. This is accessable from wxPython as a staticmethod of
2792 // wx.App called DisplayAvailable().
2795 bool wxPyTestDisplayAvailable()
2799 display
= XOpenDisplay(NULL
);
2800 if (display
== NULL
)
2802 XCloseDisplay(display
);
2807 // This is adapted from Python's Mac/Modules/MacOS.c in the
2808 // MacOS_WMAvailable function.
2810 ProcessSerialNumber psn
;
2813 ** This is a fairly innocuous call to make if we don't have a window
2814 ** manager, or if we have no permission to talk to it. It will print
2815 ** a message on stderr, but at least it won't abort the process.
2816 ** It appears the function caches the result itself, and it's cheap, so
2817 ** no need for us to cache.
2819 #ifdef kCGNullDirectDisplay
2820 /* On 10.1 CGMainDisplayID() isn't available, and
2821 ** kCGNullDirectDisplay isn't defined.
2823 if (CGMainDisplayID() == 0) {
2828 // Also foreground the application on the first call as a side-effect.
2829 if (GetCurrentProcess(&psn
) < 0 || SetFrontProcess(&psn
) < 0) {
2845 //----------------------------------------------------------------------
2846 //----------------------------------------------------------------------