comparison Framework/Orthanc/Resources/EmbedResources.py @ 1:2dbe613f6c93

add orthanc core
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 14 Oct 2016 15:39:01 +0200
parents
children
comparison
equal deleted inserted replaced
0:351ab0da0150 1:2dbe613f6c93
1 #!/usr/bin/python
2
3 # Orthanc - A Lightweight, RESTful DICOM Store
4 # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
5 # Department, University Hospital of Liege, Belgium
6 #
7 # This program is free software: you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
11 #
12 # In addition, as a special exception, the copyright holders of this
13 # program give permission to link the code of its release with the
14 # OpenSSL project's "OpenSSL" library (or with modified versions of it
15 # that use the same license as the "OpenSSL" library), and distribute
16 # the linked executables. You must obey the GNU General Public License
17 # in all respects for all of the code used other than "OpenSSL". If you
18 # modify file(s) with this exception, you may extend this exception to
19 # your version of the file(s), but you are not obligated to do so. If
20 # you do not wish to do so, delete this exception statement from your
21 # version. If you delete this exception statement from all source files
22 # in the program, then also delete it here.
23 #
24 # This program is distributed in the hope that it will be useful, but
25 # WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 # General Public License for more details.
28 #
29 # You should have received a copy of the GNU General Public License
30 # along with this program. If not, see <http://www.gnu.org/licenses/>.
31
32
33 import sys
34 import os
35 import os.path
36 import pprint
37 import re
38
39 UPCASE_CHECK = True
40 USE_SYSTEM_EXCEPTION = False
41 EXCEPTION_CLASS = 'OrthancException'
42 OUT_OF_RANGE_EXCEPTION = 'OrthancException(ErrorCode_ParameterOutOfRange)'
43 INEXISTENT_PATH_EXCEPTION = 'OrthancException(ErrorCode_InexistentItem)'
44 NAMESPACE = 'Orthanc'
45
46 ARGS = []
47 for i in range(len(sys.argv)):
48 if not sys.argv[i].startswith('--'):
49 ARGS.append(sys.argv[i])
50 elif sys.argv[i].lower() == '--no-upcase-check':
51 UPCASE_CHECK = False
52 elif sys.argv[i].lower() == '--system-exception':
53 USE_SYSTEM_EXCEPTION = True
54 EXCEPTION_CLASS = '::std::runtime_error'
55 OUT_OF_RANGE_EXCEPTION = '%s("Parameter out of range")' % EXCEPTION_CLASS
56 INEXISTENT_PATH_EXCEPTION = '%s("Unknown path in a directory resource")' % EXCEPTION_CLASS
57 elif sys.argv[i].startswith('--namespace='):
58 NAMESPACE = sys.argv[i][sys.argv[i].find('=') + 1 : ]
59
60 if len(ARGS) < 2 or len(ARGS) % 2 != 0:
61 print ('Usage:')
62 print ('python %s [--no-upcase-check] [--system-exception] [--namespace=<Namespace>] <TargetBaseFilename> [ <Name> <Source> ]*' % sys.argv[0])
63 exit(-1)
64
65 TARGET_BASE_FILENAME = ARGS[1]
66 SOURCES = ARGS[2:]
67
68 try:
69 # Make sure the destination directory exists
70 os.makedirs(os.path.normpath(os.path.join(TARGET_BASE_FILENAME, '..')))
71 except:
72 pass
73
74
75 #####################################################################
76 ## Read each resource file
77 #####################################################################
78
79 def CheckNoUpcase(s):
80 global UPCASE_CHECK
81 if (UPCASE_CHECK and
82 re.search('[A-Z]', s) != None):
83 raise Exception("Path in a directory with an upcase letter: %s" % s)
84
85 resources = {}
86
87 counter = 0
88 i = 0
89 while i < len(SOURCES):
90 resourceName = SOURCES[i].upper()
91 pathName = SOURCES[i + 1]
92
93 if not os.path.exists(pathName):
94 raise Exception("Non existing path: %s" % pathName)
95
96 if resourceName in resources:
97 raise Exception("Twice the same resource: " + resourceName)
98
99 if os.path.isdir(pathName):
100 # The resource is a directory: Recursively explore its files
101 content = {}
102 for root, dirs, files in os.walk(pathName):
103 base = os.path.relpath(root, pathName)
104
105 # Fix issue #24 (Build fails on OSX when directory has .DS_Store files):
106 # Ignore folders whose name starts with a dot (".")
107 if base.find('/.') != -1:
108 print('Ignoring folder: %s' % root)
109 continue
110
111 for f in files:
112 if f.find('~') == -1: # Ignore Emacs backup files
113 if base == '.':
114 r = f
115 else:
116 r = os.path.join(base, f)
117
118 CheckNoUpcase(r)
119 r = '/' + r.replace('\\', '/')
120 if r in content:
121 raise Exception("Twice the same filename (check case): " + r)
122
123 content[r] = {
124 'Filename' : os.path.join(root, f),
125 'Index' : counter
126 }
127 counter += 1
128
129 resources[resourceName] = {
130 'Type' : 'Directory',
131 'Files' : content
132 }
133
134 elif os.path.isfile(pathName):
135 resources[resourceName] = {
136 'Type' : 'File',
137 'Index' : counter,
138 'Filename' : pathName
139 }
140 counter += 1
141
142 else:
143 raise Exception("Not a regular file, nor a directory: " + pathName)
144
145 i += 2
146
147 #pprint.pprint(resources)
148
149
150 #####################################################################
151 ## Write .h header
152 #####################################################################
153
154 header = open(TARGET_BASE_FILENAME + '.h', 'w')
155
156 header.write("""
157 #pragma once
158
159 #include <string>
160 #include <list>
161
162 namespace %s
163 {
164 namespace EmbeddedResources
165 {
166 enum FileResourceId
167 {
168 """ % NAMESPACE)
169
170 isFirst = True
171 for name in resources:
172 if resources[name]['Type'] == 'File':
173 if isFirst:
174 isFirst = False
175 else:
176 header.write(',\n')
177 header.write(' %s' % name)
178
179 header.write("""
180 };
181
182 enum DirectoryResourceId
183 {
184 """)
185
186 isFirst = True
187 for name in resources:
188 if resources[name]['Type'] == 'Directory':
189 if isFirst:
190 isFirst = False
191 else:
192 header.write(',\n')
193 header.write(' %s' % name)
194
195 header.write("""
196 };
197
198 const void* GetFileResourceBuffer(FileResourceId id);
199 size_t GetFileResourceSize(FileResourceId id);
200 void GetFileResource(std::string& result, FileResourceId id);
201
202 const void* GetDirectoryResourceBuffer(DirectoryResourceId id, const char* path);
203 size_t GetDirectoryResourceSize(DirectoryResourceId id, const char* path);
204 void GetDirectoryResource(std::string& result, DirectoryResourceId id, const char* path);
205
206 void ListResources(std::list<std::string>& result, DirectoryResourceId id);
207 }
208 }
209 """)
210 header.close()
211
212
213
214 #####################################################################
215 ## Write the resource content in the .cpp source
216 #####################################################################
217
218 PYTHON_MAJOR_VERSION = sys.version_info[0]
219
220 def WriteResource(cpp, item):
221 cpp.write(' static const uint8_t resource%dBuffer[] = {' % item['Index'])
222
223 f = open(item['Filename'], "rb")
224 content = f.read()
225 f.close()
226
227 # http://stackoverflow.com/a/1035360
228 pos = 0
229 for b in content:
230 if PYTHON_MAJOR_VERSION == 2:
231 c = ord(b[0])
232 else:
233 c = b
234
235 if pos > 0:
236 cpp.write(', ')
237
238 if (pos % 16) == 0:
239 cpp.write('\n ')
240
241 if c < 0:
242 raise Exception("Internal error")
243
244 cpp.write("0x%02x" % c)
245 pos += 1
246
247 # Zero-size array are disallowed, so we put one single void character in it.
248 if pos == 0:
249 cpp.write(' 0')
250
251 cpp.write(' };\n')
252 cpp.write(' static const size_t resource%dSize = %d;\n' % (item['Index'], pos))
253
254
255 cpp = open(TARGET_BASE_FILENAME + '.cpp', 'w')
256
257 cpp.write('#include "%s.h"\n' % os.path.basename(TARGET_BASE_FILENAME))
258
259 if USE_SYSTEM_EXCEPTION:
260 cpp.write('#include <stdexcept>')
261 else:
262 cpp.write('#include "%s/Core/OrthancException.h"' % os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
263
264 cpp.write("""
265 #include <stdint.h>
266 #include <string.h>
267
268 namespace %s
269 {
270 namespace EmbeddedResources
271 {
272 """ % NAMESPACE)
273
274
275 for name in resources:
276 if resources[name]['Type'] == 'File':
277 WriteResource(cpp, resources[name])
278 else:
279 for f in resources[name]['Files']:
280 WriteResource(cpp, resources[name]['Files'][f])
281
282
283
284 #####################################################################
285 ## Write the accessors to the file resources in .cpp
286 #####################################################################
287
288 cpp.write("""
289 const void* GetFileResourceBuffer(FileResourceId id)
290 {
291 switch (id)
292 {
293 """)
294 for name in resources:
295 if resources[name]['Type'] == 'File':
296 cpp.write(' case %s:\n' % name)
297 cpp.write(' return resource%dBuffer;\n' % resources[name]['Index'])
298
299 cpp.write("""
300 default:
301 throw %s;
302 }
303 }
304
305 size_t GetFileResourceSize(FileResourceId id)
306 {
307 switch (id)
308 {
309 """ % OUT_OF_RANGE_EXCEPTION)
310
311 for name in resources:
312 if resources[name]['Type'] == 'File':
313 cpp.write(' case %s:\n' % name)
314 cpp.write(' return resource%dSize;\n' % resources[name]['Index'])
315
316 cpp.write("""
317 default:
318 throw %s;
319 }
320 }
321 """ % OUT_OF_RANGE_EXCEPTION)
322
323
324
325 #####################################################################
326 ## Write the accessors to the directory resources in .cpp
327 #####################################################################
328
329 cpp.write("""
330 const void* GetDirectoryResourceBuffer(DirectoryResourceId id, const char* path)
331 {
332 switch (id)
333 {
334 """)
335
336 for name in resources:
337 if resources[name]['Type'] == 'Directory':
338 cpp.write(' case %s:\n' % name)
339 isFirst = True
340 for path in resources[name]['Files']:
341 cpp.write(' if (!strcmp(path, "%s"))\n' % path)
342 cpp.write(' return resource%dBuffer;\n' % resources[name]['Files'][path]['Index'])
343 cpp.write(' throw %s;\n\n' % INEXISTENT_PATH_EXCEPTION)
344
345 cpp.write(""" default:
346 throw %s;
347 }
348 }
349
350 size_t GetDirectoryResourceSize(DirectoryResourceId id, const char* path)
351 {
352 switch (id)
353 {
354 """ % OUT_OF_RANGE_EXCEPTION)
355
356 for name in resources:
357 if resources[name]['Type'] == 'Directory':
358 cpp.write(' case %s:\n' % name)
359 isFirst = True
360 for path in resources[name]['Files']:
361 cpp.write(' if (!strcmp(path, "%s"))\n' % path)
362 cpp.write(' return resource%dSize;\n' % resources[name]['Files'][path]['Index'])
363 cpp.write(' throw %s;\n\n' % INEXISTENT_PATH_EXCEPTION)
364
365 cpp.write(""" default:
366 throw %s;
367 }
368 }
369 """ % OUT_OF_RANGE_EXCEPTION)
370
371
372
373
374 #####################################################################
375 ## List the resources in a directory
376 #####################################################################
377
378 cpp.write("""
379 void ListResources(std::list<std::string>& result, DirectoryResourceId id)
380 {
381 result.clear();
382
383 switch (id)
384 {
385 """)
386
387 for name in resources:
388 if resources[name]['Type'] == 'Directory':
389 cpp.write(' case %s:\n' % name)
390 for path in sorted(resources[name]['Files']):
391 cpp.write(' result.push_back("%s");\n' % path)
392 cpp.write(' break;\n\n')
393
394 cpp.write(""" default:
395 throw %s;
396 }
397 }
398 """ % OUT_OF_RANGE_EXCEPTION)
399
400
401
402
403 #####################################################################
404 ## Write the convenience wrappers in .cpp
405 #####################################################################
406
407 cpp.write("""
408 void GetFileResource(std::string& result, FileResourceId id)
409 {
410 size_t size = GetFileResourceSize(id);
411 result.resize(size);
412 if (size > 0)
413 memcpy(&result[0], GetFileResourceBuffer(id), size);
414 }
415
416 void GetDirectoryResource(std::string& result, DirectoryResourceId id, const char* path)
417 {
418 size_t size = GetDirectoryResourceSize(id, path);
419 result.resize(size);
420 if (size > 0)
421 memcpy(&result[0], GetDirectoryResourceBuffer(id, path), size);
422 }
423 }
424 }
425 """)
426 cpp.close()