asn1_value_editor.py 46.9 KB
Newer Older
1
2
3
4
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    TASTE ASN.1 Value Editor
Maxime Perrotin's avatar
Maxime Perrotin committed
5

6
7
    Main GUI widget

8
    Copyright (c) 2012-2018 European Space Agency
9
10
11
12
13
14
15

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int

    License is LGPLv3 - Check the LICENSE file
"""
Maxime Perrotin's avatar
Maxime Perrotin committed
16
17

__author__ = "Maxime Perrotin"
18
__license__ = "LGPLv3"
Maxime Perrotin's avatar
Maxime Perrotin committed
19
__version__ = "1.7.0"
20
__url__ = "https://taste.tools"
Maxime Perrotin's avatar
Maxime Perrotin committed
21
22

import sys
Maxime Perrotin's avatar
Maxime Perrotin committed
23
import logging
24
from functools import partial
Maxime Perrotin's avatar
Maxime Perrotin committed
25
26
27
28
29
30

try:
    from PySide import *
    from PySide.QtCore import *
    from PySide.QtGui import *
    from PySide.QtUiTools import *
31
32
except ImportError as err:
    print 'Pyside not found (package python-pyside missing)...' + str(err)
Maxime Perrotin's avatar
Maxime Perrotin committed
33
34
35

import vn

36
37
MIN_RANGE   = Qt.UserRole + 1
MAX_RANGE   = Qt.UserRole + 2
38
39
CHOICE_LIST = Qt.UserRole + 1     # list of strings (enumerants)
INTMAP      = Qt.UserRole + 5     # for enum/choice: map string-numerical value
40
41
PLOTTERS    = Qt.UserRole + 4
ASN1TYPE    = Qt.UserRole
42
OPTIONAL    = Qt.UserRole + 6
Maxime Perrotin's avatar
Maxime Perrotin committed
43
44
45


class myTextEdit(QTextEdit):
46
47
    ''' Customized text editor that contains a context menu for loading
    data from a file '''
Maxime Perrotin's avatar
Maxime Perrotin committed
48
    def __init__(self, parent=None):
49
        super(myTextEdit, self).__init__(parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
50
51

    def contextMenuEvent(self, event):
52
53
        ''' When the context menu is open, add the Load from file action
        and open the menu '''
Maxime Perrotin's avatar
Maxime Perrotin committed
54
55
56
57
58
        myMenu = self.createStandardContextMenu()
        myAction = 'Load data from file'
        myMenu.addAction(myAction)
        action = myMenu.exec_(event.globalPos())
        if action is not None and action.text() == myAction:
59
60
61
62
            filename = QFileDialog.getOpenFileName(self,
                                                  "Load string from file",
                                                  ".",
                                                  "All (*)")[0]
Maxime Perrotin's avatar
Maxime Perrotin committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
            if len(filename) == 0:
                return
            stringFile = QFile(filename)
            stringFile.open(QIODevice.ReadOnly)
            stringData = str(stringFile.readData(stringFile.size()))
            self.setText(stringData)
            stringFile.close()


class TreeDelegate(QStyledItemDelegate):
    '''Tree Delegate allows to define specific editors for each cell of the
tree view. This way, e.g. ASN.1 ENUMERATED values can be selected using a
combo box, while INTEGERS values can be set using a spin box.
Three functions have been redefined:
(1) createEditor, which  sets an editor to a cell, using the cell attributes
to learn about the ASN.1 basic type (stored in Qt.UserRole)
79
(2) setEditorData, which is used at runtime to put the value in the given
Maxime Perrotin's avatar
Maxime Perrotin committed
80
editor when the user clicks on the cell
81
(3) setModelData, which is called when the user is done with the editing: it
Maxime Perrotin's avatar
Maxime Perrotin committed
82
83
84
85
86
reads the value from the editor and place it back in the model '''
    seqof = Signal(QModelIndex, int, int)
    choice = Signal(QModelIndex, int, int)

    def __init__(self, oParent=None):
87
        super(TreeDelegate, self).__init__(oParent)
Maxime Perrotin's avatar
Maxime Perrotin committed
88
89

    def createEditor(self, parent, option, index):
90
91
        ''' Define the delegate (editor) to use for a given cell. This function
            is called when the user clicks on a cell.
92
93
94
95
96
97
98
99
            index.data() returns the actual value, and index.data(role) points
            to some user data when role >= 32. 32 is Qt.UserRole. '''
        def update_model(editor, index, event):
            ''' Trigger an immediate update of the model and therefore of the
            visible elements of the gui, when user changes a value in the
            editor. For example when the CHOICE index changes, this makes sure
            that the relevant choice data is updated without gaving to wait
            for the user to click outside from the widget '''
100
101
102
103
            # Do not call setModelData directly, it would segfault
            # self.setModelData(editor, index.model(), index)
            self.commitData.emit(editor)

Maxime Perrotin's avatar
Maxime Perrotin committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        # Check the (user-defined) type associated with the cell
        asnType = index.data(ASN1TYPE)
        if asnType == 'INTEGER':
            editor = QSpinBox(parent)
            # Qt's int is 32-bits signed, so we may get overflows
            try:
                editor.setMinimum(index.data(MIN_RANGE))
            except OverflowError:
                editor.setMinimum(sys.maxint)
            try:
                editor.setMaximum(index.data(MAX_RANGE))
            except OverflowError:
                editor.setMaximum(sys.maxint)
        elif asnType == 'SEQOF':
            editor = QSpinBox(parent)
            minVal = index.data(MIN_RANGE)
            maxVal = index.data(MAX_RANGE)
            editor.setRange(minVal, maxVal)
122
            editor.valueChanged.connect(partial(update_model, editor, index))
123
        elif asnType in ('ENUMERATED', 'CHOICE'):
Maxime Perrotin's avatar
Maxime Perrotin committed
124
            editor = QComboBox(parent)
125
            editor.activated.connect(partial(update_model, editor, index))
Maxime Perrotin's avatar
Maxime Perrotin committed
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
            enumVal = index.data(CHOICE_LIST)
            for val in enumVal:
                editor.addItem(val)
        elif asnType == 'REAL':
            editor = QDoubleSpinBox(parent)
            minVal = index.data(MIN_RANGE)
            maxVal = index.data(MAX_RANGE)
            editor.setRange(float(minVal), float(maxVal))
        elif asnType == 'STRING':
            editor = myTextEdit(parent)
        elif asnType == 'BOOLEAN':
            editor = QComboBox(parent)
            boolVal = index.data(CHOICE_LIST)
            for val in boolVal:
                editor.addItem(val)
        else:
            return  # Non-editable cells
        return editor

    def setEditorData(self, editor, index):
        ''' Set the curent value of the editor (when cell is clicked)
            in principle, take it from the model (index.data() = value) '''
        asnType = index.data(ASN1TYPE)
        if asnType in ('INTEGER', 'SEQOF'):
            editor. setValue(int(index.data()))
        elif asnType in ('ENUMERATED', 'CHOICE'):
            idx = editor.findText(index.data())
            editor.setCurrentIndex(idx)
            #editor. setEditText(index.data())
        elif asnType == 'REAL':
            editor.setValue(float(index.data()))
        elif asnType == 'STRING':
            editor.setText(index.data())
        elif asnType == 'BOOLEAN':
            idx = editor.findText(index.data())
            editor.setCurrentIndex(idx)
            #isChecked = index.model().data(index,  Qt.CheckStateRole)
            #editor.setCheckState(Qt.CheckState(isChecked))
        else:
            pass

    def setModelData(self, editor, model, index):
        '''  Once a choice has been made (by the user) take the value from
             the corresponding editor, and set it back in the model '''
        asnType = index.data(ASN1TYPE)
        if asnType == 'INTEGER':
            val = editor.value()
            model.setData(index, val)
        elif asnType == 'SEQOF':
            val = editor.value()
            model.setData(index, val)
            # Sequence of: display only the corresponding number of elements
178
179
180
            self.seqof.emit(index.sibling(index.row(), 0),
                            val,
                            index.data(MAX_RANGE))
Maxime Perrotin's avatar
Maxime Perrotin committed
181
182
183
184
185
186
187
        elif asnType == 'ENUMERATED':
            val = editor.currentText()
            model.setData(index, val)
        elif asnType == 'CHOICE':
            val = editor.currentText()
            model.setData(index, val)
            # display only the corresponding choice definition
188
189
190
            self.choice.emit(index.sibling(index.row(), 0),
                             len(index.data(CHOICE_LIST)),
                             editor.currentIndex())
Maxime Perrotin's avatar
Maxime Perrotin committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        elif asnType == 'REAL':
            val = editor.value()
            model.setData(index, val)
        elif asnType == 'STRING':
            val = editor.toPlainText()
            model.setData(index, val)
        elif asnType == 'BOOLEAN':
            val = editor.currentText()
            model.setData(index, val)
        else:
            pass

    def updateEditorGeometry(self, editor, option, index):
        ''' Set editor geometry (bigger box for string types) '''
        asnType = index.data(ASN1TYPE)
        if asnType == 'STRING':
207
208
            r = QRect(option.rect.x(), option.rect.y(),
                      option.rect.width(), max(option.rect.height(), 100))
Maxime Perrotin's avatar
Maxime Perrotin committed
209
210
211
212
213
214
215
216
217
218
219
        else:
            r = option.rect
        editor.setGeometry(r)


class asn1Editor(QTreeView):
    ''' ASN.1 Fields editor to define, load, save and/or send TC '''
    expandTree = Signal()
    expandBranch = Signal(QModelIndex)
    statusBarMessage = Signal(str)
    msc = Signal(unicode, unicode)
220
221
    # Whenever a new TM is received, the new_tm signal is emitted
    new_tm = Signal()
Maxime Perrotin's avatar
Maxime Perrotin committed
222
223
    # Use a signal to tell the plots (matplotlib) to update
    plot_refresh = Signal()
Maxime Perrotin's avatar
Maxime Perrotin committed
224
225

    def __init__(self, parent=None):
226
        super(asn1Editor, self).__init__(parent)
227
228
229
230
231
232
        self.model = QStandardItemModel(1, 5)   # 5 columns
        self.model.setHorizontalHeaderLabels(['Field',       # field name
                                              'Type',        # hidden
                                              'Constraints', # hidden
                                              'Value',       # editable
                                              'Present'])    # optionality flag
Maxime Perrotin's avatar
Maxime Perrotin committed
233
234
        self.delegate = TreeDelegate()
        self.setItemDelegate(self.delegate)
235
236
        # Set selection mode and behavior to allow multiple rows to be selected
        # with Ctrl/Shift keys
Maxime Perrotin's avatar
Maxime Perrotin committed
237
238
239
240
241
242
243
244
245
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.setModel(self.model)
        self.setAlternatingRowColors(True)
        # Set Editing triggers so that a single click in a cell opens the editor
        self.setEditTriggers(QAbstractItemView.AllEditTriggers)
        # If we later want to drag & drop values (to plot, meter..):
        self.setDragEnabled(False)
246
247
        # When the number of elements for a sequence of is changed,
        # signal "seqof" is triggered by the delegate. Same for choice.
Maxime Perrotin's avatar
Maxime Perrotin committed
248
249
250
251
252
253
254
        self.delegate.seqof.connect(self.seqofDisplay)
        self.delegate.choice.connect(self.choiceDisplay)
        self.expandTree.connect(self.expandAll)
        self.expandBranch.connect(self.expand)
        self.plotterBackend = None
        self.backend = None
        self.plottedIdxs = []
Maxime Perrotin's avatar
Maxime Perrotin committed
255
        self.log = logging
256
        self.pendingTM = False
257
258
259
260
        # item is the ASN.1 node in Pyside format from datamodel.py
        self.item = None
        # List of classes that have an "update" method (user custom widgets)
        self.tm_clients = []
261
262
263
264
265
266
267
268
        # Instance of the ASN.1 type to store the value of this editor
        self.asn1Instance = None

    def setBackend(self, backend):
        ''' Set the pointer to the TMTC backend generated by the B mapper '''
        self.backend = backend
        # Create an instance of the ASN.1 type using the backend
        self.asn1Instance = self.backend.typeInstance()
Maxime Perrotin's avatar
Maxime Perrotin committed
269

270
271
272
273
    def setDefaultValue(self):
        # Update the value to get default values if set in ASN1
        self.updateVariable()

Maxime Perrotin's avatar
Maxime Perrotin committed
274
275
276
277
278
279
280
281
282
283
    def hideExtraColumns(self):
        ''' Hide the columns containing the type and constraint '''
        self.setColumnHidden(1, True)
        self.setColumnHidden(2, True)

    def showExtraColumns(self):
        ''' Show the columns containing the type and constraint '''
        self.setColumnHidden(1, False)
        self.setColumnHidden(2, False)

284
    def setAsn1Model(self, dataview, row=0):
Maxime Perrotin's avatar
Maxime Perrotin committed
285
        self.item = dataview
286
287
        rootItem = self.addItem(self.item)
        self.treeItem = rootItem["item"]
Maxime Perrotin's avatar
Maxime Perrotin committed
288

289
290
291
        self.model.setItem(row, 1, QStandardItem(rootItem["type"]))
        self.model.setItem(row, 2, QStandardItem(rootItem["constraint"]))
        self.model.setItem(row, 3, QStandardItem(rootItem["value"]))
Maxime Perrotin's avatar
Maxime Perrotin committed
292
293

        # Add the item to the actual tree. 0,0 = 1st row, 1st column
294
        self.model.setItem(row, 0, self.treeItem)
Maxime Perrotin's avatar
Maxime Perrotin committed
295
        self.setWindowTitle('ASN.1 Variable editor')
296
        self.hideUnusedFields(self.treeItem, start=True, row=row)
Maxime Perrotin's avatar
Maxime Perrotin committed
297
298
299
        self.setColumnWidth(0, 200)
        self.setColumnWidth(1, 150)
        self.expandAll()
300
        return rootItem["item"]
Maxime Perrotin's avatar
Maxime Perrotin committed
301

302
    def hideUnusedFields(self, root, start=False, row=0):
Maxime Perrotin's avatar
Maxime Perrotin committed
303
        ''' Hide CHOICE unselected fields and SEQUENCE OF out-of-range fields '''
304
        rootType = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
305
        if rootType == 'CHOICE' and start:
306
307
            choices = self.model.item(row, 3).data(CHOICE_LIST)
            currValue = self.model.item(row, 3).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
308
309
310
            for j in range(len(choices)):
                if currValue == choices[j]:
                    break
311
            rowIndex = self.model.item(row).index()
Maxime Perrotin's avatar
Maxime Perrotin committed
312
313
            self.choiceDisplay(rowIndex, len(choices), j)
        elif rootType == 'SEQOF' and start:
314
315
316
            maxValue = self.model.item(row, 3).data(MAX_RANGE)
            currValue = self.model.item(row, 3).text()
            rowIndex = self.model.item(row).index()
Maxime Perrotin's avatar
Maxime Perrotin committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            self.seqofDisplay(rowIndex, currValue, maxValue)

        if root.hasChildren():
            for i in range(root.rowCount()):  # for each row
                self.hideUnusedFields(root.child(i))  # check recursively
                asnType = root.child(i, 1).text()
                if asnType == 'SEQOF':
                    maxValue = root.child(i, 3).data(MAX_RANGE)
                    currValue = root.child(i, 3).text()
                    rowIndex = root.child(i).index()
                    self.seqofDisplay(rowIndex, currValue, maxValue)
                elif asnType == 'CHOICE':
                    choices = root.child(i, 3).data(CHOICE_LIST)
                    currValue = root.child(i, 3).text()
                    for j in range(len(choices)):
                        if currValue == choices[j]:
                            break
                    rowIndex = root.child(i).index()
                    self.choiceDisplay(rowIndex, len(choices), j)

337
    def parseModel(self, root, nbRows=-1, dest=None, choice=-1):
338
339
        ''' Parse the model to get all field values recursively
            root type is QStandardItem
Maxime Perrotin's avatar
Maxime Perrotin committed
340
            dest is a ctypes instance of the type to fill
341
            choice >= 0 to specify a specific row to parse for a CHOICE
342
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
343
344
345
        if dest is None:
            self.log.error('parseModel: destination ASN.1 variable not set')

Maxime Perrotin's avatar
Maxime Perrotin committed
346
        if root.hasChildren():
Maxime Perrotin's avatar
Maxime Perrotin committed
347
348
            seqOf = True if nbRows != -1 else False
            if not seqOf:
Maxime Perrotin's avatar
Maxime Perrotin committed
349
                nbRows = root.rowCount()
350

351
            def parseRow(root, i, dest, seqOf=False):
Maxime Perrotin's avatar
Maxime Perrotin committed
352
                name    = root.child(i, 0).text().replace('-', '_')
Maxime Perrotin's avatar
Maxime Perrotin committed
353
                asnType = root.child(i, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
354
                value   = root.child(i, 3).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
355
                ptr = getattr(dest, name) if not seqOf else dest
356
357
                if seqOf:
                    ptr = ptr[i]
Maxime Perrotin's avatar
Maxime Perrotin committed
358

Maxime Perrotin's avatar
Maxime Perrotin committed
359
                if asnType in ('SEQUENCE', 'SET'):
Maxime Perrotin's avatar
Maxime Perrotin committed
360
361
362
                    if root.child(i).hasChildren():
                        # Discard empty sequence
                        self.parseModel(root.child(i), dest=ptr)
Maxime Perrotin's avatar
Maxime Perrotin committed
363
                elif asnType == 'SEQOF':
Maxime Perrotin's avatar
Maxime Perrotin committed
364
                    state = ptr.GetState()
365
                    self.parseModel(root.child(i), nbRows=int(value), dest=ptr)
Maxime Perrotin's avatar
Maxime Perrotin committed
366
367
                    ptr.SetLength(int(value))
                    ptr.Reset(state)
Maxime Perrotin's avatar
Maxime Perrotin committed
368
                elif asnType == 'CHOICE':
369
370
371
372
                    state = ptr.GetState()
                    # We must parse only one row, containing the choice (value)
                    chrow = root.child(i)
                    for rownb in xrange(chrow.rowCount()):
Maxime Perrotin's avatar
Maxime Perrotin committed
373
374
                        curr = chrow.child(rownb, 0).text()
                        if curr == value:
375
376
377
                            # set rownb to the row of the current choice
                            break
                    else:
Maxime Perrotin's avatar
Maxime Perrotin committed
378
                        raise TypeError('CHOICE row not found')
379
                    parseRow(chrow, rownb, dest=ptr)
380
                    ptr.Reset(state)
Maxime Perrotin's avatar
Maxime Perrotin committed
381
382
383
384
385
386
387
                    intMappings = root.child(i, 3).data(INTMAP)
                    for enumerant, num in intMappings.viewitems():
                        if enumerant == value:
                            ptr.kind.Set(num)
                            break
                    else:
                        raise TypeError('CHOICE determinant not found')
Maxime Perrotin's avatar
Maxime Perrotin committed
388
                elif asnType == 'INTEGER':
389
                    ptr.Set(int(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
390
                elif asnType == 'REAL':
391
                    ptr.Set(float(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
392
                elif asnType == 'BOOLEAN':
Maxime Perrotin's avatar
Maxime Perrotin committed
393
                    boolValue = value == 'True'
394
                    ptr.Set(boolValue)
Maxime Perrotin's avatar
Maxime Perrotin committed
395
                elif asnType == 'ENUMERATED':
Maxime Perrotin's avatar
Maxime Perrotin committed
396
397
398
399
400
401
402
                    intMappings = root.child(i, 3).data(INTMAP)
                    for enumerant, num in intMappings.viewitems():
                        if enumerant == value:
                            ptr.Set(num)
                            break
                    else:
                        raise TypeError('ENUMERATED value not found')
Maxime Perrotin's avatar
Maxime Perrotin committed
403
                else:  # Strings
404
                    ptr.SetFromPyString(value)
405
406
407

            if choice != -1:
                # Read only the row of the choice selection
Maxime Perrotin's avatar
Maxime Perrotin committed
408
                stateBefore = dest.GetState()
409
                parseRow(root, choice, dest, seqOf=False)
Maxime Perrotin's avatar
Maxime Perrotin committed
410
                dest.Reset(stateBefore)
411
412
413
414
415
            else:
                for i in xrange(nbRows):  # for each child row
                    stateBefore = dest.GetState()
                    parseRow(root, i, dest, seqOf=seqOf)
                    dest.Reset(stateBefore)
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
                    # Check if field is optional and set the .exist.field
                    # accordingly
                    field_root = root.child(i)
                    field_name = \
                            root.child(i, 0).text().replace('-', '_')
                    field_optionality = root.child(i, 4)
                    if field_optionality.data(OPTIONAL) \
                            and field_optionality.isCheckable():
                        present = field_optionality.checkState() == Qt.Checked
                        print field_name, "SET" if present else "UNSET"
                        # Uncomment the following when Stubs.py supports it:
                        #ptr = getattr(dest, "exist")
                        #ptr = getattr(ptr, field_name)
                        #ptr.Set (1 if present else 0)
                        dest.Reset(stateBefore)


433
        else:  # single elements (all but SeqOf, Choice, Sequence)
Maxime Perrotin's avatar
Maxime Perrotin committed
434
            row = root.row()
435
436
437
438
439
440
441
            try:
                value = self.model.item(row, 3).text()
                asnType = self.model.item(row, 1).text()
            except AttributeError:
                # Empty SEQUENCEs elems contain nothing
                value = ''
                asnType = None
Maxime Perrotin's avatar
Maxime Perrotin committed
442
            if asnType == 'INTEGER':
443
                dest.Set(int(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
444
            elif asnType == 'REAL':
445
                dest.Set(float(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
446
            elif asnType == 'BOOLEAN':
447
                dest.Set(True if value == 'True' else False)
Maxime Perrotin's avatar
Maxime Perrotin committed
448
            elif asnType == 'ENUMERATED':
Maxime Perrotin's avatar
Maxime Perrotin committed
449
450
451
452
453
454
455
456
457
                intMappings = self.model.item(row, 3).data(INTMAP)
                for enumerant, num in intMappings.viewitems():
                    if enumerant == value:
                        dest.Set(num)
                        break
                else:
                    self.log.error('Missing enumerted or bug - please report')
            elif asnType == 'STRING':
                dest.SetFromPyString(value)
Maxime Perrotin's avatar
Maxime Perrotin committed
458
            else:
Maxime Perrotin's avatar
Maxime Perrotin committed
459
                self.log.error('Unsupported type: please report bug')
Maxime Perrotin's avatar
Maxime Perrotin committed
460

461
462
463
    def getVariable(self, root=None, dest=None):
        ''' Read the ASN.1 variable from the tree editor
            root allows to specify which variable/row to start from
464
            dest is a ctypes instance of the given type, that
465
466
467
            will be filled by the recursive parser.
        '''
        assert dest is not None
468
469
        root = root or self.treeItem
        row = root.row()
Maxime Perrotin's avatar
Maxime Perrotin committed
470
        name = root.text()
471
        asnType = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
472
        if asnType == 'SEQOF':
473
            nbRows = int(self.model.item(row, 3).text())
474
            self.parseModel(root, nbRows=nbRows, dest=dest)
Maxime Perrotin's avatar
Maxime Perrotin committed
475
            dest.SetLength(nbRows)
Maxime Perrotin's avatar
Maxime Perrotin committed
476
        elif asnType == 'CHOICE':
477
            value = self.model.item(row, 3).text()
478
479
480
481
482
483
484
485
            # We must parse only one row, containing the choice (value)
            for rownb in xrange(root.rowCount()):
                curr = root.child(rownb, 0).text()
                if curr == value:
                    break
            else:
                raise TypeError('CHOICE ROW not found')
            self.parseModel(root, dest=dest, choice=rownb)
Maxime Perrotin's avatar
Maxime Perrotin committed
486
487
488
489
490
491
492
            intMappings = self.model.item(row, 3).data(INTMAP)
            for enumerant, num in intMappings.viewitems():
                if enumerant == value:
                    dest.kind.Set(num)
                    break
            else:
                raise TypeError('CHOICE discriminant not found')
Maxime Perrotin's avatar
Maxime Perrotin committed
493
        else:
494
            self.parseModel(root, dest=dest)
Maxime Perrotin's avatar
Maxime Perrotin committed
495

Maxime Perrotin's avatar
Maxime Perrotin committed
496
    def updateModel(self, root, ptr, nbRows=-1, choice=-1):
Maxime Perrotin's avatar
Maxime Perrotin committed
497
        ''' Recursive update of the values in the GUI from ASN.1 instance '''
Maxime Perrotin's avatar
Maxime Perrotin committed
498
        def fillRow(root, i, dest, seqOf=False):
Maxime Perrotin's avatar
Maxime Perrotin committed
499
500
501
502
503
504
            name    = root.child(i, 0).text().replace('-', '_')
            asnType = root.child(i, 1).text()
            child   = root.child(i, 3)
            ptr = getattr(dest, name) if not seqOf else dest
            if seqOf:
                ptr = ptr[i]
Maxime Perrotin's avatar
Maxime Perrotin committed
505
            if asnType in ('INTEGER', 'REAL'):
Maxime Perrotin's avatar
Maxime Perrotin committed
506
                child.setText(str(ptr.Get()))
Maxime Perrotin's avatar
Maxime Perrotin committed
507
508
            elif asnType == 'BOOLEAN':
                child.setText('True' if ptr.Get() else 'False')
Maxime Perrotin's avatar
Maxime Perrotin committed
509
510
511
512
513
514
515
516
517
518
            elif asnType == 'STRING':
                child.setText(ptr.GetPyString())
            elif asnType == 'ENUMERATED':
                value = ptr.Get()
                intMappings = child.data(INTMAP)
                for enumerant, num in intMappings.viewitems():
                    if num == value:
                        child.setText(enumerant)
                        break
                else:
Maxime Perrotin's avatar
Maxime Perrotin committed
519
                    raise TypeError("ENUMERATED value not found")
Maxime Perrotin's avatar
Maxime Perrotin committed
520
521
522
523
            elif asnType in ('SEQUENCE', 'SET'):
                self.updateModel(root.child(i), ptr)
            elif asnType == 'CHOICE':
                state = ptr.GetState()
Maxime Perrotin's avatar
Maxime Perrotin committed
524
                valueNum = ptr.kind.Get()
Maxime Perrotin's avatar
Maxime Perrotin committed
525
526
                ptr.Reset(state)
                intMappings = child.data(INTMAP)
Maxime Perrotin's avatar
Maxime Perrotin committed
527
                choiceList = child.data(CHOICE_LIST)
Maxime Perrotin's avatar
Maxime Perrotin committed
528
                for enumerant, num in intMappings.viewitems():
Maxime Perrotin's avatar
Maxime Perrotin committed
529
                    if num == valueNum:
Maxime Perrotin's avatar
Maxime Perrotin committed
530
                        child.setText(str(enumerant))
Maxime Perrotin's avatar
Maxime Perrotin committed
531
532
533
534
                        # Find the choice row number
                        for rowNb, choiceName in enumerate(choiceList):
                            if choiceName == enumerant:
                                fillRow(root.child(i),
Maxime Perrotin's avatar
Maxime Perrotin committed
535
                                        rowNb, dest=ptr)
Maxime Perrotin's avatar
Maxime Perrotin committed
536
537
538
                                break
                        else:
                            raise TypeError('CHOICE ROW not found')
Maxime Perrotin's avatar
Maxime Perrotin committed
539
                        break
Maxime Perrotin's avatar
Maxime Perrotin committed
540
541
                else:
                    raise TypeError('fillRow: CHOICE determinant not found')
Maxime Perrotin's avatar
Maxime Perrotin committed
542
543
544
545
546
547
            elif asnType == 'SEQOF':
                state = ptr.GetState()
                size = ptr.GetLength()
                ptr.Reset(state)
                child.setText(str(size))
                self.updateModel(root.child(i), ptr, nbRows=size)
Maxime Perrotin's avatar
Maxime Perrotin committed
548
549
550
551
552
553
554
555
            if asnType in ('INTEGER', 'REAL', 'SEQOF'):
                plotters = child.data(PLOTTERS)
                if plotters is not None:
                    self.log.debug("updateModel - updatePlot call")
                    value = float(child.text())
                    for plotter in plotters:
                        self.plotterBackend.updatePlot(plotter, value)
                    self.log.debug("updateModel - updatePlot end")
Maxime Perrotin's avatar
Maxime Perrotin committed
556

Maxime Perrotin's avatar
Maxime Perrotin committed
557
558
559
560
561
562
563
564
565
        if choice != -1:
            stateBefore = ptr.GetState()
            fillRow(root, choice, ptr)
            ptr.Reset(stateBefore)
        else:
            if root.hasChildren():
                seqOf = True if nbRows != -1 else False
                if not seqOf:
                    nbRows = root.rowCount()
Maxime Perrotin's avatar
Maxime Perrotin committed
566

Maxime Perrotin's avatar
Maxime Perrotin committed
567
568
569
570
                for i in xrange(nbRows):
                    stateBefore = ptr.GetState()
                    fillRow(root, i, ptr, seqOf=seqOf)
                    ptr.Reset(stateBefore)
571

Maxime Perrotin's avatar
Maxime Perrotin committed
572
    def updateVariable(self, root=None, asn1Var=None):
573
        ''' Update the variable value (when loading a TC or receiving a TM) '''
Maxime Perrotin's avatar
Maxime Perrotin committed
574
        root         = root or self.treeItem
Maxime Perrotin's avatar
Maxime Perrotin committed
575
        asn1Instance = asn1Var or self.asn1Instance
Maxime Perrotin's avatar
Maxime Perrotin committed
576
577
        row          = root.row()
        asnType      = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
578
        asn1Instance.Reset()
Maxime Perrotin's avatar
Maxime Perrotin committed
579

Maxime Perrotin's avatar
Maxime Perrotin committed
580
        if asnType == 'SEQOF':
581
            # Set the number of items in column 3
Maxime Perrotin's avatar
Maxime Perrotin committed
582
            nbElem = asn1Instance.GetLength()
583
584
            self.model.item(row, 3).setText(str(nbElem))
            # And set the values recursively
Maxime Perrotin's avatar
Maxime Perrotin committed
585
            self.updateModel(root, ptr=asn1Instance, nbRows=nbElem)
Maxime Perrotin's avatar
Maxime Perrotin committed
586
        elif asnType == 'CHOICE':
Maxime Perrotin's avatar
Maxime Perrotin committed
587
            kind = asn1Instance.kind.Get()
588
589
590
591
592
593
            # get the mapping to retrieve the choice name from the kind
            intMappings = self.model.item(row, 3).data(INTMAP)
            for enumerant, num in intMappings.viewitems():
                if num == kind:
                    break
            else:
Maxime Perrotin's avatar
Maxime Perrotin committed
594
                self.log.error("CHOICE index not found in DV.py")
595
            self.model.item(row, 3).setText(enumerant)
Maxime Perrotin's avatar
Maxime Perrotin committed
596
597
598
599
600
601
602
            # Find the row and set the value
            for rownb in xrange(root.rowCount()):
                if enumerant == root.child(rownb, 0).text():
                    break
            else:
                raise TypeError('(SET) CHOICE ROW not found')
            self.updateModel(root, asn1Instance, choice=rownb)
Maxime Perrotin's avatar
Maxime Perrotin committed
603
604
605
606
607
608
609
        elif asnType in ('INTEGER', 'REAL'):
            self.model.item(row, 3).setText(str(asn1Instance.Get()))
        elif asnType == 'BOOLEAN':
            value = 'True' if asn1Instance.Get() else 'False'
            self.model.item(row, 3).setText(value)
        elif asnType == 'STRING':
            self.model.item(row, 3).setText(asn1Instance.GetPyString())
Maxime Perrotin's avatar
Maxime Perrotin committed
610
        elif asnType == 'ENUMERATED':
Maxime Perrotin's avatar
Maxime Perrotin committed
611
            value = asn1Instance.Get()
612
613
614
            # get the mapping to retrieve the integer value
            intMappings = self.model.item(row, 3).data(INTMAP)
            for enumerant, num in intMappings.viewitems():
Maxime Perrotin's avatar
Maxime Perrotin committed
615
616
                # XXX if value is not initialized and no enum has value 0
                # an error will be raised
617
618
619
620
                if num == value:
                    self.model.item(row, 3).setText(enumerant)
                    break
            else:
Maxime Perrotin's avatar
Maxime Perrotin committed
621
                self.log.error("ENUMERATED value '{}' not found".format(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
622
        else:  # SEQUENCE or SET
Maxime Perrotin's avatar
Maxime Perrotin committed
623
            self.updateModel(root, asn1Instance)
Maxime Perrotin's avatar
Maxime Perrotin committed
624
        if asnType in ('INTEGER', 'REAL', 'SEQOF'):
Maxime Perrotin's avatar
Maxime Perrotin committed
625
626
627
628
            plotters = self.model.item(row, 3).data(PLOTTERS) or []
            value = self.model.item(row, 3).text()
            for plotter in plotters:
                self.plotterBackend.updatePlot(plotter, float(value))
629
        self.hideUnusedFields(root, True, row=row)
Maxime Perrotin's avatar
Maxime Perrotin committed
630
        if self.plotterBackend is not None:
Maxime Perrotin's avatar
Maxime Perrotin committed
631
632
            self.plot_refresh.emit()
            #self.plotterBackend.refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
633
634
635
        # Inform the thread to update the tree (expand all branches)
        self.expandTree.emit()

636
    def tmToEditor(self, emit_msc=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
637
        ''' Check validity of a TM and update the viewer with the value '''
638
639
        self.updateVariable()
        # Send value to the MSC recorder
Maxime Perrotin's avatar
Maxime Perrotin committed
640
641
642
        name = self.item['id']
        msg = name + '(' + vn.format_gser(self.asn1Instance.GSER()) + ')'
        self.log.debug('MSC: '+ msg)
643
644
645
        if emit_msc:
            self.msc.emit('in', msg)
        self.new_tm.emit()
Maxime Perrotin's avatar
Maxime Perrotin committed
646
647
648
649
650

    @Slot()
    def receivedTM(self):
        ''' TM received from another thread (polling queue) '''
        if self.pendingTM:
651
652
653
654
655
656
            self.log.debug("Got TM from MsgQ")
            self.tmToEditor()
            # Send TM to user custom widgets
            for each in self.tm_clients:
                each.update(self.asn1Instance)
            self.pendingTM = False
Maxime Perrotin's avatar
Maxime Perrotin committed
657
658

    def ProcessUDPTM(self, uperMsg):
Maxime Perrotin's avatar
Maxime Perrotin committed
659
660
        ''' Decode an uPER-encoded TM (e.g. received from UDP sockets)
            and update the model '''
661
662
663
664
665
        self.log.error('DEPRECATED - UDP channel not supported anymore')
        return
        #native_tm = self.backend.decode_uPER(uperMsg)
        #pythonVar = self.backend.fromASN1ToPyside(native_tm)
        #self.tmToEditor(pythonVar)
Maxime Perrotin's avatar
Maxime Perrotin committed
666

667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#   def saveTC(self):
#   DEPRECATED - Load/Save TC must be done with databases
#       ''' Encode the data using GSER (ASN.1 Value Notation) and save it
#       to a file'''
#       name = self.treeItem.text()
#       gser = self.gser(use_dash=True)
#       self.log.debug('Saving ' + gser)
#       filename = QFileDialog.getSaveFileName(self,
#                                              "Save TC",
#                                              ".",
#                                              "ASN.1 Variable (*.tc)")[0]
#       try:
#           if filename.split('.')[-1] != 'tc':
#               filename += ".tc"
#           tcFile = QFile(filename)
#           tcFile.open(QIODevice.WriteOnly | QIODevice.Text)
#           tcFile.write(str(gser))
#           tcFile.close()
#       except:
#           pass
Maxime Perrotin's avatar
Maxime Perrotin committed
687

688
689
    def gser(self, use_dash=False):
        ''' Helper API function: return the GSER representation of the data '''
690
        self.getVariable(dest=self.asn1Instance)
Maxime Perrotin's avatar
Maxime Perrotin committed
691
        res = vn.format_gser(self.asn1Instance.GSER())
692
        return res if use_dash else res.replace('-', '_')
693

694
695
    def to_asn1scc_ctypes(self, root, dest, ASN1Mod, sort, ASN1_AST):
        ''' Helper API function: read variable and set ASN.1 Native variable
696
        Inputs: root: select which variable to parse
697
698
                dest: Native ctypes variable (will be modified)
                ASN1Mod: python module containing ctypes DV access
699
700
                sort: root ASN.1 typename (with dash, no underscores)
                ASN1_AST: full AST generated by ASN1SCC
701
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
702
        # DEPRECATED - call getVariable directly
703
        self.getVariable(root=root, dest=dest)
704

Maxime Perrotin's avatar
Maxime Perrotin committed
705
    def sendTC(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
706
707
        ''' Encode and send the TC to the main TASTE binary
            using message queue or UDP '''
708
        self.getVariable(dest=self.asn1Instance)
Maxime Perrotin's avatar
Maxime Perrotin committed
709
        gser = vn.format_gser(self.asn1Instance.GSER())
710
711
712
713
        msg = "{name}({gser})".format(name=self.treeItem.text(), gser=gser)
        self.log.debug('out ' + msg)
        self.msc.emit('out', msg)
        self.backend.sendTC(self.asn1Instance)
Maxime Perrotin's avatar
Maxime Perrotin committed
714

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
#   def loadTC(self, dest=None):
#   DEPRECATED / Load/Save of TC must be done with databases
#       ''' Load/Decode a TC and populate the values in the model '''
#       dest = dest or self.asn1Instance
#       filename = QFileDialog.getOpenFileName(self,
#                                              "Open TC",
#                                              ".",
#                                              "ASN.1 Variable (*.tc)")[0]
#       if len(filename) == 0:
#           return
#       try:
#           tcFile = QFile(filename)
#           tcFile.open(QIODevice.ReadOnly | QIODevice.Text)
#           asnVN = str(tcFile.readData(tcFile.size()))
#           tcFile.close()
#           vn.valueNotationToCTypes(gser=asnVN,
#                                    dest=dest,
#                                    sort=,
#                                    ASN1Mod=,
#                                    ASN1_AST=)
#       except:
#           self.log.error('TC not loaded')
Maxime Perrotin's avatar
Maxime Perrotin committed
737
738

    def dataPath(self, idx):
Maxime Perrotin's avatar
Maxime Perrotin committed
739
740
        ''' Create a textual representation of a field path
            (e.g. myTM.myChoice.position.x) '''
Maxime Perrotin's avatar
Maxime Perrotin committed
741
742
743
744
        if not idx.isValid():
            return ''
        subpath = self.dataPath(idx.parent())
        if len(subpath)>0:
745
            subpath += '.'
Maxime Perrotin's avatar
Maxime Perrotin committed
746
747
748
749
        subpath += idx.data()
        return subpath

    def pathToIdx(self, path, root=None):
Maxime Perrotin's avatar
Maxime Perrotin committed
750
751
        ''' Find an index in the model based from a dot-splitted
            path representation '''
Maxime Perrotin's avatar
Maxime Perrotin committed
752
753
754
755
756
757
758
759
760
761
762
763
        if root is None:
            root = self.treeItem.index()
        if len(path) == 1:
            return QPersistentModelIndex(root) if root.data() == path[0] else None
        else:
            # Recursive call for each child
            for i in range(self.model.itemFromIndex(root).rowCount()):
                result = self.pathToIdx(path[1:], root.child(i, 0))
                if result is not None:
                    return result

    def newPlot(self, fifoId=-1, meter=False):
Maxime Perrotin's avatar
Maxime Perrotin committed
764
765
        ''' Add a set of data (based on selected lines) to a new plotter
            or speedometer '''
Maxime Perrotin's avatar
Maxime Perrotin committed
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
        selectedIdxs = self.selectedIndexes()
        # Count the number of eligible lines for plotting (discard non-numerical types)
        eligible=[]
        for idx in selectedIdxs:
            if idx.column() > 0:
                continue
            asntype = idx.sibling(idx.row(), 1).data()
            if asntype in ('INTEGER', 'REAL', 'SEQOF'):
                self.log.info('Candidate for plot: '+ self.dataPath(idx))
                discard = False
                if fifoId > 0:
                    currData=idx.sibling(idx.row(), 3).data(PLOTTERS)
                    if currData is not None:
                        for elem in currData:
                            if elem['fifoId'] == fifoId:
                                discard = True
                if not discard:
                    eligible.append(idx.sibling(idx.row(), 3))
                else:
                    self.log.info('(but discarding because already in current plot)')
            else:
                self.log.warning('Cannot plot {data} (type {asntype} is not numerical)'.format(data=idx.data(), asntype=asntype))
        if len(eligible) == 0:
            self.log.warning('No valid lines selected for the plot')
            self.statusBarMessage.emit('No valid lines selected for the plot')
            return
        if fifoId == -1 and not meter:
            fifoId = self.plotterBackend.newPlot()
        for idx in eligible:
            dataPath = self.dataPath(idx.sibling(idx.row(), 0))
            currData = idx.data(PLOTTERS)
            minRange = idx.data(MIN_RANGE)
            maxRange = idx.data(MAX_RANGE)
            if meter:
                fifoId = self.plotterBackend.newMeter(dataPath, minRange, maxRange)
            if currData is None:
                currData = []
            currData.append({'fifoId': int(fifoId), 'curveName': dataPath})
            idx.model().setData(idx, currData, PLOTTERS)
            # Keep track of all plotted values - used when saving the model state
            persistentIdx = QPersistentModelIndex(idx)
            if persistentIdx not in self.plottedIdxs:
                self.plottedIdxs.append(persistentIdx)

    def addToPlot(self):
        ''' Add a new curve to an existing plot window '''
        fifoId = self.sender().text().split()[-1]
        self.newPlot(int(fifoId))

    def setPlotterBackend(self, backend):
        ''' Set a "pointer" to the GnuPlot/Meter backend module '''
        self.plotterBackend = backend

    def meter(self):
        ''' Create speedometers for the selected values '''
        self.newPlot(meter=True)

823
824
825
826
827
828
829
830
831
832
    def custom(self, custom_class):
        ''' Handle user-defined widgets: for TC, provide access to the Send
        and Update APIs. Defined differently for the asn1Viwer (TM) class '''
        custom_handler = custom_class(self.item['nodeTypename']
                                      .replace('-', '_'), parent=self)
        # Attach the docking widget to the GUI (XXX refactor)
        self.parent().parent().parent().addDockWidget(Qt.RightDockWidgetArea,
                                                      custom_handler)
        custom_handler.setFloating(True)

Maxime Perrotin's avatar
Maxime Perrotin committed
833
834
835
836
    def displaytip(self, index):
        ''' Display a tip when the mouse moves above a cell '''
        asnType = index.sibling(index.row(), 1).data()
        constraint = index.sibling(index.row(), 2).data()
837
838
        self.statusBarMessage.emit(asnType + ' ' +
                             (constraint if constraint is not None else ''))
Maxime Perrotin's avatar
Maxime Perrotin committed
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

    @Slot(QModelIndex, int, int)
    def seqofDisplay(self, parent, val, max):
        ''' Slot updating the number of SEQOF elements displayed '''
        for row in range(max):
            if int(row) < int(val):
                display = False
            else:
                display = True
            self.setRowHidden(row, parent, display)
        self.expandBranch.emit(parent)

    @Slot(QModelIndex, int, int)
    def choiceDisplay(self, parent, nbOfElem, choice):
        ''' Slot updating the current selected CHOICE element '''
        for row in range(nbOfElem):
            if int(choice) == int(row):
                display = False
            else:
                display = True
            self.setRowHidden(row, parent, display)
        self.expandBranch.emit(parent)

    def addInteger(self, elem):
        # Set default value (min range):
        val = QStandardItem('%d' % elem["minR"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)
        try:
            val.setData(elem["minR"], MIN_RANGE)
        except OverflowError:
            val.setData(-1000000, MIN_RANGE)
        try:
            val.setData(elem["maxR"], MAX_RANGE)
        except OverflowError:
            val.setData(1000000, MAX_RANGE)
        # Set the text for the constraint and add it to the 3rd column:
        constraint = QStandardItem('(%d..%d)' % (elem["minR"], elem["maxR"]))
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
878
879
880
881
882
883
        present = QStandardItem()
        present.setData (elem['isOptional'], OPTIONAL)
        if elem['isOptional']:
            present.setCheckState(Qt.Checked)
            present.setCheckable(True)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

    def addReal(self, elem):
        # Set default value (min range):
        val = QStandardItem('%.2f' % elem["minR"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)
        try:
            val.setData(elem["minR"], MIN_RANGE)
        except OverflowError:
            # Python cannot handle 64bit double - reducing the range in case of overflow
            val.setData(-10000000.0, MIN_RANGE)
        try:
            val.setData(elem["maxR"], MAX_RANGE)
        except OverflowError:
            val.setData(10000000.0, MAX_RANGE)
        # Set the text for the constraint and add it to the 3rd column:
        constraint = QStandardItem('(%.2f..%.2f)' % (elem["minR"], elem["maxR"]))
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
902
903
904
905
906
907
        present = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
908
909
910
911
912
913
914

    def addEnum(self, elem):
        # Set default value (first enum value)
        val = QStandardItem(elem["values"][0])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (ENUMERATED)
        val.setData(elem["values"], CHOICE_LIST)  # enum values
915
        val.setData(elem["valuesInt"], INTMAP) # mapping name - value
Maxime Perrotin's avatar
Maxime Perrotin committed
916
        constraint = QStandardItem()
917
918
919
920
921
922
        present    = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        return {"value": val, "constraint": constraint, "present" : present}
Maxime Perrotin's avatar
Maxime Perrotin committed
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941

    def addString(self, elem):
        # Set default value (empty string)
        if "default" in elem:
            defaultString = elem["default"]
        else:
            defaultString = ""
        val = QStandardItem(defaultString)
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (IA5String)
        val.setData(elem["minSize"], MIN_RANGE)  # size min
        val.setData(elem["maxSize"], MAX_RANGE)  # size max
        # Set the text for the constraint and add it to the 3rd column:
        if elem["minSize"] == elem["maxSize"]:
            constraintStr = 'SIZE(%d)' % elem["minSize"]
        else:
            constraintStr = 'SIZE(%d..%d)' % (elem["minSize"], elem["maxSize"])
        constraint = QStandardItem(constraintStr)
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
942
943
944
945
946
947
        present    = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
948
949
950
951
952
953
954
955

    def addBool(self, elem):
        # Set default value (True or False)
        val = QStandardItem(elem["default"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (BOOLEAN)
        val.setData(['True', 'False'], CHOICE_LIST)  # enum values
        constraint = QStandardItem()
956
957
958
959
960
961
        present    = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
962
963
964
965
966

    def addSequence(self, elem, parent):
        types = []
        values = []
        constraints = []
967
        presence = []
Maxime Perrotin's avatar
Maxime Perrotin committed
968
969
970

        for child in elem["children"]:
            field = self.addItem(child)
971
972
973
974
975
            parent.appendRow   (field["item"])
            types.append       (field["type"])
            values.append      (field["value"])
            constraints.append (field["constraint"])
            presence.append    (field["present"])
Maxime Perrotin's avatar
Maxime Perrotin committed
976
977
978
979

        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)
980
981
        parent.appendColumn(presence)

Maxime Perrotin's avatar
Maxime Perrotin committed
982
        constraint = QStandardItem()
983
984
985
986
987
988
989
990
        val     = QStandardItem()
        present = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        present.setCheckable (elem['isOptional'])
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
991
992
993
994
995

    def addSeqOf(self, elem, parent):
        types = []
        values = []
        constraints = []
996
        presence = []
Maxime Perrotin's avatar
Maxime Perrotin committed
997
998
999
        for i in range(elem["maxSize"]):
            elem["seqoftype"]["id"] = "elem_%d" % i
            field = self.addItem(elem["seqoftype"])
1000
1001
1002
1003
1004
1005
            parent.appendRow   (field["item"])
            types.append       (field["type"])
            values.append      (field["value"])
            constraints.append (field["constraint"])
            presence.append    (field["present"])

Maxime Perrotin's avatar
Maxime Perrotin committed
1006
1007
1008
        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)
1009
1010
        parent.appendColumn(presence)

Maxime Perrotin's avatar
Maxime Perrotin committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
        if elem["minSize"] == elem["maxSize"]:
            constraintStr = 'SIZE(%d)' % elem["minSize"]
        else:
            constraintStr = 'SIZE(%d..%d)' % (elem["minSize"], elem["maxSize"])
        constraint = QStandardItem(constraintStr)
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
        val = QStandardItem('%d' % elem["minSize"])
        val.setData(elem["type"], ASN1TYPE)   # type (SEQOF)
        val.setData(elem["minSize"], MIN_RANGE)  # min number of elements
        val.setData(elem["maxSize"], MAX_RANGE)  # max number of elements
1021
1022
1023
1024
1025
1026
        present = QStandardItem()
        present.setData (elem['isOptional'], OPTIONAL)
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
1027
1028
1029
1030
1031

    def addChoice(self, elem, parent):
        types = []
        values = []
        constraints = []
1032
        presence = []
Maxime Perrotin's avatar
Maxime Perrotin committed
1033
        ids = []
1034

Maxime Perrotin's avatar
Maxime Perrotin committed
1035
1036
        for choice in elem["choices"]:
            field = self.addItem(choice)
1037
1038
1039
1040
1041
1042
            ids.append         (choice["id"])
            parent.appendRow   (field["item"])
            types.append       (field["type"])
            values.append      (field["value"])
            constraints.append (field["constraint"])
            presence.append    (field["present"])
Maxime Perrotin's avatar
Maxime Perrotin committed
1043
1044
1045
1046

        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)
1047
        parent.appendColumn(presence)
Maxime Perrotin's avatar
Maxime Perrotin committed
1048
1049
1050

        val = QStandardItem(ids[0])  # default value: first choice
        # Define type attributes, later used to define the proper cell editor
1051
1052
        val.setData(elem["type"],      ASN1TYPE)  # type (CHOICE)
        val.setData(ids,               CHOICE_LIST)  # choice values
1053
        val.setData(elem["choiceIdx"], INTMAP) # mapping name - DV value
Maxime Perrotin's avatar
Maxime Perrotin committed
1054
        constraint = QStandardItem()
1055
1056
1057
1058
1059
1060
        present = QStandardItem()
        if elem['isOptional']:
            present.setCheckState (Qt.Checked)
            present.setCheckable(True)
        present.setData (elem['isOptional'], OPTIONAL)
        return {"value": val, "constraint": constraint, "present": present}
Maxime Perrotin's avatar
Maxime Perrotin committed
1061
1062
1063
1064
1065
1066
1067

    def addItem(self, elem):
        # Add field name on the first column:
        field = QStandardItem(elem["id"])
        # Add type on the second column in gray:
        asnType = QStandardItem(elem["type"])
        asnType.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
1068
        # elem['isOptional'] is true if the field is marked OPTIONAL in ASN.1
Maxime Perrotin's avatar
Maxime Perrotin committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087

        # get the Value and Contraints fields for the different types:
        if elem["type"] == 'INTEGER':
            data = self.addInteger(elem)
        elif elem["type"] == 'REAL':
            data = self.addReal(elem)
        elif elem["type"] == 'BOOLEAN':
            data = self.addBool(elem)
        elif elem["type"] == 'ENUMERATED':
            data = self.addEnum(elem)
        elif elem["type"] == 'STRING':
            data = self.addString(elem)
        elif elem["type"] in ('SEQUENCE', 'SET'):
            data = self.addSequence(elem, field)
        elif elem["type"] == 'SEQOF':
            data = self.addSeqOf(elem, field)
        elif elem["type"] == 'CHOICE':
            data = self.addChoice(elem, field)
        else:
Maxime Perrotin's avatar
Maxime Perrotin committed
1088
            raise TypeError('Unsupported type: ' + elem["type"])
Maxime Perrotin's avatar
Maxime Perrotin committed
1089
            sys.exit(-1)
1090
1091
1092
1093
1094
        return {"item":       field,
                "type":       asnType,
                "value":      data["value"],
                "constraint": data["constraint"],
                "present"   : data["present"]}
Maxime Perrotin's avatar
Maxime Perrotin committed
1095
1096
1097
1098
1099


class asn1Viewer(asn1Editor):
    ''' TM Viewing class. Fields are not editable '''
    def __init__(self, parent=None):
1100
        super(asn1Viewer, self).__init__(parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
1101
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112

    def custom(self, custom_class):
        ''' Handle user-defined widgets: for TM make sure a signal is emitted
        with ASN1 value when a TM is received '''
        custom_handler = custom_class(parent=self)
        # Attach the docking widget to the GUI (XXX refactor)
        self.parent().parent().parent().addDockWidget(Qt.RightDockWidgetArea,
                                                      custom_handler)
        self.tm_clients.append(custom_handler)
        self.new_tm.connect(custom_handler.new_tm)
        custom_handler.setFloating(True)