pyside_B_mapper.py 28 KB
Newer Older
1 2 3 4 5
# (C) Semantix Information Technologies for the mapper design.
# (C) European Space Agency for the Pyside GUI code - Author: Maxime Perrotin

import re
import os
6
from typing import List
7 8 9 10

from ..commonPy.asnAST import (
    AsnInt, AsnBool, AsnReal, AsnEnumerated,
    AsnOctetString, AsnChoice, AsnSequence, AsnSet,
11
    AsnSequenceOf, AsnSetOf, AsnMetaMember, AsnNode)
12 13

from ..commonPy.utility import panic
14 15
from ..commonPy.asnParser import AST_Lookup, AST_Leaftypes
from ..commonPy.aadlAST import ApLevelContainer, Param
16 17 18 19 20

g_PyDataModel = None
g_iter = 1
g_IFCount = 0
g_BackendFile = None
21 22
g_fromPysideToASN1 = []  # type: List[str]
g_fromASN1ToPyside = []  # type: List[str]
23
g_QUiFile = None
24 25 26 27 28
g_bStarted = False       # type: bool
g_firstElem = True       # type: bool
g_asnId = ""             # type: str
g_needsComa = False      # type: bool
g_onceOnly = True        # type: bool
29 30


31
def CleanName(name: str) -> str:
32 33 34
    return re.sub(r'[^a-zA-Z0-9_]', '_', name)


35 36
def OneTimeOnly(
        unused_modelingLanguage: str,
37
        unused_asnFile: str,
38 39 40 41 42
        subProgram: ApLevelContainer,
        subProgramImplementation: str,
        outputDir: str,
        FVname: str,
        unused_useOSS: bool) -> None:
43 44 45 46
    global g_PyDataModel
    g_PyDataModel = open(outputDir + 'datamodel.py', 'w')
    g_PyDataModel.write('''#!/usr/bin/python

47 48
import DV

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
FVname = "{fvname}"

tc = {{}}
tm = {{}}
errCodes = {{}}
'''.format(fvname=FVname))

    global g_QUiFile
    g_QUiFile = open(outputDir + 'guilayout.ui', 'w')
    g_QUiFile.write('''<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="TasteMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>710</width>
    <height>575</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>{fvName}</string>
  </property>
  <property name="tabShape">
   <enum>QTabWidget::Rounded</enum>
  </property>
  <property name="dockOptions">
   <set>QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::AnimatedDocks</set>
  </property>
  <widget class="QWidget" name="centralWidget">
  <layout class="QVBoxLayout" name="verticalLayout">
     <item>
      <widget class="QLabel" name="tasteLogo" native="true">
       <property name="pixmap">
        <pixmap>tasteLogo_white.png</pixmap>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QLabel" name="instructions" native="true">
       <property name="text">
        <string>Available test scripts:</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QListWidget" name="msc" native="true"/>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QPushButton" name="runMSC">
         <property name="text">
          <string>Run</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="loadMSC">
         <property name="text">
          <string>Load</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="editMSC">
         <property name="text">
          <string>Edit</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </widget>
   <widget class="QStatusBar" name="statusBar"/>
'''.format(fvName=FVname))
    if FVname == "":
        panic("GUI APLCs must have an FV_Name attribute! (%s)\n" %
              subProgram._id + "." + subProgramImplementation)  # pragma: no cover


132 133 134 135 136 137 138 139
def OnStartup(
        modelingLanguage: str,
        asnFile: str,
        subProgram: ApLevelContainer,
        subProgramImplementation: str,
        outputDir: str,
        FVname: str,
        useOSS: bool) -> None:
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
    '''
        Called once per interface (PI or RI)
        (SUBPROGRAM IMPLEMENTATION in mini_cv.aadl)
    '''
    global g_bStarted
    if not g_bStarted:
        g_bStarted = True
        OneTimeOnly(modelingLanguage, asnFile, subProgram,
                    subProgramImplementation, outputDir, FVname, useOSS)

    CleanSP = CleanName(subProgram._id)

    # Create the per-PI/RI backend file that includes Encode/Decode functions
    global g_BackendFile
    g_BackendFile = open(outputDir + '%s_backend.py' % CleanSP, 'w')
    g_BackendFile.write('''#!/usr/bin/python

import sys
import ctypes
import Queue
import datamodel
import DV
import Stubs
try:
    import vn
    import asn1_python
except ImportError:
    # Support both the old and new installation schemes
    from asn1_value_editor import vn, asn1_python

import {asn1Module} as ASN1

# Optional GUI panel for this message - used to forward received TMs
editor = None
'''.format(asn1Module=CleanName(os.path.basename(asnFile))))

    global g_firstElem
    g_firstElem = True
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
178 179 180
    # buttons = []  # type: List[List[str]]
    buttons = ([["plotButton", "Plot"], ["meterButton", "Meter"],
                ["unusedButton", "Unused"]])
