-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathentries.py
More file actions
1994 lines (1661 loc) · 61.6 KB
/
Copy pathentries.py
File metadata and controls
1994 lines (1661 loc) · 61.6 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
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 -*-
import dataclasses
import io
import string
import typing as t
from typing import Any, Dict, List, Optional, Type
import construct as cs
import construct_typed as cst
import construct_editor.core.model as model
from construct_editor.core.context_menu import (
ButtonMenuItem,
CheckboxMenuItem,
ContextMenu,
SeparatorMenuItem,
)
from construct_editor.core.preprocessor import (
GuiMetaData,
IncludeGuiMetaData,
get_gui_metadata,
)
def evaluate(param, context):
return param(context) if callable(param) else param
def int_to_str(integer_format: "model.IntegerFormat", val: int) -> str:
if isinstance(val, str):
return val # tolerate string
if integer_format is model.IntegerFormat.Hex:
return f"0x{val:X}"
return f"{val}"
def str_to_int(s: str) -> int:
if len(s) == 0:
s = "0"
# convert string to int
# (base=0 means, that eg. 0x, 0b prefixes are allowed)
i = int(s, base=0)
return i
def str_to_bytes(s: str) -> bytes:
return bytes.fromhex(s)
@dataclasses.dataclass
class ObjViewSettings_Default:
entry: "EntryConstruct"
@dataclasses.dataclass
class ObjViewSettings_String:
entry: "EntryConstruct"
@dataclasses.dataclass
class ObjViewSettings_Integer:
entry: "EntryConstruct"
@dataclasses.dataclass
class ObjViewSettings_Flag:
entry: "EntryConstruct"
@dataclasses.dataclass
class ObjViewSettings_Bytes:
entry: "EntryConstruct"
@dataclasses.dataclass
class ObjViewSettings_Enum:
entry: t.Union["EntryEnum", "EntryTEnum"]
@dataclasses.dataclass
class ObjViewSettings_FlagsEnum:
entry: t.Union["EntryFlagsEnum", "EntryTFlagsEnum"]
@dataclasses.dataclass
class ObjViewSettings_Timestamp:
entry: "EntryTimestamp"
ObjViewSettings = t.Union[
ObjViewSettings_Default,
ObjViewSettings_String,
ObjViewSettings_Integer,
ObjViewSettings_Flag,
ObjViewSettings_Bytes,
ObjViewSettings_Enum,
ObjViewSettings_FlagsEnum,
ObjViewSettings_Timestamp,
]
def _convert_restreamed(stream: cs.RestreamedBytesIO) -> io.BytesIO:
"""
Helper method to convert a `RestreamedBytesIO` to a normal `BytesIO`.
This is eg. nessesary for:
- `cs.Bitwise(cs.GreedyRange(cs.Bit))`
- `cs.BitsSwapped(cs.Bitwise(cs.GreedyRange(cs.Bit)))`
"""
def reset_substream_recursively(stream: t.Union[io.BytesIO, cs.RestreamedBytesIO]):
if isinstance(stream, cs.RestreamedBytesIO):
if stream.substream is None:
raise RuntimeError(
"stream.substream has to be io.BytesIO or cs.RestreamedBytesIO"
)
return reset_substream_recursively(stream.substream)
else:
stream.seek(0)
# check if there is already a cached version
bytes_io_stream: t.Optional[io.BytesIO] = getattr(
stream, "_construct_bytes_io", None
)
if bytes_io_stream is None:
# reset substream recursively, so that the whole RestreamedBytesIO can be read again
reset_substream_recursively(stream)
# read the entire RestreamedBytesIO
data = stream.read()
# create a new BytesIO with the data of the RestreamedBytesIO
bytes_io_stream = io.BytesIO(data)
# cache the created stream, so that we dont have to do it again
setattr(stream, "_construct_bytes_io", bytes_io_stream)
return bytes_io_stream
@dataclasses.dataclass
class EnumItem:
name: str
value: int
@dataclasses.dataclass
class FlagsEnumItem:
name: str
value: int
checked: bool
@dataclasses.dataclass
class StreamInfo:
stream: io.BytesIO
path_str: str
byte_range: t.Tuple[int, int]
bitstream: bool
class NameExcludedFromPath(str):
pass
class ListIndexName(str):
pass
NameType = t.Union[str, NameExcludedFromPath, ListIndexName]
PathType = t.List[t.Union[str, ListIndexName]]
def create_path_str(path: PathType) -> str:
path_str = ""
for p in path:
if isinstance(p, ListIndexName):
path_str += f"{p}"
else:
path_str += f".{p}"
if path_str.startswith("."):
path_str = path_str[1:]
return path_str
# #####################################################################################################################
# Construct Entries ###################################################################################################
# #####################################################################################################################
# EntryConstruct ######################################################################################################
class EntryConstruct(object):
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.Construct[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
self.model = model
self._parent = parent
self._construct = construct
self._name = name
self._docs = docs
# Flag, if this entry is an own row in the view.
# This is nessesarry, because most `subcon` in an `Subconstruct` is not
# visible as an own row in the view. So to detect the visible row of an
# entry we can iterate through the parents till we find an visible row.
self._visible_row: bool = False
# Flag if this row is expanded or not.
# Only valid, if self._visible_row is True. This is needed because the
# expansion state is sometimes not saved in the view itself while reloading
# the view (eg. in wxPython).
self._row_expanded: bool = False
def get_debug_infos(self) -> str:
s = ""
s += f"{create_path_str(self.path)}\n"
s += f" - name={str(self.name)}\n"
s += f" - construct={str(self.construct)}\n"
s += f" - entry={self}\n"
s += f" - parent={self.parent}\n"
s += f" - subentries={self.subentries}"
s += f" - visible_row={str(self.visible_row)}\n"
s += f" - row_expanded={self.row_expanded}\n"
s += f" - visible_row_entry={str(self.get_visible_row_entry())}\n"
return s
# default "parent" ########################################################
@property
def parent(self) -> Optional["EntryConstruct"]:
return self._parent
# default "construct" #####################################################
@property
def construct(self) -> "cs.Construct[Any, Any]":
return self._construct
# default "obj" ###########################################################
@property
def obj(self) -> Any:
path = self.path
obj = self.model.root_obj
for p in path[1:]:
if isinstance(obj, dict) or isinstance(obj, cst.DataclassMixin):
obj = obj[p]
elif isinstance(obj, list):
obj = obj[int(p.strip("[]"))]
return obj
@obj.setter
def obj(self, val: Any):
path = self.path
obj = self.model.root_obj
for p in path[1:-1]:
if isinstance(obj, dict) or isinstance(obj, cst.DataclassMixin):
obj = obj[p]
elif isinstance(obj, list):
obj = obj[int(p.strip("[]"))]
if isinstance(obj, dict) or isinstance(obj, cst.DataclassMixin):
obj[path[-1]] = val
elif isinstance(obj, list):
obj[int(path[-1].strip("[]"))] = val
# default "obj_str" #######################################################
@property
def obj_str(self) -> str:
return str(self.obj)
# default "obj_metadata" ##################################################
@property
def obj_metadata(self) -> t.Optional[GuiMetaData]:
return get_gui_metadata(self.obj)
# default "name" ##########################################################
@property
def name(self) -> NameType:
if self._name is not None:
return self._name
else:
return ""
# default "docs" ##########################################################
@property
def docs(self) -> str:
return self._docs
# default "typ_str" #######################################################
@property
def typ_str(self) -> str:
return repr(self.construct)
# default "subentries" ####################################################
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
return None
# default "visible_row" ###################################################
@property
def visible_row(self) -> bool:
return self._visible_row
@visible_row.setter
def visible_row(self, val: bool):
self._visible_row = val
# default "get_visible_row_entry" #########################################
def get_visible_row_entry(self) -> t.Optional["EntryConstruct"]:
"""
Get the entry that represents the visible row.
If this is not an visible row, iterate throud all parents till we find
the visible row.
"""
# Check if this is the visible row
if self._visible_row is True:
return self
# Check if a parent is available. If not this is the root object
if self.parent is None:
return None
# Recusivly check all parents
return self.parent.get_visible_row_entry()
# default "row_expanded" ##################################################
@property
def row_expanded(self) -> bool:
return self._row_expanded
@row_expanded.setter
def row_expanded(self, val: bool):
self._row_expanded = val
# default "obj_view_settings" #############################################
@property
def obj_view_settings(self) -> ObjViewSettings:
"""Settings for the view of an entry (eg. renderer and editor)."""
return ObjViewSettings_Default(self)
# default "modify_context_menu" ###########################################
def modify_context_menu(self, menu: ContextMenu):
"""This method is called, when the user right clicks an entry and a ContextMenu is created"""
pass
# default "path" ##########################################################
@property
def path(self) -> PathType:
parent = self.parent
if parent is not None:
path = parent.path
else:
path = []
# Append name if available and should not be excluded
name = self.name
if not isinstance(name, NameExcludedFromPath):
if name != "":
path.append(name)
return path
def get_stream_infos(
self, child_stream: t.Optional[t.BinaryIO] = None
) -> t.List[StreamInfo]:
"""
Get infos about the current and parent streams.
"""
stream_infos: t.List[StreamInfo] = []
# If no GUI-Metadata is available, StreamInfos cannot be created
metadata = self.obj_metadata
if metadata is None:
return stream_infos
stream = metadata["stream"]
# Add StreamInfos from parent, if a parent exists
if self.parent is not None:
stream_infos.extend(self.parent.get_stream_infos(stream))
# Create new StreamInfo for the stream
if child_stream != stream:
bitstream = getattr(stream, "_construct_bitstream_flag", False)
# Some special handling for RestreamedBytesIO
if isinstance(stream, cs.RestreamedBytesIO):
stream = _convert_restreamed(stream)
if not isinstance(stream, io.BytesIO):
raise RuntimeError("stream has to be io.BytesIO")
stream_infos.append(
StreamInfo(
stream=stream,
path_str=create_path_str(self.path[:-1]),
byte_range=(metadata["byte_range"]),
bitstream=bitstream,
)
)
return stream_infos
# EntrySubconstruct ###################################################################################################
class EntrySubconstruct(EntryConstruct):
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.Subconstruct[Any, Any, Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
self.subentry = create_entry_from_construct(
model, self, construct.subcon, None, ""
)
# pass throught "obj_str" to subentry #####################################
@property
def obj_str(self) -> Any:
return self.subentry.obj_str
# pass throught "typ_str" to subentry #####################################
@property
def typ_str(self) -> str:
return self.subentry.typ_str
# pass throught "subentries" to subentry ##################################
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
return self.subentry.subentries
# pass throught "obj_view_settings" to subentry ###########################
@property
def obj_view_settings(self) -> ObjViewSettings:
return self.subentry.obj_view_settings
# pass throught "modify_context_menu" to subentry #########################
def modify_context_menu(self, menu: ContextMenu):
return self.subentry.modify_context_menu(menu)
# EntryStruct #########################################################################################################
class EntryStruct(EntryConstruct):
construct: "cs.Struct[Any, Any]"
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.Struct[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
# change default row infos
self._subentries = []
# create sub entries
for subcon in self.construct.subcons:
subentry = create_entry_from_construct(model, self, subcon, None, "")
self._subentries.append(subentry)
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
return self._subentries
@property
def typ_str(self) -> str:
return "Struct"
@property
def obj_str(self) -> str:
return ""
@property
def obj_view_settings(self) -> ObjViewSettings:
return ObjViewSettings_Default(self) # TODO: create panel for cs.Struct
def modify_context_menu(self, menu: ContextMenu):
def on_expand_children_clicked():
menu.parent.expand_children(self)
def on_collapse_children_clicked():
menu.parent.collapse_children(self)
menu.add_menu_item(SeparatorMenuItem())
menu.add_menu_item(
ButtonMenuItem(
"Expand Children",
None,
True,
on_expand_children_clicked,
)
)
menu.add_menu_item(
ButtonMenuItem(
"Collapse Children",
None,
True,
on_collapse_children_clicked,
)
)
# EntryArray ##########################################################################################################
class EntryArray(EntrySubconstruct):
construct: t.Union[
"cs.Array[Any, Any]", "cs.GreedyRange[Any, Any]"
]
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: t.Union[
"cs.Array[Any, Any]", "cs.GreedyRange[Any, Any]"
],
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
self._subentries = []
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
# get length of array
try:
array_len = len(self.obj)
except Exception:
if isinstance(self.construct, cs.Array) and isinstance(
self.construct.count, int
):
array_len = self.construct.count
else:
array_len = 1
# append entries if not appended yet
if len(self._subentries) != array_len:
self._subentries.clear()
for index in range(0, array_len):
subentry = create_entry_from_construct(
self.model,
self,
self.construct.subcon,
ListIndexName(f"[{index}]"),
"",
)
self._subentries.append(subentry)
return self._subentries
@property
def typ_str(self) -> str:
try:
obj = self.obj
return f"Array[{len(obj)}]"
except Exception:
if isinstance(self.construct, cs.Array):
return f"Array[{self.construct.count}]"
else:
return "GreedyRange"
@property
def obj_str(self) -> str:
return ""
@property
def obj_view_settings(self) -> ObjViewSettings:
return ObjViewSettings_Default(self) # TODO: create panel for cs.Array
def modify_context_menu(self, menu: ContextMenu):
def on_expand_children_clicked():
menu.parent.expand_children(self)
def on_collapse_children_clicked():
menu.parent.collapse_children(self)
menu.add_menu_item(SeparatorMenuItem())
menu.add_menu_item(
ButtonMenuItem(
"Expand Children",
None,
True,
on_expand_children_clicked,
)
)
menu.add_menu_item(
ButtonMenuItem(
"Collapse Children",
None,
True,
on_collapse_children_clicked,
)
)
# If the subentry has no subentries itself, it makes no sense to create a list view.
temp_subentry = create_entry_from_construct(
self.model, self, self.construct.subcon, None, ""
)
if temp_subentry.subentries is None:
return
def on_menu_item_clicked(checked: bool):
if menu.parent.is_list_view_enabled(self):
menu.parent.disable_list_view(self)
else:
menu.parent.enable_list_view(self)
menu.add_menu_item(SeparatorMenuItem())
menu.add_menu_item(
CheckboxMenuItem(
"Enable List View",
None,
True,
menu.parent.is_list_view_enabled(self),
on_menu_item_clicked,
)
)
# EntryIfThenElse #####################################################################################################
class EntryIfThenElse(EntryConstruct):
construct: "cs.IfThenElse[Any, Any]"
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.IfThenElse[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
self._subentry_then = create_entry_from_construct(
self.model,
self,
self.construct.thensubcon,
NameExcludedFromPath(f"If {self.construct.condfunc} then"),
"",
)
self._subentry_else = create_entry_from_construct(
self.model,
self,
self.construct.elsesubcon,
NameExcludedFromPath("Else"),
"",
)
# change default row infos
self._subentries: List[EntryConstruct] = [
self._subentry_then,
self._subentry_else,
]
def _get_subentry(self) -> "Optional[EntryConstruct]":
"""Evaluate the conditional function to detect the type of the subentry"""
obj = self.obj
if obj is None:
return None
metadata = get_gui_metadata(obj)
if metadata is None:
return None
ctx = metadata["context"]
cond = evaluate(self.construct.condfunc, ctx)
if cond:
return self._subentry_then
else:
return self._subentry_else
@property
def obj_str(self) -> str:
subentry = self._get_subentry()
if subentry is None:
return ""
else:
return subentry.obj_str
@property
def typ_str(self) -> str:
subentry = self._get_subentry()
if subentry is None:
return "IfThenElse"
else:
return subentry.typ_str
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
subentry = self._get_subentry()
if subentry is None:
return self._subentries
else:
return subentry.subentries
@property
def obj_view_settings(self) -> ObjViewSettings:
subentry = self._get_subentry()
if subentry is None:
return ObjViewSettings_Default(self)
else:
return subentry.obj_view_settings
def modify_context_menu(self, menu: ContextMenu):
subentry = self._get_subentry()
if subentry is None:
return
else:
return subentry.modify_context_menu(menu)
# EntrySwitch #########################################################################################################
class EntrySwitch(EntryConstruct):
construct: "cs.Switch[Any, Any]"
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.Switch[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
self._subentries: List[EntryConstruct] = []
self._subentry_cases: Dict[str, EntryConstruct] = {}
self._subentry_default: Optional[EntryConstruct] = None
for key, value in self.construct.cases.items():
subentry_case = create_entry_from_construct(
self.model,
self,
value,
NameExcludedFromPath(f"Case {self.construct.keyfunc} == {str(key)}"),
"",
)
self._subentry_cases[key] = subentry_case
self._subentries.append(subentry_case)
if self.construct.default is not None:
self._subentry_default = create_entry_from_construct(
self.model,
self,
self.construct.default,
NameExcludedFromPath("Default"),
"",
)
self._subentries.append(self._subentry_default)
def _get_subentry(self) -> "Optional[EntryConstruct]":
"""Evaluate the conditional function to detect the type of the subentry"""
obj = self.obj
if obj is None:
return None
metadata = get_gui_metadata(obj)
if metadata is None:
return None
ctx = metadata["context"]
key = evaluate(self.construct.keyfunc, ctx)
if key in self._subentry_cases:
return self._subentry_cases[key]
else:
return self._subentry_default
@property
def obj_str(self) -> str:
subentry = self._get_subentry()
if subentry is None:
return ""
else:
return subentry.obj_str
@property
def typ_str(self) -> str:
subentry = self._get_subentry()
if subentry is None:
return "Switch"
else:
return subentry.typ_str
@property
def subentries(self) -> Optional[List["EntryConstruct"]]:
subentry = self._get_subentry()
if subentry is None:
return self._subentries
else:
return subentry.subentries
@property
def obj_view_settings(self) -> ObjViewSettings:
subentry = self._get_subentry()
if subentry is None:
return ObjViewSettings_Default(self)
else:
return subentry.obj_view_settings
def modify_context_menu(self, menu: ContextMenu):
subentry = self._get_subentry()
if subentry is None:
return
else:
return subentry.modify_context_menu(menu)
# EntryFormatField ####################################################################################################
@dataclasses.dataclass
class FormatFieldInt:
name: str
bits: int
signed: bool
@dataclasses.dataclass()
class FormatFieldFloat:
name: str
class EntryFormatField(EntryConstruct):
construct: "cs.FormatField[Any, Any]"
type_mapping: t.Dict[str, t.Union[FormatFieldInt, FormatFieldFloat]] = {
">B": FormatFieldInt("Int8ub", 8, False),
">H": FormatFieldInt("Int16ub", 16, False),
">L": FormatFieldInt("Int32ub", 32, False),
">Q": FormatFieldInt("Int64ub", 64, False),
">b": FormatFieldInt("Int8sb", 8, True),
">h": FormatFieldInt("Int16sb", 16, True),
">l": FormatFieldInt("Int32sb", 32, True),
">q": FormatFieldInt("Int64sb", 64, True),
"<B": FormatFieldInt("Int8ul", 8, False),
"<H": FormatFieldInt("Int16ul", 16, False),
"<L": FormatFieldInt("Int32ul", 32, False),
"<Q": FormatFieldInt("Int64ul", 64, False),
"<b": FormatFieldInt("Int8sl", 8, True),
"<h": FormatFieldInt("Int16sl", 16, True),
"<l": FormatFieldInt("Int32sl", 32, True),
"<q": FormatFieldInt("Int64sl", 64, True),
"=B": FormatFieldInt("Int8un", 8, False),
"=H": FormatFieldInt("Int16un", 16, False),
"=L": FormatFieldInt("Int32un", 32, False),
"=Q": FormatFieldInt("Int64un", 64, False),
"=b": FormatFieldInt("Int8sn", 8, True),
"=h": FormatFieldInt("Int16sn", 16, True),
"=l": FormatFieldInt("Int32sn", 32, True),
"=q": FormatFieldInt("Int64sn", 64, True),
">e": FormatFieldFloat("Float16b"),
"<e": FormatFieldFloat("Float16l"),
"=e": FormatFieldFloat("Float16n"),
">f": FormatFieldFloat("Float32b"),
"<f": FormatFieldFloat("Float32l"),
"=f": FormatFieldFloat("Float32n"),
">d": FormatFieldFloat("Float64b"),
"<d": FormatFieldFloat("Float64l"),
"=d": FormatFieldFloat("Float64n"),
}
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.FormatField[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
# change default row infos
self.type_infos = None
if construct.fmtstr in self.type_mapping:
self.type_infos = self.type_mapping[construct.fmtstr]
@property
def obj_view_settings(self) -> ObjViewSettings:
if isinstance(self.type_infos, FormatFieldInt):
return ObjViewSettings_Integer(self)
elif isinstance(self.type_infos, FormatFieldFloat):
return ObjViewSettings_Default(self) # TODO: ObjEditor_Float
else:
return ObjViewSettings_Default(self)
@property
def obj_str(self) -> str:
obj = self.obj
if isinstance(self.type_infos, FormatFieldInt) and (obj is not None):
return int_to_str(self.model.integer_format, obj)
elif isinstance(self.type_infos, FormatFieldFloat) and (obj is not None):
return str(obj) # TODO: float_to_str
else:
return str(obj)
@property
def typ_str(self) -> str:
if self.type_infos is not None:
return self.type_infos.name
else:
return "FormatField[{}]".format(repr(self.construct.fmtstr))
# EntryBytesInteger ###################################################################################################
class EntryBytesInteger(EntryConstruct):
construct: "cs.BytesInteger[Any, Any]"
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.BytesInteger[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
@property
def typ_str(self) -> str:
if self.construct.length == 3:
if self.construct.signed is False:
if self.construct.swapped is False:
return "Int24ub"
else:
return "Int24ul"
else:
if self.construct.swapped is False:
return "Int24sb"
else:
return "Int24sl"
else:
return repr(self.construct)
@property
def obj_str(self) -> str:
obj = self.obj
if obj is None:
return str(obj)
else:
return int_to_str(self.model.integer_format, obj)
@property
def obj_view_settings(self) -> ObjViewSettings:
if isinstance(self.construct.length, int):
return ObjViewSettings_Integer(self)
else:
return ObjViewSettings_Default(self)
# EntryBitsInteger ####################################################################################################
class EntryBitsInteger(EntryConstruct):
construct: "cs.BitsInteger[Any, Any]"
def __init__(
self,
model: "model.ConstructEditorModel",
parent: Optional["EntryConstruct"],
construct: "cs.BitsInteger[Any, Any]",
name: t.Optional[NameType],
docs: str,
):
super().__init__(model, parent, construct, name, docs)
@property
def typ_str(self) -> str:
# change default row infos
return "BitsInteger[{}{}]".format(
repr(self.construct.length),
", signed" if self.construct.signed is True else "",
)
@property
def obj_str(self) -> str:
obj = self.obj
if obj is None:
return str(obj)
else:
return int_to_str(self.model.integer_format, obj)
@property
def obj_view_settings(self) -> ObjViewSettings:
if isinstance(self.construct.length, int):
return ObjViewSettings_Integer(self)
else:
return ObjViewSettings_Default(self)
# EntryComputed #######################################################################################################
class EntryStringEncoded(EntrySubconstruct):
def __init__(