Debian Codegraph @

src/gphoto2/port_log.i

raw
1 // python-gphoto2 - Python interface to libgphoto2
2 // http://github.com/jim-easterbrook/python-gphoto2
3 // Copyright (C) 2014-24 Jim Easterbrook [email protected]
4 //
5 // This file is part of python-gphoto2.
6 //
7 // python-gphoto2 is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU Lesser General Public License as published
9 // by the Free Software Foundation, either version 3 of the License, or
10 // (at your option) any later version.
11 //
12 // python-gphoto2 is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with python-gphoto2. If not, see <https://www.gnu.org/licenses/>.
19
20 %module(package="gphoto2") port_log
21
22 %include "common/preamble.i"
23
24 // Make docstring parameter types more Pythonic
25 %typemap(doc) enum GPLogLevel "$1_name: $1_type (gphoto2.GP_LOG_ERROR etc.)"
26
27 // Turn on default exception handling
28 DEFAULT_EXCEPTION
29
30 // Disallow varargs input to gp_log
31 %typemap(in) (...) %{
32 if (PyTuple_Size(varargs) > 0) {
33 PyErr_SetString(PyExc_ValueError,
34 "Too many arguments in function '$symname'.");
35 SWIG_fail;
36 }
37 %}
38
39 // SWIG can't wrap functions with var args
40 %ignore gp_logv;
41
42 // gp_log_xxx functions are not consistent between versions of libgphoto2
43 // they aren't needed by "front end" programs anyway, so just ignore them
44 %ignore gp_log_data;
45 %ignore gp_log_with_source_location;
46
47 // gp_log_remove_func is called when LogFuncItem is deleted
48 %ignore gp_log_remove_func;
49
50 // Object to store details of callback
51 %ignore LogFuncItem::id;
52 %ignore LogFuncItem::func;
53 %ignore LogFuncItem::data;
54 %ignore del_LogFuncItem;
55
56 %inline %{
57 typedef struct LogFuncItem {
58 int id;
59 PyObject *func;
60 PyObject *data;
61 } LogFuncItem;
62
63 // call gp_log_remove_func when LogFuncItem object is deleted
64 static int del_LogFuncItem(struct LogFuncItem *this) {
65 int error = GP_OK;
66 if (this->id >= 0)
67 error = gp_log_remove_func(this->id);
68 SWIG_Py_XDECREF(this->func);
69 SWIG_Py_XDECREF(this->data);
70 free(this);
71 return error;
72 };
73 %}
74
75 DEFAULT_DTOR(LogFuncItem, del_LogFuncItem);
76
77 // Call Python function from C callback
78 %{
79 static void gp_log_call_python(GPLogLevel level, const char *domain,
80 const char *str, void *data) {
81 if (!Py_IsInitialized()) {
82 return;
83 }
84 PyGILState_STATE gstate = PyGILState_Ensure();
85 LogFuncItem *this = data;
86 PyObject *result = NULL;
87 PyObject *arglist = NULL;
88 if (this->data) {
89 arglist = Py_BuildValue("(iNNO)", level,
90 PyUnicode_DecodeUTF8(domain, strlen(domain), "replace"),
91 PyUnicode_DecodeUTF8(str, strlen(str), "replace"), this->data);
92 } else {
93 arglist = Py_BuildValue("(iNN)", level,
94 PyUnicode_DecodeUTF8(domain, strlen(domain), "replace"),
95 PyUnicode_DecodeUTF8(str, strlen(str), "replace"));
96 }
97 if (arglist == NULL) {
98 PyErr_Print();
99 } else {
100 result = PyObject_CallObject(this->func, arglist);
101 SWIG_Py_DECREF(arglist);
102 if (result == NULL) {
103 PyErr_Print();
104 } else {
105 SWIG_Py_DECREF(result);
106 }
107 }
108 PyGILState_Release(gstate);
109 };
110 %}
111
112 // Use typemaps to replace Python callback & data with gp_log_call_python
113 %typemap(arginit) GPLogFunc (LogFuncItem *_global_callback) {
114 _global_callback = malloc(sizeof(LogFuncItem));
115 if (!_global_callback) {
116 PyErr_SetNone(PyExc_MemoryError);
117 SWIG_fail;
118 }
119 _global_callback->id = GP_ERROR;
120 _global_callback->func = NULL;
121 _global_callback->data = NULL;
122 }
123 %typemap(freearg) GPLogFunc {
124 if (_global_callback)
125 del_LogFuncItem(_global_callback);
126 }
127 %typemap(in) GPLogFunc {
128 if (!PyCallable_Check($input)) {
129 %argument_fail(SWIG_TypeError, callable, $symname, $argnum);
130 }
131 _global_callback->func = $input;
132 SWIG_Py_INCREF(_global_callback->func);
133 $1 = gp_log_call_python;
134 }
135 %typemap(argout) GPLogFunc {
136 _global_callback->id = result;
137 $result = SWIG_AppendOutput($result,
138 SWIG_NewPointerObj(_global_callback, $descriptor(LogFuncItem*), SWIG_POINTER_OWN));
139 _global_callback = NULL;
140 }
141 %typemap(doc) GPLogFunc "$1_name: callable function";
142
143 // make data optional and pass LogFuncItem object to gp_log_add_func
144 %typemap(default) void *data {
145 $1 = _global_callback;
146 }
147 %typemap(in) void *data {
148 _global_callback->data = $input;
149 SWIG_Py_INCREF(_global_callback->data);
150 }
151 %typemap(doc) void *data "$1_name: object (default=None)";
152
153 // Add static member methods to hypothetical Log object
154 %nodefaultdtor Log;
155 struct Log {};
156 MEMBER_FUNCTION(Log,
157 static int, add_func, (GPLogLevel level, GPLogFunc func, void *data),
158 gp_log_add_func, (level, func, data), )
159
160
161 // define use_python_logging function
162 %pythoncode %{
163 import logging
164
165 def _gphoto2_logger_cb(level, domain, msg, data):
166 log_func, mapping = data
167 if level in mapping:
168 log_func(mapping[level], '(%s) %s', domain, msg)
169 else:
170 log_func(logging.ERROR, '%d (%s) %s', level, domain, msg)
171
172 def use_python_logging(mapping={}):
173 """Install a callback to receive gphoto2 errors and forward them
174 to Python's logging system.
175
176 The return value is a tuple containing an error code and a Python object
177 containing details of the callback. Deleting this object will uninstall
178 the callback.
179
180 Parameters
181 ----------
182 * `mapping` :
183 a dictionary mapping any of the four gphoto2 logging severity
184 levels to a Python logging level. Note that anything below Python
185 DEBUG level will not be forwarded.
186
187 Returns
188 -------
189 a tuple containing an id or error code and a callback reference object.
190
191 """
192 full_mapping = {
193 GP_LOG_ERROR : logging.WARNING,
194 GP_LOG_VERBOSE : logging.INFO,
195 GP_LOG_DEBUG : logging.DEBUG,
196 GP_LOG_DATA : logging.DEBUG - 5,
197 }
198 full_mapping.update(mapping)
199 log_func = logging.getLogger('gphoto2').log
200 for level in (GP_LOG_DATA, GP_LOG_DEBUG, GP_LOG_VERBOSE, GP_LOG_ERROR):
201 if full_mapping[level] >= logging.DEBUG:
202 break
203 return gp_log_add_func(level, _gphoto2_logger_cb, (log_func, full_mapping))
204 %}
205
206 // Turn off default exception handling
207 %noexception;
208
209 %include "gphoto2/gphoto2-port-log.h"