181 182 183 184 185 186 187
    # RI = TC (Telecommand), PI = TM (Telemetry)
    if modelingLanguage.lower() == 'gui_ri':
        g_BackendFile.write('''
tcId = -1
msgQ = False
udp = False
shared_lib = False
Maxime Perrotin's avatar
Maxime Perrotin committed
188
ASN1_AST = None # Set by Scenario.py - point to the ASN.1 AST from Python.stg
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

# Variable containing a signal that is used to send a message via a dll
send_via_dll = None

try:
    import PythonController
except ImportError:
    pass

# External configuration point - user must select between message queues,
# UDP or shared libraries for exchanging messages with the main binary

def setMsgQ():
    global tcId
    global msgQ
    tcId = PythonController.i_{tcName}
    msgQ = True


def setUDP():
    global udp
    global tcId
    from _InterfaceEnum import i_{fvName}_RI_{tcName}
    tcId = i_{fvName}_RI_{tcName}
    udp = True


def setSharedLib(dll=None):
    # The shared library is loaded and initialized by the caller
    global shared_lib
    global {tcName}_via_shared_lib
    shared_lib = True
221
    {tcName}_via_shared_lib = dll.{fvName}_PI_{tcName}
222 223

'''.format(fvName=FVname, tcName=CleanSP))
Maxime Perrotin's avatar
Maxime Perrotin committed
224
        g_PyDataModel.write('\ntc["{tcName}"] = '.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
225
            tcName=CleanSP))
226 227 228
        buttons = ([["sendButton", "Send TC"], ["loadButton", "Load TC"],
                    ["saveButton", "Save TC"]])
        classType = "asn1Editor"
