-
Notifications
You must be signed in to change notification settings - Fork 32
/
common.py
5039 lines (3750 loc) · 179 KB
/
common.py
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Common Generator Library
Copyright (C) 2012-2017, 2019 Matthias Bolte <[email protected]>
Copyright (C) 2012-2015, 2019 Olaf Lüke <[email protected]>
Copyright (C) 2020 Erik Fleckstein <[email protected]>
common.py: Common library for generation of bindings and documentation
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
"""
import os
import shutil
import re
import datetime
import subprocess
import sys
import copy
import math
import multiprocessing.dummy
import functools
from collections import namedtuple
import importlib
import argparse
import shlex
from generators.configs import device_commonconfig
gen_text_rst = """..
#############################################################
# This file was automatically generated on {0}. #
# #
# If you have a bugfix for this file and want to commit it, #
# please fix the bug in the generator. You can find a link #
# to the generators git repository on tinkerforge.com #
#############################################################
"""
bf_str = {
'en': """
Basic Functions
^^^^^^^^^^^^^^^
{0}
{1}
""",
'de': """
Grundfunktionen
^^^^^^^^^^^^^^^
{0}
{1}
"""
}
af_str = {
'en': """
Advanced Functions
^^^^^^^^^^^^^^^^^^
{0}
""",
'de': """
Fortgeschrittene Funktionen
^^^^^^^^^^^^^^^^^^^^^^^^^^^
{0}
"""
}
ccf_str = {
'en': """
Callback Configuration Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{0}
{1}
""",
'de': """
Konfigurationsfunktionen für Callbacks
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{0}
{1}
"""
}
vf_str = {
'en': """
Virtual Functions
^^^^^^^^^^^^^^^^^
Virtual functions don't communicate with the device itself, but operate only on
the API bindings device object. They can be called without the corresponding
IP Connection object being connected.
{0}
""",
'de': """
Virtuelle Funktionen
^^^^^^^^^^^^^^^^^^^^
Virtuelle Funktionen kommunizieren nicht mit dem Gerät selbst, sie arbeiten nur
auf dem API Bindings Objekt. Dadurch können sie auch aufgerufen werden, ohne das
das dazugehörige IP Connection Objekt verbunden ist.
{0}
"""
}
if_str = {
'en': """
Internal Functions
^^^^^^^^^^^^^^^^^^
Internal functions are used for maintenance tasks such as flashing a new firmware
of changing the UID of a Bricklet. These task should be performed using
Brick Viewer instead of using the internal functions directly.
{0}
""",
'de': """
Interne Funktionen
^^^^^^^^^^^^^^^^^^
Interne Funktionen werden für Wartungsaufgaben, wie zum Beispiel das Flashen
einer neuen Firmware oder das Ändern der UID eines Bricklets, verwendet. Diese
Aufgaben sollten mit Brick Viewer durchgeführt werden, anstelle die internen
Funktionen direkt zu verwenden.
{0}
"""
}
lang = 'en'
enable_verbose = False
def print_verbose(*args, **kwargs):
if enable_verbose:
print(*args, **kwargs)
def html_escape(text):
return text.replace("&", "&").replace('"', """).replace("'", "'").replace(">", ">").replace("<", "<")
def shift_right(text, n):
return text.replace('\n', '\n' + ' '*n)
def strip_trailing_whitespace(text):
lines = []
for line in text.split('\n'):
lines.append(line.rstrip())
return '\n'.join(lines)
_changelog_version_cache = {}
def get_changelog_version(root_dir):
global _changelog_version_cache
version = _changelog_version_cache.get(root_dir)
if version != None:
return version
versions = []
with open(os.path.join(root_dir, 'changelog.txt'), 'r') as f:
for i, line in enumerate(f.readlines()):
line = line.rstrip()
if len(line) == 0:
continue
if re.match(r'^(?:- [A-Z0-9\(]| ([A-Za-z0-9\(\"]|--hide-payload)).*$', line) != None:
continue
m = re.match(r'^(?:<unknown>|20[0-9]{2}-[0-9]{2}-[0-9]{2}): ([1-9][0-9]*)\.([0-9]+)\.([0-9]+) \((?:<unknown>|[a-f0-9]+)\)$', line)
if m == None:
raise GeneratorError('invalid line {0} in changelog {1}: {2}'.format(i + 1, root_dir, line))
version = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
if version[0] not in [1, 2]:
raise GeneratorError('invalid major version in changelog {0}: {1}'.format(root_dir, version))
if len(versions) > 0:
if versions[-1] >= version:
raise GeneratorError('invalid version order in changelog {0}: {1} -> {2}'.format(root_dir, versions[-1], version))
if versions[-1][0] == version[0] and versions[-1][1] == version[1] and versions[-1][2] + 1 != version[2]:
raise GeneratorError('invalid version jump in changelog {0}: {1} -> {2}'.format(root_dir, versions[-1], version))
if versions[-1][0] == version[0] and versions[-1][1] != version[1] and versions[-1][1] + 1 != version[1]:
raise GeneratorError('invalid version jump in changelog {0}: {1} -> {2}'.format(root_dir, versions[-1], version))
if versions[-1][1] != version[1] and version[2] != 0:
if (root_dir == 'javascript' or root_dir.endswith('/javascript')) and versions[-1] == (2, 0, 18) and version == (2, 1, 19):
pass # ignore historical glitch
else:
raise GeneratorError('invalid version jump in changelog {0}: {1} -> {2}'.format(root_dir, versions[-1], version))
if versions[-1][0] != version[0] and (version[1] != 0 or version[2] != 0):
raise GeneratorError('invalid version jump in changelog {0}: {1} -> {2}'.format(root_dir, versions[-1], version))
versions.append(version)
if len(versions) == 0:
raise GeneratorError('no version found in changelog: ' + root_dir)
version = (str(versions[-1][0]), str(versions[-1][1]), str(versions[-1][2]))
_changelog_version_cache[root_dir] = version
return version
def modify_items(kind, active_items, all_items, action, item):
if item == 'all':
if action == '+':
active_items |= set(all_items)
elif action == '-':
active_items -= set(all_items)
else:
raise Exception('invalid --{0}s item: {1}'.format(kind, action + item))
else:
if item not in all_items:
raise Exception('unknown {0}: {1}'.format(kind, item))
if action == '+':
active_items.add(item)
elif action == '-':
active_items.remove(item)
elif action == '>=':
active_items |= set(all_items[all_items.index(item):])
elif action == '>':
active_items |= set(all_items[all_items.index(item) + 1:])
elif action == '<=':
active_items |= set(all_items[:all_items.index(item) + 1])
elif action == '<':
active_items |= set(all_items[:all_items.index(item)])
else:
assert False, action
return active_items
def apply_item_changes(kind, active_items, all_items, item_changes):
for item_change in item_changes:
if len(item_change) == 0:
raise Exception('empty --{0}s item'.format(kind))
m = re.match(r'^(\+|-|>=|>|<=|<)(.*)$', item_change)
if m == None:
raise Exception('invalid --{0}s item: {1}'.format(kind, item_change))
action = m.group(1)
item = m.group(2)
active_items = modify_items(kind, active_items, all_items, action, item)
return active_items
def get_image_size(path):
from PIL import Image
return Image.open(path).size
def select_lang(d, language=None):
if language == None:
language = lang
return d[language]
def make_rst_header(device, has_device_identifier_constant=True):
bindings_display_name = device.get_generator().get_bindings_display_name()
ref_name = device.get_generator().get_bindings_name()
date = datetime.datetime.now().strftime("%Y-%m-%d")
full_title = '{0} - {1}'.format(bindings_display_name, device.get_long_display_name())
full_title_underline = '='*len(full_title)
brick_name = {
'en': 'this Brick',
'de': 'dieses Bricks'
}
bricklet_name = {
'en': 'this Bricklet',
'de': 'dieses Bricklets'
}
tng_name = {
'en': 'this TNG module',
'de': 'dieses TNG-Moduls'
}
if device.is_brick():
device_name = select_lang(brick_name)
elif device.is_bricklet():
device_name = select_lang(bricklet_name)
elif device.is_tng():
device_name = select_lang(tng_name)
else:
assert False
device_identifier_constant = {'en': '.. |device_identifier_constant| replace:: There is also a :ref:`constant <{0}_{1}_constants>` for the device identifier of {2}.\n',
'de': '.. |device_identifier_constant| replace:: Es gibt auch eine :ref:`Konstante <{0}_{1}_constants>` für den Device Identifier {2}.\n'}
if device.is_released():
orphan = ''
else:
orphan = ':orphan:\n'
if has_device_identifier_constant:
device_identifier_constant = select_lang(device_identifier_constant).format(device.get_doc_rst_ref_name(),
ref_name,
device_name)
else:
device_identifier_constant = '.. |device_identifier_constant| unicode:: 0xA0\n :trim:\n'
ref = '.. _{0}_{1}:\n'.format(device.get_doc_rst_ref_name(), ref_name)
return '{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n'.format(gen_text_rst.format(date),
orphan,
device_identifier_constant,
ref,
full_title,
full_title_underline)
def make_rst_summary(device, is_programming_language=True):
not_released = {
'en': """
.. note::
{0} is currently in the prototype stage and the software/hardware
as well as the documentation is in an incomplete state.
""",
'de': """
.. note::
{0} ist im Moment in der Prototyp-Phase und die Software/Hardware
sowie die Dokumentation sind in einem unfertigen Zustand.
"""
}
summary = {
'en': """
This is the description {0} for {1}. General information and technical
specifications for the {2} are summarized in its :ref:`hardware description
<{3}_description>`.
""",
'de': """
Dies ist die Beschreibung {0} für {1}. Allgemeine Informationen über
die Funktionen und technischen Spezifikationen des {2} sind in dessen
:ref:`Hardware Beschreibung <{3}_description>` zusammengefasst.
"""
}
summary_install = {
'en': """
An :ref:`installation guide <api_bindings_{0}_install>` for the {1} API
bindings is part of their general description.
""",
'de': """
Eine :ref:`Installationanleitung <api_bindings_{0}_install>` für die {1} API
Bindings ist Teil deren allgemeine Beschreibung.
"""
}
brick = {
'en': 'This Brick',
'de': 'Dieser Brick'
}
bricklet = {
'en': 'This Bricklet',
'de': 'Dieses Bricklet'
}
tng = {
'en': 'This TNG module',
'de': 'Dieses TNG-Modul'
}
programming_language_name_link = {
'en': 'of the :ref:`{0} API bindings <api_bindings_{1}>`',
'de': 'der :ref:`{0} API Bindings <api_bindings_{1}>`'
}
protocol_name_link = {
'en': 'of the :ref:`{0} protocol <llproto_{1}>`',
'de': 'des :ref:`{0} Protokolls <llproto_{1}>`'
}
brick_name = {
'en': 'the :ref:`{0} <{1}>`',
'de': 'den :ref:`{0} <{1}>`',
}
bricklet_name = {
'en': 'the :ref:`{0} <{1}>`',
'de': 'das :ref:`{0} <{1}>`',
}
tng_name = {
'en': 'the :ref:`{0} <{1}>`',
'de': 'das :ref:`{0} <{1}>`',
}
# format bindings name
if is_programming_language:
bindings_name_link = select_lang(programming_language_name_link)
else:
bindings_name_link = select_lang(protocol_name_link)
bindings_name_link = bindings_name_link.format(device.get_generator().get_bindings_display_name(),
device.get_generator().get_bindings_name())
# format device name
if device.is_brick():
device_name = select_lang(brick_name)
elif device.is_bricklet():
device_name = select_lang(bricklet_name)
elif device.is_tng():
device_name = select_lang(tng_name)
else:
assert False
device_name = device_name.format(device.get_long_display_name(),
device.get_doc_rst_ref_name())
s = select_lang(summary).format(bindings_name_link,
device_name,
device.get_long_display_name(),
device.get_doc_rst_ref_name())
if is_programming_language:
s += select_lang(summary_install).format(device.get_generator().get_bindings_name(),
device.get_generator().get_bindings_display_name())
if not device.is_released():
if device.is_brick():
d = brick
elif device.is_bricklet():
d = bricklet
elif device.is_tng():
d = tng
else:
assert False
s = select_lang(not_released).format(select_lang(d)) + s
return s
def make_rst_examples(title_from_filename, device, url_fixer=None,
is_picture=False, additional_download_finder=None,
display_name_fixer=None, language_from_filename=None,
add_html_test_link=False, add_tvpl_test_link=False):
bindings_name = device.get_generator().get_bindings_name()
filename_regex = device.get_generator().get_doc_example_regex()
ex = {
'en': """
{0}
Examples
--------
The example code below is `Public Domain (CC0 1.0)
<https://creativecommons.org/publicdomain/zero/1.0/>`__.
""",
'de': """
{0}
Beispiele
---------
Der folgende Beispielcode ist `Public Domain (CC0 1.0)
<https://creativecommons.org/publicdomain/zero/1.0/deed.de>`__.
"""
}
imp_code = """
{0}
{1}
{3}
.. literalinclude:: {2}{language} {4}
:linenos:
:tab-width: 4
"""
imp_picture = """
{0}
{1}
{3}
.. image:: /Images/Screenshots/LabVIEW/{2}
:scale: 100 %
:alt: LabVIEW {0} Example
:align: center
"""
imp_picture_scroll = """
{0}
{1}
{3}
.. raw:: html
<div class="horizontal-image-scroll">
.. image:: /Images/Screenshots/LabVIEW/{2}
:scale: 100 %
:alt: LabVIEW {0} Example
:align: center
.. raw:: html
</div>
"""
download = '`Download ({0}) <{1}>`__'
url_format = 'https://github.com/Tinkerforge/{0}/raw/master/software/examples/{1}/{2}'
imp = imp_code
if is_picture:
imp = imp_picture_scroll
ref = '.. _{0}_{1}_examples:\n'.format(device.get_doc_rst_ref_name(),
bindings_name)
files = find_device_examples(device, filename_regex)
if len(files) == 0:
print_verbose(' \033[01;31m! no examples\033[0m')
return ''
examples = select_lang(ex).format(ref)
copy_files = []
include_name = device.get_generator().get_doc_rst_filename_part()
for f in files:
if is_picture:
if get_image_size(f[1])[0] > 950:
imp = imp_picture_scroll
else:
imp = imp_picture
if language_from_filename is None:
language = bindings_name
else:
language = language_from_filename(f[0])
include = '{0}_{1}_{2}'.format(device.get_doc_rst_name(), include_name, f[0].replace(' ', '_'))
copy_files.append((f[1], include))
title = title_from_filename(f[0])
url = url_format.format(device.get_git_name(), bindings_name, f[0].replace(' ', '%20'))
if url_fixer is not None:
url = url_fixer(url)
display_name = f[0]
if display_name_fixer is not None:
display_name = display_name_fixer(display_name)
downloads = []
if additional_download_finder is not None:
for additional_download in additional_download_finder(f[1]):
additional_url = url_format.format(device.get_git_name(), bindings_name, additional_download.replace(' ', '%20'))
downloads.append(download.format(additional_download, additional_url))
downloads = [download.format(display_name, url)] + downloads
if add_html_test_link and include.endswith('.html'):
downloads.append('`Test ({0}) <https://www.tinkerforge.com/{1}/doc/Software/Examples/JavaScript/{2}>`__'.format(display_name, lang, include))
if add_tvpl_test_link and include.endswith('.tvpl'):
downloads.append('`Test ({0}) <https://www.tinkerforge.com/{1}/tvpl/editor.html?example={2}/{3}/{4}>`__'
.format(display_name, lang, device.get_category().under, device.get_name().under, f[0]))
lang_placeholder = "\n :language:" if language is not None else ""
examples += imp.format(title, '^'*len(title), include, ', '.join(downloads), language if language is not None else "", language=lang_placeholder)
copy_examples(copy_files, device.get_generator().get_root_dir())
return examples
def format_simple_element_meta(simple_elements, no_out_value=None,
parameter_label_override=None,
return_label_override=None):
type_label = select_lang({'en': 'Type', 'de': 'Typ'})
if parameter_label_override != None:
parameter_label = select_lang(parameter_label_override)
else:
parameter_label = select_lang({'en': 'Parameters', 'de': 'Parameter'})
if return_label_override != None:
return_label = select_lang(return_label_override)
else:
return_label = select_lang({'en': 'Returns', 'de': 'Rückgabe'})
formatted_meta_in = []
formatted_meta_out = []
for simple_element in simple_elements:
assert simple_element[2] in [None, 1] # FIXME: no list support yet
meta = ('plain', simple_element[0], '{0}: {1}'.format(type_label, simple_element[1]))
if simple_element[3] == 'in':
formatted_meta_in.append(meta)
elif simple_element[3] == 'out':
formatted_meta_out.append(meta)
else:
assert False, simple_element[3]
if len(formatted_meta_out) == 0 and no_out_value != None:
formatted_meta_out.append(select_lang(no_out_value))
formatted_meta = []
if len(formatted_meta_in) > 0:
formatted_meta.append(('plain', parameter_label, formatted_meta_in))
if len(formatted_meta_out) > 0:
formatted_meta.append(('plain', return_label, formatted_meta_out))
return formatted_meta
def format_full_element_meta(packet_type,
selected_elements,
all_elements,
type_func,
name_func,
output_parameter='never',
return_object='never',
callback_object='never',
prefix_elements=None,
suffix_elements=None,
stream_length_suffix=None,
parameter_label_override=None,
output_parameter_label_override=None,
return_label_override=None,
return_object_label_override=None,
return_object_is_array=False,
callback_parameter_label_override=None,
callback_object_label_override=None,
constants_hint_override=None,
no_in_value=None,
no_out_value=None,
no_return_value=None,
explicit_string_cardinality=False,
explicit_variable_stream_cardinality=False,
explicit_fixed_stream_cardinality=False,
explicit_common_cardinality=False,
function_id=None):
assert output_parameter in ['never', 'always', 'conditional']
assert return_object in ['never', 'always', 'conditional']
assert callback_object in ['never', 'always', 'conditional']
type_label = select_lang({'en': 'Type', 'de': 'Typ'})
length_label = select_lang({'en': 'Length', 'de': 'Länge'})
up_to_hint = select_lang({'en': 'up to', 'de': 'bis zu'})
variable_hint = select_lang({'en': 'variable', 'de': 'variabel'})
unit_label = select_lang({'en': 'Unit', 'de': 'Einheit'})
to_hint = select_lang({'en': 'to', 'de': 'bis'})
range_label = select_lang({'en': 'Range', 'de': 'Wertebereich'})
default_label = select_lang({'en': 'Default', 'de': 'Standardwert'})
formatted_meta_in = []
formatted_meta_out = []
formatted_meta_return = []
if prefix_elements != None:
for prefix_element in prefix_elements:
assert prefix_element[2] == 1 # FIXME: no list support yet
meta = ('plain', prefix_element[0], '{0}: {1}'.format(type_label, prefix_element[1]))
if prefix_element[3] == 'in':
formatted_meta_in.append(meta)
elif prefix_element[3] == 'out':
formatted_meta_out.append(meta)
elif prefix_element[3] == 'return':
formatted_meta_return.append(meta)
else:
assert False, prefix_element[3]
for element in selected_elements:
meta = ['{0}: {1}'.format(type_label, type_func(element))]
cardinality = element.get_cardinality()
if cardinality != 1:
if element.get_type() == 'string':
if explicit_string_cardinality:
meta.append('{0}: {1} {2}'.format(length_label, up_to_hint, cardinality))
elif cardinality < 0:
if explicit_variable_stream_cardinality:
meta.append('{0}: {1}'.format(length_label, variable_hint))
elif element.get_role() == 'stream_data':
if explicit_fixed_stream_cardinality:
meta.append('{0}: {1}'.format(length_label, cardinality))
elif explicit_common_cardinality:
meta.append('{0}: {1}'.format(length_label, cardinality))
if element.is_struct():
assert cardinality > 1
if element.get_direction() == 'in':
formatted_meta_in.append(('plain', name_func(element), ', '.join(meta)))
else:
formatted_meta_out.append(('plain', name_func(element), ', '.join(meta)))
for index in element.get_indices():
if index != None:
meta = ['{0}: {1}'.format(type_label, type_func(element, cardinality=1))]
type_ = element.get_type()
scale = element.get_scale(index=index)
unit = element.get_unit(index=index)
if scale != (1, 1) and unit == None:
if scale == 'dynamic':
formatted_scale = '?'
else:
formatted_scale = format_fraction(*scale)
meta.append('{0}: {1}'.format(unit_label, formatted_scale))
elif scale == (1, 1) and unit != None:
if unit == 'dynamic':
formatted_unit = '?'
sequence = '{value} {unit}'
else:
formatted_unit = '⟨abbr title=«{0} ({1})»⟩{2}⟨/abbr⟩'.format(unit.get_title(), unit.get_usage(), unit.get_symbol())
sequence = unit.get_sequence()
meta.append('{0}: {1}'.format(unit_label, sequence.format(value='1', unit=formatted_unit)))
elif scale != (1, 1) and unit != None:
if scale == 'dynamic':
formatted_scale = '?'
if unit == 'dynamic':
formatted_unit = '?'
sequence = '{value} {unit}'
else:
formatted_unit = '⟨abbr title=«{0} ({1})»⟩{2}⟨/abbr⟩'.format(unit.get_title(), unit.get_usage(), unit.get_symbol())
sequence = unit.get_sequence()
else:
if unit == 'dynamic':
formatted_scale = format_fraction(*scale)
formatted_unit = '?'
sequence = '{value} {unit}'
else:
normalized_scale, unit_title, unit_symbol = normalize_scale(scale, unit)
formatted_scale = format_fraction(*normalized_scale)
formatted_unit = '⟨abbr title=«{0} ({1})»⟩{2}⟨/abbr⟩'.format(unit_title, unit.get_usage(), unit_symbol)
sequence = unit.get_sequence()
meta.append('{0}: {1}'.format(unit_label, sequence.format(value=formatted_scale, unit=formatted_unit)))
if type_ not in ['bool', 'string']:
if constants_hint_override != None:
constants_hint = select_lang(constants_hint_override)
else:
constants_hint = select_lang({'en': ('See constants', 'with constants'), 'de': ('Siehe Konstanten', 'mit Konstanten')})
range_ = element.get_range(index=index)
if range_ == 'constants':
meta.append('{0}: {1}'.format(range_label, constants_hint[0]))
elif range_ == 'dynamic':
meta.append('{0}: ⟨abbr title=«{1}»⟩?⟨/abbr⟩'.format(range_label, select_lang({'en': 'Dynamic, see documentation', 'de': 'Dynamisch, siehe Dokumentation'})))
elif range_ != None:
if range_ == 'type':
range_ = [element.get_type_range()]
formatted_range = []
for subrange in range_:
assert isinstance(subrange, tuple), range_
formatted_subrange = [None, None]
if type_.startswith('int') or type_.startswith('uint'):
for i, value in enumerate(subrange):
formatted_subrange[i] = format_value_with_tooltip(element, value, scale, unit)
else:
for i, value in enumerate(subrange):
formatted_subrange[i] = element.format_value(value)
if subrange[0] == subrange[1]:
formatted_range.append(formatted_subrange[0])
else:
formatted_range.append('{0} {1} {2}'.format(formatted_subrange[0], to_hint, formatted_subrange[1]))
if element.get_constant_group(index=index) != None:
meta.append('{0}: [{1}] {2}'.format(range_label, ', '.join(formatted_range), constants_hint[1]))
else:
meta.append('{0}: [{1}]'.format(range_label, ', '.join(formatted_range)))
default = element.get_default(index=index)
if default != None:
if type_.startswith('int') or type_.startswith('uint'):
formatted_default = format_value_with_tooltip(element, default, scale, unit)
else:
formatted_default = element.format_value(default)
meta.append('{0}: {1}'.format(default_label, formatted_default))
if index == None:
style = 'plain'
else:
style = 'index'
name = name_func(element, index=index)
if element.get_direction() == 'in':
formatted_meta_in.append((style, name, ', '.join(meta)))
else:
formatted_meta_out.append((style, name, ', '.join(meta)))
if stream_length_suffix != None:
length_elements = []
chunk_offset_elements = []
for other in all_elements:
if other.get_role() == 'stream_length':
length_elements.append(other)
elif other.get_role() == 'stream_chunk_offset':
chunk_offset_elements.append(other)
if element.get_role() == 'stream_data' and (element.get_direction() == 'out' or len(length_elements) > 0):
if len(length_elements) > 0:
length_type = type_func(length_elements[0])
elif len(chunk_offset_elements) > 0:
length_type = type_func(chunk_offset_elements[0])
else:
raise GeneratorError('Malformed stream config')
meta = ('plain', name_func(element) + stream_length_suffix, ', '.join(['{0}: {1}'.format(type_label, length_type)]))
if element.get_direction() == 'in':
formatted_meta_in.append(meta)
else:
formatted_meta_out.append(meta)
if suffix_elements != None:
for suffix_element in suffix_elements:
assert suffix_element[2] == 1 # FIXME: no list support yet
meta = ('plain', suffix_element[0], '{0}: {1}'.format(type_label, suffix_element[1]))
if suffix_element[3] == 'in':
formatted_meta_in.append(meta)
elif suffix_element[3] == 'out':
formatted_meta_out.append(meta)
elif suffix_element[3] == 'return':
formatted_meta_return.append(meta)
else:
assert False, suffix_element[3]
if len(formatted_meta_in) == 0 and no_in_value != None:
formatted_meta_in.append(select_lang(no_in_value))
if len(formatted_meta_out) == 0 and no_out_value != None:
formatted_meta_out.append(select_lang(no_out_value))
function_id_label = select_lang({'en': 'Function ID', 'de': 'Funktions-ID'})
if parameter_label_override != None:
parameter_label = select_lang(parameter_label_override)
else:
parameter_label = select_lang({'en': 'Parameters', 'de': 'Parameter'})
if output_parameter_label_override != None:
output_parameter_label = select_lang(output_parameter_label_override)
else:
output_parameter_label = select_lang({'en': 'Output Parameters', 'de': 'Ausgabeparameter'})
if return_label_override != None:
return_label = select_lang(return_label_override)
else:
return_label = select_lang({'en': 'Returns', 'de': 'Rückgabe'})
if return_object_label_override != None:
return_object_label = select_lang(return_object_label_override)
else:
return_object_label = select_lang({'en': 'Return Object', 'de': 'Rückgabeobjekt'})
if callback_parameter_label_override != None:
callback_parameter_label = select_lang(callback_parameter_label_override)
else:
callback_parameter_label = select_lang({'en': 'Callback Parameters', 'de': 'Callback-Parameter'})
if callback_object_label_override != None:
callback_object_label = select_lang(callback_object_label_override)
else:
callback_object_label = select_lang({'en': 'Callback Object', 'de': 'Callback-Objekt'})
formatted_meta = []
if function_id != None:
formatted_meta.append(('plain', function_id_label, str(function_id)))
if len(formatted_meta_in) > 0:
formatted_meta.append(('plain', parameter_label, formatted_meta_in))
has_return = False
if len(formatted_meta_out) > 0:
if packet_type == 'function':
if output_parameter == 'never':
if return_object == 'never':
formatted_meta.append(('plain', return_label, formatted_meta_out))
has_return = True
elif return_object == 'always':
formatted_meta.append(('index' if return_object_is_array else 'plain', return_object_label, formatted_meta_out))
elif return_object == 'conditional':
if len(formatted_meta_out) == 1:
formatted_meta.append(('plain', return_label, formatted_meta_out))
has_return = True
else:
formatted_meta.append(('index' if return_object_is_array else 'plain', return_object_label, formatted_meta_out))
else:
assert False, return_object
elif output_parameter == 'always':
formatted_meta.append(('plain', output_parameter_label, formatted_meta_out))
elif output_parameter == 'conditional':
if len(formatted_meta_out) == 1:
formatted_meta.append(('plain', return_label, formatted_meta_out))
has_return = True
else:
formatted_meta.append(('plain', output_parameter_label, formatted_meta_out))
else:
assert False, output_parameter
elif packet_type == 'callback':
if callback_object == 'never':
formatted_meta.append(('plain', callback_parameter_label, formatted_meta_out))
elif callback_object == 'always':
formatted_meta.append(('plain', callback_object_label, formatted_meta_out))
elif callback_object == 'conditional':
if len(formatted_meta_out) == 1:
formatted_meta.append(('plain', callback_parameter_label, formatted_meta_out))
else:
formatted_meta.append(('plain', callback_object_label, formatted_meta_out))
else:
assert False, output_parameter
else:
assert False, packet_type
if len(formatted_meta_return) > 0:
formatted_meta.append(('plain', return_label, formatted_meta_return))
has_return = True
if not has_return and no_return_value != None:
formatted_meta.append(('plain', return_label, select_lang(no_return_value)))
return formatted_meta
def merge_meta_sections(items):
merged_items = []
for style, label, values in items:
merged = False
for merged_style, merged_label, merged_values in merged_items:
if merged_style == style and merged_label == label:
merged_values += values
merged = True
break
if merged:
continue
merged_items.append((style, label, values[:]))