Update the trunk to the OpenCV's CVS (2008-07-14)
[opencv] / interfaces / swig / python / highgui.i
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42
43 // 2004-03-16, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
44 //             Mark Asbach       <asbach@ient.rwth-aachen.de>
45 //             Institute of Communications Engineering, RWTH Aachen University
46
47 %{
48         #include <cxtypes.h>
49         #include <cv.h>
50         #include <highgui.h>
51         #include "pyhelpers.h"
52         #include "pycvseq.hpp"
53 %}
54 // include python-specific files
55 %include "./nointpb.i"
56 %include "./pytypemaps.i"
57 %include "exception.i"
58
59 /* the wrapping code to enable the use of Python-based mouse callbacks */
60 %header %{
61         /* This encapsulates the python callback and user_data for mouse callback */
62         struct PyCvMouseCBData {
63                 PyObject * py_func;
64                 PyObject * user_data;
65         };
66         /* This encapsulates the python callback and user_data for mouse callback */
67     /* C helper function which is responsible for calling
68        the Python real trackbar callback function */
69     static void icvPyOnMouse (int event, int x, int y,
70                                          int flags, PyCvMouseCBData * param) {
71
72                 /* Must ensure this thread has a lock on the interpreter */
73                 PyGILState_STATE state = PyGILState_Ensure();
74
75                 PyObject *result;
76
77                 /* the argument of the callback ready to be passed to Python code */
78                 PyObject *arg1 = PyInt_FromLong (event);
79                 PyObject *arg2 = PyInt_FromLong (x);
80                 PyObject *arg3 = PyInt_FromLong (y);
81                 PyObject *arg4 = PyInt_FromLong (flags);
82                 PyObject *arg5 = param->user_data;  // assume this is already a PyObject
83
84                 /* build the tuple for calling the Python callback */
85                 PyObject *arglist = Py_BuildValue ("(OOOOO)",
86                                 arg1, arg2, arg3, arg4, arg5);
87
88                 /* call the Python callback */
89                 result = PyEval_CallObject (param->py_func, arglist);
90
91                 /* Errors in Python callback get swallowed, so report them here */
92                 if(!result){
93                         PyErr_Print();
94                         cvError( CV_StsInternal, "icvPyOnMouse", "", __FILE__, __LINE__);
95                 }
96
97                 /* cleanup */
98                 Py_XDECREF (result);
99
100                 /* Release Interpreter lock */
101                 PyGILState_Release(state);
102         }
103 %}
104 /**
105  * adapt cvSetMouseCallback to use python callback
106  */
107 %rename (cvSetMouseCallbackOld) cvSetMouseCallback;
108 %rename (cvSetMouseCallback) cvSetMouseCallbackPy;
109 %inline %{
110         void cvSetMouseCallbackPy( const char* window_name, PyObject * on_mouse, PyObject * param=NULL ){
111                 // TODO potential memory leak if mouse callback is redefined
112                 PyCvMouseCBData * py_callback = new PyCvMouseCBData;
113                 py_callback->py_func = on_mouse;
114                 py_callback->user_data = param ? param : Py_None;
115
116         Py_XINCREF(py_callback->py_func);
117         Py_XINCREF(py_callback->user_data);
118             
119                 cvSetMouseCallback( window_name, (CvMouseCallback) icvPyOnMouse, (void *) py_callback );
120         }
121 %}
122
123
124
125 /**
126  * The following code enables trackbar callbacks from python.  Unfortunately, there is no 
127  * way to distinguish which trackbar the event originated from, so must hard code a 
128  * fixed number of unique c callback functions using the macros below
129  */
130 %wrapper %{
131     /* C helper function which is responsible for calling
132        the Python real trackbar callback function */
133     static void icvPyOnTrackbar( PyObject * py_cb_func, int pos) {
134         
135                 /* Must ensure this thread has a lock on the interpreter */
136                 PyGILState_STATE state = PyGILState_Ensure();
137
138                 PyObject *result;
139
140                 /* the argument of the callback ready to be passed to Python code */
141                 PyObject *arg1 = PyInt_FromLong (pos);
142
143                 /* build the tuple for calling the Python callback */
144                 PyObject *arglist = Py_BuildValue ("(O)", arg1);
145
146                 /* call the Python callback */
147                 result = PyEval_CallObject (py_cb_func, arglist);
148
149                 /* Errors in Python callback get swallowed, so report them here */
150                 if(!result){
151                         PyErr_Print();
152                         cvError( CV_StsInternal, "icvPyOnTrackbar", "", __FILE__, __LINE__);
153                 }
154
155
156                 /* cleanup */
157                 Py_XDECREF (result);
158
159                 /* Release Interpreter lock */
160                 PyGILState_Release(state);
161         }
162
163 #define ICV_PY_MAX_CB 10
164
165         struct PyCvTrackbar {
166                 CvTrackbarCallback cv_func;
167                 PyObject * py_func;
168                 PyObject * py_pos;
169         };
170
171         static int my_trackbar_cb_size=0;
172         extern PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB];
173 %}
174
175 /* Callback table entry */
176 %define %ICV_PY_CB_TAB_ENTRY(idx)
177         {(CvTrackbarCallback) icvPyTrackbarCB##idx, NULL, NULL }
178 %enddef
179
180 /* Table of callbacks */
181 %define %ICV_PY_CB_TAB
182 %wrapper %{
183         PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB] = {
184                 %ICV_PY_CB_TAB_ENTRY(0),
185                 %ICV_PY_CB_TAB_ENTRY(1),
186                 %ICV_PY_CB_TAB_ENTRY(2),
187                 %ICV_PY_CB_TAB_ENTRY(3),
188                 %ICV_PY_CB_TAB_ENTRY(4),
189                 %ICV_PY_CB_TAB_ENTRY(5),
190                 %ICV_PY_CB_TAB_ENTRY(6),
191                 %ICV_PY_CB_TAB_ENTRY(7),
192                 %ICV_PY_CB_TAB_ENTRY(8),
193                 %ICV_PY_CB_TAB_ENTRY(9)
194         };
195 %}       
196 %enddef
197
198 /* Callback definition */
199 %define %ICV_PY_CB_IMPL(idx) 
200 %wrapper %{
201 static void icvPyTrackbarCB##idx(int pos){                                      
202         if(!my_trackbar_cb_funcs[idx].py_func) return;                              
203         icvPyOnTrackbar( my_trackbar_cb_funcs[idx].py_func, pos );                    
204 }                                                                               
205 %}
206 %enddef
207
208
209 %ICV_PY_CB_IMPL(0);
210 %ICV_PY_CB_IMPL(1);
211 %ICV_PY_CB_IMPL(2);
212 %ICV_PY_CB_IMPL(3);
213 %ICV_PY_CB_IMPL(4);
214 %ICV_PY_CB_IMPL(5);
215 %ICV_PY_CB_IMPL(6);
216 %ICV_PY_CB_IMPL(7);
217 %ICV_PY_CB_IMPL(8);
218 %ICV_PY_CB_IMPL(9);
219
220 %ICV_PY_CB_TAB;
221
222
223 /**
224  * typemap to memorize the Python callback when doing cvCreateTrackbar ()
225  */
226 %typemap(in) CvTrackbarCallback {
227
228         if(my_trackbar_cb_size == ICV_PY_MAX_CB){
229                 SWIG_exception(SWIG_IndexError, "Exceeded maximum number of trackbars");
230         }
231
232         my_trackbar_cb_size++;
233
234     if (!PyCallable_Check($input)) {
235         PyErr_SetString(PyExc_TypeError, "parameter must be callable");
236         return 0;
237     }
238     Py_XINCREF((PyObject*) $input);         /* Add a reference to new callback */
239     Py_XDECREF(my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func);  /* Dispose of previous callback */
240         my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func = (PyObject *) $input;
241
242         /* prepare to call the C function who will register the callback */
243         $1 = my_trackbar_cb_funcs[ my_trackbar_cb_size-1 ].cv_func;
244 }
245
246 /**
247  * typemap so that cvWaitKey returns a character in all cases except -1
248  */
249 %rename (cvWaitKeyC) cvWaitKey;
250 %rename (cvWaitKey) cvWaitKeyPy;
251 %inline %{
252         PyObject * cvWaitKeyPy(int delay=0){
253                 // In order for the event processing thread to run a python callback
254                 // it must acquire the global interpreter lock, but  cvWaitKey blocks, so
255                 // this thread can never release the lock. So release it here.
256                 PyThreadState * thread_state = PyEval_SaveThread();
257                 int res = cvWaitKey(delay);
258                 PyEval_RestoreThread( thread_state );
259                 
260                 char str[2]={(char)res,0};
261                 if(res==-1){
262                         return PyLong_FromLong(-1);
263                 }
264                 return PyString_FromString(str);
265         }
266 %}
267 /* HighGUI Python module initialization
268  * needed for callbacks to work in a threaded environment 
269  */
270 %init %{
271         PyEval_InitThreads();
272 %}
273
274
275 %include "../general/highgui.i"
276
277 %pythoncode 
278 %{
279
280 __doc__ = """HighGUI provides minimalistic user interface parts and video input/output.
281
282 Dependent on the platform it was compiled on, this library provides methods
283 to draw a window for image display, capture video from a camera or framegrabber
284 or read/write video streams from/to the file system.
285
286 This wrapper was semi-automatically created from the C/C++ headers and therefore
287 contains no Python documentation. Because all identifiers are identical to their
288 C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
289 """
290
291 %}