229
    else:
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
230
        assert modelingLanguage.lower() == 'gui_pi'
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
        g_BackendFile.write('''

tmId = -1
shared_lib = None

# Class configured by the GUI with a signal to be emitted when a TM is received
tm_callback = None

try:
    import PythonController
except:
    pass

def setMsgQ():
    global tmId
    tmId = PythonController.i_{tmName}


def setUDP():
    global tmId
    from _InterfaceEnum import i_{fvName}_PI_{tmName}
    tmId = i_{fvName}_PI_{tmName}


def {tmName}(tm_ptr, size):
256
    """ Callback function when receiving this TM (opengeode-simulator) """
257
    if editor:
258 259
        editor.asn1Instance.SetData(tm_ptr)
        editor.pendingTM = True
260 261 262 263
        tm_callback.got_tm.emit()


# Callback function prototype - a void* param, and returning nothing
264 265 266 267 268 269
# Apparently c_void_p does not work on 64 bits machines... use a workaround:
class ReturnPointer (ctypes.Structure):
    pass
ReturnHandle = ctypes.POINTER(ReturnPointer)
func = ctypes.CFUNCTYPE(None, ReturnHandle, ctypes.c_long)
#func = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_long)
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
cmp_func = func({tmName})

def setSharedLib(dll=None):
    # The shared library is loaded and initialized by the caller
    global shared_lib
    shared_lib = dll
    dll.register_{tmName}(cmp_func)

'''.format(tmName=CleanSP, fvName=FVname))
        g_PyDataModel.write('\ntm["{tmName}"] = '.format(tmName=CleanSP))
        buttons = ([["plotButton", "Plot"], ["meterButton", "Meter"],
                    ["unusedButton", "Unused"]])
        classType = "asn1Viewer"

    # global g_QUiFile
    global g_IFCount
    Left = 1
    Right = 2
    g_QUiFile.write('''\
  <widget class="QDockWidget" name="{direction}_{ifCount}">
   <property name="allowedAreas">
    <set>Qt::RightDockWidgetArea</set>
   </property>
   <property name="windowTitle">
    <string>{interfaceName}</string>
   </property>
   <attribute name="dockWidgetArea">
    <number>{widgetArea}</number>
   </attribute>
   <widget class="QWidget" name="dockWidgetContents">
    <layout class="QVBoxLayout" name="verticalLayout">
     <item>
      <widget class="{classType}" name="{interfaceName}" native="true"/>
     </item>
     <item>
      <layout class="QHBoxLayout" name="horizontalLayout">
       <item>
        <widget class="QPushButton" name="{buttons[0][0]}">
         <property name="text">
          <string>{buttons[0][1]}</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="{buttons[1][0]}">
         <property name="text">
          <string>{buttons[1][1]}</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="{buttons[2][0]}">
         <property name="text">
          <string>{buttons[2][1]}</string>
         </property>
        </widget>
       </item>
       <item>
        <widget class="QPushButton" name="customCombo">
         <property name="text">
          <string>Custom</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </widget>
  </widget>
'''.format(direction='tc' if modelingLanguage.lower() == 'gui_ri' else 'tm',
           widgetArea=Right if modelingLanguage.lower() == 'gui_ri' else Left,
           ifCount=g_IFCount, interfaceName=CleanSP, buttons=buttons,
           classType=classType))

    g_IFCount += 1

    # Get ASN.1 type associated with the PI/RI (if any)
    # and create an instance of it in the Encoder file.
    if len(subProgram._params) == 1:
        param = subProgram._params[0]
        CleanASNType = CleanName(param._signal._asnNodename)
        g_BackendFile.write('''
log = None
statusbar = None
udpController = None


def checkConstraints(asnVal):
    \'\'\' Check if the ASN.1 constraints are respected \'\'\'
359
    # asnVal input is a ctypes instance of an ASN.1 type
360 361 362 363 364 365 366 367 368 369 370
    isValid, errCode = asnVal.IsConstraintValid()
    if not isValid:
        errorMsg = datamodel.errCodes[errCode]['name'] + ': Constraint error! Constraint is: ' + datamodel.errCodes[errCode]['constraint']
        if log:
            log.error(errorMsg)
        return False
    else:
        return True


def encode_ACN(asnVal):
371
    \'\'\' Encode the native Asn1Scc structure in ACN \'\'\'
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

    # Check the ASN.1 constraints:
    if not checkConstraints(asnVal):
        return

    # Create a stream buffer to host the ACN-encoded data (for saving to file)
    buffer = ASN1.DataStream(DV.{asn1Type}_REQUIRED_BYTES_FOR_ACN_ENCODING)

    try:
        # Encode the value into the buffer
        asnVal.EncodeACN(buffer)
    except:
        if log:
            log.error('ACN Encoding failed')
        return

    return buffer.GetPyString()


def decode_ACN(ACN_encodedBuffer):
    \'\'\' Decode an ACN buffer and place it in a native Asn1Scc type  \'\'\'

    # Create a stream buffer, put the encoded data inside it, and decode from it
    buffer = ASN1.DataStream(DV.{asn1Type}_REQUIRED_BYTES_FOR_ACN_ENCODING)
    buffer.SetFromPyString(ACN_encodedBuffer)
    decoded_value = ASN1.{asn1Type}()
    decoded_value.DecodeACN(buffer)
    return decoded_value


def encode_uPER(asnVal):
    \'\'\' Encode the native Asn1Scc structure in uPER \'\'\'

    # Check the ASN.1 constraints:
    if not checkConstraints(asnVal): return

    # Create a stream buffer to host the UPER encoded data (for saving to file)
    buffer = ASN1.DataStream(DV.{asn1Type}_REQUIRED_BYTES_FOR_ENCODING)

    try:
        # Encode the value into the buffer
        asnVal.Encode(buffer)
    except:
        if log:
            log.error('uPER encoding failed')
        else:
            print '[ERROR] uPER encoding failed'
        return

    return buffer.GetPyString()


def decode_uPER(uPER_encodedBuffer):
    \'\'\' Decode an uPER buffer and place it in a native Asn1Scc type  \'\'\'

    # Create a stream buffer, put the encoded data inside it, and decode it
    buffer = ASN1.DataStream(DV.{asn1Type}_REQUIRED_BYTES_FOR_ENCODING)
    buffer.SetFromPyString(uPER_encodedBuffer)
    decoded_value = ASN1.{asn1Type}()
    decoded_value.Decode(buffer)
    return decoded_value
'''.format(asn1Type=CleanASNType))

        if modelingLanguage.lower() == "gui_pi":
            g_BackendFile.write('''

def decode_TM(rawTM):
    \'\'\' Decode a msgQ message (native encoding) \'\'\'
    tm = ASN1.{asn1Type}()
    tm.SetData(rawTM)
    return tm


def expect(Q, VNvalue, ignoreOther=False, timeout=None):
    \'\'\' Wait for a specific message - optionally ignoring others \'\'\'
    while True:
        try:
            (msgId, pDataFromMQ) = Q.get(block=True, timeout=timeout)
        except Queue.Empty:
            # Timeout expired
            raise IOError('Timeout expired')
        if msgId == tmId:
Maxime Perrotin's avatar
Maxime Perrotin committed
454 455
            #expectedValue = '{{ {interfaceName} ' + VNvalue + ' }}'
            expectedValue = VNvalue
456
            nativeData = decode_TM(pDataFromMQ)
Maxime Perrotin's avatar
Maxime Perrotin committed
457
            receivedValue = nativeData.GSER()
458 459 460 461 462 463
            if asn1_python.compareVnValues(receivedValue, expectedValue):
                Q.task_done()
                return
            else:
                Q.task_done()
                raise ValueError('Received {interfaceName} with wrong data: '\
Maxime Perrotin's avatar
Maxime Perrotin committed
464
+ vn.format_gser(receivedValue))
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        elif not ignoreOther:
            Q.task_done()
            raise TypeError(
                "Expected {interfaceName} (%s), but received other\
 (%s)" % (str(tmId), str(msgId)))
        else:
            print 'Received other (%s), but still waiting for {interfaceName}'\
 % str(msgId)
            Q.task_done()
'''.format(asn1Type=CleanASNType, interfaceName=CleanSP.replace('_', '-')))

        elif modelingLanguage.lower() == "gui_ri":
            g_BackendFile.write('''


Maxime Perrotin's avatar
Maxime Perrotin committed
480
def send_{interfaceName}_VN(tc_gser):
481
    \''\' Send the TC with from input parameter in ASN.1 Value Notation \''\'
Maxime Perrotin's avatar
Maxime Perrotin committed
482 483 484 485 486 487 488 489
    instance = typeInstance()
    vn.valueNotationToCTypes(gser=tc_gser,
                             dest=instance,
                             sort=ASN1_AST['{asn1Type}'].type,
                             ASN1Mod=ASN1,
                             ASN1_AST=ASN1_AST)

    sendTC(instance)
490 491 492 493


def sendTC(tc):
    \''\' Depending on the configuration, send to msgQ, UDP or shared lib \''\'
494
    # tc is a ctypes instance of an ASN.1 type
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
    if msgQ:
        if checkConstraints(tc):
            try:
                PythonController.Invoke_{interfaceName}(tc)
            except IOError:
                raise
    elif udp:
        UPER_TC = encode_uPER(tc)
        if UPER_TC and udpController:
            udpController.UDP_Invoke(tcId, UPER_TC)
        else:
            if log:
                log.error('UPER Encoding or UDP Sending failed')
            else:
                print '[ERROR] UPER Encoding or UDP Sending failed'

    elif shared_lib:
        # TC is sent in native format
        # ptr = ctypes.cast(tc._ptr.__long__(), ctypes.POINTER(ctypes.c_long))
        # {interfaceName}_via_shared_lib(ptr)
        # The call to the dll will be done by the SDL handler that manages
        # the Undo stack and the the overal system state
        send_via_dll.dll.emit("{interfaceName}",
                              {interfaceName}_via_shared_lib,
                              tc)
Maxime Perrotin's avatar
Maxime Perrotin committed
520
'''.format(interfaceName=CleanSP, asn1Type=param._signal._asnNodename))
521 522 523 524

        global g_fromPysideToASN1
        g_fromPysideToASN1 = ['''

525 526 527 528 529
def fromPysideToASN1(_):
    print('DEPRECATED call to "fromPysideToASN1"')
    # Create a native ASN.1 variable of type {asn1Type}
    # {interfaceName} = ASN1.{asn1Type}()
    return None
530

531 532 533
def typeInstance():
    # Create an intance of an ASN.1 ctype
    return ASN1.{asn1Type}()
534 535 536 537 538
'''.format(interfaceName=CleanSP, asn1Type=CleanASNType)]

        global g_fromASN1ToPyside
        g_fromASN1ToPyside = ['''

539 540 541 542 543 544
def fromASN1ToPyside(_):
    print('DEPRECATED call to "fromASN1ToPyside"')
    return None
''']


