]> git.saurik.com Git - wxWidgets.git/blob - utils/wxPython/src/helpers.cpp
Lots more support for event-less callbacks
[wxWidgets.git] / utils / wxPython / src / helpers.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: helpers.cpp
3 // Purpose: Helper functions/classes for the wxPython extension module
4 //
5 // Author: Robin Dunn
6 //
7 // Created: 7/1/97
8 // RCS-ID: $Id$
9 // Copyright: (c) 1998 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13
14 #ifdef __WXGTK__
15 #include <gtk/gtk.h>
16 #endif
17
18 #undef DEBUG
19 #include <Python.h>
20 #include "helpers.h"
21 #ifdef __WXMSW__
22 #include <wx/msw/private.h>
23 #undef FindWindow
24 #undef GetCharWidth
25 #undef LoadAccelerators
26 #undef GetClassInfo
27 #undef GetClassName
28 #endif
29 #include <wx/module.h>
30
31
32 //---------------------------------------------------------------------------
33
34 //wxHashTable* wxPyWindows = NULL;
35
36
37 wxPoint wxPyDefaultPosition; //wxDefaultPosition);
38 wxSize wxPyDefaultSize; //wxDefaultSize);
39 wxString wxPyEmptyStr("");
40
41
42
43 #ifdef __WXMSW__ // If building for win32...
44 //----------------------------------------------------------------------
45 // This gets run when the DLL is loaded. We just need to save a handle.
46 //----------------------------------------------------------------------
47
48 BOOL WINAPI DllMain(
49 HINSTANCE hinstDLL, // handle to DLL module
50 DWORD fdwReason, // reason for calling function
51 LPVOID lpvReserved // reserved
52 )
53 {
54 wxSetInstance(hinstDLL);
55 return 1;
56 }
57 #endif
58
59 //----------------------------------------------------------------------
60 // Class for implementing the wxp main application shell.
61 //----------------------------------------------------------------------
62
63 wxPyApp *wxPythonApp = NULL; // Global instance of application object
64
65
66 wxPyApp::wxPyApp() {
67 // printf("**** ctor\n");
68 }
69
70 wxPyApp::~wxPyApp() {
71 // printf("**** dtor\n");
72 }
73
74
75 // This one isn't acutally called... See __wxStart()
76 bool wxPyApp::OnInit(void) {
77 return false;
78 }
79
80 int wxPyApp::MainLoop(void) {
81 int retval = wxApp::MainLoop();
82 //# AfterMainLoop();
83 wxPythonApp->OnExit(); //#
84 return retval;
85 }
86
87
88 //# void wxPyApp::AfterMainLoop(void) {
89 // // more stuff from wxEntry...
90
91 // if (wxPythonApp->GetTopWindow()) {
92 // // Forcibly delete the window.
93 // if (wxPythonApp->GetTopWindow()->IsKindOf(CLASSINFO(wxFrame)) ||
94 // wxPythonApp->GetTopWindow()->IsKindOf(CLASSINFO(wxDialog))) {
95
96 // wxPythonApp->GetTopWindow()->Close(TRUE);
97 // wxPythonApp->DeletePendingObjects();
98 // }
99 // else {
100 // delete wxPythonApp->GetTopWindow();
101 // wxPythonApp->SetTopWindow(NULL);
102 // }
103 // }
104 // #ifdef __WXGTK__
105 // wxPythonApp->DeletePendingObjects();
106 // #endif
107
108 // wxPythonApp->OnExit();
109 // wxApp::CleanUp();
110 // // delete wxPythonApp;
111 // }
112
113
114 //---------------------------------------------------------------------
115 // a few native methods to add to the module
116 //----------------------------------------------------------------------
117
118
119 // This is where we pick up the first part of the wxEntry functionality...
120 // The rest is in __wxStart and AfterMainLoop. This function is called when
121 // wxcmodule is imported. (Before there is a wxApp object.)
122 void __wxPreStart()
123 {
124 // Bail out if there is already windows created. This means that the
125 // toolkit has already been initialized, as in embedding wxPython in
126 // a C++ wxWindows app.
127 if (wxTopLevelWindows.Number() > 0)
128 return;
129
130 #ifdef __WXMSW__
131 wxApp::Initialize();
132 #endif
133
134 #ifdef __WXGTK__
135 PyObject* sysargv = PySys_GetObject("argv");
136 int argc = PyList_Size(sysargv);
137 char** argv = new char*[argc+1];
138 int x;
139 for(x=0; x<argc; x++)
140 argv[x] = PyString_AsString(PyList_GetItem(sysargv, x));
141 argv[argc] = NULL;
142
143 gtk_set_locale();
144 if (!wxOKlibc()) wxConvCurrent = &wxConvLocal;
145 gtk_init( &argc, &argv );
146 wxSetDetectableAutoRepeat( TRUE );
147 delete [] argv;
148
149 wxApp::Initialize(); // may return FALSE. Should we check?
150 #endif
151
152 }
153
154
155 #ifdef WXP_WITH_THREAD
156 PyThreadState* wxPyEventThreadState = NULL;
157 #endif
158 static char* __nullArgv[1] = { 0 };
159
160
161
162 // Start the user application, user App's OnInit method is a parameter here
163 PyObject* __wxStart(PyObject* /* self */, PyObject* args)
164 {
165 PyObject* onInitFunc = NULL;
166 PyObject* arglist;
167 PyObject* result;
168 long bResult;
169
170 #ifdef WXP_WITH_THREAD
171 wxPyEventThreadState = PyThreadState_Get();
172 #endif
173
174 if (!PyArg_ParseTuple(args, "O", &onInitFunc))
175 return NULL;
176
177 if (wxTopLevelWindows.Number() > 0) {
178 PyErr_SetString(PyExc_TypeError, "Only 1 wxApp per process!");
179 return NULL;
180 }
181
182
183 // This is the next part of the wxEntry functionality...
184 wxPythonApp->argc = 0;
185 wxPythonApp->argv = NULL;
186 wxPythonApp->OnInitGui();
187
188
189 // Call the Python App's OnInit function
190 arglist = PyTuple_New(0);
191 result = PyEval_CallObject(onInitFunc, arglist);
192 if (!result) { // an exception was raised.
193 return NULL;
194 }
195
196 if (! PyInt_Check(result)) {
197 PyErr_SetString(PyExc_TypeError, "OnInit should return a boolean value");
198 return NULL;
199 }
200 bResult = PyInt_AS_LONG(result);
201 if (! bResult) {
202 PyErr_SetString(PyExc_SystemExit, "OnInit returned false, exiting...");
203 return NULL;
204 }
205
206 #ifdef __WXGTK__
207 wxTheApp->m_initialized = (wxTopLevelWindows.Number() > 0);
208 #endif
209
210 Py_INCREF(Py_None);
211 return Py_None;
212 }
213
214
215
216
217
218 PyObject* wxPython_dict;
219 PyObject* __wxSetDictionary(PyObject* /* self */, PyObject* args)
220 {
221
222 if (!PyArg_ParseTuple(args, "O", &wxPython_dict))
223 return NULL;
224
225 if (!PyDict_Check(wxPython_dict)) {
226 PyErr_SetString(PyExc_TypeError, "_wxSetDictionary must have dictionary object!");
227 return NULL;
228 }
229 #ifdef __WXMOTIF__
230 #define wxPlatform "__WXMOTIF__"
231 #endif
232 #ifdef __WXQT__
233 #define wxPlatform "__WXQT__"
234 #endif
235 #ifdef __WXGTK__
236 #define wxPlatform "__WXGTK__"
237 #endif
238 #if defined(__WIN32__) || defined(__WXMSW__)
239 #define wxPlatform "__WXMSW__"
240 #endif
241 #ifdef __WXMAC__
242 #define wxPlatform "__WXMAC__"
243 #endif
244
245 PyDict_SetItemString(wxPython_dict, "wxPlatform", PyString_FromString(wxPlatform));
246
247 Py_INCREF(Py_None);
248 return Py_None;
249 }
250
251
252 //---------------------------------------------------------------------------
253
254 PyObject* wxPyConstructObject(void* ptr, char* className) {
255 char buff[64]; // should always be big enough...
256 char swigptr[64];
257
258 sprintf(buff, "_%s_p", className);
259 SWIG_MakePtr(swigptr, ptr, buff);
260
261 sprintf(buff, "%sPtr", className);
262 PyObject* classobj = PyDict_GetItemString(wxPython_dict, buff);
263 if (! classobj) {
264 Py_INCREF(Py_None);
265 return Py_None;
266 }
267
268 PyObject* arg = Py_BuildValue("(s)", swigptr);
269 PyObject* obj = PyInstance_New(classobj, arg, NULL);
270 Py_DECREF(arg);
271
272 return obj;
273 }
274
275 //---------------------------------------------------------------------------
276
277 //static bool _wxPyInEvent = false;
278 static unsigned int _wxPyNestCount = 0;
279
280 HELPEREXPORT bool wxPyRestoreThread() {
281 // #ifdef WXP_WITH_THREAD
282 // //if (wxPyEventThreadState != PyThreadState_Get()) {
283 // if (! _wxPyInEvent) {
284 // PyEval_RestoreThread(wxPyEventThreadState);
285 // _wxPyInEvent = true;
286 // return TRUE;
287 // } else
288 // #endif
289 // return FALSE;
290
291 // NOTE: The Python API docs state that if a thread already has the
292 // interpreter lock and calls PyEval_RestoreThread again a deadlock
293 // occurs, so I put in the above code as a guard condition since there are
294 // many possibilites for nested events and callbacks in wxPython.
295 //
296 // Unfortunately, it seems like somebody was lying (or I'm not
297 // understanding...) because each of the nested calls to this function
298 // MUST call PyEval_RestoreThread or Python pukes with a thread error (at
299 // least on Win32.)
300 //
301 // until I know better, this is how I am doing it instead:
302 #ifdef WXP_WITH_THREAD
303 PyEval_RestoreThread(wxPyEventThreadState);
304 _wxPyNestCount += 1;
305 if (_wxPyNestCount == 1)
306 return TRUE;
307 else
308 #endif
309 return FALSE;
310 }
311
312
313 HELPEREXPORT void wxPySaveThread(bool doSave) {
314 #ifdef WXP_WITH_THREAD
315 if (doSave) {
316 PyEval_SaveThread();
317 //_wxPyInEvent = false;
318 }
319 _wxPyNestCount -= 1;
320 #endif
321 }
322
323 //---------------------------------------------------------------------------
324
325
326 wxPyCallback::wxPyCallback(PyObject* func) {
327 m_func = func;
328 Py_INCREF(m_func);
329 }
330
331 wxPyCallback::~wxPyCallback() {
332 bool doSave = wxPyRestoreThread();
333 Py_DECREF(m_func);
334 wxPySaveThread(doSave);
335 }
336
337
338
339
340 // This function is used for all events destined for Python event handlers.
341 void wxPyCallback::EventThunker(wxEvent& event) {
342 wxPyCallback* cb = (wxPyCallback*)event.m_callbackUserData;
343 PyObject* func = cb->m_func;
344 PyObject* result;
345 PyObject* arg;
346 PyObject* tuple;
347
348
349 bool doSave = wxPyRestoreThread();
350 arg = wxPyConstructObject((void*)&event, event.GetClassInfo()->GetClassName());
351
352 tuple = PyTuple_New(1);
353 PyTuple_SET_ITEM(tuple, 0, arg);
354 result = PyEval_CallObject(func, tuple);
355 Py_DECREF(tuple);
356 if (result) {
357 Py_DECREF(result);
358 PyErr_Clear();
359 } else {
360 PyErr_Print();
361 }
362 wxPySaveThread(doSave);
363 }
364
365
366 //----------------------------------------------------------------------
367
368 wxPyCallbackHelper::wxPyCallbackHelper() {
369 m_self = NULL;
370 m_lastFound = NULL;
371 }
372
373
374 wxPyCallbackHelper::~wxPyCallbackHelper() {
375 bool doSave = wxPyRestoreThread();
376 Py_XDECREF(m_self);
377 wxPySaveThread(doSave);
378 }
379
380 void wxPyCallbackHelper::setSelf(PyObject* self) {
381 m_self = self;
382 Py_INCREF(m_self);
383 }
384
385
386 bool wxPyCallbackHelper::findCallback(const wxString& name) {
387 m_lastFound = NULL;
388 if (m_self && PyObject_HasAttrString(m_self, (char*)name.c_str()))
389 m_lastFound = PyObject_GetAttrString(m_self, (char*)name.c_str());
390
391 return m_lastFound != NULL;
392 }
393
394
395 int wxPyCallbackHelper::callCallback(PyObject* argTuple) {
396 PyObject* result;
397 int retval = FALSE;
398
399 result = callCallbackObj(argTuple);
400 if (result) { // Assumes an integer return type...
401 retval = PyInt_AsLong(result);
402 Py_DECREF(result);
403 PyErr_Clear(); // forget about it if it's not...
404 }
405 return retval;
406 }
407
408 // Invoke the Python callable object, returning the raw PyObject return
409 // value. Caller should DECREF the return value and also call PyEval_SaveThread.
410 PyObject* wxPyCallbackHelper::callCallbackObj(PyObject* argTuple) {
411 PyObject* result;
412
413 result = PyEval_CallObject(m_lastFound, argTuple);
414 Py_DECREF(argTuple);
415 if (!result) {
416 PyErr_Print();
417 }
418 return result;
419 }
420
421
422
423 //---------------------------------------------------------------------------
424 //---------------------------------------------------------------------------
425
426
427 wxPyTimer::wxPyTimer(PyObject* callback) {
428 func = callback;
429 Py_INCREF(func);
430 }
431
432 wxPyTimer::~wxPyTimer() {
433 bool doSave = wxPyRestoreThread();
434 Py_DECREF(func);
435 wxPySaveThread(doSave);
436 }
437
438 void wxPyTimer::Notify() {
439 bool doSave = wxPyRestoreThread();
440
441 PyObject* result;
442 PyObject* args = Py_BuildValue("()");
443
444 result = PyEval_CallObject(func, args);
445 Py_DECREF(args);
446 if (result) {
447 Py_DECREF(result);
448 PyErr_Clear();
449 } else {
450 PyErr_Print();
451 }
452 wxPySaveThread(doSave);
453 }
454
455
456 //----------------------------------------------------------------------
457
458 IMPLEMENT_DYNAMIC_CLASS(wxPyEvent, wxCommandEvent)
459
460 wxPyEvent::wxPyEvent(wxEventType commandType, PyObject* userData)
461 : wxCommandEvent(commandType), m_userData(Py_None)
462 {
463 m_userData = userData;
464 if (m_userData != Py_None) {
465 Py_INCREF(m_userData);
466 }
467 }
468
469
470 wxPyEvent::~wxPyEvent() {
471 bool doSave = wxPyRestoreThread();
472 if (m_userData != Py_None) {
473 Py_DECREF(m_userData);
474 m_userData = Py_None;
475 }
476 wxPySaveThread(doSave);
477 }
478
479
480 void wxPyEvent::SetUserData(PyObject* userData) {
481 if (m_userData != Py_None) {
482 Py_DECREF(m_userData);
483 m_userData = Py_None;
484 }
485 m_userData = userData;
486 if (m_userData != Py_None) {
487 Py_INCREF(m_userData);
488 }
489 }
490
491
492 PyObject* wxPyEvent::GetUserData() {
493 return m_userData;
494 }
495
496 //----------------------------------------------------------------------
497 //----------------------------------------------------------------------
498 // Some helper functions for typemaps in my_typemaps.i, so they won't be
499 // imcluded in every file...
500
501
502 HELPEREXPORT byte* byte_LIST_helper(PyObject* source) {
503 if (!PyList_Check(source)) {
504 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
505 return NULL;
506 }
507 int count = PyList_Size(source);
508 byte* temp = new byte[count];
509 if (! temp) {
510 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
511 return NULL;
512 }
513 for (int x=0; x<count; x++) {
514 PyObject* o = PyList_GetItem(source, x);
515 if (! PyInt_Check(o)) {
516 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
517 return NULL;
518 }
519 temp[x] = (byte)PyInt_AsLong(o);
520 }
521 return temp;
522 }
523
524
525 HELPEREXPORT int* int_LIST_helper(PyObject* source) {
526 if (!PyList_Check(source)) {
527 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
528 return NULL;
529 }
530 int count = PyList_Size(source);
531 int* temp = new int[count];
532 if (! temp) {
533 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
534 return NULL;
535 }
536 for (int x=0; x<count; x++) {
537 PyObject* o = PyList_GetItem(source, x);
538 if (! PyInt_Check(o)) {
539 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
540 return NULL;
541 }
542 temp[x] = PyInt_AsLong(o);
543 }
544 return temp;
545 }
546
547
548 HELPEREXPORT long* long_LIST_helper(PyObject* source) {
549 if (!PyList_Check(source)) {
550 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
551 return NULL;
552 }
553 int count = PyList_Size(source);
554 long* temp = new long[count];
555 if (! temp) {
556 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
557 return NULL;
558 }
559 for (int x=0; x<count; x++) {
560 PyObject* o = PyList_GetItem(source, x);
561 if (! PyInt_Check(o)) {
562 PyErr_SetString(PyExc_TypeError, "Expected a list of integers.");
563 return NULL;
564 }
565 temp[x] = PyInt_AsLong(o);
566 }
567 return temp;
568 }
569
570
571 HELPEREXPORT char** string_LIST_helper(PyObject* source) {
572 if (!PyList_Check(source)) {
573 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
574 return NULL;
575 }
576 int count = PyList_Size(source);
577 char** temp = new char*[count];
578 if (! temp) {
579 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
580 return NULL;
581 }
582 for (int x=0; x<count; x++) {
583 PyObject* o = PyList_GetItem(source, x);
584 if (! PyString_Check(o)) {
585 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
586 return NULL;
587 }
588 temp[x] = PyString_AsString(o);
589 }
590 return temp;
591 }
592
593
594
595 HELPEREXPORT wxPoint* wxPoint_LIST_helper(PyObject* source) {
596 if (!PyList_Check(source)) {
597 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
598 return NULL;
599 }
600 int count = PyList_Size(source);
601 wxPoint* temp = new wxPoint[count];
602 if (! temp) {
603 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
604 return NULL;
605 }
606 for (int x=0; x<count; x++) {
607 PyObject* o = PyList_GetItem(source, x);
608 if (PyTuple_Check(o)) {
609 PyObject* o1 = PyTuple_GetItem(o, 0);
610 PyObject* o2 = PyTuple_GetItem(o, 1);
611
612 temp[x].x = PyInt_AsLong(o1);
613 temp[x].y = PyInt_AsLong(o2);
614 }
615 else if (PyInstance_Check(o)) {
616 wxPoint* pt;
617 if (SWIG_GetPtrObj(o,(void **) &pt,"_wxPoint_p")) {
618 PyErr_SetString(PyExc_TypeError,"Expected _wxPoint_p.");
619 return NULL;
620 }
621 temp[x] = *pt;
622 }
623 else {
624 PyErr_SetString(PyExc_TypeError, "Expected a list of 2-tuples or wxPoints.");
625 return NULL;
626 }
627 }
628 return temp;
629 }
630
631
632 HELPEREXPORT wxBitmap** wxBitmap_LIST_helper(PyObject* source) {
633 if (!PyList_Check(source)) {
634 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
635 return NULL;
636 }
637 int count = PyList_Size(source);
638 wxBitmap** temp = new wxBitmap*[count];
639 if (! temp) {
640 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
641 return NULL;
642 }
643 for (int x=0; x<count; x++) {
644 PyObject* o = PyList_GetItem(source, x);
645 if (PyString_Check(o)) {
646 char* st = PyString_AsString(o);
647 wxBitmap* pt;
648 if (SWIG_GetPtr(st,(void **) &pt,"_wxBitmap_p")) {
649 PyErr_SetString(PyExc_TypeError,"Expected _wxBitmap_p.");
650 return NULL;
651 }
652 temp[x] = pt;
653 }
654 else {
655 PyErr_SetString(PyExc_TypeError, "Expected a list of wxBitmaps.");
656 return NULL;
657 }
658 }
659 return temp;
660 }
661
662
663
664 HELPEREXPORT wxString* wxString_LIST_helper(PyObject* source) {
665 if (!PyList_Check(source)) {
666 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
667 return NULL;
668 }
669 int count = PyList_Size(source);
670 wxString* temp = new wxString[count];
671 if (! temp) {
672 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
673 return NULL;
674 }
675 for (int x=0; x<count; x++) {
676 PyObject* o = PyList_GetItem(source, x);
677 if (! PyString_Check(o)) {
678 PyErr_SetString(PyExc_TypeError, "Expected a list of strings.");
679 return NULL;
680 }
681 temp[x] = PyString_AsString(o);
682 }
683 return temp;
684 }
685
686
687 HELPEREXPORT wxAcceleratorEntry* wxAcceleratorEntry_LIST_helper(PyObject* source) {
688 if (!PyList_Check(source)) {
689 PyErr_SetString(PyExc_TypeError, "Expected a list object.");
690 return NULL;
691 }
692 int count = PyList_Size(source);
693 wxAcceleratorEntry* temp = new wxAcceleratorEntry[count];
694 if (! temp) {
695 PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
696 return NULL;
697 }
698 for (int x=0; x<count; x++) {
699 PyObject* o = PyList_GetItem(source, x);
700 if (PyString_Check(o)) {
701 char* st = PyString_AsString(o);
702 wxAcceleratorEntry* ae;
703 if (SWIG_GetPtr(st,(void **) &ae,"_wxAcceleratorEntry_p")) {
704 PyErr_SetString(PyExc_TypeError,"Expected _wxAcceleratorEntry_p.");
705 return NULL;
706 }
707 temp[x] = *ae;
708 }
709 else if (PyTuple_Check(o)) {
710 PyObject* o1 = PyTuple_GetItem(o, 0);
711 PyObject* o2 = PyTuple_GetItem(o, 1);
712 PyObject* o3 = PyTuple_GetItem(o, 2);
713
714 temp[x].m_flags = PyInt_AsLong(o1);
715 temp[x].m_keyCode = PyInt_AsLong(o2);
716 temp[x].m_command = PyInt_AsLong(o3);
717 }
718 else {
719 PyErr_SetString(PyExc_TypeError, "Expected a list of 3-tuples or wxAcceleratorEntry objects.");
720 return NULL;
721 }
722 }
723 return temp;
724 }
725
726
727
728 //----------------------------------------------------------------------
729
730 //----------------------------------------------------------------------
731 //----------------------------------------------------------------------
732 //----------------------------------------------------------------------
733
734
735