-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaddybus-codegen.py
More file actions
executable file
·402 lines (333 loc) · 13 KB
/
taddybus-codegen.py
File metadata and controls
executable file
·402 lines (333 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#! /usr/bin/env python3
#
# Copyright (C) 2022 T+A elektroakustik GmbH & Co. KG
#
# This file is part of T+A-D-Bus.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
import argparse
import xml.etree.ElementTree as ET
from pathlib import Path
import sys
import re
def _mk_include_guard(options):
if options['include_guard']:
return options['include_guard']
if options['output']:
return options['output'].name.upper().replace('.', '_')
return options['FILE'].stem.upper() + '_HH'
def _write_header_top(hhfile, include_guard, gdbus_header, namespace):
template = """//
// Generated by taddybus-codegen.
// Do not modify!
//
#ifndef {}
#define {}
#include "dbus/{}"
#include "dbus/taddybus.hh"
namespace {}
{{"""
print(template.format(include_guard, include_guard, gdbus_header,
namespace),
file=hhfile)
def _write_header_bottom(hhfile, include_guard):
template = """}}
#endif /* !{} */"""
print(template.format(include_guard), file=hhfile)
def _to_snake_case(name, divider='_'):
return divider.join(re.findall(R'[A-Z]+$|[A-Z]*[a-z]+', name)).lower()
def _method_name(iface_type, name, is_call=False):
return _to_snake_case(iface_type) + '_' + name + ('()' if is_call else '')
def _simple_type_to_ctype(typespec):
dbus_type_to_ctype = {
"b": "gboolean",
"d": "gdouble",
"i": "gint",
"n": "gint16",
"o": "const gchar *",
"q": "guint16",
"s": "const gchar *",
"t": "guint64",
"u": "guint",
"v": "GVariant *",
"x": "gint64",
"y": "guchar"
}
ctype = dbus_type_to_ctype.get(typespec, None)
if ctype and ctype[-1] != '*':
return ctype + ' '
else:
return ctype
def _mk_c_argument_list(params, is_method):
args = []
for param in params.findall('arg'):
if is_method:
dir = param.attrib.get('direction', 'in')
if dir != 'in':
continue
argname = 'arg_' + param.attrib['name']
type = None
is_array = False
is_forced_gvariant = False
for anno in param.findall('annotation'):
if anno.attrib['name'] == 'org.gtk.GDBus.C.ForceGVariant' and \
anno.attrib['value'] == 'arg':
type = param.attrib['type']
is_array = True
is_forced_gvariant = True
break
if not type:
type = param.attrib['type']
is_array = type[0] == 'a'
if is_array:
if is_forced_gvariant or type[1:] not in ('s', 'o', 'y', 'ay'):
t = _simple_type_to_ctype('v') + argname + ' /* ' + type + ' */'
else:
if type[1] == 'y':
t = ''
else:
t = 'const *'
t = _simple_type_to_ctype('s') + t + argname
else:
t = _simple_type_to_ctype(type[0])
t += argname
args.append(t)
return args
def _format_argument_list(args, indent):
if not args:
return ''
spaces = ' ' * indent
return '\n' + spaces + (',\n' + spaces).join(args) + ','
def _write_method_code(hhfile, iface_name, iface_name_stripped, iface_type,
traits_prefix, fn_prefix, method):
handler_template = """// Method {}.{}
struct {};
template <>
struct MethodHandlerTraits<{}>
{{
private:
using ThisMethod = {};
public:
using IfaceType = {};
static const char *method_type_name() {{ return "{}"; }}
static const char *dbus_method_name() {{ return "{}.{}"; }}
static const char *glib_signal_name() {{ return "handle-{}"; }}
template <typename... UserDataT>
using UserData = Iface<IfaceType>::MethodHandlerData<ThisMethod, UserDataT...>;
template <typename... UserDataT>
using HandlerType =
gboolean(IfaceType *const object,
GDBusMethodInvocation *const invocation,{}
UserData<UserDataT...> *const d);
using ClassicHandlerType =
gboolean(IfaceType *const object,
GDBusMethodInvocation *const invocation,{}
gpointer);
/*!
* Handler for this D-Bus method.
*
* Must be implemented by application if it wants to handle this method.
* The handler is connected by calling D-Bus interface function
* #TDBus::Iface::connect_default_method_handler().
*/
static gboolean method_handler(
IfaceType *const object, GDBusMethodInvocation *const invocation,{}
Iface<IfaceType> *const iface);
static constexpr auto complete = {};
}};
"""
method_type = traits_prefix + iface_name_stripped + method.attrib['name']
args = _mk_c_argument_list(method, True)
complete_fn_name = \
_method_name(fn_prefix,
'complete_' + _to_snake_case(method.attrib['name']))
print(handler_template.format(iface_name, method.attrib['name'],
method_type, method_type, method_type,
iface_type, method_type,
iface_name, method.attrib['name'],
_to_snake_case(method.attrib['name'], '-'),
_format_argument_list(args, 17),
_format_argument_list(args, 17),
_format_argument_list(args, 12),
complete_fn_name),
file=hhfile)
caller_template = """template <>
struct MethodCallerTraits<{}>
{{
using IfaceType = {};
static constexpr auto invoke_sync = {};
static constexpr auto invoke = {};
static constexpr auto finish = {};
}};
"""
invoke_fn_name = \
_method_name(fn_prefix,
'call_' + _to_snake_case(method.attrib['name']))
finish_fn_name = \
_method_name(fn_prefix,
'call_' + _to_snake_case(method.attrib['name']) +
'_finish')
print(caller_template.format(method_type, iface_type,
invoke_fn_name + '_sync',
invoke_fn_name, finish_fn_name),
file=hhfile)
def _write_signal_code(hhfile, iface_name, iface_name_stripped, iface_type,
traits_prefix, signal):
template = """// Signal {}.{}
struct {};
template <>
struct SignalHandlerTraits<{}>
{{
private:
using ThisSignal = {};
public:
using IfaceType = {};
static const char *signal_type_name() {{ return "{}"; }}
static const char *dbus_signal_name() {{ return "{}.{}"; }}
static const char *glib_signal_name() {{ return "{}"; }}
template <typename... UserDataT>
using UserData = Proxy<IfaceType>::SignalHandlerData<ThisSignal, UserDataT...>;
template <typename... UserDataT>
using HandlerType =
void(IfaceType *const object,{}
UserData<UserDataT...> *const d);
using ClassicHandlerType =
void(IfaceType *const object,{}
gpointer);
/*!
* Handler for this D-Bus signal.
*
* Must be implemented by application if it wants to handle this signal.
* The handler is connected by calling proxy function
* #TDBus::Proxy::connect_default_signal_handler().
*/
static void signal_handler(
IfaceType *const object,{}
Proxy<IfaceType> *const proxy);
}};
"""
signal_type = traits_prefix + iface_name_stripped + signal.attrib['name']
args = _mk_c_argument_list(signal, False)
print(template.format(iface_name, signal.attrib['name'],
signal_type, signal_type, signal_type,
iface_type, signal_type,
iface_name, signal.attrib['name'],
_to_snake_case(signal.attrib['name'], '-'),
_format_argument_list(args, 13),
_format_argument_list(args, 13),
_format_argument_list(args, 12)),
file=hhfile)
if sys.version_info >= (3, 9, 0):
def _remove_prefix(s, p):
return s.removeprefix(p)
else:
def _remove_prefix(s, p):
return s[len(p):] if s.startswith(p) else s
def _write_interface_code(hhfile, iface, iface_prefix, method_traits_prefix,
signal_traits_prefix, c_namespace):
template = """
//
// D-Bus interface: {}
//
template <>
struct IfaceTraits<{}>
{{
static {} *skeleton_new() {{ return {}; }}
}};
template <>
struct ProxyTraits<{}>
{{
static ProxyBase::ProxyNewFunction
proxy_new_fn() {{ return {}; }}
static ProxyBase::ProxyNewFinishFunction<{}>
proxy_new_finish_fn() {{ return {}; }}
}};
"""
iface_name = iface.attrib['name']
iface_name_stripped = _remove_prefix(iface_name, iface_prefix)
iface_type = c_namespace.replace('_', '') + iface_name_stripped
fn_prefix = c_namespace + '_' + _to_snake_case(iface_name_stripped)
print(template.format(iface_name, iface_type, iface_type,
_method_name(fn_prefix, 'skeleton_new', True),
iface_type, _method_name(fn_prefix, 'proxy_new'),
iface_type,
_method_name(fn_prefix, 'proxy_new_finish')),
file=hhfile)
for method in iface.findall('method'):
_write_method_code(hhfile, iface_name, iface_name_stripped,
iface_type, method_traits_prefix, fn_prefix, method)
for signal in iface.findall('signal'):
_write_signal_code(hhfile, iface_name, iface_name_stripped,
iface_type, signal_traits_prefix, signal)
def _write_body(hhfile, spec, iface_prefix, method_traits_prefix,
signal_traits_prefix, c_namespace):
for iface in spec.findall('interface'):
_write_interface_code(hhfile, iface, iface_prefix,
method_traits_prefix, signal_traits_prefix,
c_namespace)
def main():
parser = argparse.ArgumentParser(
description='Generate C++ headers from D-Bus introspection data')
parser.add_argument(
'--interface-prefix', metavar='PREFIX', type=str,
help='string to strip from D-Bus interface names')
parser.add_argument(
'--c-namespace', metavar='NAMESPACE', type=str,
help='the namespace used by the C code generated by gdbus-codegen')
parser.add_argument(
'--cpp-namespace', metavar='NAMESPACE', type=str, default='TDBus',
help='the namespace to use for the generated C++ header '
'(default: TDBus)')
parser.add_argument(
'--cpp-traits-prefix', metavar='PREFIX', type=str, default='',
help='string to add to generated C++ traits structure names '
'(default: none)')
parser.add_argument(
'--cpp-traits-method-prefix', metavar='PREFIX', type=str, default='',
help='string to add to generated C++ traits structure names for D-Bus '
'methods (appended to prefix passed via --cpp-traits-prefix; '
'default: none)')
parser.add_argument(
'--cpp-traits-signal-prefix', metavar='PREFIX', type=str, default='',
help='string to add to generated C++ traits structure names for D-Bus '
'signals (appended to prefix passed via --cpp-traits-prefix; '
'default: none)')
parser.add_argument(
'--output', '-o', metavar='FILE', type=Path,
help='write C++ header to this file instead of stdout')
parser.add_argument(
'--include-guard', metavar='NAME', type=str,
help='name of the #include guard written to the header file')
parser.add_argument(
'FILE', type=Path,
help='XML file containing the D-Bus interface specification')
args = parser.parse_args()
options = vars(args)
xmlfile = ET.parse(options['FILE'].open())
hhfile = options['output'].open('w') if options['output'] else sys.stdout
include_guard = _mk_include_guard(options)
gdbus_header = options['FILE'].stem + '.h'
_write_header_top(hhfile, include_guard, gdbus_header,
options['cpp_namespace'])
_write_body(
hhfile, xmlfile, options['interface_prefix'],
options['cpp_traits_prefix'] + options['cpp_traits_method_prefix'],
options['cpp_traits_prefix'] + options['cpp_traits_signal_prefix'],
options['c_namespace'])
_write_header_bottom(hhfile, include_guard)
if __name__ == '__main__':
main()