Update to 2.0.0 tree from current Fremantle build
[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 %include "cvswigmacros.i"
59
60 // handle camera and video writer destruction
61 %myrelease(highgui, cvReleaseCapture, CvCapture);
62 %myrelease(highgui, cvReleaseVideoWriter, CvVideoWriter);
63
64 /* the wrapping code to enable the use of Python-based mouse callbacks */
65 %header %{
66         /* This encapsulates the python callback and user_data for mouse callback */
67         struct PyCvMouseCBData {
68                 PyObject * py_func;
69                 PyObject * user_data;
70         };
71         /* This encapsulates the python callback and user_data for mouse callback */
72     /* C helper function which is responsible for calling
73        the Python real trackbar callback function */
74     static void icvPyOnMouse (int event, int x, int y,
75                                          int flags, PyCvMouseCBData * param) {
76
77                 /* Must ensure this thread has a lock on the interpreter */
78                 PyGILState_STATE state = PyGILState_Ensure();
79
80                 PyObject *result;
81
82                 /* the argument of the callback ready to be passed to Python code */
83                 PyObject *arg1 = PyInt_FromLong (event);
84                 PyObject *arg2 = PyInt_FromLong (x);
85                 PyObject *arg3 = PyInt_FromLong (y);
86                 PyObject *arg4 = PyInt_FromLong (flags);
87                 PyObject *arg5 = param->user_data;  // assume this is already a PyObject
88
89                 /* build the tuple for calling the Python callback */
90                 PyObject *arglist = Py_BuildValue ("(OOOOO)",
91                                 arg1, arg2, arg3, arg4, arg5);
92
93                 /* call the Python callback */
94                 result = PyEval_CallObject (param->py_func, arglist);
95
96                 /* Errors in Python callback get swallowed, so report them here */
97                 if(!result){
98                         PyErr_Print();
99                         cvError( CV_StsInternal, "icvPyOnMouse", "", __FILE__, __LINE__);
100                 }
101
102                 /* cleanup */
103                 Py_XDECREF (result);
104
105                 /* Release Interpreter lock */
106                 PyGILState_Release(state);
107         }
108 %}
109 /**
110  * adapt cvSetMouseCallback to use python callback
111  */
112 %rename (cvSetMouseCallbackOld) cvSetMouseCallback;
113 %rename (cvSetMouseCallback) cvSetMouseCallbackPy;
114 %inline %{
115         void cvSetMouseCallbackPy( const char* window_name, PyObject * on_mouse, PyObject * param=NULL ){
116                 // TODO potential memory leak if mouse callback is redefined
117                 PyCvMouseCBData * py_callback = new PyCvMouseCBData;
118                 py_callback->py_func = on_mouse;
119                 py_callback->user_data = param ? param : Py_None;
120
121         Py_XINCREF(py_callback->py_func);
122         Py_XINCREF(py_callback->user_data);
123             
124                 cvSetMouseCallback( window_name, (CvMouseCallback) icvPyOnMouse, (void *) py_callback );
125         }
126 %}
127
128
129
130 /**
131  * The following code enables trackbar callbacks from python.  Unfortunately, there is no 
132  * way to distinguish which trackbar the event originated from, so must hard code a 
133  * fixed number of unique c callback functions using the macros below
134  */
135 %wrapper %{
136     /* C helper function which is responsible for calling
137        the Python real trackbar callback function */
138     static void icvPyOnTrackbar( PyObject * py_cb_func, int pos) {
139         
140                 /* Must ensure this thread has a lock on the interpreter */
141                 PyGILState_STATE state = PyGILState_Ensure();
142
143                 PyObject *result;
144
145                 /* the argument of the callback ready to be passed to Python code */
146                 PyObject *arg1 = PyInt_FromLong (pos);
147
148                 /* build the tuple for calling the Python callback */
149                 PyObject *arglist = Py_BuildValue ("(O)", arg1);
150
151                 /* call the Python callback */
152                 result = PyEval_CallObject (py_cb_func, arglist);
153
154                 /* Errors in Python callback get swallowed, so report them here */
155                 if(!result){
156                         PyErr_Print();
157                         cvError( CV_StsInternal, "icvPyOnTrackbar", "", __FILE__, __LINE__);
158                 }
159
160
161                 /* cleanup */
162                 Py_XDECREF (result);
163
164                 /* Release Interpreter lock */
165                 PyGILState_Release(state);
166         }
167
168 #define ICV_PY_MAX_CB 10
169
170         struct PyCvTrackbar {
171                 CvTrackbarCallback cv_func;
172                 PyObject * py_func;
173                 PyObject * py_pos;
174         };
175
176         static int my_trackbar_cb_size=0;
177         extern PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB];
178 %}
179
180 /* Callback table entry */
181 %define %ICV_PY_CB_TAB_ENTRY(idx)
182         {(CvTrackbarCallback) icvPyTrackbarCB##idx, NULL, NULL }
183 %enddef
184
185 /* Table of callbacks */
186 %define %ICV_PY_CB_TAB
187 %wrapper %{
188         PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB] = {
189                 %ICV_PY_CB_TAB_ENTRY(0),
190                 %ICV_PY_CB_TAB_ENTRY(1),
191                 %ICV_PY_CB_TAB_ENTRY(2),
192                 %ICV_PY_CB_TAB_ENTRY(3),
193                 %ICV_PY_CB_TAB_ENTRY(4),
194                 %ICV_PY_CB_TAB_ENTRY(5),
195                 %ICV_PY_CB_TAB_ENTRY(6),
196                 %ICV_PY_CB_TAB_ENTRY(7),
197                 %ICV_PY_CB_TAB_ENTRY(8),
198                 %ICV_PY_CB_TAB_ENTRY(9)
199         };
200 %}       
201 %enddef
202
203 /* Callback definition */
204 %define %ICV_PY_CB_IMPL(idx) 
205 %wrapper %{
206 static void icvPyTrackbarCB##idx(int pos){                                      
207         if(!my_trackbar_cb_funcs[idx].py_func) return;                              
208         icvPyOnTrackbar( my_trackbar_cb_funcs[idx].py_func, pos );                    
209 }                                                                               
210 %}
211 %enddef
212
213
214 %ICV_PY_CB_IMPL(0);
215 %ICV_PY_CB_IMPL(1);
216 %ICV_PY_CB_IMPL(2);
217 %ICV_PY_CB_IMPL(3);
218 %ICV_PY_CB_IMPL(4);
219 %ICV_PY_CB_IMPL(5);
220 %ICV_PY_CB_IMPL(6);
221 %ICV_PY_CB_IMPL(7);
222 %ICV_PY_CB_IMPL(8);
223 %ICV_PY_CB_IMPL(9);
224
225 %ICV_PY_CB_TAB;
226
227
228 /**
229  * typemap to memorize the Python callback when doing cvCreateTrackbar ()
230  */
231 %typemap(in) CvTrackbarCallback {
232
233         if(my_trackbar_cb_size == ICV_PY_MAX_CB){
234                 SWIG_exception(SWIG_IndexError, "Exceeded maximum number of trackbars");
235         }
236
237         my_trackbar_cb_size++;
238
239     if (!PyCallable_Check($input)) {
240         PyErr_SetString(PyExc_TypeError, "parameter must be callable");
241         return 0;
242     }
243     Py_XINCREF((PyObject*) $input);         /* Add a reference to new callback */
244     Py_XDECREF(my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func);  /* Dispose of previous callback */
245         my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func = (PyObject *) $input;
246
247         /* prepare to call the C function who will register the callback */
248         $1 = my_trackbar_cb_funcs[ my_trackbar_cb_size-1 ].cv_func;
249 }
250
251 /**
252  * typemap so that cvWaitKey returns a character in all cases except -1
253  */
254 %rename (cvWaitKeyC) cvWaitKey;
255 %rename (cvWaitKey) cvWaitKeyPy;
256 %inline %{
257         PyObject * cvWaitKeyPy(int delay=0){
258                 // In order for the event processing thread to run a python callback
259                 // it must acquire the global interpreter lock, but  cvWaitKey blocks, so
260                 // this thread can never release the lock. So release it here.
261                 PyThreadState * thread_state = PyEval_SaveThread();
262                 int res = cvWaitKey(delay);
263                 PyEval_RestoreThread( thread_state );
264                 
265                 char str[2]={(char)res,0};
266                 if(res==-1){
267                         return PyLong_FromLong(-1);
268                 }
269                 return PyString_FromString(str);
270         }
271 %}
272 /* HighGUI Python module initialization
273  * needed for callbacks to work in a threaded environment 
274  */
275 %init %{
276         PyEval_InitThreads();
277 %}
278
279
280 %include "../general/highgui.i"
281
282 %pythoncode 
283 %{
284
285 __doc__ = """HighGUI provides minimalistic user interface parts and video input/output.
286
287 Dependent on the platform it was compiled on, this library provides methods
288 to draw a window for image display, capture video from a camera or framegrabber
289 or read/write video streams from/to the file system.
290
291 This wrapper was semi-automatically created from the C/C++ headers and therefore
292 contains no Python documentation. Because all identifiers are identical to their
293 C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
294 """
295
296 %}