545 546
def WriteCodeForGUIControls(prefixes: List[str],  # pylint: disable=invalid-sequence-index
                            parentControl: List[int],  # pylint: disable=invalid-sequence-index
547 548 549 550 551 552
                            node: AsnNode,
                            subProgram: ApLevelContainer,
                            subProgramImplementation: str,
                            param: Param,
                            leafTypeDict: AST_Leaftypes,
                            names: AST_Lookup,
553
                            nodeTypename: str = '',
554 555 556
                            isOptional: bool = False,
                            alwaysPresent: bool = False,
                            alwaysAbsent: bool = False) -> None:
557 558
    global g_firstElem
    global g_onceOnly
559
    global g_asnId
560 561 562 563 564
    for prefix in prefixes:
        txtPrefix = re.sub(r'^.*\.', '', prefix)
    if not g_firstElem and g_onceOnly:
        g_PyDataModel.write(",\n")
    else:
565
        g_asnId = prefixes[0]
566 567 568
        g_firstElem = False

    # Create string to store the Asn1 and python representation of a field
569
    # (e.g. in asnStr: tc.a[0].b and in pyStr: ["tc"]["a"][0]["b"])
570
    pyStr = ""  # type: str
571
    asnStr = prefixes[0]  # type: str
572 573 574 575 576
    for i in range(1, len(prefixes)):
        if len(parentControl) >= i:
            asnStr += "[{index}]".format(index=parentControl[i - 1])
        asnStr += prefixes[i][len(prefixes[i - 1]):]

