]> sigrok.org Git - libsigrok.git/blob - bindings/python/sigrok/core/classes.i
Reimplement high-level Python bindings on top of SWIG/C++ bindings.
[libsigrok.git] / bindings / python / sigrok / core / classes.i
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Martin Ling <martin-sigrok@earth.li>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 %module classes
21
22 %{
23 #include <pygobject.h>
24
25 PyObject *GLib;
26 PyTypeObject *IOChannel;
27 PyTypeObject *PollFD;
28
29 %}
30
31 %init %{
32     pygobject_init(-1, -1, -1);
33     GLib = PyImport_ImportModule("gi.repository.GLib");
34     IOChannel = (PyTypeObject *) PyObject_GetAttrString(GLib, "IOChannel");
35     PollFD = (PyTypeObject *) PyObject_GetAttrString(GLib, "PollFD");
36 %}
37
38 /* Map file objects to file descriptors. */
39 %typecheck(SWIG_TYPECHECK_POINTER) int fd {
40     $1 = (PyObject_AsFileDescriptor($input) != -1);
41 }
42
43 %typemap(in) int fd {
44     int fd = PyObject_AsFileDescriptor($input);
45     if (fd == -1)
46         SWIG_exception(SWIG_TypeError,
47             "Expected file object or integer file descriptor");
48     else
49       $1 = fd;
50 }
51
52 /* Map from Glib::Variant to native Python types. */
53 %typemap(out) Glib::VariantBase {
54     GValue *value = g_new0(GValue, 1);
55     g_value_init(value, G_TYPE_VARIANT);
56     g_value_set_variant(value, $1.gobj());
57     PyObject *variant = pyg_value_as_pyobject(value, true);
58     $result = PyObject_CallMethod(variant,
59         const_cast<char *>("unpack"),
60         const_cast<char *>(""), NULL);
61     Py_XDECREF(variant);
62     g_free(value);
63 }
64
65 /* Map from Glib::IOCondition to GLib.IOCondition. */
66 %typecheck(SWIG_TYPECHECK_POINTER) Glib::IOCondition {
67     gint flags;
68     $1 = pygobject_check($input, &PyGFlags_Type) &&
69          (pyg_flags_get_value(G_TYPE_IO_CONDITION, $input, &flags) != -1);
70 }
71
72 %typemap(in) Glib::IOCondition {
73     if (!pygobject_check($input, &PyGFlags_Type))
74         SWIG_exception(SWIG_TypeError, "Expected GLib.IOCondition value");
75     gint flags;
76     if (pyg_flags_get_value(G_TYPE_IO_CONDITION, $input, &flags) == -1)
77         SWIG_exception(SWIG_TypeError, "Not a valid Glib.IOCondition value");
78     $1 = (Glib::IOCondition) flags;
79 }
80
81 /* And back */
82 %typemap(out) Glib::IOCondition {
83     GValue *value = g_new0(GValue, 1);
84     g_value_init(value, G_TYPE_IO_CONDITION);
85     g_value_set_flags(value, &$1);
86     $result = pyg_value_as_pyobject(value, true);
87     g_free(value);
88 }
89
90 /* Map from GLib.PollFD to Glib::PollFD *. */
91 %typecheck(SWIG_TYPECHECK_POINTER) Glib::PollFD {
92     $1 = pygobject_check($input, PollFD);
93 }
94
95 %typemap(in) Glib::PollFD {
96     if (!pygobject_check($input, PollFD))
97         SWIG_exception(SWIG_TypeError, "Expected GLib.PollFD");
98     PyObject *fd_obj = PyObject_GetAttrString($input, "fd");
99     PyObject *events_obj = PyObject_GetAttrString($input, "events");
100     gint flags;
101     pyg_flags_get_value(G_TYPE_IO_CONDITION, events_obj, &flags);
102     int fd = PyInt_AsLong(fd_obj);
103     Glib::IOCondition events = (Glib::IOCondition) flags;
104     $1 = Glib::PollFD(fd, events);
105 }
106
107 /* Map from GLib.IOChannel to Glib::IOChannel *. */
108 %typecheck(SWIG_TYPECHECK_POINTER) Glib::RefPtr<Glib::IOChannel> {
109     $1 = pygobject_check($input, IOChannel);
110 }
111
112 %typemap(in) Glib::RefPtr<Glib::IOChannel> {
113     if (!pygobject_check($input, IOChannel))
114         SWIG_exception(SWIG_TypeError, "Expected GLib.IOChannel");
115     $1 = Glib::wrap((GIOChannel *) PyObject_Hash($input), true);
116 }
117
118 /* Map from callable PyObject to SourceCallbackFunction. */
119 %typecheck(SWIG_TYPECHECK_POINTER) sigrok::SourceCallbackFunction {
120     $1 = PyCallable_Check($input);
121 }
122
123 %typemap(in) sigrok::SourceCallbackFunction {
124     if (!PyCallable_Check($input))
125         SWIG_exception(SWIG_TypeError, "Expected a callable Python object");
126
127     $1 = [=] (Glib::IOCondition revents) {
128         auto gstate = PyGILState_Ensure();
129
130         GValue *value = g_new0(GValue, 1);
131         g_value_init(value, G_TYPE_IO_CONDITION);
132         g_value_set_flags(value, revents);
133         auto revents_obj = pyg_value_as_pyobject(value, true);
134         g_free(value);
135
136         auto arglist = Py_BuildValue("(O)", revents_obj);
137
138         auto result = PyEval_CallObject($input, arglist);
139
140         Py_XDECREF(arglist);
141         Py_XDECREF(revents_obj);
142
143         if (PyErr_Occurred() || !PyBool_Check(result))
144             throw sigrok::Error(SR_ERR);
145
146         bool retval = (result == Py_True);
147
148         Py_XDECREF(result);
149
150         PyGILState_Release(gstate);
151
152         return retval;
153     };
154
155     Py_XINCREF($input);
156 }
157
158 /* Map from callable PyObject to LogCallbackFunction */
159 %typecheck(SWIG_TYPECHECK_POINTER) sigrok::LogCallbackFunction {
160     $1 = PyCallable_Check($input);
161 }
162
163 %typemap(in) sigrok::LogCallbackFunction {
164     if (!PyCallable_Check($input))
165         SWIG_exception(SWIG_TypeError, "Expected a callable Python object");
166
167     $1 = [=] (const sigrok::LogLevel *loglevel, string message) {
168         auto gstate = PyGILState_Ensure();
169
170         auto log_obj = SWIG_NewPointerObj(
171                 SWIG_as_voidptr(loglevel), SWIGTYPE_p_sigrok__LogLevel, 0);
172
173         auto string_obj = PyString_FromString(message.c_str());
174
175         auto arglist = Py_BuildValue("(OO)", log_obj, string_obj);
176
177         auto result = PyEval_CallObject($input, arglist);
178
179         Py_XDECREF(arglist);
180         Py_XDECREF(log_obj);
181         Py_XDECREF(string_obj);
182         Py_XDECREF(result);
183
184         PyGILState_Release(gstate);
185     };
186
187     Py_XINCREF($input);
188 }
189
190 /* Map from callable PyObject to DatafeedCallbackFunction */
191 %typecheck(SWIG_TYPECHECK_POINTER) sigrok::DatafeedCallbackFunction {
192     $1 = PyCallable_Check($input);
193 }
194
195 %typemap(in) sigrok::DatafeedCallbackFunction {
196     if (!PyCallable_Check($input))
197         SWIG_exception(SWIG_TypeError, "Expected a callable Python object");
198
199     $1 = [=] (std::shared_ptr<sigrok::Device> device,
200             std::shared_ptr<sigrok::Packet> packet) {
201         auto gstate = PyGILState_Ensure();
202
203         auto device_obj = SWIG_NewPointerObj(
204             SWIG_as_voidptr(new std::shared_ptr<sigrok::Device>(device)),
205             SWIGTYPE_p_std__shared_ptrT_sigrok__Device_t, SWIG_POINTER_OWN);
206
207         auto packet_obj = SWIG_NewPointerObj(
208             SWIG_as_voidptr(new std::shared_ptr<sigrok::Packet>(packet)),
209             SWIGTYPE_p_std__shared_ptrT_sigrok__Packet_t, SWIG_POINTER_OWN);
210
211         auto arglist = Py_BuildValue("(OO)", device_obj, packet_obj);
212
213         auto result = PyEval_CallObject($input, arglist);
214
215         Py_XDECREF(arglist);
216         Py_XDECREF(device_obj);
217         Py_XDECREF(packet_obj);
218         Py_XDECREF(result);
219
220         PyGILState_Release(gstate);
221     };
222
223     Py_XINCREF($input);
224 }
225
226 %{
227
228 #include "libsigrok/libsigrok.hpp"
229
230 /* Convert from a Python dict to a std::map<std::string, std::string> */
231 std::map<std::string, std::string> dict_to_map(PyObject *dict)
232 {
233     if (!PyDict_Check(dict))
234         throw sigrok::Error(SR_ERR_ARG);
235
236     std::map<std::string, std::string> output;
237
238     PyObject *py_key, *py_value;
239     Py_ssize_t pos = 0;
240
241     while (PyDict_Next(dict, &pos, &py_key, &py_value)) {
242         if (!PyString_Check(py_key))
243             throw sigrok::Error(SR_ERR_ARG);
244         if (!PyString_Check(py_value))
245             throw sigrok::Error(SR_ERR_ARG);
246         auto key = PyString_AsString(py_key);
247         auto value = PyString_AsString(py_value);
248         output[key] = value;
249     }
250
251     return output;
252 }
253
254 /* Convert from a Python type to Glib::Variant, according to config key data type. */
255 Glib::VariantBase python_to_variant_by_key(PyObject *input, const sigrok::ConfigKey *key)
256 {
257     enum sr_datatype type = key->get_data_type()->get_id();
258
259     if (type == SR_T_UINT64 && PyInt_Check(input))
260         return Glib::Variant<guint64>::create(PyInt_AsLong(input));
261     if (type == SR_T_UINT64 && PyLong_Check(input))
262         return Glib::Variant<guint64>::create(PyLong_AsLong(input));
263     else if (type == SR_T_STRING && PyString_Check(input))
264         return Glib::Variant<std::string>::create(PyString_AsString(input));
265     else if (type == SR_T_BOOL && PyBool_Check(input))
266         return Glib::Variant<bool>::create(input == Py_True);
267     else if (type == SR_T_FLOAT && PyFloat_Check(input))
268         return Glib::Variant<double>::create(PyFloat_AsDouble(input));
269     else if (type == SR_T_INT32 && PyInt_Check(input))
270         return Glib::Variant<gint32>::create(PyInt_AsLong(input));
271     else
272         throw sigrok::Error(SR_ERR_ARG);
273 }
274
275 %}
276
277 /* Ignore these methods, we will override them below. */
278 %ignore sigrok::Driver::scan;
279 %ignore sigrok::InputFormat::open_file;
280 %ignore sigrok::OutputFormat::create_output;
281
282 %include "../../../swig/classes.i"
283
284 /* Support Driver.scan() with keyword arguments. */
285 %extend sigrok::Driver
286 {
287     std::vector<std::shared_ptr<sigrok::HardwareDevice> > _scan_kwargs(PyObject *dict)
288     {
289         if (!PyDict_Check(dict))
290             throw sigrok::Error(SR_ERR_ARG);
291
292         PyObject *py_key, *py_value;
293         Py_ssize_t pos = 0;
294         std::map<const sigrok::ConfigKey *, Glib::VariantBase> options;
295
296         while (PyDict_Next(dict, &pos, &py_key, &py_value))
297         {
298             if (!PyString_Check(py_key))
299                 throw sigrok::Error(SR_ERR_ARG);
300             auto key = sigrok::ConfigKey::get(PyString_AsString(py_key));
301             auto value = python_to_variant_by_key(py_value, key);
302             options[key] = value;
303         }
304
305         return $self->scan(options);
306     }
307 }
308
309 %pythoncode
310 {
311     def _Driver_scan(self, **kwargs):
312         return self._scan_kwargs(kwargs)
313
314     Driver.scan = _Driver_scan
315 }
316
317 /* Support InputFormat.open_file() with keyword arguments. */
318 %extend sigrok::InputFormat
319 {
320     std::shared_ptr<sigrok::InputFileDevice> _open_file_kwargs(std::string filename, PyObject *dict)
321     {
322         return $self->open_file(filename, dict_to_map(dict));
323     }
324 }
325
326 %pythoncode
327 {
328     def _InputFormat_open_file(self, filename, **kwargs):
329         return self._open_file_kwargs(filename, kwargs)
330
331     InputFormat.open_file = _InputFormat_open_file
332 }
333
334 /* Support OutputFormat.create_output() with keyword arguments. */
335 %extend sigrok::OutputFormat
336 {
337     std::shared_ptr<sigrok::Output> _create_output_kwargs(
338         std::shared_ptr<sigrok::Device> device, PyObject *dict)
339     {
340         return $self->create_output(device, dict_to_map(dict));
341     }
342 }
343
344 %pythoncode
345 {
346     def _OutputFormat_create_output(self, device, **kwargs):
347         return self._create_output_kwargs(device, kwargs)
348
349     OutputFormat.create_output = _OutputFormat_create_output
350 }
351
352 /* Support config_set() with Python input types. */
353 %extend sigrok::Configurable
354 {
355     void config_set(const ConfigKey *key, PyObject *input)
356     {
357         $self->config_set(key, python_to_variant_by_key(input, key));
358     }
359 }