0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 ##
|
|
4 ## Python plugin for Orthanc
|
|
5 ## Copyright (C) 2017-2020 Osimis S.A., Belgium
|
|
6 ##
|
|
7 ## This program is free software: you can redistribute it and/or
|
|
8 ## modify it under the terms of the GNU Affero General Public License
|
|
9 ## as published by the Free Software Foundation, either version 3 of
|
|
10 ## the License, or (at your option) any later version.
|
|
11 ##
|
|
12 ## This program is distributed in the hope that it will be useful, but
|
|
13 ## WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
15 ## Affero General Public License for more details.
|
|
16 ##
|
|
17 ## You should have received a copy of the GNU Affero General Public License
|
|
18 ## along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19 ##
|
|
20
|
|
21
|
|
22 # Ubuntu 18.04:
|
|
23 # sudo apt-get install python-clang-4.0
|
|
24 # python2 ./ParseOrthancSDK.py --libclang=libclang-4.0.so.1 ../Resources/Orthanc/Sdk-1.5.7/orthanc/OrthancCPlugin.h ../Sources/Autogenerated
|
|
25
|
|
26
|
|
27 import argparse
|
|
28 import clang.cindex
|
|
29 import os
|
|
30 import pprint
|
|
31 import pystache
|
|
32 import sys
|
|
33
|
|
34
|
|
35 ROOT = os.path.dirname(os.path.realpath(sys.argv[0]))
|
|
36
|
|
37
|
|
38 ##
|
|
39 ## Parse the command-line arguments
|
|
40 ##
|
|
41
|
|
42 parser = argparse.ArgumentParser(description = 'Parse the Orthanc SDK.')
|
|
43 parser.add_argument('--libclang',
|
|
44 default = 'libclang-4.0.so.1',
|
|
45 help = 'manually provides the path to the libclang shared library')
|
|
46 parser.add_argument('--source',
|
|
47 default = os.path.join(os.path.dirname(__file__),
|
|
48 '../Resources/Orthanc/Sdk-1.5.7/orthanc/OrthancCPlugin.h'),
|
|
49 help = 'Input C++ file')
|
|
50 parser.add_argument('--target',
|
|
51 default = os.path.join(os.path.dirname(__file__),
|
|
52 '../Sources/Autogenerated'),
|
|
53 help = 'Target folder')
|
|
54
|
|
55 args = parser.parse_args()
|
|
56
|
|
57
|
|
58
|
|
59 if len(args.libclang) != 0:
|
|
60 clang.cindex.Config.set_library_file(args.libclang)
|
|
61
|
|
62 index = clang.cindex.Index.create()
|
|
63
|
|
64 tu = index.parse(args.source, [ ])
|
|
65
|
|
66 TARGET = os.path.realpath(args.target)
|
|
67
|
|
68
|
|
69
|
|
70 def ToUpperCase(name):
|
|
71 s = ''
|
|
72 for i in range(len(name)):
|
|
73 if name[i].isupper():
|
|
74 if len(s) == 0:
|
|
75 s += name[i]
|
|
76 elif name[i - 1].islower():
|
|
77 s += '_' + name[i]
|
|
78 elif (i + 1 < len(name) and
|
|
79 name[i - 1].islower() and
|
|
80 name[i + 1].isupper()):
|
|
81 s += '_' + name[i]
|
|
82 else:
|
|
83 s += name[i]
|
|
84 else:
|
|
85 s += name[i].upper()
|
|
86 return s
|
|
87
|
|
88
|
|
89
|
|
90 with open(os.path.join(ROOT, 'Enumeration.mustache'), 'r') as f:
|
|
91 TEMPLATE = f.read()
|
|
92
|
|
93
|
|
94 classes = {}
|
|
95 enumerations = {}
|
|
96 globalFunctions = []
|
2
|
97 countAllFunctions = 0
|
|
98 countSupportedFunctions = 0
|
0
|
99
|
|
100 def IsSourceStringType(t):
|
|
101 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
102 t.get_pointee().kind == clang.cindex.TypeKind.CHAR_S and
|
|
103 t.get_pointee().is_const_qualified())
|
|
104
|
|
105 def IsTargetStaticStringType(t):
|
|
106 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
107 t.get_pointee().kind == clang.cindex.TypeKind.CHAR_S and
|
|
108 t.get_pointee().is_const_qualified())
|
|
109
|
|
110 def IsTargetDynamicStringType(t):
|
|
111 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
112 t.get_pointee().kind == clang.cindex.TypeKind.CHAR_S and
|
|
113 not t.get_pointee().is_const_qualified())
|
|
114
|
|
115 def IsIntegerType(t):
|
|
116 return (t.kind == clang.cindex.TypeKind.INT or
|
|
117 t.spelling in [ 'int8_t', 'int16_t', 'int32_t', 'int64_t',
|
|
118 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t'])
|
|
119
|
|
120 def IsFloatType(t):
|
|
121 return t.kind == clang.cindex.TypeKind.FLOAT
|
|
122
|
|
123 def IsEnumerationType(t):
|
|
124 return (t.kind == clang.cindex.TypeKind.TYPEDEF and
|
|
125 t.spelling in enumerations)
|
|
126
|
|
127 def IsTargetMemoryBufferType(t):
|
|
128 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
129 not t.get_pointee().is_const_qualified() and
|
|
130 t.get_pointee().spelling == 'OrthancPluginMemoryBuffer')
|
|
131
|
|
132 def IsSourceMemoryBufferType(t):
|
|
133 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
134 t.get_pointee().kind == clang.cindex.TypeKind.VOID and
|
|
135 t.get_pointee().is_const_qualified())
|
|
136
|
|
137 def IsClassType(t):
|
|
138 return (t.kind == clang.cindex.TypeKind.POINTER and
|
|
139 ((t.get_pointee().is_const_qualified() and
|
|
140 t.get_pointee().spelling.startswith('const ') and
|
|
141 t.get_pointee().spelling[len('const '):] in classes) or
|
|
142 (not t.get_pointee().is_const_qualified() and
|
|
143 t.get_pointee().spelling in classes)))
|
|
144
|
|
145 def IsSimpleSourceType(t):
|
|
146 return (IsSourceStringType(t) or
|
|
147 IsFloatType(t) or
|
|
148 IsIntegerType(t) or
|
|
149 IsEnumerationType(t) or
|
|
150 IsSourceMemoryBufferType(t))
|
|
151
|
|
152 def IsVoidType(t):
|
|
153 return t.kind == clang.cindex.TypeKind.VOID
|
|
154
|
|
155 def IsSupportedTargetType(t):
|
|
156 return (IsVoidType(t) or
|
|
157 IsIntegerType(t) or
|
|
158 IsEnumerationType(t) or
|
|
159 # Constructor of a class
|
|
160 (t.kind == clang.cindex.TypeKind.POINTER and
|
|
161 not t.get_pointee().is_const_qualified() and
|
|
162 t.get_pointee().spelling in classes) or
|
|
163 # "const char*" or "char*" outputs
|
|
164 (t.kind == clang.cindex.TypeKind.POINTER and
|
|
165 #not t.get_pointee().is_const_qualified() and
|
|
166 t.get_pointee().kind == clang.cindex.TypeKind.CHAR_S))
|
|
167
|
|
168 def IsBytesArgument(args, index):
|
|
169 return (index + 1 < len(args) and
|
|
170 args[index].type.kind == clang.cindex.TypeKind.POINTER and
|
|
171 args[index].type.get_pointee().kind == clang.cindex.TypeKind.VOID and
|
|
172 args[index].type.get_pointee().is_const_qualified() and
|
|
173 args[index + 1].type.spelling == 'uint32_t')
|
|
174
|
|
175 def CheckOnlySupportedArguments(args):
|
|
176 j = 0
|
|
177 while j < len(args):
|
|
178 if IsBytesArgument(args, j):
|
|
179 j += 2
|
|
180 elif IsSimpleSourceType(args[j].type):
|
|
181 j += 1
|
|
182 else:
|
|
183 return False
|
|
184 return True
|
|
185
|
|
186
|
|
187 ORTHANC_TO_PYTHON_NUMERIC_TYPES = {
|
|
188 # https://docs.python.org/3/c-api/arg.html#numbers
|
|
189 'int' : {
|
|
190 'type' : 'int',
|
|
191 'format' : 'i',
|
|
192 },
|
|
193 'uint8_t' : {
|
|
194 'type' : 'unsigned char',
|
|
195 'format' : 'b',
|
|
196 },
|
|
197 'int32_t' : {
|
|
198 'type' : 'long int',
|
|
199 'format' : 'l',
|
|
200 },
|
|
201 'uint16_t' : {
|
|
202 'type' : 'unsigned short',
|
|
203 'format' : 'H',
|
|
204 },
|
|
205 'uint32_t' : {
|
|
206 'type' : 'unsigned long',
|
|
207 'format' : 'k',
|
|
208 },
|
|
209 'uint64_t' : {
|
|
210 'type' : 'unsigned long long',
|
|
211 'format' : 'K',
|
|
212 },
|
|
213 'float' : {
|
|
214 'type' : 'float',
|
|
215 'format' : 'f',
|
|
216 }
|
|
217 }
|
|
218
|
|
219
|
|
220 def GenerateFunctionBodyTemplate(cFunction, result_type, args):
|
|
221 if not cFunction.startswith('OrthancPlugin'):
|
|
222 raise Exception()
|
|
223
|
|
224 func = {
|
|
225 'c_function' : cFunction,
|
|
226 'short_name' : cFunction[len('OrthancPlugin'):],
|
|
227 'args' : [],
|
|
228 }
|
|
229
|
|
230 if IsIntegerType(result_type):
|
|
231 func['return_long'] = True
|
|
232 elif IsTargetDynamicStringType(result_type):
|
|
233 func['return_dynamic_string'] = True
|
|
234 elif IsTargetStaticStringType(result_type):
|
|
235 func['return_static_string'] = True
|
|
236 elif IsVoidType(result_type):
|
|
237 func['return_void'] = True
|
|
238 elif result_type.spelling == 'OrthancPluginErrorCode':
|
|
239 func['return_error'] = True
|
|
240 elif IsClassType(result_type):
|
|
241 func['return_object'] = result_type.get_pointee().spelling
|
|
242 elif IsTargetMemoryBufferType(result_type):
|
|
243 func['return_bytes'] = True
|
|
244 elif IsEnumerationType(result_type):
|
|
245 func['return_enumeration'] = result_type.spelling
|
|
246 else:
|
|
247 raise Exception('Not supported: %s' % result_type.spelling)
|
|
248
|
|
249 i = 0
|
|
250 while i < len(args):
|
|
251 a = {
|
|
252 'name' : 'arg%d' % i,
|
|
253 }
|
|
254
|
|
255 if (IsIntegerType(args[i].type) or
|
|
256 IsFloatType(args[i].type)):
|
|
257 t = ORTHANC_TO_PYTHON_NUMERIC_TYPES[args[i].type.spelling]
|
|
258 a['python_type'] = t['type']
|
|
259 a['python_format'] = t['format']
|
|
260 a['initialization'] = ' = 0'
|
|
261 a['orthanc_cast'] = 'arg%d' % i
|
|
262 func['args'].append(a)
|
|
263 elif IsSourceStringType(args[i].type):
|
|
264 a['python_type'] = 'const char*'
|
|
265 a['python_format'] = 's'
|
|
266 a['initialization'] = ' = NULL'
|
|
267 a['orthanc_cast'] = 'arg%d' % i
|
|
268 func['args'].append(a)
|
|
269 elif IsEnumerationType(args[i].type):
|
|
270 a['python_type'] = 'long int'
|
|
271 a['python_format'] = 'l'
|
|
272 a['initialization'] = ' = 0'
|
|
273 a['orthanc_cast'] = 'static_cast<%s>(arg%d)' % (args[i].type.spelling, i)
|
|
274 func['args'].append(a)
|
|
275 elif IsBytesArgument(args, i):
|
|
276 a['python_type'] = 'Py_buffer'
|
|
277 # In theory, one should use "y*" (this is the recommended
|
|
278 # way to accept binary data). However, this is not
|
|
279 # available in Python 2.7
|
|
280 a['python_format'] = 's*'
|
|
281 a['orthanc_cast'] = 'arg%d.buf, arg%d.len' % (i, i)
|
|
282 a['release'] = 'PyBuffer_Release(&arg%d);' % i
|
|
283 func['args'].append(a)
|
|
284 i += 1
|
|
285 elif IsSourceMemoryBufferType(args[i].type):
|
|
286 a['python_type'] = 'Py_buffer'
|
|
287 a['python_format'] = 's*'
|
|
288 a['orthanc_cast'] = 'arg%d.buf' % i
|
|
289 a['release'] = 'PyBuffer_Release(&arg%d);' % i
|
|
290 func['args'].append(a)
|
|
291 else:
|
|
292 raise Exception('Not supported: %s, %s' % (cFunction, args[i].spelling))
|
|
293
|
|
294 i += 1
|
|
295
|
|
296 func['tuple_format'] = '"%s", %s' % (
|
|
297 ''.join(map(lambda x: x['python_format'], func['args'])),
|
|
298 ', '.join(map(lambda x: '&' + x['name'], func['args'])))
|
|
299
|
|
300 if len(func['args']) > 0:
|
|
301 func['count_args'] = len(func['args'])
|
|
302 func['has_args'] = True
|
|
303 func['call_args'] = ', ' + ', '.join(map(lambda x: x['orthanc_cast'], func['args']))
|
|
304
|
|
305 return func
|
|
306
|
|
307
|
|
308 for node in tu.cursor.get_children():
|
|
309 if node.kind == clang.cindex.CursorKind.ENUM_DECL:
|
|
310 if node.type.spelling.startswith('OrthancPlugin'):
|
|
311 name = node.type.spelling
|
|
312
|
|
313 values = []
|
|
314 for item in node.get_children():
|
|
315 if (item.kind == clang.cindex.CursorKind.ENUM_CONSTANT_DECL and
|
|
316 item.spelling.startswith(name + '_')):
|
|
317 values.append({
|
|
318 'key' : ToUpperCase(item.spelling[len(name)+1:]),
|
|
319 'value' : item.enum_value
|
|
320 })
|
|
321
|
|
322 path = 'sdk_%s.impl.h' % name
|
|
323 shortName = name[len('OrthancPlugin'):]
|
|
324
|
|
325 with open(os.path.join(TARGET, path), 'w') as f:
|
|
326 f.write(pystache.render(TEMPLATE, {
|
|
327 'name' : name,
|
|
328 'short_name' : shortName,
|
|
329 'values' : values,
|
|
330 }))
|
|
331
|
|
332 enumerations[name] = {
|
|
333 'name' : name,
|
|
334 'path' : path,
|
|
335 }
|
|
336
|
|
337 elif node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
|
|
338 if node.spelling.startswith('OrthancPlugin'):
|
|
339 #if node.spelling != 'OrthancPluginWorklistGetDicomQuery':
|
|
340 # continue
|
|
341 shortName = node.spelling[len('OrthancPlugin'):]
|
|
342
|
|
343 # Check that the first argument is the Orthanc context
|
|
344 args = list(filter(lambda x: x.kind == clang.cindex.CursorKind.PARM_DECL,
|
|
345 node.get_children()))
|
|
346
|
|
347 if (len(args) == 0 or
|
|
348 args[0].type.kind != clang.cindex.TypeKind.POINTER or
|
|
349 args[0].type.get_pointee().spelling != 'OrthancPluginContext'):
|
|
350 print('Not in the Orthanc SDK: %s()' % node.spelling)
|
|
351 continue
|
|
352
|
|
353 # Discard the context from the arguments
|
2
|
354 countAllFunctions += 1
|
0
|
355 args = args[1:]
|
|
356
|
|
357 if not IsSupportedTargetType(node.result_type):
|
|
358 print('*** UNSUPPORTED OUTPUT: %s' % node.spelling)
|
|
359
|
|
360 elif (len(args) == 1 and
|
|
361 IsClassType(args[0].type) and
|
|
362 node.spelling.startswith('OrthancPluginFree')):
|
|
363 print('Destructor: %s' % node.spelling)
|
|
364 className = args[0].type.get_pointee().spelling
|
|
365 classes[className]['destructor'] = node.spelling
|
2
|
366 countSupportedFunctions += 1
|
0
|
367
|
|
368 elif CheckOnlySupportedArguments(args):
|
|
369 if IsClassType(node.result_type):
|
|
370 print('Constructor: %s' % node.spelling)
|
|
371 else:
|
|
372 print('Simple global function: %s => %s' % (node.spelling, node.result_type.spelling))
|
|
373
|
|
374 body = GenerateFunctionBodyTemplate(node.spelling, node.result_type, args)
|
|
375 globalFunctions.append(body)
|
2
|
376 countSupportedFunctions += 1
|
0
|
377
|
|
378 elif (len(args) >= 2 and
|
|
379 IsTargetMemoryBufferType(args[0].type) and
|
|
380 CheckOnlySupportedArguments(args[1:])):
|
|
381 print('Simple global function, returning bytes: %s' % node.spelling)
|
|
382
|
|
383 body = GenerateFunctionBodyTemplate(node.spelling, args[0].type, args[1:])
|
|
384 globalFunctions.append(body)
|
2
|
385 countSupportedFunctions += 1
|
0
|
386
|
|
387 elif (IsClassType(args[0].type) and
|
|
388 CheckOnlySupportedArguments(args[1:])):
|
|
389 className = args[0].type.get_pointee().spelling
|
|
390
|
|
391 if className.startswith('const '):
|
|
392 className = className[len('const '):]
|
|
393
|
|
394 print('Simple method of class %s: %s' % (className, node.spelling))
|
|
395
|
|
396 method = GenerateFunctionBodyTemplate(node.spelling, node.result_type, args[1:])
|
|
397 method['self'] = ', self->object_'
|
|
398 classes[className]['methods'].append(method)
|
2
|
399 countSupportedFunctions += 1
|
0
|
400
|
|
401 elif (len(args) >= 2 and
|
|
402 IsTargetMemoryBufferType(args[0].type) and
|
|
403 IsClassType(args[1].type) and
|
|
404 CheckOnlySupportedArguments(args[2:])):
|
|
405 print('Simple method of class %s, returning bytes: %s' % (
|
|
406 args[0].type.get_pointee().spelling,
|
|
407 node.spelling))
|
|
408
|
|
409 method = GenerateFunctionBodyTemplate(node.spelling, args[0].type, args[2:])
|
|
410 method['self'] = ', self->object_'
|
|
411 classes[className]['methods'].append(method)
|
2
|
412 countSupportedFunctions += 1
|
0
|
413
|
|
414 else:
|
|
415 print('*** UNSUPPORTED INPUT: %s' % node.spelling)
|
|
416
|
|
417
|
|
418
|
|
419 elif node.kind == clang.cindex.CursorKind.STRUCT_DECL:
|
|
420 if (node.spelling.startswith('_OrthancPlugin') and
|
|
421 node.spelling.endswith('_t') and
|
|
422 node.spelling != '_OrthancPluginContext_t'):
|
|
423 name = node.spelling[len('_') : -len('_t')]
|
|
424 classes[name] = {
|
|
425 'class_name' : name,
|
|
426 'short_name' : name[len('OrthancPlugin'):],
|
|
427 'methods' : [ ]
|
|
428 }
|
|
429
|
|
430
|
|
431
|
|
432
|
|
433 partials = {}
|
|
434
|
|
435 with open(os.path.join(ROOT, 'FunctionBody.mustache'), 'r') as f:
|
|
436 partials['function_body'] = f.read()
|
|
437
|
|
438 renderer = pystache.Renderer(
|
|
439 escape = lambda u: u, # No escaping
|
|
440 partials = partials,
|
|
441 )
|
|
442
|
|
443 with open(os.path.join(ROOT, 'Class.mustache'), 'r') as f:
|
|
444 template = f.read()
|
|
445
|
|
446 for (key, value) in classes.items():
|
|
447 with open(os.path.join(TARGET, 'sdk_%s.impl.h' % value['class_name']), 'w') as h:
|
|
448 h.write(renderer.render(template, value))
|
|
449
|
|
450
|
|
451 def FlattenDictionary(source):
|
|
452 result = []
|
|
453 for (key, value) in source.items():
|
|
454 result.append(value)
|
|
455 return result
|
|
456
|
|
457
|
|
458 with open(os.path.join(ROOT, 'GlobalFunctions.mustache'), 'r') as f:
|
|
459 with open(os.path.join(TARGET, 'sdk_GlobalFunctions.impl.h'), 'w') as h:
|
|
460 h.write(renderer.render(f.read(), {
|
|
461 'global_functions' : globalFunctions,
|
|
462 }))
|
|
463
|
|
464 with open(os.path.join(ROOT, 'sdk.cpp.mustache'), 'r') as f:
|
|
465 with open(os.path.join(TARGET, 'sdk.cpp'), 'w') as h:
|
|
466 h.write(renderer.render(f.read(), {
|
|
467 'classes' : FlattenDictionary(classes),
|
|
468 'enumerations' : FlattenDictionary(enumerations),
|
|
469 'global_functions' : globalFunctions,
|
|
470 }))
|
|
471
|
|
472 with open(os.path.join(ROOT, 'sdk.h.mustache'), 'r') as f:
|
|
473 with open(os.path.join(TARGET, 'sdk.h'), 'w') as h:
|
|
474 h.write(renderer.render(f.read(), {
|
|
475 'classes' : FlattenDictionary(classes),
|
|
476 }))
|
2
|
477
|
|
478
|
|
479 print('')
|
|
480 print('Total functions in the SDK: %d' % countAllFunctions)
|
|
481 print('Total supported functions: %d' % countSupportedFunctions)
|
|
482 print('Coverage: %.0f%%' % (float(countSupportedFunctions) /
|
|
483 float(countAllFunctions) * 100.0))
|