577 578
    splitted = prefixes[0].split('.')
    for item in splitted:
579 580 581 582 583
        pyStr += '''["{prefixKey}"]'''.format(prefixKey=item)
    for i in range(1, len(prefixes)):
        if len(parentControl) >= i:
            pyStr += "[{index}]".format(index=parentControl[i - 1])
        for item in prefixes[i][len(prefixes[i - 1]):].split('.'):
584
            if item:
585 586 587
                pyStr += '''["{prefixKey}"]'''.format(prefixKey=item)

    if isinstance(node, (AsnInt, AsnReal, AsnOctetString)):
588
        if isinstance(node, AsnInt):
589 590
            if g_onceOnly:
                g_PyDataModel.write(
591 592
                    '''{'nodeTypename': '%s', 'type': '%s', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'minR': %d, 'maxR': %d}''' % (
                        nodeTypename, node._name, txtPrefix, isOptional, alwaysPresent, alwaysAbsent,
593 594
                        node._range[0], node._range[1]))

595 596 597
        elif isinstance(node, AsnReal):
            if g_onceOnly:
                g_PyDataModel.write(
598 599
                    '''{'nodeTypename': '%s', 'type': '%s', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'minR': %20.20f, 'maxR': %20.20f}''' % (
                        nodeTypename, node._name, txtPrefix, isOptional, alwaysPresent, alwaysAbsent,
600 601
                        node._range[0], node._range[1]))

602 603 604
        elif isinstance(node, AsnOctetString):
            if g_onceOnly:
                g_PyDataModel.write(
605 606 607
                    '''{'nodeTypename': '%s', 'type': 'STRING', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'minSize': %d, 'maxSize': %d}''' % (
                        nodeTypename, txtPrefix, isOptional, alwaysPresent, alwaysAbsent,
                        node._range[0], node._range[1]))
608 609 610 611

    elif isinstance(node, AsnBool):
        if g_onceOnly:
            g_PyDataModel.write(
612 613
                '''{'nodeTypename': '%s', 'type': '%s', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'default': 'False'}''' % (
                    nodeTypename, node._name, txtPrefix, isOptional, alwaysPresent, alwaysAbsent))
614 615 616 617 618 619

    elif isinstance(node, AsnEnumerated):
        if g_onceOnly:
            global g_needsComa
            g_needsComa = False
            g_PyDataModel.write(
620 621
                '''{'nodeTypename': '%s', 'type': '%s', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'values':[''' % (
                    nodeTypename, node._name, txtPrefix, isOptional, alwaysPresent, alwaysAbsent))
622 623
            values = []
            valuesmap = []
624
            for enum_value in node._members:
625 626 627 628 629 630 631
                values.append('"' + enum_value[0] + '"')
                valuesmap.append('"%s": %s' % (enum_value[0], enum_value[1]))
                # enum_value[0]: name, enum_value[1]: integer value (or None)
            g_PyDataModel.write(', '.join(values) + ']')
            g_PyDataModel.write(', "valuesInt": {' + ', '.join(valuesmap) + '}}')

    elif isinstance(node, (AsnSequence, AsnChoice, AsnSet)):
632 633
        if g_onceOnly:
            g_PyDataModel.write(
634
                '''{'nodeTypename': '%s', 'type': '%s', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, ''' % (
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
635
                    nodeTypename, node._name, txtPrefix, isOptional, alwaysPresent, alwaysAbsent))
636 637
            if isinstance(node, AsnChoice):
                g_PyDataModel.write('''"choices":[''')
638
            elif isinstance(node, (AsnSequence, AsnSet)):
639 640 641 642 643 644
                g_PyDataModel.write('''"children":[''')
        # Recurse on children
        if node._members:
            g_firstElem = True
        else:
            # Empty sequence, nothing to set
645
            pass
646 647 648 649

        for child in node._members:
            # child[0] is the name of the field
            # child[2] is the string "field_PRESENT" used for choice indexes
650
            # child[3] is the field optionality status
651 652
            # child[4] is the "alwaysPresent" status (when child[3] is True)
            # child[5] is the "alwaysAbsent" status (when child[3] is True)
653 654
            CleanChild = CleanName(child[0])
            childType = child[1]
655
            isOptional = child[3]
656 657 658
            alwaysPresent = child[4]
            alwaysAbsent = child[5]
            # print(CleanChild + " optional: "+ str(isOptional) + " always Present: " + str(alwaysPresent) + " always absent: " + str(alwaysAbsent))
659 660 661 662 663 664
            if isinstance(childType, AsnMetaMember):
                childType = names[childType._containedType]
            seqPrefix = prefixes[-1]
            prefixes[-1] = prefixes[-1] + "." + CleanChild
            WriteCodeForGUIControls(prefixes, parentControl, childType,
                                    subProgram, subProgramImplementation,
665
                                    param, leafTypeDict, names,
666 667 668
                                    isOptional=isOptional,
                                    alwaysPresent=alwaysPresent,
                                    alwaysAbsent=alwaysAbsent)
669 670
            prefixes[-1] = seqPrefix
        if g_onceOnly:
671 672 673 674 675 676 677 678
            if isinstance(node, AsnChoice):
                g_PyDataModel.write('], "choiceIdx": {')
                # the mapping choice->DV.choice_PRESENT is needed by the GUIs
                indexes = []
                for child in node._members:
                    indexes.append('"%s": DV.%s' % (CleanName(child[0]),
                                                    CleanName(child[2])))
                g_PyDataModel.write("%s}}" % ','.join(indexes))
679

680 681
            else:
                g_PyDataModel.write("]}")
682
    elif isinstance(node, (AsnSequenceOf, AsnSetOf)):
683 684
        if g_onceOnly:
            g_PyDataModel.write(
685 686
                "{'nodeTypename': '%s', 'type': 'SEQOF', 'id': '%s', 'isOptional': %s, 'alwaysPresent': %s, 'alwaysAbsent': %s, 'minSize': %d, 'maxSize': %d, 'seqoftype':" % (
                    nodeTypename, txtPrefix, isOptional, alwaysPresent, alwaysAbsent, node._range[0], node._range[1]))
687 688 689 690 691 692 693 694
        containedNode = node._containedType
        if isinstance(containedNode, str):
            containedNode = names[containedNode]
        g_firstElem = True
        prefixes.append(prefixes[-1])
        l_lock = False
        for i in range(node._range[1]):
            parentControl.append(i)
695 696 697 698 699 700 701 702
            WriteCodeForGUIControls(prefixes,
                                    parentControl,
                                    containedNode,
                                    subProgram,
                                    subProgramImplementation,
                                    param,
                                    leafTypeDict,
                                    names)
703 704 705 706 707 708 709 710 711 712 713 714 715 716
            if g_onceOnly:
                g_PyDataModel.write("\n}")
            # l_lock prevents g_onceOnly to be reset during a recursive call
            if g_onceOnly:
                g_onceOnly = False
                l_lock = True
            del parentControl[-1]
        if l_lock:
            g_onceOnly = True
        del prefixes[-1]
    else:  # pragma: nocover
        panic("GUI codegen doesn't support this type yet (%s)" % str(node))  # pragma: nocover


717 718 719 720 721 722 723 724
def Common(
        nodeTypename: str,
        node: AsnNode,
        subProgram: ApLevelContainer,
        subProgramImplementation: str,
        param: Param,
        leafTypeDict: AST_Leaftypes,
        names: AST_Lookup) -> None:
725
    control = CleanName(subProgram._id)
726 727 728 729 730 731 732 733 734
    WriteCodeForGUIControls([control],   # prefixes, start with interface name
                            [],          # parentControl
                            node,
                            subProgram,
                            subProgramImplementation,
                            param,
                            leafTypeDict,
                            names,
                            nodeTypename)
735 736 737 738 739
    g_BackendFile.write(''.join(g_fromPysideToASN1))
    g_BackendFile.write(''.join(g_fromASN1ToPyside))
    g_BackendFile.close()


740 741
def OnBasic(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)
742 743


744 745
def OnSequence(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)
746 747


748 749
def OnSet(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)  # pragma: nocover
750 751


752 753
def OnEnumerated(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)
754 755


756 757
def OnSequenceOf(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)
758 759


760 761
def OnSetOf(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)  # pragma: nocover
762 763


764 765
def OnChoice(nodeTypename: str, node: AsnNode, subProgram: ApLevelContainer, subProgramImplementation: str, param: Param, leafTypeDict: AST_Leaftypes, names: AST_Lookup) -> None:
    Common(nodeTypename, node, subProgram, subProgramImplementation, param, leafTypeDict, names)
766 767


768
def OnShutdown(unused_modelingLanguage: str, unused_asnFile: str, unused_sp: ApLevelContainer, unused_subProgramImplementation: str, unused_maybeFVname: str) -> None:
769 770 771
    pass


772
def OnFinal() -> None:
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
    # global g_PyDataModel
    # global g_QUiFile
    g_PyDataModel.write("\n")
    g_QUiFile.write(''' </widget>
 <layoutdefault spacing="6" margin="11"/>
 <customwidgets>
     <customwidget>
          <class>asn1Editor</class>
          <extends>QWidget</extends>
          <header>asn1_value_editor</header>
     </customwidget>
     <customwidget>
          <class>asn1Viewer</class>
          <extends>QWidget</extends>
          <header>asn1_value_editor</header>
     </customwidget>
     <customwidget>
          <class>TasteMainWindow</class>
          <extends>QMainWindow</extends>
          <header>TasteMainWindow</header>
     </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
''')
    g_PyDataModel.close()
    g_QUiFile.close()
    # This is for restart the module when it is used.
    global g_bStarted
    g_bStarted = False